-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
391 lines (303 loc) · 9.36 KB
/
parser.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
from pyparsing import (
Word,
nums,
alphas,
Combine,
oneOf,
opAssoc,
infixNotation,
Literal,
ParserElement,
Keyword,
Forward,
Optional,
Suppress,
Group,
QuotedString,
Regex
)
ParserElement.enablePackrat()
VarKW = Keyword("Var")
ReturnKW = Keyword("Return")
IfKW = Keyword("If")
ElseKW = Keyword("Else")
WhileKW = Keyword("While")
FunctionKW = Keyword("Func")
StringT = Keyword("String")
BoolT = Keyword("Bool")
IntegerT = Keyword("Int")
class IntegerLiteral:
def __init__(self, tokens):
self.value = int(tokens[0])
print("IntegerLiteral ", self.value)
class BinaryLiteral:
def __init__(self, tokens):
self.value = int("0b" + tokens[0][1:], 2)
print("BinaryLiteral ", self.value)
class BoolLiteral:
def __init__(self, tokens):
self.value = bool(tokens[0])
print("BoolLiteral ", self.value)
class VariableToken:
def __init__(self, tokens):
self.value = tokens[0]
print("VariableToken", self.value)
class StringLiteral:
def __init__(self, tokens):
self.value = tokens[0]
print("StringLiteral ", self.value)
class EvalSignOp:
def __init__(self, tokens):
print("EvalSignOp ", end='')
print(tokens[0])
self.sign, self.value = tokens[0]
def eval(self):
mult = {"+": 1, "-": -1}[self.sign]
return mult * self.value.eval()
def operatorOperands(tokenlist):
it = iter(tokenlist)
while 1:
try:
yield next(it), next(it)
except StopIteration:
break
class EvalPowerOp:
def __init__(self, tokens):
self.value = tokens[0]
print("EvalPowerOp ", end='')
print(self.value)
def eval(self):
res = self.value[-1].eval()
for val in self.value[-3::-2]:
res = val.eval() ** res
return res
class EvalMultOp:
def __init__(self, tokens):
self.value = tokens[0]
print("EvalMultOp ", end='')
print(self.value)
def eval(self):
prod = self.value[0].eval()
for op, val in operatorOperands(self.value[1:]):
if op == "*":
prod *= val.eval()
if op == "/":
prod /= val.eval()
return prod
class EvalAddOp:
def __init__(self, tokens):
self.value = tokens[0]
print("EvalAddOp ", end='')
print(self.value)
def eval(self):
sum = self.value[0].eval()
for op, val in operatorOperands(self.value[1:]):
if op == "+":
sum += val.eval()
if op == "-":
sum -= val.eval()
return sum
class EvalComparisonOp:
opMap = {
"<": lambda a, b: a < b,
"<=": lambda a, b: a <= b,
">": lambda a, b: a > b,
">=": lambda a, b: a >= b,
"/=": lambda a, b: a != b,
"==": lambda a, b: a == b,
}
def __init__(self, tokens):
self.value = tokens[0]
print("EvalComparisonOp ", end='')
print(self.value)
def eval(self):
val1 = self.value[0].eval()
for op, val in operatorOperands(self.value[1:]):
fn = EvalComparisonOp.opMap[op]
val2 = val.eval()
if not fn(val1, val2):
break
val1 = val2
else:
return True
return False
class EvalNegOp:
def __init__(self, tokens):
self.neg, self.value = tokens[0]
print("EvalNegOp ", end='')
print(self.value)
def eval(self):
return not self.value.eval()
class EvalAndOp:
def __init__(self, tokens):
self.value = tokens[0]
print("EvalAndOp ", end='')
print(self.value)
def eval(self):
val1 = self.value[0].eval()
if not val1:
return False
for op, val in operatorOperands(self.value[1:]):
val2 = val.eval()
if not (val1 and val2):
break
val1 = val2
return True
class EvalOrOp:
def __init__(self, tokens):
self.value = tokens[0]
print("EvalOrOp ", end='')
print(self.value)
def eval(self):
if self.value[0].eval():
return True
for op, val in operatorOperands(self.value[1:]):
if val.eval():
return True
return False
class EvalFunctionCall:
def __init__(self, tokens):
self.name = tokens[0]
self.arguments = tokens[1:]
print("EvalFunctionCall ", end='')
print(self.name, ' ', self.arguments)
class VariableDeclaration:
def __init__(self, tokens):
self.type = tokens[0]
self.name = tokens[1]
self.value = tokens[2]
print("VariableDeclaration ", end='')
print(self.name, ' ', self.value)
class AssignmentStatement:
def __init__(self, tokens):
self.name = tokens[0]
self.value = tokens[1]
print("Assignment statement", end='')
print(self.name, ' ', self.value)
class FunctionDeclaration:
def __init__(self, tokens):
print(tokens)
self.name = tokens[0]
# TODO: change index of end
self.args = tokens[1]
self.return_type = tokens[2]
self.body = tokens[3]
class ReturnStatement:
def __init__(self, tokens):
self.value = tokens[0]
print("ReturnStatement ", self.value)
class IfStatement:
def __init__(self, tokens):
self.t = len(tokens) >= 3
self.cond = tokens[0]
self.then_br = tokens[1]
print("IfStatement ", self.cond, ' ', self.then_br, end='')
if self.t:
self.else_br = tokens[2]
print(' ', self.else_br)
class WhileStatement:
def __init__(self, tokens):
self.cond = tokens[0]
self.while_body = tokens[1]
print("WhileStatement ", self.cond, ' ', self.while_body)
class LProgram:
def __init__(self, tokens):
self.funcs = tokens
print("LProgram ", self.funcs)
expr = Forward()
integer = Word(nums)
# variable = Word(alphas)
variable = Regex(r"[a-z][a-zA-Z0-9]*")
TYPE = StringT | BoolT | IntegerT
StringL = QuotedString('"', endQuoteChar='"')
BoolL = Literal("True") | Literal("False")
BinaryL = Regex(r"B[01]+")
IntegerL = integer
Lit = BinaryL | StringL | BoolL | IntegerL
LP = Literal('(')
LB = Literal('{')
RP = Literal(')')
RB = Literal('}')
ASSIGN = Literal(':=')
ARROW = Literal('->')
COMMA = Literal(',')
EOS = Literal(';')
return_statement = Suppress(ReturnKW) + expr + EOS
function_call = variable + Suppress(LP) + Optional(expr + (Suppress(COMMA) + expr)[...]) + Suppress(RP)
signop = oneOf("+ -")
multop = oneOf("* /")
plusop = oneOf("+ -")
expop = Literal("^")
negop = Literal("!")
logic_or_op = Literal("||")
logic_and_op = Literal("&&")
IntegerL.setParseAction(IntegerLiteral)
BoolL.setParseAction(BoolLiteral)
variable.setParseAction(VariableToken)
BinaryL.setParseAction(BinaryLiteral)
StringL.setParseAction(StringLiteral)
function_call.setParseAction(EvalFunctionCall)
arith_expr = infixNotation(
function_call | Lit | variable,
[
(signop, 1, opAssoc.RIGHT, EvalSignOp),
(expop, 2, opAssoc.LEFT, EvalPowerOp),
(multop, 2, opAssoc.LEFT, EvalMultOp),
(plusop, 2, opAssoc.LEFT, EvalAddOp),
],
)
comparisonop = oneOf("< <= > >= /= ==")
comp_expr = infixNotation(
arith_expr,
[
(comparisonop, 2, opAssoc.LEFT, EvalComparisonOp),
],
)
logic_expr = infixNotation(
comp_expr,
[
(negop, 1, opAssoc.RIGHT, EvalNegOp),
(logic_and_op, 2, opAssoc.LEFT, EvalAndOp),
(logic_or_op, 2, opAssoc.LEFT, EvalOrOp),
]
)
expr <<= logic_expr
if_statement = Forward()
while_statement = Forward()
statement = Forward()
statement_list = statement[...]
var_decl_statement = Suppress(VarKW) + TYPE + variable + Suppress(ASSIGN) + expr + Suppress(EOS)
assignment_statement = variable + Suppress(ASSIGN) + expr + Suppress(EOS)
if_statement <<= Suppress(IfKW) \
+ Suppress(LP) \
+ expr \
+ Suppress(RP) \
+ Suppress(LB) \
+ statement_list \
+ Suppress(RB) + Optional(Suppress(ElseKW + LB) + statement_list + Suppress(RB))
while_statement <<= Suppress(WhileKW) \
+ Suppress(LP) \
+ expr \
+ Suppress(RP) \
+ Suppress(LB) \
+ statement_list \
+ Suppress(RB)
statement <<= while_statement | var_decl_statement | if_statement | return_statement | assignment_statement | (
expr + Suppress(EOS)) | Suppress(EOS)
function_declaration \
= Suppress(FunctionKW) + \
variable + Suppress(LP) + \
Group(Optional(Group(TYPE + variable) + (Suppress(COMMA) + Group(TYPE + variable))[...])) \
+ Suppress(RP) + Suppress(ARROW) + TYPE + Suppress(LB) + statement_list + Suppress(RB)
program_entry = function_declaration[1, ...]
var_decl_statement.setParseAction(VariableDeclaration)
if_statement.setParseAction(IfStatement)
while_statement.setParseAction(WhileStatement)
assignment_statement.setParseAction(AssignmentStatement)
return_statement.setParseAction(ReturnStatement)
program_entry.setParseAction(LProgram)
function_declaration.setParseAction(FunctionDeclaration)
with open(input(), 'r') as file:
data = file.read().replace('\n', '')
ast = program_entry.parseString(data, parseAll=True)[0]
print(ast)