-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag_parser.py
1656 lines (1415 loc) · 62.8 KB
/
tag_parser.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
from CodeGenTools import ConstantTable, LabelGen, VariableTable, ConstantFucntionsManager, SymbolTable
import sexprs
class AbstractSchemeExpr:
@staticmethod
def parseRec(input):
isSuccess, parsingObject = ConstantFactory.parseRec(input)
if(isSuccess):
return parsingObject
elif(AbstractLambda.instanceof(input)):
return LambdaFactory.CreateLambda(input)
elif(QuasiQuote.instanceof(input)):
return AbstractSchemeExpr.parseRec(QuasiQuote.MyExpandQQ(input))
elif(Def.instanceof(input)):
return Def(input)
elif(IfThenElse.instanceof(input)):
return IfThenElse(input)
elif(Or.instanceof(input)):
return Or(input)
elif(Cond.instanceof(input)):
return Cond.ConvertToIf(input)
elif(And.instanceof(input)):
return And.ConvertToIf(input)
elif(Let.instanceof(input)):
return Let.ConvertToApplic(input)
elif(LetAsterisk.instanceof(input)):
return LetAsterisk.Parse(input)
elif(Letrec.instanceof(input)):
return Letrec.ConvertToYag(input)
elif(Applic.instanceof(input)):
return Applic(input)
elif(Variable.instanceof(input)):
return Variable(input)
elif(isinstance(input, AbstractSchemeExpr)):
return input
else:
return False
@staticmethod
def parse(input):
result, rem = sexprs.AbstractSexpr.readFromString(input)
return AbstractSchemeExpr.parseRec(result), rem
def semantic_analysis(self):
return self.debruijn().annotateTC()
OutputCode = ""
TempOutputCode = ""
def Enterl(self, line):
self.OutputCode += line
self.OutputCode += "\n"
def EnterT(self, line):
self.TempOutputCode += line
self.TempOutputCode += "\n"
def EnterTTab(self,line):
self.TempOutputCode+=("\t"+line+"\n")
def Comment(self, desc):
self.TempOutputCode += "//"
self.TempOutputCode += desc
self.TempOutputCode += "\n"
def CodeGenRec(self):
self.EnterTTab('printf("%s", "TBD");')
return self.TempOutputCode
def code_gen(self):
return self.CodeGenRec()
def __str__(self):
return ""
def debruijn(self):
return self.debrujinParams(self,[[]],[])
def debrujinParams(self,e,B,p):
if isinstance(e,Variable):
if str(e) in p:
minor=p.index(str(e))
return VarParam(e,minor)
elif findBound(e,B)!=-1:
major,minor=findBound(e,B)
return VarBound(e,major,minor)
else:
return VarFree(e)
elif isinstance(e,LambdaSimple):
return LambdaSimple(e.Params,self.debrujinParams(e.Body,[p]+B,list(map(str,e.Params))))
elif isinstance(e,LambdaVar):
return LambdaVar(e.OneParam,self.debrujinParams(e.Body,[p]+B,[str(e.OneParam)]))
elif isinstance(e,LambdaOpt):
return LambdaOpt(e.Params,self.debrujinParams(e.Body,[p]+B,list(map(str,e.Params))))
elif isinstance(e,Applic):
newParams=list()
for param in e.ParamList:
newParams.append( self.debrujinParams(param,B,p))
e.ParamList=newParams
e.Lambda = self.debrujinParams(e.Lambda,B,p)
return e
elif isinstance(e,Def):
e.variable = self.debrujinParams(e.variable,B,p)
e.Value= self.debrujinParams(e.Value,B,p)
return e
elif isinstance(e,IfThenElse):
e.IfCondition=self.debrujinParams(e.IfCondition,B,p)
e.IfTrue=self.debrujinParams(e.IfTrue,B,p)
e.IfFalse=self.debrujinParams(e.IfFalse,B,p)
return e
elif isinstance(e,Or):
OrList=[]
for item in e.OrConditions:
OrList.append(self.debrujinParams(item,B,p))
e.OrConditions=OrList
return e
else:
return e
def annotateTC(self):
return self.Atp(self, False)
def Atp(self, exp, tp):
if(isinstance(exp, Or)):
NewLastCond = self.Atp(exp.OrConditions.pop(), tp)
NewOrConditions = list(map((lambda x: self.Atp(x, False)),exp.OrConditions))
NewOrConditions.append(NewLastCond)
exp.OrConditions = NewOrConditions
elif (isinstance(exp, Def)):
exp.Value = self.Atp(exp.Value, False)
elif (isinstance(exp, IfThenElse)):
exp.IfCondition = self.Atp(exp.IfCondition, False)
exp.IfTrue = self.Atp(exp.IfTrue, tp)
exp.IfFalse = self.Atp(exp.IfFalse, tp)
elif (isinstance(exp, AbstractLambda)):
exp.Body = self.Atp(exp.Body, True)
elif(isinstance(exp, Applic)):
if(tp):
exp = ApplicTP(self.Atp(exp.Lambda, False), list(map((lambda x: self.Atp(x, False)), exp.ParamList) ))
else:
exp.Lambda = self.Atp(exp.Lambda, False)
exp.ParamList = list(map((lambda x: self.Atp(x, False)), exp.ParamList))
return exp
def findBound(e,B):
for i,lst in enumerate(B):
for j,boundVar in enumerate(lst):
if str(boundVar) == str(e):
return i, j
return -1
def NextItem(input):
Next = input.Item2
if(not isinstance(Next, sexprs.Pair)):
return False
return Next
def StartWith(Prefix, input):
if(isinstance(input, sexprs.Pair)):
Label = input.Item1
return (isinstance(Label, sexprs.Symbol) and (str(Label) == Prefix))
else:
return False
class SyntaxError(Exception):
pass
class QuasiQuote:
@staticmethod
def instanceof(instance):
item = instance
return ((isinstance(item,sexprs.Pair)) and (isinstance(item.Item1,sexprs.Symbol)) and (str(item.Item1)=="QUASIQUOTE"))
@staticmethod
def MyExpandQQ(MyE):
e = MyE.Item2.Item1
return QuasiQuote.ExpandQQ(e)
@staticmethod
def ExpandQQ(e):
if(QuasiQuote.Unqouted(e)):
return e.Item2.Item1
elif(QuasiQuote.UnqouteSplicing(e)):
print("unquote-splicing here makes no sense!")
raise SyntaxError
elif ((isinstance(e,sexprs.Pair))):
if QuasiQuote.UnqouteSplicing(e.Item1):
if(isinstance(e.Item2,sexprs.Nil)):
return sexprs.Pair(sexprs.Symbol("append"), sexprs.Pair((((e.Item1).Item2)).Item1, sexprs.Nil()))
else:
return sexprs.Pair(sexprs.Symbol("append"), sexprs.Pair((((e.Item1).Item2)).Item1,sexprs.Pair(QuasiQuote.ExpandQQ(e.Item2), sexprs.Nil())))
elif QuasiQuote.UnqouteSplicing(e.Item2):
return sexprs.Pair(sexprs.Symbol("cons"),sexprs.Pair(QuasiQuote.ExpandQQ(e.Item1),sexprs.Pair(((e.Item2).Item2).Item1, sexprs.Nil())))
else:
return sexprs.Pair(sexprs.Symbol("cons"),sexprs.Pair(QuasiQuote.ExpandQQ(e.Item1),sexprs.Pair(QuasiQuote.ExpandQQ(e.Item2), sexprs.Nil())))
elif((isinstance(e,sexprs.Vector))):
return sexprs.Pair(sexprs.Symbol("list->vector"),sexprs.Pair(QuasiQuote.ExpandQQ(QuasiQuote.VectorToList(e.values)) ,sexprs.Nil()))
elif((isinstance(e,sexprs.Nil)) or (isinstance(e,sexprs.Symbol))):
return sexprs.Pair(sexprs.Symbol("quote"),sexprs.Pair(e,sexprs.Nil()))
else:
return e
@staticmethod
def VectorToList(items):
if items:
return sexprs.Pair(items[0], QuasiQuote.VectorToList(items[1:]))
else:
return sexprs.Nil()
@staticmethod
def Qoute(tag,e):
return ((isinstance(e,sexprs.Pair)) and
(str(e.Item1)==tag) and
(isinstance(e.Item2,sexprs.Pair)) and
(isinstance(e.Item2.Item2,sexprs.Nil)))
@staticmethod
def Unqouted(q):
return QuasiQuote.Qoute("UNQUOTE", q)
@staticmethod
def UnqouteSplicing(q):
return QuasiQuote.Qoute("UNQUOTE-SPLICING", q)
class ConstantFactory:
@staticmethod
def parseRec(input):
return ConstantFactory.InnerParseRec(input, False)
@staticmethod
def InnerParseRec(input, IsInQoute):
if(IntegerConstant.instanceof(input)):
return (True, IntegerConstant(input))
elif(BooleanConstant.instanceof(input)):
return (True, BooleanConstant(input))
elif(FractionConstant.instanceof(input)):
return (True, FractionConstant(input))
elif(CharConstant.instanceof(input)):
return (True,CharConstant(input))
elif(VoidConstant.instanceof(input)):
return (True,VoidConstant(input))
elif(StringConstant.instanceof(input)):
return (True,StringConstant(input))
elif(IsInQoute):
if(SymbolConstant.instanceof(input)):
return (True,SymbolConstant(input))
elif(PairConstant.instanceof(input)):
return (True,PairConstant(input))
elif(NilConstant.instanceof(input)):
return (True,NilConstant(input))
elif(VectorConstant.instanceof(input)):
return (True,VectorConstant(input))
elif((not IsInQoute) and (isinstance(input,sexprs.Pair)) and \
(isinstance(input.Item1,sexprs.Symbol)) and \
(str(input.Item1)=="QUOTE")):
return ConstantFactory.InnerParseRec(input.Item2.Item1, True)
else:
return (False, False)
class Constant(AbstractSchemeExpr):
def __init__(self,var):
self.var=var
self.value = 0 #Dummy
# This section is importent for the hash table of ConstantTable class
value = 0
def __hash__(self):
return hash((self.__class__.__name__, self.value))
def __eq__(self, other):
return (self.__class__.__name__, self.value) == (other.__class__.__name__, other.value)
def __str__(self):
return str(self.var)
def CodeGenRec(self):
# correct only for constant that save in the memory: tag and then value in length 1
self.EnterTTab("MOV(R0," + str(ConsTable.GetAddr(self)) + ");")
return self.TempOutputCode
# This function tell the ConstantTable class what is the size of this constant in the memory
def SpaceInMemory(self):
return 2
# This function tell the ConstantTable class how to enter the constant to the memory
def EnterToConstantTable(self):
ConstatTableOutputCode = ""
ConstatTableOutputCode += "// Enter constant " + self.__class__.__name__ + " to Constant table \n"
ConstatTableOutputCode += ("PUSH(" + str(self.value) + "); \n")
ConstatTableOutputCode += "CALL(" + self.CreatorInMemFunction() + "); \n"
ConstatTableOutputCode +="DROP(1); \n"
return ConstatTableOutputCode
def CreatorInMemFunction(self):
pass
class BooleanConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Boolean)
def __init__(self,var):
super(BooleanConstant,self).__init__(var)
self.value = int(self.var.value)
def CreatorInMemFunction(self):
return "MAKE_SOB_BOOL"
class FractionConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Fraction)
def __init__(self,var):
super(FractionConstant,self).__init__(var)
self.Numerator = self.var.Numerator
self.Denominator = self.var.Denominator
self.value = str(self.Numerator) + str(self.Denominator)
def EnterToConstantTable(self):
ConstatTableOutputCode = ""
ConstatTableOutputCode += "// Enter constant " + self.__class__.__name__ + " to Constant table \n"
ConstatTableOutputCode += ("PUSH(" + str(self.Denominator) + "); \n")
ConstatTableOutputCode += ("PUSH(" + str(self.Numerator) + "); \n")
ConstatTableOutputCode += "CALL(" + self.CreatorInMemFunction() + "); \n"
ConstatTableOutputCode +="DROP(2); \n"
return ConstatTableOutputCode
def CreatorInMemFunction(self):
return "MAKE_SOB_FRACTION"
def SpaceInMemory(self):
return 3
class IntegerConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Integer)
def __init__(self,var):
super(IntegerConstant,self).__init__(var)
self.value = self.var.value
def CreatorInMemFunction(self):
return "MAKE_SOB_INTEGER"
class CharConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Char)
def __init__(self,var):
super(CharConstant,self).__init__(var)
char=self.var.sym
if(char=='newline'):
self.value=10
elif(char=='return'):
self.value=13
elif(char=='tab'):
self.value=9
elif(char=='page'):
self.value=12
elif(char=='lambda'):
self.value=0x03bb
elif(char[0]=='x'):
self.value=('0'+char)
else:
self.value = ord(self.var.sym) #ord - get ascii value
def CreatorInMemFunction(self):
return "MAKE_SOB_CHAR"
class VoidConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Void)
def CreatorInMemFunction(self):
return "MAKE_SOB_VOID"
def SpaceInMemory(self):
return 1
class NilConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Nil)
def CreatorInMemFunction(self):
return "MAKE_SOB_NIL"
def SpaceInMemory(self):
return 1
class StringConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.String)
def __init__(self,var):
super(StringConstant,self).__init__(var)
self.value = self.var.sym
self.AsciiString = [ord(c) for c in self.value] #ord - get ascii value
def EnterToConstantTable(self):
ConstatTableOutputCode = ""
ConstatTableOutputCode += "// Enter constant StringConstant to Constant table \n"
ConstatTableOutputCode += "// Enter all the char in ascii to the stack \n"
for char in self.AsciiString :
ConstatTableOutputCode += ("PUSH(" + str(char) + "); \n")
ConstatTableOutputCode += "// Enter length of string to the stack \n"
ConstatTableOutputCode += ("PUSH(" + str(len(self.AsciiString )) + "); \n")
ConstatTableOutputCode += "CALL(MAKE_SOB_STRING); \n"
ConstatTableOutputCode +="DROP("+ str(len(self.AsciiString ) + 1) +"); \n"
return ConstatTableOutputCode
def SpaceInMemory(self):
return len(self.AsciiString) + 2
class SymbolConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Symbol)
def __init__(self,var):
super(SymbolConstant,self).__init__(var)
self.value = StringConstant(sexprs.String(str(var)))
def CreatorInMemFunction(self):
return "MAKE_SOB_SYMBOL"
def EnterToConstantTable(self):
SymTable.AddSymbol(self)
self.value = ConsTable.GetAddr(self.value)
return super(SymbolConstant,self).EnterToConstantTable()
class PairConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Pair)
def __init__(self,var):
super(PairConstant,self).__init__(var)
#todo - maybe to change the dummy to some validy check
dummy, self.Item1 = ConstantFactory.InnerParseRec(var.Item1, True)
dummy, self.Item2 = ConstantFactory.InnerParseRec(var.Item2, True)
self.value = str(var)
def SpaceInMemory(self):
return 3
# This function tell the ConstantTable class how to enter the constant to the memory
def EnterToConstantTable(self):
self.Item1 = ConsTable.GetAddr(self.Item1)
self.Item2 = ConsTable.GetAddr(self.Item2)
ConstatTableOutputCode = ""
ConstatTableOutputCode += "// Enter constant " + self.__class__.__name__ + " to Constant table \n"
ConstatTableOutputCode += ("PUSH(" + str(self.Item2) + "); \n")
ConstatTableOutputCode += ("PUSH(" + str(self.Item1) + "); \n")
ConstatTableOutputCode += "CALL(" + self.CreatorInMemFunction() + "); \n"
ConstatTableOutputCode +="DROP(2); \n"
return ConstatTableOutputCode
def CreatorInMemFunction(self):
return "MAKE_SOB_PAIR"
class VectorConstant(Constant):
@staticmethod
def instanceof(instance):
return isinstance(instance,sexprs.Vector)
def __init__(self,var):
super(VectorConstant,self).__init__(var)
self.size = len(var.values)
self.values = []
for cons in var.values:
#todo - maybe to change the dummy to some validy check
dummy, cons = ConstantFactory.InnerParseRec(cons, True)
self.values.append(cons)
self.value = ""
for x in self.values:
self.value += " "
self.value += str(x.value)
def SpaceInMemory(self):
return 2 + self.size
# This function tell the ConstantTable class how to enter the constant to the memory
def EnterToConstantTable(self):
ConstatTableOutputCode = ""
ConstatTableOutputCode += "// Enter constant " + self.__class__.__name__ + " to Constant table \n"
for cons in self.values:
cons = ConsTable.GetAddr(cons)
ConstatTableOutputCode += ("PUSH(" + str(cons) + "); \n")
ConstatTableOutputCode += ("PUSH(" + str(self.size) + "); \n")
ConstatTableOutputCode += "CALL(" + self.CreatorInMemFunction() + "); \n"
ConstatTableOutputCode +="DROP(" + str(1 + self.size) + "); \n"
return ConstatTableOutputCode
def CreatorInMemFunction(self):
return "MAKE_SOB_VECTOR"
class Variable(AbstractSchemeExpr):
def __init__(self,con):
if(isinstance(con, sexprs.Pair)):
self.con=con.Item1
else:
self.con=con
@staticmethod
def instanceof(instance):
if(isinstance(instance, sexprs.Pair)):
item = instance.Item1
else:
item = instance
return isinstance(item, sexprs.Symbol)
def __str__(self):
return str(self.con)
class VarFree(Variable):
def __init__(self,e):
super(VarFree,self).__init__(str(e))
VarTable.AddFreeVar(self.__str__())
def __str__(self):
return super(VarFree,self).__str__()
def CodeGenRec(self):
self.Comment("---------------------------------Free Var Begin-------------------------------------------------")
self.EnterTTab("MOV(R0, IND(" + VarTable.GetAddress(self.__str__()) + "));")
self.Comment("---------------------------------Free Var End---------------------------------------------------")
return self.TempOutputCode
class VarParam(Variable):
def __init__(self,e,minor):
super(VarParam,self).__init__(str(e))
self.minor=minor
def __str__(self):
return super(VarParam,self).__str__()
def CodeGenRec(self):
self.EnterTTab("MOV(R0,FPARG("+ str(self.minor+2)+ "));//variable is "+ str(self.minor) +" in the stack ")
return self.TempOutputCode
class VarBound(Variable):
def __init__(self,e,major,minor):
super(VarBound,self).__init__(str(e))
self.major=major
self.minor=minor
def __str__(self):
return super(VarBound,self).__str__()
def CodeGenRec(self):
self.EnterTTab("PUSH(R1);")
self.EnterTTab("MOV(R1,FPARG(0));")
self.EnterTTab("MOV(R0,INDD(R1,"+str(self.major+2) +"));//R0 will have the proper major")
self.EnterTTab("MOV(R0,INDD(R0,"+ str(self.minor+1) +"));//R0 will have the proper minor")
self.EnterTTab("POP(R1);")
return self.TempOutputCode
class IfThenElse(AbstractSchemeExpr):
def __init__(self,statment):
Cond = NextItem(statment)
self.IfCondition = AbstractSchemeExpr.parseRec(Cond.Item1)
TrueOperand = NextItem(Cond)
self.IfTrue = AbstractSchemeExpr.parseRec(TrueOperand.Item1)
ElseOperands = TrueOperand.Item2
NilExcepted = ""
if(not isinstance(ElseOperands, sexprs.Pair)):
self.IfFalse = AbstractSchemeExpr.parseRec(sexprs.Void()) #fixed
NilExcepted = ElseOperands
else:
self.IfFalse = AbstractSchemeExpr.parseRec(ElseOperands.Item1)
NilExcepted = ElseOperands.Item2
if(not isinstance(NilExcepted, sexprs.Nil)):
raise SyntaxError
@staticmethod
def instanceof(instance):
if(isinstance(instance, sexprs.Pair)):
IfLabel = instance.Item1
return (isinstance(IfLabel, sexprs.Symbol) and (str(IfLabel) == "IF"))
else:
return False
def CodeGenRec(self):
self.Comment("<<<<<<<<<<<<<<< IF then else statment begin >>>>>>>>>>>>>>>")
self.EnterT(" ")
self.TempOutputCode += self.IfCondition.CodeGenRec()
self.EnterTTab("CMP (R0," + ConsTable.GetAddr(MyBoolConstantFalse) + ");")
FalseLabel = LabelGen.Next("iffalse")
ExitLabel = LabelGen.Next("ifexit")
self.EnterTTab("JUMP_EQ(" + FalseLabel + ");")
self.TempOutputCode += self.IfTrue.CodeGenRec()
self.EnterTTab("JUMP(" + ExitLabel + ");")
self.EnterT(FalseLabel + ":")
self.TempOutputCode += self.IfFalse.CodeGenRec()
self.EnterT(ExitLabel + ":")
self.Comment("<<<<<<<<<<<<<<< IF then else statment end >>>>>>>>>>>>>>>")
self.EnterT(" ")
return self.TempOutputCode
def __str__(self):
return "(if " + str(self.IfCondition) + " " + str(self.IfTrue) + " " + str(self.IfFalse)+ ")"
class Def(AbstractSchemeExpr):
def __init__(self,definestatment):
operands = NextItem(definestatment)
Type, Typearg = self.ParseLeftPart(operands.Item1)
operands = NextItem(operands)
if(Type):
lambdaStatement = sexprs.Pair(Typearg, operands)
ValueToParse = sexprs.Pair(sexprs.Symbol("LAMBDA"), lambdaStatement)
else:
ValueToParse = operands.Item1
self.Value = AbstractSchemeExpr.parseRec(ValueToParse)
endofdefine = operands.Item2
if(not (isinstance(endofdefine, sexprs.Nil))):
raise SyntaxError
def ParseLeftPart(self, input):
if(isinstance(input, sexprs.Pair)):
self.ParseName(input.Item1)
return (True, input.Item2)
else:
self.ParseName(input)
return (False, "")
def ParseName(self, input):
self.variable = AbstractSchemeExpr.parseRec(input)
if(not isinstance(self.variable, Variable)):
raise SyntaxError
@staticmethod
def instanceof(instance):
if(isinstance(instance, sexprs.Pair)):
DefineLabel = instance.Item1
return (isinstance(DefineLabel, sexprs.Symbol) and (str(DefineLabel) == "DEFINE"))
else:
return False
def CodeGenRec(self):
self.Comment("----------------------------- Define statment for "+ str(self.variable) + " Begin-----------------------------")
self.TempOutputCode += self.Value.CodeGenRec()
self.EnterTTab("MOV(IND(" + VarTable.GetAddress( str(self.variable)) + "), R0);")
self.EnterTTab("MOV(R0," + ConsTable.GetAddr(MyVoidConstant) + ");")
self.Comment("----------------------------- Define statment for "+ str(self.variable) + " End-------------------------------")
return self.TempOutputCode
def __str__(self):
return "(define " + str(self.variable) + " " + str(self.Value)+ ")"
class LambdaFactory:
@staticmethod
def CreateLambda(input):
operands = NextItem(input)
bodyStatement = NextItem(operands)
if(not isinstance(bodyStatement.Item2, sexprs.Nil)):
raise SyntaxError
body = AbstractSchemeExpr.parseRec(bodyStatement.Item1)
parameters = operands.Item1
if(isinstance(parameters, sexprs.Symbol)):
OneParam = AbstractSchemeExpr.parseRec(parameters)
if(not isinstance(OneParam, Variable)):
raise SyntaxError
return LambdaVar(OneParam, body)
else:
type, ParamList = LambdaFactory.ParametersParse(parameters, [])
if(type):
return LambdaOpt(ParamList, body)
else:
return LambdaSimple(ParamList, body)
@staticmethod
def ParametersParse(input, list):
if(not isinstance(input, sexprs.Pair)):
if(not isinstance(input, sexprs.Nil)):
raise SyntaxError
else:
return (False, ())
else:
CurrParam = AbstractSchemeExpr.parseRec(input.Item1)
if(not isinstance(CurrParam, Variable)):
raise SyntaxError
list.append(CurrParam)
if(isinstance(input.Item2, sexprs.Nil)):
return (False, list)
elif(isinstance(input.Item2, sexprs.Symbol)):
LastParam = AbstractSchemeExpr.parseRec(input.Item2)
if(not isinstance(LastParam, Variable)):
raise SyntaxError
list.append(LastParam)
return (True, list)
else:
return LambdaFactory.ParametersParse(input.Item2, list)
class AbstractLambda(AbstractSchemeExpr):
def __init__(self, body):
self.Body = body
@staticmethod
def instanceof(instance):
if(isinstance(instance, sexprs.Pair)):
LambdaLabel = instance.Item1
return (isinstance(LambdaLabel, sexprs.Symbol) and (str(LambdaLabel) == "LAMBDA"))
else:
return False
def __str__(self):
return "(lambda "
def body(self):
return self.Body
def CodeGenRec(self):
self.Comment("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Lambda code"+self.Name()+" start:@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
self.EnterT(" ")
self.Comment("Save registry values before make lambda code")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(R2);")
self.EnterTTab("PUSH(R3);")
self.EnterTTab("PUSH(R4);")
self.EnterT(" ")
#Enlarge the env
self.Comment("Enlarge env")
self.EnterTTab("PUSH(FPARG(0));//push the env")
self.EnterTTab("CALL(ENLARGE_ENV);")
self.EnterTTab("DROP(1);")
self.Comment("save in R1 the new env")
self.EnterTTab("MOV(R1, R0);") #save in R1 the new env
self.EnterT(" ")
#Allocate space for the new level
self.Comment("Allocate space for the new level")
self.EnterTTab("MOV(R3, FPARG(1));")
self.EnterTTab("INCR(R3);") #make space for meta-data: number of args in level
self.EnterTTab("PUSH(R3);")
self.EnterTTab("CALL(MALLOC);")
self.EnterTTab("DROP(1);")
self.EnterTTab("MOV(R2, R0);") #save in R2 the new level
self.EnterTTab("MOV(IND(R2), FPARG(1));") #save in the first cell the number of args in level
self.EnterT(" ")
#Create Labels for the copy args loop - copy from the stack to the new level
LambdaCopyArgLoop = LabelGen.Next("Lambda"+ self.Name()+"CopyArgLoop")
LambdaCopyArgExit = LabelGen.Next("Lambda"+ self.Name()+"CopyArgExit")
#init loop
self.Comment("This loop - copy from the stack to the new level")
self.EnterTTab("INCR(R2);") #skip the metadata of the new level for the offset will be correct(like in stack)
self.EnterTTab("MOV(R3, 0);") #R3 is the loop counter and also the offest
self.EnterT(" ")
self.EnterTTab("MOV(R4,R3);")
self.EnterTTab("ADD(R4,IMM(2));")###########
#loop cond +body
self.Comment("loop cond +body")
self.EnterT(LambdaCopyArgLoop + ":")
self.EnterTTab("CMP(R3, FPARG(1));")
self.EnterTTab("JUMP_EQ(" + LambdaCopyArgExit + ");" )
self.EnterTTab("MOV(INDD(R2,R3), FPARG(R4));")##########3
self.EnterTTab("INCR(R3);")
self.EnterTTab("INCR(R4);")############3
self.EnterTTab("JUMP(" + LambdaCopyArgLoop + ");")
self.EnterT(" ")
#exit loop
self.Comment("exit loop")
self.EnterT(LambdaCopyArgExit + ":")
self.EnterTTab("DECR(R2);") #Cancel the INCR(R2) before the loop
self.EnterTTab(" ")
#make closure
self.Comment("make closure")
LambdaBody = LabelGen.Next("Lambda"+ self.Name()+"Body")
LambdaBodyExit = LabelGen.Next("Lambda"+ self.Name()+"BodyExit")
self.EnterTTab("MOV(INDD(R1, 2), R2);") #copy the new level(address) into the env
self.EnterTTab("PUSH(LABEL(" + LambdaBody + "));")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("CALL(MAKE_SOB_CLOSURE);")
self.EnterTTab("DROP(2);")
self.EnterTTab(" ")
self.Comment("recover temp vars")
self.EnterTTab("POP(R4);")
self.EnterTTab("POP(R3);")
self.EnterTTab("POP(R2);")
self.EnterTTab("POP(R1);")
self.EnterTTab(" ")
self.EnterTTab("JUMP(" + LambdaBodyExit + ");")
self.EnterTTab(" ")
self.CodeGenBody(LambdaBody, LambdaBodyExit)
self.Comment("^^^^^^^^^^^^^^^^^^^^^^^^^Lambda"+ self.Name() + "code end:^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
return self.TempOutputCode
class LambdaSimple(AbstractLambda):
def __init__(self,Params, body):
super(LambdaSimple, self).__init__(body)
self.Params = Params
def Name(self):
return "Simple"
def CodeGenBody(self, LambdaBody, LambdaBodyExit):
self.Comment("Body appiication:")
self.EnterT(LambdaBody + ":")
self.EnterTTab("PUSH(FP);")
self.EnterTTab("MOV(FP, SP);")
self.TempOutputCode += self.Body.CodeGenRec()
self.EnterTTab("POP(FP);")
self.EnterTTab("RETURN;")
self.EnterT(LambdaBodyExit + ":")
def __str__(self):
return "(lambda (" + ' '.join((map(str,self.Params))) + ") " + str(self.Body)+ ")"
class LambdaOpt(AbstractLambda):
def __init__(self,Params, body):
super(LambdaOpt, self).__init__(body)
self.Params = Params
def Name(self):
return "Optional"
def CodeGenBody(self, LambdaBody, LambdaBodyExit):
self.EnterT(LambdaBody + ":")
self.Comment("Body appiication:")
self.EnterTTab("PUSH(FP);")
self.EnterTTab("MOV(FP, SP);")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(R2);")
self.EnterTTab("PUSH(R3);")
#Fixing the Stack
self.Comment("***LAMBDA OPT begin **")
LambdaFixing = LabelGen.Next("Lambda"+ self.Name()+"FixingTheStack")
LambdaFixingEnd = LabelGen.Next("Lambda"+ self.Name()+"FixingTheStackEnd")
LambdaMagicDeleteOpt= LabelGen.Next("Lambda"+ self.Name()+"MagicDelete")
self.EnterTTab("MOV(R1,"+ConsTable.GetAddr(MyNilConstant)+");") #R1 is the final object
self.EnterTTab("MOV(R2,FPARG(1));")#R2 is the number of parameters left
self.EnterTTab("SUB(R2,"+str(len(self.Params)-1)+");")
self.EnterTTab("MOV(R3,FPARG(1));")#R3 is the number of total parameters
self.EnterTTab("INCR(R3);")
self.EnterT(LambdaFixing+":")
if 1:
self.EnterTTab("CMP(R2,0);")
self.EnterTTab("JUMP_EQ("+LambdaFixingEnd +");")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(FPARG(R3));")
self.EnterTTab("CALL(MAKE_SOB_PAIR);")
self.EnterTTab("MOV(R1,R0);")
self.EnterTTab("DROP(2);")
self.EnterTTab("DECR(R2);")
self.EnterTTab("DECR(R3);")
self.EnterTTab("JUMP("+LambdaFixing +");")
self.EnterT(LambdaFixingEnd+":")
self.EnterTTab("MOV(R2,FPARG(1));")
self.EnterTTab("ADD(R2,2);")
self.Comment("****************")
self.EnterTTab("CMP(FPARG(R2),IMM(123456));")
self.EnterTTab("JUMP_EQ("+LambdaMagicDeleteOpt+");")
self.EnterTTab("DECR(R2);")
self.EnterT(LambdaMagicDeleteOpt+":")
self.EnterTTab("MOV(FPARG(R2),R1);")
self.EnterTTab("DECR(R2);")
LambdaOPTFixing = LabelGen.Next("LambdaOPTFixing")
LambdaOPTFixingEnd = LabelGen.Next("LambdaOPTFixingEnd")
self.EnterTTab("MOV(R3,"+str(len(self.Params))+");")
self.EnterT(LambdaOPTFixing+":")
self.EnterTTab("CMP(2,R3);")
self.EnterTTab("JUMP_GT("+LambdaOPTFixingEnd+");")
self.EnterTTab("MOV(FPARG(R2),FPARG(R3));")
self.EnterTTab("DECR(R2);")
self.EnterTTab("DECR(R3);")
self.EnterTTab("JUMP("+LambdaOPTFixing+");")
self.EnterTTab(LambdaOPTFixingEnd+":")
self.EnterTTab("MOV(FPARG(R2),"+str(len(self.Params))+");")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(0));")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(-1));")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(-2));")
self.EnterTTab("SUB(FP,R2);")
self.EnterTTab("SUB(FP,2);")
self.EnterTTab("POP(R3);")
self.EnterTTab("POP(R2);")
self.EnterTTab("POP(R1);")
self.EnterTTab("MOV(SP,FP);")
self.Comment("***LAMBDA OPT end **")
self.TempOutputCode += self.Body.CodeGenRec()
self.EnterTTab("POP(FP);")
self.EnterTTab("RETURN;")
self.EnterT(LambdaBodyExit + ":")
def __str__(self):
return "(lambda (" + ' . '.join((map(str,self.Params))) + ") " + str(self.Body)+ ")"
class LambdaVar(AbstractLambda):
def __init__(self,OneParam, body):
super(LambdaVar, self).__init__(body)
self.OneParam = OneParam
def __str__(self):
return "(lambda " + str(self.OneParam) + " " + str(self.Body)+ ")"
def Name(self):
return "Variadic"
def CodeGenBody(self, LambdaBody, LambdaBodyExit):
self.EnterT(LambdaBody + ":")
self.Comment("Body appiication:")
self.EnterTTab("PUSH(FP);")
self.EnterTTab("MOV(FP, SP);")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(R2);")
#Fixing the Stack
LambdaFixing = LabelGen.Next("Lambda"+ self.Name()+"FixingTheStack")
LambdaFixingEnd = LabelGen.Next("Lambda"+ self.Name()+"FixingTheStackEnd")
LambdaMagicDelete= LabelGen.Next("Lambda"+ self.Name()+"MagicDelete")
self.EnterTTab("MOV(R1,"+ConsTable.GetAddr(MyNilConstant)+");") #R1 is the final object
self.EnterTTab("MOV(R2,FPARG(1));")#R2 is the number of parameters left
self.EnterTTab("ADD(R2,1);")
self.EnterT(LambdaFixing+":")
if 1:
self.EnterTTab("CMP(2,R2);")
self.EnterTTab("JUMP_GT("+LambdaFixingEnd +");")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(FPARG(R2));")
self.EnterTTab("CALL(MAKE_SOB_PAIR);")
self.EnterTTab("MOV(R1,R0);")
self.EnterTTab("DROP(2);")
self.EnterTTab("DECR(R2);")
self.EnterTTab("JUMP("+LambdaFixing +");")
self.EnterT(LambdaFixingEnd+":")
self.EnterTTab("MOV(R2,FPARG(1));")
self.EnterTTab("ADD(R2,2);")
self.EnterTTab("CMP(FPARG(R2),IMM(123456));")
self.EnterTTab("JUMP_EQ("+LambdaMagicDelete+");")
self.EnterTTab("DECR(R2);")
self.EnterT(LambdaMagicDelete+":")
self.EnterTTab("MOV(FPARG(R2),R1);")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),1);")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(0));")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(-1));")
self.EnterTTab("DECR(R2);")
self.EnterTTab("MOV(FPARG(R2),FPARG(-2));")
self.EnterTTab("SUB(FP,R2);")
self.EnterTTab("SUB(FP,2);")
self.EnterTTab("POP(R2);")
self.EnterTTab("POP(R1);")
self.EnterTTab("MOV(SP,FP);")
self.TempOutputCode += self.Body.CodeGenRec()
self.EnterTTab("POP(FP);")
self.EnterTTab("RETURN;")
self.EnterT(LambdaBodyExit + ":")
class Applic(AbstractSchemeExpr):
def __init__(self,applic):
self.Lambda = AbstractSchemeExpr.parseRec(applic.Item1)
params = NextItem(applic)
ParamList = []
while(isinstance(params,sexprs.Pair)):
temp= AbstractSchemeExpr.parseRec(params.Item1)
ParamList.append(temp)
params= params.Item2
self.ParamList=ParamList
@staticmethod
def instanceof(instance):
if(isinstance(instance, sexprs.Pair)):
Lambda = instance.Item1
return (isinstance(Lambda, sexprs.Pair) or isinstance(Lambda,( sexprs.Symbol, sexprs.Char, sexprs.Integer )))
else:
return False
def __str__(self):
return "(" + str(self.Lambda) + " " + ' '.join((map(str,self.ParamList)))+ ")"
def CodeGenRec(self):
self.Comment("**************Aplic MotherFucker***************")
self.EnterTTab(" ")
self.Comment("Save the regisry will change in the application")
self.EnterTTab("PUSH(R1);")
self.EnterTTab("PUSH(R2);")
self.EnterTTab("PUSH(R3);")
self.EnterTTab("PUSH(R4);")
self.EnterTTab("PUSH(R5);")
self.EnterTTab(" ")
self.Comment("Entering all the the application parameters in reverse order after Evaluation")
self.Comment("**Magic Parameter**")
self.EnterTTab("PUSH (123456); //Magic Parameter")
ReverseParamList=self.ParamList
ReverseParamList.reverse()
for param in ReverseParamList: #Entering all the the application parameters in reverse order after Evaluation
self.TempOutputCode += param.CodeGenRec()
self.EnterTTab("PUSH (R0);")
self.EnterT(" ")
self.Comment("*******Number of Parameters***********")
self.EnterTTab("PUSH ("+ str(len(self.ParamList))+");")#Number of Parameters