-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.py
1491 lines (1135 loc) · 44.3 KB
/
compiler.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
# PATSAOGLOU PANTELEIMON 5102
# IATRAKIS IOANNIS 5116
import sys
#define TOKENS
EOFTK = -1
ERRORTK=-5
K1=-3 #desmeumenes lekseis kai anagnwristika
K2=-2 #gia akeraies statheres
ADDTK =100 #+
MINUSTK=101 #-
MULTK=102 #*
DIVTK=103 #//
MODTK=104 #%
LTTK=105 #< LESS THAN
GTTK=106 #> GREAT THAN
LETK = 107 # <= LESS EQUAL
GETK = 108 # >= GREAT EQUAL
EQUALTK = 109 # ==
NOT_EQUALTK = 110 # !=
ASSIGNTK = 111 # =
COMMATK = 112 # ,
UPDOWNDOTTK = 113 # :
OPARTK = 114 # ( OPEN PARENTHESIS
CPARTK = 115 # ) CLOSE PARENTHESIS
OBLOCKTK = 116 # #{ OPEN BLOCK
CBLOCKTK = 117 # #} CLOSE BLOCK
COMMENTK = 118 # ## COMMNENT
INTEGERTK = 119 # AKERAIA STATHERA
ANAGNORTK = 120 # ANAGNORISTIKO (GRAMMATA + ARITHMOUS) megethos:30
#define DESMEUMENES LEKSEIS
MAINTK =121 #main
DEFTK=122 #def
DEF2TK=123 # #def
INTTYPETK=124 # #int e.g #int x=3
GLOBALTK=125 #global
IFTK=126 #if
ELIFTK=127 #elif
ELSETK=128 #else
WHILETK=129 #while
PRINTTK=130 #print
RETURNTK=131 #return
INPUTTK=132 #input
INTCASTTK=133 #int for casting
ANDTK=134 #and
ORTK=135 #or
NOTTK=136 #not
token = ""
line=1
retArray=[]
# generally before each call lex() is already called
current_token = None
is_in_function_definition = 0
quadsList = []
quadNum = 1
tempNum = 1
# ---------------------- Pinakas Sym ---------------------- #
assembly_file = None
sym_file = None
scope_list = []
current_scope_level = 0
class Entity:
def __init__(self, name, offset = None, label = None, arguments = None, framelength = None, type = "NOT_GLOBAL"):
self.name = name
self.offset = offset
self.label = label
self.arguments = arguments if arguments is not None else []
self.framelength = framelength
self.type = type
def __str__(self):
return f"Name: {self.name}, Offset: {self.offset}, Label: {self.label}, Arguments: {self.arguments}, Framelength: {self.framelength}, Type: {self.type}"
class Scope:
def __init__(self, name, level = 0):
self.name = name
self.level = level
self.entities = []
self.previous_offset = 0
def add_entity(self, entity):
self.entities.append(entity)
def __str__(self):
entity_list = "\n".join([f"\t{entity}" for entity in self.entities])
return f"\n\nScope Name: {self.name}, Level: {self.level}\nEntities:\n{entity_list}"
def create_scope(name):
global current_scope_level
scope = Scope(name, current_scope_level)
scope_list.append(scope)
current_scope_level += 1
return scope
def close_scope():
global current_scope_level, scope_list
if scope_list:
sym_out(scope_list)
last_scope = scope_list.pop()
if len(last_scope.entities) == 0:
current_scope_level -= 1
scope_list[current_scope_level-1].entities[-1].framelength = 12
return
last_entity_with_offset = len(last_scope.entities) - 1
while(last_scope.entities[last_entity_with_offset].offset == None):
last_entity_with_offset-=1
if(last_entity_with_offset<0):
current_scope_level -= 1
scope_list[current_scope_level-1].entities[-1].framelength = 12
return
framelength = last_scope.entities[last_entity_with_offset].offset + 4
current_scope_level -= 1
scope_list[current_scope_level-1].entities[-1].framelength = framelength
def add_entity(newEntity, isFuction = False, isGlobal = False):
global current_scope_level, scope_list
scope_entity_list = scope_list[current_scope_level-1].entities
for entity in scope_entity_list:
if entity.name == newEntity.name:
fail_exit("Entity with name '"+newEntity.name+"' cannot be added to scope because this entity name already exists in current scope.")
if isFuction == False and isGlobal == False:
if len(scope_entity_list) == 0:
scope_list[current_scope_level-1].previous_offset = 12
newEntity.offset = scope_list[current_scope_level-1].previous_offset
else:
if scope_list[current_scope_level-1].previous_offset == 0:
scope_list[current_scope_level-1].previous_offset = 12
else:
scope_list[current_scope_level-1].previous_offset += 4
newEntity.offset = scope_list[current_scope_level-1].previous_offset
if isGlobal:
newEntity.type = "GLOBAL"
scope_entity_list.append(newEntity)
# --------------------------Telikos------------------------ #
assembly_quads = []
starting_quad = 0
ending_quad = 0
function_par = []
is_in_main_block = False
block_name_list = []
endblock = []
call_entity = None
initial_par_offset = 12
par_len = 0
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
def gnlvcode(v):
global current_scope_level, scope_list, assembly_quads
check_scope = current_scope_level - 2
entity_found = None
assembly_out(" lw t0,-4(sp)")
while check_scope >=0:
for entity in scope_list[check_scope].entities:
if entity.offset == None and entity.type != "GLOBAL":
break
if entity.name == v:
entity_found = entity
break
if entity_found != None:
break
check_scope -= 1
assembly_out(" lw t0,-4(t0)")
if entity_found:
assembly_out(" addi t0,t0,-"+str(entity_found.offset))
else:
int_out()
fail_exit("Variable '"+v+"' not found in parent scopes")
def gnlvcode_local(v, reg, is_storing = False):
global current_scope_level,scope_list,assembly_quads
entity_found = None
check_scope = current_scope_level - 1
for entity in scope_list[check_scope].entities:
if entity.name == v:
if entity.offset == None:
if entity.type == "GLOBAL":
return gnlvcode_global(v, reg, is_storing)
else:
continue
entity_found = entity
break
if entity_found:
if is_storing:
assembly_out(" sw "+reg+",-"+str(entity_found.offset)+"(sp)")
else:
assembly_out(" lw "+reg+",-"+str(entity_found.offset)+"(sp)")
return entity_found
def gnlvcode_global(v, reg, is_storing = False):
global current_scope_level,scope_list,assembly_quads ,initial_par_offset
entity_found = None
# immediatly checks first scope for global
for entity in scope_list[0].entities:
if entity.name == v:
entity_found = entity
break
if entity_found:
if is_storing:
assembly_out(" sw "+reg+",-"+str(entity_found.offset)+"(gp)")
else:
assembly_out(" lw "+reg+",-"+str(entity_found.offset)+"(gp)")
return entity_found
def loadvr(v, reg):
global assembly_quads
if is_integer(v):
assembly_out(" li "+reg+","+str(v))
elif gnlvcode_local(v, reg) != None:
return
else: # progonous
gnlvcode(v)
assembly_out(" lw "+reg+", 0(t0)")
def storerv(reg, v):
if gnlvcode_local(v, reg, True) != None:
return
else:
gnlvcode(v)
assembly_out(" sw "+reg+", 0(t0)")
def search_call_quad(par_quad):
global quadsList
par_quad_label = par_quad[0]
while quadsList[par_quad_label][1] != "call":
par_quad_label +=1
return quadsList[par_quad_label][2]
def assembly_quad_from_quad(quad):
global starting_quad, function_par, endblock, ending_quad, call_entity, initial_par_offset, par_len
if quad[1] == "JUMP":
assembly_out("L"+str(quad[0])+":")
assembly_out(" j L"+str(quad[4]))
elif quad[1] == '=':
if is_integer(quad[2]) or quad[2].isalpha() or 'T_' in quad[2]:
assembly_out("L"+str(quad[0])+":")
loadvr(quad[2],"t1")
storerv("t1", quad[4])
elif quad[1] in ["+","-","%","//","*"]:
assembly_out("L"+str(quad[0])+":")
loadvr(quad[2],"t1")
loadvr(quad[3],"t2")
if quad[1] == "+":
assembly_out(" add t1, t1, t2")
elif quad[1] == "-":
assembly_out(" sub t1, t1, t2")
elif quad[1] == "*":
assembly_out(" mul t1, t1, t2")
elif quad[1] == "%":
assembly_out(" rem t1, t1, t2")
elif quad[1] == "//":
assembly_out(" div t1, t1, t2")
storerv("t1",quad[4])
elif quad[1] in ["<","<=",">=",">","==","!="]:
assembly_out("L" + str(quad[0]) + ":")
loadvr(quad[2], "t1")
loadvr(quad[3], "t2")
if quad[1] == "<":
assembly_out(" blt t1, t2, L" + str(quad[4]))
elif quad[1] == "<=":
assembly_out(" ble t1, t2, L" + str(quad[4]))
elif quad[1] == ">":
assembly_out(" bgt t1, t2, L" + str(quad[4]))
elif quad[1] == ">=":
assembly_out(" bge t1, t2, L" + str(quad[4]))
elif quad[1] == "==":
assembly_out(" beq t1, t2, L" + str(quad[4]))
elif quad[1] == "!=":
assembly_out(" bne t1, t2, L" + str(quad[4]))
elif quad[1] == "call":
if len(endblock)> 0 and endblock[-1] == quad[2]:
function_entity = search_function(quad[2], True)
else:
function_entity = search_function(quad[2], False)
actual_par_len = len(function_entity[0].arguments)
if par_len != actual_par_len:
fail_exit("Funtion call parameter number not same as in declaration")
call_function(quad, function_entity)
elif quad[1] == "PAR":
if call_entity == None:
call_entity = search_function(search_call_quad(quad), True)[0]
assembly_out("L" + str(quad[0]) + ":")
assembly_out(" addi fp, sp,"+str(handle_none_framelength(call_entity)))
if quad[3] == "CV":
loadvr(quad[2], "t1")
assembly_out(" sw t1, -"+str(initial_par_offset)+"(fp)")
initial_par_offset+=4
par_len +=1
elif quad[3] == "RET":
assembly_out(" addi t0, sp,-"+str(ret_offset(quad[2])))
assembly_out(" sw t0, -8(fp)")
else:
if quad[3] == "CV":
assembly_out("L" + str(quad[0]) + ":")
loadvr(quad[2], "t1")
assembly_out(" sw t1, -"+str(initial_par_offset)+"(fp)")
initial_par_offset+=4
par_len +=1
elif quad[3] == "RET":
assembly_out("L" + str(quad[0]) + ":")
assembly_out(" addi t0, sp,-"+str(ret_offset(quad[2])))
assembly_out(" sw t0, -8(fp)")
elif quad[1] == "out":
assembly_out("L"+str(quad[0])+":")
loadvr(quad[2],"a0")
assembly_out(" li a7, 1")
assembly_out(" ecall")
assembly_out(" la a0, str_nl")
assembly_out(" li a7, 4")
assembly_out(" ecall")
elif quad[1] == "inp":
assembly_out("L"+str(quad[0])+":")
assembly_out(" li a7,5")
assembly_out(" ecall")
elif quad[1] == "ret":
assembly_out("L"+str(quad[0])+":")
loadvr(quad[2],"t1")
assembly_out(" lw t0, -8(sp)")
assembly_out(" sw t1, 0(t0)")
assembly_out(" j L"+ str(ending_quad))
def call_function(quad, function_entity):
global function_par, endblock, is_in_main_block, call_entity, initial_par_offset, par_len
caller_scope = 0
if len(endblock)>0:
caller_scope = search_function(endblock[-1], True)[1]
if initial_par_offset == 12:
assembly_out("L" + str(quad[0]) + ":")
assembly_out(" addi fp, sp,"+str(handle_none_framelength(function_entity[0])))
else:
assembly_out("L" + str(quad[0]) + ":")
if (caller_scope == function_entity[1]) and is_in_main_block == False: # if entities are brothers in the same scope
assembly_out(" lw t0, -4(sp)")
assembly_out(" sw t0, -4(fp)")
else:
assembly_out(" sw sp, -4(fp)")
assembly_out(" addi sp, sp,"+str(handle_none_framelength(function_entity[0])))
assembly_out(" sw ra, 0(sp)")
assembly_out(" jal L"+str(function_entity[0].label))
assembly_out(" addi sp, sp,-"+str(handle_none_framelength(function_entity[0])))
function_par = []
call_entity = None
initial_par_offset = 12
par_len = 0
return function_entity[0]
def handle_none_framelength(entity):
global scope_list
if entity.framelength == None: # recursion / framelength of previous scope entity is no yet return because scope is not removed
return scope_list[-1].entities[-1].offset + 4
else:
return entity.framelength
def ret_offset(v):
global current_scope_level, scope_list, assembly_quads
check_scope = current_scope_level - 1
entity_found = None
for entity in scope_list[check_scope].entities[::-1]:
if entity.name == v:
entity_found = entity
break
if entity_found:
return entity_found.offset
else:
fail_exit("Variable '"+v+"' not found in parent scopes")
def search_function(function_name, is_from_scope_check = False):
global current_scope_level, scope_list
starting_scope = current_scope_level - 1
function_entity = None
while starting_scope >= 0 and function_entity== None:
for entity in scope_list[starting_scope].entities[::-1]:
if entity.name == function_name and is_from_scope_check:
function_entity = entity
break
if entity.name == function_name and entity.framelength != None:
function_entity = entity
break
if function_entity == None:
starting_scope-=1
if function_entity == None:
fail_exit("Function that is called cannot be found in known scopes.")
return [function_entity, starting_scope]
def gen_assembly_fuction_quads():
global quadsList, starting_quad # global because issue in case of nested function declaration
# print(starting_quad) # starting quad of parent not the initial quad
# we dont want start again regenarating child function
while(quadsList[starting_quad][1] != "end_block"):
assembly_quad_from_quad(quadsList[starting_quad])
starting_quad +=1
starting_quad += 1 # begin quad of parent fuction (end_block child + 1 quad for parent's)
def gen_assembly_main_quads(starting_quad):
global quadsList
assembly_out("Lmain:")
assembly_out(" addi sp,sp,"+ str(get_main_framelength()))
assembly_out(" mv gp,sp")
while(quadsList[starting_quad][1] != "end_main"):
assembly_quad_from_quad(quadsList[starting_quad])
starting_quad +=1
assembly_out("L"+str(quadsList[starting_quad][0]-1) +":")
assembly_out(" li a0,0")
assembly_out(" li a7,93")
assembly_out(" ecall")
def get_main_framelength():
global scope_list
return scope_list[0].entities[-1].offset + 4
# --------------------------------------------------------- #
# ---------------------- Symasiologikos ---------------------- #
# --------------------------------------------------------- #
# -------------------------Endiamesos---------------------- #
def gen_quad(op, op1, op2, op3):
global quadsList
global quadNum
newQuad = [quadNum, op, op1, op2, op3]
quadsList.append(newQuad)
quadNum += 1
# print(newQuad)
def new_temp():
global tempNum
newTemp = "T_" + str(tempNum)
tempNum += 1
temp_entity = Entity(newTemp)
add_entity(temp_entity)
return newTemp
def next_quad():
global quadNum
return quadNum
def empty_list():
return []
def make_list(x):
return [x]
def merge(list_1, list_2):
return list_1 + list_2
def backpatch(quads_with_label_to_backpatch, label):
global quadsList
for quad_with_label in quads_with_label_to_backpatch:
for quad in quadsList:
if quad_with_label == quad[0]:
quad[4] = label
def retARRAYTK(state,token):
global retArray
retArray=[]
retArray.append(state)
retArray.append(''.join([char for char in token if not char.isspace()]))
return retArray
def lex():
global line
global retArray
start_cmd_line = 0
EOFflag=0
state=0
i=0
element=' '
next_element=' '
token=[]
array=[[0,1,2,ADDTK,MINUSTK,MULTK,MODTK,DIVTK,ERRORTK,LETK,LTTK,GETK,GTTK,NOT_EQUALTK,ERRORTK,EQUALTK,ASSIGNTK,COMMATK,UPDOWNDOTTK,CPARTK,OPARTK,CBLOCKTK,OBLOCKTK,
ERRORTK,COMMENTK,DEF2TK,ERRORTK,ERRORTK,INTTYPETK,ERRORTK,ERRORTK,ERRORTK,EOFTK,ERRORTK],
[K1,1,1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1,K1],
[K2,K2,2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2,K2]]
while state>=0 and state<100 and i<=31: #i gia na diabazei mexri 30 char + \0 gia anagnwristiko
element=file.read(1)
if element.isspace():
index=0
token.append(element)
if element=='\n':
line=line+1
elif element.isalpha(): #anagnoristiko exei kai digit
i=i+1
index=1
token.append(element)
pos1 = file.tell()
elif element.isdigit():
i=i+1
index=2
token.append(element)
pos1 = file.tell()
elif element=='+':
index=3
token.append(element)
elif element=='-':
#pos1 = file.tell()
index=4
token.append(element)
elif element=='*':
index=5
token.append(element)
elif element=='%':
index=6
token.append(element)
elif element=='/': #katastasi 3
token.append(element)
pos = file.tell() #thesi mesa sto arxeio prin diabasw to epomeno xaraktira gia na dw se ti katastasi kattaligw
next_element=file.read(1) #thelei epistrofi?
if next_element=='/':
token.pop()
token.append('//')
index=7 #komple katastasi //
else:
token.append(next_element)
index=8 #ERROR
print("Invalid character ", token[-1], "is not expected after a '/' in line ",line)
elif element=='<': #katastasi 4
token.append(element)
pos = file.tell()
next_element=file.read(1)
if next_element=='=':
token.pop()
token.append('<=')
index=9 #<=
else:
index=10 #<
file.seek(pos) #xreiazetai gt exw koitaxei to epomeno kai den einai to = opote prepeina epistrafei
elif element=='>': #katastasi 5
token.append(element)
pos = file.tell()
next_element=file.read(1)
if next_element=='=':
token.pop()
token.append('>=')
index=11 #>=
else:
index=12 #>
file.seek(pos) #xreiazetai gt exw koitaxei to epomeno kai den einai to = opote prepeina epistrafei
elif element=='!': #katastasi 6
token.append(element)
pos = file.tell() #thesi mesa sto arxeio prin diabasw to epomeno xaraktira gia na dw sw ti katastasi kattaligw
next_element=file.read(1) #thelei epistrofi
if next_element=='=':
token.pop()
token.append('!=')
index=13 #komple katastasi !=
else:
token.append(next_element)
index=14 #ERROR
print("Invalid character ", token[-1], "is not expected after a '!' in line ",line)
elif element=='=': #katastasi 7
token.append(element)
pos = file.tell()
next_element=file.read(1)
if next_element=='=':
token.pop()
token.append('==')
index=15 #==
else:
index=16 #=
file.seek(pos) #xreiazetai gt exw koitaxei to epomeno kai den einai to = opote prepeina epistrafei
elif element==',':
index=17
token.append(element)
elif element==':':
index=18
token.append(element)
elif element==')':
index=19
token.append(element)
elif element=='(':
index=20
token.append(element)
elif element=='#': #katastasi 8
token.append(element)
next_element=file.read(1)
if next_element=='}':
token.append(next_element)
index=21 # #}
elif next_element=='{':
token.append(next_element)
index=22 # #{
elif next_element=='#': #katastasi 9
token.append(next_element)
start_cmd_line = line
while True:
next_element=file.read(1)
if not next_element: #EOF pianei kai kena
index=23 #array error bazw anti eoftk
print("EOF: Open comments and not closed in line",start_cmd_line)
fail_exit("Exit")
EOFflag=1
break
if next_element=='#':#pame sti katastasi 10 exw brei to ena # apo ta 2 gia to kleisimo sxoliou
pos = file.tell()
next_next=file.read(1)
if next_next=='#':
index=24 # exoun ## kleisei ta sxolia
state=0
break
elif next_element=='d':
token.append(next_element)
next_element=file.read(1)
if next_element=='e':
token.append(next_element)
next_element=file.read(1)
if next_element=='f':
token.append(next_element)
index=25 # #def
else:
token.append(next_element)
index=26 #error
print("Invalid character '", token[-1], "' is not expected after '",''.join(token[:-1]),"' in line ",line)
else:
token.append(next_element)
index=27 #ERROR
print("Invalid character '", token[-1], "'is not expected after '" ,''.join(token[:-1]),"' in line ",line)
elif next_element=='i': #katastasi 13
token.append(next_element)
next_element=file.read(1)
if next_element=='n':
token.append(next_element)
next_element=file.read(1)
if next_element=='t':
token.append(next_element)
index=28 # #int
else:
token.append(next_element)
index=29 #error
print("Invalid character '", token[-1], "' is not expected after '",''.join(token[:-1]),"' in line ",line)
else:
token.append(next_element)
index=30 #error
print("Invalid character '", token[-1], "' is not expected after '",''.join(token[:-1]),"' in line ",line)
else:
token.append(next_element)
index=31 #error den akolouthei meta to # kati apo ta orismena
print("Invalid character ", token[-1], "is not expected after a '#' in line ",line)
elif not element: #EOF
index=32
EOFflag=1
else:
token.append(element)
index=33 #error
print("Find character '",token[-1],"' that is not in the language in line",line)
if i >=31:
fail_exit("Found alphanumeric with length >30. Analisis failed.")
index=0 #ipervenei ta 30 char
state=array[state][index]
if state==K1 or state==K2:
if not element.isspace(): #elegxos den einai kenos char na epistrefei stin proigoumeni thesi (an einai kenos apla katanalwnetai kai proxwrame)
file.seek(pos1) #epistrefoume stin proigoumeni thesi afou exoume krifokoitaxei to epomeno
token.pop()
if state >=100:
return retARRAYTK(state,token)
elif state==K1:
new_token=''.join([char for char in token if not char.isspace()])
if new_token=='main':
return retARRAYTK(MAINTK,token)
if new_token=='def':
return retARRAYTK(DEFTK,token)
if new_token=='#def':
return retARRAYTK(DEF2TK,token)
if new_token=='#int':
return retARRAYTK(INTTYPETK,token)
if new_token=='global':
return retARRAYTK(GLOBALTK,token)
if new_token=='if':
return retARRAYTK(IFTK,token)
if new_token=='elif':
return retARRAYTK(ELIFTK,token)
if new_token=='else':
return retARRAYTK(ELSETK,token)
if new_token=='while':
return retARRAYTK(WHILETK,token)
if new_token=='print':
return retARRAYTK(PRINTTK,token)
if new_token=='return':
return retARRAYTK(RETURNTK,token)
if new_token=='input':
return retARRAYTK(INPUTTK,token)
if new_token=='int':
return retARRAYTK(INTCASTTK,token)
if new_token=='and':
return retARRAYTK(ANDTK,token)
if new_token=='or':
return retARRAYTK(ORTK,token)
if new_token=='not':
return retARRAYTK(NOTTK,token)
return retARRAYTK(ANAGNORTK,token)
elif state==K2:
num=int(''.join(token))
if num <= 32767:
return retARRAYTK(INTEGERTK,token)
else:
return retARRAYTK(ERRORTK,token) #error ektos oriwn arithmos
elif EOFflag==1:
return retARRAYTK(EOFTK,'EOF')
else:
return retARRAYTK(ERRORTK,'ERROR')
def statement_or_block():
global current_token, line
if current_token[0] == OBLOCKTK:
temp_line = line
current_token = lex()
while current_token[0] != CBLOCKTK:
if current_token[0] == EOFTK:
err = "Code block opened in line "+str(temp_line) +" and did not closed before EOF"
fail_exit(err)
parse_statement()
current_token = lex()
else:
parse_statement()
def parse_statement():
global current_token
if current_token[0] == ANAGNORTK:
id = current_token[1]
current_token = lex()
if current_token[0] == ASSIGNTK:
current_token = lex()
if current_token[0] == INTCASTTK:
current_token = lex()
ePlace = parse_int()
gen_quad("=", ePlace, "_", id)
else:
ePlace = parse_expression()
gen_quad("=", ePlace, "_", id)
else:
fail_exit("Expected '=' on simple statement structure but did not get it")
elif current_token[0] == PRINTTK:
parse_print_call()
elif current_token[0] == RETURNTK:
ret()
elif current_token[0] == IFTK:
parse_if_stat()
elif current_token[0] == WHILETK:
parse_while_stat()
else:
err = "Expected statement structure but did not get it. Got '" + current_token[1] + "'."
fail_exit(err)
def parse_while_stat():
global current_token
B_quad = next_quad()
B_cond = parse_condition()
if current_token[0] == UPDOWNDOTTK:
current_token = lex()
backpatch(B_cond[0], next_quad())
statement_or_block()
gen_quad("JUMP", "_", "_", B_quad)
backpatch(B_cond[1], next_quad())
else:
fail_exit("Expected ':' after while statement but did not get it")
def parse_if_stat():
global current_token
B_cond = parse_condition()
if current_token[0] == UPDOWNDOTTK:
current_token = lex()
p1_quad = next_quad()
statement_or_block()
jumps = make_list(next_quad())
gen_quad("JUMP", "_", "_", "_")
p2_quad = next_quad()
backpatch(B_cond[0], p1_quad)
backpatch(B_cond[1], p2_quad)
if current_token[0] == ELIFTK:
parse_if_stat()
p2_quad = next_quad()
if current_token[0] == ELSETK:
parse_else()
jump_else = make_list(next_quad())
gen_quad("JUMP", "_", "_", "_")
p2_quad = next_quad()
jumps = merge(jumps,jump_else)
backpatch(jumps, p2_quad)
else:
fail_exit("Expected ':' after if statement but did not get it")
def parse_else():
global current_token
current_token = lex()
if current_token[0] == UPDOWNDOTTK:
current_token = lex()
statement_or_block()
else:
fail_exit("Expected ':' after if statement but did not get it")
def parse_condition():
global current_token
B1 = bool_term()
while current_token[0] == ORTK:
backpatch(B1[1], next_quad())
B2 = bool_term()
B1[0] = merge(B1[0], B2[0]) # True
B1[1] = B2[1] # False
return B1
def bool_term():
global current_token
Q1 = bool_factor()
while current_token[0] == ANDTK:
backpatch(Q1[0], next_quad())
Q2 = bool_factor()
Q1[1] = merge(Q1[1], Q2[1]) # False
Q1[0] = Q2[0] # True
return Q1
def bool_factor():
global current_token
not_flag = False
current_token = lex()
if current_token[0] == NOTTK:
not_flag = True
current_token = lex()
e1_place = parse_expression()
relop = current_token[1]
if current_token[0] not in [LTTK, GTTK, LETK, GETK, EQUALTK, NOT_EQUALTK]:
fail_exit("Expected comparison token but didn't get it")
current_token = lex()
e2_place = parse_expression()
R_true = make_list(next_quad())
gen_quad(relop, e1_place, e2_place, "_")
R_false = make_list(next_quad())
gen_quad("JUMP", "_", "_", "_",)
if (not_flag):
return [R_false, R_true]
return [R_true, R_false]