aboutsummaryrefslogtreecommitdiff
path: root/src/compile.zig
diff options
context:
space:
mode:
authorMathias Magnusson <mathias@magnusson.space>2025-06-02 18:47:24 +0200
committerMathias Magnusson <mathias@magnusson.space>2025-06-02 18:47:24 +0200
commitbb66477d1423f16c77986b48acd6156222d7d195 (patch)
tree772e8f3915dc5854f0d5e2d4376fcd1490a11dc6 /src/compile.zig
parent601916b828b8d94a89df6950da73ea68a20daa69 (diff)
downloadhuginn-bb66477d1423f16c77986b48acd6156222d7d195.tar.gz
add variable declarations
Diffstat (limited to 'src/compile.zig')
-rw-r--r--src/compile.zig12
1 files changed, 11 insertions, 1 deletions
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;
}