-
Notifications
You must be signed in to change notification settings - Fork 0
/
oaf_vm.py
368 lines (346 loc) · 15.7 KB
/
oaf_vm.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
import cPickle as pickle
import turtle
class VirtualMachine:
def __init__(self, filename, local_address, stack_address, heap_address):
self.color_list = []#the list of colors
self.instr_ptr = 0 # Current quad
self.instr_ptr_stack = [] # Stack used when returning to previous instruction
self.function_call_stack = [] # Stack of function calls
self.return_dir_stack = [] # Address to save value to
self.return_value_stack = [] # Value to save at address
self.local_dir_start = local_address # Address to start the local variables
self.stack_dir_start = stack_address # Address to start the stack
self.stack_dir = stack_address # Next free address to start continue stack
self.heap_dir = heap_address # Last used temporal address
self.context = ["main", [], []] # [function name, [stack begin, stack end], [{temporals list}]]
# Loads the object code and initializes the virtual machine
self.obj = self.load_obj(filename)
self.quads = self.obj["quads"]
self.functions = self.obj["functions"]
self.mem = self.obj["mem"]
# List of memory addresses
self.mem_map = {}
self.graphic_used = False # variable to set main loop if any graphic commands are used
# Operators list
self.op_list = ["u+", "u-", "u!", "=", "+", "-", "*", "/", "<", ">", "<=", ">=", "<>", "==", "||", "&&", "print", "param", "return"]
def square(self, size):
for i in range(4):
turtle.fd(size)
turtle.rt(90)
def triangle(self, size):
for i in range(3):
turtle.fd(size)
turtle.rt(120)
def figure(self, n, size):
angle = 360 / n
for i in range(n):
turtle.fd(size)
turtle.rt(angle)
def load_obj(self, filename):
f = open(filename, "rb")
return pickle.load(f)
# Adds current function variables to stack before calling another one
# and saves the local variables to the stack
# If the functions returns a value that value is also stored in the stack
def save_state(self, temporals):
copy_dir = self.stack_dir
for item in self.mem.items()[:]:
if (self.local_dir_start <= item[0] < self.stack_dir_start):
self.mem[copy_dir] = item[0] # Copies the memory address
self.mem[copy_dir + 4] = item[1] # Copies the value stored in that address
copy_dir += 8
for item in temporals:
if (self.mem[item] != None):
self.mem[copy_dir] = item # Copies the memory address
self.mem[copy_dir + 4] = self.mem[item] # Copies the value stored in that address
copy_dir += 8
if (copy_dir > self.heap_dir): # If addresses collide
raise NameError("Stack buffer overflow")
return copy_dir
def restore_state(self):
self.context = self.function_call_stack.pop()
dirs = self.context[1]
if (dirs[0] >= 0): # There's something to restore
for i in range(dirs[0], dirs[1], 8):
self.mem[self.mem[i]] = self.mem[i + 4]
del (self.mem[i], self.mem[i + 4])
return dirs[0] # Something was restored
else:
return self.stack_dir # Nothing was restored
def init_func(self, func_name):
# Initializes local variables
self.mem_map = {}
# Adds all the used addresses to the dictionary
for var in self.functions[func_name][5].items():
# Check if variable is an array
if ("[]" in var[1][0]):
if (var[1][0][0] == "i" or var[1][0][0] == "f"):
step = 4
else:
step = 1
for x in range(0, var[1][2][0], step):
self.mem_map[var[1][1] + x] = None
else:
self.mem_map[var[1][1]] = None
def copy_mem(self):
# Clears the local memory
for dir in range(self.local_dir_start, self.stack_dir_start):
if (dir in self.mem):
del (self.mem[dir])
# Adds the variables to memory
self.mem.update(self.mem_map)
def run(self):
quad = self.quads[self.instr_ptr]
op = quad.operator
op1 = quad.operand1
op2 = quad.operand2
res = quad.result
while (op != "end" or op1 != "main"):
if(op in self.op_list):
if (self.mem.get(op1) != None and isinstance(self.mem[op1], str) and self.mem[op1][0] == "*"):
op1 = int(self.mem[op1][1:])
if (self.mem.get(op2) != None and isinstance(self.mem[op2], str) and self.mem[op2][0] == "*"):
op2 = int(self.mem[op2][1:])
if (self.mem.get(res) != None and isinstance(self.mem[res], str) and self.mem[res][0] == "*"):
res = int(self.mem[res][1:])
if(op == "u+"):
self.mem[res] = self.mem[op1]
elif(op == "u-"):
self.mem[res] = -self.mem[op1]
elif(op == "u!"):
if (self.mem[op1] == "true"):
self.mem[res] = "false"
else:
self.mem[res] = "true"
elif (op == "+"):
self.mem[res] = self.mem[op1] + self.mem[op2]
elif (op == "-"):
self.mem[res] = self.mem[op1] - self.mem[op2]
elif (op == "*"):
self.mem[res] = self.mem[op1] * self.mem[op2]
elif (op == "/"):
if(self.mem[op2] == 0):
raise NameError("Division by zero")
self.mem[res] = float(self.mem[op1]) / self.mem[op2]
elif (op == "="):
if(len(self.functions[self.context[0]][5]) > 0):
for var, attr in self.functions[self.context[0]][5].items():
if(attr[1] == res):
type = attr[0]
if(type == "float"):
self.mem[res] = float(self.mem[op1])
elif(type == "int"):
self.mem[res] = int(self.mem[op1])
else:
self.mem[res] = self.mem[op1]
else:
self.mem[res] = self.mem[op1]
elif (op == ">"):
if (self.mem[op1] > self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "<"):
if (self.mem[op1] < self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "=="):
if (self.mem[op1] == self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "<>"):
if (self.mem[op1] != self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == ">="):
if (self.mem[op1] >= self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "<="):
if (self.mem[op1] <= self.mem[op2]):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "&&"):
if (self.mem[op1]== "true" and self.mem[op2] == "true"):
self.mem[res] = "true"
else:
self.mem[res] = "false"
elif (op == "||"):
if (self.mem[op1] == "true" or self.mem[op2] == "true"):
self.mem[res] = "true"
else:
self.mem[res] = "false"
# Special functions
if(op == "len"):
if(op2 == 0):
if(self.functions[self.context[0]][5].get(op1) != None):
length = reduce(lambda x, y: x * y, self.functions[self.context[0]][5][op1][2][1:])
else:
length = reduce(lambda x, y: x * y, self.functions["global"][5][op1][2][1:])
else:
if(self.functions[self.context[0]][5].get(op1) != None):
length = self.functions[self.context[0]][5][op1][2][op2]
else:
length = self.functions["global"][5][op1][2][op2]
self.mem[res] = length
# Array operations
if (op == "ver"):
if (self.mem[op1] > res or self.mem[op1] < 0):
raise NameError("Array limits out of bounds")
elif (op == "add"):
self.mem[res] = "*" + str(self.mem[op1] + op2)
elif (op == "mul"):
self.mem[res] = self.mem[op1] * op2
# Function operations
if (op == "era"):
self.context[0] = op1
self.init_func(op1)
# Checks if function returns a value
# if it returns assigns a memory address
if (res):
self.mem[res] = None
self.return_dir_stack.append(res)
self.context[2].append(res)
copy_dir = self.save_state(self.context[2]) # Saves memory state and returns next free address
if (copy_dir == self.stack_dir): # Function didn't save any variables
self.context[1] = [-1, -1]
else: # Function saved variables in the stack
self.context[1] = [self.stack_dir, copy_dir - 4]
self.function_call_stack.append(self.context)
self.stack_dir = copy_dir
if (op == "param"):
func_name = self.function_call_stack[-1][0]
var = self.functions[func_name][2][res]
type = self.functions[func_name][5][var][0]
dir = self.functions[func_name][5][var][1]
size = self.functions[func_name][5][var][2][0]
if (type[0] == "i" or type[0] == "f"):
bytes = 4
else:
bytes = 1
# Copies the variables to local memory
for x in range(0, size, bytes):
#self.mem[dir + x] = self.mem[op1 + x]
self.mem_map[dir + x] = self.mem[op1 + x]
# Removes already initialized variables
#self.mem_map.remove(dir + x)
# Printing functions
if (op == "print"):
# Parameter is a string
if(isinstance(op1, str) and op1[0] == '"'):
print op1[1:-1]
else:
print self.mem[op1]
#read a variable in a memory addres
if (op == "read"):
#if(op1 == "int"):
response = input("inserte el valor :")
if (isinstance(response, int) and op1 != "int" ):
raise NameError("Incompatible types '{0}' and '{1}'".format("int", op1))
if (isinstance(response, float) and op1 != "float"):
raise NameError("Incompatible types '{0}' and '{1}'".format("float", op1))
if (isinstance(response, bool) and op1 != "bool"):
raise NameError("Incompatible types '{0}' and '{1}'".format("bool", op1))
if (isinstance(response, str) and op1 != "char"):
raise NameError("Incompatible types '{0}' and '{1}'".format("char", op1))
self.mem[res] = response
#all the graphic quads traductions
if (op == "circle"):
turtle.circle(self.mem[op1])
self.graphic_used = True
if (op == "fd"):
turtle.forward(self.mem[op1])
self.graphic_used = True
if (op == "rt"):
turtle.rt(self.mem[op1])
self.graphic_used = True
if (op == "square"):
self.square(self.mem[op1])
if (op =="triangle"):
self.triangle(self.mem[op1])
self.graphic_used = True
if (op == "brush"):
turtle.pensize(self.mem[op1])
self.graphic_used = True
if (op == "arc"):
a = self.mem[op1]
b = self.mem[op2]
c = a-b
if(c<0):
c = c*-1
turtle.rt(270)
angle = 180/c
for e in range(c*2):
turtle.fd(1)
turtle.rt(angle/2)
self.graphic_used = True
if (op == "pd"):
turtle.pd()
self.graphic_used = True
if (op == "pu"):
turtle.pu()
self.graphic_used = True
if (op == "color"):
self.color_list.append(self.mem[op2])
if (len(self.color_list) == 3):
turtle.pencolor(self.color_list[0], self.color_list[1], self.color_list[2])
self.graphic_used = True
self.color_list = []
if (op == "home"):
turtle.home()
self.graphic_used = True
if (op == "speed"):
turtle.speed(self.mem[op1])
self.graphic_used = True
if (op == "figure"):
self.graphic_used = True
self.figure(self.mem[op1], self.mem[op2])
if(op == "clear"):
turtle.clear()
# Operators that change the instruction pointer
if (op == "goto"):
self.instr_ptr = res
elif (op == "gotoFalse"):
#print self.mem[op1]
if (self.mem[op1] == "false"):
self.instr_ptr = res
else:
self.instr_ptr += 1
elif (op == "gosub"):
self.context = [op1, [], []]
self.instr_ptr_stack.append(self.instr_ptr + 1)
self.instr_ptr = res
self.copy_mem()
elif (op == "return"):
if(op1 != None):
self.return_value_stack.append(self.mem[op1])
self.instr_ptr = self.functions[self.context[0]][3][1]
elif (op == "end"):
self.stack_dir = self.restore_state() # Reloads previous values and returns next free address
if (self.functions[op1][0][0] != "void"): # Function returns a value
self.mem[
self.return_dir_stack.pop()] = self.return_value_stack.pop() # Saves value returned by function
self.instr_ptr = self.instr_ptr_stack.pop()
else:
self.instr_ptr += 1
# Updates last temporal variable
self.heap_dir = min(filter(lambda x: x > self.stack_dir, self.mem.keys()) + [self.heap_dir])
# Check if heap and stack buffers collided
if (self.heap_dir < self.stack_dir):
raise NameError("Heap buffer overflow")
# Check if memory is full
if (min(self.mem.keys() + [0]) < 0 or self.heap_dir < self.stack_dir):
raise NameError("Not enough memory")
quad = self.quads[self.instr_ptr]
op = quad.operator
op1 = quad.operand1
op2 = quad.operand2
res = quad.result
if (self.graphic_used):
turtle.mainloop()
print "Program finished"