-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtac.py
878 lines (667 loc) · 24 KB
/
tac.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
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
import abc
from collections import defaultdict
from symbol_table import SymbolInfo
from typing import Any, Dict, List, Optional, Tuple
from tabulate import tabulate
import syntree
from go_lexer import symtab, type_table
from utils import print_error, print_line_marker_nowhitespace
class Quad:
def __init__(self, dest, op1, op2, operator):
self.dest = dest
self.op1 = op1
self.op2 = op2
self.operator = operator
self.scope_id = symtab.cur_scope
def __str__(self):
return f"{self.dest} = {self.op1} {self.operator} {self.op2}"
def str_operation(self):
return f"{self.op1} {self.operator} {self.op2}"
class Assign(Quad):
"""An assignment operation (to a single value)"""
def __init__(self, dest, value, scope_id="1"):
self.scope_id = scope_id
super().__init__(dest, None, value, "=")
def __str__(self):
return f"{self.dest} = {self.op2}"
class Label(Quad):
def __init__(self, name: str, index: int):
self.name = name
self.index = index
super().__init__(name, None, None, "LABEL")
def __str__(self):
return f"LABEL {self.name}:"
class GoTo(Quad):
def __init__(self, label_name: str):
self.label_name = label_name
super().__init__(label_name, None, None, "goto")
def __str__(self):
return f"goto {self.label_name}"
class Call(Quad):
def __init__(self, label_name: str, res: Any):
self.label_name = label_name
self.res = res
super().__init__(res, None, label_name, "call")
def __str__(self):
return f"{self.dest} = call {self.op2}"
class ConditionalGoTo(Quad):
"""if operation goto label_name1 else goto label_name2"""
def __init__(
self, label_name1: str, operation: "TempVar", label_name2: Optional[str] = None
):
self.label_name1 = label_name1
self.label_name2 = label_name2
self.operation = operation
super().__init__(label_name1, operation, label_name2, "if")
def __str__(self):
if self.label_name2 is None:
return f"if {self.operation} goto {self.label_name1}"
else:
return (
f"if {self.operation} goto {self.label_name1}"
f" else goto {self.label_name2}"
)
class Single(Quad):
"""Quad to store a single value like a keyword"""
def __init__(self, value: Any):
super().__init__(None, None, None, value)
def __str__(self):
return self.operator
class Double(Quad):
"""Quad to store two values"""
def __init__(self, op, value, dest=None):
super().__init__(dest, None, value, op)
def __str__(self):
if self.dest is None:
return f"{self.operator} {self.op2}"
else:
return f"{self.dest} = {self.operator} {self.op2}"
class Operand(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def name(self):
pass
@abc.abstractmethod
def is_const(self):
pass
@property
@abc.abstractmethod
def value(self):
pass
@value.setter
@abc.abstractmethod
def value(self, value: Any):
pass
def __str__(self):
return self.name
class TempVar(Operand):
def __init__(self, id: int, value: Any = None, type_: Any = None):
self.__name = "t" + str(id)
self.symbol = symtab.add_if_not_exists(self.name)
self.symbol.const_flag = True if value is not None else False
self.symbol.value = value
self.symbol.type_ = type_
@property
def name(self):
return self.__name
@name.setter
def name(self, id: int):
self.__name = "t" + str(id)
def is_const(self):
return self.symbol.const_flag
@property
def value(self):
if self.is_const():
return self.symbol.value
else:
raise Exception(
self.name + " is not a constant and has no value attribute!"
)
@value.setter
def value(self, value: Any):
self.symbol.const_flag = True
self.symbol.value = value
@property
def type_(self):
return self.symbol.type_
@type_.setter
def type_(self, value: Any):
self.symbol.type_ = value
def __repr__(self):
return f"<Temp {self.name}>"
def __hash__(self):
return hash(self.symbol.name + self.symbol.scope_id)
def __eq__(self, other):
if isinstance(other, ActualVar):
if (
self.symbol.name == other.symbol.name
and self.symbol.scope_id == self.symbol.scope_id
):
return True
return False
return False
class ActualVar(Operand):
def __init__(self, symbol: Optional[SymbolInfo]):
self.__symbol = symbol
self.symbol.const_flag = self.symbol.const
@property
def symbol(self):
return self.__symbol
@property
def name(self):
return self.symbol.name
def is_const(self):
return self.symbol.const_flag
def deconstantize(self):
self.symbol.const_flag = False
@property
def value(self):
if self.is_const():
return self.symbol.value
else:
raise Exception(
self.name + " is not a constant and has no value attribute!"
)
@value.setter
def value(self, value: Any):
if self.symbol.const:
raise Exception(
self.name + " is a defined constant and its value cannot be changed!"
)
self.symbol.const_flag = True
self.symbol.value = value
@property
def type_(self):
return self.symbol.type_
@type_.setter
def type_(self, value: Any):
self.symbol.type_ = value
def __hash__(self):
return hash(self.symbol.name + self.symbol.scope_id)
def __eq__(self, other):
if isinstance(other, ActualVar):
if (
self.symbol.name == other.symbol.name
and self.symbol.scope_id == self.symbol.scope_id
):
return True
return False
return False
def __repr__(self):
return f"<ActualVar {self.name}>"
class IntermediateCode:
def __init__(self):
self.code_list: List[Quad] = []
self.temp_var_count = 0
self.label_prefix_counts: Dict[str, int] = defaultdict(lambda: 0)
self.label_map: Dict[str, Label] = {}
self.loop_stack: List[Tuple[str, str]] = []
# BUILT-IN functions (or labels)
self._add_label(self.get_fn_label("fmt__Println"))
self._add_label(self.get_fn_label("fmt__Printf"))
self._add_label(self.get_fn_label("fmt__Print"))
def get_new_temp_var(self, value: Any = None):
self.temp_var_count += 1
return TempVar(self.temp_var_count, value)
def add_to_list(self, code: Quad):
self.code_list.append(code)
# generating labels
@staticmethod
def get_fn_label(fn_name: str):
return f"FUNCTION_{fn_name}"
@staticmethod
def get_fn_end_label(fn_name: str):
return f"FUNCTION_END_{fn_name}"
def _add_label(self, label_name: str, label_index: int = -1) -> Label:
"""Private function for adding label without adding
to the code_list"""
label = Label(label_name, label_index)
self.label_map[label_name] = label
return label
def add_label(self, label_name: str) -> Label:
"""Add given label name. For named labels like functions, etc."""
if label_name in self.label_map:
raise Exception(f"Label {label_name} already exists")
label = self._add_label(label_name, len(self.code_list))
self.code_list.append(label)
return label
def get_new_increment_label(self, prefix="label") -> str:
"""Return a new label with an incremental number name.
Ex: label_1, label_2, etc.
Must be added using self.add_label later!
"""
self.label_prefix_counts[prefix] += 1
name = f"{prefix}_{self.label_prefix_counts[prefix]}"
return name
def get_label(self, label_name: str) -> Label:
return self.label_map[label_name]
def add_goto(self, label_name: str) -> GoTo:
if label_name not in self.label_map:
raise Exception(f"Label {label_name} does not exist, cannot goto to it")
goto_stmt = GoTo(label_name)
self.add_to_list(goto_stmt)
return goto_stmt
def add_call(self, label_name: str, res) -> Call:
if label_name not in self.label_map:
raise Exception(f"Label {label_name} does not exist, cannot goto to it")
call_stmt = Call(label_name, res)
self.add_to_list(call_stmt)
return call_stmt
def enter_new_loop(self, start_label: str, end_label: str):
self.loop_stack.append((start_label, end_label))
def exit_loop(self):
self.loop_stack.pop()
def is_inloop(self):
return len(self.loop_stack) > 0
def get_nearest_loop(self):
return self.loop_stack[-1]
def print_three_address_code(self):
for i in self.code_list:
print(i)
def __str__(self) -> str:
return str(
tabulate(
[
[i.dest, i.op1, i.operator, i.op2]
for i in self.code_list
],
headers=["Dest", "Operand 1", "Operator", "Operand 2"],
tablefmt="psql",
)
)
def tac_Assignment(
ic: IntermediateCode,
node: syntree.Assignment,
new_children: List[List[Any]],
return_val: List[Any],
):
left = new_children[0][0]
right = new_children[1][0]
if len(node.operator) == 2 and node.operator[1] == "=":
ic.add_to_list(Quad(left, left, right, node.operator[0]))
return_val.append(left)
elif node.operator == "=":
ic.add_to_list(Assign(left, right))
return_val.append(left)
return_val.append(node)
def tac_BinOp(
ic: IntermediateCode,
node: syntree.BinOp,
new_children: List[List[Any]],
return_val: List[Any],
):
temp = ic.get_new_temp_var()
temp.type_ = node.type_
# the children can be temporaries made in the _recur_codegen call above
# so they are stored in new_children which is used here
# each return value is a list, so the second [0] is needed
ic.add_to_list(Quad(temp, new_children[0][0], new_children[1][0], node.operator))
return_val.append(temp)
def tac_UnaryOp(
ic: IntermediateCode,
node: syntree.UnaryOp,
new_children: List[List[Any]],
return_val: List[Any],
):
if node.operator == "++" or node.operator == "--":
print("found incdec")
ic.add_to_list(
Quad(new_children[0][0], new_children[0][0], 1, node.operator[0])
)
return_val.append(new_children[0][0])
else:
temp = ic.get_new_temp_var()
temp.type_ = node.type_
ic.add_to_list(Double(node.operator, new_children[0][0], temp))
return_val.append(temp)
def tac_Literal(
ic: IntermediateCode,
node: syntree.Literal,
new_children: List[List[Any]],
return_val: List[Any],
):
# temp = ic.get_new_temp_var(node.value)
# TODO: how to handle type here?
# ic.add_to_list(Assign(temp, node.value))
# ic.add_to_list(node.value)
if not isinstance(node.value, syntree.Node):
return_val.append(node)
else:
if len(new_children) > 1:
if isinstance(new_children[0][0], syntree.Array):
arr = "{" + ", ".join(map(lambda x: str(x[0]), new_children[1])) + "}"
return_val.append(arr)
else:
return_val.append(new_children[1][0])
else:
return_val.append(new_children[0][0])
def tac_Keyword(
ic: IntermediateCode,
node: syntree.Keyword,
new_children: List[List[Any]],
return_val: List[Any],
):
if node.kw == "RETURN":
if len(new_children) > 0 and len(new_children[0]) > 0:
ic.add_to_list(Double("return", new_children[0][0]))
else:
ic.add_to_list(Single("return"))
elif node.kw == "BREAK" or node.kw == "CONTINUE":
if not ic.is_inloop():
print_error("Invalid keyword usage")
print(f"Keyword {node.kw} not allowed outside a loop")
print_line_marker_nowhitespace(node.lineno)
else:
print(f"Keyword {node.kw} not implemented yet!")
return_val.append(node)
def tac_PrimaryExpr(
ic: IntermediateCode,
node: syntree.PrimaryExpr,
new_children: List[List[Any]],
return_val: List[Any],
):
if isinstance(node.data, tuple) and node.data[0] == "identifier":
# a simple identifier
if not node.children:
if node.ident is None:
print(f"Skipping undeclared identifier {node.data[1]}")
else:
return_val.append(ActualVar(node.ident))
# not so simple identifier
elif len(node.children) == 1 and isinstance(node.children[0], syntree.Index):
arr_name = node.data[1]
index: syntree.Index = node.children[0]
ident: Optional[SymbolInfo] = node.ident
base_addr_t = ic.get_new_temp_var()
base_addr_t.type_ = "int"
ic.add_to_list(Assign(base_addr_t, f"base({arr_name})"))
# return_val.append(base_addr_t)
if ident is not None:
ind = new_children[0][0][0]
width = syntree.Literal(
"int", type_table.get_type(ident.type_.eltype).storage
)
offset_t = ic.get_new_temp_var()
offset_t.type_ = "int"
ic.add_to_list(Quad(offset_t, ind, width, "*"))
index_t = ic.get_new_temp_var()
index_t.type_ = "int"
ic.add_to_list(Quad(index_t, base_addr_t, offset_t, "+"))
res_t = ic.get_new_temp_var()
res_t.type_ = ident.type_.eltype
ic.add_to_list(Quad(res_t, arr_name, index_t, "[]"))
return_val.append(res_t)
else:
print("uhhh could not get type")
return_val.append(node)
else:
return_val.append(node)
elif (
node.data is None
and len(new_children) == 2
and isinstance(new_children[1][0], syntree.Index)
):
# TODO: do array/slice indexing here
arr_name_, index_ = new_children
arr_name = arr_name_[0]
index: syntree.Index = index_[0]
ident: Optional[SymbolInfo] = node.ident
# temp1 = ic.get_new_temp_var()
base_addr_t = ic.get_new_temp_var()
base_addr_t.type_ = "int"
ic.add_to_list(Assign(base_addr_t, f"base({arr_name})"))
return_val.append(base_addr_t)
if ident is not None:
print(ident.type_)
else:
print("This should not be None, something is wrong", index, arr_name)
# TODO: implement other variants of PrimaryExpr
else:
return_val.append(node)
def tac_Index(
ic: IntermediateCode,
node: syntree.Index,
new_children: List[List[Any]],
return_val: List[Any],
):
return_val.append(new_children[0])
def tac_pre_VarDecl(ic: IntermediateCode, node: syntree.VarDecl):
if len(node.children) > 1 and isinstance(node.children[1], syntree.BinOp):
op = node.children[1]
if isinstance(op.left, syntree.Literal):
if isinstance(op.right, syntree.Literal):
ic.add_to_list(
Quad(ActualVar(node.symbol), op.left, op.right, op.operator)
)
node.children.remove(op)
elif isinstance(op.children[1], syntree.PrimaryExpr):
right = _recur_codegen(op.children[1], ic)[0]
ic.add_to_list(
Quad(ActualVar(node.symbol), op.left, right, op.operator)
)
node.children.remove(op)
elif isinstance(op.children[0], syntree.PrimaryExpr):
left = _recur_codegen(op.children[0], ic)[0]
if isinstance(op.right, syntree.Literal):
ic.add_to_list(
Quad(ActualVar(node.symbol), left, op.right, op.operator)
)
node.children.remove(op)
elif isinstance(op.children[1], syntree.PrimaryExpr):
right = _recur_codegen(op.children[1], ic)[0]
ic.add_to_list(Quad(ActualVar(node.symbol), left, right, op.operator))
node.children.remove(op)
def tac_VarDecl(
ic: IntermediateCode,
node: syntree.VarDecl,
new_children: List[List[Any]],
return_val: List[Any],
):
if len(new_children) > 1:
if len(new_children[1]) > 0:
ic.add_to_list(Assign(ActualVar(node.symbol), new_children[1][0]))
return_val.append(node.ident.ident_name)
def tac_List(
ic: IntermediateCode,
node: syntree.List,
new_children: List[List[Any]],
return_val: List[Any],
):
return_val.extend(new_children)
def tac_pre_Function(ic: IntermediateCode, node: syntree.Function):
symtab.enter_scope()
symtab.enter_scope()
fn_name = syntree.FunctionCall.get_fn_name(node.fn_name)
fn_label = ic.get_fn_label(fn_name)
ic.add_label(fn_label)
def tac_Function(
ic: IntermediateCode,
node: syntree.Function,
new_children: List[List[Any]],
return_val: List[Any],
):
fn_name = syntree.FunctionCall.get_fn_name(node.fn_name)
fn_label = ic.get_fn_end_label(fn_name)
ic.add_label(fn_label)
symtab.leave_scope()
symtab.leave_scope()
def tac_Arguments(
ic: IntermediateCode,
node: syntree.Arguments,
new_children: List[List[Any]],
return_val: List[Any],
):
for child in new_children:
if isinstance(child, list):
for subchild in child:
if isinstance(subchild, list):
for subsubchild in subchild:
ic.add_to_list(Double("push", subsubchild))
return_val.append(subsubchild)
else:
ic.add_to_list(Double("push", subchild))
return_val.append(subchild)
else:
ic.add_to_list(Double("push", child[0]))
return_val.append(child[0])
def tac_FunctionCall(
ic: IntermediateCode,
node: syntree.FunctionCall,
new_children: List[List[Any]],
return_val: List[Any],
):
label = ic.get_fn_label(node.get_fn_name(node.fn_name))
temp = ic.get_new_temp_var()
temp.type_ = node.type_
ic.add_call(label, temp)
return_val.append(temp)
def tac_pre_IfStmt(
ic: IntermediateCode,
node: syntree.IfStmt,
):
symtab.enter_scope()
# there can be a statement to be executed just before
# the condition. specified as "if a := 10; a > 5 {...}"
# we process the statement before anything else and remove
# it from the children
before_statement = node.statement
if before_statement is not None:
_recur_codegen(before_statement, ic)
node.children.remove(before_statement)
# we'll process the condition here
# so we are removing it from the children
condition = node.expr
node.children.remove(condition)
condition_res = _recur_codegen(condition, ic)[0]
symtab.enter_scope()
# now add the actual if statement
true_label = ic.get_new_increment_label("if_true")
false_label = ic.get_new_increment_label("if_false")
g1 = ConditionalGoTo(true_label, condition_res, false_label)
ic.add_to_list(g1)
ic.add_label(true_label)
# now the body (after true label)
body = node.body
node.children.remove(body)
_recur_codegen(body, ic)
# false label after body
ic.add_label(false_label)
symtab.leave_scope()
# else part
next_ = node.next_
if next_ is not None:
symtab.enter_scope()
node.children.remove(next_)
_recur_codegen(next_, ic)
symtab.leave_scope()
symtab.leave_scope()
def tac_IfStmt(
ic: IntermediateCode,
node: syntree.IfStmt,
new_children: List[List[Any]],
return_val: List[Any],
):
pass
def tac_pre_ForStmt(ic: IntermediateCode, node: syntree.ForStmt):
symtab.enter_scope()
if hasattr(node.clause, "type_") and getattr(node.clause, "type_") == "bool":
# start of loop
start_label = ic.get_new_increment_label("for_simple_start")
ic.add_label(start_label)
# the condition
condition = node.clause
node.children.remove(condition)
condition_res = _recur_codegen(condition, ic)[0]
true_label = ic.get_new_increment_label("for_simple_true")
end_label = ic.get_new_increment_label("for_simple_end")
symtab.enter_scope()
# actual if else
g1 = ConditionalGoTo(true_label, condition_res, end_label)
ic.add_to_list(g1)
ic.add_label(true_label)
ic.enter_new_loop(start_label, end_label)
# now the body (after true label)
body = node.body
if body is not None:
node.children.remove(body)
_recur_codegen(body, ic)
# loop back to start label
ic.add_goto(start_label)
# end label after body
ic.add_label(end_label)
ic.exit_loop()
elif isinstance(node.clause, syntree.ForClause):
clause = node.clause
# init statement (first part of for)
if clause.init is not None:
_recur_codegen(clause.init, ic)
clause.children.remove(clause.init)
# start of loop (just before condition)
start_label = ic.get_new_increment_label("for_cmpd_start")
ic.add_label(start_label)
# the condition
condition = clause.cond
clause.children.remove(condition)
condition_res = _recur_codegen(condition, ic)[0]
true_label = ic.get_new_increment_label("for_cmpd_true")
end_label = ic.get_new_increment_label("for_cmpd_end")
symtab.enter_scope()
# actual if else
g1 = ConditionalGoTo(true_label, condition_res, end_label)
ic.add_to_list(g1)
ic.add_label(true_label)
ic.enter_new_loop(start_label, end_label)
# now the body (after true label)
body = node.body
if body is not None:
node.children.remove(body)
_recur_codegen(body, ic)
# the post statement (increment/decrement)
if clause.post is not None:
_recur_codegen(clause.post, ic)
clause.children.remove(clause.post)
# loop back to start label
ic.add_goto(start_label)
# end label after body
ic.add_label(end_label)
ic.exit_loop()
else:
print("Could not determine clause type")
symtab.leave_scope()
def tac_ForStmt(
ic: IntermediateCode,
node: syntree.ForStmt,
new_children: List[List[Any]],
return_val: List[Any],
):
symtab.leave_scope()
ignored_nodes = {"Identifier", "Type", "Array"}
def _recur_codegen(node: syntree.Node, ic: IntermediateCode):
# process all child nodes before parent
# ast is from right to left, so need to traverse in reverse order
node_class_name = node.__class__.__name__
# call TAC functions before processing children
# these have the prefix tac_pre_
tac_pre_fn_name = f"tac_pre_{node_class_name}"
if tac_pre_fn_name in globals():
globals()[tac_pre_fn_name](ic, node)
# recurse over children
new_children = []
for child in reversed(node.children):
new_children.append(_recur_codegen(child, ic))
new_children.reverse()
return_val = []
# call appropriate TAC functions after processing children
# at this point, the children are already in the IC
tac_fn_name = f"tac_{node_class_name}"
if tac_fn_name in globals():
globals()[tac_fn_name](ic, node, new_children, return_val)
elif node_class_name in ignored_nodes:
return_val.append(node)
else:
return_val.append(node)
return return_val
def intermediate_codegen(ast: syntree.Node) -> IntermediateCode:
ic = IntermediateCode()
_recur_codegen(ast, ic)
return ic