-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhackvm.py
executable file
·183 lines (152 loc) · 4.74 KB
/
hackvm.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
#!/usr/bin/env python
### Imports
from functools import partial
import sys, re
ProgramCounter = None
def run(MAX_CYCLES = 10000):
global ProgramCounter
### Constants
MIN_INT=-(1<<63)
MAX_INT=(1<<63)-1
### Globals
Memory = [0]*16384
CallStack = []
OperandStack = []
ProgramCounter = 0
CycleCounter = 0
### Functions
def Push(v):
if (v < MIN_INT or v > MAX_INT): raise Exception('integer overflow')
OperandStack.append(v)
def Pop():
if len(OperandStack) == 0: raise Exception('stack underflow')
return OperandStack.pop()
def DoPrintChar():
sys.stdout.write(chr(Pop()&0x7F))
def DoPrintInt():
sys.stdout.write(str(Pop()))
def DoAdd():
Push(Pop()+Pop())
def DoSub():
a = Pop()
b = Pop()
Push(b-a)
def DoMul():
Push(Pop()*Pop())
def DoDiv():
a = Pop()
b = Pop()
Push(b/a)
def DoCmp():
a = Pop()
b = Pop()
Push(cmp(b,a))
def DoGoto():
global ProgramCounter
ProgramCounter += Pop()
def DoGotoIfZero():
global ProgramCounter
offset = Pop()
if Pop() == 0: ProgramCounter += offset
def DoCall():
global ProgramCounter
CallStack.append(ProgramCounter)
ProgramCounter = Pop()
def DoReturn():
global ProgramCounter
ProgramCounter = CallStack.pop()
def DoPeek():
addr = Pop()
if addr < 0 or addr >= len(Memory): raise Exception('memory read access violation @'+str(addr))
Push(Memory[addr])
def DoPoke():
addr = Pop()
if addr < 0 or addr >= len(Memory): raise Exception('memory write access violation @'+str(addr))
Memory[addr] = Pop()
def DoPick():
where = Pop()
if where < 0 or where >= len(OperandStack): raise Exception('out of stack bounds @'+str(where))
Push(OperandStack[-1-where])
def DoRoll():
where = Pop()
if where < 0 or where >= len(OperandStack): raise Exception('out of stack @'+str(where))
v = OperandStack[-1-where]
del OperandStack[-1-where]
Push(v)
def DoDrop():
Pop()
def DoEnd():
global ProgramCounter
ProgramCounter = len(Code)
def DoNothing():
pass
OPS = {
' ': DoNothing,
'\n':DoNothing,
'p': DoPrintInt,
'P': DoPrintChar,
'0': partial(Push, 0),
'1': partial(Push, 1),
'2': partial(Push, 2),
'3': partial(Push, 3),
'4': partial(Push, 4),
'5': partial(Push, 5),
'6': partial(Push, 6),
'7': partial(Push, 7),
'8': partial(Push, 8),
'9': partial(Push, 9),
'+': DoAdd,
'-': DoSub,
'*': DoMul,
'/': DoDiv,
':': DoCmp,
'g': DoGoto,
'?': DoGotoIfZero,
'c': DoCall,
'$': DoReturn,
'<': DoPeek,
'>': DoPoke,
'^': DoPick,
'v': DoRoll,
'd': DoDrop,
'!': DoEnd
}
### Parse the command line
if len(sys.argv) < 2:
print 'hackvm.py [--init <init-mem-filename>] [--trace] <code-filename>\nThe format for the initial memory file is: cell0,cell1,...'
sys.exit(0)
Trace = False
args = sys.argv
args.reverse()
args.pop()
while len(args):
arg = args.pop()
if len(args) == 0:
Code = open(arg).read()
elif arg == '--trace':
Trace = True
elif arg == '--init':
initial_memory = re.compile('\s*,\s*').split(open(args.pop()).read())
#print initial_memory
for i in range(0,len(initial_memory)):
Memory[i] = int(initial_memory[i].strip())
else:
raise Exception('invalid argument '+arg)
### main loop
try:
while ProgramCounter != len(Code):
op_code = Code[ProgramCounter]
if Trace: sys.stderr.write('@'+str(ProgramCounter)+' '+op_code+' ')
ProgramCounter += 1
CycleCounter += 1
if CycleCounter > MAX_CYCLES: raise Exception('too many cycles')
OPS[op_code]()
if ProgramCounter < 0 or ProgramCounter > len(Code): raise Exception('out of code bounds')
if Trace: sys.stderr.write(str(OperandStack)+'\n')
except:
sys.stderr.write('!ERROR: exception while executing I='+str(op_code)+' PC='+str(ProgramCounter-1)+' STACK_SIZE='+str(len(OperandStack))+'\n')
sys.stderr.write(str(sys.exc_info()[1])+'\n')
sys.exit(1)
print
if __name__ == '__main__':
run()