-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcapi.py
1558 lines (1393 loc) · 46.9 KB
/
capi.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
#------------------------------------------------------
# Capi Lang
# capi.py
#
# By:
# Luis Felipe Alvarez & David Cantu Martinez
#
#------------------------------------------------------
import ply.lex as lex
from collections import deque #Para el stack de scopes
from semantic_cube import *
from util import get_type_s
from memory import get_next_global, get_next_local, get_next_temporal, get_const_address, get_next_local_list, get_next_global_list
from virtual import init_virtual
import argparse
# Inits the semantic cube
s_cube = semantic_cube()
tokens = (
'ID','IF','ELSE','EX','TERMS','RELOP','LOGIC','LEFTPAR','RIGHTPAR',
'LEFTKEY','RIGHTKEY','LEFTBRACKET','RIGHTBRACKET','EQUAL','SEMICOLON',
'COLON','COMMA','VAR','TINT','TFLOAT','TSTRING','INT','FLOAT','STRING',
'FOR','FUNC','WHILE','GLOBAL','LIST','TLIST','OBJECT','TOBJECT','DOT','PRINT',
'RUN','START','RETURN','TRUE','FALSE','TBOOL', 'COMMENT', 'VOID', 'DRAW', 'SIZE','INIT',
"HEAD","LAST","SET_TITLE","CREATE_TEXT", "UPDATE", "SET_DIMENSION","GET_EVENT","POW","SQRT","QUIT","SET_FILL", 'MAIN',"BAR", "WINDOW_H", "WINDOW_W", "CAPIGAME","FIND","RAND"
)
# This is used to handle reserved words
reserved = {
'int':'TINT',
'float':'TFLOAT',
'bool' : 'TBOOL',
'string':'TSTRING',
'true':'TRUE',
'false':'FALSE',
'if':'IF',
'else':'ELSE',
'var':'VAR',
'for':'FOR',
'while':'WHILE',
'global':'GLOBAL',
'func':'FUNC',
'main' :'MAIN',
'list':'TLIST',
'print':'PRINT',
'object': 'TOBJECT',
'run': 'RUN',
'start': 'START',
'return': 'RETURN',
'void': 'VOID',
'draw':'DRAW',
'init': 'INIT',
'size':'SIZE',
'head':'HEAD',
'find':'FIND',
'last':'LAST',
'update' : "UPDATE",
'set_fill': 'SET_FILL',
'get_event': 'GET_EVENT',
'set_title': 'SET_TITLE',
'create_text': 'CREATE_TEXT',
'set_dimension': 'SET_DIMENSION',
'window_h': 'WINDOW_H',
'window_w': 'WINDOW_W',
'rand':'RAND',
'pow':'POW',
'quit': 'QUIT',
'sqrt':'SQRT',
'capigame':'CAPIGAME',
}
# Argument parser.
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--file",
type=argparse.FileType("r"),
help="The capi file used as source",
required=True,
)
args = parser.parse_args()
fileName = args.file
# Used for generating code
class quadruple():
def __init__(self, operator, left_operand, right_operand, temp, isptr = False):
self.id = -1
self.operator = operator
self.left_operand = left_operand
self.right_operand = right_operand
self.temp = temp
self.isptr = isptr
def __str__(self):
return f'operator: {self.operator}, left_operand: {self.left_operand}, right_operand: {self.right_operand}, temp: {self.temp}, isptr:{self.isptr}\n'
def __repr__(self):
return f'operator: {self.operator}, left_operand: {self.left_operand}, right_operand: {self.right_operand}, temp: {self.temp}, isptr:{self.isptr}\n'
# Used for variables
class variable():
def __init__(self, varid, vartype, address, dim, array_block = None):
self.id = varid
self.type = vartype
self.address = address
self.dim = dim
self.array_block = array_block
def __str__(self):
return f'Id: {self.id}, Type: {self.type}, Addr: {self.address}, Dim: {self.dim}, ArrayBlock:{self.array_block}'
def __repr__(self):
return f'Id: {self.id}, Type: {self.type}, Addr: {self.address}, Dim: {self.dim}, ArrayBlock:{self.array_block}'
# Used for list type variables
class array_block():
def __init__(self, array_type ,left, right, k):
self.array_type = array_type
self.left = left
self.right = right
self.k = k
def __str__(self):
return f'array_type: {self.array_type}, left: {self.left}, right: {self.right}, k: {self.k}'
def __repr__(self):
return f'array_type: {self.array_type}, left: {self.left}, right: {self.right}, k: {self.k}'
# Used for creating function scope
class function_values():
def __init__(self, functiontype='', params=[], scopevars={}, params_order=[]):
self.functiontype = functiontype
self.params = params.copy()
self.vars = scopevars.copy()
self.params_order = params_order.copy()
self.temp_count = 0
self.cont = -1
def __str__(self):
return f'Type: {self.functiontype}, Params: {self.params}, Vars: {self.vars}, Params_Order: {self.params_order}, CONT: {self.cont}, TEMP_COUNT: {self.temp_count}\n'
def __repr__(self):
return f'Type: {self.functiontype}, Params: {self.params}, Vars: {self.vars}, Params_Order: {self.params_order}, CONT: {self.cont}, TEMP_COUNT: {self.temp_count}\n'
# Gets the type of the id
def get_typeof_id(inc_id):
current_active_scopes = active_scopes.copy()
current_type = ""
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if inc_id in current_vars:
current_type = current_vars[inc_id].type
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0):
raise Exception("Variable does not exist")
else:
operand_stack.append(inc_id)
types_stack.append(current_type)
return current_type
# Gets the type of id for both vars and params
def get_typeof_id_vp(inc_id):
current_active_scopes = active_scopes.copy()
current_type = ""
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
current_params = current_active_scopes[-1].params
for param in current_params:
if inc_id == param.id:
current_type = param.type
break
if inc_id in current_vars:
current_type = current_vars[inc_id].type
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0 and current_type == ""):
raise Exception("Variable does not exist.")
return current_type
def get_next_avail(tp, convert = True):
global temporals
temporals +=1
if convert:
return get_next_temporal(get_type_s(tp))
return get_next_temporal(tp)
quadruples = [] # Quadruple List
current_callId = '' # This is the id of the current function call
current_returnAddress = '' # This is the current return Address when handling returns in functions
is_assign_for = False # We use this when handling assignation of variables inside forloop
current_functionId = '' # This is the id of the current function. It is used when declaring functions
operator_stack = deque() # Operator Stack
operand_stack = deque() # Operand Stack
types_stack = deque() # Types Stack
go_to_stack = deque() # Jump Stack
dimension_stack = deque() #Used to store the current dimension of the array
params_stack = deque() # We use this to handle params
expression_counter = 0 # We use this to count the expressions
temporals = 0 # This is used to count the temporals in a context
func_dir = {} # Function Directory
active_scopes = deque() # Scope stacks
active_scopes.append(function_values('global', [], {}))
t_EQUAL = r'\='
t_RELOP = r'\<\=|\>\=|\>|\<|\!\=|\=\='
t_LOGIC = r'\|\| | \&\&'
t_EX = r'\+|\-'
t_TERMS = r'\*|\/'
t_LEFTPAR = r'\('
t_RIGHTPAR = r'\)'
t_LEFTKEY = r'\{'
t_RIGHTKEY = r'\}'
t_LEFTBRACKET = r'\['
t_RIGHTBRACKET = r'\]'
t_SEMICOLON = r';'
t_COLON = r':'
t_COMMA = r','
t_DOT = r'\.'
t_BAR = r'\|'
relop_arr = ['<=',">=",">","<","!=","=="]
logic_arr = ["||","&&"]
def t_FLOAT(t):
r'\d+\.\d+'
t.value = float(t.value)
return t
def t_INT(t):
r'-?\d+'
t.value = int(t.value)
return t
def t_STRING(t):
r'\"[a-zA-Z_ ][a-zA-Z0-9_ ]*\"'
return t
def t_TRUE(t):
r'(true)'
t.value = 1
return t
def t_FALSE(t):
r'(false)'
t.value = 0
return t
def t_COMMENT(t):
r'\@.*'
pass
# No return value. Token discarded
# Ignored characters
t_ignore = " \t\r\n\f\v"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_ID(t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
if t.value in reserved:
t.type = reserved[t.value]
else:
t.type = 'ID'
return t
def t_error(t):
print(f"Illegal character {t.value[0]!r}")
t.lexer.skip(1)
lex = lex.lex()
# Program
def p_capi(p):
'''
capi : capi_action1 global recfunc MAIN COLON LEFTKEY start capi_action2 run RIGHTKEY SEMICOLON
| capi_action1 recfunc MAIN COLON LEFTKEY start capi_action2 run RIGHTKEY SEMICOLON
| capi_action1 global MAIN COLON LEFTKEY start capi_action2 run RIGHTKEY SEMICOLON
| capi_action1 MAIN COLON LEFTKEY start capi_action2 run RIGHTKEY SEMICOLON
'''
def p_capi_action1(p):
'''
capi_action1 :
'''
# This goto is created to be used later in the start function. This is used so that at the start of the
# program it jumps to the start function.
quadruples.append(quadruple("GOTO",None,None,None))
def p_capi_action2(p):
'''
capi_action2 :
'''
quadruples[0] = quadruple("GOTO",None,None,func_dir['start'].cont - 1)
def p_global(p):
'''
global : GLOBAL COLON LEFTKEY vars RIGHTKEY SEMICOLON
| GLOBAL COLON LEFTKEY RIGHTKEY SEMICOLON
'''
globalscope = active_scopes.pop()
func_dir['global'] = globalscope
active_scopes.append(globalscope)
def p_start(p):
'''
start : VOID FUNC start_action1 START startscope_action LEFTPAR RIGHTPAR main_cont block
'''
# We add the start function to the func dir
global temporals
new_func = active_scopes.pop()
new_func.temp_count = temporals
temporals = 0
new_func.functiontype = 'void'
new_func.params = []
new_func.params_order = []
func_dir[p[4]] = new_func
quadruples.append(quadruple("ENDFUNC", None,None, None))
def p_start_action1(p):
'''
start_action1 :
'''
quadruples.append(quadruple("ERA","start" ,None, None))
quadruples.append(quadruple("GOSUB","start",None,None))
def p_run(p):
'''
run : VOID FUNC run_action1 RUN startscope_action LEFTPAR RIGHTPAR main_cont block
'''
global temporals
new_func = active_scopes.pop()
new_func.temp_count = temporals
temporals = 0
new_func.functiontype = 'void'
new_func.params = []
new_func.params_order = []
func_dir[p[4]] = new_func
quadruples.append(quadruple("GOTO", None, None, go_to_stack.pop()))
quadruples.append(quadruple("ENDFUNC", None,None, None))
def p_run_action1(p):
'''
run_action1 :
'''
quadruples.append(quadruple("ERA", "run",None, None))
quadruples.append(quadruple("GOSUB","run",None,None))
go_to_stack.append(len(quadruples))
def p_main_cont(p):
'''
main_cont :
'''
active_scopes[-1].cont = len(quadruples) - 1
def p_vars(p):
'''
vars : VAR recids COLON type SEMICOLON vars
| VAR recids COLON type SEMICOLON
'''
global dimension_stack
rule_len = len(p) - 1
current_function = active_scopes.pop()
address = 0
current_list_addr = 0 # We use this to handle multiple declarations with same dimension
addr_popped = False # We use this to handle multiple declarations with same dimension
# We use a for in here so that we can handle multiple declarations
for l in p[2]:
if p[4][0] == 'list':
if not addr_popped:
current_list_addr = dimension_stack.pop()
addr_popped = True
if(current_function.functiontype == 'global'):
# We create global addresses
if p[4][0] == 'list':
address = get_next_global_list(p[4][1], current_list_addr)
else:
address = get_next_global(p[4])
else:
if p[4][0] == 'list':
address = get_next_local_list(p[4][1], current_list_addr)
else:
address = get_next_local(p[4])
if p[4][0] == 'list':
current_function.vars[l] = variable(l,p[4][0], address,1, array_block(p[4][1],get_const_address(0,'i'),current_list_addr,get_const_address(0,'i')))
else:
current_function.vars[l] = variable(l,p[4], address,get_const_address(0,'i'))
active_scopes.append(current_function)
def p_recids(p):
'''
recids : ID
| ID COMMA recids
'''
rule_len = len(p) - 1
if rule_len == 1:
p[0] = [p[1]]
elif rule_len == 3:
p[0] = [p[1]] + p[3]
def p_block(p):
'''
block : COLON LEFTKEY recstatement RIGHTKEY SEMICOLON
| COLON LEFTKEY RIGHTKEY SEMICOLON
'''
def p_recstatement(p):
'''
recstatement : statement recstatement
| statement
'''
def p_statement(p):
'''
statement : assign SEMICOLON
| condition
| vars
| loop
| write SEMICOLON
| return SEMICOLON
| functioncall SEMICOLON
| specialfunction SEMICOLON
'''
# In here we are sending the first instruction of our grammar
p[0] = p[1]
def p_specialfunction(p):
'''
specialfunction : draw
| init
| size
| head
| find
| last
| set_fill
| set_title
| get_event
| update
| window_h
| window_w
| set_dimension
| create_text
| rand
| pow
| sqrt
| quit
'''
p[0] = p[1]
def p_quit(p):
'''
quit : QUIT LEFTPAR RIGHTPAR
'''
quadruples.append(quadruple('QUIT', None, None, None))
def p_pow(p):
'''
pow : POW pow_action1 LEFTPAR expression COMMA expression RIGHTPAR
'''
pot = operand_stack.pop()
types_stack.pop()
num = operand_stack.pop()
t = types_stack.pop()
temp = get_next_avail('f', False)
quadruples.append(quadruple('POW', num, pot, temp))
operator_stack.pop()
p[0] = (temp, 'f')
def p_pow_action1(p):
'''
pow_action1 :
'''
operator_stack.append("|WALL|")
def p_sqrt(p):
'''
sqrt : SQRT sqrt_action1 LEFTPAR expression RIGHTPAR
'''
num = operand_stack.pop()
t = types_stack.pop()
temp = get_next_avail(t, False)
quadruples.append(quadruple('SQRT', num, None, temp))
operator_stack.pop()
p[0] = (temp, t)
def p_sqrt_action1(p):
'''
sqrt_action1 :
'''
operator_stack.append("|WALL|")
def p_draw(p):
'''
draw : CAPIGAME DOT DRAW LEFTPAR expression COMMA expression COMMA expression COMMA expression COMMA expression RIGHTPAR
'''
height = operand_stack.pop()
types_stack.pop()
width = operand_stack.pop()
types_stack.pop()
y = operand_stack.pop()
types_stack.pop()
x = operand_stack.pop()
types_stack.pop()
color = operand_stack.pop()
types_stack.pop()
temp = get_next_avail('o', False)
quadruples.append(quadruple('DRAW', color, (x,y,width,height), temp))
p[0] = (temp, 'o')
def p_init(p):
'''
init : CAPIGAME DOT INIT LEFTPAR RIGHTPAR
'''
quadruples.append(quadruple('INIT', None, None, None))
def p_size(p):
'''
size : ID DOT SIZE LEFTPAR RIGHTPAR
'''
var_id = p[1]
id_valid = False
size = 0
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if var_id in current_vars:
if current_vars[var_id].type == 'list':
is_valid = True
size = current_vars[var_id].array_block.right
else:
is_valid = False
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0 ):
raise Exception("Variable does not exist")
if not is_valid:
raise Exception("Size function does not exist for this type of variable.")
temp = get_next_avail('i', False)
quadruples.append(quadruple('SIZE', size, None, temp))
p[0] = (temp, 'i')
def p_head(p):
'''
head : ID DOT HEAD LEFTPAR RIGHTPAR
'''
var_id = p[1]
id_valid = False
address = 0
element_type = ''
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if var_id in current_vars:
if current_vars[var_id].type == 'list':
is_valid = True
address = current_vars[var_id].address
element_type = current_vars[var_id].array_block.array_type
else:
is_valid = False
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0 ):
raise Exception("Variable does not exist")
if not is_valid:
raise Exception("Size function does not exist for this type of variable.")
temp = get_next_avail(element_type, False)
quadruples.append(quadruple('HEAD', address, None, temp))
p[0] = (temp, element_type)
# Height of the window
def p_window_h(p):
'''
window_h : CAPIGAME DOT WINDOW_H LEFTPAR RIGHTPAR
'''
temp = get_next_avail('i', False)
quadruples.append(quadruple('WINDOW_H', None, None, temp))
p[0] = (temp, 'i')
# Width of the window
def p_window_w(p):
'''
window_w : CAPIGAME DOT WINDOW_W LEFTPAR RIGHTPAR
'''
temp = get_next_avail('i', False)
quadruples.append(quadruple('WINDOW_W', None, None, temp))
p[0] = (temp, 'i')
# Random number
def p_rand(p):
'''
rand : CAPIGAME DOT RAND LEFTPAR expression COMMA expression RIGHTPAR
'''
sup_num = operand_stack.pop()
types_stack.pop()
inf_num = operand_stack.pop()
types_stack.pop()
temp = get_next_avail('i', False)
quadruples.append(quadruple('RAND', inf_num, sup_num, temp))
p[0] = (temp, 'i')
# Find an element in an array
def p_find(p):
'''
find : ID DOT FIND LEFTPAR expression RIGHTPAR
'''
var_id = p[1]
id_valid = False
find_value = operand_stack.pop()
types_stack.pop()
address = 0
element_type = ''
right = 0
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if var_id in current_vars:
if current_vars[var_id].type == 'list':
is_valid = True
address = current_vars[var_id].address
right = current_vars[var_id].array_block.right
element_type = current_vars[var_id].array_block.array_type
else:
is_valid = False
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0 ):
raise Exception("Variable does not exist")
if not is_valid:
raise Exception("Find function does not exist for this type of variable.")
temp = get_next_avail('b', False)
quadruples.append(quadruple('FIND', (address, right), find_value, temp))
p[0] = (temp, 'b')
# Gets the last element of an array
def p_last(p):
'''
last : ID DOT LAST LEFTPAR RIGHTPAR
'''
var_id = p[1]
id_valid = False
address = 0
element_type = ''
right = 0
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if var_id in current_vars:
if current_vars[var_id].type == 'list':
is_valid = True
address = current_vars[var_id].address
right = current_vars[var_id].array_block.right
element_type = current_vars[var_id].array_block.array_type
else:
is_valid = False
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0 ):
raise Exception("Variable does not exist")
if not is_valid:
raise Exception("Last function does not exist for this type of variable.")
temp = get_next_avail(element_type, False)
quadruples.append(quadruple('LAST', address, right, temp))
p[0] = (temp, element_type)
# Sets the window title
def p_set_title(p):
'''
set_title : CAPIGAME DOT SET_TITLE LEFTPAR expression RIGHTPAR
'''
title = operand_stack.pop()
title_type = types_stack.pop()
# Quadruple used to send the title to the VM
if title_type == 's':
quadruples.append(quadruple('SET_TITLE', title, None, None))
else:
raise Exception("The title expression must be a string.")
# Sets the color of the window
def p_set_fill(p):
'''
set_fill : CAPIGAME DOT SET_FILL LEFTPAR expression COMMA expression COMMA expression RIGHTPAR
'''
b = operand_stack.pop()
g = operand_stack.pop()
r = operand_stack.pop()
types_stack.pop()
types_stack.pop()
types_stack.pop()
quadruples.append(quadruple('SET_FILL', r, g, b))
# Sets the dimension of the window
def p_set_dimension(p):
'''
set_dimension : CAPIGAME DOT SET_DIMENSION LEFTPAR expression COMMA expression RIGHTPAR
'''
x = operand_stack.pop()
y = operand_stack.pop()
types_stack.pop()
types_stack.pop()
# Quadruple used to send the dimension to the VM
quadruples.append(quadruple('SET_DIM', x, y, None))
# Updates the objects inside the run module.
def p_update(p):
'''
update : CAPIGAME DOT UPDATE LEFTPAR RIGHTPAR
'''
quadruples.append(quadruple('UPDATE', None, None, None))
# Gets the pygame events.
def p_get_event(p):
'''
get_event : CAPIGAME DOT GET_EVENT LEFTPAR RIGHTPAR
'''
temp = get_next_avail('s', False)
quadruples.append(quadruple('GET_EVENT', None, None, temp))
p[0] = (temp, 's')
# Creates a text object
def p_create_text(p):
'''
create_text : CREATE_TEXT LEFTPAR expression COMMA expression COMMA expression COMMA expression RIGHTPAR
'''
y = operand_stack.pop()
types_stack.pop()
x = operand_stack.pop()
types_stack.pop()
color = operand_stack.pop()
types_stack.pop()
text = operand_stack.pop()
types_stack.pop()
temp = get_next_avail('o', False)
quadruples.append(quadruple('CREATE_TEXT', text,(color,x,y), temp))
p[0] = (temp, 'o')
def p_assign(p):
'''
assign : ID assign_action1 EQUAL assign_action2 expression
| assign_list EQUAL assign_action2 expression
'''
# we need to do the same for var i :int = 5;
global is_assign_for
# We use this to ignore the wall and just pop it
if operator_stack[-1] == '|WALL|':
operator_stack.pop()
result = operand_stack.pop()
type_result = types_stack.pop()
quad_list = []
if len(operand_stack) > 0:
left_operand = operand_stack.pop()
left_operand_type = types_stack.pop()
operator = operator_stack.pop()
# We use this to distinguish list assign from the other types
if type(left_operand) is tuple:
expression_type = s_cube.validate_expression(type_result, left_operand_type, operator)
if expression_type != "ERROR":
address = ""
var_type = ""
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if left_operand[0] in current_vars:
address = current_vars[left_operand[0]].address
var_type = current_vars[left_operand[0]].type
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0):
raise Exception("Variable does not exist")
else:
quadruples.append(quadruple(operator, result, None, left_operand[1], True))
else:
raise Exception("Type mismatch at assignation")
else:
expression_type = s_cube.validate_expression(type_result, left_operand_type, operator)
if expression_type != "ERROR":
address = ""
var_type = ""
current_active_scopes = active_scopes.copy()
while len(current_active_scopes) != 0:
current_vars = current_active_scopes[-1].vars
if left_operand in current_vars:
address = current_vars[left_operand].address
var_type = current_vars[left_operand].type
break
current_active_scopes.pop()
if(len(current_active_scopes) <= 0):
raise Exception("Variable does not exist")
else:
quad_list.append(quadruple(operator, result, None, address))
if not is_assign_for:
quadruples.append(quadruple(operator, result, None, address))
else:
raise Exception("Type mismatch at assignation")
if is_assign_for:
p[0] = quad_list
is_assign_for = False
quad_list = []
def p_assign_action1(p):
'''
assign_action1 :
'''
current_id = p[-1] # Get current ID
get_typeof_id(current_id)
def p_assign_action2(p):
'''
assign_action2 :
'''
operator_stack.append(p[-1])
def p_condition(p):
''' condition : IF LEFTPAR expression condition_action1 RIGHTPAR block condition_action2
| IF LEFTPAR expression condition_action1 RIGHTPAR block condition_action3 ELSE block condition_action2
'''
def p_condition_action1(p):
'''
condition_action1 :
'''
exp_type = types_stack.pop()
if exp_type != "b":
raise Exception("Type mismatch.")
else:
result = operand_stack.pop()
# We generate our Goto_F for the if statement
quadruples.append(quadruple("GOTO_F", result,None,None))
go_to_stack.append(len(quadruples)-1)
def p_condition_action2(p):
'''
condition_action2 :
'''
jump = go_to_stack.pop()
quadruples[jump] = quadruple(quadruples[jump].operator, quadruples[jump].left_operand,None, len(quadruples))
def p_condition_action3(p):
'''
condition_action3 :
'''
false = go_to_stack.pop()
# We generate the GOTO Quadruple when we have an else in our if
quadruples.append(quadruple("GOTO", None,None,None))
go_to_stack.append(len(quadruples) - 1)
quadruples[false] = quadruple("GOTO_F",quadruples[false].left_operand,None,len(quadruples))
def p_loop(p):
'''
loop : for
| while
'''
def p_for(p):
'''
for : FOR startscope_action LEFTPAR assign SEMICOLON for_action1 expression for_action2 SEMICOLON assign SEMICOLON RIGHTPAR block for_action3
'''
new_func = active_scopes.pop() # Get the last function created
new_func.functiontype = "" # We clear out the name of the function
new_func.params = []
def p_for_action1(p):
'''
for_action1 :
'''
global is_assign_for
is_assign_for = True
go_to_stack.append(len(quadruples))
def p_for_action2(p):
'''
for_action2 :
'''
cond = operand_stack.pop()
cond_type = types_stack.pop()
if cond_type != "b":
raise Exception("Type mismatch.")
else:
# We use this GOTO_F to handle our for loop if the condition is false
quadruples.append(quadruple("GOTO_F", cond,None,None))
go_to_stack.append(len(quadruples)-1)
def p_for_action3(p):
'''
for_action3 :
'''
falso = go_to_stack.pop()
ref = go_to_stack.pop()
quad_list = p[-4]
for quad in quad_list:
quadruples.append(quad)
# We generate this to return to the expresion and re evaluate it
quadruples.append(quadruple("GOTO", None, None, ref))
quadruples[falso] = quadruple(quadruples[falso].operator, quadruples[falso].left_operand,None, len(quadruples))
def p_while(p):
'''
while : WHILE startscope_action while_action1 LEFTPAR expression while_action2 RIGHTPAR block while_action3
'''
new_func = active_scopes.pop() # Get the last function created
new_func.functiontype = "" # Assign empty string to the function type
new_func.params = []
def p_while_action1(p):
'''
while_action1 :
'''
go_to_stack.append(len(quadruples))
def p_while_action2(p):
'''
while_action2 :
'''
cond = operand_stack.pop()
cond_type = types_stack.pop()
if cond_type != "b":
raise Exception("Type mismatch.")
else:
# We use this quadruple to handle when the while expression is false
quadruples.append(quadruple("GOTO_F", cond,None,None))
go_to_stack.append(len(quadruples)-1)
def p_while_action3(p):
'''
while_action3 :
'''
falso = go_to_stack.pop()
ref = go_to_stack.pop()
# We generate this to return to the expresion and re evaluate it
quadruples.append(quadruple("GOTO", None, None, ref))
quadruples[falso] = quadruple(quadruples[falso].operator, quadruples[falso].left_operand,None, len(quadruples))
def p_function(p):
'''
function : type FUNC ID startscope_action LEFTPAR recparams function_action1 RIGHTPAR function_action2 function_action3 block
| type FUNC ID startscope_action LEFTPAR RIGHTPAR function_action3 block
| VOID FUNC ID startscope_action LEFTPAR recparams function_action1 RIGHTPAR function_action2 function_action3 block
| VOID FUNC ID startscope_action LEFTPAR RIGHTPAR function_action3 block
'''
global temporals, current_functionId,current_returnAddress
new_func = active_scopes.pop()
new_func.temp_count = temporals
# We generate this quadruple to hanlde when the function terminates
quadruples.append(quadruple("ENDFUNC",None,None,None))
temporals = 0
func_dir[p[3]] = new_func # We add the function to the function directory
if p[1] != "void":
# TODO We need to handle this error
if current_functionId in func_dir['global'].vars:
add = func_dir['global'].vars[current_functionId].address
for quad in quadruples:
if quad.operator != 'ERA' and quad.operator != 'GOSUB':
if quad.left_operand == current_functionId:
quad.left_operand = add
if quad.right_operand == current_functionId:
quad.right_operand = add
if quad.temp == current_functionId:
quad.temp = add
else:
raise Exception("Return missing in function:", current_functionId)
current_functionId = ""
current_returnAddress = ""
# We use this to handle scopes between, functions, while, for and if statements
def p_startscope_action(p):
'''
startscope_action :
'''
global current_functionId
if p[-1] in func_dir.keys():
raise Exception("Function name already exists.")
else:
if p[-1] != 'for' and p[-1] != 'while' and p[-1] != 'if':
current_functionId = p[-1]
new_function = function_values()
new_function.functiontype = p[-3]
active_scopes.append(new_function)
else:
new_function = function_values()
new_function.functiontype = p[-3]
active_scopes.append(new_function)
def p_function_action1(p):
'''
function_action1 :
'''
active_scopes[-1].params = p[-1]