-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_parser.py
More file actions
569 lines (391 loc) · 10.5 KB
/
Copy pathast_parser.py
File metadata and controls
569 lines (391 loc) · 10.5 KB
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
from compiler_studies.no_loop import scanner
class Node:
__counter = 0
def __init__(self):
self.id = Node.__counter
Node.__counter += 1
def __str__(self):
return '<{} {}>'.format(self.id, self.__class__.__name__)
class ASTNode(Node):
def __init__(self, type, children=None):
super().__init__()
self.type = type
# Filter out production rules -> $
self.children = [c for c in children if c is not None] or []
def __str__(self):
return '<{}:{}>'.format(self.id, self.type)
class ASTLeaf(Node):
def __init__(self, value):
super().__init__()
self.value = value
class Atom(Node):
def __init__(self, value):
super().__init__()
self.value = value
def __str__(self):
return '<{} {} {}>'.format(self.id, type(self).__name__, self.value)
class Comment(Node):
def __init__(self, value):
super().__init__()
self.value = value
class Num(Atom):
def __init__(self, value):
super().__init__(value)
class String(Atom):
def __init__(self, value):
super().__init__(value)
class VarLookup(Atom):
def __init__(self, value):
super().__init__(value)
class FunCall(Node):
def __init__(self, expr, args):
super().__init__()
self.expr = expr
self.args = args
def __str__(self):
return '<{} FunCall {} | {} args>'.format(self.id, self.expr, len(self.args))
@property
def children(self):
return self.args
class IfElse(Node):
def __init__(self, cond, cons, alt):
super().__init__()
self.cond = cond
self.cons = cons
self.alt = alt
def __str__(self):
return '<{} IfElse>'.format(self.id)
@property
def children(self):
return [self.cond, self.cons, self.alt]
class LambDef(Node):
def __init__(self, args, body):
super().__init__()
self.args = args
self.body = body
def __str__(self):
return '<{} LambDef ({})>'.format(self.id, self.args)
@property
def children(self):
return [self.body]
class Return(Node):
def __init__(self, expr):
super().__init__()
self.expr = expr
class Stmts(Node):
def __init__(self, stmts):
super().__init__()
self.stmts = stmts
def __str__(self):
return '<{} Stmts>'.format(self.id)
@property
def children(self):
return self.stmts
class InvalidSyntax(Exception):
pass
def stmts(stream):
lst = []
s = stmt(stream)
if s is None:
raise InvalidSyntax('Invalid statement {}'.format(stream.head))
while s is not None:
lst.append(s)
s = morestmts(stream)
return Stmts(lst)
def morestmts(stream):
# Bit of hand-waving here:
# When parsing a block like this:
# fun hello_world() {
# say_hello()
# say_world()
# }
#
# The guts of the function contains multiple statements.
# We're looking ahead here so we don't try to parse the
# closing } as a statement. Same for $ in the top level.
if stream.head.type in '$}':
return None
return stmt(stream)
def stmt(stream):
if stream.head.type == 'comment':
w = stream.head
next(stream)
return Comment(w.value)
ie = ifelse(stream)
if ie is not None:
return ie
r = ret(stream)
if r is not None:
return r
a = asgn(stream)
if a is not None:
return a
raise InvalidSyntax('Unable to parse statement')
def ret(stream):
if stream.head.value != 'return':
return None
next(stream)
e = expr(stream)
return Return(e)
def ifelse(stream):
if stream.head.value != 'if':
return None
next(stream)
cond = comp(stream)
if cond is None:
raise InvalidSyntax('Unable to parse condition')
stream.test('{')
next(stream)
cons = stmts(stream)
stream.test('}')
stream.next_and_test('else')
stream.next_and_test('{')
next(stream)
alt = stmts(stream)
stream.test('}')
next(stream)
return IfElse(cond, cons, alt)
def argsdef(stream):
if stream.head.type != '(':
raise InvalidSyntax('Expected (, found {}'.format(stream.head.type))
next(stream)
args = argsnames(stream) or []
if stream.head.type != ')':
raise InvalidSyntax('Expected ), found {}'.format(stream.head.type))
next(stream)
return args
def argsnames(stream):
if stream.head.type != 'name':
return None
args = [stream.head.value]
next(stream)
more = morenames(stream)
while more is not None:
args.append(more)
more = morenames(stream)
return args
def morenames(stream):
if stream.head.type != ',':
return None
next(stream)
if stream.head.type != 'name':
raise InvalidSyntax('Expected name, found {}'.format(stream.head.type))
name = stream.head.value
next(stream)
return name
def asgn(stream):
e = comp(stream)
prime = asgn_prime(stream)
if prime is not None:
return ASTNode(
'=',
[e, prime]
)
else:
return e
def asgn_prime(stream):
if stream.head.type == '=':
next(stream)
return comp(stream)
else:
return None
def comp(stream):
e = expr(stream)
prime = comp_prime(stream)
if prime is not None:
prime.children = [e] + prime.children
return prime
else:
return e
def comp_prime(stream):
if stream.head.value in ['==', '<=', '>=']:
w = stream.head
next(stream)
e = expr(stream)
return ASTNode(w.type, [e])
return None
def expr(stream):
t = term(stream)
prime = expr_prime(stream)
if prime is not None:
prime.children = [t] + prime.children
return prime
else:
return t
def expr_prime(stream):
if stream.head.type in '+-':
w = stream.head
next(stream)
t = term(stream)
prime = expr_prime(stream)
if prime is not None:
prime.children = [t] + prime.children
return ASTNode(
w.type,
[prime]
)
else:
return ASTNode(
w.type,
[t]
)
return None
def term(stream):
f = factor(stream)
prime = term_prime(stream)
if prime is not None:
prime.children = [f] + prime.children
return prime
else:
return f
def term_prime(stream):
if stream.head.type in '*/':
w = stream.head
next(stream)
f = factor(stream)
prime = term_prime(stream)
if prime is not None:
prime.children = [t] + prime.children
return ASTNode(
w.type,
[prime]
)
else:
return ASTNode(
w.type,
[f]
)
else:
return None
def factor(stream):
if stream.head.type == '(':
next(stream)
e = comp(stream)
if stream.head.type != ')':
raise InvalidSyntax('Expected ), found', stream.head.type)
next(stream)
return e
else:
return atomcalls(stream)
def atomcalls(stream):
node = atom(stream)
for a in callsargs(stream):
node = FunCall(node, a)
return node
def callsargs(stream):
all_allsargs = []
while stream.head.type == '(':
next(stream)
all_allsargs.append(args(stream))
if stream.head.type != ')':
raise InvalidSyntax('Expected ), found', stream.head.type)
next(stream)
return all_allsargs
def atom(stream):
lamb = lambdef(stream)
if lamb is not None:
return lamb
elif stream.head.type == 'num':
w = stream.head
next(stream)
return Num(w.value)
elif stream.head.type == 'string':
w = stream.head
next(stream)
return String(w.value)
elif stream.head.type == 'name':
w = stream.head
next(stream)
return VarLookup(w.value)
raise InvalidSyntax('Unable to parse atom {}'.format(stream.head.value))
def args(stream):
if stream.head.type == ')':
return []
arglist = []
a = comp(stream)
while a is not None:
arglist.append(a)
a = moreargs(stream)
return arglist
def moreargs(stream):
if stream.head.type == ',':
w = stream.head
next(stream)
return comp(stream)
else:
return None
def lambdef(stream):
if stream.head.value != '\\':
return None
next(stream)
al = argsdef(stream)
stream.test('{')
next(stream)
ss = stmts(stream)
stream.test('}')
next(stream)
return LambDef(al, ss)
parse = stmts
def pprint(node, indent=0):
print('{}{}'.format('\t'*indent, node))
if isinstance(node, ASTNode):
for child in node.children:
pprint(child, indent+1)
def print_dot(node):
def inner(node):
if not hasattr(node, 'children'):
print('"{}";'.format(node))
return
for child in node.children:
print('"{}" -> "{}";'.format(node, child))
inner(child)
print('digraph G {')
inner(node)
print('}')
class Stream:
def __init__(self, lexemes):
self.iter = iter(lexemes)
self.head = None
next(self)
def __next__(self):
if self.head is None or not self.is_eof():
try:
self.head = next(self.iter)
except StopIteration:
self.head = scanner.Lexeme('$', '$')
return self.head
else:
raise InvalidSyntax('Incomplete program')
def __iter__(self):
return self
def test(self, expected_value):
if self.head.value != expected_value:
raise InvalidSyntax('Expected {}; found {}'.format(expected_value, self.head.value))
def next_and_test(self, value):
next(self)
self.test(value)
def is_eof(self):
return self.head.type == '$'
def main():
prog = '''
func = \(n) {
c = n + 42
a b
return c
}
if 1 + 2 {
print('yes')
} else {
print('no')
}
a = b + func(1 + len('hello, ' + 'world'), c)
'''
lexemes = scanner.scan(prog)
stream = Stream(lexemes)
s = parse(stream)
if not stream.is_eof():
raise InvalidSyntax('Leftover starting with {}'.format(stream.head))
#pprint(e)
print_dot(s)
if __name__ == '__main__':
main()