-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanguage_c.py
307 lines (246 loc) · 9.44 KB
/
language_c.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
#
# Nick Quinn - Compiler Construction
#
# This file describes and implements the C language.
#
# Language C0:
#
# p := (program info [label -> tail] ... )
# tail := (return arg) | (seq stmt tail)
# stmt := set var expr
# expr := arg | (read) | (-arg) | (+ arg arg)
# arg := number | var
#
from language_x import *
from support import *
#########################################################################################
########################## C0 Language #################################
#########################################################################################
########################## C Program ####################################################
class cprog():
# Dictionary to hold all vars -> (x...)
info_dict = {}
# Mapping for select pass
label_map = {}
# Program = (Program Info [label->tail])
def __init__(self, info, label):
self._info = info
self._label = label
def interp(self):
# Empty enviroment
cenv = env()
try:
instr = self._label["main"]
except KeyError:
instr = self._label["middle"]
return print("return ", ctail.interp(cenv, instr), "\n")
# Requires that ECON and RCO have passed
def uncover(self):
# Reinitialize info dictionary
cprog.info_dict.clear()
# Initialize empty enviroment
cenv = env()
# middle is label created by ECON
instr = self._label["middle"]
ctail.uncover(cenv, instr)
if ( self._info is None ):
self._info = {}
self._info["uncover"] = cprog.info_dict
return cprog(self._info, self._label);
# Takes a C program and returns a X0 program
def select(self):
# Reinitialize mapping
cprog.label_map.clear()
# List of C instructions
c_instr = self._label["middle"]
# Empty List to hold new X instructions
x_instr = []
# New enviroment
cenv = env()
# Go through C program and create X program
x_instr = ctail.select(cenv, c_instr, x_instr)
# Select will return the x_instr list
cprog.label_map["main"] = x_instr
# After rco, every program will have at least one variable so we will need this
# label for now
end_instr = [retq()]
cprog.label_map["end"] = end_instr
return xprog(self._info, cprog.label_map);
########################## C Tail ########################################################
class ctail():
# tail = (return arg) | (sequence statement tail) | go-to |
# go-to if cmp(arg arg) label1 label2
def __init__(self, info):
self._info = info
def interp(cenv, instr):
for i in instr:
if isinstance(i, cstmt):
# sequence stmt tail
i.interp(cenv)
else:
# Return Arg
arg = i.interp(cenv)
return arg;
return "Error: No return statement in interp.";
def uncover(cenv, instr):
for i in instr:
if isinstance(i, cstmt):
# sequence stmt tail
i.uncover(cenv)
else:
return;
return "Error: No return statement in uncover.";
def select(cenv, c_instr, x_instr):
for i in c_instr:
if isinstance(i, cstmt):
# sequence stmt tail
x_instr = i.select(cenv, c_instr, x_instr)
else:
# Last instruction, should be a return so we will jump to a new label
# since we do not know how many local variales are in the stack
dst = None
arg = i.select(cenv, c_instr, x_instr, dst)
x_instr.append(movq(arg, xreg("rax")))
x_instr.append(jmp("end"))
#i.select(cenv, c_instr, x_instr, dst)
return x_instr;
return "Error: No return statement in select.";
########################## C Statement ##################################################
class cstmt():
# Statement = set: var expresion
def __init__(self, var, expr):
self._var = var
self._expr = expr
def interp(self, cenv):
# env [x -> (interp expression)]
expr = self._expr.interp(cenv)
cenv.add_var(self._var, expr)
return;
def uncover(self, cenv):
cprog.info_dict[self._var] = self._expr
# Call to uncover from here is strictly for pretty print feature
#if(self._var.startswith("_")):
# print(self._var, " = ", self._expr.uncover(cenv))
#else:
# print(" " + self._var, " = ", self._expr.uncover(cenv))
return;
def select(self, cenv, c_instr, x_instr):
dst = xvar(self._var)
x_instr = self._expr.select(cenv, c_instr, x_instr, dst)
return x_instr;
########################## C Expression #################################################
class cexpr():
# Expression = arg | (read) | (-arg) | (+ arg arg) | !(arg) | ccmp(arg, arg)
def __init__(self, arg):
self._arg = arg
def interp(self, cenv):
return self._arg.interp(cenv);
def uncover(self, cenv):
#print("Error: cexpr was hit in uncover-locals function.")
return self._arg.uncover(cenv);
def select(self, cenv, c_instr, x_instr, dst):
x_instr = self._arg.select(cenv, c_instr, x_instr, dst)
return x_instr;
########################## C Read #######################################################
class cread():
def __init__(self):
pass
def interp(self, cenv):
num = input("Please enter a numerical value: ")
self._num = int(num)
print(" read ", self._num, " ")
return self._num;
def uncover(self, cenv):
#print("Error: cread was hit in uncover-locals function.")
return "Read()";
def select(self, cenv, c_instr, x_instr, dst):
x_instr.append(callq("_read_int"))
x_instr.append(movq("rax", dst))
return x_instr;
########################## C Negate #####################################################
class cneg():
def __init__(self, arg):
self._arg = arg
def interp(self, cenv):
result = self._arg.interp(cenv)
result *= -1
print("Neg(", result, ")")
return result
def uncover(self, cenv):
#print("Error: cneg was hit in uncover-locals function.")
return "cneg(" + str(self._arg) + ")";
def select(self, cenv, c_instr, x_instr, dst):
# Retrieve actual argument value from carg object
if(isinstance(self._arg, carg)):
self._arg = self._arg._arg
if(isinstance(self._arg, int)):
x_instr.append(movq(xnum(self._arg), dst))
else:
x_instr.append(movq(xvar(self._arg), dst))
x_instr.append(negq(dst))
return x_instr;
########################## C Add ########################################################
class cadd():
def __init__(self, arg1, arg2):
self._arg1 = arg1
self._arg2 = arg2
def interp(self, cenv):
arg1 = self._arg1.interp(cenv)
arg2 = self._arg2.interp(cenv)
result = arg1 + arg2
print("add(", arg1, ",", arg2, ")")
return result;
def uncover(self, cenv):
#print("Error: cadd was hit in uncover-locals function.")
if(isinstance(self._arg1, carg) and isinstance(self._arg2, carg)):
return "add(" + str(self._arg1.uncover(cenv)) + "," + str(self._arg2.uncover(cenv)) + ")";
def select(self, cenv, c_instr, x_instr, dst):
# Retrieve actual argument value from carg object
if(isinstance(self._arg1, carg)):
self._arg1 = self._arg1._arg
if(isinstance(self._arg2, carg)):
self._arg2 = self._arg2._arg
if(isinstance(self._arg2, int)):
x_instr.append(movq(xnum(self._arg2), dst))
else:
x_instr.append(movq(xvar(self._arg2), dst))
if(isinstance(self._arg1,int)):
x_instr.append(addq(xnum(self._arg1), dst))
else:
x_instr.append(addq(xvar(self._arg1), dst))
return x_instr;
########################## C Compare ###################################################
class ccmp():
# ccmp = == | < | <= | > | >=
def __init__(self, arg):
self._arg = arg
########################## C Argument ###################################################
class carg():
# arg = number | var | true | false
def __init__(self, arg):
self._arg = arg
def interp(self, cenv):
# If arg is just a number
if isinstance(self._arg, int):
return self._arg;
# If arg is a var
arg = cenv.find_var(self._arg)
return arg;
# I do not believe carg needs to be implemented for uncover-locals to work. I may need to
# change this in the future.
def uncover(self, cenv):
#print("Error: carg was hit in uncover-locals function.")
return "carg(" + str(self._arg) + ")";
def select(self, cenv, c_instr, x_instr, dst):
if(dst is None):
if(isinstance(self._arg, int)):
return xnum(self._arg);
else:
return xvar(self._arg);
else:
if(isinstance(self._arg, int)):
x_instr.append(movq(xnum(self._arg), dst))
return x_instr;
else:
x_instr.append(movq(xvar(self._arg), dst))
return x_instr;