From 975280be8fec016bae4261fb6aeb561875c532c2 Mon Sep 17 00:00:00 2001 From: Araozu Date: Tue, 14 May 2024 09:00:34 -0500 Subject: [PATCH] constant dissasemble --- src/chunk.zig | 15 +++++++++++++++ src/main.zig | 7 +++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/chunk.zig b/src/chunk.zig index f99ad5f..e3edcc1 100644 --- a/src/chunk.zig +++ b/src/chunk.zig @@ -5,6 +5,7 @@ const ValueArray = value.ValueArray; pub const OpCode = enum(u8) { OP_RETURN, + OP_CONSTANT, }; pub const Chunk = struct { @@ -62,6 +63,7 @@ pub const Chunk = struct { const instruction = self.code[offset]; switch (instruction) { @intFromEnum(OpCode.OP_RETURN) => return simple_instruction("OP_RETURN", offset), + @intFromEnum(OpCode.OP_CONSTANT) => return self.constant_instruction("OP_CONSTANT", offset), else => { print("unknown opcode {d}\n", .{instruction}); return offset + 1; @@ -78,6 +80,15 @@ pub const Chunk = struct { self.allocator.free(self.code); self.constants.deinit(); } + fn constant_instruction(self: *Chunk, comptime name: []const u8, offset: usize) usize { + const constant_addr = self.code[offset + 1]; + const constant_value = self.constants.values[constant_addr]; + + print("{s} ", .{name}); + print_value(constant_value); + print("\n", .{}); + return offset + 2; + } }; fn simple_instruction(comptime name: []const u8, offset: usize) usize { @@ -85,6 +96,10 @@ fn simple_instruction(comptime name: []const u8, offset: usize) usize { return offset + 1; } +fn print_value(v: value.Value) void { + print("{d}", .{v}); +} + inline fn grow_capacity(old: usize) usize { return if (old < 8) 8 else old * 2; } diff --git a/src/main.zig b/src/main.zig index 943910d..d924c56 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,5 +1,6 @@ const std = @import("std"); const chunk = @import("./chunk.zig"); +const OpCode = chunk.OpCode; pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) @@ -11,10 +12,12 @@ pub fn main() !void { var c = try chunk.Chunk.init(alloc); defer c.deinit(); - try c.write(@intFromEnum(chunk.OpCode.OP_RETURN)); try c.write(@intFromEnum(chunk.OpCode.OP_RETURN)); - _ = try c.add_constant(0.0); + const constant_idx = try c.add_constant(1.2); + try c.write(@intFromEnum(OpCode.OP_CONSTANT)); + try c.write(@truncate(constant_idx)); + c.dissasemble_chunk("test chunk"); }