-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram.zig
67 lines (59 loc) · 2.34 KB
/
program.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const std = @import("std");
const Instr = @import("instr.zig").Instr;
const Value = @import("value.zig").Value;
pub const Program = struct {
instrs: []const Instr,
data: []const u8,
locations: []const Location,
pub fn deinit(self: Program, allocator: std.mem.Allocator) void {
allocator.free(self.instrs);
allocator.free(self.data);
allocator.free(self.locations);
}
pub fn format(self: Program, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try self.write(writer, 0, 0);
}
fn write(self: Program, writer: anytype, init_i: usize, indent: usize) !void {
var i = init_i;
while (i < self.instrs.len) {
try writer.print("{:0>4} ", .{i});
for (0..indent) |_| try writer.print("│ ", .{});
const instr = self.instrs[i];
i += 1;
switch (instr) {
.num => |value| try writer.print("num: {d}\n", .{value}),
.global => |value| try writer.print("global: {s}\n", .{@tagName(value)}),
.lambda => |value| {
try writer.print("lambda: {d}\n", .{value.caps});
try (Program{
.instrs = self.instrs[0 .. i + value.len],
.data = self.data,
}).write(writer, i, indent + 1);
i += value.len;
},
.short_str => |*short| {
try writer.print("str: ", .{});
try Value.writeStr(Value.fromShort(short), writer);
try writer.print("\n", .{});
},
.long_str => |value| {
try writer.print("str: ", .{});
try Value.writeStr(self.data[value.index .. value.index + value.len], writer);
try writer.print("\n", .{});
},
inline else => |value, tag| {
try writer.print("{s}", .{@tagName(tag)});
if (@TypeOf(value) != void) {
try writer.print(": {any}", .{value});
}
try writer.print("\n", .{});
},
}
}
}
pub const Location = struct {
offset: usize,
index: usize,
location: Instr.Location,
};
};