Repository navigation
Expand file tree
/
Copy pathvirtual_machine.py
More file actions
318 lines (276 loc) · 11.3 KB
/
Copy pathvirtual_machine.py
File metadata and controls
318 lines (276 loc) · 11.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
from PopurriListener import ContextWrapper, QuadWrapper, Variable, Function, pprint
from memory import MemoryHandler, Memory
from popurri_tokens import *
from error_tokens import *
from operator import *
import json
from copy import deepcopy
def importMemory(f):
memHandler = MemoryHandler()
mem_dict = json.loads(f.readline())
for ctx, mem in mem_dict.items():
memObj = Memory(mem['start'], mem['max_size'])
for section, spaces in mem['sections'].items():
memObj.sections[int(section)] = spaces
memHandler.contexts[int(ctx)] = memObj
return memHandler
def importContext(f):
# Import Variables
vars = json.loads(f.readline())
for ctx in vars.values(): # Iterate over contexts
for k, v in ctx.items():
if 'func ' in k or 'self' in v: # Inside method/object varTable
for vid, vdict in v.items():
if 'self' in vdict: # Var is object, iterate over attributes
for attrid, attrdict in vdict.items():
vdict[attrid] = Variable(**attrdict)
else:
v[vid] = Variable(**vdict)
else:
ctx[k] = Variable(**v)
# Import Functions
funcs = json.loads(f.readline())
for ctx in funcs.values():
for fid, fdict in ctx.items():
ctx[fid] = Function(**fdict)
return ContextWrapper(variables=vars, functions=funcs)
opMap = {
ADD: add,
MINUS: sub,
MULT: mul,
DIV: truediv,
MOD: mod,
POWER: pow,
EQUAL: eq,
NOTEQUAL: ne,
GREATER: gt,
GREATEREQ: ge,
LESSER: lt,
LESSEREQ: le,
UNARYADD: pos,
UNARYMINUS: neg,
}
def handleBinaryOperation(memHandler, op, l_val, r_val, res):
opFunc = opMap[op]
memHandler.update(res, opFunc(l_val, r_val))
def handleUnaryOperation(memHandler, op, r_val, res):
opFunc = opMap[op]
memHandler.update(res, opFunc(r_val))
def run(obj_file):
with open(obj_file, 'r') as f:
ctx = importContext(f)
memHandler = importMemory(f)
quads = json.loads(f.readline())
# Reutilizing the ctx_stack in this wrapper to handle memory stacks
memCtxWrapper = ContextWrapper()
memCtxWrapper.pop() # Remove global context
# Flag
method_call = False
# Instruction Pointer
ip = 0
ip_stack = []
while ip < len(quads):
quad = quads[ip]
# print(ip + 1, '(', end='')
# print(stringifyToken(quad[0]), *quad[1:], sep=', ', end='')
# print(')')
op, l, r, res = quad
if type(l) == int:
l_val = memHandler.getValue(l)
if type(r) == int:
r_val = memHandler.getValue(r)
# GOTOs
if op == GOTO:
ip = res - 1
continue
elif (op == GOTOF and l_val == False or
op == GOTOV and l_val == True):
ip = res - 1
continue
# Operations
elif op == ASSIGN:
if type(l) == str: # l is a return value from a function
func_name = 'func ' + l.split('.')[-1]
return_var = ctx.getVariable(func_name)
l_val = memHandler.getValue(return_var.address)
# Remove return value from memory & global varTable
del ctx.variables['global'][func_name]
memHandler.contexts[GLOBAL].sections[tokenize(
return_var.type)].pop()
if l_val >= 28000 and l_val <= 30000:
val_type = memHandler.getAddressType(l_val)
if val_type == POINTER:
l_val = memHandler.getValue(l_val)
if res >= 28000 and res <= 30000:
res_type = memHandler.getAddressType(res)
if res_type == POINTER:
res = memHandler.getValue(res)
memHandler.update(res, l_val)
elif op in [ADD, MINUS, MULT, DIV, MOD, POWER, EQUAL, NOTEQUAL, GREATER, GREATEREQ, LESSER, LESSEREQ]:
handleBinaryOperation(memHandler, op, l_val, r_val, res)
elif op in [UNARYADD, UNARYMINUS]:
handleUnaryOperation(memHandler, op, r_val, res)
elif op == ANDOP: # For some reason these arent implemented in operator pkg, so do them manually
memHandler.update(res, l_val and r_val)
elif op == OROP:
memHandler.update(res, l_val or r_val)
elif op in [ADDASSIGN, MINUSASSIGN, MULTASSIGN, DIVASSIGN, MODASSIGN]:
res_val = memHandler.getValue(res)
# Move token one pos up, so ADDASSIGN -> ADD, MINUSASSIGN -> MINUS, etc.
op -= 1
# Applies short-hand operator and stores it in res
handleBinaryOperation(memHandler, op, res_val, l_val, res)
# Special Functions
elif op == INPUT:
res_type = memHandler.getAddressType(res)
tmp = input()
try:
if res_type == INT:
tmp = int(tmp)
elif res_type == FLOAT:
tmp = float(tmp)
elif res_type == BOOL:
tmp = tmp == 'true'
# Input is casted to string by default, so no need to cast
except Exception:
raise Exception(CANNOT_CAST.format(
tmp, stringifyToken(res_type)))
memHandler.update(res, tmp)
elif op == PRINT or op == PRINTLN:
if res >= 28000 and res <= 30000: # POINTER
res = memHandler.getValue(res)
print(memHandler.getValue(res), end=' ' if PRINT else '\n')
# Classes
elif op == ERAC:
# Push function's memory ctx to stack
memCtxWrapper.push(memHandler)
func_mem = memCtxWrapper.top()
# Flush allocated values from memory, but keep count of how many have been allocated
for context in [LOCAL, TEMPORAL]:
func_mem.flush(context)
func_mem.contexts[context].allocations = memHandler.contexts[context].allocations
if l == 'self': # Recursive class call
class_var = ctx.getAttributes(ctx.getClassContext())
ctx.push(ctx.getClassContext())
else:
class_var = ctx.getVariable(
l,
context=ctx.top(),
insideClass=ctx.top() != 'global'
)
ctx.push('class ' + class_var['self'].type)
for attr in class_var.values():
if attr.id == 'self': # this attribute only contains the class name
continue
attr_val = memHandler.getValue(attr.address)
func_mem.reserve(
context=LOCAL,
dtype=tokenize(attr.type),
value=attr_val
)
if attr.isArray(): # Allocate array slots
for i in range(attr.arraySize):
slot_val = memHandler.getValue(attr.address + i)
func_mem.reserve(
context=LOCAL,
dtype=tokenize(attr.type),
value=slot_val
)
method_call = True # Set flag so ERA quad doesnt flush mem
# Function Calls
elif op == ERA:
# Push memory ctx to stack (if calling a regular function)
if not method_call:
memCtxWrapper.push(memHandler)
func_mem = memCtxWrapper.top()
# Flush allocated values from memory, but keep count of how many have been allocated
for context in [LOCAL, TEMPORAL]:
func_mem.flush(context)
func_mem.contexts[context].allocations = memHandler.contexts[context].allocations
else:
func_mem = memCtxWrapper.top()
ctx.push('func ' + l)
func = ctx.getCurrentFunction()
# Allocate required function memory
ctxs = [LOCAL, TEMPORAL]
dtypes = [INT, FLOAT, BOOL, STRING, POINTER]
for i, era in enumerate([func.era_local, func.era_tmp]):
for j, type_allocations in enumerate(era):
for _ in range(type_allocations):
func_mem.reserve(
context=ctxs[i],
dtype=dtypes[j],
)
method_call = False # Reset flag
elif op == PARAM:
if ctx.insideClass():
params = ctx.variables[ctx.getClassContext()][ctx.top()]
else:
params = ctx.variables[ctx.top()]
# Update the local param address with the passed value
paramNo = int(res.split(' ')[1]) # res is formatted as 'param N'
for param in params.values():
if param.paramNo == paramNo:
func_mem = memCtxWrapper.top()
func_mem.update(
address=param.address,
value=l_val,
)
break
elif op == GOSUB:
func_id = l.split('.')[-1]
func_ctx = ctx.getClassContext() if ctx.insideClass() else 'global'
func = ctx.getFunction(func_id, func_ctx)
if func.quads_range != (-1, -1):
# Gonna return to this ip when returning from func
ip_stack.append(ip + 1)
# Go to function start
ip = func.quads_range[0] - 1
# Sleep current context
tmp = memHandler
memHandler = memCtxWrapper.pop()
memCtxWrapper.push(tmp)
continue
elif op == GOTOR:
prev_ctx = memCtxWrapper.pop()
# Copy Global memory in case function did any changes
prev_ctx.contexts[GLOBAL] = deepcopy(memHandler.contexts[GLOBAL])
# Allocate return value as global with func name
return_dtype = memHandler.getAddressType(res)
return_var = Variable(
id=ctx.top(),
type=stringifyToken(return_dtype)
)
return_var.address = prev_ctx.reserve(
context=GLOBAL,
dtype=return_dtype,
value=memHandler.getValue(res)
)
# And add it to global varTable
ctx.addVariable(return_var)
# Return to previous context
ip = ip_stack.pop()
memHandler = prev_ctx
# Pop function/method context
ctx.pop()
if 'class ' in ctx.top():
ctx.pop()
continue
elif op == ENDPROC:
# Return to previous context
ip = ip_stack.pop()
prev_ctx = memCtxWrapper.pop()
# Copy Global memory in case function did any changes
prev_ctx.contexts[GLOBAL] = deepcopy(memHandler.contexts[GLOBAL])
# Pop function/method context
ctx.pop()
if 'class ' in ctx.top():
ctx.pop()
continue
elif op == VERIFY:
index = l_val
lInf = r_val
lSup = memHandler.getValue(res)
if index < lInf or index > lSup:
raise Exception(OUT_OF_RANGE.format(index))
ip += 1