-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminimal++.py
1478 lines (1245 loc) · 47.3 KB
/
minimal++.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
#############################################################
#Omada
#Eftihia Kiafa AM 3003 cse53003
#Kyrkenidis Anestis AM 3016 cse53016
#############################################################
#############################################################
# Minimal++ Compiler
#To run the analysis do:
# python3 minimal++.py -i <file_name>
##############################################################
#Declarations
###############################################################
import sys, getopt, enum, os, struct
lineNumber = -1
charNumber = -1
end_of_file = 0
name = ""
showfile="" #global for the file read, in order to use in the lexicalAnalyzer()
nontoken="" #for id and numbers, basically anything not in the list below
tokens= ["+","-",'*',"/",",",":",";","<",">","<=",">=","=","<>",":=","(",")","{","}","[","]",
"program","declare","if","else","while","doublewhile","loop","exit","forcase","incase","when",
"default","not","and","or","function","procedure","call","return","in","inout","input","print","EOF"]
c_file = ""
int_file = ""
finalfile = ""
quadlist = []
nextquadlabel = 0
templist = [] #global list with the temp variables used
nexttemp = 0 #global integer zerved for the next temp ( used to differentiate the temporary variables)
program_name = "" # needed for intermediate code
func = "" # needed for intermediate code
mainPFrameLength=-1
scopeList=[]
halt=-1 #halt label
subprogramExists = False #label for subrograms in final code
inFunctionBlock=[]
haveReturn=[]
subprogramParams=[]
parameterC = "("
#class that acts as a struct for the Quads
class Quad():
def __init__(self, label, op, x, y, z):
self.label = label
self.op = op
self.x = x
self.y = y
self.z = z
def writeQuadToFile(self):
return str(self.label) +': ('+str(self.op)+', '+str(self.x)+', '+str(self.y)+', '+str(self.z)+')'
#class for Scope as a data pack for this element
class Scope():
def __init__(self, enlevel=0,enclosing_scope=None):
self.entities=[]
self.enlevel = enlevel
self.enclosing_scope= enclosing_scope
self.toffset=12
def addEntity(self,entity):
self.entities.append(entity)
def getOffset(self):
returnValue=self.toffset
self.toffset+=4
return returnValue
#class for Entity as a data pack for this element
class Entity():
def __init__(self,name,entityType):
self.name=name
self.entityType=entityType
#class for Fuction as a data pack for this element
class Function(Entity):
def __init__(self,name,returnType,startQuad=-1):
super().__init__(name,'Function')
self.returnType=returnType
self.startQuad=startQuad
self.arguments=[]
self.framelength=-1
def addArguments(self,argument):
self.arguments.append(argument)
def setFramelength(self,framelength):
self.framelength=framelength
def setStartQuad(self,startQuad):
self.startQuad=startQuad
#class for Parameter as a data pack for this element
class Parameter(Entity):
def __init__(self,name,parameterMode,offset=-1):
self.parameterMode=parameterMode
self.offset=offset
super().__init__(name,'Parameter')
#class for Argument as a data pack for this element
class Argument():
def __init__(self,parameterMode,nextArgument=None):
self.parameterMode=parameterMode
self.nextArgument=nextArgument
def setNextArgument(self,nextArgument):
self.nextArgument=nextArgument
class Variable(Entity):
def __init__(self,name,offset=-1):
super().__init__(name,'Variable')
self.offset=offset
class TempVariable(Entity):
def __init__(self,name,offset=-1):
super().__init__(name, "TempVariable")
self.offset=offset
#########################################################
#Lexical Analyzer
#########################################################
def lexicalAnalyzer():
global lineNumber,charNumber,char,showfile,nontoken, end_of_file
buffer = []
tokenLine = tokenChar= -1
commentLine = commentChar = -1
state = 0
finalState = -2
foundChar = False
count=0
#lexical analyzer automata
while state != finalState:
char = showfile.read(1)
buffer.append(char)
charNumber += 1
#print(str(charNumber))
if state == 0:
if char.isalpha():
state = 1
elif char.isdigit():
state = 2
elif char == '<':
state = 3
elif char == '>':
state = 4
elif char == ':':
state = 5
elif char == '/':
state = 6
elif char in ('+', '-', '*', '=', ',', ';', '{', '}', '(', ')', '[', ']'):
state = finalState
elif char == '': # EOF
#print("REACHED END")
end_of_file = 1
return ("EOF")
#sys.exit()
elif char.isspace():
state = 0
else:
ErrorFunc("Invalid char in program " + char +"'.")
elif state == 1:
if not char.isalnum():
foundChar = True
state = finalState
#print(str(state))
elif state == 2:
if not char.isdigit():
if char.isalpha():
ErrorFunc("Variables can't begin with numbers. Please start a variable with an alphabetic character.")
foundChar = True
state = finalState
elif state == 3:
if char != '=' and char != '>':
foundChar = True
state = finalState
elif state == 4:
if char != '=':
foundChar = True
state = finalState
elif state == 5:
if char != '=':
foundChar = True
state = finalState
elif state == 6:
if char == '*':
state = 7
commentLine = lineNumber
commentChar = charNumber - 1
elif char != "/" and char != "*":
state = finalState
elif state == 7:
if char == '': # EOF
ErrorFunc("Unclosed comment found.")
elif char == '*':
state = 8
elif state == 8:
if char == '/':
del buffer[:]
state = 0
else:
state = 7
if state == finalState:
tokenLine = lineNumber
tokenChar = charNumber - len(''.join(buffer)) + 1
if char.isspace():
del buffer[-1]
foundChar = False
if char == '\n':
lineNumber += 1
charNumber = 0
if foundChar == True:
del buffer[-1]
if char != '':#EOF
showfile.seek(showfile.tell() -1)
charNumber -=1
nontoken = "empty"
bufferContents= ''.join(buffer)
if bufferContents not in tokens:
if bufferContents.isdigit():
nontoken="number"
returnToken=bufferContents
else:
nontoken="id"
returnToken=bufferContents[:30] #cant be more than 30
else:
returnToken=bufferContents
#print(bufferContents)
del buffer [:]
#print(str(state))
#print(str(returnToken))
return returnToken
def ErrorFunc(message):
global lineNumber, charNumber
print("======ERROR Detected!======")
print(message + "(At line : " + str(lineNumber + 2) +")")
showfile.close()
sys.exit()
###################################################################
#Intermediate Code Functions
###################################################################
def nextquad(): # return the number of the next quad
global nextquadlabel
return nextquadlabel
def genquad(op=None, x='_', y='_', z='_'): # generate a new quad with the parameters given
global nextquadlabel
tmplabel = nextquadlabel
nextquadlabel+=1
temp = Quad(tmplabel, op, x, y, z)
#print("XXXX ",x)
quadlist.append(temp)
def newTemp(): # return the next Temp ( i.e T_1 ) to be used
global templist, nexttemp
key = "T_" + str(nexttemp)
templist.append(key)
scopeList[-1].addEntity(TempVariable(key, scopeList[-1].getOffset()))
nexttemp+=1
#print("Key : ",key)
return key
def emptylist(): # create an empty quad list
global quadlist
quadlist.clear()
def makelist(x): # create an empty quad list that has only 'x' in it
return [x]
def mergelist(l1, l2): # merge the 2 lists ( l1 and l2 )
return l1 + l2
def backpatch(a1, z): # put in each quad of the list, the 'z' at the 4th element of each quad
global quadlist
for i in quadlist:
if i.label in a1:
i.z = z
####################### Utility Function #######################3
def is_number(n):
try:
int(n) # Type-casting the string to `int`.
# if the string is a number then it will return true
# if not then it goes to exception
return True
except ValueError:
return False
def findVariables(quad):
vars=dict()
index=quadlist.index(quad)+1
while True:
q=quadlist[index]
if q.op=='end_block':
break
if (q.y !='CV' and q.y!='REF' and q.y!='RET') and q.op!= 'call' and q.x!='':
if isinstance(q.x, str):
if(is_number(q.x) == False ):
vars[q.x] = 'int'
if isinstance(q.y, str):
if(is_number(q.y) == False ):
vars[q.y] = 'int'
if isinstance(q.z, str):
vars[q.z] = 'int'
index += 1
if '_' in vars:
del vars['_']
return vars.items()
def transformToCdeclarations(vars):
inVars= False
returnValue='int '
for var in vars:
inVars= True
returnValue+= var[0] + ', '
if inVars==True:
return returnValue[:-2]+';'
else:
return ''
def c_equivalent(quad):
global parameterC
haveSeenBlock=False
returnCommand=""
#reg Operators
if quad.op in ('<=','>','>=','=','<>','<'):
op= quad.op
if op== '=':
op='=='
elif op == '<>':
op='!='
returnCommand= 'if ('+str(quad.x)+' '+op+' '+str(quad.y)+') goto Line_'+ str(quad.z)+';'
#math operators
elif quad.op in ('+','-','*','/'):
returnCommand = quad.z +'='+str(quad.x)+' '+str(quad.op)+' '+str(quad.y)+';'
#evaluation
elif quad.op == ':=':
returnCommand = quad.z + '=' + str(quad.x) + ';'
#out
elif quad.op == 'out':
returnCommand = 'printf("%d\\n", '+str(quad.x)+');'
elif quad.op == 'retv':
returnCommand = 'return ('+str(quad.x)+');'
#beginblock
elif quad.op == 'begin_block':
haveSeenBlock = True
if quad.x == program_name:
returnCommand = 'int main(void)\n{\n'
else:
returnCommand = 'int '+ quad.x +'()\n{\n'
vars = findVariables(quad)
returnCommand += ' ' + transformToCdeclarations(vars)
returnCommand += '\nLine_'+str(quad.label) +':'
#endblock
elif quad.op == 'end_block':
haveSeenBlock = True
returnCommand = 'Line_'+str(quad.label)+': {}\n'
returnCommand += '}\n'
#halt
elif quad.op == 'halt':
returnCommand = 'return 0;'
#jump
elif quad.op=='jump':
returnCommand='goto Line_'+str(quad.z) + ';'
elif quad.op == "par":
if quad.y == "CV":
parameterC+=" "+quad.x+","
elif quad.y == "REF":
parameterC+="&"+quad.x+","
elif quad.y == "RET":
print("par ", quad.x)
parameterC=str(quad.x)+"="+parameterC+")"
#call
elif quad.op == 'call':
tmp = 0
for par in range(len(parameterC)):
if parameterC[par]=="=":
tmp=par
parameterC=parameterC[0:tmp+1]+quad.x+parameterC[tmp+1:]+";"
parameterC = parameterC.replace(',);', ' );')
returnCommand = parameterC
else:
return None
if haveSeenBlock== False:
returnCommand = ' Line_' + str(quad.label) + ': ' + returnCommand
return returnCommand
def makeIntermediateCodeFile():
global quadlist
for quad in quadlist:
int_file.write(quad.writeQuadToFile() +'\n')
int_file.close()
def makeCcodeFile():
global quadlist
c_file.write('#include <stdio.h>\n\n')
for quad in quadlist:
#print("Whatever\n")
a = c_equivalent(quad)
if a is not None:
c_file.write('' + a + '\n')
c_file.close()
#############################################################
# Symbol Table Functions
#############################################################
def addNewScope():
enclosing_scope = scopeList[-1]
currentScope= Scope(enclosing_scope.enlevel+1,enclosing_scope)
scopeList.append(currentScope)
def addFunctionEntity(name):
enlevel=scopeList[-1].enclosing_scope.enlevel
if not (uniqueEntity(name,'Function',enlevel)):
ErrorFunc('Not unique entity %s'% name)
if inFunctionBlock[-1]==True:
returnType='int'
else:
returnType='void'
scopeList[-2].addEntity(Function(name,returnType))
def addParameterEntity(name,parameterMode):
enlevel=scopeList[-1].enlevel
parameterOffset=scopeList[-1].getOffset()
if not (uniqueEntity(name,'Function',enlevel)):
ErrorFunc('Not unique entity %s'% name)
scopeList[-1].addEntity(Parameter(name,parameterMode,parameterOffset))
def addVariableEntity(name):
enlevel = scopeList[-1].enlevel
variableOffset = scopeList[-1].getOffset()
if not (uniqueEntity(name, "Variable", enlevel)):
ErrorFunc('Not unique entity %s'% name)
if variableExistsAsParameter(name, enlevel):
ErrorFunc('Already given as parameter %s'% name)
scopeList[-1].addEntity(Variable(name, variableOffset))
def searchEntity(name,entityType):
if scopeList ==[]:
return
else:
tempScope=scopeList[-1]
while tempScope is not None:
for entity in tempScope.entities:
if entity.entityType == entityType and entity.name == name:
return entity, tempScope.enlevel
tempScope = tempScope.enclosing_scope
def searchEntityWithName(name):
if scopeList ==[]:
return
else:
tempScope=scopeList[-1]
while tempScope is not None:
for entity in tempScope.entities:
if entity.name == name:
return entity, tempScope.enlevel
tempScope = tempScope.enclosing_scope
def addFunctionArgument(functionName,parameterMode):
if(parameterMode=='in'):
newArgument=Argument('CV')
else:
newArgument=Argument('REF')
tempEntity=searchEntity(functionName,"Function")
functionEntity = tempEntity[0]
if functionEntity is None:
ErrorFunc('%s:Entity not found'% functionName)
if functionEntity.arguments!=[]:
functionEntity.arguments[-1].setNextArgument(newArgument)
functionEntity.addArguments(newArgument)
def updateFunctionEntityQuad(name):
startQuad=nextquad()
if name==program_name:
return startQuad
tempEntity = searchEntity(name,"Function")
functionEntity = tempEntity[0]
functionEntity.setStartQuad(startQuad)
return startQuad
def updateFunctionEntityFramelength(name,framelength):
global mainPFrameLength
if name== program_name:
mainPFrameLength=framelength
return
tempEntity=searchEntity(name,"Function")
functionEntity = tempEntity[0]
functionEntity.setFramelength(framelength)
def uniqueEntity(entity_name,entity_type,entityLevel):
if scopeList[-1].enlevel< entityLevel:
return
else:
scope=scopeList[entityLevel]
for i in range(len(scope.entities)):
for j in range(len(scope.entities)):
a1=scope.entities[i]
a2=scope.entities[j]
if a1.name==a2.name and a1.entityType==a2.entityType and a1.name==entity_name and a1.entityType==entity_type:
return False
return True
def variableExistsAsParameter(name,enlevel):
if scopeList[-1].enlevel < enlevel:
return
else:
scope=scopeList[enlevel]
for i in range(len(scope.entities)):
a=scope.entities[i]
if a.name==name and a.entityType=='Parameter':
return True
return False
########################################################################
#Final code functions
########################################################################
#load $t0 the non-local variable var
def gnvlcode(var):
if searchEntityWithName(var) is not None:
tempEntity,tmplevel=searchEntityWithName(var)
else:
ErrorFunc('Non declared variable: ' + var)
if tempEntity.entityType=='Function':
ErrorFunc('Non declared variable: ' + var)
currentEnLevel=scopeList[-1].enlevel
finalfile.write('lw $t0, -4($sp)\n')
newEnLevel=currentEnLevel-1-tmplevel
while newEnLevel!=0 and newEnLevel>0:
finalfile.write('lw $t0, -4($t0)\n')
newEnLevel=newEnLevel-1
finalfile.write('addi $t0, $t0, -%d\n' % tempEntity.offset)
def loadvr(var,reg):
tmp = str(var)
if tmp.isdigit():
finalfile.write('li $t%s, %d\n' % (reg, int(var)))
else:
if searchEntityWithName(var) is not None:
tempEntity, tmplevel=searchEntityWithName(var)
else:
ErrorFunc('Non declared variable: ' + var)
currentEnLevel=scopeList[-1].enlevel
if tempEntity.entityType == 'Variable' and tmplevel == 0:
finalfile.write('lw $t%s, -%d($s0)\n' % (reg, tempEntity.offset))
elif (tempEntity.entityType == 'Variable' and tmplevel == currentEnLevel) or \
(tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'in' and tmplevel == currentEnLevel) or\
(tempEntity.entityType == 'TempVariable'):
finalfile.write('lw $t%s, -%d($sp)\n' % (reg, tempEntity.offset))
elif tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'inout' and tmplevel == currentEnLevel:
finalfile.write('lw $t0, -%d($sp)\n' % tempEntity.offset)
finalfile.write('lw $t%s, 0($t0)\n' % reg)
elif (tempEntity.entityType == 'Variable' and tmplevel < currentEnLevel) or \
(tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'in' and tmplevel < currentEnLevel):
gnvlcode(var)
finalfile.write('lw $t%s, 0($t0)\n' % reg)
elif tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'inout' and tmplevel < currentEnLevel:
gnvlcode(var)
finalfile.write('lw $t0, 0($t0)\n')
finalfile.write('lw $t%s, 0($t0)\n' % reg)
else:
ErrorFunc('loadvr loads data from memory in a register ')
def storerv(reg, var):
if searchEntityWithName(var) is not None:
tempEntity, tmplevel=searchEntityWithName(var)
else:
ErrorFunc('Non declared variable:' + var) # lathos edo
currentEnLevel=scopeList[-1].enlevel
if tempEntity.entityType == 'Variable' and tmplevel == 0:
finalfile.write('sw $t%s, -%d($s0)\n' % (reg, tempEntity.offset))
elif (tempEntity.entityType == 'Variable' and tmplevel == currentEnLevel) or \
(tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'in' and tmplevel == currentEnLevel) or \
(tempEntity.entityType == 'TempVariable'):
finalfile.write('sw $t%s, -%d($sp)\n' % (reg, tempEntity.offset))
elif tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'inout' and tmplevel == currentEnLevel:
finalfile.write('lw $t0, -%d($sp)\n' % tempEntity.offset)
finalfile.write('sw $t%s, 0($t0)\n' % reg)
elif (tempEntity.entityType == 'Variable' and tmplevel < currentEnLevel) or \
(tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'in' and tmplevel < currentEnLevel):
gnvlcode(var)
finalfile.write('sw $t%s, 0($t0)\n' % reg)
elif tempEntity.entityType == 'Parameter' and tempEntity.parameterMode == 'inout' and tmplevel < currentEnLevel:
gnvlcode(var)
finalfile.write('lw $t0,0(%t0)\n')
finalfile.write('sw $t%s, 0($t0)\n' % reg)
else:
ErrorFunc('storerv stores data of a register to memory ')
def corvertionToAssemblyCode(quad,blockName):
global subprogramParams
if str(quad.label) == '0':
finalfile.write(' ' * 50) # de ta grafei ola alliws, opote skeftikame na to baloyme na kanei polles fores space prokeimenoy na ta parei
finalfile.write('\nLine_' + str(quad.label) + ':#' + quad.writeQuadToFile() +'\n')
if quad.op=='jump':
finalfile.write('j Line_%d\n' % quad.z)
elif quad.op in ('=', '<>', '<', '<=', '>', '>='):
assemblyRelationalOperators=('beq', 'bne', 'blt', 'ble', 'bgt', 'bge')
relOperators=('=', '<>', '<', '<=', '>', '>=')
relop = assemblyRelationalOperators[relOperators.index(quad.op)]
loadvr(quad.x, '1')
loadvr(quad.y, '2')
finalfile.write('%s $t1, $t2, Line_%d\n' % (relop, quad.z))
elif quad.op == ':=':
loadvr(quad.x, '1')
storerv('1', quad.z)
elif quad.op in ('+', '-', '*', '/'):
assemblyOperators=('add', 'sub', 'mul', 'div')
op = assemblyOperators[('+', '-', '*', '/').index(quad.op)]
loadvr(quad.x, '1')
loadvr(quad.y, '2')
finalfile.write('%s $t1, $t1, $t2\n' % op)
storerv('1', quad.z)
elif quad.op=='out':
loadvr(quad.x, '9')
finalfile.write('li $v0, 1\n')
finalfile.write('add $a0, $zero, $t9\n')
finalfile.write('syscall\n')
elif quad.op == 'retv':
loadvr(quad.x, '1')
finalfile.write('lw $t0, -8($sp)\n')
finalfile.write('sw $t1, 0($t0)\n')
finalfile.write('lw $ra, 0($sp)\n')
finalfile.write('jr $ra\n')
elif quad.op == 'halt':
finalfile.write('li $v0, 10 # service code 10: exit\n')
finalfile.write('syscall\n')
elif quad.op == 'par':
if blockName==program_name:
callerLevel=0
framelength=mainPFrameLength
else:
callerEntity,callerLevel=searchEntity(blockName,'Function')
framelength=callerEntity.framelength
if subprogramParams == []:
finalfile.write('addi $fp, $sp, -%d\n' % framelength)
subprogramParams.append(quad)
parameterOffset=12+4*subprogramParams.index(quad)
if quad.y == 'CV':
loadvr(quad.x, '0')
finalfile.write('sw $t0, -%d($fp)\n' % parameterOffset)
elif quad.y == 'REF':
if searchEntityWithName(quad.x) is not None:
variableEntity, variableLevel = searchEntityWithName(quad.x)
else:
ErrorFunc('Non declared variable: ' + quad.x)
if callerLevel == variableLevel:
if variableEntity.entityType == 'Variable' or \
(variableEntity.entityType == 'Parameter' and variableEntity.parameterMode == 'in'):
finalfile.write('addi $t0, $sp, -%s\n' % variableEntity.offset)
finalfile.write('sw $t0, -%d($fp)\n' % parameterOffset)
elif variableEntity.entityType == 'Parameter' and variableEntity.parameterMode == 'inout':
finalfile.write('lw $t0, -%d($sp)\n' % variableEntity.offset)
finalfile.write('sw $t0, -%d($fp)\n' % parameterOffset)
else:
if variableEntity.entityType == 'Variable' or \
(variableEntity.entityType == 'Parameter' and variableEntity.parameterMode == 'in'):
gnvlcode(quad.x)
finalfile.write('sw $t0, -%d($fp)\n' % parameterOffset)
elif variableEntity.entityType == 'Parameter' and variableEntity.parameterMode == 'inout':
gnvlcode(quad.x)
finalfile.write('lw $t0, 0($t0)\n')
finalfile.write('sw $t0, -%d($fp)\n' % parameterOffset)
elif quad.y == 'RET':
if searchEntityWithName(quad.x)is not None:
variableEntity, variableLevel = searchEntityWithName(quad.x)
else:
ErrorFunc('Non declared variable: ' + quad.x)
finalfile.write('addi $t0, $sp, -%d\n' % variableEntity.offset)
finalfile.write('sw $t0, -8($fp)\n')
elif quad.op == 'call':
if blockName == program_name :
callerLevel = 0
framelength = mainPFrameLength
else:
callerEntity, callerLevel = searchEntity(blockName, 'Function')
framelength = callerEntity.framelength
if searchEntity(quad.x, 'Function') is not None:
calledEntity, calledLevel = searchEntity(quad.x, 'Function')
else:
ErrorFunc('Non defined function: ' + quad.x)
#if subprogram exists get in here###########################################
entity, enlevel = searchEntityWithName(calledEntity.name)
if entity.returnType == 'int':
subprogramParams.pop()
if len(entity.arguments) != len(subprogramParams):
ErrorFunc('Subprogram %s arguments number not match'% calledEntity.name)
for argument in entity.arguments:
quad = subprogramParams.pop(0)
if not (argument.parameterMode == quad.y):
if argument.parameterMode == 'CV':
parameterType = 'int'
else:
parameterType = 'int *'
ErrorFunc('%s parameter %s to be of'
' type "%s"' % (name, quad.x, parameterType))
#############################################################################
if callerLevel == calledLevel:
finalfile.write('lw $t0, -4($sp)\n')
finalfile.write('sw $t0, -4($fp)\n')
else:
finalfile.write('sw $sp, -4($fp)\n')
finalfile.write('addi $sp, $sp, -%d\n' % framelength)
finalfile.write('jal Line_%s\n' % str(calledEntity.startQuad))
finalfile.write('addi $sp, $sp, %d\n' % framelength)
elif quad.op == 'begin_block':
finalfile.write('sw $ra, 0($sp)\n')
if blockName == program_name:
finalfile.seek(0,0) # start of output file
finalfile.write('.globl Line_%d\n' % quad.label)
finalfile.write('j Line_%d\n' % quad.label)
finalfile.seek(0,2) # end of output file
finalfile.write('addi $sp, $sp, %d\n' % mainPFrameLength)
finalfile.write('move $s0, $sp\n')
elif quad.op == 'end_block':
if blockName == program_name:
finalfile.write('j Line_%d\n' % halt)
else:
finalfile.write('lw $ra, 0($sp)\n')
finalfile.write('jr $ra\n')
###################################################################
#Parser Functions and grammar implementation
###################################################################
def parser():
global token, end_of_file
token=lexicalAnalyzer()
program() #start syntax analyze
if end_of_file == 1:
makeIntermediateCodeFile()
makeCcodeFile()
def program(): # program id { <block>}
global token, nontoken,program_name, func, scopeList
if token == "program": #program
token = lexicalAnalyzer()
if nontoken == "id": #id
program_name = token
token = lexicalAnalyzer()
if token == "{": # {
token = lexicalAnalyzer()
func = program_name
scopeList.append(Scope())
block() # block
if token != "}": # }
ErrorFunc("Expected '}' instead of '" + token +"'.")
token = lexicalAnalyzer()
else:
ErrorFunc("Expected '{' for the program and not '" + token+ "'.")
else:
ErrorFunc("keyword 'program' is missing.")
def block(): # decleration subprograms statements
global func, halt, program_name
#printScopes()
tempfunc = func
declarations() # declarations
subprograms() #subprograms
blockBeginningQuad=updateFunctionEntityQuad(tempfunc)
genquad("begin_block",tempfunc,"","")
statements() #statements
if tempfunc == program_name:
halt = nextquad()
genquad('halt')
genquad('end_block', tempfunc)
updateFunctionEntityFramelength(tempfunc,scopeList[-1].toffset)
for quad in quadlist[blockBeginningQuad:]:
corvertionToAssemblyCode(quad,tempfunc)
scopeList.pop()
def declarations(): # ( declare <varlist>;)*
global token
while token == "declare": # )
token = lexicalAnalyzer()
varlist() # varlist
if token == ";":
token = lexicalAnalyzer() # repeats to check if the next is a declare.
else:
ErrorFunc("Expected ';' , not '" + token +"'.")
def varlist(): # e|id ( ,id)*
global token,nontoken
if nontoken == "id":
addVariableEntity(token)
token = lexicalAnalyzer()
while token == ",":
token = lexicalAnalyzer()
if nontoken == "id":
addVariableEntity(token)
token = lexicalAnalyzer()
else:
ErrorFunc("Expected a variable declaration, not '" +token+"'.")
def subprograms():
global token, haveReturn,inFunctionBlock,subprogramExists,func
while token == "function" or token == "procedure":
inFunctionBlock.append(False)
haveReturn.append(False)
subprogramExists=True
if token == "function" :
inFunctionBlock[-1]=True
token = lexicalAnalyzer()
subprogram()
if inFunctionBlock.pop() ==True:
if haveReturn.pop()==False:
ErrorFunc("Expected return from function ")
else:
haveReturn.pop()
def subprogram():# function id <funcbody> | procedure id <funcbody>
global token, nontoken, func
addNewScope()
if nontoken == "id":
func = token
token = lexicalAnalyzer()
addFunctionEntity(func)
funcbody()
else:
ErrorFunc("Expected procedure or function name instead of '" +token+"'.")
def funcbody(): #formalpars { block }
global token
formalpars() # formalpars
if token== "{": # {
token = lexicalAnalyzer()
block() # block
if token != "}": # }
ErrorFunc("Expected '}' and not '" +token+"'.")
token = lexicalAnalyzer()
else:
ErrorFunc("Expected '{' and not '" +token+"'.")
def formalpars(): # (formalparlist)
global token
if token == "(": # (
token = lexicalAnalyzer()
if token == "in" or token == "inout":
formalparlist()
if token != ")": # )
ErrorFunc("Expected ')' and not '" +token+"'.")
token = lexicalAnalyzer()
else:
ErrorFunc("Expected '(' and not '" +token+"'.")
def formalparlist():# <formalparitem> ( , <formalparitem> )* | e
global token
if token == "in" or token == "inout":
formalparitem() # formalparitem
while token == ",":
token = lexicalAnalyzer()
formalparitem()
def formalparitem():# in id | inout id
global token,nontoken, func
if token == "in" or token == "inout": # in | out
parameterMode=token
token = lexicalAnalyzer()
if nontoken != "id": # id
ErrorFunc("Formal parameter name was expected instead of '"+token+"'.")
parameterName=token
addFunctionArgument(func,parameterMode)
addParameterEntity(parameterName,parameterMode)
token = lexicalAnalyzer()
def statements(): #<statement> | { <statement> ( ; <statement> )* }
global token
#token = lexicalAnalyzer()
if token == "{":
token = lexicalAnalyzer()
statement() #statement
while token == ";": #;
token = lexicalAnalyzer()
statement() #statement
if token != "}":
ErrorFunc("Expected '}' to close statement(s), but found '"+token+"' instead.")
token = lexicalAnalyzer()
else:
statement()
def statement():
global token, nontoken, name, haveReturn
if nontoken == "id":
tid = token
token = lexicalAnalyzer()
assignment_stat() #assignment_stat
genquad(":=", name , "_", tid)
if token == "if": #if-stat
token = lexicalAnalyzer()
if_stat()
elif token == "while": #while-stat