print builtin

This commit is contained in:
Theis Pieter Hollebeek 2024-12-11 13:37:26 +01:00
parent a6da283b0a
commit 483a5081e3
4 changed files with 32 additions and 4 deletions

View File

@ -134,7 +134,28 @@ export class Lowerer {
for (const { ident } of stmt.kind.params) {
this.locals.allocSym(ident);
}
if (stmt.kind.anno?.ident === "builtin") {
const anno = stmt.kind.anno.values[0];
if (!anno) {
throw new Error("builtin annotation without ident");
}
if (anno.kind.type !== "ident") {
throw new Error("builtin annotation without ident");
}
const value = anno.kind.value;
switch (value) {
case "print": {
this.program.add(Ops.LoadLocal, 0);
this.program.add(Ops.Builtin, Builtins.Print);
break;
}
default: {
throw new Error("unrecognized builtin");
}
}
} else {
this.lowerExpr(stmt.kind.body);
}
this.locals = outerLocals;
const localAmount = fnRoot.stackReserved() -

View File

@ -3,5 +3,5 @@ fn print(msg: string) #[builtin(print)] {
}
fn main() {
print("hello world!");
print("hello world!\n");
}

View File

@ -43,6 +43,7 @@ enum class Builtin : uint32_t {
StringEqual = 0x11,
ArraySet = 0x20,
StructSet = 0x30,
Print = 0x40,
};
}

View File

@ -68,8 +68,8 @@ void VM::run_n_instructions(size_t amount)
void VM::run_instruction()
{
std::cout << std::format(" {:>4}: {:<12}{}\n", this->pc,
maybe_op_to_string(this->program[this->pc]), stack_repr_string(8));
// std::cout << std::format(" {:>4}: {:<12}{}\n", this->pc,
// maybe_op_to_string(this->program[this->pc]), stack_repr_string(8));
auto op = eat_op();
switch (op) {
case Op::Nop:
@ -339,5 +339,11 @@ void VM::run_builtin(Builtin builtin_id)
std::exit(1);
break;
}
case Builtin::Print: {
assert_stack_has(1);
auto message = stack_pop().as_string().value;
std::cout << message;
break;
}
}
}