Compare commits

...

2 Commits

4 changed files with 22 additions and 2 deletions

View File

@ -36,6 +36,14 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
// Declare an option to build the program with debug statements
// (crafting interpreters: A virtual machine: execution tracing)
const executionTracing = b.option(bool, "tracing", "enable execution tracing") orelse false;
const options = b.addOptions();
options.addOption(bool, "tracing", executionTracing);
exe.root_module.addOptions("config", options);
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).

View File

@ -54,7 +54,7 @@ pub const Chunk = struct {
}
/// Prints the value of a single instruction
fn dissasemble_instruction(self: *Chunk, offset: usize) usize {
pub fn dissasemble_instruction(self: *Chunk, offset: usize) usize {
// Print the instruction offset
print("{d:0>4} ", .{offset});

View File

@ -1,11 +1,15 @@
const std = @import("std");
const config = @import("config");
const chunk = @import("./chunk.zig");
const OpCode = chunk.OpCode;
const VM = @import("./vm.zig").VM;
pub fn main() !void {
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
if (config.tracing) {
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
}
var mem = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = mem.allocator();

View File

@ -4,6 +4,8 @@ const Chunk = chunk_mod.Chunk;
const OpCode = chunk_mod.OpCode;
const print = std.debug.print;
const tracing = @import("config").tracing;
const InterpretResult = enum {
Ok,
CompileError,
@ -28,6 +30,12 @@ pub const VM = struct {
// Executes the instructions in the bytecode
pub fn run(self: *VM) InterpretResult {
while (true) {
if (tracing) {
// dissasemble & print the current instruction
const offset: usize = @intFromPtr(self.ip) - @intFromPtr(self.chunk.code.ptr);
_ = self.chunk.dissasemble_instruction(offset);
}
const next = self.ip[0];
self.ip += 1;
switch (next) {