-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimal++_Compiler.py
1509 lines (1316 loc) · 55.4 KB
/
Minimal++_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
# ---------------------------------------------------------------------------------------------
# Miminal++_Compiler.py
#
# A complete compiler for the Minimal ++ language developed as a college project
# More info on the report as well as the given pdf files
#
# Teacher: Dr G.Manis
#
# Students
# Names: Stylianos Zappids, Zisimos Parasxis
# Usernames: cse52971 cse53059
# AMs: 2971, 3059
#
# Python Edition 3.7
# Developed in PyCharm
# ---------------------------------------------------------------------------------------------
import _io
import string
import sys
from collections import deque
class Error:
def __init__(self, error_type, error_cause, error_suggestion='No suggestion'):
error_id = error_type + ": " + error_cause
error_location = "\nIn Line: " + str(minimal.line_index) + ", Character: " + str(minimal.char_index)
error_solution = "\nSuggestion: " + error_suggestion
exit(error_id + error_location + error_solution)
class Compiler:
@staticmethod
def load_source():
file = filename.split(".")
if file[1] != "min":
exit("SYSTEM ERROR: This compiler only works for .min files")
try:
return open(filename, 'r')
except FileNotFoundError:
exit("SYSTEM ERROR: File not found!")
def __init__(self):
""" Compiler: The main class of the program.
It contains all the tools required for the compiler to work properly as attributes
LP: The Lexical Analyzer
SP: The Syntax Parser
IC: The Intermediate code generator
ST: The Symbol Table
FC: The Final Code creator
Also it has two addional attributes for handling errors
line_index: Points at the line where the error appears
char_index: Points at the character after which the error appears (Not accurate)
"""
self.LP = Lexer()
self.SP = Parser()
self.IC = ICGenerator()
self.ST = SymbolTable()
self.FC = Finalizer()
self.line_index = 0
self.char_index = 0
self.main_framelength = 0
self.program_name = ''
# Lectical Analysis
class Lexical(Error):
Error1 = 13
Error2 = Error1 + 1
Error3 = Error1 + 2
Error4 = Error1 + 3
Error5 = Error1 + 4
errors = {
Error1: "1: Digits can not be followed by characters",
Error2: "2: Closed long comment without opening one",
Error3: "3: Opened second comment inside another one",
Error4: "4: EOF while in long comment",
Error5: "5: Invalid symbol"
}
def __init__(self, cause, char):
msg = self.errors.get(cause)
if cause == self.Error5:
msg += " '" + char + "'"
super().__init__('LexicalError', msg)
class Lexeme:
IDTK = 1
CONSTANTTK = 2
# Operators
ADDTK = 3
MULTIPLYTK = 4
BRACKETTK = 5
SEPARATORTK = 6
COMPARATORTK = 7
DECLARATORTK = 8
# Key words
PROGRAMTK = 9
DECLARETK = 10
IFTK = 11
THENTK = 12
ELSETK = 13
WHILETK = 14
DOUBLEWHILETK = 15
LOOPTK = 16
EXITTK = 17
FORCASETK = 18
INCASETK = 19
WHENTK = 20
DEFAULTTK = 21
NOTTK = 22
ANDTK = 23
ORTK = 24
FUNCTIONTK = 25
PROCEDURETK = 26
CALLTK = 27
RETURNTK = 28
INTK = 29
INOUTTK = 30
INPUTTK = 31
PRINTTK = 32
# EOF
EOFTK = 33
dictionary = {
# Add ops
'+': ADDTK,
'-': ADDTK,
# Multiply ops
'*': MULTIPLYTK,
'/': MULTIPLYTK,
# Brackets
'(': BRACKETTK,
')': BRACKETTK,
'[': BRACKETTK,
']': BRACKETTK,
'{': BRACKETTK,
'}': BRACKETTK,
# Separators
':': SEPARATORTK,
';': SEPARATORTK,
',': SEPARATORTK,
# relops
'<': COMPARATORTK,
'>': COMPARATORTK,
'=': COMPARATORTK,
'<=': COMPARATORTK,
'>=': COMPARATORTK,
'<>': COMPARATORTK,
# declator
':=': DECLARATORTK,
# Key words
'program': PROGRAMTK,
'declare': DECLARETK,
'if': IFTK,
'then': THENTK,
'else': ELSETK,
'while': WHILETK,
'doublewhile': DOUBLEWHILETK,
'loop': LOOPTK,
'exit': EXITTK,
'forcase': FORCASETK,
'incase': INCASETK,
'when': WHENTK,
'default': DEFAULTTK,
'not': NOTTK,
'and': ANDTK,
'or': ORTK,
'function': FUNCTIONTK,
'procedure': PROCEDURETK,
'call': CALLTK,
'return': RETURNTK,
'in': INTK,
'inout': INOUTTK,
'input': INPUTTK,
'print': PRINTTK,
'': EOFTK,
}
key_words = ["program", "declare", "if", "else", "while", "doublewhile", "loop", "exit", "forcase", "incase",
"when", "default", "not", "and", "or", "function", "procedure", "call", "return", "in",
"inout", "input", "print", "then"]
relops = ['<', '>', '=', '<=', '>=', '<>']
def __init__(self, word, char):
""" Lexeme: An object with 2 attributes
token: The token recognized by the Parser
word: The actual word
:param word: The constructed word
:param char: The last character
"""
full_word = word + char
minimal.LP.pos_index -= 1
if full_word in self.dictionary:
minimal.LP.pos_index += 1
self.token = self.dictionary.get(full_word, self.IDTK)
self.word = full_word
return
self.word = word
if word.isdigit():
self.token = self.CONSTANTTK
if int(self.word) > 32767 or int(self.word) < -32767:
print("Warning! Number " + str(self.word) + " is out of range")
return
self.token = self.dictionary.get(word, self.IDTK)
return
def __str__(self):
return "Word: " + self.word + " with Token: " + str(self.token)
class Lexer:
""" Lexer: The tool that reads from the source code, breaks it into words
and then returns the tokens to the parser. Lexer has a few states that goes
through while analyzing the source code.
alphabet: The symbols that the lexer understands
DFA: A code implementation of the Finite Automata the Lexer uses
"""
source: _io.TextIOWrapper
start_state = 0
special1 = start_state + 1 # Read * Symbol
special2 = start_state + 2 # Read / Symbol
chars_state = 3
numbs_state = 4
long_comment = 5
special3 = long_comment + 1 # Read * inside long comment
special4 = long_comment + 2 # Read / inside long comment
short_comment = 8
special5 = short_comment + 1 # Read * inside short comment
special6 = short_comment + 2 # Read / inside short comment
temp = 11 # < > or :
return_state = 12
comments = [short_comment, special3, special4, long_comment, special5, special6]
alphabet = {
'+': 2,
'-': 2,
'*': 3,
'/': 4,
'<': 5,
'>': 6,
'=': 7,
':': 8,
';': 9,
',': 9,
'(': 10,
')': 10,
'[': 10,
']': 10,
'{': 10,
'}': 10,
'\n': 11,
' ': 12,
'\t': 12,
'': 13
}
DFA = [
# start_state
[chars_state, numbs_state, return_state, special1, special2, temp, temp,
return_state, temp, return_state, return_state, start_state, start_state, return_state,
Lexical.Error5],
# Special 1
[return_state, return_state, return_state, return_state, Lexical.Error2, return_state, return_state,
return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state],
# Special 2
[return_state, return_state, return_state, long_comment, short_comment, return_state, return_state,
return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state],
# chars_state
[chars_state, chars_state, return_state, return_state, return_state, return_state, return_state,
return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state],
# numbs_state
[Lexical.Error1, numbs_state, return_state, return_state, return_state, return_state, return_state,
return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state],
# Long_comment
[long_comment, long_comment, long_comment, special3, special4, long_comment, long_comment,
long_comment, long_comment, long_comment, long_comment, long_comment, long_comment, Lexical.Error4,
long_comment],
# Special 3
[long_comment, long_comment, long_comment, long_comment, start_state, long_comment, long_comment,
long_comment, long_comment, long_comment, long_comment, long_comment, long_comment, Lexical.Error4,
long_comment],
# Special 4
[long_comment, long_comment, long_comment, Lexical.Error3, Lexical.Error3, long_comment, long_comment,
long_comment, long_comment, long_comment, long_comment, long_comment, long_comment, Lexical.Error4,
long_comment],
# Short Comment
[short_comment, short_comment, short_comment, special5, special6, short_comment, short_comment,
short_comment, short_comment, short_comment, short_comment, start_state, short_comment, return_state,
short_comment],
# Special 5
[short_comment, short_comment, short_comment, short_comment, Lexical.Error2, short_comment, short_comment,
short_comment, short_comment, short_comment, short_comment, start_state, short_comment, return_state,
short_comment],
# Special 6
[short_comment, short_comment, short_comment, Lexical.Error3, Lexical.Error3, short_comment, short_comment,
short_comment, short_comment, short_comment, short_comment, start_state, short_comment, return_state,
short_comment],
# temp
[return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state, return_state, return_state, return_state, return_state, return_state, return_state,
return_state]
]
def __init__(self):
self.pos_index = 0
self.source = Compiler.load_source()
def identify(self, char):
""" Check if given char is in the compiler's alphabet and returns the assigned column
:param char: Character given for identification
:return: The columned assigned for that char (special case 14 for invalid characters)
"""
if char in string.ascii_letters: # Only Latin Characters
return 0
elif char.isnumeric():
return 1
else:
if char == '\n':
minimal.line_index += 1
minimal.char_index = 0
return self.alphabet.get(char, 14)
# Create the lexeme and update the starting position
def handle_return(self, word, char):
result = Lexeme(word, char)
self.source.seek(self.pos_index)
return result
def lex(self):
char = word = ''
state = self.start_state
line = self.source.readline()
while line != '':
for char in line:
minimal.char_index += 1
self.pos_index += 1
state = self.DFA[state][self.identify(char)]
if state == self.return_state:
return self.handle_return(word, char)
elif state in Lexical.errors:
Lexical(state, char)
elif state in self.comments or state == self.start_state:
word = ""
elif char not in [' ', '\t', '\n'] and len(word) <= 30:
word += char
line = self.source.readline()
self.pos_index += 1
state = self.DFA[state][13]
if state in Lexical.errors:
Lexical(state, char)
elif state == self.return_state:
return self.handle_return(word, char)
exit("Something went very wrong")
# Syntax Analysis
class Parse(Error):
def __init__(self, error_cause, suggestion='No Suggestion'):
super().__init__('SyntaxError', error_cause, error_suggestion=suggestion)
class Parser:
""" Parser: The syntax analyzing tool, goes through all of the source code checking whether it follows the syntax
of the language or not.
This class also contains the syntax of the minimal++ language
"""
def __init__(self):
self.lexeme = None
# --------------------------- Starting ---------------------------
def program(self):
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.PROGRAMTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
minimal.program_name = self.lexeme.word
self.lexeme = minimal.LP.lex()
minimal.ST.add_scope()
if self.lexeme.word == '{':
self.lexeme = minimal.LP.lex()
self.block(minimal.program_name)
if self.lexeme.word == '}':
minimal.ST.delete_scope()
return # This is the proper end of the compiling process
# Possible Errors Part
msg = ""
final_token = self.lexeme
self.lexeme = minimal.LP.lex()
if final_token.word == ";" and self.lexeme.word == "}":
msg += "The ';' separator is unnecessary after the program's last statement."
elif final_token.word in Lexeme.key_words:
msg += "Statements not separated by ';' operator"
else:
msg += "Check if multiple statements are not inside {} blocks"
Parse("Expected '}' bracket to end program's block\n", msg)
Parse("Expected '{' character to start program's block", "Add the appropriate symbol")
Parse("A program should always have a name ", "Name the program")
Parse("Keyword 'program' is required to start", "Add the appropriate keyword")
def block(self, name):
self.declarations()
self.subprograms()
if len(minimal.ST.scopes) > 1:
minimal.ST.scopes[-2].entities[-1].startQuad = minimal.IC.next_quad()
minimal.IC.generate_quad("begin_block", name, "_", "_")
self.statements()
if name == minimal.program_name:
minimal.IC.generate_quad("halt", "_", "_", "_")
minimal.IC.generate_quad("end_block", name, "_", "_")
# ------------------------- Declarations -------------------------
def declarations(self):
while self.lexeme.token == Lexeme.DECLARETK:
self.lexeme = minimal.LP.lex()
char = self.varlist()
if self.lexeme.word == ';':
self.lexeme = minimal.LP.lex()
else:
Parse("Either ',' or ';' separator was expected after variable " + char, "Find what is missing")
def varlist(self):
var = ""
if self.lexeme.token == Lexeme.IDTK:
var = self.lexeme.word
minimal.ST.add_entity(Variable(var))
self.lexeme = minimal.LP.lex()
while self.lexeme.word == ',':
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
var = self.lexeme.word
minimal.ST.add_entity(Variable(var))
self.lexeme = minimal.LP.lex()
else:
Parse("Expected variable's name after ',' character",
"Either add another variable or remove the last ,")
elif self.lexeme.word == ',':
Parse("Expected a variable's name before the first ',' character", "Add the first variable")
return var # Return the last character written before the error pops up
def subprograms(self):
while self.lexeme.token in [Lexeme.FUNCTIONTK, Lexeme.PROCEDURETK]:
self.subprogram()
def subprogram(self):
if self.lexeme.token == Lexeme.FUNCTIONTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
function_name = self.lexeme.word
if function_name == minimal.program_name:
Semantic(6)
minimal.ST.add_entity(Subprogram(function_name, 1))
minimal.ST.add_scope()
self.lexeme = minimal.LP.lex()
self.funcbody(function_name)
minimal.ST.delete_scope()
elif self.lexeme.word in Lexeme.key_words:
Parse("A function can't have a key word as a name")
else:
Parse("A function should always have a name", )
elif self.lexeme.token == Lexeme.PROCEDURETK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
procedure_name = self.lexeme.word
if procedure_name == minimal.program_name:
Semantic(6)
minimal.ST.add_entity(Subprogram(procedure_name, 2))
minimal.ST.add_scope()
self.lexeme = minimal.LP.lex()
self.funcbody(procedure_name)
minimal.ST.delete_scope()
elif self.lexeme.word in Lexeme.key_words:
Parse("A procedure can't have a key word as a name")
else:
Parse("A procedure should always have a name")
def funcbody(self, name):
self.formalpars()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "{":
self.lexeme = minimal.LP.lex()
self.block(name)
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "}":
self.lexeme = minimal.LP.lex()
else:
Parse("Expected '}' char to end the subprogram's block",
"Check if multiple statements are not between { } brackets")
else:
Parse("Expected '{' to start the subprogram's block",
"Add the approriate symbol")
def formalpars(self):
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
self.formalparlist()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
else:
if self.lexeme.token == Lexeme.IDTK:
Parse("Parameter " + self.lexeme.word + "'s type has not been declared",
"Parameter " + self.lexeme.word + " identify yourself!")
else:
Parse("Expected either another variable name or ')' to stop declaring parameters")
else:
Parse("Expected '(' character to start declaring parameters")
return
def formalparlist(self):
if self.lexeme.token == Lexeme.INTK or self.lexeme.token == Lexeme.INOUTTK:
self.formalparitem()
while self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ",":
self.lexeme = minimal.LP.lex()
if self.lexeme.token not in [Lexeme.INTK, Lexeme.INOUTTK]:
Parse("Expected another parameter's type after ','")
self.formalparitem()
def formalparitem(self): # The parameters as shown in function
if self.lexeme.token == Lexeme.INTK:
par_type = self.lexeme.word
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
minimal.ST.add_entity(Parameter(self.lexeme.word, 1))
minimal.ST.add_argument(1)
self.lexeme = minimal.LP.lex()
else:
Parse("Expected parameter's name after type " + par_type)
elif self.lexeme.token == Lexeme.INOUTTK:
par_type = self.lexeme.word
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
minimal.ST.add_entity(Parameter(self.lexeme.word, 2))
minimal.ST.add_argument(2)
self.lexeme = minimal.LP.lex()
else:
Parse("Expected parameter's name after type " + par_type)
@staticmethod
def compare_lists(formal_pars, actual_pars):
if len(formal_pars) != len(actual_pars):
Semantic(5)
for i in range(len(formal_pars)):
if str(formal_pars[i]) != actual_pars[i][0]:
Semantic(4, actual_pars[i][1])
def actualpars(self, subprogram):
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
parlist = self.actualparlist()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
# When you are done compare the actual parameters with the formal parameters
self.compare_lists(subprogram.arguments, parlist)
for par in parlist:
minimal.IC.generate_quad("par", par[1], par[0], '_')
self.lexeme = minimal.LP.lex()
else:
msg = "Expected right bracket ) to close call parameters"
cause = "Add appropriate symbol"
if self.lexeme.token == Lexeme.IDTK:
cause = "\nSuggestion: Parameter " + self.lexeme.word + "identify yourself"
Parse(msg, cause)
else:
Parse("Expected opening bracket ( to open call parameters")
def actualparlist(self):
parlist = []
if self.lexeme.token == Lexeme.INTK or self.lexeme.token == Lexeme.INOUTTK:
par_item = self.actualparitem()
parlist.append(par_item)
while self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ",":
self.lexeme = minimal.LP.lex()
parlist.append(self.actualparitem())
return parlist
def actualparitem(self):
par_type = ''
var = None
if self.lexeme.token == Lexeme.INTK:
par_type = 'CV'
self.lexeme = minimal.LP.lex()
var = self.expression()
elif self.lexeme.token == Lexeme.INOUTTK:
par_type = 'REF'
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
var = self.lexeme.word
self.lexeme = minimal.LP.lex()
else:
Parse("Variable name was expected")
return par_type, var # Return parameter type and name
# ------------------------- Statements -------------------------
def assignment_stat(self, var):
if self.lexeme.token == Lexeme.DECLARATORTK:
self.lexeme = minimal.LP.lex()
Eplace = self.expression()
minimal.IC.generate_quad(":=", Eplace, "_", var)
else:
Parse("Expected := symbol for assignment", "Add appropriate opperator")
return
def if_stat(self): # S -> if B then {P1} S1 {P2} TAIL{P3}
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
C = self.condition() # S -> if B
BTrue = C[0]
BFalse = C[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.THENTK: # S -> if B then {P1}
minimal.IC.backpatch(BTrue, minimal.IC.next_quad())
self.lexeme = minimal.LP.lex()
self.statements() # S1
ifList = minimal.IC.make_list(minimal.IC.next_quad())
minimal.IC.generate_quad("jump", "_", "_", "_")
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
self.elsepart()
minimal.IC.backpatch(ifList, minimal.IC.next_quad())
else:
Parse("Expected keyword 'then' after if clause's condition")
else:
Parse("Expected right bracket ) to close if clause's condition")
else:
Parse("Expected left bracket ( to open if clause's condition")
def elsepart(self):
if self.lexeme.token == Lexeme.ELSETK:
self.lexeme = minimal.LP.lex()
self.statements()
def while_stat(self):
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
Bquad = minimal.IC.next_quad() # Return to condition check
self.lexeme = minimal.LP.lex()
C = self.condition()
BTrue = C[0]
BFalse = C[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
minimal.IC.backpatch(BTrue, minimal.IC.next_quad())
self.statements()
minimal.IC.generate_quad("jump", "_", "_", Bquad)
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
else:
Parse("Expected right bracket ) to close while condition")
else:
Parse("Expected left bracket ( to open while condition")
def doublewhile_stat(self): # The state/flag was an interesting concept
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
state = minimal.IC.new_temp()
minimal.ST.add_entity(Constant('0', 0))
minimal.IC.generate_quad(":=", "0", "_", state) # Initialize loop state
condQuad = minimal.IC.next_quad()
self.lexeme = minimal.LP.lex()
C = self.condition()
BTrue = C[0]
BFalse = C[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
minimal.IC.backpatch(BTrue, minimal.IC.next_quad())
state1_list = minimal.IC.make_list(minimal.IC.next_quad())
minimal.IC.generate_quad("=", "2", state, "_")
minimal.ST.add_entity(Constant('1', 1))
minimal.IC.generate_quad(":=", "1", "_", state)
self.statements() # True statements
minimal.IC.generate_quad("jump", "_", "_", condQuad)
if self.lexeme.token == Lexeme.ELSETK:
self.lexeme = minimal.LP.lex()
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
state2_list = minimal.IC.make_list(minimal.IC.next_quad())
minimal.IC.generate_quad("=", "1", state, "_")
minimal.ST.add_entity(Constant('2', 2))
minimal.IC.generate_quad(":=", "2", "_", state)
self.statements()
minimal.IC.generate_quad("jump", "_", "_", condQuad)
minimal.IC.backpatch(state1_list, minimal.IC.next_quad())
minimal.IC.backpatch(state2_list, minimal.IC.next_quad())
else:
Parse("Expected keyword 'else' for doublewhile to have the proper syntax")
else:
Parse("Right bracket expected ) to end doublewhile condition")
else:
Parse("Expected left bracket ( to start doublewhile condition")
def loop_stat(self): # The program repeats the following statments until
Bquad = minimal.IC.next_quad()
self.statements()
minimal.IC.generate_quad("jump", "_", "_", Bquad)
def exit_stat(self):
minimal.IC.generate_quad("halt", "_", "_", "_")
def forcase_stat(self):
first_quad = minimal.IC.next_quad()
while self.lexeme.token == Lexeme.WHENTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
C = self.condition()
BTrue = C[0]
BFalse = C[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ":":
self.lexeme = minimal.LP.lex()
minimal.IC.backpatch(BTrue, minimal.IC.next_quad())
self.statements()
minimal.IC.generate_quad("jump", "_", "_", first_quad)
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
else:
Parse("Expected ':' after condition symbol")
else:
Parse("Expected closing bracket ) to close when case condition")
else:
Parse("Expected opening bracket ( for when case condition")
if self.lexeme.token == Lexeme.DEFAULTTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ":":
self.lexeme = minimal.LP.lex()
self.statements()
else:
Parse("Expected : symbol")
else:
Parse("Expected keyword 'default' for the default case")
def incase_stat(self):
t = minimal.IC.new_temp()
first_quad = minimal.IC.next_quad()
minimal.IC.generate_quad(":=", "0", "_", t)
while self.lexeme.token == Lexeme.WHENTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
C = self.condition()
BTrue = C[0]
BFalse = C[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ":":
self.lexeme = minimal.LP.lex()
minimal.IC.backpatch(BTrue, minimal.IC.next_quad())
self.statements()
minimal.IC.generate_quad(":=", "1", "_", t)
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
else:
Parse("Expected ':' after condition symbol")
else:
Parse("Expected closing bracket ) to close when case condition")
else:
Parse("Expected opening bracket ( for when case condition")
minimal.IC.generate_quad("=", "1", t, first_quad)
return
def return_stat(self):
if minimal.ST.scopes[-2].entities[-1].program_type == 2:
print("Warning: Procedures should not have a return statement")
print("Line " + str(minimal.line_index))
minimal.IC.generate_quad("retv", "_", "_", self.expression())
def call_stat(self):
if self.lexeme.token == Lexeme.IDTK:
procedure_name = self.lexeme.word
self.lexeme = minimal.LP.lex()
procedure = minimal.ST.find_entity(procedure_name)
if procedure is None:
Semantic(1, procedure_name)
self.actualpars(procedure)
minimal.IC.generate_quad("call", '_', "_", procedure_name)
return
if self.lexeme.word in Lexeme.key_words:
Parse(self.lexeme.word + " is a key word, you can not use it as a function's name", "I lied")
Parse("Expected name of procedure to call")
def print_stat(self):
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
minimal.IC.generate_quad("out", '_', "_", self.expression())
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
else:
Parse("Expected right bracket ) to close print statment")
else:
Parse("Expected left bracket ( to open print statement")
def input_stat(self):
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.IDTK:
minimal.IC.generate_quad("in", "_", "_", self.lexeme.word)
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
else:
Parse("Expected closing bracket ) for input statement")
else:
Parse("Expected name of variable to save input")
else:
Parse("Expected opening bracket ( for input statement")
statements_selector = {
Lexeme.IDTK: assignment_stat,
Lexeme.IFTK: if_stat,
Lexeme.WHILETK: while_stat,
Lexeme.DOUBLEWHILETK: doublewhile_stat,
Lexeme.LOOPTK: loop_stat,
Lexeme.EXITTK: exit_stat,
Lexeme.FORCASETK: forcase_stat,
Lexeme.INCASETK: incase_stat,
Lexeme.RETURNTK: return_stat,
Lexeme.CALLTK: call_stat,
Lexeme.PRINTTK: print_stat,
Lexeme.INPUTTK: input_stat
}
def statements(self):
statements_counter = [0]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "{":
self.lexeme = minimal.LP.lex()
self.statement(statements_counter)
while self.lexeme.token == Lexeme.SEPARATORTK and self.lexeme.word == ";":
self.lexeme = minimal.LP.lex()
self.statement(statements_counter)
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "}":
self.lexeme = minimal.LP.lex()
return
Parse("Right curly bracket } was expected to stop statements block",
"Maybe you missed a ';' operator between previous statements")
self.statement(statements_counter)
def statement(self, counter):
if self.lexeme.token in self.statements_selector:
counter[0] += 1
statement_id = self.statements_selector.get(self.lexeme.token)
if self.lexeme.token == Lexeme.IDTK:
word = self.lexeme.word
self.lexeme = minimal.LP.lex()
statement_id(self, word)
else:
self.lexeme = minimal.LP.lex()
statement_id(self)
else: # Handle possible Errors
if counter[0] > 0:
Parse("Expected a statement", "The block's last statement has no need of ';' separator")
elif self.lexeme.word == '}':
Parse("Expected a statement", "I am sorry, our services do not accept empty statement blocks")
Parse("Expected '}' bracket")
# ------------------------- Logical -------------------------
def condition(self): # B-> Q1{P1}(OR {P2}Q2 {P3})*
Q1 = self.boolterm()
BTrue = Q1[0] # Q1.true
BFalse = Q1[1] # Q1.false
while self.lexeme.token == Lexeme.ORTK: # (or {P2}Q2 {P3})*
minimal.IC.backpatch(BFalse, minimal.IC.next_quad())
self.lexeme = minimal.LP.lex()
Q2 = self.boolterm()
BTrue = minimal.IC.merge_lists(BTrue, Q2[0])
BFalse = Q2[1]
return BTrue, BFalse
def boolterm(self): # Q->R1{P1}( AND {P2}R2 {P3})*
R1 = self.boolfactor()
QTrue = R1[0] # R1.true
QFalse = R1[1] # R1.false
while self.lexeme.token == Lexeme.ANDTK: # (and {P2} R2{P3})*
minimal.IC.backpatch(QTrue, minimal.IC.next_quad()) # If condition is true, go to the immediate next quad
self.lexeme = minimal.LP.lex()
R2 = self.boolfactor()
QFalse = minimal.IC.merge_lists(QFalse, R2[1])
QTrue = R2[0]
return QTrue, QFalse
def boolfactor(self):
RTrue = minimal.IC.empty_list()
RFalse = minimal.IC.empty_list()
if self.lexeme.token == Lexeme.NOTTK:
self.lexeme = minimal.LP.lex()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.token == "[":
self.lexeme = minimal.LP.lex()
B = self.condition() # R ->( B )
# {P1}:
RTrue = B[1]
RFalse = B[0]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "]":
self.lexeme = minimal.LP.lex()
else:
Parse("Expected ]")
else:
Parse("Expected [")
elif self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "[":
self.lexeme = minimal.LP.lex()
B = self.condition() # R ->( B )
# {P1}:
RTrue = B[0]
RFalse = B[1]
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "]":
self.lexeme = minimal.LP.lex()
else:
Parse("Expected ]")
else: # R ->E1 relop E2{P1}
E1 = self.expression() # x
relop = self.relational_oper() # <>=
E2 = self.expression() # y
RTrue = minimal.IC.make_list(minimal.IC.next_quad())
minimal.IC.generate_quad(relop, E1, E2, "_")
RFalse = minimal.IC.make_list(minimal.IC.next_quad())
minimal.IC.generate_quad("jump", "_", "_", "_")
return RTrue, RFalse
def expression(self):
sign = self.optional_sign()
T1place = sign + self.term()
while self.lexeme.token == Lexeme.ADDTK: # (+T2{P1})*
oper = self.add_oper()
T2place = self.term()
# {P1}
w = minimal.IC.new_temp()
minimal.IC.generate_quad(oper, T1place, T2place, w)
T1place = w
return T1place
def term(self):
F1place = self.factor() # F1
while self.lexeme.token == Lexeme.MULTIPLYTK:
oper = self.mul_oper()
F2place = self.factor() # F2
w = minimal.IC.new_temp()
minimal.IC.generate_quad(oper, F1place, F2place, w)
F1place = w
return F1place
def factor(self):
Fplace = ""
if self.lexeme.token == Lexeme.CONSTANTTK:
constant = Constant(self.lexeme.word, int(self.lexeme.word))
minimal.ST.add_entity(constant)
Fplace = self.lexeme.word
self.lexeme = minimal.LP.lex()
elif self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == "(":
self.lexeme = minimal.LP.lex()
Fplace = self.expression()
if self.lexeme.token == Lexeme.BRACKETTK and self.lexeme.word == ")":
self.lexeme = minimal.LP.lex()
else:
Parse("Right bracket ')' expected")
elif self.lexeme.token == Lexeme.IDTK:
idt = self.lexeme.word
self.lexeme = minimal.LP.lex()
Fplace = self.idtail(idt)
else:
Parse("This factor's syntax is not supported")
return Fplace