-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimise.py
executable file
·110 lines (100 loc) · 3.23 KB
/
optimise.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
import pickle
import sys
'''
with open('symbol_table.pickle', 'rb') as handle:
symbol = pickle.load(handle)
def print_symbol_table():
print("*" * 50)
for i in symbol:
print("Variable name = ", i['name'])
print("Type = ", i['type'])
print("Value = ", i['value'])
print("width = ", i['width'])
print("scope = ", i['scope'])
print("*" * 25)
print("*" * 50)
print("Symbol Table!!")
print_symbol_table()
'''
with open(sys.argv[1], 'r') as f:
lines = f.readlines()
for i in range(len(lines)):
lines[i] = lines[i].strip()
lines2 = []
for i in lines:
if(i):
lines2.append(i)
def solve(operands , operation):
if(operation == '+'):
return operands[0] + operands[1]
elif(operation == '-'):
return operands[0] - operands[1]
elif(operation == '/'):
return operands[0] / operands[1]
elif(operation == '*'):
return operands[0] * operands[1]
elif(operation == '%'):
return operands[0] % operands[1]
elif(operation == '&&'):
return operands[0] and operands[1]
elif(operation == '||'):
return operands[0] or operands[1]
elif(operation == '^'):
return operands[0] ^ operands[1]
elif(operation == '=='):
return operands[0] == operands[1]
elif(operation == '!='):
return operands[0] != operands[1]
elif(operation == '<'):
return operands[0] < operands[1]
elif(operation == '>'):
return operands[0] > operands[1]
elif(operation == '<='):
return operands[0] <= operands[1]
elif(operation == '>='):
return operands[0] >= operands[1]
op = ['+', '-', '/', '*', '%', '&&', '||', '^', '==', '!=', '<', '>', '>=', '<=']
def constant_fold():
for i in range(len(lines2)):
x = lines2[i].split('=')
if(len(x) == 2):
expr = x[-1]
numbers = 0
operation = ''
for j in expr:
if(j in op):
operation += j
break
if(operation):
operand_list = expr.split(operation)
operands = []
try:
int(operand_list[0])
if(int(operand_list[0]) == float(operand_list[0])):
operands.append(int(operand_list[0]))
else:
operands.append(float(operand_list[0]))
except:
#print("operand 1 is not constant!!")
pass
try:
int(operand_list[1])
if(int(operand_list[1]) == float(operand_list[1])):
operands.append(int(operand_list[1]))
else:
operands.append(float(operand_list[1]))
except:
#print("operand 2 is not constant!!")
pass
if(len(operands) == 2):
res = solve(operands, operation)
print(x[0], "=", res)
else:
print(lines2[i])
else:
print(lines2[i])
else:
print(lines2[i])
print("\n\nAFTER CONSTANT FOLDING\n\n")
constant_fold()
print("\n")