-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.py
1442 lines (1249 loc) · 51.1 KB
/
ast.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
import decafparser as dp
classtable = {} # initially empty dictionary of classes.
staticdata = {}
lastmethod = 0
lastconstructor = 0
static_data_size = 0
treg = {}
# Class table. Only user-defined classes are placed in the class table.
def lookup(table, key):
if key in table:
return table[key]
else:
return None
def getmethodidbyname(c, m):
global classtable
for a in classtable[c.name].methods:
if str(a.name) == m:
return a.id
return None
def getsizeheap(c):
sizeheap = 0
for m in c.methods:
if m.storage != "static":
sizeheap += 1
return sizeheap
def find_static_var(classname, varname):
print "Find static var; classname {0}, varname {1}".format(classname, varname)
for keys,values in fstaticdata.items():
print "Key: {0} Value: {1}".format(keys, values.name)
if values.inclass.name is classname and values.name is varname:
print "STATIC %s (%s.%s)" % (keys, values.inclass.name, values.name)
return values
print "Not found"
return None
def addtotable(table, key, value):
table[key] = value
def print_ast():
for cid in classtable:
c = classtable[cid]
c.printout()
print "-----------------------------------------------------------------------------"
def typecheck():
global errorflag
errorflag = False
# add default constructors to all classes first!
for cid in classtable:
c = classtable[cid]
if not c.builtin:
c.add_default_constructor()
for cid in classtable:
c = classtable[cid]
c.typecheck()
return not errorflag
def initialize_ast():
# define In class:
cin = Class("In", None)
cin.builtin = True # this is a builtin class
cout = Class("Out", None)
cout.builtin = True # this, too, is a builtin class
scanint = Method('scan_int', cin, 'public', 'static', Type('int'))
scanint.update_body(SkipStmt(None)) # No line number information for the empty body
cin.add_method(scanint)
scanfloat = Method('scan_float', cin, 'public', 'static', Type('float'))
scanfloat.update_body(SkipStmt(None)) # No line number information for the empty body
cin.add_method(scanfloat)
printint = Method('print', cout, 'public', 'static', Type('void'))
printint.update_body(SkipStmt(None)) # No line number information for the empty body
printint.add_var('i', 'formal', Type('int')) # single integer formal parameter
cout.add_method(printint)
printfloat = Method('print', cout, 'public', 'static', Type('void'))
printfloat.update_body(SkipStmt(None)) # No line number information for the empty body
printfloat.add_var('f', 'formal', Type('float')) # single float formal parameter
cout.add_method(printfloat)
printboolean = Method('print', cout, 'public', 'static', Type('void'))
printboolean.update_body(SkipStmt(None)) # No line number information for the empty body
printboolean.add_var('b', 'formal', Type('boolean')) # single boolean formal parameter
cout.add_method(printboolean)
printstring = Method('print', cout, 'public', 'static', Type('void'))
printstring.update_body(SkipStmt(None)) # No line number information for the empty body
printstring.add_var('b', 'formal', Type('string')) # single string formal parameter
cout.add_method(printstring)
addtotable(classtable, "In", cin)
addtotable(classtable, "Out", cout)
def gettreg(c,var):
global treg
if treg.has_key(c):
for t in treg[c]:
if t is var:
return "t%d" % treg[c].index(var)
else:
treg[c] = []
treg[c].append(var)
return "t%d" % treg[c].index(var)
class Class:
"""A class encoding Classes in Decaf"""
global treg
def __init__(self, classname, superclass):
self.name = classname
self.superclass = superclass
self.fields = {} # dictionary, keyed by field name
self.constructors = []
self.methods = []
self.builtin = False
self.classSize = 0
def printout(self):
if (self.builtin):
return # Do not print builtin classes
print "-----------------------------------------------------------------------------"
print "Class Name: {0}".format(self.name)
sc = self.superclass
if (sc == None):
scname = ""
else:
scname = sc.name
print "Superclass Name: {0}".format(scname)
print "Fields:"
for f in self.fields:
(self.fields[f]).printout()
print "Constructors:"
for k in self.constructors:
k.printout()
print "Methods:"
for m in self.methods:
m.printout()
def typecheck(self):
global current_class
if (self.builtin):
return # Do not type check builtin classes
current_class = self
# First check if there are overlapping overloaded constructors and methods
n = len(self.constructors)
for i in range(0,n):
for j in range(i+1, n):
at1 = self.constructors[i].argtypes()
at2 = self.constructors[j].argtypes()
if (not subtype_or_incompatible(at1, at2)):
t1 = ",".join([str(t) for t in at1])
t2 = ",".join([str(t) for t in at2])
signal_type_error("Overlapping types in overloaded constructors: `{0}' (line {2}) and `{1}'".format(t1,t2, self.constructors[i].body.lines), self.constructors[j].body.lines)
n = len(self.methods)
for i in range(0,n):
for j in range(i+1, n):
if (self.methods[i].name != self.methods[j].name):
# Check only overloaded methods
break
at1 = self.methods[i].argtypes()
at2 = self.methods[j].argtypes()
if (not subtype_or_incompatible(at1, at2)):
t1 = ",".join([str(t) for t in at1])
t2 = ",".join([str(t) for t in at2])
signal_type_error("Overlapping types in overloaded methods: `{0}' (line {2}) and `{1}'".format(t1,t2, self.methods[i].body.lines), self.methods[j].body.lines)
for k in self.constructors:
k.typecheck()
# ensure it does not have a return statement
if (k.body.has_return() > 0):
signal_type_error("Constructor cannot have a return statement", k.body.lines)
for m in self.methods:
m.typecheck()
# ensure that non-void methods have a return statement on every path
if (m.rtype.is_subtype_of(Type('void'))):
if (isinstance(m.body, BlockStmt)):
m.body.stmtlist.append(ReturnStmt(None,m.body.lines))
else:
m.body = BlockStmt([m.body, ReturnStmt(None,m.body.lines)], mbody.lines)
else:
if (m.body.has_return() < 2):
signal_type_error("Method needs a return statement on every control flow path", m.body.lines)
def add_field(self, fname, field):
self.fields[fname] = field
gettreg(dp.current_class, field)
# Static / Non-static Field Size
# Update class size if the field is non-static
global static_data_size
if field.storage != "static":
self.classSize += 1
else:
staticdata[static_data_size] = field
static_data_size += 1
def add_constructor(self, constr):
self.constructors.append(constr)
def add_method(self, method):
self.methods.append(method)
def add_default_constructor(self):
# check if a parameterless constructor already exists
exists = False
for c in self.constructors:
if (len(c.vars.get_params()) == 0):
exists = True
break
if (not exists):
c = Constructor(self.name, 'public')
c.update_body(SkipStmt(None))
self.constructors.append(c)
def lookup_field(self, fname):
return lookup(self.fields, fname)
def is_subclass_of(self, other):
if (self.name == other.name):
return True
elif (self.superclass != None):
if (self.superclass == other):
return True
else:
return self.superclass.is_subclass_of(other)
return False
class Type:
"""A class encoding Types in Decaf"""
def __init__(self, basetype, params=None, literal=False):
if ((params == None) or (params == 0)):
if (basetype in ['int', 'boolean', 'float', 'string', 'void', 'error', 'null']):
self.kind = 'basic'
self.typename = basetype
elif (not literal):
self.kind = 'user'
self.baseclass = basetype
else:
self.kind = 'class_literal'
self.baseclass = basetype
else:
if (params == 1):
bt = basetype
else:
bt = Type(basetype, params=params-1)
self.kind = 'array'
self.basetype = bt
def __str__(self):
if (self.kind == 'array'):
return 'array(%s)'%(self.basetype.__str__())
elif (self.kind == 'user'):
return 'user(%s)'%str(self.baseclass.name)
elif (self.kind == 'class_literal'):
return 'class_literal(%s)'%str(self.baseclass.name)
else:
return self.typename
def __repr(self):
return self.__str__()
def is_subtype_of(self, other):
if (self.kind == 'basic'):
if other.kind == 'basic':
if (self.typename == other.typename):
return True
elif (self.typename == 'int') and (other.typename == 'float'):
return True
elif (self.typename == 'null'):
return (other.kind == 'user') or (other.kind == 'array')
elif (self.kind == 'user'):
if (other.kind == 'user'):
return self.baseclass.is_subclass_of(other.baseclass)
elif (self.kind == 'class_literal'):
if (other.kind == 'class_literal'):
return self.baseclass.is_subclass_of(other.baseclass)
elif (self.kind == 'array') and (other.kind =='array'):
return self.basetype.is_subtype_of(other.basetype)
return False
def isint(self):
return self.kind == 'basic' and self.typename == 'int'
def isnumeric(self):
return self.kind == 'basic' and (self.typename == 'int'
or self.typename == 'float')
def isboolean(self):
return self.kind == 'basic' and self.typename == 'boolean'
def isok(self):
return not (self.kind == 'basic' and self.typename == 'error')
class Field:
"""A class encoding fields and their attributes in Decaf"""
lastfield = 0
def __init__(self, fname, fclass, visibility, storage, ftype):
Field.lastfield += 1
self.name = fname
self.id = Field.lastfield
self.inclass = fclass
self.visibility = visibility # Public/Private
self.storage = storage # Static/Instance
self.type = ftype # Int/Float
def printout(self):
print "FIELD {0}, {1}, {2}, {3}, {4}, {5}".format(self.id, self.name, self.inclass.name, self.visibility, self.storage, self.type)
class Method:
"""A class encoding methods and their attributes in Decaf"""
def __init__(self, mname, mclass, visibility, storage, rtype):
global lastmethod
self.name = mname
lastmethod += 1
self.id = lastmethod
self.inclass = mclass
self.visibility = visibility
self.storage = storage
self.rtype = rtype
self.vars = VarTable()
self.tempreg = 0
def __repr__(self):
return "M_%s_%d" % (self.name, self.id)
def update_body(self, body):
self.body = body
def add_var(self, vname, vkind, vtype):
self.tempreg += self.vars.add_var(vname, vkind, vtype)
def printout(self):
print "METHOD: {0}, {1}, {2}, {3}, {4}, {5}".format(self.id, self.name, self.inclass.name, self.visibility, self.storage, self.rtype)
print "Method Parameters:",
print ', '.join(["%d"%v.id for v in self.vars.get_params()])
self.vars.printout()
print "Method Body:"
self.body.printout()
def argtypes(self):
return [v.type for v in self.vars.get_params()]
def typecheck(self):
global current_method
current_method = self
self.body.typecheck()
class Constructor:
"""A class encoding constructors and their attributes in Decaf"""
global treg
def __init__(self, cname, visibility):
global lastconstructor
self.name = cname
lastconstructor += 1
self.id = lastconstructor
self.visibility = visibility
self.vars = VarTable()
def update_body(self, body):
self.body = body
def add_var(self, vname, vkind, vtype):
self.vars.add_var(vname, vkind, vtype)
def printout(self):
print "CONSTRUCTOR: {0}, {1}".format(self.id, self.visibility)
print "Constructor Parameters:",
print ', '.join(["%d"%v.id for v in self.vars.get_params()])
self.vars.printout()
print "Constructor Body:"
self.body.printout()
def argtypes(self):
return [v.type for v in self.vars.get_params()]
def typecheck(self):
self.body.typecheck()
class VarTable:
""" Table of variables in each method/constructor"""
def __init__(self):
self.vars = {0:{}}
self.lastvar = 0
self.lastblock = 0
self.levels = [0]
self.localvar = 0
def enter_block(self):
self.lastblock += 1
self.levels.insert(0, self.lastblock)
self.vars[self.lastblock] = {}
def leave_block(self):
self.levels = self.levels[1:]
# where should we check if we can indeed leave the block?
def add_var(self, vname, vkind, vtype):
global treg
self.lastvar += 1
c = self.levels[0] # current block number
v = Variable(vname, self.lastvar, vkind, vtype)
vbl = self.vars[c] # list of variables in current block
vbl[vname] = v
if vkind is "local":
return 1
else:
return 0
def _find_in_block(self, vname, b):
if (b in self.vars):
# block exists
if (vname in self.vars[b]):
return self.vars[b][vname]
# Otherwise, either block b does not exist, or vname is not in block b
return None
def find_in_current_block(self, vname):
return self._find_in_block(vname, self.levels[0])
def find_in_scope(self, vname):
for b in self.levels:
v = self._find_in_block(vname, b)
if (v != None):
return v
# otherwise, locate in enclosing block until we run out
return None
def get_params(self):
outermost = self.vars[0] # 0 is the outermost block
vars = [outermost[vname] for vname in outermost if outermost[vname].kind=='formal']
vars_ids = [(v.id,v) for v in vars] # get the ids as well, so that we can order them
vars_ids.sort()
return [v for (i,v) in vars_ids] # in their order of definition!
def printout(self):
print "Variable Table:"
for b in range(self.lastblock+1):
for vname in self.vars[b]:
v = self.vars[b][vname]
v.printout()
class Variable:
""" Record for a single variable"""
def __init__(self, vname, id, vkind, vtype):
self.name = vname
self.id = id
self.kind = vkind
self.type = vtype
self.new = gettreg(dp.current_class, self)
# def __repr__(self):
# return "{0}".format(self.new)
def printout(self):
print "VARIABLE {0}, {1}, {2}, {3}".format(self.id, self.name, self.kind, self.type)
class Stmt(object):
""" Top-level (abstract) class representing all statements"""
class IfStmt(Stmt):
labelcount = 0
def __init__(self, condition, thenpart, elsepart, lines):
self.lines = lines
self.condition = condition
self.thenpart = thenpart
self.elsepart = elsepart
self.__typecorrect = None
self.type = "If"
def codegen(self):
condition_str = "%s\n\t" % (self.condition.codegen())
if str(self.elsepart.type) == 'Skip':
ifstmt_str = "bz %s IFEND%d\n" % (gettreg(dp.current_class, self.elsepart), IfStmt.labelcount)
then_str = "IF%d:\n\t%s\n" % (IfStmt.labelcount, self.thenpart.codegen())
else_str = "IFEND%d:\n" % (IfStmt.labelcount)
else:
ifstmt_str = "bz %s ELSE%d\n" % (gettreg(dp.current_class, self.elsepart), IfStmt.labelcount)
then_str = "IF%d:\n\t%s\n\tjmp IFEND%d\n" % (IfStmt.labelcount, self.thenpart.codegen(), IfStmt.labelcount)
else_str = "ELSE%d:\n\t%s\nIFEND%d:\n" % (IfStmt.labelcount, self.elsepart.codegen(), IfStmt.labelcount)
IfStmt.labelcount += 1
return condition_str + ifstmt_str + then_str + else_str
def printout(self):
print "If(",
self.condition.printout()
print ", ",
self.thenpart.printout()
print ", ",
self.elsepart.printout()
print ")"
def typecheck(self):
if (self.__typecorrect == None):
b = self.condition.typeof()
if (not b.isboolean()):
signal_type_error("Type error in If statement's condition: boolean expected, found {0}".format(str(b)), self.lines)
self.__typecorrect = False
self.__typecorrect = b.isboolean() and self.thenpart.typecheck() and self.elsepart.typecheck()
return self.__typecorrect
def has_return(self):
# 0 if none, 1 if at least one path has a return, 2 if all paths have a return
r = self.thenpart.has_return() + self.elsepart.has_return()
if (r == 4):
return 2
elif (r > 0):
return 1
else:
return 0
class WhileStmt(Stmt):
labelcount = 0
def __init__(self, cond, body, lines):
self.lines = lines
self.cond = cond
self.body = body
self.__typecorrect = None
self.type = "While"
def codegen(self):
temp = gettreg(dp.current_class, "temp")
if str(self.body.type) == 'Skip':
return ''
else:
while_str = "WHILE%d:\n\t%s\n\t" % (WhileStmt.labelcount, self.cond.codegen())
condition_str = "bz %s WEXIT%d\n\t" % (temp, WhileStmt.labelcount)
body_str = "%s\n\tjmp WHILE%d\n" % (self.body.codegen(), WhileStmt.labelcount)
exit_str = "WEXIT%d:\n" % (WhileStmt.labelcount)
WhileStmt.labelcount += 1
return while_str + condition_str + body_str + exit_str
def printout(self):
print "While(",
self.cond.printout()
print ", ",
self.body.printout()
print ")"
def typecheck(self):
if (self.__typecorrect == None):
b = self.cond.typeof()
if (not b.isboolean()):
signal_type_error("Type error in While statement's condition: boolean expected, found {0}".format(str(b)), self.lines)
self.__typecorrect = False
self.__typecorrect = b.isboolean() and self.body.typecheck()
return self.__typecorrect
def has_return(self):
# 0 if none, 1 if at least one path has a return, 2 if all paths have a return
if (self.body.has_return() > 0):
return 1
else:
return 0
class ForStmt(Stmt):
labelcount = 0
def __init__(self, init, cond, update, body, lines):
self.lines = lines
self.init = init # 1st var
self.cond = cond # 2nd var
self.update = update # 3rd var
self.body = body # body
self.__typecorrect = None
self.type="For"
def codegen(self):
temp = gettreg(dp.current_class, "temp")
forlabel = "For%ds:\n" % ForStmt.labelcount
forinitstr = "\t%s\n" % self.init.codegen()
forloopstart="For%d:\n" % ForStmt.labelcount
forcond = "\t%s\n" % self.cond.codegen()
forcondjmp = "\tbz %s, For%de\n" % (temp, ForStmt.labelcount)
forupdate = "\t%s\n" % self.update.codegen()
forbody = "\t%s\n" % self.body.codegen()
forloopback = "\tjmp For%d\n" % ForStmt.labelcount
fordone = "For%de:\n" % ForStmt.labelcount
ForStmt.labelcount += 1
return "{0}{1}{2}{3}{4}{5}{6}{7}{8}".format(forlabel, forinitstr, forloopstart, forcond, forcondjmp, forupdate, forbody, forloopback, fordone)
def printout(self):
print "For(",
if (self.init != None):
self.init.printout()
print ", ",
if (self.cond != None):
self.cond.printout()
print ", ",
if (self.update != None):
self.update.printout()
print ", ",
self.body.printout()
print ")"
def typecheck(self):
if (self.__typecorrect == None):
a = True
if (self.init != None):
a = a and self.init.typeof().isok()
if (self.update != None):
a = a and self.update.typeof().isok()
if (self.cond != None):
b = self.cond.typeof()
if (not b.isboolean()):
signal_type_error("Type error in For statement's condition: boolean expected, found {0}".format(str(b)), self.lines)
a = False
a = a and self.body.typecheck()
self.__typecorrect = a
return self.__typecorrect
def has_return(self):
# 0 if none, 1 if at least one path has a return, 2 if all paths have a return
if (self.body.has_return() > 0):
return 1
else:
return 0
class ReturnStmt(Stmt):
def __init__(self, expr, lines):
self.lines = lines
self.expr = expr
self.type = "Return"
self.__typecorrect = None
def printout(self):
print "Return(",
if (self.expr != None):
self.expr.printout()
print ")"
def typecheck(self):
global current_method
if (self.__typecorrect == None):
if (self.expr == None):
argtype = Type('void')
else:
argtype = self.expr.typeof()
self.__typecorrect = argtype.is_subtype_of(current_method.rtype)
if (argtype.isok() and (not self.__typecorrect)):
signal_type_error("Type error in Return statement: {0} expected, found {1}".format(str(current_method.rtype), str(argtype)), self.lines)
return self.__typecorrect
def codegen(self):
if str(self.expr) != None:
return "\tret\n"
else:
return "{0}\n\tret\n".format(self.expr)
def has_return(self):
return 2
class BlockStmt(Stmt):
def __init__(self, stmtlist, lines):
self.lines = lines
self.stmtlist = [s for s in stmtlist if (s != None) and (not isinstance(s, SkipStmt))]
self.__typecorrect = None
self.type = "Block"
def codegen(self):
blockStmt_str = ''
for s in self.stmtlist:
if s.type != "Skip":
blockStmt_str += s.expr.codegen()
return blockStmt_str
def printout(self):
print "Block(["
if (len(self.stmtlist) > 0):
self.stmtlist[0].printout()
for s in self.stmtlist[1:]:
print ", ",
s.printout()
print "])"
def typecheck(self):
if (self.__typecorrect == None):
self.__typecorrect = all([s.typecheck() for s in self.stmtlist])
return self.__typecorrect
def has_return(self):
rs = [s.has_return() for s in self.stmtlist]
if (2 in rs):
return 2
elif (1 in rs):
return 1
else:
return 0
class BreakStmt(Stmt):
def __init__(self, lines):
self.lines = lines
self.__typecorrect = True
self.type = "Break"
def printout(self):
print "Break"
def codegen(self):
return "\tret\n"
def typecheck(self):
return self.__typecorrect
def has_return(self):
return 0
class ContinueStmt(Stmt):
def __init__(self, lines):
self.lines = lines
self.__typecorrect = True
self.type = "Continue"
def codegen(self):
return "\tret\n"
def printout(self):
print "Continue"
def typecheck(self):
return self.__typecorrect
def has_return(self):
return 0
class ExprStmt(Stmt):
def __init__(self, expr, lines):
self.lines = lines
self.expr = expr
self.type = "Expr"
self.__typecorrect = None
def printout(self):
print "Expr(",
self.expr.printout()
print ")"
def typecheck(self):
if (self.__typecorrect == None):
if (self.expr.typeof().kind == 'error'):
self.__typecorrect = False
else:
self.__typecorrect = True
return self.__typecorrect
def has_return(self):
return 0
class SkipStmt(Stmt):
def __init__(self, lines):
self.lines = lines
self.type = "Skip"
self.__typecorrect = True
def printout(self):
print "Skip"
def typecheck(self):
return self.__typecorrect
def has_return(self):
return 0
class Expr(object):
'''Class representing all expressions in Decaf'''
def __repr__(self):
return "Unknown expression"
def printout(self):
print self,
class ConstantExpr(Expr):
def __init__(self, kind, arg=None, lines=None):
self.lines = lines
self.kind = kind
if (kind=='int'):
self.int = arg
elif (kind == 'float'):
self.float = arg
elif (kind == 'string'):
self.string = arg
self.__typeof = None
def __repr__(self):
s = "Unknown"
if (self.kind == 'int'):
s = "%d"%self.int
elif (self.kind == 'float'):
s = "%g"%self.float
elif (self.kind == 'string'):
s = "%s"%self.string
elif (self.kind == 'Null'):
s = "Null"
elif (self.kind == 'True'):
s = "True"
elif (self.kind == 'False'):
s = "False"
return "{0}".format(s)
def codegen(self):
return self
def typeof(self):
if (self.__typeof == None):
if (self.kind == 'int'):
self.__typeof = Type('int')
elif (self.kind == 'float'):
self.__typeof = Type('float')
elif (self.kind == 'string'):
self.__typeof = Type('string')
elif (self.kind == 'Null'):
self.__typeof = Type('null')
elif (self.kind == 'True'):
self.__typeof = Type('boolean')
elif (self.kind == 'False'):
self.__typeof = Type('boolean')
return self.__typeof
class VarExpr(Expr):
def __init__(self, var, lines):
self.lines = lines
self.var = var
self.__typeof = None
def __repr__(self):
# if self.var not in tmpreg:
# tmpreg.append(self.var)
return "{0}".format(gettreg(dp.current_class, self.var))
def typeof(self):
if (self.__typeof == None):
self.__typeof = self.var.type
return self.__typeof
class UnaryExpr(Expr):
labelcount = 0
def __init__(self, uop, expr, lines):
self.lines = lines
self.uop = uop
self.arg = expr
self.__typeof = None
def __repr__(self):
return "Unary({0}, {1})".format(self.uop, self.arg)
def typeof(self):
if (self.__typeof == None):
argtype = self.arg.typeof()
self.__typeof = Type('error')
if (self.uop == 'uminus'):
if (argtype.isnumeric()):
self.__typeof = argtype
elif (argtype.kind != 'error'):
# not already in error
signal_type_error("Type error in unary minus expression: int/float expected, found {0}".format(str(argtype)), self.arg.lines)
elif (self.uop == 'neg'):
if (argtype.isboolean()):
self.__typeof = argtype
elif (argtype.kind != 'error'):
# not already in error
signal_type_error("Type error in unary negation expression: boolean expected, found {0}".format(str(argtype)), self.arg.lines)
return self.__typeof
def signal_bop_error(argpos, bop, argtype, arg, possible_types, ptype_string):
if (argtype.kind not in (['error'] + possible_types)):
# not already in error
signal_type_error("Type error in {0} argument of binary {1} expression: {2} expected, found {3}".format(argpos, bop, ptype_string, str(argtype)), arg.lines)
class BinaryExpr(Expr):
def __init__(self, bop, arg1, arg2, lines):
self.lines = lines
self.bop = bop
self.arg1 = arg1
self.arg2 = arg2
self.__typeof = None
def __repr__(self):
return "Binary({0}, {1}, {2})".format(self.bop,self.arg1,self.arg2)
def codegen(self):
temp = gettreg(dp.current_class, "temp")
if type(self.arg1) == ConstantExpr or type(self.arg2) == ConstantExpr:
if str(self.arg1.typeof()) == 'int' and str(self.arg2.typeof()) == 'int':
if type(self.arg2) == ConstantExpr:
binary_str = "move_immed_i %s, %s" % (temp, self.arg2)
return binary_str + "\n\ti%s %s, %s, %s" % (self.bop, temp, self.arg1, temp)
return "i%s %s, %s, %s" % (self.bop, temp, self.arg1, self.arg2)
else:
if(self.bop == 'mod'):
print "cannot perform mod with floating point"
sys.exit(0)
return "f%s %s, %s, %s" % (self.bop, temp, self.arg1, self.arg2)
else:
if str(self.arg1.var.type) == 'int' and str(self.arg2.var.type) == 'int':
return "i%s %s, %s, %s" % (self.bop, temp, self.arg1, self.arg2)
else:
if(self.bop == 'mod'):
print "cannot perform mod with floating point"
sys.exit(0)
return "f%s %s, %s, %s" % (self.bop, temp, self.arg1, self.arg2)
def typeof(self):
if (self.__typeof == None):
arg1type = self.arg1.typeof()
arg2type = self.arg2.typeof()
self.__typeof = Type('error')
if (self.bop in ['add', 'sub', 'mul', 'div']):
if (arg1type.isint()) and (arg2type.isint()):
self.__typeof = arg1type
elif (arg1type.isnumeric()) and (arg2type.isnumeric()):
self.__typeof = Type('float')
else:
if (arg1type.isok() and arg2type.isok()):
signal_bop_error('first', self.bop, arg1type, self.arg1,
['int', 'float'], 'int/float')
signal_bop_error('second', self.bop, arg2type, self.arg2,
['int', 'float'], 'int/float')
elif (self.bop in ['lt', 'leq', 'gt', 'geq']):
if ((arg1type.isnumeric()) and (arg2type.isnumeric())):
self.__typeof = Type('boolean')
else:
if (arg1type.isok() and arg2type.isok()):
signal_bop_error('first', self.bop, arg1type, self.arg1,
['int', 'float'], 'int/float')
signal_bop_error('second', self.bop, arg2type, self.arg2,
['int', 'float'], 'int/float')
elif (self.bop in ['and', 'or']):
if ((arg1type.isboolean()) and (arg2type.isboolean())):
self.__typeof = Type('boolean')
else:
if (arg1type.isok() and arg2type.isok()):
signal_bop_error('first', self.bop, arg1type, self.arg1,
['boolean'], 'boolean')
signal_bop_error('second', self.bop, arg2type, self.arg2,
['boolean'], 'boolean')
else:
# equality/disequality
if ((arg1type.isok()) and (arg2type.isok())):
if ((arg1type.is_subtype_of(arg2type)) or (arg2type.is_subtype_of(arg1type))):
self.__typeof = Type('boolean')
else:
signal_type_error('Type error in arguments of binary {0} expression: compatible types expected, found {1} and {2}'.format(self.bop, str(arg1type), str(arg2type)), self.lines)
return self.__typeof
class AssignExpr(Expr):
def __init__(self, lhs, rhs, lines):
self.lines = lines
self.lhs = lhs
self.rhs = rhs
self.__typeof = None
def codegen(self):
lhstype = self.lhs.typeof().typename
temp = gettreg(dp.current_class, "temp")
if type(self.rhs) == BinaryExpr:
if type(self.rhs.arg2) == ConstantExpr:
if self.rhs.arg2.typeof().typename == "float":
return "move_immed_f {0} {1}\n\ti{2} {3} {4} {5}".format(temp, self.rhs.arg2, self.rhs.bop, gettreg(dp.current_class, self.lhs.var), self.rhs.arg1, temp)
else:
return "move_immed_i {0} {1}\n\ti{2} {3} {4} {5}".format(temp, self.rhs.arg2, self.rhs.bop, gettreg(dp.current_class, self.lhs.var), self.rhs.arg1, temp)
else:
return "i{0} {1} {2} {3}".format(self.rhs.bop, self.lhs.var, self.rhs.arg1, self.rhs.arg2)
elif type(self.rhs) == VarExpr:
return "move {0} {1}".format(self.lhs, self.rhs)
elif type(self.rhs) == UnaryExpr:
if(self.rhs.uop == 'uminus'):
if type(self.rhs.arg) == ConstantExpr:
return "move_immed_i %s -%s\n" % (self.lhs, self.rhs.arg)
if(str(self.rhs.arg.var.type) == 'int'):
return "move_immed_i %s -1\n\timul %s, %s, %s" % (temp, self.lhs, self.rhs.arg, temp)
else:
return "move_immed_f %s -1\n\tfmul %s, %s, %s" % (temp, self.lhs, self.rhs.arg, temp)
else:
unary_str = "bz %s, T%d\n\t" % (self.lhs, UnaryExpr.labelcount)
iftrue_str = "move_immed_i %s, 0\n\tjmp T%d\n" % (self.lhs, UnaryExpr.labelcount+1)
iffalse_str = "T%d:\n\tmove_immed_i %s, 1\nT%d:" % (UnaryExpr.labelcount, self.lhs, UnaryExpr.labelcount+1)