From 456bc951382741e34c4d17af01406ff7bda32f7b Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 1 Jun 2019 15:01:39 -0300 Subject: [PATCH] vm: add debug flags --- src/main.zig | 6 +----- src/vm.zig | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/main.zig b/src/main.zig index 1c982e3..1d4bdc7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -118,11 +118,7 @@ pub fn main() !void { var constant = try chk.writeConstant(1.2, 123); try chk.write(chunk.OpCode.Return, 123); - try chk.disassemble(stdout, "test chunk"); - var vmach = vm.VM.init(stdout, &chk); - - std.debug.warn("vm start\n"); + var vmach = vm.VM.init(stdout, &chk, true); _ = try vmach.interpret(); - std.debug.warn("vm end\n"); } diff --git a/src/vm.zig b/src/vm.zig index fd510b3..1765c6c 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -15,15 +15,23 @@ pub const VM = struct { chk: *Chunk, ip: usize, stdout: StdOut, + debug_flag: bool, - pub fn init(stdout: StdOut, chk: *Chunk) VM { + pub fn init(stdout: StdOut, chk: *Chunk, debug_flag: bool) VM { return VM{ .stdout = stdout, .chk = chk, .ip = 0, + .debug_flag = debug_flag, }; } + pub fn debug(self: *VM, comptime fmt: []const u8, args: ...) void { + if (self.debug_flag) { + std.debug.warn(fmt, args); + } + } + fn readByte(self: *VM) u8 { var byte: u8 = self.chk.code[self.ip]; self.ip += 1; @@ -47,17 +55,23 @@ pub const VM = struct { fn run(self: *VM) !InterpretResult { while (true) { + if (self.debug_flag) { + _ = try self.chk.disassembleInstruction(self.stdout, self.ip); + } + var instruction = self.readByte(); switch (instruction) { chunk.OpCode.Constant => blk: { var constant = self.readConst(); try value.printValue(self.stdout, constant); + try self.stdout.write("\n"); break :blk; }, chunk.OpCode.ConstantLong => blk: { var constant = self.readConstLong(); try value.printValue(self.stdout, constant); + try self.stdout.write("\n"); break :blk; }, chunk.OpCode.Return => blk: { @@ -73,6 +87,10 @@ pub const VM = struct { pub fn interpret(self: *VM) !InterpretResult { self.ip = 0; - return try self.run(); + + self.debug("VM start\n"); + var res = try self.run(); + self.debug("VM end\n"); + return res; } };