From 1cb8c95fe917e6473e8eeb4d3e0e75e27fdb3d43 Mon Sep 17 00:00:00 2001 From: Patrick MARIE Date: Sat, 24 Aug 2024 18:49:14 +0200 Subject: [PATCH] execution tracing --- src/chunk.zig | 1 + src/main.zig | 4 +++- src/vm.zig | 17 +++++++++++++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/chunk.zig b/src/chunk.zig index 56c7130..2db5177 100644 --- a/src/chunk.zig +++ b/src/chunk.zig @@ -61,6 +61,7 @@ pub const Chunk = struct { while (offset < self.count) { offset += self.dissassemble_instruction(offset); } + debug.print("== end of {s} ==\n\n", .{name}); } pub fn dissassemble_instruction(self: Chunk, offset: usize) usize { diff --git a/src/main.zig b/src/main.zig index 0d3034a..a1b83b7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -6,6 +6,8 @@ const Chunk = @import("./chunk.zig").Chunk; const OpCode = @import("./opcode.zig").OpCode; const VM = @import("./vm.zig").VM; +pub const DEBUG_TRACE_EXECUTION = true; + pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true }){}; defer _ = debug.assert(gpa.deinit() == .ok); @@ -16,10 +18,10 @@ pub fn main() !void { var chunk = Chunk.new(); try chunk.init(allocator); - try chunk.write(allocator, @intFromEnum(OpCode.OP_RETURN), 123); const constant = try chunk.add_constant(allocator, 1.2); try chunk.write(allocator, @intFromEnum(OpCode.OP_CONSTANT), 123); try chunk.write(allocator, @intCast(constant), 123); + try chunk.write(allocator, @intFromEnum(OpCode.OP_RETURN), 123); chunk.dissassemble("test chunk"); diff --git a/src/vm.zig b/src/vm.zig index 78ca569..a2d8154 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -3,6 +3,8 @@ const Chunk = @import("./chunk.zig").Chunk; const OpCode = @import("./opcode.zig").OpCode; const Value = @import("./values.zig").Value; +const DEBUG_TRACE_EXECUTION = @import("./main.zig").DEBUG_TRACE_EXECUTION; + const print_value = @import("./values.zig").print_value; const InterpretResult = enum { @@ -35,15 +37,25 @@ pub const VM = struct { pub fn run(self: *VM) InterpretResult { while (true) { + if (DEBUG_TRACE_EXECUTION) { + _ = self.chunk.?.dissassemble_instruction(self.ip.?); + } + const instruction = self.read_byte(); switch (instruction) { @intFromEnum(OpCode.OP_CONSTANT) => { const constant = self.read_constant(); + + // XXX Those should not be std.debug, but stdout. print_value(constant); + std.debug.print("\n", .{}); }, @intFromEnum(OpCode.OP_RETURN) => return InterpretResult.OK, - else => return InterpretResult.RUNTIME_ERROR, + else => { + std.debug.print("Invalid instruction: {d}\n", .{instruction}); + return InterpretResult.RUNTIME_ERROR; + }, } } @@ -53,9 +65,10 @@ pub const VM = struct { // XXX In the book, we're using a ptr to data directly, to avoid dereferencing to a given offset // How to do that in Zig? pub fn read_byte(self: *VM) u8 { + const ret = self.chunk.?.code[self.ip.?]; self.ip.? += 1; - return self.chunk.?.code[self.ip.?]; + return ret; } pub fn read_constant(self: *VM) Value {