commit d029753740ee504e49ac581cf101ea57c3a1534c
parent 894c642b4d9c59a602305306f9ac8800d4108871
Author: Szymon Mikulicz <szymon.mikulicz@posteo.net>
Date: Sat, 22 Oct 2022 03:03:55 +0200
First instruction
Diffstat:
3 files changed, 74 insertions(+), 6 deletions(-)
diff --git a/zlox/src/chunk.zig b/zlox/src/chunk.zig
@@ -0,0 +1,35 @@
+const std = @import("std");
+
+pub const OP = enum(u8) { RETURN };
+
+fn grow_capacity(capacity: usize) usize {
+ return if (capacity < 8) 8 else capacity * 2;
+}
+
+fn grow_array(comptime T: type, allocator: std.mem.Allocator, ptr: ?[]T, new_count: usize) ![]T {
+ return if (ptr == null)
+ try allocator.alloc(T, new_count)
+ else
+ try allocator.reallocAtLeast(ptr.?, new_count);
+}
+
+pub const Chunk = struct {
+ pub fn init(allocator: std.mem.Allocator) Chunk {
+ return Chunk{ .count = 0, .capacity = 0, .code = null, .allocator = allocator };
+ }
+ pub fn write(self: *Chunk, byte: u8) !void {
+ if (self.capacity < self.count + 1) {
+ self.capacity = grow_capacity(self.capacity);
+ self.code = try grow_array(u8, self.allocator, self.code, self.capacity);
+ }
+ self.code.?[self.count] = byte;
+ self.count += 1;
+ }
+ pub fn free(self: *Chunk) void {
+ self.allocator.free(self.code.?);
+ }
+ count: usize,
+ capacity: usize,
+ code: ?[]u8,
+ allocator: std.mem.Allocator,
+};
diff --git a/zlox/src/debug.zig b/zlox/src/debug.zig
@@ -0,0 +1,29 @@
+const std = @import("std");
+const chunk = @import("chunk.zig");
+const OP = chunk.OP;
+
+pub fn disassembleChunk(ch: chunk.Chunk, name: []const u8) !void {
+ std.debug.print("== {s} ==\n", .{name});
+
+ var offset: usize = 0;
+ while (offset < ch.count) {
+ offset = disassembleInstruction(ch.code.?, offset);
+ }
+}
+
+pub fn disassembleInstruction(code: []u8, offset: usize) usize {
+ std.debug.print("{d:0>4} ", .{offset});
+
+ return switch (code[offset]) {
+ @enumToInt(OP.RETURN) => simpleInstruction("OP_RETURN", offset),
+ else => blk: {
+ std.debug.print("Unknown opcode {}\n", .{code[offset]});
+ break :blk offset + 1;
+ },
+ };
+}
+
+pub fn simpleInstruction(name: []const u8, offset: usize) usize {
+ std.debug.print("{s}\n", .{name});
+ return offset + 1;
+}
diff --git a/zlox/src/main.zig b/zlox/src/main.zig
@@ -1,9 +1,13 @@
const std = @import("std");
+const chunk = @import("chunk.zig");
+const debug = @import("debug.zig");
-pub fn main() anyerror!void {
- std.log.info("All your codebase are belong to us.", .{});
-}
-
-test "basic test" {
- try std.testing.expectEqual(10, 3 + 7);
+pub fn main() anyerror!u8 {
+ var allocator = std.heap.GeneralPurposeAllocator(.{}){};
+ defer std.debug.assert(!allocator.deinit());
+ var ch = chunk.Chunk.init(allocator.allocator());
+ try ch.write(@enumToInt(chunk.OP.RETURN));
+ try debug.disassembleChunk(ch, "test chunk");
+ ch.free();
+ return 0;
}