-
Notifications
You must be signed in to change notification settings - Fork 0
/
EELC_Intermediate.py
2116 lines (1470 loc) · 54.5 KB
/
EELC_Intermediate.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
# + ------------------------- + #
# Deligiannis Nikos 2681 #
# UoI - Spring Semester 2018 #
# CSE Department #
# Compilers MYY802 prof G.Manis #
# Project: Compiler for EEL #
# + ------------------------- + #
import sys
import signal
import os
# Just in case someone is curious!
def handler(signum, frame):
print ("\n")
print (Colors.HIGHL + "Compilation shall not be stopped" + Colors.RESET)
print ("\n")
# [PHASE: 1] :: Lexical and Syntactical Analysis Due 14/3/2018
# [PHASE: 2] :: Intermediate Code Generation Due 18/4/2018
#Classes
class Colors:
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
YELLOW = "\033[93m"
BOLD = "\033[;1m"
RESET = "\033[0;0m"
HIGHL = "\033[;7m"
class Quad:
def __init__(self, label, op, arg_1, arg_2, res):
self.label = label
self.op = op
self.arg_1 = arg_1
self.arg_2 = arg_2
self.res = res
def __str__(self):
return "(" + str(self.label) + ": " + str(self.op) + ", " + str(self.arg_1) + ", " \
+ str(self.arg_2) + ", " + str(self.res) + ")"
# + ------------------------------------ + #
# #
# Global Variables Declaration #
# #
# + ------------------------------------ + #
token_dict = dict(alphaTK = 1, # Alpharithmetic - String (e.g Compiler)
numberTK = 2, # Any Number (e.g 65)
plusTK = 3, # +
minusTK = 4, # -
mulTK = 5, # *
divTK = 6, # /
lessTK = 7, # <
greaTK = 8, # >
leqTK = 9, # <=
greqTK = 10, # >=
eqTK = 11, # =
difTK = 12, # <>
assigTK = 13, # :=
semiTK = 14, # ;
commaTK = 15, # ,
colonTK = 16, # :
lbrTK = 17, # (
rbrTK = 18, # )
blbrTK = 19, # [
brbrTK = 20, # ]
#Commited Words#
progTK = 100, # program
eprogTK = 101, # endprogram
decTK = 102, # declare
edecTK = 103, # enddeclare
ifTK = 104, # if
thenTK = 105, # then
elseTK = 106, # else
eifTK = 107, # endif
whileTK = 108, # while
ewhileTK = 109, # endwhile
repTK = 110, # repeat
erepTK = 111, # endrepeat
exitTK = 112, # exit
swiTK = 113, # switch
caseTK = 114, # case
eswiTK = 115, # endswitch
fcaseTK = 116, # forcase
whenTK = 117, # when
efcaseTK = 118, # endforcase
procTK = 119, # procedure
eprocTK = 120, # endprocedure
funTK = 121, # function
efunTK = 122, # endfunction
callTK = 123, # call
retTK = 124, # return
inTK = 124, # in
inoutTK = 125, # inout
andTK = 126, # and
orTK = 127, # or
notTK = 128, # not
trueTK = 129, # true
falseTK = 130, # false
inputTK = 131, # input
printTK = 132, # print
#Special Tokens#
eofTK = 200, # End of File
errTK = 201, # Error || Won't be used
cmtTK = 202) # Comment(s) || Won't be used
max_word_size = 30 # An Alpharithmetic can't be over 30 char's long
line = 1 # The current line (used for debugging messages)
ret_token = 0 # The token lex() will return
lex_unit = "" # The lexical unit lex() will return
label_cc = 0 # The counter for the label generation/showcase
tmp_cc = 0 # The counter for the tmp unique var generation
code_quads = list()# The list of the program stored in quads
program_name ="" # The name of the main program
to_ansi_c_problem = 0 # Used to display Error messages during Int ansi c generation
eel_source_code ="" # The source code filename
global code # File pointer of the Source Code
# + ------------------------------------ + #
# #
# Intermediate Code Related Funcs #
# #
# + ------------------------------------ + #
# Shows (does not alter) the next label value (string format)
def next_quad():
global label_cc
return str(label_cc)
# Generates a new Quad and increases the label_cc value by 1
def gen_quad(op, x, y, res):
global label_cc
global code_quads
tmp_label = label_cc
label_cc = label_cc + 1
ret_quad = Quad(str(tmp_label), str(op), str(x), str(y), str(res))
code_quads.append(ret_quad)
return ret_quad
# Generates a new unique temp variable that will be used for the intermediate code generation
def new_temp():
global tmp_cc
ret_tmp = "T_"+str(tmp_cc)
tmp_cc = tmp_cc + 1
return ret_tmp
# Returns an empty list
def empty_list():
return list()
# Generates and returns a list with one item in it
def make_list(item):
ret_list = list()
ret_list.append(item)
return ret_list
# Merges the two lists
def merge_list(list_a, list_b):
if list_a and list_b :
ret_list = list_a + list_b
return ret_list
elif list_a and not list_b:
ret_list = list_a
return list_a
elif list_b and not list_a:
ret_list = list_b
return list_b
# For every quad in quadlist alters the .res field into res
def back_patch(quadlist, res):
global code_quads
if quadlist:
for quad in code_quads:
if quad.label in quadlist:
quad.res = res
# + ------------------------------------ + #
# #
# Error Display & #
# File Generation Related Funcs #
# #
# + ------------------------------------ + #
#Used by everyone for errors
def error_display(arg,output,line):
if(arg == 1): #Lex Related Error Display
print('[' + Colors.RED + "LexError" + Colors.RESET + ']')
print(Colors.BOLD + output + Colors.RESET)
print(Colors.BLUE + "Error spotted ~at line: " + str(line) + Colors.RESET)
elif(arg == 2): #Lex, Comments - EOF Related Error Display
print('[' + Colors.RED + "LexError" + Colors.RESET + ']')
print(Colors.BOLD + output + Colors.RESET)
print(Colors.BLUE + "Comments start ~at Line: " + str(line) + Colors.RESET)
elif(arg == 3): #Syn Related Error Display
print('[' + Colors.GREEN + "SynError" + Colors.RESET + ']')
print(Colors.BOLD + output + Colors.RESET)
print(Colors.BLUE + "Error spotted ~at line: " + str(line) + Colors.RESET)
elif(arg == 4): #IOError
print('[' + Colors.CYAN + "IOError" + Colors.RESET + ']')
print(Colors.BOLD + output + Colors.RESET)
def generate_intermediate_int():
global code_quads
global eel_source_code
file = str(eel_source_code).split('.')[0]+".int"
int_file = open(file,"w")
int_file.write("This file was generated automatically from EEL Compiler.\n")
int_file.write("Intermediate code in quadruples of " + "\"" + eel_source_code + "\".\n\n")
for quad in code_quads:
int_file.write(str(quad))
int_file.write("\n")
int_file.close()
# Creates the ANSI C equivalent of a quadruple
def to_ansi_c(quad):
global progam_name
global to_ansi_c_problem
ret_str = ""
if quad.op == "begin_block":
if quad.res == program_name:
ret_str = "void main()\n{"
declare = find_declarations()
ints = make_declare_string(declare)
ret_str = ret_str + ints + "\n\tL_" + quad.label + ": "
else: #Problem here. This won't work
to_ansi_c_problem = 1
elif quad.op == "halt" :
ret_str = "\tL_" + quad.label + ": exit(0);"
elif quad.op == "end_block":
ret_str = "\tL_" + quad.label + ": {}\n}\n"
elif quad.op == ":=" :
ret_str = "\tL_" + quad.label + ": " + quad.res + " = " + quad.arg_1 + ";"
elif quad.op in ("+","-","*","/"):
ret_str = "\tL_" + quad.label + ": " + quad.res + " = " + quad.arg_1 + " " + \
quad.op + " " + quad.arg_2 + ";"
elif quad.op in ("<>", "=", "<", ">", "<=", ">="):
if quad.op == "<>": relop = "!="
elif quad.op == "=" : relop = "=="
else: relop = quad.op
ret_str = "\tL_" + quad.label + ": if ( " + quad.arg_1 + " " + relop + " " + \
quad.arg_2 + " ) goto L_" + quad.res + ";"
elif quad.op == "jump":
ret_str = "\tL_" + quad.label + ": goto L_" + quad.res + ";"
elif quad.op == "return":
ret_str = "\tL_" + quad.label + ": return (" + quad.arg_1 + " );"
elif quad.op == "print":
ret_str = "\tL_" + quad.label + ': printf( "'+str(quad.arg_1)+' %d\\n" , ' + quad.arg_1 + " );"
elif quad.op == "input":
ret_str = "\tL_" + quad.label + ': printf("Input: '+str(quad.arg_1)+' ");'+' scanf( " %d", &' + quad.arg_1 + " );" + \
" if ( ( " + quad.arg_1 + " < -32767 ) || ( " + quad.arg_1 + " > +32767 ) ) " + \
" { puts(\"[Error]: Too large/small number ( |Number| <= 32767 ) \"); exit(0); } "
elif quad.op == "call": #Problem here. This won't work
to_ansi_c_problem = 1
return ret_str
# Finds which variables to declare in C file
def find_declarations():
global code_quads
ret_list = []
for quad in code_quads:
if quad.op != "call" and quad.op != "begin_block" and quad.arg_2 not in ("in","inout","ret"):
if quad.op == "end_block" : break
if isinstance(quad.arg_1,str) and not quad.arg_1.isdigit() and quad.arg_1 not in ret_list: ret_list.append(quad.arg_1)
if isinstance(quad.arg_2,str) and not quad.arg_2.isdigit() and quad.arg_2 not in ret_list: ret_list.append(quad.arg_2)
if isinstance(quad.res ,str) and not quad.res.isdigit() and quad.res not in ret_list: ret_list.append(quad.res)
for pos in ret_list:
if pos == "_" : ret_list.remove(pos)
ret_list.sort()
return ret_list
# Create the declaration string of integers
def make_declare_string(declare):
ret_string = "int "
for var in declare:
ret_string = ret_string + var + ","
ret_string = "\n\t" + ret_string[:-1] + ";" #Cut the last comma
return ret_string
# Create the C file
def generate_intermediate_ansi_c():
global code_quads
global eel_source_code
file = str(eel_source_code).split('.')[0]+".c"
c_file = open(file,"w")
c_file.write("/*\n * This file was generated automatically from EEL Compiler. \n")
c_file.write(" * This is the equivalent Code in ANSI C of " + "\"" + eel_source_code + "\". \n */\n")
c_file.write("#include <stdio.h>\n#include <stdlib.h>\n\n")
declare = find_declarations()
for quad in code_quads:
equiv = to_ansi_c(quad)
if equiv:
c_file.write(equiv + " \n")
c_file.write("\n/* Equivalent Quads \n")
for quad in code_quads:
c_file.write(" * " + str(quad) + "\n")
c_file.write(" */")
c_file.close()
# + ------------------------------------ + #
# #
# Lexical Analysis Related Funcs #
# #
# + ------------------------------------ + #
def backtrack():
global code
position = code.tell()
code.seek(position - 1)
def lex():
global lex_unit
lex_unit = ""
global line
global ret_token
global code
while True:
unit = code.read(1)
if not unit :
break # EOF reached break the loop.
if unit == '\n' : line = line + 1
if unit == '\t' : continue # Ignore TABs
if unit.isspace() : continue
# -------------------[State 1 of the FSM]------------------- #
# -Character found. Keep reading until you read him whole #
# -Check for commited words. Else return alphaTK. #
# -Must be <= 30 characters long. #
# -IMPORTANT: Backtrack is required after while() #
# ---------------------------------------------------------- #
if unit.isalpha():
alpha_flag = 0
lex_unit = lex_unit + unit
unit = code.read(1)
while ( (unit.isalpha() or unit.isdigit() ) and len(lex_unit) <= max_word_size ):
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == '\n' : line = line + 1
if(lex_unit != "endprogram"): #and unit != '\n'):
backtrack()
if lex_unit == "program":
ret_token = token_dict["progTK"]
return token_dict["progTK"]
if lex_unit == "endprogram":
ret_token = token_dict["eprogTK"]
return token_dict["eprogTK"]
if lex_unit == "declare":
ret_token = token_dict["decTK"]
return token_dict["decTK"]
if lex_unit == "enddeclare":
ret_token = token_dict["edecTK"]
return token_dict["edecTK"]
if lex_unit == "if":
ret_token = token_dict["ifTK"]
return token_dict["ifTK"]
if lex_unit == "then":
ret_token = token_dict["thenTK"]
return token_dict["thenTK"]
if lex_unit == "else":
ret_token = token_dict["elseTK"]
return token_dict["elseTK"]
if lex_unit == "endif":
ret_token = token_dict["eifTK"]
return token_dict["eifTK"]
if lex_unit == "while":
ret_token = token_dict["whileTK"]
return token_dict["whileTK"]
if lex_unit == "endwhile":
ret_token = token_dict["ewhileTK"]
return token_dict["ewhileTK"]
if lex_unit == "repeat":
ret_token = token_dict["repTK"]
return token_dict["repTK"]
if lex_unit == "endrepeat":
ret_token = token_dict["erepTK"]
return token_dict["erepTK"]
if lex_unit == "exit":
ret_token = token_dict["exitTK"]
return token_dict["exitTK"]
if lex_unit == "switch":
ret_token = token_dict["swiTK"]
return token_dict["swiTK"]
if lex_unit == "case":
ret_token = token_dict["caseTK"]
return token_dict["caseTK"]
if lex_unit == "endswitch":
ret_token = token_dict["eswiTK"]
return token_dict["eswiTK"]
if lex_unit == "forcase":
ret_token = token_dict["fcaseTK"]
return token_dict["fcaseTK"]
if lex_unit == "when":
ret_token = token_dict["whenTK"]
return token_dict["whenTK"]
if lex_unit == "endforcase":
ret_token = token_dict["efcaseTK"]
return token_dict["efcaseTK"]
if lex_unit == "procedure":
ret_token = token_dict["procTK"]
return token_dict["procTK"]
if lex_unit == "endprocedure":
ret_token = token_dict["eprocTK"]
return token_dict["eprocTK"]
if lex_unit == "function":
ret_token = token_dict["funTK"]
return token_dict["funTK"]
if lex_unit == "endfunction":
ret_token = token_dict["efunTK"]
return token_dict["efunTK"]
if lex_unit == "call":
ret_token = token_dict["callTK"]
return token_dict["callTK"]
if lex_unit == "return":
ret_token = token_dict["retTK"]
return token_dict["retTK"]
if lex_unit == "in":
ret_token = token_dict["inTK"]
return token_dict["inTK"]
if lex_unit == "inout":
ret_token = token_dict["inoutTK"]
return token_dict["inoutTK"]
if lex_unit == "and":
ret_token = token_dict["andTK"]
return token_dict["andTK"]
if lex_unit == "or":
ret_token = token_dict["orTK"]
return token_dict["orTK"]
if lex_unit == "not":
ret_token = token_dict["notTK"]
return token_dict["notTK"]
if lex_unit == "true":
ret_token = token_dict["trueTK"]
return token_dict["trueTK"]
if lex_unit == "false":
ret_token = token_dict["falseTK"]
return token_dict["falseTK"]
if lex_unit == "input":
ret_token = token_dict["inputTK"]
return token_dict["inputTK"]
if lex_unit == "print":
ret_token = token_dict["printTK"]
return token_dict["printTK"]
ret_token = token_dict["alphaTK"] #Default case, its an alpharithmetic (e.g. variableA)
return token_dict["alphaTK"]
# -------------------[State 2 of the FSM]------------------- #
# -Digit is found. Read the whole number! #
# -Constrains: A. number <= 32767 #
# B. alphabetics not allowed after digit #
# -IMPORTANT: Backtrack is required at the end! #
# ---------------------------------------------------------- #
if unit.isdigit():
lex_unit = lex_unit + unit
unit = code.read(1)
while (unit.isdigit()):
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == '\n' : line = line + 1
if(unit.isalpha()):
error = "Found \"" + lex_unit + unit + "\"." + " A number must not be followed by character(s)."
error_display(1,error,line)
exit()
tmp_num = int(lex_unit) #Grammar will provide the sign
if tmp_num > 32767:
error = "Found \"" + str(tmp_num) + "\"." + " Maximum allowed integer value is 32767."
error_display(1,error,line)
exit()
backtrack()
ret_token = token_dict["numberTK"]
return token_dict["numberTK"]
if unit == '+':
lex_unit = lex_unit + unit
ret_token = token_dict["plusTK"]
return token_dict["plusTK"]
if unit == '-':
lex_unit = lex_unit + unit
ret_token = token_dict["minusTK"]
return token_dict["plusTK"]
# -------------------[State 3 of the FSM]------------------- #
# -Symbol '*' found. Must see what follows in case of error! #
# -If what follows is '/' then error (closing comments) #
# -else return '*' + token #
# -IMPORTANT: Backtrack is required at the end! #
# ---------------------------------------------------------- #
if unit == '*':
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == '/':
error = "Found \"" + lex_unit + unit + "\"." + " A comment section was not initialized \"/*\"."
error_display(1,error,line)
exit()
backtrack()
ret_token = token_dict["mulTK"]
return token_dict["mulTK"]
if unit == ',':
lex_unit = lex_unit + unit
ret_token = token_dict["commaTK"]
return token_dict["commaTK"]
# -------------------[State 4 of the FSM]------------------- #
# -Symbol '/' found. Must see what follows. #
# -Three possible scenarios to begin with #
# [A]: /* Comment initializer #
# [B]: // Comment until new line #
# [C]: / Division operator #
# -IMPORTANT: Backtrack is required in case [C] #
# -IMPORTANT: In case of comments, lex() has call itself #
# to return the next lex_unit and token!! #
# ---------------------------------------------------------- #
if unit == '/':
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == '*':
tmp_flag = 0
tmp_err = line # Used in case of an error!
while(tmp_flag == 0):
unit = code.read(1)
if unit == '\n': line = line + 1
if unit == '*':
unit = code.read(1)
if not unit : # Reached EOF without closing comments
error = "Reached EOF while reading comments. A comment section was not terminated"
error_display(2,error,tmp_err)
exit()
if(unit == '/') : tmp_flag = 1
if not unit : # Reached EOF without closing comments
error = "Reached EOF while reading comments. A comment section was not terminated"
error_display(2,error,tmp_err)
exit()
return lex() #Recursively provide the next unit
elif unit == '/':
tmp_flag = 0
while(tmp_flag == 0):
unit = code.read(1)
if unit == '\n': tmp_flag = 1
return lex() #Recursively provide the next unit
else:
backtrack()
ret_token = token_dict["divTK"]
return token_dict["divTK"]
if unit == '=':
lex_unit = lex_unit + unit
ret_token = token_dict["eqTK"]
return token_dict["eqTK"]
if unit == ';':
lex_unit = lex_unit + unit
ret_token = token_dict["semiTK"]
return token_dict["semiTK"]
if unit == '(':
lex_unit = lex_unit + unit
ret_token = token_dict["lbrTK"]
return token_dict["lbrTK"]
if unit == ')':
lex_unit = lex_unit + unit
ret_token = token_dict["rbrTK"]
return token_dict["rbrTK"]
if unit == '[':
lex_unit = lex_unit + unit
ret_token = token_dict["blbrTK"]
return token_dict["blbrTK"]
if unit == ']':
lex_unit = lex_unit + unit
ret_token = token_dict["brbrTK"]
return token_dict["brbrTK"]
# -------------------[State 5 of the FSM]------------------- #
# -Symbol ':' found. We must check if: #
# [A]: Symbol '=' follows #
# [B]: alphabetical or digit follows #
# -IMPORTANT: Backtrack required for [B]! #
# ---------------------------------------------------------- #
if unit == ':':
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == '=':
lex_unit = lex_unit + unit
ret_token = token_dict["assigTK"]
return token_dict["assigTK"]
backtrack()
ret_token = token_dict["colonTK"]
return token_dict["colonTK"]
# -------------------[State 6 of the FSM]------------------- #
# -Symbol '<' found. We must check again if: #
# [A]: Symbol '=' follows (lower equal operator '<=') #
# [B]: Symbol '>' follows (different operatior '<>') #
# [C]: else (lower operator '<') #
# -IMPORTANT: Backtrack required for [C]! #
# ---------------------------------------------------------- #
if unit == '<':
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == "=":
lex_unit = lex_unit + unit
ret_token = token_dict["leqTK"]
return token_dict["leqTK"]
if unit == ">":
lex_unit = lex_unit + unit
ret_token = token_dict["difTK"]
return token_dict["difTK"]
backtrack()
ret_token = token_dict["leqTK"]
return token_dict["leqTK"]
# -------------------[State 7 of the FSM]------------------- #
# -Symbol '>' found. We must check if: #
# [A]: Symbol '=' follows (greater equal operator '>=') #
# [B]: else (greater operator '>') #
# -IMPORTANT: Backtrack required for [B] #
# ---------------------------------------------------------- #
if unit == '>':
lex_unit = lex_unit + unit
unit = code.read(1)
if unit == "=":
lex_unit = lex_unit + unit
ret_token = token_dict["greqTK"]
return token_dict["greqTK"]
backtrack()
ret_token = token_dict["greaTK"]
return token_dict["greaTK"]
# -------------------[State 8 of the FSM]------------------- #
# -Uknown symbol found. Error! #
# ---------------------------------------------------------- #
error = "Found \"" + unit + "\". Uknown character or symbol."
error_display(1,error,line)
exit()
lex_unit = "EOF"
ret_token = token_dict["eofTK"]
return token_dict["eofTK"]
# + ------------------------------------ + #
# #
# Syntactical Analysis & #
# Intermediate Code Generation #
# #
# + ------------------------------------ + #
# -- <PROGRAM> ::= PROGRAM ID <BLOCK> ENDPROGRAM -- # [SYN: Done]
def PROGRAM():
global ret_token
global program_name
global line
name = None
if ret_token == token_dict["progTK"]:
lex()
if ret_token == token_dict["alphaTK"]:
program_name = name = lex_unit
lex()
BLOCK(name)
if ret_token == token_dict["eprogTK"]:
lex() # EOF is expected
if ret_token == token_dict["eofTK"]:
pass #EOF reached
else:
error = "Expected \"endprogram\". Instead found \"" + lex_unit +"\"."
error_display(3,error,line)
exit()
else:
error = "Expected program name after \"program\". Instead found \"" + lex_unit + "\"."
error_display(3,error,line)
exit()
else:
error = "Expected \"program\". Instead found \"" + lex_unit + "\"."
error_display(3,error,line)
exit()
# -- <BLOCK> ::= <DECLARATIONS><SUBPROGRAMS><STATEMENTS> -- # [SYN: Done, INT: Done]
def BLOCK(name):
global program_name
global line
DECLARATIONS()
SUBPROGRAMS()
gen_quad("begin_block","_","_",name)
STATEMENTS()
if name == program_name:
gen_quad("halt","_","_","_")
gen_quad("end_block","_","_",name)
# -- <DECLARATIONS> ::= e | DECLARE <VARLIST> ENDDECLARE -- # [SYN: Done]
def DECLARATIONS():
global ret_token
global line
if ret_token == token_dict["decTK"]:
lex()
VARLIST()
if ret_token == token_dict["edecTK"]:
lex()
else:
error = "Expected \"enddeclare\". Instead found \"" + lex_unit + "\". \
\nPerhaps you missed a \",\" ?"
error_display(3,error,line)
exit()
# e : No Declarations is acceptable
# -- <VARLIST> ::= e | ID (, ID)* -- # [SYN: Done]
def VARLIST():
global ret_token
global line
if ret_token == token_dict["alphaTK"]:
lex()
while(ret_token == token_dict["commaTK"]):
lex()
if ret_token == token_dict["alphaTK"]:
lex()
else:
error = error = "Expected variable name after \",\"." + " Instead found \"" + lex_unit + "\"."
error_display(3,error,line)
exit()
# e : No Variables is acceptable
# -- <SUBPROGRAMS> ::= (<PROCORFUNC>)* -- # [SYN: Done]
def SUBPROGRAMS():
global ret_token
global line
#Sneak Peek
while(ret_token == token_dict["procTK"] or ret_token == token_dict["funTK"]):
PROCORFUNC()
# e : Kleene-Star includes e! So missing Function or Procedure is acceptable
# -- <PROCORFUNC> ::= PROCEDURE ID <PROCORFUNCBODY> ENDPROCEDURE |
# FUNCTION ID <PROCORFUNCBODY> ENDFUNCTION -- # [SYN: Done]
def PROCORFUNC():
global ret_token
global line
toPROCORFUNCBODY = None
if ret_token == token_dict["procTK"]:
lex()
if ret_token == token_dict["alphaTK"]:
toPROCORFUNCBODY = lex_unit
lex()
PROCORFUNCBODY(toPROCORFUNCBODY)
if ret_token == token_dict["eprocTK"]:
lex()
else:
error = "Expected \"endprocedure\". Instead found \"" + lex_unit +"\"."
error_display(3,error,line)
exit()
else:
error = "Expected procedure name after \"procedure\". Instead found \"" + lex_unit +"\"."
error_display(3,error,line)
exit()
# No need to display an error message. If there was no procedure Token we wouldn't be here.
elif ret_token == token_dict["funTK"]:
lex()
if ret_token == token_dict["alphaTK"]:
toPROCORFUNCBODY = lex_unit
lex()
PROCORFUNCBODY(toPROCORFUNCBODY)
if ret_token == token_dict["efunTK"]:
lex()
else:
error = "Expected \"endfunction\". Instead found \"" + lex_unit +"\"."
error_display(3,error,line)
exit()