-
Notifications
You must be signed in to change notification settings - Fork 1
/
assembly.py
85 lines (66 loc) · 2.36 KB
/
assembly.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
from itertools import count
from collections import namedtuple
from abc import ABC, abstractmethod
class BaseAssembler(ABC):
Result = namedtuple("Result", ["result", "finished"])
def __init__(self, lines, registers, print_idxs=None):
self.lines = lines
self.instrs = self.process_lines(lines)
self.registers = registers
self.print_idxs = set() if print_idxs is None else print_idxs
self.step = -1
self.instr_idx = 0
self.instr_idx_delta = 1
self.jump = None
self.jump_abs = False
@abstractmethod
def is_finished(self):
pass
@abstractmethod
def get_result(self):
pass
@classmethod
def get_possible_instrs(cls):
return [e[3:] for e in dir(cls) if e.startswith("i__")]
def print_state(self):
print(
f"{self.step:10} | {self.instr_idx:3} "
+ str(" ".join(str(e) for e in self.instrs[self.instr_idx])).ljust(20)
+ " | "
+ " ".join(f"{k}: {v:<10}" for k, v in sorted(self.registers.items()))
)
def process_line(self, line):
return [
int(e) if e.isdigit() or (e.startswith("-") and e[1:].isdigit()) else e
for e in line.split()
]
def process_lines(self, lines):
return [self.process_line(e) for e in lines]
def is_paused(self):
return False
def get_cmd_and_args(self):
cmd, *args = self.instrs[self.instr_idx]
return cmd, args
def eval(self, val):
return val if isinstance(val, int) else self.registers[val]
def update_instr_idx(self):
if self.jump is not None:
if self.jump_abs:
self.instr_idx = self.jump
else:
self.instr_idx += self.jump
self.jump = None
return
self.instr_idx += self.instr_idx_delta
def run(self):
for self.step in count(self.step + 1):
if self.instr_idx in self.print_idxs:
self.print_state()
if self.is_finished():
return BaseAssembler.Result(self.get_result(), True)
if self.is_paused():
return BaseAssembler.Result(self.get_result(), False)
cmd, args = self.get_cmd_and_args()
fn = getattr(self, f"i__{cmd}")
fn(*args)
self.update_instr_idx()