-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast.py
More file actions
2804 lines (2244 loc) · 89.7 KB
/
ast.py
File metadata and controls
2804 lines (2244 loc) · 89.7 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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import lex
from ir3 import *
from typing import List, Set, Dict, Tuple, Optional, Callable, Optional, Any, Union, Type
######################################################################
######################## ABSTRACT SYNTAX TREE ########################
######################################################################
AST_PROGRAM = "PROGRAM"
AST_MAINCLASS = "MAINCLASS"
AST_CLASSDECL = "CLASSDECL"
AST_CLASSDECLS = "CLASSDECLS"
AST_CNAME = "CNAME"
AST_MDDECL = "MDDECL"
AST_MDDECLS = "MDDECLS"
AST_BLOCK = "BLOCK"
AST_VARDECLS = "VARDECLS"
AST_VARDECL = "VARDECL"
AST_STMTS = "STMTS"
AST_ID = "ID"
AST_FMLLIST = "PARAMETERS"
AST_MDBODY = "MDBODY"
AST_FML = "PARAMETER"
AST_TYPE = "TYPE"
AST_INT = "INT"
AST_BOOL = "BOOL"
AST_STRING = "STRING"
AST_VOID = "VOID"
AST_IF_STATEMENT = "IF"
AST_CONDITIONAL_EXP = "CONDITIONAL"
AST_IF_BODY = "IF_BODY"
AST_ELSE_BODY = "ELSE_BODY"
AST_WHILE = "WHILE"
AST_WHILE_BODY = "WHILE_BODY"
AST_READLN = "READLN"
AST_PRINTLN = "PRINTLN"
AST_METHOD_CALL = "METHOD_CALL"
AST_EXPLIST = "EXPLIST"
AST_RETURN = "RETURN"
AST_FIELD_ACCESS = "FIELD_ACCESS"
AST_EXP = "EXP"
AST_BEXP = "BEXP"
AST_SEXP = "SEXP"
AST_CONJ = "CONJ"
AST_AND = "&&"
AST_OR = "||"
AST_REXP = "REXP"
AST_BGRD = "BGRD"
AST_BOP = "BOP"
AST_LT = "<"
AST_GT = ">"
AST_LE = "<="
AST_GE = ">="
AST_EQ = "=="
AST_NE = "!="
AST_TRUE = "TRUE"
AST_FALSE = "FALSE"
AST_ATOM = "ATOM"
AST_TERM = "TERM"
AST_NEGATE = '!'
AST_PLUS = "+ ADD"
AST_MINUS = "- MINUS"
AST_MULT = "*"
AST_DIV = "/"
AST_FACTOR = "FTR"
AST_INT_LITERAL = "INT_LITERAL"
AST_STR_LITERAL = "STR_LITERAL"
AST_CONCAT = "+ CONCAT"
AST_EPSILON = "EPSILON"
AST_UNEGATIVE = "- UNEG"
AST_THIS = "THIS"
AST_CLASS_INSTANCE_CREATION = "CLASS_INSTANCE_CREATION"
AST_NULL = "NULL"
AST_RETURN_STATEMENT = "RETURN_STATEMENT"
AST_ASSIGNMENT_STATEMENT = "ASSIGNMENT_STATEMENT"
# Hack to retrieve all string literals associated with a program
string_literals = []
def get_string_literals():
return string_literals
class AstNode:
@classmethod
def epsilon(cls) -> 'AstNode':
return AstNode(AST_EPSILON)
######################### NONTERMINALS #########################
@classmethod
def make_program(cls, mainclass: 'MainClass', classdecls: 'ClassDecls') -> 'Program':
return Program(mainclass, classdecls)
@classmethod
def make_mainclass(cls, cname: 'Cname', mainmd: 'MdDecl') -> 'MainClass':
return MainClass(cname, mainmd)
@classmethod
def make_classdecls(cls, classdecls: List['ClassDecl']) -> 'ClassDecls':
return ClassDecls(classdecls)
@classmethod
def make_classdecl(cls, cname: 'Cname', vardecls: 'VarDecls', mddecls: 'MdDecls') -> 'ClassDecl':
return ClassDecl(cname, vardecls, mddecls)
@classmethod
def make_mddecls(cls, mddecls: List['MdDecl']) -> 'MdDecls':
return MdDecls(mddecls)
@classmethod
def make_mddecl(cls, type: 'AstType', id: 'Id', fmllist: 'FmlList', mdbody: 'MdBody') -> 'MdDecl':
return MdDecl(type, id, fmllist, mdbody)
@classmethod
def make_fmllist(cls, fmls: List['Fml']) -> 'FmlList':
return FmlList(fmls)
@classmethod
def make_fml(cls, type_node: 'AstType', id_node: 'Id') -> 'Fml':
return Fml(type_node, id_node)
@classmethod
def make_mdbody(cls, vardecls: 'VarDecls', stmts: 'Stmts') -> 'MdBody':
return MdBody(vardecls, stmts)
@classmethod
def make_vardecls(cls, vardecls: List['VarDecl']) -> 'VarDecls':
return VarDecls(vardecls)
@classmethod
def make_vardecl(cls, type: 'AstType', id: 'Id') -> 'VarDecl':
return VarDecl(type, id)
@classmethod
def make_stmts(cls, stmts: List['AstNode']) -> 'Stmts':
return Stmts(stmts)
@classmethod
def make_if_statement(cls, conditional: 'Exp', if_body: 'Stmts', else_body: 'Stmts') -> 'IfStatement':
return IfStatement(conditional, if_body, else_body)
@classmethod
def make_while_statement(cls, conditional: 'AstNode', while_body: 'AstNode') -> 'WhileStatement':
return WhileStatement(conditional, while_body)
@classmethod
def make_exp(cls, actual_exp: 'AstNode') -> 'Exp':
return Exp(actual_exp)
@classmethod
def make_explist(cls, exps: List['Exp']) -> 'ExpList':
return ExpList(exps)
@classmethod
def make_complement(cls, bgrd_atom_true_false: 'AstNode') -> 'Complement':
return Complement(bgrd_atom_true_false)
@classmethod
def make_and_op(cls, left: 'AstNode', right: 'AstNode') -> 'AndOp':
return AndOp(left, right)
@classmethod
def make_or_op(cls, left: 'AstNode', right: 'AstNode') -> 'OrOp':
return OrOp(left, right)
@classmethod
def make_plus_op(cls, left: 'AstNode', right: 'AstNode') -> 'PlusOp':
return PlusOp(left, right)
@classmethod
def make_minus_op(cls, left: 'AstNode', right: 'AstNode') -> 'MinusOp':
return MinusOp(left, right)
@classmethod
def make_mult_op(cls, left: 'AstNode', right: 'AstNode') -> 'MultOp':
return MultOp(left, right)
@classmethod
def make_div_op(cls, left: 'AstNode', right: 'AstNode') -> 'DivOp':
return DivOp(left, right)
@classmethod
def make_unegative(cls, factor: 'AstNode') -> 'Unegative':
return Unegative(factor)
@classmethod
def make_class_instance_creation(cls, cname: 'Cname') -> 'ClassInstanceCreation':
return ClassInstanceCreation(cname)
@classmethod
# due to how we construct the ast, left may be None, but the final ast won't have None.
def make_field_access(cls, left: Optional['AstNode'], id: 'Id') -> 'FieldAccess':
return FieldAccess(left, id)
@classmethod
# due to how we construct the ast, left may be None, but the final ast won't have None.
def make_method_call(cls, left: Optional['AstNode'], explist: 'ExpList') -> 'MethodCall':
return MethodCall(left, explist)
@classmethod
def make_return_statement(cls, exp: Optional['AstNode']=None) -> 'ReturnStatement':
return ReturnStatement(exp)
@classmethod
def make_assignment_statement(cls, left: 'AstNode', right: 'AstNode') -> 'AssignmentStatement':
return AssignmentStatement(left, right)
@classmethod
def make_println(cls, exp: 'AstNode') -> 'Println':
return Println(exp)
@classmethod
def make_readln(cls, idd: 'Id')-> 'Readln':
return Readln(idd)
@classmethod
def make_lt(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Lt':
return Lt(lhs, rhs)
@classmethod
def make_gt(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Gt':
return Gt(lhs, rhs)
@classmethod
def make_le(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Le':
return Le(lhs, rhs)
@classmethod
def make_ge(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Ge':
return Ge(lhs, rhs)
@classmethod
def make_eq(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Eq':
return Eq(lhs, rhs)
@classmethod
def make_ne(cls, lhs: 'AstNode'=None, rhs: 'AstNode'=None) -> 'Ne':
return Ne(lhs, rhs)
######################### TERMINALS #########################
@classmethod
def make_int(cls) -> 'Int':
return Int()
@classmethod
def make_bool(cls) -> 'Bool':
return Bool()
@classmethod
def make_string(cls) -> 'String':
return String()
@classmethod
def make_void(cls) -> 'Void':
return Void()
@classmethod
def make_cname(cls, tok: lex.Token) -> 'Cname':
# except the first letter, uppercase letters are not distinguished from lowercase
tok.value = tok.value.lower().capitalize()
return Cname(tok)
@classmethod
def make_id(cls, tok: lex.Token) -> 'Id':
# except the first letter, uppercase letters are not distinguished from lowercase
tok.value = tok.value.lower()
return Id(tok)
@classmethod
def make_true(cls, tok: lex.Token) -> 'TrueLit':
return TrueLit(tok)
@classmethod
def make_false(cls, tok: lex.Token) -> 'FalseLit':
return FalseLit(tok)
@classmethod
def make_integer_literal(cls, tok: lex.Token) -> 'IntegerLiteral':
return IntegerLiteral(tok)
@classmethod
def make_string_literal(cls, tok: lex.Token) -> 'StringLiteral':
return StringLiteral(tok)
@classmethod
def make_this(cls, tok: lex.Token) -> 'This':
return This(tok)
@classmethod
def make_null(cls, tok: lex.Token) -> 'Null':
return Null(tok)
def __init__(self, name: str, value: lex.Token=None, children=None):
if children is None:
children = []
self.name = name
self.value = value
self.children = children
def set_left_child(self, node: 'AstNode'):
if len(self.children) != 2:
raise AssertionError("set_left_child")
self.children[0] = node
def set_right_child(self, node: 'AstNode'):
if len(self.children) != 2:
raise AssertionError("set_right_child")
self.children[1] = node
# must be overriden
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
raise RuntimeError("static_check not defined on AstNode")
# must be overriden
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError("ir3 not defined on AstNode")
def __repr__(self):
if self.value:
return f"AstNode({self.name}, {self.value})"
return f"AstNode({self.name})"
def __str__(self):
return print_tree(self, 0)
########################### NONTERMINAL AST NODES ###########################
class Program(AstNode):
def __init__(self, mainclass: 'MainClass', classdecls: 'ClassDecls'):
super().__init__(name=AST_PROGRAM, children=[mainclass,classdecls])
# persist the type env for ir3 later
self.type_env = None
@property
def mainclass(self) -> 'MainClass':
return self.children[0]
@property
def classdecls(self) -> 'ClassDecls':
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
# distinct name-checking done during initialization
self.type_env = TypeEnvironment.initialize(self.mainclass, self.classdecls)
# print(type_env)
# type check
self.mainclass.static_check(self.type_env, metadata)
self.classdecls.static_check(self.type_env, metadata)
def ir3(self, context: Dict[str, Any]) -> Program3:
cdata3_list = []
cmtd3_list = []
# fill in main class
main_class: MainClass = self.mainclass
main_classname = main_class.cname.class_name
# pass classname down to child nodes (e.g method call nodes need to mangle names too)
context["classname"] = main_classname
main_md: MdDecl = main_class.mainmd
# fill in cdata3 of main class
fds, msigs = self.type_env.class_lookup(main_classname)
vardecls = [VarDecl3(type3, id3) for id3, type3 in fds.items()]
cdata3_list.append(CData3(main_classname, vardecls))
# fill in cmtd3 of main class
for mname, msig in msigs.items():
fmllist, rettype = msig
fmllist3: FmlList3 = FmlList3(main_classname, [Fml3(JClass(main_classname), "this")] + [Fml3(type3, id3) for id3, type3 in fmllist])
context["parameters"] = fmllist3.fml3_list
context["localvars"] = main_md.mdbody.vardecls.vardecl_list
# generate ir3 for a single method
mdbody3: MdBody3 = main_md.mdbody.ir3(context)
# generate mangled method name, e.g %Functional_f(a, b)
mangled_mname = IR3Node.mangle_method_name(context["classname"], mname)
cmtd3 = CMtd3(rettype, mangled_mname, fmllist3, mdbody3)
cmtd3_list.append(cmtd3)
# fill in class decls (and their methods)
class_decls: ClassDecls = self.classdecls
for class_decl_node in class_decls.classdecls:
classname = class_decl_node.cname.class_name
# pass classname down to child nodes (e.g method call nodes need to mangle names too)
context["classname"] = classname
md_decls: MdDecls = class_decl_node.mddecls
# fill in cdata3 of current class
fds, msigs = self.type_env.class_lookup(classname)
vardecls = [VarDecl3(type3, id3) for id3, type3 in fds.items()]
cdata3_list.append(CData3(classname, vardecls))
# fill in cmtd3 of current class
for md_decl_node in md_decls.mddecl_list:
md_name = md_decl_node.id_node.id_name
md_sig = msigs[md_name]
md_fml_list, md_ret_type = md_sig
fmllist3: FmlList3 = FmlList3(classname, [Fml3(JClass(classname), "this")] + [Fml3(type3, id3) for id3, type3 in md_fml_list])
# fill in local variables (to handle "this")
context["parameters"] = fmllist3.fml3_list
context["localvars"] = md_decl_node.mdbody.vardecls.vardecl_list
# generate ir3 for a single method
mdbody3: MdBody3 = md_decl_node.mdbody.ir3(context)
# generate mangled method name, e.g %Functional_f(a, b)
mangled_mdname = IR3Node.mangle_method_name(context["classname"], md_name)
cmtd3 = CMtd3(md_ret_type, mangled_mdname, fmllist3, mdbody3)
cmtd3_list.append(cmtd3)
return Program3(cdata3_list, cmtd3_list)
class MainClass(AstNode):
def __init__(self, cname: 'Cname', mainmd: 'MdDecl'):
super().__init__(name=AST_MAINCLASS, children=[cname,mainmd])
@property
def cname(self) -> 'Cname':
return self.children[0]
@property
def mainmd(self) -> 'MdDecl':
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
# retrieve details for current class
cid = self.cname.class_name
field_decls, mtd_sigs = type_env.class_lookup(cid)
field_decls["this"] = JClass(cid)
# fill a local environment with main method (basically follow the appendix)
child_env = type_env.child_env()
child_env.augment_fields(field_decls)
child_env.augment_msigs(mtd_sigs)
# then type check the main method
self.mainmd.static_check(child_env, cid)
# cleanup
del field_decls["this"]
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class ClassDecls(AstNode):
def __init__(self, classdecls: List['ClassDecl']):
super().__init__(name=AST_CLASSDECLS, children=classdecls)
@property
def classdecls(self) -> List['ClassDecl']:
return self.children
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
for classdecl in self.classdecls:
classdecl.static_check(type_env, metadata)
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class ClassDecl(AstNode):
def __init__(self, cname: 'Cname', vardecls: 'VarDecls', mddecls: 'MdDecls'):
super().__init__(name=AST_CLASSDECL, children=[cname,vardecls,mddecls])
@property
def cname(self) -> 'Cname':
return self.children[0]
@property
def vardecls(self) -> 'VarDecls':
return self.children[1]
@property
def mddecls(self) -> 'MdDecls':
return self.children[2]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
# retrieve details for current class
cid = self.cname.class_name
field_decls, mtd_sigs = type_env.class_lookup(cid)
field_decls["this"] = JClass(cid)
# create a new local environment for child class (has block)
child_env = type_env.child_env()
child_env.augment_fields(field_decls)
child_env.augment_msigs(mtd_sigs)
# check all methods are OK in the current environment
self.mddecls.static_check(child_env, cid)
# cleanup
del field_decls["this"]
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class MdDecls(AstNode):
def __init__(self, mddecls: List['MdDecl']):
super().__init__(name=AST_MDDECLS, children=mddecls)
@property
def mddecl_list(self) -> List['MdDecl']:
return self.children
def static_check(self, type_env: 'TypeEnvironment'=None, cid=None):
for mddecl in self.mddecl_list:
mddecl.static_check(type_env, cid)
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class MdDecl(AstNode):
def __init__(self, type_node: 'AstType',
id_node: 'Id',
fmllist: 'FmlList',
mdbody: 'MdBody'):
super().__init__(name=AST_MDDECL, children=[type_node, id_node, fmllist, mdbody])
self._type_env = None
@property
def type_node(self) -> 'AstType':
return self.children[0]
@property
def id_node(self) -> 'Id':
return self.children[1]
@property
def fmllist(self) -> 'FmlList':
return self.children[2]
@property
def mdbody(self) -> 'MdBody':
return self.children[3]
def static_check(self, type_env: 'TypeEnvironment' = None, cid=None):
# augment a new env with params and return type of method
stuff = type_env.class_lookup(cid)
if not stuff:
raise TypeCheckError(f"unexpected cname '{cid}' in Mddecl")
msigs: Dict[str, MethodSignature] = stuff[1]
mid = self.id_node.id_name
params_list, ret_type = msigs[mid]
# add params and the special return type before checking MDecl
child_env = type_env.child_env()
child_env.augment_field("Ret", ret_type)
for param_name, param_type in params_list:
child_env.augment_field(param_name, param_type)
# add local variable declarations before checking method body
for vardecl_node in self.mdbody.vardecls.vardecl_list:
localvar_type: JLiteType = node_to_type(vardecl_node.type_node)
localvar_id = vardecl_node.id_node.id_name
child_env.augment_field(localvar_id, localvar_type)
# type-check the method body block
mdbody_type = self.mdbody.static_check(child_env, cid)
if mdbody_type != ret_type:
raise TypeCheckError(f"types {mdbody_type} and {ret_type} must match for class {cid} method {mid}")
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class FmlList(AstNode):
def __init__(self, fmls: List['Fml']):
super().__init__(name=AST_FMLLIST, children=fmls)
@property
def fmls(self) -> List['Fml']:
return self.children
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
pass
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class Fml(AstNode):
def __init__(self, type_node: 'AstType', id_node: AstNode):
super().__init__(name=AST_FML, children=[type_node, id_node])
@property
def type_node(self) -> 'AstType':
return self.children[0]
@property
def id_node(self) -> 'Id':
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
pass
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class MdBody(AstNode):
def __init__(self, vardecls: 'VarDecls', stmts: 'Stmts'):
super().__init__(name=AST_MDBODY, children=[vardecls,stmts])
self._type_env = None
@property
def vardecls(self) -> 'VarDecls':
return self.children[0]
@property
def stmts(self) -> 'Stmts':
return self.children[1]
@property
def type_env(self) -> 'TypeEnvironment':
return self._type_env
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
self._type_env = type_env
return self.stmts.static_check(type_env, metadata)
def ir3(self, context: Dict[str, Any]) -> 'MdBody3':
vardecl3_lst = []
stmt3s_lst = []
# load var decls
for var_decl_node in self.vardecls.vardecl_list:
var_id: str = var_decl_node.id_node.id_name
var_type: JLiteType = self.type_env.field_lookup(var_id)
vardecl3 = VarDecl3(var_type, var_id)
vardecl3_lst.append(vardecl3)
# load stmts (ir3 representation)
stmts_code, _ = self.stmts.ir3(context)
stmt3s_lst.extend(stmts_code)
# add return type declaration (if any)
if "return" in context:
type3, id3 = context["return"]
stmt3s_lst.insert(0, VarDecl3(type3, id3))
del context["return"]
return MdBody3(vardecl3_lst, stmt3s_lst)
class VarDecls(AstNode):
def __init__(self, vardecls: List['VarDecl']):
super().__init__(name=AST_VARDECLS, children=vardecls)
@property
def vardecl_list(self) -> List['VarDecl']:
return self.children
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
pass
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class VarDecl(AstNode):
def __init__(self, type_node: 'AstType', id_node: 'Id'):
super().__init__(name=AST_VARDECL, children=[type_node, id_node])
@property
def type_node(self) -> 'AstType':
return self.children[0]
@property
def id_node(self) -> 'Id':
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
pass
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class Stmts(AstNode):
def __init__(self, stmts: List[AstNode]):
super().__init__(name=AST_STMTS, children=stmts)
@property
def stmts(self) -> List['AstNode']:
return self.children
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JLiteType':
if len(self.stmts) == 0:
return JVoid()
# the type of a bunch of statements is the last statement
last_type = None
# children are atoms, etc..
for ast_node in self.stmts:
last_type = ast_node.static_check(type_env, metadata)
return last_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
code = []
for stmt in self.stmts:
tmp_code, _ = stmt.ir3(context)
code.extend(tmp_code)
return code, None
class IfStatement(AstNode):
def __init__(self, conditional: 'Exp', if_body: 'Stmts', else_body: 'Stmts'):
super().__init__(name=AST_IF_STATEMENT, children=[conditional,if_body,else_body])
@property
def conditional(self) -> 'Exp':
return self.children[0]
@property
def if_body(self) -> 'Stmts':
return self.children[1]
@property
def else_body(self) -> 'Stmts':
return self.children[2]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JLiteType':
# conditional should be bool type
cond_type = self.conditional.static_check(type_env, metadata)
if cond_type != JBool():
raise TypeCheckError(f"expected type {JBool} in 'if' conditional, got {cond_type}")
# if body and else body should match types
if_env = type_env.child_env()
if_type = self.if_body.static_check(if_env, metadata)
else_env = type_env.child_env()
else_type = self.else_body.static_check(else_env, metadata)
if if_type != else_type:
raise TypeCheckError(f"expected if body type {if_type} to match else body type {else_type}")
return if_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
if (B) S1 else S2
B.true = newlabel()
B.next = newlabel()
S.code = B.code ||
if (B.label) goto B.true ||
S2.code ||
gen('goto' B.next) ||
B.true ||
S1.code ||
B.next ||
"""
b_true = IR3Node.new_label()
b_next = IR3Node.new_label()
b_code, b_temp = self.conditional.ir3(context)
s1_code, _ = self.if_body.ir3(context) # anchor should be None
s2_code, _ = self.else_body.ir3(context) # anchor should be None
code = []
code.extend(b_code)
code.append(Stmt3IfGoto(b_temp, b_true))
code.extend(s2_code)
code.append(Stmt3GotoLabel(b_next))
code.append(Stmt3LabelSemicolon(b_true))
code.extend(s1_code)
code.append(Stmt3LabelSemicolon(b_next))
return code, None
class WhileStatement(AstNode):
def __init__(self, conditional: AstNode, while_body: AstNode):
super().__init__(name=AST_WHILE, children=[conditional,while_body])
@property
def conditional(self):
return self.children[0]
@property
def while_body(self):
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JLiteType':
# conditional should be bool type
cond_type = self.conditional.static_check(type_env, metadata)
if type(cond_type) != JBool:
raise TypeCheckError(f"expected type {JBool} in 'while' conditional, got {cond_type}")
# while body is final type
while_env = type_env.child_env()
while_type = self.while_body.static_check(while_env, metadata)
return while_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
while (B) { S1 }
B.temporary = new temporary()
B.next = new label()
B.true = new label()
B.begin:
B.code
if (B.temporary) goto B.true
goto B.next
B.true:
S1.code
goto B.begin
B.next:
"""
b_begin = IR3Node.new_label()
b_next = IR3Node.new_label()
b_true = IR3Node.new_label()
b_code, b_temp = self.conditional.ir3(context)
s1_code, _ = self.while_body.ir3(context) # anchor should be None
code = []
code.append(Stmt3LabelSemicolon(b_begin))
code.extend(b_code)
code.append(Stmt3IfGoto(b_temp, b_true))
code.append(Stmt3GotoLabel(b_next))
code.append(Stmt3LabelSemicolon(b_true))
code.extend(s1_code)
code.append(Stmt3GotoLabel(b_begin))
code.append(Stmt3LabelSemicolon(b_next))
return code, None
class Exp(AstNode):
def __init__(self, actual_exp: AstNode):
super().__init__(name=AST_EXP, children=[actual_exp])
@property
def actual_exp(self):
return self.children[0]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
return self.actual_exp.static_check(type_env, metadata)
def ir3(self, context: Dict[str, Any]) -> IR3Result:
# need use temporary if it exists, pass to BExp/AExp/SExp
return self.actual_exp.ir3(context)
class ExpList(AstNode):
def __init__(self, exps: List['Exp']):
super().__init__(name=AST_EXPLIST, children=exps)
@property
def exps(self) -> List['Exp']:
return self.children
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None):
# just make sure each expression is checked
for node in self.exps:
node.static_check(type_env, metadata)
def ir3(self, context: Dict[str, Any]):
raise NotImplementedError()
class Complement(AstNode):
def __init__(self, bgrd_atom_true_false: AstNode):
super().__init__(name=AST_NEGATE, children=[bgrd_atom_true_false])
@property
def bgrd_atom_true_false(self):
return self.children[0]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JBool':
child_type = self.bgrd_atom_true_false.static_check(type_env, metadata)
if type(child_type) != JBool:
raise TypeCheckError(f"expected type Bool in complement, got {child_type}")
return child_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
! B
b_temp = new temporary() // pass to B to use
B.code
! b_temp
"""
b_code, b_temp = self.bgrd_atom_true_false.ir3(context)
code = []
code.extend(b_code)
# if a temporary is given, assign it to the result of this operation
temporary = IR3Node.new_temporary()
exp3 = Exp3Uop(Uop3.complement(), Idc3(b_temp))
code.append(Stmt3Assignment(temporary, exp3, JBool()))
return code, temporary
class AndOp(AstNode):
def __init__(self, left: AstNode, right: AstNode):
super().__init__(name=AST_AND, children=[left, right])
@property
def left(self):
return self.children[0]
@property
def right(self):
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JBool':
left_type = self.left.static_check(type_env, metadata)
if type(left_type) != JBool:
raise TypeCheckError(f"expected type Bool in '&&' LHS, got {left_type}")
right_type = self.right.static_check(type_env, metadata)
if type(right_type) != JBool:
raise TypeCheckError(f"expected type Bool in '&&' RHS, got {right_type}")
return left_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
A && B
a_temp = new temp()
b_temp = new temp()
A.code // get a_temp
B.code // get b_temp
a_temp && b_temp
"""
a_code, a_temp = self.left.ir3(context)
b_code, b_temp = self.right.ir3(context)
code = []
code.extend(a_code)
code.extend(b_code)
temporary = IR3Node.new_temporary()
exp3 = Exp3Bop(Idc3(a_temp), Bop3.and_op(), Idc3(b_temp))
code.append(Stmt3Assignment(temporary, exp3, JBool()))
return code, temporary
class OrOp(AstNode):
def __init__(self, left: AstNode, right: AstNode):
super().__init__(name=AST_OR, children=[left,right])
@property
def left(self):
return self.children[0]
@property
def right(self):
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JBool':
left_type = self.left.static_check(type_env, metadata)
if type(left_type) != JBool:
raise TypeCheckError(f"expected type Bool in '||' LHS, got {left_type}")
right_type = self.right.static_check(type_env, metadata)
if type(right_type) != JBool:
raise TypeCheckError(f"expected type Bool in '||' RHS, got {right_type}")
return left_type
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
A || B
a_temp = new temp()
b_temp = new temp()
A.code // get a_temp
B.code // get b_temp
a_temp || b_temp
"""
a_code, a_temp = self.left.ir3(context)
b_code, b_temp = self.right.ir3(context)
code = []
code.extend(a_code)
code.extend(b_code)
temporary = IR3Node.new_temporary()
exp3 = Exp3Bop(Idc3(a_temp), Bop3.or_op(), Idc3(b_temp))
code.append(Stmt3Assignment(temporary, exp3, JBool()))
return code, temporary
class PlusOp(AstNode):
def __init__(self, left: AstNode, right: AstNode):
super().__init__(name=AST_PLUS, children=[left,right])
@property
def left(self):
return self.children[0]
@property
def right(self):
return self.children[1]
def static_check(self, type_env: 'TypeEnvironment' = None, metadata=None) -> 'JLiteType':
# left, right types should be Int (Arith) or both String (String)
left_type = self.left.static_check(type_env, metadata)
right_type = self.right.static_check(type_env, metadata)
if type(left_type) in (JNull, JString) and type(right_type) in (JNull, JString):
return JString()
if type(left_type) == JInt and type(right_type) == JInt:
return JInt()
raise TypeCheckError(f"expected lhs and rhs to be both Int or both String/Null in '+', got {left_type} and {right_type}")
def ir3(self, context: Dict[str, Any]) -> IR3Result:
"""
A + B