-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenptdot.py
198 lines (155 loc) · 5.37 KB
/
genptdot.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file: genptdot.py
@author: amazing coder
@date: 2024/8/28
@desc:
"""
###############################################################################
# #
# Parse Tree visualizer #
# #
# To generate an image from the DOT file run: #
# $ dot -Tpng -o parsetree.png parsetree.dot #
# #
###############################################################################
import argparse
import textwrap
from interpreter import PLUS, MINUS, MUL, DIV, INTEGER, LPAREN, RPAREN, Analyzer
class Node(object):
def __init__(self, name):
self.name = name
self.children = []
def add(self, node):
self.children.append(node)
class RuleNode(Node):
pass
class TokenNode(Node):
pass
class Parser(object):
"""Parses the input and builds a parse tree."""
def __init__(self, lexer):
self.lexer = lexer
# set current token to the first token taken from the input
self.current_token = self.lexer.get_next_token()
# Parse tree root
self.root = None
self.current_node = None
def error(self):
raise Exception('Invalid syntax')
def eat(self, token_type):
# compare the current token type with the passed token
# type and if they match then "eat" the current token
# and assign the next token to the self.current_token,
# otherwise raise an exception.
if self.current_token.symbol_type == token_type:
self.current_node.add(TokenNode(self.current_token.value))
self.current_token = self.lexer.get_next_token()
else:
self.error()
def factor(self):
"""factor : INTEGER | LPAREN expr RPAREN"""
node = RuleNode('factor')
self.current_node.add(node)
_save = self.current_node
self.current_node = node
token = self.current_token
if token.symbol_type == INTEGER:
self.eat(INTEGER)
elif token.symbol_type == LPAREN:
self.eat(LPAREN)
self.expr()
self.eat(RPAREN)
self.current_node = _save
def term(self):
"""term : factor ((MUL | DIV) factor)*"""
node = RuleNode('term')
self.current_node.add(node)
_save = self.current_node
self.current_node = node
self.factor()
while self.current_token.symbol_type in (MUL, DIV):
token = self.current_token
if token.symbol_type == MUL:
self.eat(MUL)
elif token.symbol_type == DIV:
self.eat(DIV)
self.factor()
self.current_node = _save
def expr(self):
"""
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : INTEGER | LPAREN expr RPAREN
"""
node = RuleNode('expr')
if self.root is None:
self.root = node
else:
self.current_node.add(node)
_save = self.current_node
self.current_node = node
self.term()
while self.current_token.symbol_type in (PLUS, MINUS):
token = self.current_token
if token.symbol_type == PLUS:
self.eat(PLUS)
elif token.symbol_type == MINUS:
self.eat(MINUS)
self.term()
self.current_node = _save
def parse(self):
self.expr()
return self.root
class ParseTreeVisualizer(object):
def __init__(self, parser):
self.parser = parser
self.ncount = 1
self.dot_header = [textwrap.dedent("""\
digraph astgraph {
node [shape=none, fontsize=12, fontname="Courier", height=.1];
ranksep=.3;
edge [arrowsize=.5]
""")]
self.dot_body = []
self.dot_footer = ['}']
def bfs(self, node):
ncount = 1
queue = []
queue.append(node)
s = ' node{} [label="{}"]\n'.format(ncount, node.name)
self.dot_body.append(s)
node._num = ncount
ncount += 1
while queue:
node = queue.pop(0)
for child_node in node.children:
s = ' node{} [label="{}"]\n'.format(ncount, child_node.name)
self.dot_body.append(s)
child_node._num = ncount
ncount += 1
s = ' node{} -> node{}\n'.format(node._num, child_node._num)
self.dot_body.append(s)
queue.append(child_node)
def gendot(self):
tree = self.parser.parse()
self.bfs(tree)
return ''.join(self.dot_header + self.dot_body + self.dot_footer)
def main():
argparser = argparse.ArgumentParser(
description='Generate a Parse Tree DOT file.'
)
argparser.add_argument(
'text',
help='Arithmetic expression (in quotes): "1 + 2 * 3"'
)
args = argparser.parse_args()
text = args.text
lexer = Lexer(text)
parser = Parser(lexer)
viz = ParseTreeVisualizer(parser)
content = viz.gendot()
print(content)
if __name__ == '__main__':
main()