jorts/src/chunk.zig

72 lines
1.6 KiB
Zig
Raw Normal View History

const std = @import("std");
const Allocator = std.mem.Allocator;
// hack. ugly hack. zig has compiler crash.
const AllOpcodes = struct {
pub Return: u8 = 0,
};
pub const OpCode = AllOpcodes{};
fn simpleInstruction(
stdout: var,
comptime name: []const u8,
offset: usize,
) !usize {
try stdout.print("{}\n", name);
return offset + 1;
}
pub const Chunk = struct {
count: usize,
code: []u8,
allocator: *Allocator,
pub fn init(allocator: *Allocator) !Chunk {
return Chunk{
.count = 0,
.allocator = allocator,
.code = try allocator.alloc(u8, 0),
};
}
pub fn write(self: *Chunk, byte: u8) !void {
if (self.code.len < self.count + 1) {
self.code = try self.allocator.realloc(
self.code,
self.count + 1,
);
}
self.code[self.count] = byte;
self.count += 1;
}
pub fn disassembleInstruction(
self: *Chunk,
stdout: var,
index: usize,
) !usize {
try stdout.print("{} ", index);
var instruction = self.code[index];
if (instruction == 0) {
return try simpleInstruction(stdout, "OP_RETURN", index);
} else {
try stdout.print("Unknown opcode: {}\n", instruction);
return index + 1;
}
}
pub fn disassemble(self: *Chunk, stdout: var, name: []const u8) !void {
try stdout.print("== {} ==\n", name);
var i: usize = 0;
while (i < self.count) : (i += 1) {
i = try self.disassembleInstruction(stdout, i);
}
}
};