forked from sanya28wd/Python-Compiler-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_printer.py
More file actions
32 lines (24 loc) · 1014 Bytes
/
tree_printer.py
File metadata and controls
32 lines (24 loc) · 1014 Bytes
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
class Node:
def __init__(self, type, children=None):
self.type = type
self.children = children if children is not None else []
def __repr__(self):
return f"Node({self.type})"
def print_tree(node, prefix="", is_last=True):
"""
Prints the syntax tree in a human-readable format.
"""
# Print the current node
print(prefix + ("└── " if is_last else "├── ") + str(node.type))
# Update the prefix for children
child_prefix = prefix + (" " if is_last else "│ ")
if not hasattr(node, 'children'):
return
for i, child in enumerate(node.children):
is_child_last = (i == len(node.children) - 1)
if isinstance(child, Node):
print_tree(child, child_prefix, is_child_last)
else:
# It's a terminal token (leaf)
token_repr = f"{child.type} ('{child.value}')"
print(child_prefix + ("└── " if is_child_last else "├── ") + token_repr)