-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservusYacc.py
More file actions
641 lines (548 loc) · 18.6 KB
/
servusYacc.py
File metadata and controls
641 lines (548 loc) · 18.6 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
from servusLex import *
import ply.yacc as yacc
from servusSymbolTable import *
from servusTemp import *
import sys
import os
# ---------------------------- TYPES OF CUDRUPLES ------------------------------
# For arithmetic and logic expressions:
# - Type A : CONST + CONST (len = 5)
# - Type B : CONST + TEMP (len = 5)
# - Type C : TEMP + CONST (len = 5)
# - Type D : TEMP + TEMP (len = 5)
# - Type E : VAR = CONST (len = 4)
# - Type F : VAR = TEMP (len = 4)
# ------------------------------------------------------------------------------
# --------------------------- TYPES OF OPCODES ---------------------------------
# - p ==> PRINT
# - gF ==> GOTO on FALSE
# - gT ==> GOTO on TRUE
# - g ==> GOTO INCONDICIONAL
# - gSub ==> GOTO SUBROUTINE
# - ret ==> RETURN
# - end ==> END OF PROGRAM
# ------------------------------------------------------------------------------
# ------------------------ GLOBAL VARIABLES ------------------------------------
servusSymbolTable = SymbolTable()
newType = ""
newVars = [] # List used for variable declaration
arithmLogicOut = [] # List used when translating aritmetic & logic operations
availOfTemps = [] # This avail will store temporals to execute
# the intermediate code
intermediateCode = []
stJumps = [] # Stack to save jumps
stOperands = [] # Stack to save operands in let statement
stForCounters = [] # Stack to save the for counters
stReturn = [] # Stack of ints used to return to the correct cuadruple
servusSubroutines = {} # Key -> str(name of subroutine) : Value -> int(first cudruple)
# ------------------------------------------------------------------------------
# ------------------------ HELPER FUNCTIONS ------------------------------------
"""
LIST OF INTERMEDIATE CODE INSTRUCTIONS:
operator operand1 operand2 temporalStoreVariable
TODO:
- Translate the if instruction
- when currenInstruction is complete, add to the intermediate code
- create the assign instruction
"""
def initAvail(n=15):
global availOfTemps
for i in range(n):
t = Temp(int, 0)
availOfTemps.append(t)
def isATemporal(v):
return type(v) == Temp
def getOperators(i):
global arithmLogicOut
operator = arithmLogicOut.pop(i)
firstOperand = arithmLogicOut.pop(i-2)
secondOperand = arithmLogicOut.pop(i-2)
return operator, firstOperand, secondOperand
def getOpCode(l):
if len(l) == 4:
op1 = l[1]
op2 = l[2]
# Type A
if not isATemporal(op1) and not isATemporal(op2):
return 'A'
# Type B
elif not isATemporal(op1) and isATemporal(op2):
return 'B'
# Type C
elif isATemporal(op1) and not isATemporal(op2):
return 'C'
# Type D
elif isATemporal(op1) and isATemporal(op2):
return 'D'
elif len(l) == 3:
# Type E
if not isATemporal(l[1]):
return 'E'
# Type F
elif isATemporal(l[1]):
return 'F'
def getOperandValue(operand):
global availOfTemps
if isATemporal(operand):
availOfTemps.append(operand)
return operand.value
else:
return operand
def translateLetStatement(target=None):
global servusSymbolTable
global arithmLogicOut
global availOfTemps
global intermediateCode
global forCounter
artihmOperators = ('+','-','*','/','%','>','==','<','<=','>=','!=','=','&&','||')
i = 0
# print(arithmLogicOut)
while i >=0 and i < len(arithmLogicOut):
if arithmLogicOut[i] in artihmOperators:
currentInstruction = []
if arithmLogicOut[i] == '=':
# ['=', valToBeAssigned, var, opCode]
currentInstruction.append('=')
currentInstruction.append(arithmLogicOut.pop(0)) # Val to be assigned
currentInstruction.append(target)
currentInstruction.append(getOpCode(currentInstruction))
# Force a break from while loop
arithmLogicOut.pop()
else:
operator, firstOperand, secondOperand = getOperators(i)
currentInstruction.append(operator)
currentInstruction.append(firstOperand)
currentInstruction.append(secondOperand)
# TODO validate that both operands are of the same type for arithmetic operations
# t.valueType = currentType
# Take a Temp from avail to store the intermediate result
t = availOfTemps.pop()
currentInstruction.append(t)
# Append the OpCode
currentInstruction.append(getOpCode(currentInstruction))
arithmLogicOut.insert(i-2,t)
i -= 1
# Return operands to avail if they areTemps
if(type(firstOperand) == Temp):
availOfTemps.append(firstOperand)
if(type(secondOperand) == Temp):
availOfTemps.append(secondOperand)
intermediateCode.append(currentInstruction)
else:
i += 1
if len(arithmLogicOut) > 0:
availOfTemps.append(arithmLogicOut.pop())
def printTheP(p):
i = 0
for tP in p:
if tP != None:
print(i, tP)
i += 1
print("\nLength ==> ", len(p))
def printIntermediateCode():
global intermediateCode
print("\n###################################################################")
print("###################### INTERMEDIATE CODE ##########################")
print("###################################################################\n")
i = 0
for line in intermediateCode:
print(i,".\t", line)
i += 1
print("\n###################################################################\n")
def fillCuadruple(index, val):
global intermediateCode
intermediateCode[index].append(val)
def getCont():
global intermediateCode
return len(intermediateCode)
def getResultOfLogicExpression():
global availOfTemps
translateLetStatement()
return availOfTemps.pop()
def returnTempToAvail(t):
global availOfTemps
availOfTemps.append(t)
def addSubroutine(subroutineName, firstCuadruple):
"""
Input parameters:
- str(subroutineName)
- int(firstCuadruple) ==> inside the intermediateCode list
"""
global servusSubroutines
# if the name is not defined on servusSubroutines, add it
if servusSubroutines.get(subroutineName) == None:
servusSubroutines[subroutineName] = firstCuadruple
def printServusSubroutines():
global servusSubroutines
print("\n")
for name, firstCuadruple in servusSubroutines.items():
print("The subroutine {} begins in the {} cuadruple.\n".format(name, firstCuadruple))
def appendReturnIndex(val):
global stReturn
stReturn.append(val)
# ------------------------------------------------------------------------------
# Here begins the PARSER
def p_HEAD(p):
""" HEAD : START checkpointSTART ';' S ENDE ';' """
global intermediateCode
appendReturnIndex(getCont())
endInstruction = ['end']
intermediateCode.append(endInstruction)
def p_checkpointSTART(p):
""" checkpointSTART : empty"""
global intermediateCode
global servusSubroutines
beginInstruction = ['start']
intermediateCode.append(beginInstruction)
goToMain = ['g']
intermediateCode.append(goToMain)
def p_S(p):
"""
S : instruction S
| empty
instruction : print
| clearScreen
| if
| doWhile
| for
| let
| while
| DIM declareVariable
| input
| funcDefine
| goSub
"""
def p_empty(p):
'empty :'
pass
def p_print(p):
"""
print : DRUCK ID ';'
| DRUCK STRING ';'
"""
global intermediateCode
currenInstruction = ['p']
currenInstruction.append(p[2])
intermediateCode.append(currenInstruction)
def p_clearScreen(p):
""" clearScreen : FREI ';' """
global intermediateCode
clearScreenInstruction = ['cls']
intermediateCode.append(clearScreenInstruction)
def p_if(p):
"""
if : WENN logicExpression checkpoint_if_1 '{' S '}' if_2 checkpoint_if_3
if_2 : empty
| SONST checkpoint_if_2 '{' S '}'
"""
def p_checkpoint_if_1(p):
"""
checkpoint_if_1 : empty
"""
global intermediateCode
global stJumps
currentInstruction = ['gF']
resultLogicExpression = getResultOfLogicExpression()
# TODO validate that the result of logic expr. is a boolean
currentInstruction.append(resultLogicExpression)
stJumps.append(len(intermediateCode)) # Push to jump stack to fill later
intermediateCode.append(currentInstruction)
# Return Temp to the avail
returnTempToAvail(resultLogicExpression)
def p_checkpoint_if_2(p):
"""
checkpoint_if_2 : empty
"""
global intermediateCode
global stJumps
currentInstruction = ['g']
intermediateCode.append(currentInstruction)
cont = len(intermediateCode)
fillCuadruple(stJumps.pop(), cont)
stJumps.append(cont-1)
def p_checkpoint_if_3(p):
"""
checkpoint_if_3 : empty
"""
global stJumps
global intermediateCode
fillCuadruple(stJumps.pop(), len(intermediateCode))
def p_doWhile(p):
""" doWhile : TUN checkpoint_doWhile_1 '{' S '}' SOLANGE logicExpression checkpoint_doWhile_2 ';' """
def p_checkpoint_doWhile_1(p):
""" checkpoint_doWhile_1 : empty """
global stJumps
cont = getCont()
stJumps.append(cont)
def p_checkpoint_doWhile_2(p):
""" checkpoint_doWhile_2 : empty """
global intermediateCode
global stJumps
currentInstruction = ['gT']
resultLogicExpression = getResultOfLogicExpression()
# TODO veirfy that resultLogicExpression.valueType == boolean
dir = stJumps.pop()
currentInstruction.append(resultLogicExpression)
currentInstruction.append(dir)
intermediateCode.append(currentInstruction)
# Return Temp to the avail
returnTempToAvail(resultLogicExpression)
def p_while(p):
""" while : WAEREND checkpoint_while_1 logicExpression checkpoint_while_2 '{' S '}' checkpoint_while_3 """
def p_checkpoint_while_1(p):
""" checkpoint_while_1 : empty """
global stJumps
cont = getCont()
stJumps.append(cont)
def p_checkpoint_while_2(p):
""" checkpoint_while_2 : empty """
global intermediateCode
global stJumps
currentInstruction = ['gF']
resultLogicExpression = getResultOfLogicExpression()
# TODO veirfy that resultLogicExpression.valueType == boolean
currentInstruction.append(resultLogicExpression)
cont = getCont()
stJumps.append(cont)
intermediateCode.append(currentInstruction)
# Return Temp to Avail
returnTempToAvail(resultLogicExpression)
def p_checkpoint_while_3(p):
""" checkpoint_while_3 : empty """
global stJumps
global intermediateCode
currentInstruction = ['g']
dir2 = stJumps.pop()
dir1 = stJumps.pop()
currentInstruction.append(dir1)
intermediateCode.append(currentInstruction)
cont = getCont()
fillCuadruple(dir2, cont)
def p_for(p):
"""
for : FUR forAssignation '{' S '}'
"""
global intermediateCode
global stJumps
global stForCounters
cont = getCont()
# 1. Fill the GOTO ON FALSE from the beginning of the for loop
index = stJumps.pop()
fillCuadruple(index, cont + 2)
# 2. Increase ID ++
currentInstruction = ['++', stForCounters.pop()]
intermediateCode.append(currentInstruction)
# 3. Create cuadruple of GOTO to logic expression
currentInstruction2 = ['g', stJumps.pop()]
intermediateCode.append(currentInstruction2)
# printTheP(p)
def p_forAssignation(p):
"""
forAssignation : ID LINKER_PFEIL arithmeticExpression IN forTarget
forTarget : INTEGER_NUMBER
| FLOAT_NUMBER
| ID
"""
global intermediateCode
global stJumps
global availOfTemps
global stForCounters
global arithmLogicOut
# printTheP(p)
if len(p) > 2:
# 1. Generate cuadruples of the arithmetic expression and store result in ID
arithmLogicOut.append('=')
translateLetStatement(p[1])
# 2. Generate cuadruple to check ID <= forTarget
temp = availOfTemps.pop()
cont = getCont()
currentInstruction = ['<']
currentInstruction.append(p[1]) # ID
forTarget = p[5]
# print(forTarget, type(forTarget))
currentInstruction.append(forTarget) # forTarget
currentInstruction.append(temp) # Temp to store the result
currentInstruction.append('A') # Type of operation
# Push the NEW iterator of the current for LOOP to a Stack
stForCounters.append(p[1])
stJumps.append(cont) # Store address to jump & compare again
intermediateCode.append(currentInstruction) # ['<=', ID, forTarget, T1]
# 3. Generate cuadruple GOTO ON FALSE
cont = getCont()
currentInstruction2 = []
currentInstruction2.append('gF')
currentInstruction2.append(temp)
intermediateCode.append(currentInstruction2) # ['gF', T1, __]
stJumps.append(cont) # Store index to fill in later
returnTempToAvail(temp)
else:
p[0] = p[1]
def p_let(p):
"""
let : LASS ID LINKER_PFEIL letAssignation ';'
letAssignation : arithmeticExpression
| logicExpression
| booleanAssignation
"""
global arithmLogicOut
global servusSymbolTable
global stOperands
if p[1] == "lass":
# Ask for the complete Symbol Object
actualSymbol = servusSymbolTable.getSymbolFromTable(p[2])
stOperands.append(p[2])
if actualSymbol == None:
print("Variable ", p[2], " was not declared in this scope.")
# TODO call an error function
else:
arithmLogicOut.append('=')
translateLetStatement(p[2])
def p_declareVariable(p):
"""
declareVariable : ID declareVariable1 ALS type ';'
declareVariable1 : ',' ID declareVariable1
| empty
type : WORT
| FLOAT
"""
global newType
global newVars
for l in p:
if l != None and l != ',':
if l == ';':
if len(newVars) > 0 and newType != "":
servusSymbolTable.addElements(newVars, newType)
newVars.clear()
newType = ""
elif l == "float" or l == "wort":
newType = l
elif l not in reserved:
newVars.append(l)
def p_input(p):
"""
input : EINGABE ID ';'
"""
global intermediateCode
currentInstruction = ["inp", p[2]]
intermediateCode.append(currentInstruction)
precedence = (
# LOWEST PRIORITY
('left', '+', '-'),
('left', 'GtE', 'StE', 'EQUAL'),
('left', 'UND', 'ODER', 'NOT'),
('left', '*', '/', '%'),
# ('right', 'UMINUS'),
# HIGHEST PRIORITY
)
def p_logicExpression(p):
"""
logicExpression : logicExpression ODER logicExpressionAND
| logicExpressionAND
logicExpressionAND : logicExpressionAND UND logicExpressionNOT
| logicExpressionNOT
logicExpressionNOT : logicExpressionNOT NOT logicExpressionGtE
| logicExpressionGtE
logicExpressionGtE : logicExpressionGtE GtE logicExpressionStE
| logicExpressionStE
logicExpressionStE : logicExpressionStE StE logicExpressionSmaller
| logicExpressionSmaller
logicExpressionSmaller : logicExpressionSmaller '<' logicExpressionGreater
| logicExpressionGreater
logicExpressionGreater : logicExpressionGreater '>' logicExpressionEq
| logicExpressionEq
logicExpressionEq : logicExpressionEq EQUAL operand
| '(' logicExpression ')'
| operand
operand : ID
| INTEGER_NUMBER
| FLOAT_NUMBER
| STRING
"""
global arithmLogicOut
global servusSymbolTable
invalidElements = (None, '(', ')')
for element in p:
if element not in invalidElements:
arithmLogicOut.append(element)
def p_arithmeticExpression(p):
"""
arithmeticExpression : arithmeticExpression '+' subs
| subs
subs : subs '-' mul
| mul
mul : mul '*' mod
| mod
mod : mod '%' divi
| divi
divi : divi '/' arithOperand
| '(' arithmeticExpression ')'
| arithOperand
arithOperand : ID
| INTEGER_NUMBER
| FLOAT_NUMBER
"""
global arithmLogicOut
global servusSymbolTable
invalidElements = (None, '(', ')')
for element in p:
if element not in invalidElements:
arithmLogicOut.append(element)
def p_booleanAssignation(p):
"""
booleanAssignation : logicExpression checkpoint_if_1 '?' arithmeticExpression checkpoint_boolean_1 ':' arithmeticExpression checkpoint_boolean_2
"""
global stOperands
# Final Step - Clear the stack of operands
while len(stOperands) > 0:
stOperands.pop()
def p_checkpoint_boolean_1(p):
"""
checkpoint_boolean_1 : empty
"""
global intermediateCode
global stOperands
global availOfTemps
newValue = availOfTemps[-1].value
id = stOperands[-1]
currenInstruction = ['=', newValue, id]
def p_checkpoint_boolean_2(p):
"""
checkpoint_boolean_2 : empty
"""
def p_goSub(p):
"""
goSub : GOSUB ID ';'
"""
global intermediateCode
global servusSubroutines
# - Create cuadruple for going to the beginning line of the subroutine 'ID'
indexToJump = servusSubroutines.get(p[2])
returnIndex = getCont() + 1
currentInstruction = ["gSub", indexToJump, returnIndex]
intermediateCode.append(currentInstruction)
def p_funcDefine(p):
"""
funcDefine : DEF checkpoint_funcDefine_1 '{' S RETURN ';' '}'
"""
global intermediateCode
# When the parsing is complete, store the return statement
currentInstruction = ["return"]
intermediateCode.append(currentInstruction)
def p_checkpoint_funcDefine_1(p):
"""
checkpoint_funcDefine_1 : ID
"""
subroutineName = p[1]
firstCuadruple = getCont()
# 1) Add subroutine to the Table (Name = ID, Val = len(intermediateCode))
addSubroutine(subroutineName, firstCuadruple)
if subroutineName == 'main':
fillCuadruple(1, firstCuadruple)
# Error rule for syntax errors
def p_error(p):
print("Syntax error in input! ", p)
sys.exit("Syntax error in input! ", p)
#Initialize the Avail of Temporals
initAvail()
# Build the parser
parser = yacc.yacc()