From bb66477d1423f16c77986b48acd6156222d7d195 Mon Sep 17 00:00:00 2001 From: Mathias Magnusson Date: Mon, 2 Jun 2025 18:47:24 +0200 Subject: add variable declarations --- src/compile.zig | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src/compile.zig') diff --git a/src/compile.zig b/src/compile.zig index 9513a93..c352994 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -103,6 +103,7 @@ pub fn compile(allocator: Allocator, source: []const u8, stmts: []parse.Stmt) !B .allocator = allocator, .source = source, .register_counter = 0, + .scope = .empty, .instrs = instrs, }; for (stmts) |stmt| { @@ -115,6 +116,7 @@ const CompileContext = struct { allocator: Allocator, source: []const u8, register_counter: u32, + scope: std.StringHashMapUnmanaged(VReg), instrs: std.ArrayListUnmanaged(Instr), const Self = @This(); @@ -129,10 +131,16 @@ const CompileContext = struct { .loc = stmt.loc, .type = .{ .discard = .{ .vreg = try self.compileExpr(expr) } }, }), + .declare_var => |declare_var| { + const val = try self.compileExpr(declare_var.value); + const name = declare_var.ident.getIdent(self.source); + try self.scope.put(self.allocator, name, val); + }, } } fn compileExpr(self: *Self, expr: *const parse.Expr) !VReg { + // This is not used by all expression types, but creating an unused virtual register is not a problem. const dest = self.register(); switch (expr.type) { .integer_literal => try addInstr(self, .{ @@ -168,7 +176,9 @@ const CompileContext = struct { .type = .{ .print = .{ .dest = dest, .arg = arg } }, }); }, - .identifier => return error.CantCompileIdentifierExpr, + .identifier => { + return self.scope.get(expr.loc.getIdent(self.source)) orelse return error.UnknownVariable; + }, } return dest; } -- cgit v1.2.3