diff --git a/src/compile.zig b/src/compile.zig index 6e8766e..ca72de9 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -15,8 +15,6 @@ const VM = @import("./vm.zig").VM; const ParsingError = @import("./errors.zig").ParsingError; -const DEBUG_TRACE_EXECUTION = @import("./main.zig").DEBUG_TRACE_EXECUTION; - const Precedence = enum { None, Assignement, @@ -130,7 +128,7 @@ const Parser = struct { } fn end_parser(self: *Parser) !void { - if (!self.had_error and DEBUG_TRACE_EXECUTION) { + if (!self.had_error and self.vm.has_tracing()) { self.chunk.dissassemble("code"); } try self.emit_return(); diff --git a/src/main.zig b/src/main.zig index dda02ec..cb80543 100644 --- a/src/main.zig +++ b/src/main.zig @@ -10,8 +10,6 @@ const InterpretResult = @import("./vm.zig").InterpretResult; // XXX imported to run tests. const Table = @import("./table.zig"); -pub const DEBUG_TRACE_EXECUTION = true; - pub fn repl(allocator: Allocator, vm: *VM) !void { var line: [1024]u8 = undefined; @@ -61,6 +59,12 @@ pub fn main() !void { var vm = VM.new(allocator); defer vm.free(); + var env = try std.process.getEnvMap(allocator); + defer env.deinit(); + if (env.get("TRACE") != null) { + vm.set_trace(true); + } + if (args.len == 1) { try repl(allocator, &vm); } else if (args.len == 2) { diff --git a/src/vm.zig b/src/vm.zig index 809fd65..050e6ad 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -32,6 +32,7 @@ pub const VM = struct { // In the book, a linked list between objects is used to handle this. references: std.ArrayList(*Obj), strings: Table, + tracing: bool, pub fn new(allocator: Allocator) VM { return VM{ @@ -41,18 +42,30 @@ pub const VM = struct { .stack = std.ArrayList(Value).init(allocator), .references = std.ArrayList(*Obj).init(allocator), .strings = Table.new(allocator), + .tracing = false, }; } pub fn free(self: *VM) void { self.stack.deinit(); - self.strings.dump(); + if (self.has_tracing()) { + self.strings.dump(); + } + self.strings.deinit(); self.clean_references(); self.references.deinit(); } + pub fn set_trace(self: *VM, tracing: bool) void { + self.tracing = tracing; + } + + pub fn has_tracing(self: *VM) bool { + return self.tracing; + } + pub fn interpret(self: *VM, allocator: Allocator, content: []const u8) !InterpretResult { var chunk = Chunk.new(allocator); defer chunk.deinit(); @@ -70,7 +83,7 @@ pub const VM = struct { pub fn run(self: *VM) !InterpretResult { while (true) { - if (DEBUG_TRACE_EXECUTION) { + if (self.has_tracing()) { if (self.stack.items.len > 0) { debug.print("{s:32}", .{""}); for (self.stack.items) |item| {