diff --git a/src/main.zig b/src/main.zig index baabf78..14645ec 100644 --- a/src/main.zig +++ b/src/main.zig @@ -13,6 +13,7 @@ const Chunk = struct { count: usize, capacity: usize, code: []u8, + lines: []usize, constants: ValueArray, pub fn new() Chunk { @@ -20,6 +21,7 @@ const Chunk = struct { .count = 0, .capacity = 0, .code = &.{}, + .lines = &.{}, .constants = ValueArray.new(), }; } @@ -30,17 +32,20 @@ const Chunk = struct { self.count = 0; self.capacity = 0; self.code = &.{}; + self.lines = &.{}; self.constants = ValueArray.new(); } - pub fn write(self: *Chunk, allocator: Allocator, byte: u8) !void { + pub fn write(self: *Chunk, allocator: Allocator, byte: u8, line: usize) !void { if (self.capacity < self.count + 1) { const old_capacity = self.capacity; self.capacity = utils.grow_capacity(old_capacity); self.code = try allocator.realloc(self.code, self.capacity); + self.lines = try allocator.realloc(self.lines, self.capacity); } self.code[self.count] = byte; + self.lines[self.count] = line; self.count += 1; } @@ -61,6 +66,12 @@ const Chunk = struct { pub fn dissassemble_instruction(self: Chunk, offset: usize) usize { debug.print("{x:0>4} ", .{offset}); + if (offset > 0 and self.lines[offset] == self.lines[offset - 1]) { + debug.print(" | ", .{}); + } else { + debug.print("{d:4} ", .{self.lines[offset]}); + } + const instruction = self.code[offset]; switch (instruction) { @@ -78,6 +89,7 @@ const Chunk = struct { if (self.capacity > 0) { allocator.free(self.code); + allocator.free(self.lines); } } @@ -95,9 +107,9 @@ pub fn simple_instruction(opcode_name: []const u8, offset: usize) usize { pub fn constant_instruction(opcode_name: []const u8, chunk: Chunk, offset: usize) usize { const constant = chunk.code[offset + 1]; - debug.print("{s:16} {d:4} ", .{ opcode_name, constant }); + debug.print("{s:16} {d:4} '", .{ opcode_name, constant }); values.print_value(chunk.constants.values[constant]); - debug.print("\n", .{}); + debug.print("'\n", .{}); return offset + 2; } @@ -109,10 +121,10 @@ pub fn main() !void { var chunk = Chunk.new(); try chunk.init(allocator); - try chunk.write(allocator, @intFromEnum(OpCode.OP_RETURN)); + try chunk.write(allocator, @intFromEnum(OpCode.OP_RETURN), 123); const constant = try chunk.add_constant(allocator, 1.2); - try chunk.write(allocator, @intFromEnum(OpCode.OP_CONSTANT)); - try chunk.write(allocator, @intCast(constant)); + try chunk.write(allocator, @intFromEnum(OpCode.OP_CONSTANT), 123); + try chunk.write(allocator, @intCast(constant), 123); chunk.dissassemble("test chunk"); diff --git a/src/values.zig b/src/values.zig index 7075031..53c6759 100644 --- a/src/values.zig +++ b/src/values.zig @@ -39,5 +39,5 @@ pub const ValueArray = struct { }; pub fn print_value(value: Value) void { - debug.print("{any}", .{value}); + debug.print("{d}", .{value}); }