/
parserAST.py
308 lines (247 loc) · 6.61 KB
/
parserAST.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
Morgan Peters and Sean Gray
CS 440: Languages and Translators
Spring 2017
AST output of MUZL
"""
import ply.yacc as yacc
# token map import
from lexical import tokens
import MuzlRule
class Node:
def __init__(self,val):
self.val=val
self.children=[]
def set_child(self,child):
self.children.append(child)
def print_tree(node):
queue = [(node, 0)]
a = False
b = False
c = False
while queue:
current = queue.pop(0)
for x in current[0].children:
queue.append((x,current[1]+1))
if queue:
if queue[0][1] == current[1]:
a = current[0].val
else:
b = current[0].val
else:
c = current[0].val
if not a and b:
print('{:^20}'.format(b))
b = False
if a and b:
print('{:^10} {:^10}'.format(a,b))
a = False
b = False
if c:
print('{:^10}'.format(c))
rules = {}
variables = {}
precedence = (
('nonassoc', 'LTHAN', 'GTHAN', 'ETO', 'GETHAN', 'LETHAN'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE'),
('left', 'POW')
)
# this needs to stay above all the start options, it defines what items can stand alone in a parse
def p_start(p):
'''start : rule
| expression'''
node = Node("start")
node.set_child(p[1])
p[0]=node
def p_rule(p):
'''rule : rname RULE LPAREN assign RPAREN ARROW type RBLOCK'''
rules[p[1]] = MuzlRule.rule(p[1], p[4], p[7], p[8])
p[0] = p[1] + ' created.'
def p_rname(p):
'''rname : ID'''
node =Node(p[1])
p[0] = node
def p_assign_variables(p):
'''assign : assign COLON ID type
| ID type
| empty '''
if len(p) == 3:
node = Node([[p[1], p[2]]])
p[0] = node
elif len(p) == 5:
# these two need to be on different lines due to = assigning before .append
node = Node([[p[3],p[4]]])
node.set_child(p[1])
p[0] = node
# catch no args so it is empty list vs none
else:
p[0] = Node([])
def p_expression_comparisons(p):
'''expression : expression ETO val
| expression LETHAN val
| expression GETHAN val
| expression GTHAN val
| expression LTHAN val '''
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_expression_plus(p):
'expression : expression PLUS term'
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_expression_subtract(p):
'''expression : expression MINUS term
| MINUS expression'''
if len(p) == 3:
node = Node(p[1])
node.set_child(p[2])
p[0] = node
else:
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_expression_term(p):
'''expression : term'''
node = Node("expression")
node.set_child(p[1])
p[0] = node
def p_expression_mult(p):
'term : term TIMES mathlv1'
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_expression_divide(p):
'term : term DIVIDE mathlv1'
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_term_math1(p):
'term : mathlv1'
node = Node("term")
node.set_child(p[1])
p[0] = node
def p_math1_math0(p):
'mathlv1 : mathlv0'
node = Node("mathlv1")
node.set_child(p[1])
p[0] = node
def calc_rule(rule, bindings):
for x in range(0, len(bindings)):
variables[rule.args[x][0]] = bindings[x]
parse_result = parser.parse(rule.expression)
return parse_result
def p_expression_rule(p):
'''mathlv1 : ID LPAREN args RPAREN
| ID LPAREN RPAREN'''
if p[1] in rules.keys():
# check that arguments given match arguments expected first set of ifs to see if args
if len(p) > 4:
if len(rules[p[1]].args) == len(p[3]):
node = Node("Rule")
node.set_child(calc_rule(rules[p[1]], p[3]))
p[0] = node
else:
print('Error: Argument Mismatch, expeted', len(rules[p[1]].args), ' found ', len(p[3]))
else:
if len(rules[p[1]].args) == 0:
node = Node("Rule")
node.set_child(calc_rule(rules[p[1]],[]))
p[0] = node
else:
print('Error: Argument Mismatch, expeted', len(rules[p[1]].args), ' found ', len(p[3]))
else:
print('Error: Rule not found:', p[1])
def p_args(p):
'''args : val
| args val'''
# no args
if len(p) == 1:
p[0] = Node([])
# one arg
elif len(p) == 2:
node = Node(p[1])
p[0] = node
else:
node = Node(p[2])
node.set_child(p[1])
p[0] = node
def p_expression_pow(p):
'mathlv1 : mathlv1 POW mathlv0'
node = Node(p[2])
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
def p_expression_parens(p):
'''mathlv0 : LPAREN expression RPAREN
| LPAREN expression RPAREN DOT type'''
if len(p) == 6:
node = Node('()')
node.set_child(p[2])
node2 = Node('.')
node2.set_child(p[5])
node2.set_child(node)
p[0] = node2
else:
node = Node('()')
node.set_child(p[2])
p[0] = node
def p_term_val(p):
'''mathlv0 : val
| val DOT type'''
if len(p) == 2:
node = Node("mathlv0")
node.set_child(p[1])
p[0] = node
else:
node = Node('.')
node.set_child(p[1])
node.set_child(p[3])
p[0] = node
# No string type change added
# does not recognise Char/doubles to convert
def p_value(p):
'''val : INT
| FLOAT
| CHAR
| STRING
| BOOL
| HEX '''
p[0] = Node(p[1])
def p_val_id(p):
'''val : ID '''
if p[1] in variables.keys():
p[0] = Node(variables[p[1]])
else:
print("ID not found:", p[1])
def p_type(p):
'''type : INT_T
| FLOAT_T
| CHAR_T
| STRING_T
| BOOL_T
| HEX_T '''
p[0] = Node(p[1])
def p_empty(p):
'''empty : '''
def p_error(p):
print("Syntax Error at", p.value)
parser = yacc.yacc()
def get_parser():
return parser
if __name__ == '__main__':
while True:
try:
s = input('!-')
except EOFError:
break
if not s:
continue
result = parser.parse(s)
print_tree(result)