-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsc.py
executable file
·1824 lines (1586 loc) · 61.6 KB
/
csc.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
#!/usr/bin/env python3
#+-----------------------------------------------------------------------+
#| Copyright (C) 2017 George Z. Zachos |
#+-----------------------------------------------------------------------+
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Contact Information:
# Name: George Z. Zachos
# Email: gzzachos_at_gmail.com
import sys, getopt, os
from enum import Enum
from collections import OrderedDict
__version__='2.0.0'
##############################################################
# #
# Class definitions #
# #
##############################################################
class clr:
GRN = '\033[92m'
WRN = '\033[95m'
ERR = '\033[91m'
END = '\033[0m'
BLD = '\033[1m'
UNDRLN = '\033[4m'
class TokenType(Enum):
IDENT = 0
NUMBER = 1
# Brackets
LPAREN = 2
RPAREN = 3
LBRACE = 4
RBRACE = 5
LBRACKET = 6
RBRACKET = 7
# Other punctuation marks
COMMA = 8
COLON = 9
SEMICOLON = 10
# Relational Operators
LSS = 11
GTR = 12
LEQ = 13
GEQ = 14
EQL = 15
NEQ = 16
# Assignment
BECOMES = 17
# Arithmetic Operators
PLUS = 18
MINUS = 19
TIMES = 20
SLASH = 21
# Keywords
ANDSYM = 22
NOTSYM = 23
ORSYM = 24
DECLARESYM = 25
ENDDECLSYM = 26
DOSYM = 27
IFSYM = 28
ELSESYM = 29
EXITSYM = 30
PROCSYM = 31
FUNCSYM = 32
PRINTSYM = 33
CALLSYM = 34
INSYM = 35
INOUTSYM = 36
SELECTSYM = 37
PROGRAMSYM = 38
RETURNSYM = 39
WHILESYM = 40
DEFAULTSYM = 41
# EOF
EOF = 42
# What the lexical analyzer returns to the syntax analyzer
# tktype : TokenType object
# tkval : token value
# tkl : token start line number
# tkc : token start character number
class Token():
def __init__(self, tktype, tkval, tkl, tkc):
self.tktype, self.tkval, self.tkl, self.tkc = tktype, tkval, tkl, tkc
def __str__(self):
return '(' + str(self.tktype)+ ', \'' + str(self.tkval) \
+ '\', ' + str(self.tkl) + ', ' + str(self.tkc) + ')'
# The rest of the classes consist the data model required for
# the implementation of the intermediate code generation and
# the symbol table.
class Quad():
def __init__(self, label, op, arg1, arg2, res):
self.label, self.op, self.arg1, self.arg2 = label, op, arg1, arg2
self.res = res
def __str__(self):
return '(' + str(self.label) + ': ' + str(self.op)+ ', ' + \
str(self.arg1) + ', ' + str(self.arg2) + ', ' + str(self.res) + ')'
def tofile(self):
return str(self.label) + ': (' + str(self.op)+ ', ' + \
str(self.arg1) + ', ' + str(self.arg2) + ', ' + str(self.res) + ')'
class Scope():
def __init__(self, nested_level=0, enclosing_scope=None):
self.entities, self.nested_level = list(), nested_level
self.enclosing_scope = enclosing_scope
self.tmp_offset = 12
def addEntity(self, entity):
self.entities.append(entity)
def get_offset(self):
retval = self.tmp_offset
self.tmp_offset += 4
return retval
def __str__(self):
return self.__repr__() + ': (' + str(self.nested_level) + ', ' + \
self.enclosing_scope.__repr__() + ')'
class Argument():
def __init__(self, par_mode, next_arg=None):
self.par_mode = par_mode
self.next_arg = next_arg
def set_next(self, next_arg):
self.next_arg = next_arg
def __str__(self):
return self.__repr__() + ': (' + self.par_mode + ',\t' + \
self.next_arg.__repr__() + ')'
class Entity():
def __init__(self, name, etype):
self.name, self.etype, self.next = name, etype, None
def __str__(self):
return self.etype + ': ' + self.name
class Variable(Entity):
def __init__(self, name, offset=-1):
super().__init__(name, "VARIABLE")
self.offset = offset
def __str__(self):
return super().__str__() + ', offset: ' + \
str(self.offset)
class Function(Entity):
def __init__(self, name, ret_type, start_quad=-1):
super().__init__(name, "FUNCTION")
self.ret_type, self.start_quad = ret_type, start_quad
self.args, self.framelength = list(), -1
def add_arg(self, arg):
self.args.append(arg)
def set_framelen(self, framelength):
self.framelength = framelength
def set_start_quad(self, start_quad):
self.start_quad = start_quad
def __str__(self):
return super().__str__() + ', retv: ' + self.ret_type \
+ ', squad: ' + str(self.start_quad) + ', framelen: ' \
+ str(self.framelength)
class Parameter(Entity):
def __init__(self, name, par_mode, offset=-1):
super().__init__(name, "PARAMETER")
self.par_mode, self.offset = par_mode, offset
def __str__(self):
return super().__str__() + ', mode: ' + self.par_mode \
+ ', offset: ' + str(self.offset)
class TmpVar(Entity):
def __init__(self, name, offset=-1):
super().__init__(name, "TMPVAR")
self.offset = offset
def __str__(self):
return super().__str__() + ', offset: ' + str(self.offset)
##############################################################
# #
# Global data declarations and definitions #
# #
##############################################################
lineno = charno = -1 # Current line and character number of input file.
token = Token(None, None, None, None)
# in_function, in_dowhile, exit_dowhile and have_return are array
# structures and each element corresponds to a nested level in case
# of curly-braced blocks and not function/procedure blocks.
in_function = [] # currently inside a function (not procedure).
in_dowhile = [] # currently inside a do-while statement.
exit_dowhile = [] # used to implement exit for a do-while statement.
have_return = [] # have return statement at specific nested level.
have_subprog = False # True if nested functions are defined in user program.
nextlabel = 0
tmpvars = dict() # A dictionary holding temporary variable names
# used in intermediate code generation.
next_tmpvar = 1 # Used to implement the naming convention of
# temporary variables.
quad_code = list() # The main program equivalent in quadruples.
scopes = list() # The list of currently 'active' scopes.
actual_pars = list() # holds subprogram params as discovered
# while traversing intermediate code
main_programs_framelength = halt_label = -1
tokens = {
'(': TokenType.LPAREN,
')': TokenType.RPAREN,
'{': TokenType.LBRACE,
'}': TokenType.RBRACE,
'[': TokenType.LBRACKET,
']': TokenType.RBRACKET,
',': TokenType.COMMA,
':': TokenType.COLON,
';': TokenType.SEMICOLON,
'<': TokenType.LSS,
'>': TokenType.GTR,
'<=': TokenType.LEQ,
'>=': TokenType.GEQ,
'=': TokenType.EQL,
'<>': TokenType.NEQ,
':=': TokenType.BECOMES,
'+': TokenType.PLUS,
'-': TokenType.MINUS,
'*': TokenType.TIMES,
'/': TokenType.SLASH,
'and': TokenType.ANDSYM,
'not': TokenType.NOTSYM,
'or': TokenType.ORSYM,
'declare': TokenType.DECLARESYM,
'enddeclare': TokenType.ENDDECLSYM,
'do': TokenType.DOSYM,
'if': TokenType.IFSYM,
'else': TokenType.ELSESYM,
'exit': TokenType.EXITSYM,
'procedure': TokenType.PROCSYM,
'function': TokenType.FUNCSYM,
'print': TokenType.PRINTSYM,
'call': TokenType.CALLSYM,
'in': TokenType.INSYM,
'inout': TokenType.INOUTSYM,
'select': TokenType.SELECTSYM,
'program': TokenType.PROGRAMSYM,
'return': TokenType.RETURNSYM,
'while': TokenType.WHILESYM,
'default': TokenType.DEFAULTSYM,
'EOF': TokenType.EOF}
##############################################################
# #
# Useful error/warning reporting functions #
# #
##############################################################
# Print error message to stderr and exit.
def perror_exit(ec, *args, **kwargs):
print('[' + clr.ERR + 'ERROR' + clr.END + ']', *args, file=sys.stderr, **kwargs)
sys.exit(ec)
# Print error message to stderr.
def perror(*args, **kwargs):
print('[' + clr.ERR + 'ERROR' + clr.END + ']', *args, file=sys.stderr, **kwargs)
# Print warning to stderr.
def pwarn(*args, **kwargs):
print('[' + clr.WRN + 'WARNING' + clr.END + ']', *args, file=sys.stderr, **kwargs)
# Print line #lineno to stderr with character charno highlighted.
def perror_line(lineno, charno):
currchar = infile.tell()
infile.seek(0)
for index, line in enumerate(infile):
if index == lineno-1:
print(" ", line.replace('\t', ' ').replace('\n', ''), file=sys.stderr)
print(clr.GRN + " " * (charno + 1) + '^' + clr.END, file=sys.stderr)
infile.seek(currchar)
# Print line #lineno to stderr with character charno
# highlighted and along with and error message. Finally exit.
def perror_line_exit(ec, lineno, charno, *args, **kwargs):
print('[' + clr.ERR + 'ERROR' + clr.END + ']', clr.BLD + '%s:%d:%d:' %
(infile.name, lineno, charno) + clr.END, *args, file=sys.stderr, **kwargs)
currchar = infile.tell()
infile.seek(0)
for index, line in enumerate(infile):
if index == lineno-1:
print(" ", line.replace('\t', ' ').replace('\n', ''), file=sys.stderr)
print(clr.GRN + " " * (charno + 1) + '^' + clr.END, file=sys.stderr)
close_files()
os.remove(int_file.name)
os.remove(ceq_file.name)
sys.exit(ec)
# Open files.
def open_files(input_filename, interm_filename, cequiv_filename, output_filename):
global infile, int_file, ceq_file, outfile, lineno, charno
lineno = 1
charno = 0
try:
infile = open(input_filename, 'r', encoding='utf-8')
int_file = open(interm_filename, 'w', encoding='utf-8')
ceq_file = open(cequiv_filename, 'w', encoding='utf-8')
outfile = open(output_filename, 'w', encoding='utf-8')
except OSError as oserr:
if oserr.filename != None:
perror_exit(oserr.errno, oserr.filename + ':', oserr.strerror)
else:
perror_exit(oserr.errno, oserr)
# Close files.
def close_files():
global infile
infile.close()
int_file.close()
ceq_file.close()
outfile.close()
##############################################################
# #
# Lexical analyzer related functions #
# #
##############################################################
# Perform lexical analysis
def lex():
global lineno, charno
buffer = []
tkl = tkc = -1 # token start lineno, charno
cc = cl = -1 # comment start lineno, charno
state = 0 # Initial FSM state
OK = -2 # Final FSM state
unget = False # True if file pointer should be repositioned
# Lexical analyzer's FSM implementation
while state != OK:
c = infile.read(1)
buffer.append(c)
charno += 1
if state == 0:
if c.isalpha():
state = 1
elif c.isdigit():
state = 2
elif c == '<':
state = 3
elif c == '>':
state = 4
elif c == ':':
state = 5
elif c == '\\':
state = 6
elif c in ('+', '-', '*', '/', '=', ',', ';', '{', '}', '(', ')', '[', ']'):
state = OK
elif c == '': # EOF
state = OK
return Token(TokenType.EOF, 'EOF', lineno, charno)
elif c.isspace():
state = 0
else:
perror_line_exit(2, lineno, charno, 'Invalid character \'%c\' in program' % c)
elif state == 1:
if not c.isalnum():
unget = True
state = OK
elif state == 2:
if not c.isdigit():
if c.isalpha():
perror_line_exit(2, lineno, charno - len(''.join(buffer)) + 1,
'Variable names should begin with alphabetic character')
unget = True
state = OK
elif state == 3:
if c != '=' and c != '>':
unget = True
state = OK
elif state == 4:
if c != '=':
unget = True
state = OK
elif state == 5:
if c != '=':
unget = True
state = OK
elif state == 6:
if c == '*':
state = 7
cl = lineno
cc = charno - 1
else:
perror_line_exit(2, lineno, charno, 'Expected \'*\' after \'\\\'')
elif state == 7:
if c == '': # EOF
perror_line_exit(2, cl, cc, 'Unterminated comment')
elif c == '*':
state = 8
elif state == 8:
if c == '\\':
del buffer[:]
state = 0
else:
state = 7
if state == OK:
tkl = lineno
tkc = charno - len(''.join(buffer)) + 1
if c.isspace():
del buffer[-1]
unget = False
if c == '\n':
lineno += 1
charno = 0
# Unget last character read
if unget == True:
del buffer[-1]
if c != '': # EOF (special case)
infile.seek(infile.tell() - 1)
charno -= 1
# Empty buffer and return the Token object
buff_cont = ''.join(buffer)
if buff_cont not in tokens.keys():
if buff_cont.isdigit():
retval = Token(TokenType.NUMBER, buff_cont, tkl, tkc)
else:
retval = Token(TokenType.IDENT, buff_cont[:30], tkl, tkc)
else:
retval = Token(tokens[buff_cont], buff_cont, tkl, tkc)
del buffer[:]
return retval
##############################################################
# #
# Intermediate code related functions #
# #
##############################################################
def next_quad():
return nextlabel
def gen_quad(op=None, arg1='_', arg2='_', res='_'):
global nextlabel
label = nextlabel
nextlabel += 1
newquad = Quad(label, op, arg1, arg2, res)
quad_code.append(newquad)
def new_temp():
global tmpvars, next_tmpvar
key = 'T_'+str(next_tmpvar)
tmpvars[key] = None
offset = scopes[-1].get_offset()
scopes[-1].addEntity(TmpVar(key, offset))
next_tmpvar += 1
return key
def empty_list():
return list()
def make_list(label):
newlist = list()
newlist.append(label)
return newlist
def merge(list1, list2):
return list1 + list2
def backpatch(somelist, res):
global quad_code
for quad in quad_code:
if quad.label in somelist:
quad.res = res
# Generate a file containing the intermediate code
# of the user program.
def generate_int_code_file():
for quad in quad_code:
int_file.write(quad.tofile() + '\n')
int_file.close()
# A naive way to find which variables should be declared.
def find_var_decl(quad):
vars = dict()
index = quad_code.index(quad) + 1
while True:
q = quad_code[index]
if q.op == 'end_block':
break
if q.arg2 not in ('CV', 'REF', 'RET') and q.op != 'call':
if isinstance(q.arg1, str):
vars[q.arg1] = 'int'
if isinstance(q.arg2, str):
vars[q.arg2] = 'int'
if isinstance(q.res, str):
vars[q.res] = 'int'
index += 1
if '_' in vars:
del vars['_']
return OrderedDict(sorted(vars.items()))
# Transform variable declarations to ANSI C equivalent.
def transform_decls(vars):
flag = False
retval = '\n\tint '
for var in vars:
flag = True
retval += var + ', '
if flag == True:
return retval[:-2] + ';'
else:
return ''
# Transform a quad to ANSI C code.
def transform_to_c(quad):
addlabel = True
if quad.op == 'jump':
retval = 'goto L_' + str(quad.res) + ';'
elif quad.op in ('=', '<>', '<', '<=', '>', '>='):
op = quad.op
if op == '=':
op = '=='
elif op == '<>':
op = '!='
retval = 'if (' + str(quad.arg1) + ' ' + op + ' ' + \
str(quad.arg2) + ') goto L_' + str(quad.res) + ';'
elif quad.op == ':=':
retval = quad.res + ' = ' + str(quad.arg1) + ';'
elif quad.op in ('+', '-', '*', '/'):
retval = quad.res + ' = ' + str(quad.arg1) + ' ' + \
str(quad.op) + ' ' + str(quad.arg2) + ';'
elif quad.op == 'out':
retval = 'printf("%d\\n", ' + str(quad.arg1) + ');'
elif quad.op == 'retv':
retval = 'return (' + str(quad.arg1) + ');'
elif quad.op == 'begin_block':
addlabel = False
if quad.arg1 == mainprog_name:
retval = 'int main(void)\n{'
else: # Should never reach else.
retval = 'int ' + quad.arg1 + '()\n{'
vars = find_var_decl(quad)
retval += transform_decls(vars)
retval += '\n\tL_' + str(quad.label) + ':'
elif quad.op == 'call':
# Should never reach this line.
retval = quad.arg1 + '();'
elif quad.op == 'end_block':
addlabel = False
retval = '\tL_' + str(quad.label) + ': {}\n'
retval += '}\n'
elif quad.op == 'halt':
retval = 'return 0;' # change to exit() if arbitrary
# halt statements are enabled
# at a later time.
else:
return None
if addlabel == True:
retval = '\tL_' + str(quad.label) + ': ' + retval
return retval
# Generate a file containing the ANSI C equivalent code
# of intermediate code. This file is ready to compile.
def generate_c_code_file():
ceq_file.write('#include <stdio.h>\n\n')
ceq_file.write('/* This file was automatically generated by:\n')
ceq_file.write(' * CiScal Compiler ' + __version__ + '\n')
ceq_file.write(' */\n\n')
for quad in quad_code:
tmp = transform_to_c(quad)
if tmp != None:
ceq_file.write(tmp + '\n')
ceq_file.close()
##############################################################
# #
# Symbol table related functions #
# #
##############################################################
# Add a new scope.
def add_new_scope():
enclosing_scope = scopes[-1]
curr_scope = Scope(enclosing_scope.nested_level + 1, enclosing_scope)
scopes.append(curr_scope)
# Print current scope and its enclosing ones.
def print_scopes():
print('* main scope\n|')
for scope in scopes:
level = scope.nested_level + 1
print(' ' * level + str(scope))
for entity in scope.entities:
print('| ' * level + str(entity))
if isinstance(entity, Function):
for arg in entity.args:
print('| ' * level + '| ' + str(arg))
print('\n')
# Add a new function entity.
def add_func_entity(name):
# Function declarations are on the enclosing scope of
# the current scope.
nested_level = scopes[-1].enclosing_scope.nested_level
if not unique_entity(name, "FUNCTION", nested_level):
perror_line_exit(5, token.tkl, token.tkc,
'Redefinition of \'%s\'' % name)
if in_function[-1] == True:
ret_type = "int"
else:
ret_type = "void"
scopes[-2].addEntity(Function(name, ret_type))
# Update the start quad label of a function entity.
def update_func_entity_quad(name):
start_quad = next_quad()
if name == mainprog_name:
return start_quad
func_entity = search_entity(name, "FUNCTION")[0]
func_entity.set_start_quad(start_quad)
return start_quad
# Update the framelength of a function entity.
def update_func_entity_framelen(name, framelength):
global main_programs_framelength
if name == mainprog_name:
main_programs_framelength = framelength
return
func_entity = search_entity(name, "FUNCTION")[0]
func_entity.set_framelen(framelength)
# Add a new parameter entity.
def add_param_entity(name, par_mode):
nested_level = scopes[-1].nested_level
par_offset = scopes[-1].get_offset()
if not unique_entity(name, "PARAMETER", nested_level):
perror_line_exit(5, token.tkl, token.tkc,
'Redefinition of \'%s\'' % name)
scopes[-1].addEntity(Parameter(name, par_mode, par_offset))
# Add a new variable entity.
def add_var_entity(name):
nested_level = scopes[-1].nested_level
var_offset = scopes[-1].get_offset()
if not unique_entity(name, "VARIABLE", nested_level):
perror_line_exit(5, token.tkl, token.tkc,
'Redefinition of \'%s\'' % name)
if var_is_param(name, nested_level):
perror_line_exit(5, token.tkl, token.tkc,
'\'%s\' redeclared as different kind of symbol' % name)
scopes[-1].addEntity(Variable(name, var_offset))
# Add a new function argument to a given function.
def add_func_arg(func_name, par_mode):
if (par_mode == 'in'):
new_arg = Argument('CV')
else:
new_arg = Argument('REF')
func_entity = search_entity(func_name, "FUNCTION")[0]
if func_entity == None:
perror_line_exit(5, token.tkl, token.tkc,
'No definition of \'%s\' was not found' % func_name)
if func_entity.args != list():
func_entity.args[-1].set_next(new_arg)
func_entity.add_arg(new_arg)
# Search for an entity named 'name' of type 'etype'.
def search_entity(name, etype):
if scopes == list():
return
tmp_scope = scopes[-1]
while tmp_scope != None:
for entity in tmp_scope.entities:
if entity.name == name and entity.etype == etype:
return entity, tmp_scope.nested_level
tmp_scope = tmp_scope.enclosing_scope
# Search for an entity named 'name'.
def search_entity_by_name(name):
if scopes == list():
return
tmp_scope = scopes[-1]
while tmp_scope != None:
for entity in tmp_scope.entities:
if entity.name == name:
return entity, tmp_scope.nested_level
tmp_scope = tmp_scope.enclosing_scope
# Check if entity named 'name' of type 'etype' at nested level
# 'nested_level' is redefined.
def unique_entity(name, etype, nested_level):
if scopes[-1].nested_level < nested_level:
return
scope = scopes[nested_level]
list_len = len(scope.entities)
for i in range(list_len):
for j in range(list_len):
e1 = scope.entities[i]
e2 = scope.entities[j]
if e1.name == e2.name and e1.etype == e2.etype \
and e1.name == name and e1.etype == etype:
return False
return True
# Check if a variable entity named 'name' already exists
# as a parameter entity.
def var_is_param(name, nested_level):
if scopes[-1].nested_level < nested_level:
return
scope = scopes[nested_level]
list_len = len(scope.entities)
for i in range(list_len):
e = scope.entities[i]
if e.etype == "PARAMETER" and e.name == name:
return True
return False
##############################################################
# #
# Final code related functions #
# #
##############################################################
# Load in register $t0 the address of the non-local variable 'v'.
def gnvlcode(v):
try:
tmp_entity, elevel = search_entity_by_name(v)
except:
perror_exit(7, 'Undeclared variable:', v)
if tmp_entity.etype == 'FUNCTION':
perror_exit(7, 'Undeclared variable:', v)
curr_nested_level = scopes[-1].nested_level
outfile.write(' lw $t0, -4($sp)\n')
n = curr_nested_level - elevel - 1
while n > 0:
outfile.write(' lw $t0, -4($t0)\n')
n -= 1
outfile.write(' addi $t0, $t0, -%d\n' % tmp_entity.offset)
# Load immediate or data 'v' from memory to register $t{r}.
def loadvr(v, r):
if str(v).isdigit():
outfile.write(' li $t%s, %d\n' % (r, v))
else:
try:
tmp_entity, elevel = search_entity_by_name(v)
except:
perror_exit(7, 'Undeclared variable:', v)
curr_nested_level = scopes[-1].nested_level
if tmp_entity.etype == 'VARIABLE' and elevel == 0:
outfile.write(' lw $t%s, -%d($s0)\n' % (r, tmp_entity.offset))
elif (tmp_entity.etype == 'VARIABLE' and \
elevel == curr_nested_level) or \
(tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'in' \
and elevel == curr_nested_level) or \
(tmp_entity.etype == 'TMPVAR'):
outfile.write(' lw $t%s, -%d($sp)\n' % (r, tmp_entity.offset))
elif tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'inout' \
and elevel == curr_nested_level:
outfile.write(' lw $t0, -%d($sp)\n' % tmp_entity.offset)
outfile.write(' lw $t%s, 0($t0)\n' % r)
elif (tmp_entity.etype == 'VARIABLE' and \
elevel < curr_nested_level) or \
(tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'in' \
and elevel < curr_nested_level):
gnvlcode(v)
outfile.write(' lw $t%s, 0($t0)\n' % r)
elif tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'inout' \
and elevel < curr_nested_level:
gnvlcode(v)
outfile.write(' lw $t0, 0(%t0)\n')
outfile.write(' lw $t%s, 0($t0)\n' % r)
else:
perror_exit(6, 'loadvr loads an immediate or data from memory'
'to a register')
# Store the contents of register $t{r} to the memory allocated for variable 'v'.
def storerv(r, v):
try:
tmp_entity, elevel = search_entity_by_name(v)
except:
perror_exit(7, 'Undeclared variable:', v)
curr_nested_level = scopes[-1].nested_level
if tmp_entity.etype == 'VARIABLE' and elevel == 0:
outfile.write(' sw $t%s, -%d($s0)\n' % (r, tmp_entity.offset))
elif (tmp_entity.etype == 'VARIABLE' and \
elevel == curr_nested_level) or \
(tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'in' \
and elevel == curr_nested_level) or \
(tmp_entity.etype == 'TMPVAR'):
outfile.write(' sw $t%s, -%d($sp)\n' % (r, tmp_entity.offset))
elif tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'inout' \
and elevel == curr_nested_level:
outfile.write(' lw $t0, -%d($sp)\n' % tmp_entity.offset)
outfile.write(' sw $t%s, 0($t0)\n' % r)
elif (tmp_entity.etype == 'VARIABLE' and \
elevel < curr_nested_level) or \
(tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'in' \
and elevel < curr_nested_level):
gnvlcode(v)
outfile.write(' sw $t%s, 0($t0)\n' % r)
elif tmp_entity.etype == 'PARAMETER' and tmp_entity.par_mode == 'inout' \
and elevel < curr_nested_level:
gnvlcode(v)
outfile.write(' lw $t0, 0(%t0)\n')
outfile.write(' sw $t%s, 0($t0)\n' % r)
else:
perror_exit(6, 'storerv stores the contents of a register to memory')
# Generate the assembly code for quad 'quad'. 'block_name' is the name
# of the block that is currently translated into final code.
def gen_mips_asm(quad, block_name):
global actual_pars
if str(quad.label) == '0':
outfile.write(' ' * 70) # Will be later overwritten
outfile.write('\nL_' + str(quad.label) + ': #' + quad.tofile() + '\n')
csc_relop = ('=', '<>', '<', '<=', '>', '>=')
asm_relop = ('beq', 'bne', 'blt', 'ble', 'bgt', 'bge')
csc_op = ('+', '-', '*', '/')
asm_op = ('add', 'sub', 'mul', 'div')
if quad.op == 'jump':
outfile.write(' j L_%d\n' % quad.res)
elif quad.op in csc_relop:
relop = asm_relop[csc_relop.index(quad.op)]
loadvr(quad.arg1, '1')
loadvr(quad.arg2, '2')
outfile.write(' %s $t1, $t2, L_%d\n' % (relop, quad.res))
elif quad.op == ':=':
loadvr(quad.arg1, '1')
storerv('1', quad.res)
elif quad.op in csc_op:
op = asm_op[csc_op.index(quad.op)]
loadvr(quad.arg1, '1')
loadvr(quad.arg2, '2')
outfile.write(' %s $t1, $t1, $t2\n' % op)
storerv('1', quad.res)
elif quad.op == 'out':
loadvr(quad.arg1, '9')
outfile.write(' li $v0, 1\n')
outfile.write(' add $a0, $zero, $t9\n')
outfile.write(' syscall # service code 1: print integer\n')
outfile.write(' la $a0, newline\n')
outfile.write(' li $v0, 4\n')
outfile.write(' syscall # service code 4: print (a null terminated) string\n')
elif quad.op == 'retv':
loadvr(quad.arg1, '1')
outfile.write(' lw $t0, -8($sp)\n')
outfile.write(' sw $t1, 0($t0)\n')
# Actually return to caller; just like end_block case.
outfile.write(' lw $ra, 0($sp)\n')
outfile.write(' jr $ra\n')
elif quad.op == 'halt':
outfile.write(' li $v0, 10 # service code 10: exit\n')
outfile.write(' syscall\n')
elif quad.op == 'par':
if block_name == mainprog_name:
caller_level = 0
framelength = main_programs_framelength
else:
caller_entity, caller_level = search_entity(block_name, 'FUNCTION')
framelength = caller_entity.framelength
if actual_pars == []:
outfile.write(' addi $fp, $sp, -%d\n' % framelength)
actual_pars.append(quad)
param_offset = 12 + 4 * actual_pars.index(quad)
if quad.arg2 == 'CV':
loadvr(quad.arg1, '0')
outfile.write(' sw $t0, -%d($fp)\n' % param_offset)
elif quad.arg2 == 'REF':
try:
var_entity, var_level = search_entity_by_name(quad.arg1)
except:
perror_exit(7, 'Undeclared variable:', quad.arg1)
if caller_level == var_level:
if var_entity.etype == 'VARIABLE' or \
(var_entity.etype == 'PARAMETER' and \
var_entity.par_mode == 'in'):
outfile.write(' addi $t0, $sp, -%s\n' % var_entity.offset)
outfile.write(' sw $t0, -%d($fp)\n' % param_offset)
elif var_entity.etype == 'PARAMETER' and \
var_entity.par_mode == 'inout':
outfile.write(' lw $t0, -%d($sp)\n' % var_entity.offset)
outfile.write(' sw $t0, -%d($fp)\n' % param_offset)
else:
if var_entity.etype == 'VARIABLE' or \
(var_entity.etype == 'PARAMETER' and \
var_entity.par_mode == 'in'):
gnvlcode(quad.arg1)
outfile.write(' sw $t0, -%d($fp)\n' % param_offset)
elif var_entity.etype == 'PARAMETER' and \
var_entity.par_mode == 'inout':
gnvlcode(quad.arg1)
outfile.write(' lw $t0, 0($t0)\n')
outfile.write(' sw $t0, -%d($fp)\n' % param_offset)
elif quad.arg2 == 'RET':
try:
var_entity, var_level = search_entity_by_name(quad.arg1)
except:
perror_exit(7, 'Undeclared variable:', quad.arg1)
outfile.write(' addi $t0, $sp, -%d\n' % var_entity.offset)
outfile.write(' sw $t0, -8($fp)\n')
elif quad.op == 'call':
if block_name == mainprog_name:
caller_level = 0
framelength = main_programs_framelength
else:
caller_entity, caller_level = search_entity(block_name, 'FUNCTION')
framelength = caller_entity.framelength
try:
callee_entity, callee_level = search_entity(quad.arg1, 'FUNCTION')
except:
perror_exit(7, 'Undefined function/procedure:', quad.arg1)
check_subprog_args(callee_entity.name)
if caller_level == callee_level:
outfile.write(' lw $t0, -4($sp)\n')
outfile.write(' sw $t0, -4($fp)\n')
else: