-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputer.py
More file actions
245 lines (184 loc) · 6.91 KB
/
Computer.py
File metadata and controls
245 lines (184 loc) · 6.91 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
from collections import defaultdict
from six import string_types
from TypeChecking import accepts
# 32bit max/min numbers
MAX_INT = 2147483647
MIN_INT = -2147483648
class Computer(object):
"""An emulated computer with a simple instruction set"""
def __init__(self):
super(Computer, self).__init__()
self.reset_computer()
def load_program(self, program, inputs=[]):
self.reset_computer()
self.program = program
self.load_inputs(inputs)
def load_inputs(self, inputs):
for index, value in enumerate(inputs):
self.memory[str(index)].value = value
def reset_computer(self):
self.program = []
self.pc = 0
self.stack = []
self.status = {}
self.memory = defaultdict(lambda: MemoryLocation())
self.output_queue = []
self.kill_signal = False
def run_program(self):
try:
while self.pc < len(self.program) and not self.kill_signal:
instruction, operands = self.program[self.pc]
function = getattr(self, instruction)
# print("{}: {}".format(instruction, operands))
function(*operands)
self.pc += 1
except JumpedOutException, e:
pass
def kill_program(self):
self.kill_signal = True
def dereference(self, variable):
if isinstance(variable, string_types):
return self.memory[variable].value
else:
return variable
def set_status(self, **kwargs):
pass
def output(self, value):
self.output_queue.append(value)
@accepts("register")
def inc(self, location):
self.memory[location].value = self.dereference(location) + 1
@accepts("register")
def dec(self, location):
self.memory[location].value = self.dereference(location) - 1
@accepts("register")
def clear(self, location):
self.memory[location].value = 0
@accepts("any", "any", "register")
def add(self, first, second, dest):
first_ = self.dereference(first)
second_ = self.dereference(second)
self.memory[dest].value = first_ + second_
@accepts("any", "any", "register")
def multiply(self, first, second, dest):
first_ = self.dereference(first)
second_ = self.dereference(second)
self.memory[dest].value = first_ * second_
@accepts("any", "any", "register")
def divide(self, first, second, dest):
first_ = self.dereference(first)
second_ = self.dereference(second)
if second_ == 0:
second_ = 1
self.memory[dest].value = first_ / second_
@accepts("register")
def shift_left(self, location):
self.memory[location].value <<= 1
@accepts("register")
def shift_right(self, location):
self.memory[location].value >>= 1
@accepts("register", "any")
def bit_or(self, location, mask):
mask_ = self.dereference(mask)
self.memory[location].value |= mask_
@accepts("register", "any")
def bit_and(self, location, mask):
mask_ = self.dereference(mask)
self.memory[location].value &= mask_
@accepts("register")
def complement(self, location):
self.memory[location].value = ~self.memory[location].value
@accepts("register", "any")
def bit_xor(self, location, mask):
mask_ = self.dereference(mask)
self.memory[location].value ^= mask_
def nop(self):
pass
@accepts("register", "register")
def move(self, source, dest):
self.memory[dest].value = self.dereference(source)
@accepts("int", "register")
def load(self, value, dest):
self.memory[dest].value = value
@accepts("any")
def push(self, value):
value_ = self.dereference(value)
self.stack.append(value_)
@accepts("register")
def pop(self, dest):
try:
value = self.stack.pop()
except IndexError, e:
value = 0
self.memory[dest].value = value
@accepts("any")
def jump(self, distance):
distance_ = self.dereference(distance)
# -1 becuase the pc will increment after this instruction anyways
self.pc += (distance_ - 1)
if self.pc < 0 or self.pc > len(self.program):
raise JumpedOutException
@accepts("register", "any")
def jump_if_pos(self, location, distance):
distance_ = self.dereference(distance)
if self.dereference(location) > 0:
self.jump(distance_)
@accepts("register", "any")
def jump_if_neg(self, location, distance):
distance_ = self.dereference(distance)
if self.dereference(location) < 0:
self.jump(distance_)
@accepts("register", "any", "any")
def jump_if_eq(self, first, second, distance):
first_ = self.dereference(first)
second_ = self.dereference(second)
distance_ = self.dereference(distance)
if first_ == second_:
self.jump(distance_)
@accepts("register")
def print_mem(self, location):
"""Prints the memory location as an int"""
self.output(self.memory[location].value)
@accepts("register")
def print_char(self, location):
"""Chops off all by the first 8 bits and prints it as a char"""
value = self.memory[location].value
self.output(chr(value & 0b11111111))
@accepts("register", "any")
def print_string(self, location, length):
length_ = self.dereference(length)
location_int = int(location)
output_string = []
for index in xrange(location_int, location_int + length_):
print(self.memory[str(index)])
output_string.append(chr(self.memory[str(index)].value))
self.output("".join(output_string))
# self.output("".join([chr(self.memory[str(index)]) for index in xrange(location_int, location_int + length_)]))
class MemoryLocation(object):
"""Handles storing and operating on memory registers
Memory can store one 32bit number
If treated as a byte, the 8 low order bits are used
"""
def __init__(self, value=0):
super(MemoryLocation, self).__init__()
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
# Make sure it doesn't go over or under the max/min values
self._value = min(self._value, MAX_INT)
self._value = max(self._value, MIN_INT)
def as_byte(self):
pass
def __str__(self):
return str(self.value)
def __repr__(self):
return "MemoryLocation(value={})".format(self.value)
class JumpedOutException(Exception):
"""Exception for when execution jumps out of the program memory"""
def __init__(self, error_string=""):
super(JumpedOutException, self).__init__(error_string)
self.error_string = error_string