-
Notifications
You must be signed in to change notification settings - Fork 0
/
EELC.py
3092 lines (2083 loc) · 81.3 KB
/
EELC.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
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
#!/usr/bin/python2
# + ------------------------- + #
# Deligiannis Nikos 2681 #
# UoI - Spring Semester 2018 #
# CSE Department #
# Compilers MYY802 prof G.Manis #
# Project: Compiler for EEL #
# + ------------------------- + #
import sys
import signal
import os
# Just in case someone is curious!
def handler(signum, frame):
print ("\n")
print (Colors.HIGHL + "Compilation shall not be stopped" + Colors.RESET)
print ("\n")
# [PHASE: 1] :: Lexical and Syntactical Analysis Due 14/3/2018
# [PHASE: 2] :: Intermediate Code Generation Due 18/4/2018
# [PHASE: 3] :: Symbol Table & Final Code (.asm) Due 23/5/2018
#Classes
class Colors:
RED = "\033[1;31m"
REDD = "\033[31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
YELLOW = "\033[93m"
ORANGE = "\033[33m"
PURPLE = "\033[95m"
BOLD = "\033[;1m"
RESET = "\033[0;0m"
HIGHL = "\033[;7m"
class Quad:
def __init__(self, label, op, arg_1, arg_2, res):
self.label = label
self.op = op
self.arg_1 = arg_1
self.arg_2 = arg_2
self.res = res
def __str__(self):
return "(" + str(self.label) + ": " + str(self.op) + ", " + str(self.arg_1) + ", " \
+ str(self.arg_2) + ", " + str(self.res) + ")"
class Entity(object):
def __init__(self, entity_name, entity_type):
self.name = entity_name
self.type = entity_type
def __str__(self):
return "|--" + Colors.GREEN + "[" + str(self.type) + "]: " + '"' + str(self.name) + '"'
class Variable(Entity):
def __init__(self, variable_name):
super(Variable,self).__init__(variable_name,"VAR")
self.offset = 0
def set_offset(self,offset):
self.offset = offset
def __str__(self):
return super(Variable,self).__str__() + ":: offset: " + str(self.offset) + Colors.RESET
class Function(Entity):
def __init__(self, fp, name):
super(Function,self).__init__(name, "FUN")
if fp == 1 : #Procedure
self.ftype = "procedure"
elif fp == 2 : #Function
self.ftype = "function"
self.first_quad = None
self.frame_len = None
self.arg_list = list()
def set_first_quad(self,quad_label):
self.first_quad = quad_label
def set_frame_len(self,frame_len):
self.frame_len = frame_len
def append_arg(self,Arguement):
self.arg_list.append(Arguement)
def __str__(self):
args = ""
for arg in self.arg_list:
args = args + str(arg) + ", "
return super(Function,self).__str__() + ":: type: " + str(self.ftype) + ", first_quad: " + str(self.first_quad) + ", frame_len: " + str(self.frame_len) + Colors.RESET + Colors.CYAN + " --|> args: " + str(args) + Colors.RESET
class Parameter(Entity):
def __init__(self,parameter_name,parameter_mode):
super(Parameter,self).__init__(parameter_name,"PAR")
self.mode = parameter_mode
self.offset = None
def set_offset(self,offset):
self.offset = offset
def __str__(self):
return super(Parameter,self).__str__() + ":: mode: " + str(self.mode) + ", offset: " + str(self.offset) + Colors.RESET
class TempVar(Entity):
def __init__(self, tmpvar_name):
super(TempVar,self).__init__(tmpvar_name,"TMP")
self.offset = 0
def set_offset(self,offset):
self.offset = offset
def __str__(self):
return super(TempVar,self).__str__() + ":: offset: " + str(self.offset) + Colors.RESET
class Arguement():
def __init__(self, mode):
self.mode = mode
self.next = None
def set_next(self, Arguement):
self.next = Arguement
def __str__(self):
return str(self.mode)
class Scope():
def __init__(self):
self.nesting_level = None
self.outter_scope = None
self.entity_list = list()
self.offset = 12
def set_nesting_level(self, nesting_level):
self.nesting_level = nesting_level
def set_outter_scope(self, scope):
self.outter_scope = scope
def next_offset(self):
ret_offset = self.offset
self.offset = self.offset + 4 # Set offset ready for the next entity
return ret_offset
def append_entity(self, Entity):
self.entity_list.append(Entity)
def __str__(self):
return Colors.RESET + "*" + Colors.RED + "Scope " + str(self.nesting_level) + Colors.RESET + "*"
# + ------------------------------------ + #
# #
# Global Variables Declaration #
# #
# + ------------------------------------ + #
token_dict = dict(alphaTK = 1, # Alpharithmetic - String (e.g Compilers)
numberTK = 2, # Any Number (e.g 802)
plusTK = 3, # +
minusTK = 4, # -
mulTK = 5, # *
divTK = 6, # /
lessTK = 7, # <
greaTK = 8, # >
leqTK = 9, # <=
greqTK = 10, # >=
eqTK = 11, # =
difTK = 12, # <>
assigTK = 13, # :=
semiTK = 14, # ;
commaTK = 15, # ,
colonTK = 16, # :
lbrTK = 17, # (
rbrTK = 18, # )
blbrTK = 19, # [
brbrTK = 20, # ]
#Commited Words#
progTK = 100, # program
eprogTK = 101, # endprogram
decTK = 102, # declare
edecTK = 103, # enddeclare
ifTK = 104, # if
thenTK = 105, # then
elseTK = 106, # else
eifTK = 107, # endif
whileTK = 108, # while
ewhileTK = 109, # endwhile
repTK = 110, # repeat
erepTK = 111, # endrepeat
exitTK = 112, # exit
swiTK = 113, # switch
caseTK = 114, # case
eswiTK = 115, # endswitch
fcaseTK = 116, # forcase
whenTK = 117, # when
efcaseTK = 118, # endforcase
procTK = 119, # procedure
eprocTK = 120, # endprocedure
funTK = 121, # function
efunTK = 122, # endfunction
callTK = 123, # call
retTK = 124, # return
inTK = 124, # in
inoutTK = 125, # inout
andTK = 126, # and
orTK = 127, # or
notTK = 128, # not
trueTK = 129, # true
falseTK = 130, # false
inputTK = 131, # input
printTK = 132, # print
#Special Tokens#
eofTK = 200, # End of File
errTK = 201, # Error || Won't be used
cmtTK = 202) # Comment(s) || Won't be used
#Equivalance of ops and relops in MIPS assembly (used in final code generation)
ops = {
'+' : 'add',
'-' : 'sub',
'*' : 'mul',
'/' : 'div'
}
relops = {
'>' : 'bgt',
'<' : 'blt',
'>=': 'bge',
'<=': 'ble',
'=' : 'beq',
'<>': 'bne'
}
max_word_size = 30 # An Alpharithmetic can't be over 30 char's long
line = 1 # The current line (used for debugging messages)
ret_token = 0 # The token lex() will return
lex_unit = "" # The lexical unit lex() will return
label_cc = 0 # The counter for the label generation/showcase
tmp_cc = 0 # The counter for the tmp unique var generation
code_quads = list() # The list of the program stored in quads
program_name ="" # The name of the main program
to_ansi_c_problem = 0 # Used to display Error messages during Int ansi c generation
eel_source_code ="" # The source code filename
global code # File pointer of the Source Code
global asm_code # File pointer of the Final Assembly Code
main_first_quad = None # The first quad of the main function
main_frame_len = None # The total space required (in Bytes) for main function
scopes = list() # The global list of scopes
function_flag = False # To tell the difference between Procedure and Function
fp_reg_offset = 0 # Used to pass arguements in a function/procedure
check_for_exit = list()# List for checking if an exit is found outside a repeat statement
check_exit_cc = 0 # A counter which acompanies check_for_exit list.
newline_helper = 0 # A counter used only to help in generate_assembly for newline printing.
# + ------------------------------------ + #
# #
# Intermediate Code Related Funcs #
# #
# + ------------------------------------ + #
# Shows (does not alter) the next label value (string format)
def next_quad():
global label_cc
return str(label_cc)
# Generates a new Quad and increases the label_cc value by 1
def gen_quad(op, x, y, res):
global label_cc
global code_quads
tmp_label = label_cc
label_cc = label_cc + 1
ret_quad = Quad(str(tmp_label), str(op), str(x), str(y), str(res))
code_quads.append(ret_quad)
return ret_quad
# Generates a new unique temp variable that will be used for the intermediate code generation
def new_temp():
global tmp_cc
ret_tmp = "T_"+str(tmp_cc)
tmp_cc = tmp_cc + 1
new_tmp = TempVar(ret_tmp)
new_tmp.set_offset(scopes[-1].next_offset())
scopes[-1].append_entity(new_tmp)
return ret_tmp
# Returns an empty list
def empty_list():
return list()
# Generates and returns a list with one item in it
def make_list(item):
ret_list = list()
ret_list.append(item)
return ret_list
# Merges the two lists
def merge_list(list_a, list_b):
if list_a and list_b :
ret_list = list_a + list_b
return ret_list
elif list_a and not list_b:
ret_list = list_a
return list_a
elif list_b and not list_a:
ret_list = list_b
return list_b
# For every quad in quadlist alters the .res field into res
def back_patch(quadlist, res):
global code_quads
if quadlist:
for quad in code_quads:
if quad.label in quadlist:
quad.res = res
# + ------------------------------------ + #
# #
# Symbol Table Related Funcs #
# #
# + ------------------------------------ + #
#Prints the symbol table (created as far) [This was used to evaluate the results and for debugging]
"""def print_scopes():
out_string = ""
for scope in scopes:
out_string = out_string + str(scope)
padding_multiplier = scope.nesting_level + 1
if padding_multiplier == None: padding_multiplier = 0
for entity in scope.entity_list:
out_string = out_string + "\n" + " " * padding_multiplier + str(entity) + "\n" + "\t" * padding_multiplier + "|"
out_string = out_string + "\n" + "\t" * padding_multiplier
print(out_string)"""
#Checks if an entity allready exists in current scope
def duplicate_entity(entity_name,entity_type,nesting_level):
for entity in scopes[nesting_level].entity_list:
if not entity: return False
if entity.name == entity_name and entity.type == entity_type: return True
return False
#Used in case of finding a variable which was previously recorded as parameter in given nesting level
def redefinition_of_parameter(entity_name, nesting_level):
for entity in scopes[nesting_level].entity_list:
if entity.name == entity_name and entity.type == "PAR": return True
return False
#Search for an Entity(name,type)
def search_entity(entity_name,entity_type):
if not scopes: return False
counter = scopes[-1]
while counter != None:
for entity in counter.entity_list:
if entity.name == entity_name and entity.type == entity_type: return entity, counter.nesting_level
counter = counter.outter_scope
return True
#Adds new scope in scopes list
def add_new_scope():
new_scope = Scope()
new_scope.set_outter_scope(scopes[-1])
new_scope.set_nesting_level(scopes[-1].nesting_level+1)
scopes.append(new_scope)
#Adds a new variable in current scope
def add_new_variable(variable_name):
global line
if duplicate_entity(variable_name,"VAR", scopes[-1].nesting_level):
error = 'Duplicate VARIABLE "' + parameter_name +'" found'
error_display(5,error,line)
exit()
if redefinition_of_parameter(variable_name,scopes[-1].nesting_level):
error = 'VARIABLE "' + variable_name + '" used also as PARAMETER in the same scope'
error_display(5,error,line)
exit()
new_variable = Variable(variable_name)
new_variable.set_offset(scopes[-1].next_offset())
scopes[-1].entity_list.append(new_variable)
def add_new_parameter(parameter_name,parameter_mode):
global line
if duplicate_entity(parameter_name,"PAR",scopes[-1].nesting_level):
error = 'Duplicate PARAMETER "' + parameter_name + '" found'
error_display(5,error,line)
exit()
new_parameter = Parameter(parameter_name,parameter_mode)
new_parameter.set_offset(scopes[-1].next_offset())
scopes[-1].entity_list.append(new_parameter)
def add_new_function(f_or_p, name):
global line
if duplicate_entity(name,"FUN",scopes[-1].nesting_level-1): #Duplicates found on parents Scope.
if f_or_p == 1: error = 'Duplicate PROCEDURE "' + name + '" found'
elif f_or_p == 2: error = 'Duplicate FUNCTION "' + name + '" found'
error_display(5,error,line)
exit()
new_function = Function(f_or_p,name)
if len(scopes) == 1: scopes[-1].append_entity(new_function)
else : scopes[-2].append_entity(new_function) #Gets added to the outter scope's entity list
def update_fp_frame_length(name, frame_len):
f_or_p = search_entity(name, "FUN")
f_or_p[0].set_frame_len(frame_len)
def update_fp_first_quad(name, first_quad_label):
f_or_p = search_entity(name,"FUN")
f_or_p[0].set_first_quad(first_quad_label)
def add_new_arguement_fp(fpname, mode):
global line
if mode == "in" : new_arguement = Arguement("in")
elif mode == "inout": new_arguement = Arguement("inout")
f_or_p = search_entity(fpname,"FUN")
if not f_or_p[0]:
error = 'FUN Entity "' + fpname + '" not found to append an ARGUEMENT"'
error_display(5,error,line)
exit()
if f_or_p[0].arg_list != list():
f_or_p[0].arg_list[-1].set_next(new_arguement)
f_or_p[0].append_arg(new_arguement)
# + ------------------------------------ + #
# #
# Final Code Related Funcs #
# #
# + ------------------------------------ + #
#Searches in symbol table for a variable only by name
def search_for_variable(variable_name):
if not scopes: return False
counter = scopes[-1]
while counter != None:
for entity in counter.entity_list:
if entity.name == variable_name: return entity, counter.nesting_level
counter = counter.outter_scope
return True
#Finds the non_local_var entity and adds its adress to $t0 register
def gnlvcode(non_local_var):
global asm_code
find_entity = search_for_variable(non_local_var)
if find_entity == False:
error = 'Variable "' + non_local_var + '" not found due to empty scopes list.'
error_display(6,error,line)
exit()
elif find_entity == True:
error = 'Variable "' + non_local_var + '" not declared.'
error_display(6,error,line)
exit()
elif find_entity[0].type == "FUN":
error = 'Variable "' + non_local_var + '" not declared. Also, found a Function/Procedure with the same name.'
error_display(6,error,line)
exit()
my_level = scopes[-1].nesting_level
asm_code.write("\tlw $t0, -4($sp)\n")
scope_difference = my_level - find_entity[1] - 1 # Skip parrent's Stack
for i in range(scope_difference):
asm_code.write("\tlw $t0, -4($t0)\n")
asm_code.write("\taddi $t0,$t0,-%d\n" % find_entity[0].offset)
#Loads <value> into $t<register>
def loadvr(value,register):
global line
global asm_code
if (str(value).isdigit()) : asm_code.write("\tli $t%s, %d\n" % (register,int(value))) #Immediate
else:
find_value = search_for_variable(value)
if find_value == False:
error = 'Variable "' + value + '" not found due to empty scopes list.'
error_display(6,error,line)
exit()
elif find_value == True:
error = 'Variable "' + value + '" not declared.'
error_display(6,error,line)
exit()
v_type = find_value[0].type
v_offset = find_value[0].offset
v_scope = find_value[1]
c_scope = scopes[-1].nesting_level
if v_type == "VAR" and v_scope == 0:
asm_code.write("\tlw $t%s, -%d($s0)\n" %(register, v_offset))
elif ((c_scope == v_scope and (v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"))) or v_type == "TMP"):
asm_code.write("\tlw $t%s, -%d($sp)\n" %(register,v_offset))
elif (c_scope == v_scope and v_type == "PAR" and find_value[0].mode == "inout"):
asm_code.write("\tlw $t0, -%d($sp)\n" %(v_offset))
asm_code.write("\tlw $t%s, 0($t0)\n" %(register))
elif ( v_scope < c_scope and (v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"))):
gnlvcode(value)
asm_code.write("\tlw $t%s, 0($t0)\n" %(register))
elif ( v_scope < c_scope and v_type == "PAR" and find_value[0].mode == "inout"):
gnlvcode(value)
asm_code.write("\tlw $t0,0($t0)\n")
asm_code.write("\tlw $t%s,0($t0)\n" %(register))
else:
error = 'Error while trying to transfer "' + value + '" to register "$t' + str(register) + '".'
error_display(6,error,line)
exit()
#Stores the value of $t<register> into memory of <value>
def storerv(register,value):
global line
global asm_code
find_value = search_for_variable(value)
if find_value == False:
error = 'Variable "' + value + '" not found due to empty scopes list.'
error_display(6,error,line)
exit()
elif find_value == True:
error = 'Variable "' + value + '" not declared.'
error_display(6,error,line)
exit()
v_type = find_value[0].type
v_offset = find_value[0].offset
v_scope = find_value[1]
c_scope = scopes[-1].nesting_level
if v_type == "VAR" and v_scope == 0:
asm_code.write("\tsw $t%s, -%d($s0)\n" %(register,v_offset))
elif ((c_scope == v_scope and (v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"))) or v_type == "TMP"):
asm_code.write("\tsw $t%s, -%d($sp)\n" %(register,v_offset))
elif (c_scope == v_scope and v_type == "PAR" and find_value[0].mode == "inout"):
asm_code.write("\tlw $t0, -%d($sp)\n" %(v_offset))
asm_code.write("\tsw $t%d, 0($t0)\n" %(register))
elif (v_scope < c_scope and ( v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"))):
gnlvcode(value)
asm_code.write("\tsw $t%s, 0($t0)\n" %(register))
elif (v_scope < c_scope and v_type == "PAR" and find_value[0].mode == "inout"):
gnlvcode(value)
asm_code.write("\tlw $t0,0($t0)\n")
asm_code.write("\tsw $t%s,0($t0)\n" %(register))
else:
error = 'Error while trying to transfer the value of register "$t' + register + '" to memory for value "' + value + '"'
error_display(6,error_display,line)
exit()
#Generate the final code in Assembly for MIPS processor for a quad.
def generate_assembly(code_quad, name):
global asm_code
global ops
global relops
global fp_reg_offset
global newline_helper
if newline_helper == 0:
asm_code.write('.data\nnewline: .asciiz "\\n"\t\t# Used to print newline\n.text\n\n')
newline_helper = newline_helper + 1 # NEVER come here again
if code_quad == code_quads[0]: asm_code.write("\tj L_main\n")
asm_code.write("L_" + str(code_quad.label) + ":\t\t\t\t\t\t#" + str(code_quad) + "\n")
if code_quad.op == "jump":
fp_reg_offset = 0
asm_code.write("\tj L_%s\n" % (code_quad.res))
elif code_quad.op in ops:
fp_reg_offset = 0
loadvr(code_quad.arg_1,1)
loadvr(code_quad.arg_2,2)
asm_code.write("\t%s $t1,$t1,$t2\n" % (ops[code_quad.op]))
storerv(1,code_quad.res)
elif code_quad.op == ":=":
loadvr(code_quad.arg_1, 1)
storerv(1, code_quad.res)
elif code_quad.op in relops:
fp_reg_offset = 0
loadvr(code_quad.arg_1,1)
loadvr(code_quad.arg_2,2)
asm_code.write("\t%s $t1, $t2, L_%s\n" % (relops[code_quad.op],code_quad.res))
elif code_quad.op == "print":
fp_reg_offset = 0
loadvr(code_quad.arg_1,1)
asm_code.write("\tli $v0,1\n")
asm_code.write("\taddi $a0,$t1,0\n")
asm_code.write("\tsyscall\n")
asm_code.write("\tla $a0, newline\n")
asm_code.write("\taddi $v0,$0,4\n")
asm_code.write("\tsyscall\n")
elif code_quad.op == "input":
fp_reg_offset = 0
asm_code.write("\tli $v0,5\n")
asm_code.write("\tsyscall\n")
asm_code.write("\tmove $t1,$v0\n")
storerv(1,code_quad.arg_1)
elif code_quad.op == "return":
fp_reg_offset = 0
loadvr(code_quad.arg_1,1)
asm_code.write("\tlw $t0,-8($sp)\n")
asm_code.write("\tsw $t1,0($t0)\n")
#asm_code.write("\tlw $ra, 0($sp)\n") No Jumping back... :[
#asm_code.write("\tjr $ra\n")
elif code_quad.op == "begin_block":
fp_reg_offset = 0
if name == program_name:
asm_code.write("L_main:\n")
asm_code.write("\taddi $sp, $sp, %d\n" %(main_frame_len))
asm_code.write("\tmove $s0, $sp\n")
else:
asm_code.write("\tsw $ra,0($sp)\n")
elif code_quad.op == "par":
update_offset = 12 + (4*fp_reg_offset)
if name == program_name:
frame_len_for_fp = main_frame_len
if name != program_name: #Happens for Nested Functions
find_function = search_entity(name, "FUN")
if find_function == True or find_function == False: #Kinda Impossible to happen, but just to be sure
error = 'Function "' + name + '" not found'
error_display(6,error,line)
exit()
frame_len_for_fp = find_function[0].frame_len
if fp_reg_offset == 0:
asm_code.write("\taddi $fp, $sp, %d\n" % (frame_len_for_fp))
if code_quad.arg_2 == "in":
loadvr(code_quad.arg_1,0)
asm_code.write("\tsw $t0,-%d($fp)\n" %(update_offset))
fp_reg_offset = fp_reg_offset + 1
elif code_quad.arg_2 == "inout":
find_value = search_for_variable(code_quad.arg_1)
if find_value == False:
error = 'Variable "' + value + '" not found due to empty scopes list.'
error_display(6,error,line)
exit()
if find_value == True:
error = 'Variable "' + value + '" not declared.'
error_display(6,error,line)
exit()
v_type = find_value[0].type
v_offset = find_value[0].offset
v_scope = find_value[1]
c_scope = scopes[-1].nesting_level
if v_scope == c_scope:
if v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"):
asm_code.write("\taddi $t0, $sp, -%d\n" %(v_offset))
asm_code.write("\tsw $t0, -%d($fp)\n" %(update_offset))
fp_reg_offset = fp_reg_offset + 1
if v_type == "PAR" and find_value[0].mode == "inout":
asm_code.write("\tlw $t0, -%d($sp)\n" %(v_offset))
asm_code.write("\tsw $t0, -%d($fp)\n" %(update_offset))
fp_reg_offset = fp_reg_offset + 1
elif v_scope < c_scope:
if v_type == "VAR" or (v_type == "PAR" and find_value[0].mode == "in"):
gnlvcode(code_quad.arg_1)
asm_code.write("\tsw $t0, -%d($fp)\n" %(update_offset))
fp_reg_offset = fp_reg_offset + 1
elif v_type == "PAR" and find_value[0].mode == "inout":
gnlvcode(code_quad.arg_1)
asm_code.write("\tlw $t0, 0($t0)\n")
asm_code.write("\tsw $t0, -%d($fp)\n" %(update_offset))
fp_reg_offset = fp_reg_offset + 1
elif code_quad.arg_2 == "ret":
find_value = search_for_variable(code_quad.arg_1)
if find_value == False:
error = 'Return variable "' + value + '" not found due to empty scopes list.'
error_display(6,error,line)
exit()
if find_value == True:
error = 'Return variable "' + value + '" not declared.'
error_display(6,error,line)
exit()
v_type = find_value[0].type
v_offset = find_value[0].offset
v_scope = find_value[1]
c_scope = scopes[-1].nesting_level
asm_code.write("\tadd $t0,$sp,-%d\n" %(v_offset))
asm_code.write("\tsw $t0,-8($fp)\n")
elif code_quad.op == "end_block":
fp_reg_offset = 0
if name != program_name:
asm_code.write("\tlw $ra, 0($sp)\n")
asm_code.write("\tjr $ra\n")
elif code_quad.op == "call":
fp_reg_offset = 0
if name == program_name:
father_scope = 0
father_frame_len = main_frame_len
else:
find_father = search_entity(name, "FUN")
if find_father == True or find_father == False:
error = 'Father function "' + name + '" not found.'
error_display(6,error,line)
exit()
father_scope = find_father[1]
father_frame_len = find_father[0].frame_len
find_son_or_brother = search_entity(code_quad.arg_1, "FUN")
if find_son_or_brother == True or find_son_or_brother == False:
error = 'Successor function "' + code_quad.arg_1 + '" not found.'
error_display(6,error,line)
exit()
son_or_brother_scope = find_son_or_brother[1]
son_or_brother_label = find_son_or_brother[0].first_quad
if father_scope == son_or_brother_scope: # Father is Brother
asm_code.write("\tlw $t0,-4($sp)\n")
asm_code.write("\tsw $t0,-4($fp)\n")
else: # Father is indeed Father
asm_code.write("\tsw $sp,-4($fp)\n")
asm_code.write("\taddi $sp,$sp,%s\n" %str(father_frame_len))
asm_code.write("\tjal L_%s\n" %(son_or_brother_label))
asm_code.write("\taddi $sp,$sp,-%s\n" %str(father_frame_len))
def do_semantic_check_for_rets(name, from_here):
global line
global program_name
global code_quads
ret_cc = 0
for quad in code_quads[int(from_here):]:
if quad.op == "return":
ret_cc = ret_cc + 1
if name == program_name: # Checks for return statements per Block
if ret_cc != 0:
error = "Main program has a \"return\" statement."
error_display(3,error,line)
exit()
else: