vm: add debug flags
This commit is contained in:
parent
dae3c259fd
commit
456bc95138
2 changed files with 21 additions and 7 deletions
|
@ -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");
|
||||
}
|
||||
|
|
22
src/vm.zig
22
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;
|
||||
}
|
||||
};
|
||||
|
|
Loading…
Reference in a new issue