From 5aba3f29b6af2d6708ea6605d2d5c064f48d03c6 Mon Sep 17 00:00:00 2001 From: Baitinq Date: Fri, 31 Jan 2025 01:15:16 +0100 Subject: Codegen: Start handling global variables --- examples/5.src | 4 ++-- src/codegen.zig | 13 ++++++++++--- 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(), -- cgit 1.4.1