-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_parser.py
More file actions
613 lines (522 loc) · 20.8 KB
/
Copy pathast_parser.py
File metadata and controls
613 lines (522 loc) · 20.8 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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import os
import sys
import scanner
class ASTNode:
def __init__(self, type, value = None):
self.type = type
self.value = value
self.children = []
def add_child(self, child):
self.children.append(child)
def __repr__(self, level = 0):
ret = " " * level + "├" + "── " + f"{self.type} ({self.value if self.value else ''})\n"
for child in self.children:
ret += child.__repr__(level + 1)
return ret
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
self.declared_strings = set()
self.declared_lists = set()
self.declared_functions = set()
def current_token(self):
if self.pos < len(self.tokens):
token_class, token_val = self.tokens[self.pos][1:-1].split(", ")
return token_class, token_val[1:-1]
return None
def advance(self):
self.pos += 1
def match_values(self, token_class, token_values = None):
if token_values is None:
token_values = []
if self.current_token() and self.current_token()[0] == token_class \
and (token_values == [] or self.current_token()[1] in token_values):
return self.current_token()
return None
def match(self, token_class, token_value = None):
if self.current_token() and self.current_token()[0] == token_class \
and (token_value is None or self.current_token()[1] == token_value):
return self.current_token()
return None
def parse_program(self):
root = ASTNode('PROGRAM')
while self.current_token():
node = self.parse_next()
if node:
root.add_child(node)
else:
raise SyntaxError(f"Syntax error at token {self.current_token()[1]}")
return root
def parse_next(self):
# Parse variable assignment
if self.match('KEYWORD', 'string') or self.match('KEYWORD', 'list'):
return self.parse_declaration()
# Parse functions
elif self.match('KEYWORD', 'define'):
return self.parse_function()
# Parse function calls
elif self.match('KEYWORD', 'call'):
return self.parse_function_call()
# Parse statement
else:
return self.parse_statement()
def parse_declaration(self):
root = ASTNode('DECLARATION')
if self.match('KEYWORD', 'string'):
root.add_child(ASTNode('KEYWORD', "string"))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
else:
return
else:
root.add_child(ASTNode('KEYWORD', 'list'))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_lists.add(self.current_token()[1])
self.advance()
else:
return
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
node = self.parse_list()
if node:
root.add_child(node)
else:
return
if self.match('SEPARATOR', ';'):
root.add_child(ASTNode('SEPARATOR', ';'))
self.advance()
else:
raise SyntaxError(f"Syntax error at token {self.current_token()[1]}")
return root
def parse_list(self):
root = ASTNode('LIST')
if self.match('SEPARATOR', '['):
root.add_child(ASTNode('SEPARATOR', '['))
self.advance()
while self.current_token() and self.current_token()[1] != ']':
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
elif self.match('IDENTIFIER') and self.current_token()[1] in self.declared_strings:
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
else:
raise SyntaxError(f"Syntax error at token {self.current_token()[1]}")
self.advance()
if self.current_token()[1] == ']':
root.add_child(ASTNode('SEPARATOR', ']'))
self.advance()
break
if self.match('SEPARATOR', ','):
root.add_child(ASTNode('SEPARATOR', ','))
self.advance()
else:
return
elif self.match('KEYWORD', 'get_files'):
root.add_child(ASTNode('KEYWORD', 'get_files'))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
return root
def parse_function(self):
root = ASTNode("FUNCTION")
node = self.parse_function_header()
if node:
root.add_child(node)
else:
return
root.add_child(self.parse_block())
return root
def parse_function_header(self):
root = ASTNode('FUNC_HEADER')
if self.match('KEYWORD', 'define'):
root.add_child(ASTNode('KEYWORD', "define"))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_functions.add(self.current_token()[1])
self.advance()
else:
return
node = self.parse_param_list()
if node:
root.add_child(node)
else:
return
return root
def parse_param_list(self):
root = ASTNode('PARAMETER_LIST')
if self.match('SEPARATOR', '('):
root.add_child(ASTNode('SEPARATOR', '('))
self.advance()
while self.current_token() and self.current_token()[1] != ')':
node = self.parse_parameter()
expecting_parameter = False
if node:
root.add_child(node)
if self.match('SEPARATOR', ','):
root.add_child(ASTNode('SEPARATOR', ','))
self.advance()
expecting_parameter = True
else:
break
if expecting_parameter:
raise SyntaxError("Syntax Error: Trailing ',' with no parameter")
else:
return
if self.match('SEPARATOR', ')'):
root.add_child(ASTNode('SEPARATOR', ')'))
self.advance()
else:
return
return root
def parse_parameter(self):
root = ASTNode('PARAMETER')
if self.match('KEYWORD', 'string'):
root.add_child(ASTNode('KEYWORD', "string"))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
elif self.match('KEYWORD', 'list'):
root.add_child(ASTNode('KEYWORD', 'list'))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_lists.add(self.current_token()[1])
self.advance()
else:
return
else:
return
return root
def parse_block(self):
root = ASTNode('BLOCK')
if self.match('SEPARATOR', '{'):
root.add_child(ASTNode('SEPARATOR', '{'))
self.advance()
while self.current_token() and self.current_token()[1] != '}':
if self.match('KEYWORD', 'call'):
root.add_child(self.parse_function_call())
continue
if self.match('KEYWORD', 'string') or self.match('KEYWORD', 'list'):
root.add_child(self.parse_declaration())
continue
if self.match('KEYWORD', 'foreach'):
root.add_child(self.parse_foreach())
continue
else:
root.add_child(self.parse_statement())
else:
raise SyntaxError(f"Syntax error at token {self.current_token()[1]}")
if self.match('SEPARATOR', '}'):
root.add_child(ASTNode('SEPARATOR', '}'))
self.advance()
else:
raise SyntaxError(f"Syntax error at token {self.current_token()[1]}")
return root
def parse_statement(self):
root = ASTNode('STATEMENT')
acceptable_keywords_type_1 = ['create_directory','display_files', 'create_new_file','get_files']
acceptable_keywords_type_2 = ['move_files', 'copy_files']
if self.match_values('KEYWORD', acceptable_keywords_type_1):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
elif self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
elif self.match_values('KEYWORD', acceptable_keywords_type_2):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD','in'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
if self.current_token() and self.current_token()[1] == 'ends_with':
if self.match('KEYWORD', 'ends_with'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD','to'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
elif self.match('KEYWORD', 'append'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD', 'to'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
elif self.match('KEYWORD', 'add_content'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD', 'to'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
elif self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
else:
return
elif self.match('KEYWORD', 'bulk_rename_files'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD','in'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
else:
return
if self.match('KEYWORD','to'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
else:
return
root.add_child(self.parse_expression())
else:
raise SyntaxError(f"Syntax error at {self.current_token()[1]}")
if self.match('SEPARATOR', ';'):
root.add_child(ASTNode('SEPARATOR', ';'))
else:
raise SyntaxError(f"Syntax error at {self.current_token()[1] if self.current_token() else 'EOF'}")
self.advance()
return root
def parse_expression(self):
root = ASTNode('EXPRESSION')
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
elif self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
elif self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.advance()
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
elif self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.advance()
if self.match('OPERATOR'):
root.add_child(ASTNode('OPERATOR', self.current_token()[1]))
self.advance()
else:
return
if self.match('STRING'):
root.add_child(ASTNode('STRING', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
else:
return
else:
return
return root
def parse_function_call(self):
root = ASTNode('FUNC_CALL')
if self.match('KEYWORD', 'call'):
root.add_child(ASTNode('KEYWORD', "call"))
self.advance()
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
# self.declared_functions.add(self.current_token()[1])
self.advance()
else:
return
node = self.parse_argument_list()
if node:
root.add_child(node)
if self.match('SEPARATOR', ';'):
root.add_child(ASTNode('SEPARATOR', ';'))
else:
raise SyntaxError(f"Syntax error at {self.current_token()[1] if self.current_token() else 'EOF'}")
self.advance()
return root
def parse_argument_list(self):
root = ASTNode('ARGUMENTS')
if self.match('SEPARATOR', '('):
root.add_child(ASTNode('SEPARATOR', '('))
self.advance()
expecting_argument = True
while self.current_token() and self.current_token()[1] != ')':
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_strings.add(self.current_token()[1])
self.advance()
expecting_argument = False
if self.current_token()[1] == ')':
break
if self.match('SEPARATOR', ','):
root.add_child(ASTNode('SEPARATOR', ','))
self.advance()
expecting_argument = True
if expecting_argument:
raise SyntaxError("Syntax Error: Trailing ',' with no argument")
self.match('SEPARATOR', ')')
root.add_child(ASTNode('SEPARATOR', ')'))
self.advance()
return root
def parse_foreach(self):
root = ASTNode('FOREACH')
if self.match('KEYWORD', 'foreach'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
while self.current_token():
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_functions.add(self.current_token()[1])
self.advance()
continue
if self.match('KEYWORD', 'in'):
root.add_child(ASTNode('KEYWORD', self.current_token()[1]))
self.advance()
continue
if self.match('IDENTIFIER'):
root.add_child(ASTNode('IDENTIFIER', self.current_token()[1]))
self.declared_functions.add(self.current_token()[1])
self.advance()
continue
if self.match('SEPARATOR', '{'):
root.add_child(self.parse_block())
break
else:
return
return root
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Argument missing: python3 ast_parser.py <input_file>")
sys.exit(1)
input_dir = "Parser_Input_Programs/"
input_file = os.path.join(input_dir, sys.argv[1])
try:
with open(input_file, 'r') as file:
program = file.read()
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
sys.exit(1)
# Run the scanner
scanner = scanner.Scanner()
tokens, errors = scanner.scan(program)
if errors:
for error in errors:
print(error)
sys.exit(1)
# Run the parser
parser = Parser(tokens)
try:
ast = parser.parse_program()
print("\nGenerated AST:")
print(ast)
except SyntaxError as e:
print(f"Syntax error: {e}")