Repository navigation
Expand file tree
/
Copy pathvm_simulator.py
More file actions
218 lines (199 loc) · 5.56 KB
/
Copy pathvm_simulator.py
File metadata and controls
218 lines (199 loc) · 5.56 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
from opcodes import *
import struct
opcodes = {}
for n, op in enumerate(operations):
opcodes[n] = op
import argparse
commandLineArgs = argparse.ArgumentParser(description='homemade vm simulator for project scripting language')
commandLineArgs.add_argument('filepath', nargs = '?', default = '../tests/test.hex', help='path and name of file' )
commandLineArgs.add_argument('-v', '--verbose', action='store_true', default = False, help='if set will print additional execution logs, and stop at each jump' )
commandLineArgs.add_argument('-b', '--bound', type=int, default = "-1", help='limits the number of operations executed' )
args = commandLineArgs.parse_args()
import sys
def verbosePrint(a, *args):
print(a, args)
sys.stdout.flush()
vprint = verbosePrint if args.verbose else lambda a,*b:None
with open(args.filepath,'rb') as file:
stack = []
scopes = []
currentScope = 0
content = file.read()
index=0
OPsExecuted = -1
if len(content) == 0:
print('file is empty !')
while index<len(content):
OPsExecuted +=1
if args.bound > 0 and OPsExecuted > args.bound:
print(f'... MAXIMUM OPERATION COUNT REACHED ({args.bound}) ...')
sys.exit()
opcode = content[index]
opName = opcodes[opcode].name
bytesConsumed = opcodes[opcode].bytesConsumed
PADDING = ' ' * (5 - len(str(index)))
print(f'{index}{PADDING}', end='\t')
value = ''
index+=1
if opcode == OP_STRING:
c = content[index]
while c!= 0 and c != None:
value+= chr(content[index])
index+=1
c = content[index]
index+=1
elif bytesConsumed !=0 and bytesConsumed!=None :
fmt = None
if bytesConsumed != 0:
if opcode == OP_FLOAT:
fmt = 'f'
elif bytesConsumed == 1:
fmt = 'b'
elif bytesConsumed == 2:
fmt='h'
elif bytesConsumed == 4:
fmt = 'i'
else:
print('unknown number of bytes consumed :', bytesConsumed, ' for op ', opName )
value = struct.unpack(fmt, content[index:index+bytesConsumed])[0]
index += bytesConsumed
shouldWait = False
def apply_jump(offset):
global shouldWait
global index
index += offset
if index > len(content) or index < 0: print('out of bounds jump !')
if args.verbose: shouldWait = True
try:
if opcode == NO_OP:
pass
elif opcode == OP_NONE:
stack.append(None)
elif opcode == OP_TRUE:
stack.append(True)
elif opcode == OP_FALSE:
stack.append(False)
elif opcode == OP_INT1:
stack.append(value)
elif opcode == OP_INT2:
stack.append(value)
elif opcode == OP_INT4:
stack.append(value)
elif opcode == OP_FLOAT:
stack.append(value)
elif opcode == OP_STRING:
stack.append(value)
elif opcode == OP_LOAD:
var = stack[currentScope+value]
stack.append(var)
value = f'var{value} ({var})'
elif opcode == OP_STORE:
var = stack[currentScope+value]
newVar = stack[-1]
stack[value] = newVar
value = f'var{value} = {newVar} (was {var})'
elif opcode == OP_POP:
value = stack[-1]
stack.pop()
elif opcode == OP_JUMP:
apply_jump(value)
value = f'jumped {value}'
elif opcode == OP_JUMP_IF:
cond = stack[-1]
if cond: apply_jump(value)
value = ('' if cond else '!') + 'jump ' + str(value)
elif opcode == OP_JUMP_IF_FALSE:
cond = stack[-1]
if not cond: apply_jump(value)
value = ('!' if cond else '') + 'jump ' + str(value)
elif opcode == OP_JUMP_IF_POP:
cond = stack[-1]
if cond: apply_jump(value)
value = ('' if cond else '!') + 'jump ' + str(value)
stack.pop()
elif opcode == OP_JUMP_IF_FALSE_POP:
cond = stack[-1]
if not cond: apply_jump(value)
value = ('!' if cond else '') + 'jump ' + str(value)
stack.pop()
elif opcode == OP_EQ:
value = stack[-2] == stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_NEQ:
value = stack[-2] != stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_LT:
value = stack[-2] < stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_LTE:
value = stack[-2] <= stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_GT:
value = stack[-2] > stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_GTE:
value = stack[-2] >= stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_ADD:
try:
value = stack[-2] + stack[-1]
except TypeError:
value = str(stack[-2]) + str(stack[-1])
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_SUB:
value = stack[-2] - stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_MUL:
value = stack[-2] * stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_DIV:
value = stack[-2] / stack[-1]
stack.pop()
stack.pop()
stack.append(value)
elif opcode == OP_NEG:
value = stack[-1]
if isinstance(value, bool):
value = not value
else:
value = - value
stack.pop()
stack.append(value)
elif opcode == OP_SCOPE_START:
currentScope = len(stack)
scopes.append( currentScope )
elif opcode == OP_SCOPE_END:
currentScope= scopes[-1]
scopes.pop()
elif opcode == OP_PRINT:
value = f'print {stack[-1]}'
stack.pop()
elif opcode == OP_SHOW_STACK:
value = stack
elif opcode == OP_END:
value = 'END'
else:
print(f'unknown opcode {opcode}:{opName}')
except Exception as e:
print(e)
finally:
print(opName, '=>', value, '--')
if shouldWait: input('press Enter...')