From 483a5081e314d9f52f21b7bc1e7a2854aae4a248 Mon Sep 17 00:00:00 2001 From: Theis Pieter Hollebeek Date: Wed, 11 Dec 2024 13:37:26 +0100 Subject: [PATCH] print builtin --- compiler/lowerer.ts | 23 ++++++++++++++++++++++- examples/annos.slg | 2 +- runtime/arch.hpp | 1 + runtime/vm.cpp | 10 ++++++++-- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/compiler/lowerer.ts b/compiler/lowerer.ts index 79572dc..23e58a0 100644 --- a/compiler/lowerer.ts +++ b/compiler/lowerer.ts @@ -134,7 +134,28 @@ export class Lowerer { for (const { ident } of stmt.kind.params) { this.locals.allocSym(ident); } - this.lowerExpr(stmt.kind.body); + 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() - diff --git a/examples/annos.slg b/examples/annos.slg index 0225358..569a9dd 100644 --- a/examples/annos.slg +++ b/examples/annos.slg @@ -3,5 +3,5 @@ fn print(msg: string) #[builtin(print)] { } fn main() { - print("hello world!"); + print("hello world!\n"); } diff --git a/runtime/arch.hpp b/runtime/arch.hpp index 33291b4..72b4b70 100644 --- a/runtime/arch.hpp +++ b/runtime/arch.hpp @@ -43,6 +43,7 @@ enum class Builtin : uint32_t { StringEqual = 0x11, ArraySet = 0x20, StructSet = 0x30, + Print = 0x40, }; } diff --git a/runtime/vm.cpp b/runtime/vm.cpp index d65ecdc..4d1ba95 100644 --- a/runtime/vm.cpp +++ b/runtime/vm.cpp @@ -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; + } } }