-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.py
256 lines (208 loc) · 8.81 KB
/
runner.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
import enum
class BreakpointState(enum.Enum):
off = "off"
on_execute = "execute"
on_read = "read"
on_write = "write"
on_rw = "read or write"
on_next_execute = "next to execute"
class ValueState(enum.Enum):
normal = "nothing"
read = "read"
written = "written"
executed = "executed"
next_exec = "executed next"
class HaltReason(enum.Enum):
hlt = "hlt"
input = "input"
step = "step"
breakpoint = "breakpoint"
def int_to_complement(i):
return (1000 + i) % 1000
def int_from_complement(i):
return i - 1000 if i >= 500 else i
class MemoryValue:
def __init__(self, address, token=None):
self.address = address
self.token = token
self.state = ValueState.normal
self.breakpoint = BreakpointState.off
self.value = token.machine_instruction() if token else 0
def reset(self):
self.value = self.token.machine_instruction() if self.token else 0
self.state = ValueState.normal
def reset_state(self):
self.state = ValueState.normal
def write(self, value):
self.state = ValueState.written
self.value = int_to_complement(value)
def read(self):
self.state = ValueState.read
return self.value
def execute(self):
self.state = ValueState.executed
return self.value
def next_exec(self):
self.state = ValueState.next_exec
def hit_breakpoint(self):
if self.breakpoint == BreakpointState.off:
return False
elif self.breakpoint == BreakpointState.on_execute:
return self.state == ValueState.executed
elif self.breakpoint == BreakpointState.on_read:
return self.state == ValueState.read
elif self.breakpoint == BreakpointState.on_write:
return self.state == ValueState.written
elif self.breakpoint == BreakpointState.on_rw:
return self.state in (ValueState.read, ValueState.written)
elif self.breakpoint == BreakpointState.on_next_execute:
return self.state == ValueState.next_exec
def set_interactive(self, tooltip):
if self.token:
tooltip.type("mnemonic")
tooltip.value(self.token.text)
tooltip.newline()
tooltip.text("Memory value:")
tooltip.number("{:03}".format(self.value))
tooltip.newline()
tooltip.text("Last action:")
tooltip.action(self.state)
tooltip.newline()
if self.breakpoint != BreakpointState.off:
tooltip.text("Break on:")
tooltip.action(self.breakpoint.value)
class Runner:
def __init__(self, give_output):
self.give_output = give_output
self.breakpoints_active = False
self.memory = []
self.accumulator = MemoryValue("accumulator")
self.counter = 0
def load_code(self, assembler):
self.assembler = assembler
self.memory = []
self.assembler.assemble()
if self.assembler.in_error:
return
for i, v in enumerate(self.assembler.instructions):
self.memory.append(MemoryValue(i, v))
while len(self.memory) < 100:
self.memory.append(MemoryValue(len(self.memory)))
self.accumulator.reset()
self.breakables = self.memory + [self.accumulator]
self.reset()
def load_breakpoints(self, brps):
brps = sorted(brps.items())
for instr in self.assembler.instructions:
value = self.memory[instr.address]
value.breakpoint = BreakpointState.off
while brps and brps[0][0] <= instr.position.lineno:
value.breakpoint = brps.pop(0)[1]
def give_input(self, i):
if self.halt_reason == HaltReason.input:
self.accumulator.write(i)
self.halt_reason = HaltReason.breakpoint if self.hit_breakpoints() else HaltReason.step
def hit_breakpoints(self):
return [m for m in self.breakables if m.hit_breakpoint()]
def next_step(self):
for m in self.memory:
m.reset_state()
instruction = self.memory[self.counter].execute()
self.instruction_addr = self.counter
self.counter += 1
self.memory[self.counter].next_exec()
addr = instruction % 100
self.halt_reason = HaltReason.step
if instruction == 0: # HLT
self.hint = "HLT"
self.give_output("Done! Coffee break!")
self.halt_reason = HaltReason.hlt
elif instruction < 100:
raise RuntimeError("Invalid instruction {:03}".format(instruction))
elif instruction < 200: # ADD
memval = self.memory[addr].read()
value = int_to_complement(self.accumulator.read() + memval)
self.hint = ("ADD {0:03}: accumulator = {1:03} (accumulator) + "
"{2:03} (#{0:03}) = {3:03}".format(addr,
self.accumulator.value,
memval, value))
self.accumulator.write(value)
elif instruction < 300: # SUB
memval = self.memory[addr].read()
value = int_to_complement(self.accumulator.read() - memval)
self.hint = ("SUB {0:03}: accumulator = {1:03} (accumulator) - "
"{2:03} (#{0:03}) = {3:03}".format(addr,
self.accumulator.value,
memval, value))
self.accumulator.write(value)
elif instruction < 400: # STA
self.hint = ("STA {0:03}: store {1:03} (accumulator) to #{0:03}"
.format(addr, self.accumulator.value))
self.memory[addr].write(self.accumulator.read())
elif instruction < 500:
raise RuntimeError("Invalid instruction {:03}".format(instruction))
elif instruction < 600: # LDA
memval = self.memory[addr].read()
self.hint = ("LDA {0:03}: load {1:03} (#{0:03}) to accumulator"
.format(addr, memval))
self.accumulator.write(memval)
elif instruction < 700: # BRA
self.hint = "BRA {0:03}: branch to #{0:03}".format(addr)
self.counter = addr
elif instruction < 800: # BRZ
words = ("==", "") if self.accumulator.read() == 0 else ("!=", " don't")
self.hint = ("BRZ {0:03}: {1:03} (accumulator) {2} 000, so{3} branch"
" to #{0:03}".format(addr, self.accumulator.value, *words))
if self.accumulator.read() == 0:
self.counter = addr
elif instruction < 900: # BRP
words = ("<", "") if self.accumulator.read() < 500 else (">=", " don't")
self.hint = ("BRP {0:03}: {1:03} (accumulator) {2} 500, so{3} branch to #{0:03}"
.format(addr, self.accumulator.value, *words))
if self.accumulator.read() < 500:
self.counter = addr
elif instruction == 901: # INP
self.hint = "INP"
self.halt_reason = HaltReason.input
elif instruction == 902: # OUT
self.hint = "OUT"
self.give_output(int_from_complement(self.accumulator.read()))
else:
raise RuntimeError("Invalid instruction {:03}".format(instruction))
if self.halt_reason == HaltReason.step and self.breakpoints_active and self.hit_breakpoints():
self.halt_reason = HaltReason.breakpoint
return self.halt_reason
def run_to_hlt(self):
r = HaltReason.step
while r in (HaltReason.step, HaltReason.breakpoint):
r = self.next_step()
return r
def reset(self):
self.counter = self.instruction_addr = 0
self.halt_reason = HaltReason.step
self.accumulator.reset()
for m in self.memory:
m.reset()
self.memory[self.counter].next_exec()
if __name__ == "__main__":
import sys
import assembler
assem = assembler.Assembler()
assem.update_code(open(sys.argv[1]).read())
print(assem.assemble())
runner = Runner(lambda x: print(">>>", x))
runner.load_code(assem)
runner.accumulator.breakpoint = BreakpointState.on_write
runner.memory[44].breakpoint = BreakpointState.on_read
for m in runner.memory:
print(m.breakpoint)
while runner.halt_reason != HaltReason.hlt:
runner.next_step()
if runner.halt_reason == HaltReason.input:
runner.give_input(int(input("<<< ")))
print(runner.hint)
if runner.halt_reason == HaltReason.breakpoint:
print("=== Breakpoint ===")
for val in runner.hit_breakpoints():
print("{:<12}".format(str(val.address).zfill(3) + ":"), val.breakpoint)
input("Press enter to continue...")