-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.py
More file actions
1155 lines (1054 loc) · 36.3 KB
/
Copy pathparser.py
File metadata and controls
1155 lines (1054 loc) · 36.3 KB
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
import lexer as lexer
import ply.yacc as yacc
from datastructures import *
from quadruples import *
from error import Error
from virtualmachine import runner_duckie
tokens = lexer.tokens
arrMatId = Stack()
arrMatScope = Stack()
def p_program(t):
'program : PROGRAM ID globalTable SEMICOLON declaration programFunc main'
print("Compiled successfully")
# show variable table and function directory
# print()
# print(variableTable["constants"])
# for i in functionDir:
# print("\tfunction name: %s" % i)
# print("\t\ttype: %s" % functionDir[i]["type"])
# print("\t\tvars: %s" % functionDir[i]["vars"])
# if "params" in functionDir[i]:
# print("\t\tparams: %s" % functionDir[i]["params"].values())
# print("\t\tparamsLength: %d" % functionDir[i]["paramsLength"])
# print("\t\tstart: %d" % functionDir[i]["start"])
# print("\t\tvarLength: %d" % functionDir[i]["varLength"])
# print()
# operands.print()
# types.print()
# operators.print()
# Quadruples.print_all()
# variableTable.clear()
# arrMatOperands.print()
# global scope varTable
def p_globalTable(t):
'globalTable : '
variableTable["constants"] = {}
# Initialize variableTable for global and set program name and type
variableTable[currentScope] = {}
variableTable[currentScope][t[-1]] = {"type": "program"}
# Initialize functionDir for global scope
functionDir[currentScope] = {}
# Set type and vars as reference to variableTable["global"]
functionDir[currentScope]["type"] = "void"
functionDir[currentScope]["vars"] = variableTable[currentScope]
tmp_quad = Quadruple("GOTO", "_", "_", "_")
Quadruples.push_quad(tmp_quad)
Quadruples.push_jump(-1)
def p_programFunc(t):
'''programFunc : function programFunc
| '''
def p_main(t):
'main : mainTable MAIN LEFTPAR RIGHTPAR LEFTBRACE declaration statement RIGHTBRACE'
# main scope varTable
def p_mainTable(t):
'mainTable : '
global currentScope
# Add main to current scope varTable
variableTable[currentScope]["main"] = {"type": "void"}
currentScope = "main"
# Initialize variableTable and functionDir for main scope
variableTable[currentScope] = {}
functionDir[currentScope] = {}
# Set function type and vars as reference to variableTable["main"]
functionDir[currentScope]["type"] = "void"
functionDir[currentScope]["vars"] = variableTable[currentScope]
Quadruples.update_jump_quad(Quadruples.pop_jump(), Quadruples.next_id)
def p_assignment(t):
'assignment : ID dimArray EQUAL hyperExpression SEMICOLON'
# If id is in currentScope, generate quadruple and set its value in varTable
if arrMatOperands.size() > 1:
types.pop()
operands.pop()
operands.pop()
assign = arrMatOperands.pop()
address = arrMatOperands.pop()
if assign["type"] != address["type"]:
Error.type_mismatch_array_assignment(t.lexer.lineno)
if assign["rows"] != address["rows"] or assign["cols"] != address["cols"]:
Error.dimensions_do_not_match(t.lexer.lineno-1)
temp_quad = Quadruple("ARR=", assign, "_", address)
Quadruples.push_quad(temp_quad)
elif arrMatOperands.size() == 1:
Error.invalid_assignment_to_array_variable(t.lexer.lineno-1)
# Error class call
elif t[1] in variableTable[currentScope]:
if types.pop() == variableTable[currentScope][t[1]]["type"]:
if "rows" in variableTable[currentScope][t[1]]:
types.pop()
assign = operands.pop()
address = operands.pop()
temp_quad = Quadruple("=", assign, "_", address)
else:
types.pop()
address = variableTable[currentScope][t[1]]["address"]
temp_quad = Quadruple("=", operands.pop(), '_', address)
operands.pop()
Quadruples.push_quad(temp_quad)
else:
Error.type_mismatch(t[1],t.lexer.lineno - 1)
# If id is in global scope, generate quadruple and set its value in varTable
elif t[1] in variableTable["global"]:
if types.pop() == variableTable["global"][t[1]]["type"]:
if "rows" in variableTable["global"][t[1]]:
types.pop()
assign = operands.pop()
address = operands.pop()
temp_quad = Quadruple("=", assign, "_", address)
else:
types.pop()
address = variableTable["global"][t[1]]["address"]
temp_quad = Quadruple("=", operands.pop(), '_', address)
operands.pop()
Quadruples.push_quad(temp_quad)
else:
Error.type_mismatch(t[1],t.lexer.lineno - 1)
else:
Error.undefined_variable(t[1], t.lexer.lineno - 1)
def p_declaration(t):
'''declaration : VAR declarationPrim
| '''
# Set start quadruple start for function
functionDir[currentScope]["start"] = Quadruples.next_id
def p_declarationPrim(t):
'''declarationPrim : primitive vars SEMICOLON declarationPrim
| '''
def p_primitive(t):
'''primitive : INT
| FLOAT
| CHAR '''
# When stating type, change currentType for declaration
global currentType
currentType = t[1]
def p_return(t):
'return : RETURN LEFTPAR hyperExpression RIGHTPAR SEMICOLON'
def p_if(t):
'if : IF LEFTPAR hyperExpression RIGHTPAR createJumpQuadIf THEN LEFTBRACE statement RIGHTBRACE ifElse updateJumpQuad'
def p_createJumpQuadIf(t):
'createJumpQuadIf : '
result_type = types.pop()
# Check type and value for the evaluated expression and generate quadruple
if result_type == "int":
res = operands.pop()
operator = "GOTOF"
temp_quad = Quadruple(operator, res, '_', '_')
Quadruples.push_quad(temp_quad)
Quadruples.push_jump(-1)
else:
Error.condition_type_mismatch(t.lexer.lineno)
def p_updateJumpQuad(t):
'updateJumpQuad : '
# Update gotof quadruples
tmp_end = Quadruples.pop_jump()
tmp_count = Quadruples.next_id
Quadruples.update_jump_quad(tmp_end, tmp_count)
def p_ifElse(t):
'''ifElse : ELSE createJumpQuadElse LEFTBRACE statement RIGHTBRACE
| '''
def p_createJumpQuadElse(t):
'createJumpQuadElse : '
# Create quadruple for else
operator = "GOTO"
tmp_quad = Quadruple(operator, '_', '_', '_')
Quadruples.push_quad(tmp_quad)
tmp_false = Quadruples.pop_jump()
tmp_count = Quadruples.next_id
Quadruples.update_jump_quad(tmp_false, tmp_count)
Quadruples.push_jump(-1)
def p_comment(t):
'comment : COMMENT_TEXT'
def p_while(t):
'while : WHILE pushLoopJump LEFTPAR hyperExpression RIGHTPAR beginLoopAction LEFTBRACE statement RIGHTBRACE endLoopAction'
def p_pushLoopJump(t):
'pushLoopJump : '
Quadruples.push_jump(1)
def p_beginLoopAction(t):
'beginLoopAction : '
result_type = types.pop()
# Check expression type and value and add quadruple to stack
if result_type == "int":
res = operands.pop()
operator = "GOTOF"
# Generate Quadruple and push it to the list
tmp_quad = Quadruple(operator, res, "_", "_")
Quadruples.push_quad(tmp_quad)
# Push into jump stack
Quadruples.push_jump(-1)
else:
Error.condition_type_mismatch(t.lexer.lineno)
def p_endLoopAction(t):
'endLoopAction : '
# Generate quadruple when while finishes and update gotof
false_jump = Quadruples.pop_jump()
return_jump = Quadruples.pop_jump()
tmp_quad = Quadruple("GOTO", "_", "_", return_jump-1)
Quadruples.push_quad(tmp_quad)
next_id = Quadruples.next_id
Quadruples.update_jump_quad(false_jump, next_id)
def p_for(t):
'for : FOR forAssignment TO insertJumpFor hyperExpression createQuadFor LEFTBRACE statement RIGHTBRACE updateQuadFor'
def p_insertJumpFor(t):
'insertJumpFor : '
Quadruples.push_jump(0)
def p_createQuadFor(t):
'createQuadFor : '
result_type = types.pop()
# Check expression type and value and add quadruple to stack
if result_type == "int":
res = operands.pop()
operator = "GOTOF"
temp_quad = Quadruple(operator, res, '_', '_')
Quadruples.push_quad(temp_quad)
Quadruples.push_jump(-1)
else:
Error.condition_type_mismatch(t.lexer.lineno)
def p_updateQuadFor(t):
'updateQuadFor : '
# Update gotof quadruple when for finishes
tmp_end = Quadruples.jump_stack.pop()
tmp_rtn = Quadruples.jump_stack.pop()
tmp_quad = Quadruple("GOTO4", "_", "_", tmp_rtn)
Quadruples.push_quad(tmp_quad)
tmp_count = Quadruples.next_id
Quadruples.update_jump_quad(tmp_end, tmp_count)
def p_forAssignment(t):
'forAssignment : ID EQUAL CST_INT addTypeInt'
address_type = "cInt"
cstAddress = 0
if t[3] not in variableTable["constants"]:
variableTable["constants"][t[3]] = {"address": addresses[address_type], "type": "int"}
cstAddress = addresses[address_type]
addresses[address_type] += 1
else:
cstAddress = variableTable["constants"][t[3]]["address"]
if "rows" not in variableTable[currentScope][t[1]]:
# Check if id exists in currentScope and set its value
if t[1] in variableTable[currentScope]:
address = variableTable[currentScope][t[1]]["address"]
temp_quad = Quadruple("=", cstAddress, '_', address)
Quadruples.push_quad(temp_quad)
# Check if id exists in global scope and set its value
elif t[1] in variableTable["global"]:
address = variableTable["global"][t[1]]["address"]
temp_quad = Quadruple("=", t[3], '_', address)
Quadruples.push_quad(temp_quad)
else:
Error.undefined_variable(t[1], t.lexer.lineno)
else:
Error.invalid_assignment_to_array_variable(t.lexer.lineno)
def p_vars(t):
'vars : ID addVarsToTable varsArray varsComa'
def p_addVarsToTable(t):
'addVarsToTable : '
# If current ID (t[-1]) exists in scope or global, throw error
if t[-1] in variableTable[currentScope]:
Error.redefinition_of_variable(t[-1], t.lexer.lineno)
else:
# Add current ID (t[-1]) to variableTable[scope]
variableTable[currentScope][t[-1]] = {"type": currentType}
address_type = "g"
if currentScope != "global":
address_type = "l"
if currentType == "int":
address_type += "Int"
elif currentType == "float":
address_type += "Float"
else:
address_type += "Char"
variableTable[currentScope][t[-1]]["address"] = addresses[address_type]
addresses[address_type] += 1
global arrMatId
arrMatId = Stack()
arrMatId.push(t[-1])
def p_varsComa(t):
'''varsComa : COMA vars
| '''
def p_varsArray(t):
'''varsArray : LEFTBRACK CST_INT addTypeInt RIGHTBRACK setRows varsMatrix
| '''
address_type = "g"
const_address = "c"
if currentScope != "global":
address_type = "l"
if currentType == "int":
address_type += "Int"
const_address += "Int"
if currentType == "float":
address_type += "Float"
const_address += "Float"
if currentType == "char":
address_type += "Char"
const_address += "Char"
global arrMatId
arrMatAddress = variableTable[currentScope][arrMatId.peek()]["address"]
if "rows" in variableTable[currentScope][arrMatId.peek()] and "cols" not in variableTable[currentScope][arrMatId.peek()]:
rows = variableTable[currentScope][arrMatId.peek()]["rows"]
addresses[address_type] += rows - 1
variableTable["constants"][arrMatAddress] = {"address": addresses[const_address], "type": "int"}
addresses[const_address] += 1
if "cols" in variableTable[currentScope][arrMatId.peek()]:
rows = variableTable[currentScope][arrMatId.peek()]["rows"]
cols = variableTable[currentScope][arrMatId.peek()]["cols"]
addresses[address_type] += rows * cols - 1
variableTable["constants"][arrMatAddress] = {"address": addresses[const_address], "type": "int"}
addresses[const_address] += 1
arrMatId.pop()
def p_setRows(t):
'setRows : '
global arrMatId
if int(t[-3]) > 0:
variableTable[currentScope][arrMatId.peek()]["rows"] = int(t[-3])
operands.pop()
types.pop()
else:
Error.array_size_must_be_positive(arrMatId.peek(), t.lexer.lineno)
def p_varsMatrix(t):
'''varsMatrix : LEFTBRACK CST_INT addTypeInt RIGHTBRACK setCols
| '''
def p_setCols(t):
'setCols : '
global arrMatId
if int(t[-3]) > 0:
variableTable[currentScope][arrMatId.peek()]["cols"] = int(t[-3])
operands.pop()
types.pop()
else:
Error.array_size_must_be_positive(arrMatId.peek(), t.lexer.lineno)
def p_function(t):
'function : functionType ID addFuncToDir LEFTPAR param RIGHTPAR setParamLength LEFTBRACE declaration statement RIGHTBRACE'
# When exiting function scope, reset scope to global and delete variableTable and reference to it in functionDir
global currentScope
# del variableTable[currentScope]
# del functionDir[currentScope]["vars"]
# Create endfunc quadruple for function end
temp_quad = Quadruple("ENDFUNC", "_", "_", "_")
Quadruples.push_quad(temp_quad)
# Temporary variables = function quad length as maximum and reset func_quads
functionDir[currentScope]["varLength"] = len(functionDir[currentScope]["vars"])
Quadruples.func_quads = 0
currentScope = "global"
# Reset local addresses
addresses["lInt"] -= addresses["lInt"] % 1000
addresses["lFloat"] -= addresses["lFloat"] % 1000
addresses["lChar"] -= addresses["lChar"] % 1000
global returnMade
returnMade = False
def p_addFuncToDir(t):
'addFuncToDir : '
# If function exists in global scope, throw an error
if t[-1] in variableTable["global"]:
Error.redefinition_of_variable(t[-1], t.lexer.lineno)
else:
global currentScope
global currentType
# Add function to variableTable of currentScope
variableTable["global"][t[-1]] = {"type": currentType}
if currentType == "int":
address = addresses["gInt"]
addresses["gInt"] += 1
elif currentType == "float":
address = addresses["gFloat"]
addresses["gFloat"] += 1
elif currentType == "char":
address = addresses["gChar"]
addresses["gChar"] += 1
else:
address = addresses["void"]
variableTable["global"][t[-1]]["address"] = address
# Change scope to new function id
currentScope = t[-1]
# Initialize variableTable and functionDir for new function id
variableTable[currentScope] = {}
functionDir[currentScope] = {}
# Set new function type and vars as reference to variableTable[currentScope]
functionDir[currentScope]["type"] = currentType
functionDir[currentScope]["vars"] = variableTable[currentScope]
functionDir[currentScope]["params"] = Queue()
def p_functionType(t):
'''functionType : FUNCTION primitive
| FUNCTION VOID setVoidType '''
def p_setVoidType(t):
'setVoidType : '
# Set void as currentType
global currentType
currentType = t[-1]
def p_param(t):
'''param : primitive ID addFuncParams functionParam
| '''
def p_addFuncParams(t):
'addFuncParams : '
# If function param exists in scope, throw error
if t[-1] in variableTable[currentScope]:
Error.redefinition_of_variable(t[-1], t.lexer.lineno)
else:
# Add function param to variableTable of currentScope
variableTable[currentScope][t[-1]] = {"type": currentType}
if currentType == "int":
variableTable[currentScope][t[-1]]["address"] = addresses["lInt"]
addresses["lInt"] += 1
elif currentType == "float":
variableTable[currentScope][t[-1]]["address"] = addresses["lFloat"]
addresses["lFloat"] += 1
else:
variableTable[currentScope][t[-1]]["address"] = addresses["lChar"]
addresses["lChar"] += 1
if "params" not in functionDir[currentScope]:
functionDir[currentScope]["params"] = Queue()
# Insert currentTypes into params Queue
functionDir[currentScope]["params"].enqueue(currentType)
def p_setParamLength(t):
'setParamLength : '
# Set the function param number to the size of params Queue
functionDir[currentScope]["paramsLength"] = functionDir[currentScope]["params"].size()
def p_functionParam(t):
'''functionParam : COMA param
| '''
def p_cst_prim(t):
'''cst_prim : CST_INT addTypeInt
| CST_FLOAT addTypeFloat
| CST_CHAR addTypeChar'''
def p_addTypeInt(t):
'addTypeInt : '
types.push("int")
address_type = "cInt"
if t[-1] not in variableTable["constants"]:
variableTable["constants"][t[-1]] = {"address": addresses[address_type], "type": "int"}
operands.push(variableTable["constants"][t[-1]]["address"])
addresses[address_type] += 1
else:
operands.push(variableTable["constants"][t[-1]]["address"])
def p_addTypeFloat(t):
'addTypeFloat : '
types.push("float")
address_type = "cFloat"
if t[-1] not in variableTable["constants"]:
variableTable["constants"][t[-1]] = {"address": addresses[address_type], "type": "float"}
operands.push(variableTable["constants"][t[-1]]["address"])
addresses[address_type] += 1
else:
operands.push(variableTable["constants"][t[-1]]["address"])
def p_addTypeChar(t):
'addTypeChar : '
types.push("char")
address_type = "cChar"
if t[-1] not in variableTable["constants"]:
variableTable["constants"][t[-1]] = {"address": addresses[address_type]}
operands.push(variableTable["constants"][t[-1]]["address"])
addresses[address_type] += 1
else:
operands.push(variableTable["constants"][t[-1]]["address"])
def p_hyperExpression(t):
'''hyperExpression : superExpression evaluateHE opHyperExpression hyperExpressionNested
| superExpression opMatrix evaluateOpMatrix
| superExpression evaluateHE'''
def p_hyperExpressionNested(t):
'''hyperExpressionNested : superExpression evaluateHE opHyperExpression hyperExpressionNested
| superExpression evaluateHE'''
def p_evaluateOpMatrix(t):
'evaluateOpMatrix : '
if operators.size() != 0:
if operators.peek() == "!" or operators.peek() == "?" or operators.peek() == "$":
# Pop operands
operands.pop()
# Pop operator
oper = operators.pop()
# Pop types
operandType = types.pop()
# Check semanticCube with types and operator
resType = semanticCube[(operandType, operandType, oper)]
oper = "ARR" + oper
if oper == "ARR!" or oper == "ARR?":
if arrMatOperands.size() > 1:
arrOperand = arrMatOperands.pop()
# $ return type => float
# ! return type => mat with inverted rows and cols
# ? return type => mat with same row and cols
if "cols" not in arrOperand:
arrOperand["cols"] = 1
if (arrOperand["rows"] == arrOperand["cols"] and oper == "ARR?") or oper == "ARR!":
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, arrOperand, "_", addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
if oper == "ARR?":
arrMatOperands.push({
"address": addresses[address_type],
"rows": arrOperand["rows"],
"cols": arrOperand["cols"],
"type": "float"
})
addresses[address_type] += arrOperand["rows"] * arrOperand["cols"]
elif oper == "ARR!":
arrMatOperands.push({
"address": addresses[address_type],
"rows": arrOperand["cols"],
"cols": arrOperand["rows"],
"type": resType
})
addresses[address_type] += arrOperand["rows"] * arrOperand["cols"]
types.push(resType)
else:
Error.invalid_operation_in_line(t.lexer.lineno)
else:
Error.invalid_inverse_calculation(t.lexer.lineno)
else:
Error.invalid_operation_in_line(t.lexer.lineno)
else:
arrOperand = arrMatOperands.pop()
if arrOperand["rows"] == arrOperand["cols"]:
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, arrOperand, "_", addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
addresses[address_type] += 1
types.push(resType)
else:
Error.invalid_operation_in_line(t.lexer.lineno)
else:
Error.invalid_determinant_calculation(t.lexer.lineno)
def p_evaluateHE(t):
'evaluateHE : '
if operators.size() != 0:
# Generate quadruple for or/and expressions
if operators.peek() == "|" or operators.peek() == "&":
# Pop operands
rOp = operands.pop()
lOp = operands.pop()
# Pop operators
oper = operators.pop()
# Pop types
rType = types.pop()
lType = types.pop()
# Check semanticCube with types and operator
resType = semanticCube[(lType, rType, oper)]
if arrMatOperands.size() > 0:
Error.invalid_operation_in_line(t.lexer.lineno)
# Check type and value
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, lOp, rOp, addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
addresses[address_type] += 1
types.push(resType)
else:
Error.operation_type_mismatch(t.lexer.lineno)
def p_opMatrix(t):
'''opMatrix : EXCLAMATION addOperator
| QUESTION addOperator
| DOLLARSIGN addOperator '''
def p_opHyperExpression(t):
'''opHyperExpression : AND addOperator
| OR addOperator '''
def p_superExpression(t):
'''superExpression : exp evaluateSE opSuperExpression exp evaluateSE
| exp evaluateSE '''
def p_evaluateSE(t):
'evaluateSE : '
if operators.size() != 0:
# Generate quadruple for comparison operators
if operators.peek() == ">" or operators.peek() == "<" or operators.peek() == "<>" or operators.peek() == "==":
# Pop operands
rOp = operands.pop()
lOp = operands.pop()
# Pop operator
oper = operators.pop()
# Pop types
rType = types.pop()
lType = types.pop()
# Check semanticCube for types and operator
resType = semanticCube[(lType, rType, oper)]
if arrMatOperands.size() > 0:
Error.invalid_operation_in_line(t.lexer.lineno)
# Check result type and evaluate expression
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, lOp, rOp, addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
addresses[address_type] += 1
types.push(resType)
else:
Error.operation_type_mismatch(t.lexer.lineno)
def p_opSuperExpression(t):
'''opSuperExpression : GT addOperator
| LT addOperator
| NOTEQUAL addOperator
| ISEQUAL addOperator'''
def p_exp(t):
'''exp : term evaluateTerm expFunction
| term evaluateTerm '''
def p_evaluateTerm(t):
'evaluateTerm : '
if operators.size() != 0:
# Generate quadruple for add/subtract operators
if operators.peek() == "+" or operators.peek() == "-":
# Pop operands
rOp = operands.pop()
lOp = operands.pop()
# Pop operator
oper = operators.pop()
# Pop types
rType = types.pop()
lType = types.pop()
# Check semanticCube with types and operator
resType = semanticCube[(lType, rType, oper)]
# Check and validate for array or matrix operands and sizes
if arrMatOperands.size() > 1:
rId = arrMatOperands.pop()
lId = arrMatOperands.pop()
# Validate equal dimensions
if "cols" not in lId:
lId["cols"] = 1
if "cols" not in rId:
rId["cols"] = 1
if lId["rows"] == rId["rows"] and lId["cols"] == rId["cols"]:
if oper == "+":
oper = "ARR+"
else:
oper = "ARR-"
lOp = {
"address": lId["address"],
"rows": lId["rows"],
"cols": lId["cols"]
}
rOp = {
"address": rId["address"],
"rows": rId["rows"],
"cols": rId["cols"]
}
else:
Error.dimensions_do_not_match(t.lexer.lineno)
elif arrMatOperands.size() == 1:
Error.invalid_operation_in_line(t.lexer.lineno)
# Check result type and evaluate expression
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, lOp, rOp, addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
if oper == "ARR+" or oper == "ARR-":
arrMatOperands.push({
"address": addresses[address_type],
"rows": lOp["rows"],
"cols": lOp["cols"],
"type": resType
})
addresses[address_type] += lOp["rows"] * lOp["cols"]
else:
addresses[address_type] += 1
types.push(resType)
else:
Error.operation_type_mismatch(t.lexer.lineno)
def p_expFunction(t):
'''expFunction : PLUS addOperator exp
| MINUS addOperator exp '''
def p_term(t):
'''term : factor evaluateFactor termFunction
| factor evaluateFactor '''
def p_evaluateFactor(t):
'evaluateFactor : '
if operators.size() != 0:
# Generate quadruple for multiplication/division operators
if operators.peek() == "*" or operators.peek() == "/":
# Pop operands
rOp = operands.pop()
lOp = operands.pop()
# Pop operator
oper = operators.pop()
# Pop types
rType = types.pop()
lType = types.pop()
# Check semanticCube with types and operator
resType = semanticCube[(lType, rType, oper)]
# Check and validate for array or matrix operands and sizes
if arrMatOperands.size() > 1:
rId = arrMatOperands.pop()
lId = arrMatOperands.pop()
# Validate equal dimensions
if "cols" not in lId:
lId["cols"] = 1
if "cols" not in rId:
rId["cols"] = 1
if lId["cols"] == rId["rows"]:
if oper == "*":
oper = "ARR*"
else:
Error.invalid_operator_on_arrays(t.lexer.lineno)
lOp = {
"address": lId["address"],
"rows": lId["rows"],
"cols": lId["cols"]
}
rOp = {
"address": rId["address"],
"rows": rId["rows"],
"cols": rId["cols"]
}
else:
Error.invalid_operation_in_line(t.lexer.lineno)
elif arrMatOperands.size() == 1:
Error.invalid_operation_in_line(t.lexer.lineno)
# Check result type and evaluate expression
if resType != "error":
address_type = "t"
if resType == "int":
address_type += "Int"
elif resType == "float":
address_type += "Float"
else:
address_type += "Char"
temp_quad = Quadruple(oper, lOp, rOp, addresses[address_type])
Quadruples.push_quad(temp_quad)
operands.push(addresses[address_type])
if oper == "ARR*":
arrMatOperands.push({
"address": addresses[address_type],
"rows": lOp["rows"],
"cols": rOp["cols"],
"type": resType
})
addresses[address_type] += lOp["rows"] * rOp["cols"]
types.push(resType)
else:
Error.operation_type_mismatch(t.lexer.lineno)
def p_termFunction(t):
'''termFunction : MULTIPLY addOperator term
| DIVIDE addOperator term '''
def p_addOperator(t):
'addOperator : '
# Add any received operator to stack
operators.push(t[-1])
def p_factor(t):
'''factor : LEFTPAR addFF hyperExpression RIGHTPAR removeFF
| cst_prim
| module
| ID dimArray'''
def p_addFF(t):
'addFF : '
# Add "fondo falso" for priority
operators.push("(")
def p_removeFF(t):
'removeFF : '
# Remove "fondo falso"
operators.pop()
def p_read(t):
'read : READ LEFTPAR id_list RIGHTPAR SEMICOLON'
def p_id_list(t):
'id_list : ID dimArray addRead id_listFunction'
def p_addRead(t):
'addRead : '
# Generate read quadruple
if t[-2] in variableTable[currentScope]:
address = variableTable[currentScope][t[-2]]["address"]
temp_quad = Quadruple("read", '_', '_', address)
Quadruples.push_quad(temp_quad)
elif t[-2] in variableTable["global"]:
address = variableTable["global"][t[-2]]["address"]
temp_quad = Quadruple("read", '_', '_', address)
Quadruples.push_quad(temp_quad)
else:
Error.undefined_variable(t[-2], t.lexer.lineno)
def p_id_listFunction(t):
'''id_listFunction : COMA id_list
| '''
def p_print(t):
'print : PRINT LEFTPAR printFunction RIGHTPAR SEMICOLON'
def p_printFunction(t):
'''printFunction : print_param COMA printFunction2
| print_param '''
def p_printFunction2(t):
'printFunction2 : printFunction'
def p_print_param(t):
'''print_param : hyperExpression addPrint
| CST_STRING addPrintString '''
def p_addPrint(t):
'addPrint : '
# Generate print quadruple
if arrMatOperands.size() > 0:
Error.invalid_print_on_array_variable(t.lexer.lineno)
temp_quad = Quadruple("print", '_', '_', operands.pop())
Quadruples.push_quad(temp_quad)
types.pop()
def p_addPrintString(t):
'addPrintString : '
# Add string to print quadruple
address = 0
stringToPrint = t[-1][1:len(t[-1]) - 1]
if stringToPrint not in variableTable["constants"]:
variableTable["constants"][stringToPrint] = {"address": addresses["cChar"]}
address = variableTable["constants"][stringToPrint]["address"]
addresses["cChar"] += 1
else:
address = variableTable["constants"][stringToPrint]["address"]
temp_quad = Quadruple("print", '_', '_', address)
Quadruples.push_quad(temp_quad)
def p_statement(t):
'''statement : return checkVoidType
| if statement
| comment statement
| read statement
| print statement
| assignment statement
| module SEMICOLON statement
| for statement
| while statement
| checkNonVoidType'''
def p_checkVoidType(t):
'checkVoidType : '
global currentScope
if functionDir[currentScope]["type"] == "void":
Error.return_on_void_function(0, t.lexer.lineno)
if types.pop() == functionDir[currentScope]["type"]:
tmp_quad = Quadruple("RETURN", "_", "_", operands.pop())
Quadruples.push_quad(tmp_quad)
global returnMade
returnMade = True
else:
Error.type_mismatch_on_return(t.lexer.lineno)
def p_checkNonVoidType(t):
'checkNonVoidType : '
if functionDir[currentScope]["type"] != "void":
Error.no_return_on_function(0, t.lexer.lineno)
def p_module(t):
'module : ID checkFuncExists genERASize LEFTPAR moduleFunction nullParam RIGHTPAR genGosub'
def p_checkFuncExists(t):
'checkFuncExists : '
if t[-1] not in functionDir:
Error.undefined_module(t[-1], t.lexer.lineno)
global funcName
funcName = t[-1]
operators.push("module")
types.push(functionDir[funcName]["type"])
def p_genERASize(t):
'genERASize : '
global funcName
tmp_quad = Quadruple("ERA", variableTable["global"][funcName]["address"], "_", "_")
Quadruples.push_quad(tmp_quad)
global paramNum
paramNum = 1
def p_nullParam(t):
'nullParam : '
global paramNum
global funcName
if paramNum < len(functionDir[funcName]["params"].values()):
Error.unexpected_number_of_arguments(funcName, t.lexer.lineno)
def p_genGosub(t):
'genGosub : '
global funcName
tmp_quad = Quadruple("GOSUB", variableTable["global"][funcName]["address"], "_", functionDir[funcName]["start"])
Quadruples.push_quad(tmp_quad)
if functionDir[funcName]["type"] != "void":
if functionDir[funcName]["type"] == "int":
tmpAddress = addresses["tInt"]
addresses["tInt"] += 1
if functionDir[funcName]["type"] == "float":
tmpAddress = addresses["tFloat"]
addresses["tFloat"] += 1
if functionDir[funcName]["type"] == "char":
tmpAddress = addresses["tChar"]
addresses["tChar"] += 1
tmp_quad = Quadruple("=", variableTable["global"][funcName]["address"], "_", tmpAddress)
Quadruples.push_quad(tmp_quad)
operands.push(tmpAddress)
types.push(variableTable["global"][funcName]["type"])
operators.pop()
def p_moduleFunction(t):
'''moduleFunction : hyperExpression genParam nextParam COMA moduleFunction
| hyperExpression genParam
| '''
def p_genParam(t):
'genParam : '
global funcName
global paramNum
if arrMatOperands.size() > 0:
Error.array_parameter_in_module_call(t.lexer.lineno)
arg = operands.pop()
argType = types.pop()
paramList = functionDir[funcName]["params"].values()
counter = paramNum
if paramNum > len(paramList):
Error.unexpected_number_of_arguments(funcName, t.lexer.lineno)
if argType == paramList[-paramNum]:
for var in functionDir[funcName]["vars"]: