jorts/src/vm.zig

97 lines
2.6 KiB
Zig

const std = @import("std");
const chunk = @import("chunk.zig");
const value = @import("value.zig");
const Chunk = chunk.Chunk;
const StdOut = *std.io.OutStream(std.fs.File.WriteError);
pub const InterpretResult = enum {
Ok,
CompileError,
RuntimeError,
};
pub const VM = struct {
chk: *Chunk,
ip: usize,
stdout: StdOut,
debug_flag: bool,
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;
return byte;
}
fn readConst(self: *VM) value.Value {
return self.chk.constants.values[self.readByte()];
}
fn readConstLong(self: *VM) value.Value {
const v3 = self.readByte();
const v2 = self.readByte();
const v1 = self.readByte();
const const_idx = (@intCast(u24, v3) << 16) |
(@intCast(u24, v2) << 8) |
v1;
return self.chk.constants.values[const_idx];
}
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: {
return InterpretResult.Ok;
},
else => blk: {
std.debug.warn("Unknown instruction: {x}\n", instruction);
return InterpretResult.RuntimeError;
},
}
}
}
pub fn interpret(self: *VM) !InterpretResult {
self.ip = 0;
self.debug("VM start\n");
var res = try self.run();
self.debug("VM end\n");
return res;
}
};