From 29c79e7e3e9e2056d5a1d16d5549319b5b8336c3 Mon Sep 17 00:00:00 2001 From: Stefan Weigl-Bosker Date: Fri, 20 Dec 2024 19:44:25 -0500 Subject: preorder is actually more helpful lol --- src/parser.zig | 46 +++++++++++----------------------------------- 1 file 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}); } }; -- cgit v1.2.3