about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBaitinq <[email protected]>2025-01-31 01:15:16 +0100
committerBaitinq <[email protected]>2025-01-31 01:16:56 +0100
commit5aba3f29b6af2d6708ea6605d2d5c064f48d03c6 (patch)
tree44910812f45c4e79127c1e0483fb5c6f00255dbe
parentCodegen: Fix function as variables (diff)
downloadinterpreter-5aba3f29b6af2d6708ea6605d2d5c064f48d03c6.tar.gz
interpreter-5aba3f29b6af2d6708ea6605d2d5c064f48d03c6.tar.bz2
interpreter-5aba3f29b6af2d6708ea6605d2d5c064f48d03c6.zip
Codegen: Start handling global variables
-rw-r--r--examples/5.src4
-rw-r--r--src/codegen.zig13
2 files changed, 12 insertions, 5 deletions
diff --git a/examples/5.src b/examples/5.src
index 88c171c..5d6baaa 100644
--- a/examples/5.src
+++ b/examples/5.src
@@ -11,7 +11,7 @@ let foo = () => {
 let main = () => {
 	print(x);
 	let x = 2;
-	foo();
+	let y= foo();
 	print(x);
-	return x;
+	return x + y;
 };
diff --git a/src/codegen.zig b/src/codegen.zig
index f5ef608..dc9c1da 100644
--- a/src/codegen.zig
+++ b/src/codegen.zig
@@ -208,9 +208,16 @@ pub const CodeGen = struct {
             },
             .PRIMARY_EXPRESSION => |primary_expression| switch (primary_expression) {
                 .NUMBER => |n| {
-                    const ptr = core.LLVMBuildAlloca(self.builder, core.LLVMInt64Type(), "") orelse return CodeGenError.CompilationError;
-                    _ = core.LLVMBuildStore(self.builder, core.LLVMConstInt(core.LLVMInt64Type(), @intCast(n.value), 0), ptr) orelse return CodeGenError.CompilationError;
-                    const variable = core.LLVMBuildLoad2(self.builder, core.LLVMInt64Type(), ptr, "") orelse return CodeGenError.CompilationError;
+                    // Global variables
+                    var variable: types.LLVMValueRef = undefined;
+                    if (self.environment.scope_stack.items.len == 1) {
+                        variable = core.LLVMConstInt(core.LLVMInt64Type(), @intCast(n.value), 0);
+                    } else {
+                        const ptr = core.LLVMBuildAlloca(self.builder, core.LLVMInt64Type(), "") orelse return CodeGenError.CompilationError;
+                        _ = core.LLVMBuildStore(self.builder, core.LLVMConstInt(core.LLVMInt64Type(), @intCast(n.value), 0), ptr) orelse return CodeGenError.CompilationError;
+                        variable = core.LLVMBuildLoad2(self.builder, core.LLVMInt64Type(), ptr, "") orelse return CodeGenError.CompilationError;
+                    }
+
                     return try self.create_variable(.{
                         .value = variable,
                         .type = core.LLVMInt64Type(),