-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_generator.py
More file actions
993 lines (810 loc) · 36.4 KB
/
code_generator.py
File metadata and controls
993 lines (810 loc) · 36.4 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
from operator import le
from typing import List
from lark import Lark, ParseError, Tree
from lark.visitors import Interpreter
from decaf_enums import Constants, DecafTypes, LoopLabels, AccessModes
from globals import GlobalVariables
from mips_codes import MIPS, MIPSArray, MIPSDouble, MIPSStr, MIPSConditionalStmt, MIPSPrintStmt, MIPSSpecials, MIPSClass
from semantic_error import SemanticError
from symbol_table import Variable, SymbolTable, Type
from symbol_table_updaters import SymbolTableUpdater, SymbolTableParentUpdater, TypeVisitor
class CodeGenerator(Interpreter):
VARIABLE_NAME_COUNT = 0
@staticmethod
def add_continue_and_break_target_labels(continue_label: str, break_label: str):
GlobalVariables.CONTINUE_LOOP_STACK.append(continue_label)
GlobalVariables.BREAK_LOOP_STACK.append(break_label)
@staticmethod
def pop_continue_and_break_target_labels():
GlobalVariables.CONTINUE_LOOP_STACK.pop()
GlobalVariables.BREAK_LOOP_STACK.pop()
@staticmethod
def get_version() -> int:
CodeGenerator.change_var()
return CodeGenerator.VARIABLE_NAME_COUNT
@staticmethod
def decrease_stack_ptr_pos(stack_ptr: int) -> int:
return stack_ptr - 4
def conditional_do_statement(self, tree, con_stmt, bre_stmt, stmt_children_number):
CodeGenerator.add_continue_and_break_target_labels(
continue_label=con_stmt,
break_label=bre_stmt
)
statement_code = self.visit(tree.children[stmt_children_number])
CodeGenerator.pop_continue_and_break_target_labels()
return statement_code
def convert_int_shared(self, tree, target_type, convert_code):
expression_code = self.visit(tree.children[1])
expr_var = GlobalVariables.STACK.pop()
if expr_var.var_type.name != DecafTypes.int_type:
raise SemanticError(6)
output_code = expression_code
output_code += convert_code
GlobalVariables.STACK.append(
Variable(
var_type=tree.symbol_table.get_type(target_type)
)
)
return output_code
def int_to_bool(self, tree):
return self.convert_int_shared(
tree=tree,
target_type=DecafTypes.bool_type,
convert_code=MIPS.convert_int_to_bool
)
def int_to_double(self, tree):
return self.convert_int_shared(
tree=tree,
target_type=DecafTypes.double_type,
convert_code=MIPS.convert_int_to_double
)
def while_stmt(self, tree):
expression_code = self.visit(tree.children[1])
GlobalVariables.STACK.pop()
version = CodeGenerator.get_version()
statement_code = self.conditional_do_statement(
tree,
LoopLabels.while_start_label.format(version=version),
LoopLabels.while_end_label.format(version=version),
2
)
output_code = MIPSConditionalStmt.while_stmt.format(
expression_code=expression_code,
version=version,
while_statement=statement_code
)
return output_code
def continue_stmt(self, tree):
if not len(GlobalVariables.CONTINUE_LOOP_STACK):
raise SemanticError(5)
target_label = GlobalVariables.CONTINUE_LOOP_STACK[-1]
output_code = MIPSConditionalStmt.continue_stmt.format(
target_label=target_label
)
return output_code
def break_stmt(self, tree):
if not len(GlobalVariables.BREAK_LOOP_STACK):
raise SemanticError(3)
target_label = GlobalVariables.BREAK_LOOP_STACK[-1]
output_code = MIPSConditionalStmt.break_stmt.format(
target_label=target_label
)
return output_code
def for_shared_part(self, tree, expr_1, expr_2, expr_3, statement_num):
expression_code_1 = expr_1
expression_code_2 = expr_2
expression_code_3 = expr_3
version = CodeGenerator.get_version()
statement_code = self.conditional_do_statement(
tree=tree,
con_stmt=LoopLabels.for_continue_label.format(version=version),
bre_stmt=LoopLabels.for_break_label.format(version=version),
stmt_children_number=statement_num
)
if not statement_code:
statement_code = ''
output_code = MIPSConditionalStmt.for_stmt.format(
version=version,
expression_code_1=expression_code_1,
expression_code_2=expression_code_2,
expression_code_3=expression_code_3,
statement_code=statement_code
)
return output_code
def for_1(self, tree):
return self.for_shared_part(
tree,
expr_1='',
expr_2=self.visit(tree.children[3]),
expr_3='',
statement_num=6
)
def for_2(self, tree):
return self.for_shared_part(
tree,
expr_1=self.visit(tree.children[2]),
expr_2=self.visit(tree.children[4]),
expr_3='',
statement_num=7
)
def for_3(self, tree):
return self.for_shared_part(
tree,
expr_1='',
expr_2=self.visit(tree.children[3]),
expr_3=self.visit(tree.children[5]),
statement_num=7
)
def for_4(self, tree):
return self.for_shared_part(
tree,
expr_1=self.visit(tree.children[2]),
expr_2=self.visit(tree.children[4]),
expr_3=self.visit(tree.children[6]),
statement_num=8
)
def if_stmt(self, tree):
expression_code = self.visit(tree.children[1])
GlobalVariables.STACK.pop()
else_statement_code = ''
statement_code = self.visit(tree.children[2])
if len(tree.children) > 3:
else_statement_code = self.visit(tree.children[4])
if not else_statement_code:
else_statement_code = ''
if not statement_code:
statement_code = ''
output_code = MIPSConditionalStmt.if_stmt.format(
expression_code=expression_code,
version=CodeGenerator.get_version(),
else_statement_code=else_statement_code,
statement_code=statement_code
)
return output_code
def stmt_block(self, tree):
children_codes = self.visit_children(tree)
codes = []
for child_code in children_codes:
if child_code:
codes.append(child_code)
return '\n'.join(codes)
def declare_program(self, tree):
variables = [item for item in tree.children if item.data == 'variable']
functions = [item for item in tree.children if item.data == 'function_decl']
classes = [item for item in tree.children if item.data == 'class_decl']
result = "\n.text"
for item in [*variables, *functions, *classes]:
result += self.visit(item)
result += MIPS.main.format(GlobalVariables.CLASS_INIT, GlobalVariables.VAR_INIT)
result += MIPS.side_functions
segment_code = MIPS.data_segment
for index, item in enumerate(GlobalVariables.CONSTANTS):
segment_code += MIPS.constant_str.format(index, item)
segment_code += '\n'
for index, item in GlobalVariables.ARRAYS:
segment_code += MIPS.array_base.format(index, item)
segment_code += '\n'
result = segment_code + result
return result
@staticmethod
def are_types_invalid(var1: Variable, var2: Variable):
if var1.var_type.arr_type:
return not var1.var_type.is_same(var2.var_type)
return var1.var_type.name != var2.var_type.name
@classmethod
def are_boolean(cls, *variables: List[Variable]):
non_booleans = [i for i in variables if i.var_type.name != DecafTypes.bool_type]
return bool(len(non_booleans))
@classmethod
def change_var(cls):
cls.VARIABLE_NAME_COUNT += 1
def unary_neg(self, tree):
output_code = self.visit(tree.children[0])
var = GlobalVariables.STACK.pop()
if var.var_type.name == DecafTypes.int_type:
output_code += MIPS.unary_neg_int
elif var.var_type.name == DecafTypes.double_type:
output_code += MIPSDouble.unary_neg_double
else:
raise SemanticError(29)
GlobalVariables.STACK.append(var)
return output_code
def module(self, tree):
var1, var2, expr1, expr2, output_code = self.prepare_calculations(tree)
exclusive_var1 = var1 if var1.var_type.arr_type else var2
exclusive_var2 = var2 if var1.var_type.arr_type else var1
if not exclusive_var1.var_type.is_same(exclusive_var2.var_type):
raise SemanticError(23)
output_code += MIPS.module_int
var_type = tree.symbol_table.get_type('int')
GlobalVariables.STACK.append(Variable(var_type=var_type))
return output_code
# TODO: needs debug
# def class_declaration(self, tree):
# class_name = tree.children[1].value
# class_ = tree.symbol_table.get_type(class_name).class_ref
# GlobalVariables.STACK_CLASS.append(class_)
# code = ''
# functions_trees = []
# variables_trees = []
# for subtree in tree.children:
# if isinstance(subtree, Tree) and subtree.data == Constants.field:
# if subtree.children[1].data == Constants.function_decl:
# functions_trees.append(subtree)
# else:
# variables_trees.append(subtree)
# for subtree in variables_trees:
# code += self.visit(subtree)
# for subtree in functions_trees:
# code += self.visit(subtree)
# vtable_size = class_.get_vtable_size()
# class_init_codes = ''
# class_init_codes += MIPS.class_init.format(class_.name, vtable_size * 4, class_.address).replace("\t\t", "\t")
# current_class = class_
# parent_classes = []
# while current_class:
# parent_classes.append(current_class)
# current_class = current_class.parent
# all_functions = []
# for current_class in parent_classes[::-1]:
# for class_function in current_class.member_functions.values():
# for func in all_functions:
# if func.name == class_function.name:
# for i in range(len(func.formals) - 1):
# if func.formals[i + 1].type_.name != class_function.formals[i + 1].type_.name:
# raise SemanticError()
# elif func.formals[i + 1].type_.arr_type.are_equal(func.formals[i + 1].type_.arr_type):
# raise SemanticError()
# if func.return_type.name != class_function.return_type.name:
# raise SemanticError()
# all_functions.append(class_function)
# func_label = class_function.label
# _, index = current_class.get_func_and_index(class_function.name)
# class_init_codes += MIPS.store_class_functions.format(func_label, index * 4)
# all_values = []
# for current_class in parent_classes[::-1]:
# for value in current_class.member_data.values():
# for val in all_values:
# if val.name == value.name:
# raise SemanticError()
# all_values.append(value)
# GlobalVariables.STACK_CLASS.pop()
# return code
def assign(self, tree):
GlobalVariables.ASSIGN_FLAG = True
l_var, r_var, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(l_var, r_var):
raise SemanticError(2)
output_code += MIPS.assignment_int
GlobalVariables.STACK.append(l_var)
return output_code
def div(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2) and not CodeGenerator.is_var_int_or_double(var1):
raise SemanticError(7)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.div_int
elif var1.var_type.name == DecafTypes.double_type:
output_code += MIPSDouble.div
GlobalVariables.STACK.append(Variable(var_type=var1.var_type))
return output_code
def prepare_calculations(self, tree):
var1_expr = tree.children[0]
var2_expr = tree.children[1]
expr1_code = self.visit(var1_expr)
var1 = GlobalVariables.STACK.pop()
expr2_code = self.visit(var2_expr)
var2 = GlobalVariables.STACK.pop()
if isinstance(expr1_code, list):
expr1_code = expr1_code[0]
if isinstance(expr2_code, list):
expr2_code = expr2_code[0]
output_code = expr1_code
output_code += expr2_code
return var1, var2, expr1_code, expr2_code, output_code
@staticmethod
def is_var_int_or_double(var: Variable):
return var.var_type.name in (DecafTypes.double_type, DecafTypes.int_type)
def mul(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2) and not CodeGenerator.is_var_int_or_double(var1):
raise SemanticError(24)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.mul_int
elif var1.var_type.name == DecafTypes.double_type:
output_code += MIPSDouble.mul
GlobalVariables.STACK.append(Variable(var_type=var1.var_type))
return output_code
def sub(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2) and not CodeGenerator.is_var_int_or_double(var1):
raise SemanticError(28)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.sub_int
elif var1.var_type.name == DecafTypes.double_type:
output_code += MIPSDouble.sub
GlobalVariables.STACK.append(Variable(var_type=var1.var_type))
return output_code
def add(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2):
raise SemanticError(1)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.add_int
elif var1.var_type.name == DecafTypes.double_type:
output_code += MIPSDouble.add
elif var1.var_type.name == DecafTypes.str_type:
CodeGenerator.change_var()
output_code += MIPSStr.concat.format(version=CodeGenerator.VARIABLE_NAME_COUNT)
GlobalVariables.STACK.append(Variable(var_type=var1.var_type))
return output_code
def read_line(self, tree):
CodeGenerator.change_var()
output_code = MIPSStr.read_line.format(version=CodeGenerator.VARIABLE_NAME_COUNT)
GlobalVariables.STACK.append(
Variable(
var_type=tree.symbol_table.get_type(DecafTypes.str_type)
)
)
return output_code
def read_int(self, tree):
output_code = MIPS.read
var_type = tree.symbol_table.get_type(DecafTypes.int_type)
GlobalVariables.STACK.append(Variable(var_type=var_type))
return output_code
def constant(self, tree):
const_token_type = tree.children[0].type
output_code = ''
var_type = None
if const_token_type == Constants.bool_const:
value = 1
if tree.children[0].value == 'false':
value = 0
var_type = tree.symbol_table.get_type(DecafTypes.bool_type)
output_code += MIPS.bool_const.format(value=value)
elif const_token_type == Constants.int_const:
value = int(tree.children[0].value)
var_type = tree.symbol_table.get_type(DecafTypes.int_type)
output_code += MIPS.int_const.format(value=value)
elif const_token_type == Constants.double_const:
value = tree.children[0].value.lower()
var_type = tree.symbol_table.get_type(DecafTypes.double_type)
if value[-1] == '.':
value += '0'
if value[0] == '.':
value = '0' + value
if '.e' in value:
value.replace('.e', '.0e')
output_code = MIPS.double_const.format(value=value)
elif const_token_type == Constants.str_const:
value = tree.children[0].value[1:-1]
var_type = tree.symbol_table.get_type(DecafTypes.str_type)
val_size = len(value) + 1
label = CodeGenerator.get_version()
const_label = len(GlobalVariables.CONSTANTS)
GlobalVariables.CONSTANTS.append(value)
output_code = MIPS.str_const.format(
val_size,
const_label,
label,
label,
label,
label,
)
elif const_token_type == Constants.null_const:
var_type = tree.symbol_table.get_type(DecafTypes.null_type)
output_code += MIPS.null_const
GlobalVariables.STACK.append(Variable(var_type=var_type))
return output_code
def l_value_ident(self, tree):
var = tree.symbol_table.find_var(tree.children[0].value, tree=tree, error=True)
GlobalVariables.STACK.append(var)
output = MIPS.set_multiple_var(MIPS.l_value_assign_true, var.address,
2) if GlobalVariables.ASSIGN_FLAG else MIPS.l_value_assign_false.format(
var.address)
GlobalVariables.ASSIGN_FLAG = False
return output
def logical_or(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_boolean(var1, var2):
raise SemanticError(22)
output_code += MIPS.logical_or
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_and(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_boolean(var1, var2):
raise SemanticError(10)
output_code += MIPS.logical_and
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_not(self, tree):
expr1_code = self.visit(tree.children[0])
out_put = expr1_code
var = GlobalVariables.STACK.pop()
if var.var_type.name != DecafTypes.bool_type:
raise SemanticError(20)
out_put += MIPS.logical_not
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return out_put
def logical_equal(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
unknown_equal = bool((not (var1.var_type.name == 'null' and var2.var_type.name == 'null')) and \
(var1.var_type.name == var2.var_type.name or \
(var1.var_type.name == 'null' and var2.var_type.name not in ['double', 'int', 'bool',
'string',
'array']) or \
(var2.var_type.name == 'null' and var1.var_type.name not in ['double', 'int', 'bool',
'string',
'array'])))
if var1.var_type.name == DecafTypes.double_type:
version = CodeGenerator.get_version()
output_code += MIPS.logical_double_equal.format(
version=version
)
elif var1.var_type.name == DecafTypes.str_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_string_equal,
str(CodeGenerator.VARIABLE_NAME_COUNT),
10
)
elif unknown_equal:
output_code += MIPS.logical_unknown_equal
else:
raise SemanticError(11)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_not_equal(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
unknown_equal = bool(
(not (var1.var_type.name == 'null' and var2.var_type.name == 'null')) and \
(var1.var_type.name == var2.var_type.name or \
(var1.var_type.name == 'null' and var2.var_type.name not in ['double', 'int', 'bool',
'string',
'array']) or \
(var2.var_type.name == 'null' and var1.var_type.name not in ['double', 'int', 'bool',
'string',
'array'])))
if var1.var_type.name == DecafTypes.double_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_double_not_equal,
str(CodeGenerator.VARIABLE_NAME_COUNT),
2
)
elif var1.var_type.name == DecafTypes.str_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_sring_not_equal,
str(CodeGenerator.VARIABLE_NAME_COUNT),
10
)
elif unknown_equal:
output_code += MIPS.logical_unknown_not_equal
else:
raise SemanticError(21)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_less_than(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2):
raise SemanticError(16)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.logical_less_than_int
elif var1.var_type.name == DecafTypes.double_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_less_than_double,
str(CodeGenerator.VARIABLE_NAME_COUNT),
2
)
else:
raise SemanticError(17)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_less_than_or_equal(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2):
raise SemanticError(18)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.logical_less_than_or_equal_int
elif var1.var_type.name == DecafTypes.double_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_less_than_or_equal_double,
str(CodeGenerator.VARIABLE_NAME_COUNT),
2
)
else:
raise SemanticError(19)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_greater_than(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2):
raise SemanticError(12)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.logical_greater_than_int
elif var1.var_type.name == DecafTypes.double_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_greater_than_double,
str(CodeGenerator.VARIABLE_NAME_COUNT),
2
)
else:
raise SemanticError(13)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def logical_greater_than_or_equal(self, tree):
var1, var2, expr1_code, expr2_code, output_code = self.prepare_calculations(tree)
if CodeGenerator.are_types_invalid(var1, var2):
raise SemanticError(14)
if var1.var_type.name == DecafTypes.int_type:
output_code += MIPS.logical_greater_than_or_equal_int
elif var1.var_type.name == DecafTypes.double_type:
CodeGenerator.change_var()
output_code += MIPS.set_multiple_var(
MIPS.logical_greater_than_or_equal_double,
str(CodeGenerator.VARIABLE_NAME_COUNT),
2
)
else:
raise SemanticError(15)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.bool_type)))
return output_code
def call(self, tree):
function = tree.symbol_table.get_function(
tree.children[0].value
)
stack_size = len(GlobalVariables.STACK)
actuals = self.visit(tree.children[1])
args_num = len(GlobalVariables.STACK) - stack_size
if args_num != len(function.formals):
raise SemanticError(101)
formals_idx = args_num - 1
while len(GlobalVariables.STACK) > stack_size:
formal = function.formals[formals_idx]
arg = GlobalVariables.STACK.pop()
if arg.var_type.name != formal.var_type.name:
raise SemanticError(102)
formals_idx -= 1
function_label = function.name
if function_label == 'main':
function_label = 'func_main'
output_code = MIPSSpecials.method_call.format(
actuals=actuals,
func_name=function_label,
args_size=args_num * 4
)
if function.return_type:
output_code += MIPSSpecials.method_call_return
GlobalVariables.STACK.append(Variable(var_type=function.return_type))
return output_code
# TODO: needs debug
# def method_call(self, tree):
# expr_code_0 = self.visit(tree.children[0])
# variable = GlobalVariables.STACK.pop()
# class_obj = variable.var_type.class_obj
# function = tree.symbol_table.get_function(
# tree.children[1].value
# )
# if not class_obj:
# if variable.var_type.name == DecafTypes.array_type:
# if function == "length":
# output_code = self.visit(tree.children[0])
# GlobalVariables.STACK.pop()
# output_code += MIPSClass.l_var
# GlobalVariables.STACK.append(Variable(var_type=function.return_type))
# return output_code
# else:
# raise SemanticError()
# raise SemanticError()
# function, index = class_obj.get_function(function)
# current_cls = None
# if len(GlobalVariables.STACK_CLASS):
# current_cls = GlobalVariables.STACK_CLASS[-1]
# access = class_obj.get_access(function)
# can_not_access = bool(access == AccessModes.private and (not current_cls or (not class_obj.name == current_cls.name)) or\
# access == AccessModes.protected and (not current_cls or (not current_cls.can_upcast(class_obj))))
# if can_not_access:
# raise SemanticError()
# pre_stack_len = len(GlobalVariables.STACK)
# output_code = MIPSClass.method_call.format(expr_code_0)
# GlobalVariables.STACK.append(variable)
# output_code += self.visit(tree.children[2])
# arg_num = len(GlobalVariables.STACK) - pre_stack_len
# if arg_num != len(function.formals):
# raise SemanticError()
# validation_arg_num = arg_num - 1
# while len(GlobalVariables.STACK) > pre_stack_len:
# formal = function.formals[validation_arg_num]
# arg = GlobalVariables.STACK.pop()
# if not arg.var_type.same_or_can_upcast(formal.type_):
# raise SemanticError()
# validation_arg_num -= 1
# output_code += MIPSClass.load_func.format(
# 4 * (arg_num - 1),
# 4 * index,
# 4 * arg_num
# )
# if function.return_type:
# output_code += MIPSClass.return_type
# GlobalVariables.STACK.append(Variable(var_type=function.return_type))
# return output_code
def type(self, tree):
return tree.symbol_table.get_type(tree.children[0].value)
def function_decl(self, tree):
_, var_1, var_2, var_3 = tree.children[:4]
function_name = var_1.value
function = tree.symbol_table.get_function(function_name, tree=tree)
self.visit(var_2)
formal = ''
for index, val in enumerate(function.formals[::-1]):
formal += MIPS.function_formal.format(4 * (index + 1), val.address)
GlobalVariables.FUNCTION_STACK.append(function)
stmt_block = self.visit(var_3)
GlobalVariables.FUNCTION_STACK.pop()
func_label = function.name
if func_label == 'main':
func_label = 'func_main'
return MIPS.function.format(
func_label,
formal,
stmt_block,
func_label
)
def actuals(self, tree):
return '\n'.join(self.visit_children(tree))
def print_stmt(self, tree):
pre_stack_len = len(GlobalVariables.STACK)
output = self.visit(tree.children[1])
if len(GlobalVariables.STACK) == pre_stack_len:
return output
stack_ptr_pos = 4 * (len(GlobalVariables.STACK) - (1 + pre_stack_len))
for item in GlobalVariables.STACK[pre_stack_len:]:
var_type_name = item.var_type.name
if var_type_name == DecafTypes.int_type:
output += MIPSPrintStmt.int_stmt.format(stack_ptr_pos)
elif var_type_name == DecafTypes.double_type:
output += MIPSPrintStmt.double_stmt.format(stack_ptr_pos)
elif var_type_name == DecafTypes.bool_type:
output += MIPSPrintStmt.bool_stmt.format(stack_ptr_pos)
elif var_type_name == DecafTypes.str_type:
output += MIPSPrintStmt.string_stmt.format(stack_ptr_pos)
stack_ptr_pos = CodeGenerator.decrease_stack_ptr_pos(stack_ptr_pos)
GlobalVariables.STACK.pop()
output += MIPSPrintStmt.new_line_stmt.format(stack_ptr_pos)
return output
def return_stmt(self, tree):
if not len(GlobalVariables.FUNCTION_STACK):
raise SemanticError(26)
function = GlobalVariables.FUNCTION_STACK[-1]
variable = tree.symbol_table.get_type(DecafTypes.void_type)
output_code = ''
if len(tree.children) > 1:
output_code += self.visit(tree.children[1])
variable = GlobalVariables.STACK.pop()
output_code += MIPS.return_calc_expr
if variable.var_type.name != function.return_type.name:
raise SemanticError(27)
function_label = function.name
if function_label == 'main':
function_label = 'func_main'
output_code += MIPS.return_back_to_caller.format(
function_name=function_label
)
return output_code
def field(self, tree):
access_modifier = self.visit(tree.children[0])
# TODO @Arab: why do not use access modifier
return self.visit(tree.children[1])
def access_modifier(self, tree):
if tree.children:
return tree.children[0].value
return ''
def new_identifier(self, tree):
ident_name = tree.children[1].value
var_type = tree.symbol_table.get_type(ident_name)
class_ = var_type.class_ref
if not class_:
raise SemanticError(25)
object_size = class_.get_object_size() + 1
code = MIPS.new_identifier.Format(object_size * 4, class_.address).replace("\t\t", "\t")
GlobalVariables.STACK.append(Variable(var_type=var_type))
return code
def variable(self, tree):
output_code = ''
var_type = self.visit(tree.children[0])
var_name = tree.children[1].value
variable = tree.symbol_table.find_var(var_name, tree=tree)
output_code += MIPS.variable_init.format(variable.address)
GlobalVariables.VAR_INIT += output_code
return ''
def bool_to_int(self, tree):
main_code = self.visit(tree.children[1])
source_var = GlobalVariables.STACK.pop()
if source_var.var_type.name != DecafTypes.bool_type:
raise SemanticError(4)
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.int_type)))
return main_code
def new_array(self, tree):
expression = self.visit(tree.children[0])
GlobalVariables.STACK.pop()
arr_type = self.visit(tree.children[1])
var_type = Type(DecafTypes.array_type, arr_type=arr_type)
output_code = MIPSArray.new_array.format(
expression=expression
)
GlobalVariables.STACK.append(
Variable(
var_type=var_type
)
)
return output_code
def l_value_array(self, tree):
output_code = self.visit(tree.children[0])
var = GlobalVariables.STACK.pop()
output_code += self.visit(tree.children[1])
index = GlobalVariables.STACK.pop()
if not index.var_type.is_same(tree.symbol_table.get_type(DecafTypes.int_type)):
raise SemanticError(104)
if var.var_type.name != DecafTypes.array_type:
raise SemanticError(105)
assign_code = ''
if GlobalVariables.ASSIGN_FLAG:
assign_code = MIPSArray.array_assign
GlobalVariables.ASSIGN_FLAG = False
GlobalVariables.STACK.append(
Variable(
var_type=var.var_type
)
)
output_code += MIPSArray.new_array_var.format(
assign_code=assign_code
)
return output_code
def double_to_int(self, tree):
main_code = self.visit(tree.children[1])
source_var = GlobalVariables.STACK.pop()
if source_var.var_type.name != DecafTypes.double_type:
raise SemanticError(9)
CodeGenerator.VARIABLE_NAME_COUNT += 1
label = CodeGenerator.VARIABLE_NAME_COUNT
main_code += MIPS.convert_double_to_int.format(label, label, label, label, label, label).replace("\t\t\t", "")
GlobalVariables.STACK.append(Variable(var_type=tree.symbol_table.get_type(DecafTypes.int_type)))
return main_code
def array_type(self, tree):
array_type = self.visit(tree.children[0])
return Type(name=DecafTypes.array_type, arr_type=array_type)
def prepare_main_tree(tree):
SymbolTableParentUpdater().visit_topdown(tree)
tree.symbol_table = SymbolTable()
tree.symbol_table.add_type(Type(DecafTypes.int_type, 4))
tree.symbol_table.add_type(Type(DecafTypes.double_type, 4))
tree.symbol_table.add_type(Type(DecafTypes.bool_type, 4))
tree.symbol_table.add_type(Type(DecafTypes.void_type, 0))
tree.symbol_table.add_type(Type(DecafTypes.str_type, 4))
tree.symbol_table.add_type(Type(DecafTypes.array_type, 4))
SymbolTableUpdater().visit(tree)
TypeVisitor().visit(tree)
def generate(input_code):
parser = Lark.open('./grammar.lark', parser="lalr", propagate_positions=True)
try:
tree = parser.parse(input_code)
prepare_main_tree(tree)
mips_code = CodeGenerator().visit(tree)
except ParseError as e:
return e
except SemanticError as e:
mips_code = MIPS.semantic_error
print(e.token)
return mips_code
if __name__ == "__main__":
inputfile = 'example.d'
with open(inputfile, "r") as input_file:
code = input_file.read()
code = generate(code)
print("#### code ")
print(code)