diff options
author | Stefan Weigl-Bosker <stefan@s00.xyz> | 2024-12-20 19:44:25 -0500 |
---|---|---|
committer | Stefan Weigl-Bosker <stefan@s00.xyz> | 2024-12-20 19:44:25 -0500 |
commit | 29c79e7e3e9e2056d5a1d16d5549319b5b8336c3 (patch) | |
tree | 8db794350d8980807b9e51847612c4853b3f1ab5 | |
parent | 415f3971c49de45704630bd45abe03ef641f47bf (diff) | |
download | lg-29c79e7e3e9e2056d5a1d16d5549319b5b8336c3.tar.gz |
-rw-r--r-- | src/parser.zig | 46 |
1 files changed, 11 insertions, 35 deletions
diff --git a/src/parser.zig b/src/parser.zig index 80522da..e316712 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -51,45 +51,21 @@ pub const ParseTree = struct { } } - pub fn format(self: *const ParseTree, comptime fmt: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); - defer arena.deinit(); - const allocator = arena.allocator(); - - if (fmt.len != 0) { - return std.invalidFmtError(fmt, self); - } - - const Queue = std.DoublyLinkedList(struct { *const ParseTree, u32 }); - - var q: Queue = .{}; - - const root = try allocator.create(Queue.Node); - root.* = .{ .data = .{ self, 0 } }; - - q.append(root); - - var level: u32 = 0; - while (q.len != 0) { - const cur: *Queue.Node = q.popFirst().?; + pub fn format(self: *const ParseTree, _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + const child = self.child; + const sibling = self.sibling; - const tree = cur.data[0]; - const l = cur.data[1]; + try writer.print("rule: {s}\n", .{@tagName(self.rule)}); - if (l != level) { - try writer.print("\n", .{}); - level = l; - } + if (self.rule == Rule.Terminal) { + try writer.print("token: {}\n", .{self.token.?}); + } - try writer.print("{s} ", .{@tagName(tree.rule)}); + if (child) |c| + try writer.print("{}", .{c}); - var p: ?*ParseTree = tree.child; - while (p) |child| : (p = child.sibling) { - const node = try allocator.create(Queue.Node); - node.* = .{ .data = .{ child, l + 1 } }; - q.append(node); - } - } + if (sibling) |s| + try writer.print("{}", .{s}); } }; |