-
Notifications
You must be signed in to change notification settings - Fork 1
/
calculator.py
284 lines (216 loc) · 6.69 KB
/
calculator.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
##Proof of concept for project
from typing import List, Optional, Tuple
from abc import ABC, abstractmethod
import re
class StackException(Exception):
pass
Stack = List[int]
class State:
pass
class Instruction:
pass
Program = List[Instruction]
class State:
def __init__(self, stack: Stack, program: Program):
self.stack: Stack = stack
self.pc: int = 0
self.program: Program = program
class Instruction(ABC):
def __init__(self, name: str):
self.name = name
def check(self, state: State):
pass
def update_pc(self, state: State):
pass
def manipulate_stack(self, stack: Stack):
pass
def remove_inputs(self, stack: Stack, num_to_remove: int):
stack = stack[:-num_to_remove]
def do(self, state: State):
self.check(state)
self.update_pc(state)
self.manipulate_stack(state.stack)
def __repr__(self):
return self.name
class SkipInstruction(Instruction):
def update_pc(self, state):
state.pc += 1
class InputInstruction(Instruction):
def __init__(self, name: str, num_inputs: int):
super().__init__(name)
self.num_inputs = num_inputs
def check(self, state: State):
if len(state.stack) < self.num_inputs:
raise StackException(f'The {self.name} instruction requires {self.num_inputs} inputs.')
class Stop(Instruction):
symbol = '.'
def __init__(self):
super().__init__('stop')
def check(self, state: State):
pass
def update_pc(self, state: State):
pass
def manipulate_stack(self, stack: Stack):
pass
class Add(InputInstruction, SkipInstruction):
symbol = '+'
def __init__(self):
super().__init__('add', 2)
def manipulate_stack(self, stack: Stack):
a = stack.pop()
b = stack.pop()
stack.append(a + b)
class Subtract(InputInstruction, SkipInstruction):
symbol = '-'
def __init__(self):
super().__init__('subtract', 2)
def manipulate_stack(self, stack: Stack):
a = stack.pop()
b = stack.pop()
stack.append(b - a)
class Multiply(InputInstruction, SkipInstruction):
symbol = '*'
def __init__(self):
super().__init__('multiply', 2)
def manipulate_stack(self, stack: Stack):
a = stack.pop()
b = stack.pop()
stack.append(a * b)
class Divide(InputInstruction, SkipInstruction):
symbol = '/'
def __init__(self):
super().__init__('divide', 2)
def manipulate_stack(self, stack: Stack):
a = stack.pop()
b = stack.pop()
stack.append(b // a)
class Remainder(InputInstruction, SkipInstruction):
symbol = '%'
def __init__(self):
super().__init__('remainder', 2)
def manipulate_stack(self, stack: Stack):
a = stack.pop()
b = stack.pop()
stack.append(b % a)
class Push(SkipInstruction):
def __init__(self, n: int):
super().__init__('push')
self.n = n
def manipulate_stack(self, stack: Stack):
stack.append(self.n)
def __repr__(self):
return f'push {self.n}'
class Drop(InputInstruction, SkipInstruction):
symbol = 'd'
def __init__(self):
super().__init__('drop', 1)
def manipulate_stack(self, stack: Stack):
stack.pop()
class Bring(InputInstruction, SkipInstruction):
symbol = 'b'
def __init__(self):
super().__init__('bring', 1)
def manipulate_stack(self, stack: Stack):
i = stack.pop()
try:
to_move = stack[-i]
del stack[-i]
stack.append(to_move)
except IndexError:
raise StackException('Index error in bring')
class Send(InputInstruction, SkipInstruction):
symbol = 's'
def __init__(self):
super().__init__('send', 2)
def manipulate_stack(self, stack: Stack):
i = stack.pop()
to_move = stack.pop()
try:
stack.insert(i + 1, to_move)
except IndexError:
raise StackException('Index error in send')
class Copy(InputInstruction, SkipInstruction):
symbol = 'c'
def __init__(self):
super().__init__('copy', 1)
def manipulate_stack(self, stack: Stack):
i = stack.pop()
try:
to_copy = stack[-i]
stack.append(to_copy)
except IndexError:
raise StackException('Index error in copy')
class Jump(InputInstruction):
symbol = 'j'
def __init__(self):
super().__init__('jump', 1)
def update_pc(self, state: State):
x = state.stack[-1]
if x >= len(state.program):
raise StackException('Invalid program counter in jump')
state.pc = x
def manipulate_stack(self, stack: Stack):
stack.pop()
class If(InputInstruction):
symbol = 'i'
def __init__(self):
super().__init__('if', 3)
def update_pc(self, state: State):
b = state.stack[-3]
i = state.stack[-2]
e = state.stack[-1]
x = i
if b == 0:
x = e
if x >= len(state.program):
raise StackException('Invalid program counter in jump')
state.pc = x
def manipulate_stack(self, stack: Stack):
stack.pop()
stack.pop()
stack.pop()
class Equals(InputInstruction, SkipInstruction):
symbol = '='
def __init__(self):
super().__init__('equals', 2)
def manipulate_stack(self, stack: Stack):
a = stack[-1]
b = stack[-2]
if a == b:
stack.append(1)
else:
stack.append(0)
def parse(s: str) -> Program:
instructions = [Stop, Add, Subtract, Multiply, Divide, Remainder, Drop, Bring, Send, Copy, Jump, If, Equals]
symbol_dict = {i.symbol: i for i in instructions}
program: Program = []
while s != '':
print(s)
if s[0] in symbol_dict:
program.append(symbol_dict[s[0]]())
s = s[1:]
else:
match = re.match(r'\d+,?', s)
if match is None:
break
n_str = match.group().strip(',')
s = s[match.end():]
program.append(Push(int(n_str)))
s.strip()
if s != '':
raise Exception('could not parse')
return program
def run(program: Program, init_stack: Stack):
state: State = State(init_stack, program)
while True:
print(state.stack)
if state.pc >= len(program):
break
instruction: Instruction = program[state.pc]
if isinstance(instruction, Stop):
break
instruction.do(state)
p = parse('=4,6i4.7')
print(p)
# s = [3, 5]
# run(p, s)