diff --git a/src/chunk.zig b/src/chunk.zig index ebd99f3..5471a95 100644 --- a/src/chunk.zig +++ b/src/chunk.zig @@ -1,6 +1,7 @@ const std = @import("std"); +const print = std.debug.print; -const OpCode = enum { +pub const OpCode = enum(u8) { OP_RETURN, }; @@ -38,7 +39,34 @@ pub const Chunk = struct { self.code = try self.allocator.realloc(self.code, 0); } + pub fn dissasemble_chunk(self: *Chunk, name: []const u8) void { + print("== {s} ==\n", .{name}); + + var offset: usize = 0; + while (offset < self.count) { + offset = dissasemble_instruction(self, offset); + } + } + + fn dissasemble_instruction(self: *Chunk, offset: usize) usize { + print("{d:0>4} ", .{offset}); + + const instruction = self.code[offset]; + switch (instruction) { + @intFromEnum(OpCode.OP_RETURN) => return simple_instruction("OP_RETURN", offset), + else => { + print("unknown opcode {d}\n", .{instruction}); + return offset + 1; + }, + } + } + pub fn deinit(self: Chunk) void { self.allocator.free(self.code); } }; + +fn simple_instruction(comptime name: []const u8, offset: usize) usize { + print("{s}\n", .{name}); + return offset + 1; +} diff --git a/src/main.zig b/src/main.zig index 6fc3877..f2f02d0 100644 --- a/src/main.zig +++ b/src/main.zig @@ -11,8 +11,9 @@ pub fn main() !void { var c = try chunk.Chunk.init(alloc); defer c.deinit(); - try c.write_chunck('a'); - try c.free_chunck(); + try c.write_chunck(@intFromEnum(chunk.OpCode.OP_RETURN)); + try c.write_chunck(@intFromEnum(chunk.OpCode.OP_RETURN)); + c.dissasemble_chunk("test chunk"); } test "chunk test" {