-
Notifications
You must be signed in to change notification settings - Fork 1
/
Phase1.py
3611 lines (3068 loc) · 119 KB
/
Phase1.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
##########################################################################################
#Symbol Table
###########################################################################################
#from symtab2 import varEntry
userChoice1 = raw_input("Do you wish to print the Intermediate code? y/n: ")
if(userChoice1=="y"):
debug3 = True;
else:
debug3 = False;
userChoice2 = raw_input("Do you wish to print the other debugging information? y/n: ")
if(userChoice2=="y"):
debug2 = True;
debug4 = True
else:
debug2 = False;
debug4 = False
# Debugging Flags :
flag = True;
flag2 = True;
tokenPrinting = False;
tempCount = 0
labelCount = 0
quadList = []
targetList = [];
constList = []
stringList = [];
def emit(q):
global quadList;
global debug4
if(debug4):
print len(quadList);
q.Print();
quadList.append(q);
def nextQuad():
global quadList;
return len(quadList);
def makeList(l):
return [l];
def makeList_empty():
return ([])
def merge(l1,l2):
l = l1[:];
l.extend(l2);
return l;
def backPatch(l,q):
global quadList;
global targetList;
global debug4
targetList.append(q);
if(debug4):
if(len(l)>0):
print "backpatching! "
else:
print "No backpatching done!"
for each in l:
if(debug4):
quadList[each].Print()
quadList[each].result = q;
if(debug4):
quadList[each].Print()
#intSize = 2
intSize = 4
realSize = 4
charSize = 4
booleanSize = 4
pointerSize = 0
def newTemp(type):
global tempCount
global debug4
if(debug4):
print "hello"
tempCount+=1
toReturn = "t"+str(tempCount)
if(type=='INTEGER'):
typeSize = intSize
elif(type=='REAL'):
typeSize = realSize
elif(type=='BOOLEAN'):
typeSize = booleanSize
elif(type=='CHAR'):
typeSize = charSize
elif(type=='VOID'):
return toReturn
global stack
symbolTable = stack[len(stack)-1]
currentOffset = symbolTable.offset
symbolTable.offset = symbolTable.offset + typeSize
#print "creating symbol table entry for ", toReturn," ", type," ",currentOffset
entry = VarEntry(toReturn, type, currentOffset)
symbolTable.Insert(entry)
return toReturn
def newLabel():
global labelCount
labelCount+=1
return "label"+str(labelCount)+":"
unaryOps = ['UMINUS' , 'UPLUS' , '~' , 'intToReal'];
relOps = ['<' , '>' , '=' , '#' , '<=' , '>='];
class Quad():
def __init__(self, op = None , arg1 = None, arg2 = None, result = None, opType = None):
self.op = op
self.arg1 = arg1
self.arg2 = arg2
self.result = result
self.opType = opType
def Print(self, num = -1):
#print "op " , self.op;
#print "arg1 " , self.arg1;
#print "arg2 " , self.arg2;
#print "result " , self.result;
#print "\n"
global unaryOps;
global relOps;
global debug4
if(self.op=='null'):
if(debug4):
print num,": Do nothing!";
elif(self.op == 'goto'):
print num,":", self.op , self.result;
elif(self.op == 'ifgoto'):
print num,":", "if ", self.arg1, "goto ", self.result
elif(self.op == 'param'):
if(self.opType == 'STRING'):
print num,": param STRING" +str(self.arg1)
else:
print num,":", "param " , self.arg1
elif(self.op == 'actparam'):
print num,":", "actparam " , self.arg1
elif(self.op == 'call'):
if(self.arg1 == 'Out.Ln'):
print num,":", "call " , self.arg1 , 0;
else:
print num,":", "call " , self.arg1, self.arg2
elif(self.op == 'BEGIN_FUNC'):
print num,":","BEGIN_FUNC ", self.arg1
elif(self.op == 'END_FUNC'): #while mapping to mips, this would be an unconditional return in case some branch of the function forgets to return
print num,":","END_FUNC", self.arg1
elif(self.op == 'return'):
print num,":","return",self.arg1
elif(self.op == 'BEGINMAIN'):
print num,":", "BEGINMAIN";
elif(self.op == 'ENDMAIN'):
print num,":", "ENDMAIN"
elif(self.op == 'EXIT'):
print num,":", "EXIT"
elif(self.op =='READINT' or self.op =='READREAL'):
print num,":", self.op , self.arg1
else:
if(self.op is not None):
if(self.op in unaryOps):
print num,":", self.result , " = " , self.op , self.arg1;
elif(self.op in relOps):
print num,":", "if ", self.arg1 , self.op , self.arg2, " goto " , self.result;
elif(self.opType is None):
print num,":", self.result , " = " , self.arg1 , " " , self.op , " " , self.arg2;
else:
print num,":", self.result , " = " , self.arg1 , " " , self.opType ," ",self.op , " " , self.arg2;
else:
print num,":", self.result , " = " , self.arg1;
#id is the lexeme of the variable
class PointerEntry(object):
def __init__(self, id='', type='', offset=0, formalParameter = 0, callByReference = False, length = 0):
self.id = id;
self.type = type;
self.offset = offset;
self.formalParameter = formalParameter
self.callByReference = callByReference
self.length = length
class ArrayEntry(object):
def __init__(self, id='', type='', offset=0, formalParameter = 0, callByReference = False, length = 0):
self.id = id;
self.type = type;
self.offset = offset;
self.formalParameter = formalParameter
self.callByReference = callByReference
self.length = length
class VarEntry(object):
def __init__(self, id ='' , type='', offset=0, formalParameter = 0, callByReference = False, constant = False):
self.id = id;
self.type = type;
self.offset = offset;
self.formalParameter = formalParameter
self.callByReference = callByReference
self.constant = constant
#procName is the lexeme of the procedure
class ProcEntry(object):
def __init__(self, procName='',type = [], returnType='' , pointer=None, forwardDeclaration = False):#pointer is pointer to symbol table of proc name
self.procName = procName;
self.type = type;
self.returnType = returnType;
self.pointer = pointer;
self.forwardDeclaration = forwardDeclaration
class SymbolTable(object):
def __init__(self, parent=None, offset = 0):
self.parent = parent;
self.symbolDictionary = {};
self.offset = offset;
def LookUp(self, id):
if(id in self.symbolDictionary):
return self.symbolDictionary[id];
elif(self.parent == None):
return None;
else:
return self.parent.LookUp(id);
def Insert(self,entry):#while inserting into symbol table take care !!
global flag2;
if(entry.id in self.symbolDictionary):
flag2 = False
print "ERROR: Redefination of variable",entry.id;
return 0;
else:
self.symbolDictionary[entry.id] = entry;
return 1;
def InsertProcedure(self,procEntry):
global flag2;
if(procEntry.procName in self.symbolDictionary):
if not self.symbolDictionary[procEntry.procName].forwardDeclaration :
flag2 = False
print "ERROR: Redefination of variable",procEntry.procName;
return 0;
else:
if(self.symbolDictionary[procEntry.procName].type == procEntry.type and self.symbolDictionary[procEntry.procName].returnType == procEntry.returnType):
self.symbolDictionary[procEntry.procName] = procEntry
if(debug2):
print "Current insertion is corresponding to some earlier forward declaration";
return 2;
else:
print "ERROR : function definition does not match with declaration"
flag2 = False
return 3;
else:
self.symbolDictionary[procEntry.procName] = procEntry;
if(debug2):
print "Successfuly entered function"
return 1;
def Print(self):
global debug4
if(debug4):
print "\n \n PRINTING SYMBOL TABLE\n"
r = ArrayEntry()
r1 = ProcEntry()
for id in self.symbolDictionary:
if(type(r)==type(self.symbolDictionary[id])):
print id, self.symbolDictionary[id].type, self.symbolDictionary[id].offset, self.symbolDictionary[id].length
elif(type(r1)==type(self.symbolDictionary[id])):
print self.symbolDictionary[id].procName, "'s symbol table "
self.symbolDictionary[id].pointer.Print()
else:
print id, self.symbolDictionary[id].type, self.symbolDictionary[id].offset
print "\n\n"
###########################################################################################
#Lexer
###########################################################################################
import sys
sys.path.insert(0,"../..")
if sys.version_info[0] >= 3:
raw_input = input
import ply.lex as lex
literals = ['+','-','*','/','=','<','>',';',',','.',':','~','&','(',')','#','{','}','[',']','^','|']
#builtIns = []
reserved = {
# BUILT-INS -- SEPARATE DEPENDING ON NUMBER OF PARAMETERS
'ABS' : 'ABS',
'ASH' : 'ASH',
'CAP' : 'CAP',
'CHR' : 'CHR',
'MAX' : 'MAX',
'MIN' : 'MIN',
'ORD' : 'ORD',
'SIZE' : 'SIZE',
'DEC' : 'DEC',
'HALT' : 'HALT',
'INC' : 'INC',
'READINT' : 'READINT',
'READREAL' : 'READREAL',
# Activate at the time of semantic analysis
# KEYWORDS
#The following Keywords are responsible for control flow
'WHILE' : 'WHILE',
'ELSE' : 'ELSE',
'IF' : 'IF',
'THEN' : 'THEN',
'ELSIF' : 'ELSIF',
'BEGIN' : 'BEGIN',
'END' : 'END',
'RETURN' : 'RETURN',
'UNTIL' : 'UNTIL',
'LOOP' : 'LOOP',
'DO' : 'DO',
'FOR' : 'FOR',
#The following keywords are to be implemented in case of extensions
'RECORD' : 'RECORD',
'POINTER' : 'POINTER',
'CASE' : 'CASE',
'REPEAT' : 'REPEAT',
'WITH' : 'WITH',
'EXIT' : 'EXIT',
'BY' : 'BY',
#The Syntax for the procedure is given by:
#PROCEDURE <name >
#BEGIN
#...
#END <name >
#The following keywordxs are needed for the same.
'PROCEDURE' : 'PROCEDURE',
'DEFINITION' : 'DEFINITION',
'IMPORT' : 'IMPORT',
'TYPE' : 'TYPE',
'MODULE' : 'MODULE',
'VAR' : 'VAR',
# Operators (Logical and arithmetic)
'IN' : 'IN',
'TO' : 'TO',
'MOD' : 'MOD',
'OR' : 'OR',
'DIV' : 'DIV',
'OF' : 'OF',
# The following Keywords shall be activated in case of Extensions
# 'TRUE': 'TRUE',
# 'FALSE' : 'FALSE',
# The following keywords shall be needed for the basic and complex types shall be implemented
'INTEGER' : 'INTEGER',
'REAL' : 'REAL',
'BOOLEAN' : 'BOOLEAN',
'CHAR' : 'CHAR',
'CONST' : 'CONST',
'ARRAY' : 'ARRAY',
'NIL' : 'NIL'
}
tokens = [
#The following are the Contstants that have been implemented.
'ID',
'INTEGERCONSTANT',
'REALCONSTANT',
'CHARACTERCONSTANT',
'STRINGCONSTANT',
'BOOLEANCONSTANT',
#To be implemented
#'STRING-LITERAL'
#The following are the operators that have been implemented
'ASSIGN',
'LESSEQUAL',
'MOREEQUAL',
'COMMENT',
'DOTDOT'
]
tokens += reserved.values()
def t_BOOLEANCONSTANT(t): # Boolean Constants
r'TRUE|FALSE'
return t
def t_ID(t): # Check for reserved words
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = reserved.get(t.value,'ID')
return t
def t_REALCONSTANT(t):
#r'\d*\.\d+'
r'(\d*\.\d+([eE][+-]?\d+)?|\d+[eE][+-]?\d+)' # for Real Constants including those of the form 3.14 and 6.36e-34
#print t.value;
t.value= float(t.value);
print t.value, type(t.value)
#t.value = int(t.value)
return t
def t_INTEGERCONSTANT(t):
r'\d+'
t.value = int(t.value) # for Real Constants including those of the form 42
return t
def t_COMMENT(t):
r'\(\*(.|\n)*?\*\)' # for Comments of the form (* ...Comments... *)
#print t;
pass; # Do Nothing
#return t
def t_CHARACTERCONSTANT(t):
# r"\'\\t\'"
r'(\'(.|\\n|\\t)\')'#|\"(.|\\n|\\t)\")' #value assignment to escape sequences for \n and \t
#print len(t.value);
return t
def t_STRINGCONSTANT(t):
r'(\"(.|\\n|\\t)*\"|\'(.|\\n|\\t)*\')' # for String constants: Double Quotes with something in it. Special Treatment to \n and \t
return t
def t_newline(t):
r'\n+' # for the newline character
#t.lexer.lineno += t.value.count("\n")
t.lexer.lineno += len(t.value)
#return t
#print t.lexer.lineno
# for the recognition of the assignment, Less-than-equal-to, Greater-than-equal-to, dot-dot and the ignore operators
t_ASSIGN = r':='
t_LESSEQUAL = r'<='
t_MOREEQUAL = r'>='
t_DOTDOT = r'\.\.'
t_ignore = ' \t'
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Here, the lexer is built.
import ply.lex as lex
lexer = lex.lex();#debug=True);
###########################################################################################
#Parser
###########################################################################################
#TODO
#Global variables
variables = [];
moduleDictionary = {}; # Names of modules imported
moduleList = {}
moduleExpList = {}
moduleList['In'] = ['Int', 'Real']
moduleReturnTypes = {}
moduleReturnTypes['Out'] = {}
moduleReturnTypes['Out']['Int'] = 'VOID'
moduleReturnTypes['Out']['Real'] = 'VOID'
moduleReturnTypes['Out']['String'] = 'VOID'
moduleReturnTypes['Out']['Char'] = 'VOID'
moduleReturnTypes['Out']['Ln'] = 'VOID' # might create problems
moduleReturnTypes['In'] = {}
moduleReturnTypes['In']['Int'] = 'INTEGER'
moduleReturnTypes['In']['Real'] = 'REAL'
moduleExpList['Out'] = {}
moduleExpList['Out']['Int'] = ['INTEGER'];#, 'INTEGER']
moduleExpList['Out']['Real'] = ['REAL'];#, 'INTEGER', 'INTEGER']
moduleExpList['Out']['String'] = ['STRINGCONSTANT'];
moduleExpList['Out']['Char'] = ['CHAR'];
moduleList['Out'] = ['Int', 'Real', 'String', 'Ln', 'Char'] #can remove ln
# current function
# Call by value or reference ! -- Just check for 'VAR'
passByReference = False;
# nesting Depth
# Insert markers after procedure name and after 'END' of it!
# Add some erraneous constructs in the grammar
symbolTable = SymbolTable()
stack = [symbolTable]
formalParameterNo = 0
start = 'module'
#Broadly, the following specification are responsible for the declarations of Modules, and the lists to be imported.
def p_module(t):
'''module : MODULE ID ';' importList declarationList statementBlock END ID '.' ''';
if(t[2]!=t[8]):
global flag2
flag2 = False
print "ERROR : module names do not match in line no ", t.lineno(8)
#print "lineno , ", t.lexer.lineno
#Erraneous construct -- commonly done by programmers!
def p_module2(t):
'''module : MODULE ID ';' importList declarationList statementBlock END ID ''';
global flag2;
if(t[2]!=t[8]):
flag2 = False
print "ERROR : module names do not match in line no ", t.lineno(8)
flag2 = False
print "ERROR : Full stop missing in the end in line no", t.lineno(8)
def p_importList(t):
'''importList : IMPORT importedModulesList ';'
| ''';
if(debug2):
print("Imported Modules");
print moduleDictionary;
print moduleDictionary.keys();#These cannot be declared as variables
def p_importedModulesList(t):
'''importedModulesList : importedModules ',' importedModulesList
| importedModules''' ;
def p_importedModules(t):
'''importedModules : ID ASSIGN ID
| ID '''
global flag2;
if(len(t)==2):
if(t[1]!="In" and t[1]!="Out"): #check if imported modules are either of In and Out
flag2 = False
print "ERROR: in importing module ", t[1] , " at line no ", t.lineno(1)
else:
t[0] = t[1]
moduleDictionary[t[1]]=t[1];
if(len(t)==4):
if(t[3]!="In" and t[3]!="Out"):
flag2 = False
print "ERROR: in importing module ", t[3] , " at line no ", t.lineno(2)
else:
t[0] = t[3]
moduleDictionary[t[1]]=t[3];
#create a symbol table entry for module names
#Broadly, the following specification are responsible for the declarations of Identifiers, constants, variables, procedures, formal parameters and of declarations
def p_declarationList(t):
'''declarationList : identifierDeclarationList procedureDeclarationList '''
def p_identifierDeclarationList(t):
'''identifierDeclarationList : CONST constantDeclarationList identifierDeclarationList
| VAR variableDeclarationList identifierDeclarationList
| ''';
def p_constantDeclarationList(t):
'''constantDeclarationList : ID '=' expression ';' constantDeclarationList
| ''';
global stack
global intSize, realSize ,charSize, booleanSize
global constList
symbolTable = stack[len(stack)-1]
if(len(t) > 1):
currentOffset = symbolTable.offset
if(t[3]['type']=='INTEGER'):
symbolTable.offset = symbolTable.offset + intSize
elif(t[3]['type']=='REAL'):
symbolTable.offset = symbolTable.offset + realSize
elif(t[3]['type']=='CHAR'):
symbolTable.offset = symbolTable.offset + charSize
elif(t[3]['type']=='BOOLEAN'):
symbolTable.offset = symbolTable.offset + booleanSize
entry = VarEntry(t[1], t[3]['type'], currentOffset, 0, False, True);
symbolTable.Insert(entry);
quad = Quad(None, t[3]['place'], None, t[1], t[3]['type'])
constList.append(quad)
def p_variableDeclarationList(t):
'''variableDeclarationList : identifierList ':' type ';' clearVariables variableDeclarationList
|''';
#global variables
#if(len(t) > 1):
# for i in variables:
# print (i,t[3]);
#variables.remove(i)
#print variables
def p_clearVariables(t):
''' clearVariables : '''
global stack
global variables
global debug2
global flag2
global debug3
global intSize
global realSize
global charSize
global booleanSize
if(debug2):
print("Printing variables");
symbolTable = stack[len(stack)-1]
for i in variables:
if(t[-2]['type']=='BOOLEAN' or t[-2]['type']=='INTEGER' or t[-2]['type']=='REAL' or t[-2]['type']=='CHAR'):
if(debug2):
print "Adding variable entry"
currentOffset = symbolTable.offset
if(t[-2]['type']=='INTEGER'):
symbolTable.offset = symbolTable.offset + intSize
elif(t[-2]['type']=='REAL'):
symbolTable.offset = symbolTable.offset + realSize
elif(t[-2]['type']=='CHAR'):
symbolTable.offset = symbolTable.offset + charSize
elif(t[-2]['type']=='BOOLEAN'):
symbolTable.offset = symbolTable.offset + booleanSize
entry = VarEntry(i, t[-2]['type'], currentOffset)
symbolTable.Insert(entry)
if(debug2):
print (i,t[-2]['type']);
elif(t[-2] is not None):
if(len(t[-2])>0 ):
if(t[-2]['type']=='ARRAY'):
if(debug2):
print "Adding array entry"
if(t[-2]['arrayLength'] is None ):
flag2 = False
print "ERROR : Array size not known at compile time" , " at line no ", t.lineno(-1)
elif(t[-2]['arrayLength'] <0 ):
print "ERROR : Negative array size" , " at line no ", t.lineno(-1)
flag2 = False
else:
currentOffset = symbolTable.offset
arrayLength = t[-2]['arrayLength'];
if(t[-2]['arrayOf']['type']=='INTEGER'):
symbolTable.offset = symbolTable.offset + intSize*arrayLength
elif(t[-2]['arrayOf']['type']=='REAL'):
symbolTable.offset = symbolTable.offset + realSize*arrayLength
elif(t[-2]['arrayOf']['type']=='CHAR'):
symbolTable.offset = symbolTable.offset + charSize*arrayLength
elif(t[-2]['arrayOf']['type']=='BOOLEAN'):
symbolTable.offset = symbolTable.offset + booleanSize*arrayLength
entry = ArrayEntry(i, t[-2]['arrayOf'], currentOffset, False, False, t[-2]['arrayLength'])
symbolTable.Insert(entry)
if(debug2):
print (i,t[-2]);
elif(t[-2]['type']=='POINTER'):
if(debug2):
print "Adding pointer entry"
if(t[-2]['arrayLength'] is None ):
print "ERROR : Array size not known at compile time" , " at line no ", t.lineno(-1)
flag2 = False
elif(t[-2]['arrayLength'] <0 ):
print "ERROR : Negative array size" , " at line no ", t.lineno(-1)
flag2 = False
else:
currentOffset = symbolTable.offset
symbolTable.offset += pointerSize
arrayLength = t[-2]['arrayLength'];
#print arrayLength , "arrayLength";
#print t[-2]['arrayOf']
if(t[-2]['arrayOf']['type']=='INTEGER'):
#print "old offset ", symbolTable.offset
symbolTable.offset = symbolTable.offset + intSize*arrayLength
#print "new offset ", symbolTable.offset
elif(t[-2]['arrayOf']['type']=='REAL'):
symbolTable.offset = symbolTable.offset + realSize*arrayLength
elif(t[-2]['arrayOf']['type']=='CHAR'):
symbolTable.offset = symbolTable.offset + charSize*arrayLength
elif(t[-2]['arrayOf']['type']=='BOOLEAN'):
symbolTable.offset = symbolTable.offset + booleanSize*arrayLength
entry = PointerEntry(i, t[-2]['arrayOf'], currentOffset, False, False, t[-2]['arrayLength'])
symbolTable.Insert(entry)
if(debug2):
print (i,t[-2]);
variables=[];
if(debug2):
symbolTable.Print()
#print variables
# Also print the nesting depth and function in which it is declared
def p_identifierList(t):
'''identifierList : ID
| ID ',' identifierList ''';
global variables;
global moduleDictionary;
t[0] = {}
if(t[1] in moduleDictionary):
print "ERROR : Variable ",t[1] ," already in use as a module name" , " at line no ", t.lineno(1)
global flag2
flag2 = False
else:
variables.append(t[1]);
if(len(t)==2):
t[0]['place'] = [t[1]]
else:
t[0]['place'] = t[3]['place']
t[0]['place'].append(t[1])
#print variables
def p_procedureDeclarationList(t):
'''procedureDeclarationList : procedureDeclaration ';' procedureDeclarationList
| forwardDeclaration ';' procedureDeclarationList
|''' ;
def p_procedureDeclaration(t):
'''procedureDeclaration : PROCEDURE receiver ID createTable optionalFormalParameters ';' declarationList insertEntry statementBlock END ID popTable''';
#quad1 = Quad('BEGIN_FUNC',t[3]);#to be done in createTable
#emit(quad1);
#quad2 = Quad()
def p_insertEntry(t):
'''insertEntry : '''
global stack
if(debug2):
print "inserting symbol table"
oldSymbolTable = stack[len(stack)-2]
newSymbolTable = stack[len(stack)-1]
#procName = t[-1];
procName = t[-5];
#returnType = t[-6]['returnType']
returnType = t[-3]['returnType']
var = VarEntry()
inputType = []
inputType2 = []
count = len(newSymbolTable.symbolDictionary)
for i in range(0, count+1):
inputType.append('')
for i in newSymbolTable.symbolDictionary:
if(type(newSymbolTable.symbolDictionary[i]) == type(var)):
#if( type(newSymbolTable.symbolDictionary[i].formalParameter)):
#print "sumit ", ( type(newSymbolTable.symbolDictionary[i].formalParameter))
if( newSymbolTable.symbolDictionary[i].formalParameter != 0):
inputType[newSymbolTable.symbolDictionary[i].formalParameter] = newSymbolTable.symbolDictionary[i].type
#print "noooooooooooooo" , newSymbolTable.symbolDictionary[i].formalParameter
for i in inputType:
if(i!=''):
inputType2.append(i)
'''for i in newSymbolTable.symbolDictionary:
if(type(newSymbolTable.symbolDictionary[i]) == type(var)):
if( type(newSymbolTable.symbolDictionary[i].formalParameter)):
inputType.append(newSymbolTable.symbolDictionary[i].type)
'''
if(debug2):
print "printing input type !!!!!!!!!!\n" , inputType2
print "printing return type !!!!!!!\n", returnType
print "printing procedure name !!!!!!!\n", procName
entry = ProcEntry(procName, inputType2, returnType, newSymbolTable)
oldSymbolTable.InsertProcedure(entry)
if(debug2):
print len(stack)
quad1 = Quad('BEGIN_FUNC',procName);
emit(quad1);
def p_popTable(t):
'''popTable : '''
global stack
if(debug2):
print "popping symbol table"
oldSymbolTable = stack[len(stack)-2]
newSymbolTable = stack[len(stack)-1]
procName = t[-1];
#procName = t[-5];
if(debug2):
print len(stack)
stack.pop().Print()
else:
stack.pop()
quad = Quad('END_FUNC', procName);
emit(quad)
def p_createTable(t):
'''createTable : '''
global stack
if(debug2):
print "\nCreating table \n\n"
oldSymbolTable = stack[len(stack)-1]
newSymbolTable = SymbolTable(oldSymbolTable)
if(debug2):
print t[-1];
#entry = ProcEntry(t[-1],'','',newSymbolTable)
#oldSymbolTable.InsertProcedure(entry)
stack.append(newSymbolTable)
#quad1 = Quad('BEGIN_FUNC',t[-1]);
#emit(quad1);
#quad2 = Quad()
if(debug2):
print "Old symbol table"
oldSymbolTable.Print()
print "New symbol table"
newSymbolTable.Print()
def p_receiver(t):
'''receiver : '(' optionalVAR ID ':' ID ')'
| ''';
if(len(t)>1):
if(debug2):
print("receiver found");
def p_optionalVAR(t):
'''optionalVAR : VAR
| ''';
global passByReference;
if(len(t)>1):
if(debug2):
print("Passing by reference");
passByReference = True;
def p_optionalFormalParameters(t):
'''optionalFormalParameters : '(' optionalFormalParameterList ')' ':' qualident
| '(' optionalFormalParameterList ')'
|''';
t[0] = {}
if(len(t)==6):
t[0]['returnType'] = t[5]
else:
t[0]['returnType'] = "VOID"
global formalParameterNo
formalParameterNo = 0
if(len(t)>1):
t[0]['place'] = t[2]['place']
else:
t[0]['place'] = []
t[0]['place'].reverse()
for i in t[0]['place']:
quad = Quad('actparam', i)
#var = VarEntry(i, )
emit(quad)
def p_optionalFormalParameterList(t):
'''optionalFormalParameterList : formalParameterList
| ''';
t[0] = {}
if(len(t)==1):
t[0]['place'] = []
else:
t[0]['place'] = t[1]['place']
def p_formalParameterList(t):
'''formalParameterList : formalParameter ';' formalParameterList
| formalParameter ''';
t[0] = {}
if(len(t)==2):
t[0]['place'] = t[1]['place']
else:
t[0]['place'] = t[1]['place']
t[0]['place'].extend(t[3]['place'])
def p_formalParameter(t):
'''formalParameter : optionalVAR identifierList ':' type '''
# Doubtful in t[4] -- take care.
global debug2
global intSize
global realSize
global charSize
global booleanSize
t[0] = {}
if(debug2):
print("Printing Formal Parameters");
global variables;
global passByReference;
global stack
symbolTable = stack[len(stack)-1]
global formalParameterNo
for i in variables:
formalParameterNo += 1
currentOffset = symbolTable.offset
if(t[4]['type']=='INTEGER'):
symbolTable.offset = symbolTable.offset + intSize
elif(t[4]['type']=='REAL'):
symbolTable.offset = symbolTable.offset + realSize
elif(t[4]['type']=='CHAR'):
symbolTable.offset = symbolTable.offset + charSize
elif(t[4]['type']=='BOOLEAN'):
symbolTable.offset = symbolTable.offset + booleanSize
entry = VarEntry(i,t[4]['type'], currentOffset, formalParameterNo, passByReference)
#entry = VarEntry(i,t[4]['type'], 0, formalParameterNo, passByReference)
symbolTable.Insert(entry)
if(debug2):
print (i,t[4]['type']) , passByReference;
variables=[];
passByReference = False;
#print(t[4]);
t[0]['place'] = t[2]['place']
def p_forwardDeclaration(t):
'''forwardDeclaration : PROCEDURE '^' receiver ID createTable optionalFormalParameters popTable2''';
def p_popTable2(t):
'''popTable2 : '''
global stack
if(debug2):
print "popping symbol table"
oldSymbolTable = stack[len(stack)-2]
newSymbolTable = stack[len(stack)-1]
procName = t[-3];
returnType = t[-1]
var = VarEntry()
inputType = []
inputType2 = []
count = len(newSymbolTable.symbolDictionary)