-
Notifications
You must be signed in to change notification settings - Fork 0
/
abeinterpreter.py
339 lines (259 loc) · 10 KB
/
abeinterpreter.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import re
import operator
class AbeInterpreter:
def __init__(self):
self._i = 0
self._tape = [0]
self._buffer = []
self._tokens = list()
self._loopcons = list()
self._loopactions = list()
self._currentlooplevel = 0
self._cval = 0
self._output = ''
self._has_error = False
self._error = ''
self._rs = {
'number': '((\-?\d+\.\d*)|(\-?\d+))',
'bool': 'True|False',
'string': '\".*\"'
}
def _mr(self):
raw = self._tokens.pop()
v = self._cast(self._getParmType(raw), raw)
self._i += v
length = len(self._tape) - 1
if self._i > length:
for n in range(length, self._i + 1):
self._tape.append(0)
def _ml(self):
raw = self._tokens.pop()
v = self._cast(self._getParmType(raw), raw)
self._i -= v
if self._i < 0:
self._has_error = True
self._error = 'Not allowed to move left of index 0.'
def _incr(self):
raw = self._tokens.pop()
v = self._cast(self._getParmType(raw), raw)
self._tape[self._i] += v
def _decr(self):
raw = self._tokens.pop()
v = self._cast(self._getParmType(raw), raw)
self._tape[self._i] -= v
def _getInput(self):
x = input()
x = self._cast(self._getParmType(x), x)
self._tape[self._i] = x
def _storeVal(self):
raw = self._tokens.pop()
v = self._cast(self._getParmType(raw), raw)
self._buffer = self._buffer[1:]
self._tape[self._i] = v
def _doLoop(self):
raw = self._tokens.pop()
loop_id = self._cast(self._getParmType(raw), raw)
# get conditions linked to this loop
op, val = self._loopcons[loop_id]
condition_met = op(self._tape[self._i], val)
# if conditions are met, push the loop actions onto the tokens stack
if condition_met:
self._tokens.extend(self._loopactions[loop_id])
def _defineLoop(self):
# get the loop condition's operator (rawOp) and value (rawVal)
rawOp = self._tokens.pop()
rawVal = self._tokens.pop()
ops = {'>':operator.gt, '<':operator.lt, '==':operator.eq}
# dict with string as key and function as value
op = ops[rawOp]
val = self._cast(self._getParmType(rawVal), rawVal)
# add the loop condition to the loop condition stack
self._loopcons.append([op, val])
loopIndex = len(self._loopactions)
self._currentlooplevel += 1
is_inner_loop = self._currentlooplevel > 1 # outermost loop will have loop level 1
# need to evaluate actions within loop
self._loopactions.append(list())
while True:
if self._tokens[-1] == 'while':
self._tokens.pop()
self._loopactions[loopIndex].extend(self._defineLoop()) # include tokens for any inner loops
if self._tokens[-1] == 'loopend':
# can either be loopend token for inner loop or for this loop
self._tokens.pop()
break # either way, exit while loop
else:
# append normal token to list of actions for this loop
self._loopactions[loopIndex].append(self._tokens.pop())
# when we get to the end of the loop actions, re-evaluate loop condition
self._loopactions[loopIndex].append('loop')
self._loopactions[loopIndex].append(str(loopIndex)) # adds loop to end of itself for re-eval
self._loopactions[loopIndex].reverse()
self._currentlooplevel -= 1
if is_inner_loop: # all inner loops will return their loop token to containing loop
return ['loop', str(loopIndex)]
else: # is base-level loop, so push on loop tokens for stack
self._tokens.append(str(loopIndex))
self._tokens.append('loop')
def _loopend(self):
op, val = self._loopcons[-1]
condition_met = op(self._tape[self._i], val)
if condition_met:
# if loop conditions are met, re-append the loop actions
self._tokens.append('loopend')
self._tokens.extend(self._loopactions[-1])
def _copyVal(self):
self._cval = self._tape[self._i]
def _pasteVal(self):
self._tape[self._i] = self._cval
def _cast(self, typeString, val):
d = dict()
d['float'] = float
d['int'] = int
try:
if typeString == 'str':
val = val.strip('"')
return val
elif typeString == 'bool':
val = (val == 'True')
return val
return d[typeString](val)
except:
self._has_error = True
self._error = f'Could not cast {val} to type {typeString}'
def _getParmType(self, p):
tokens = [
('float', r'\-?\d+\.\d*'),
('int', r'\-?\d+'),
('bool', r'%s' % self._rs['bool']),
('str', r'%s' % self._rs['string'])
]
ms = re.compile('|'.join(['(?P<%s>%s)' % tup for tup in tokens]))
match = re.match(ms, p)
return match.lastgroup
def _printCell(self):
self._output += str(self._tape[self._i]) + '\n'
def _processCond(self, match):
s = match.string[match.start():match.end()]
s = s.replace('He ran into the mountains, but only when ', '')
cond = s.replace('. This is what happened there:', '')
# parse condition
t = [
('gt', r'they had more than %s fish' % self._rs['number']),
('lt', r'they had less than %s fish' % self._rs['number']),
('eq', r'the stone said .*')
]
op = ''
val = ''
ms = re.compile('|'.join(["(?P<%s>%s)" % tup for tup in t]))
try:
optype = re.search(ms, cond).lastgroup
except:
self._has_error = True
self._error = 'Loop condition syntax is incorrect.'
return 'error'
if optype in ['gt', 'lt', 'deq']:
d = re.search(r'%s' % self._rs['number'], cond)
if d:
val = d.group()
elif optype=='eq':
op = '=='
val = cond.replace('the stone said ', '')
else:
self._has_error = True
return 'error'
opdict = {'eq':'==', 'gt':'>', 'lt':'<'}
op = opdict[optype]
return op, val
def _processDigitToken(self, match):
s = match.string[match.start():match.end()]
ms = re.compile(r'%s' % self._rs['number'])
m = re.search(ms, s)
v = 0
if m is not None:
v = m.group()
return v
def _processStoreToken(self, match):
s = match.string[match.start():match.end()]
s = s.replace('Preparing for the storm, he carved ', '')
s = s.replace(' into the stone.', '')
return s
def _consumeToken(self, token):
comms = dict()
comms['mr'] = self._mr
comms['ml'] = self._ml
comms['incr'] = self._incr
comms['decr'] = self._decr
comms['store'] = self._storeVal
comms['pin'] = self._getInput
comms['pout'] = self._printCell
comms['while'] = self._defineLoop
comms['loop'] = self._doLoop
comms['loopend'] = self._loopend
comms['copyval'] = self._copyVal
comms['pasteval'] = self._pasteVal
comms[token]()
def _consumeTokenList(self):
while len(self._tokens) > 0:
if self._has_error:
break
self._consumeToken(self._tokens.pop())
def _tokenize(self, s):
t = [
('mr', r'Overhead, the geese flew \d+ miles east\.'),
('ml', r'Overhead, the geese flew \d+ miles west\.'),
('incr', r'He sold .*? sheep\.'),
('decr', r'They paid for their .*? mistakes\.'),
('pout', r'And Abraham spoke!'),
('pin', r'He listened when his wife spoke\.'),
('while', r'He ran into the mountains, but only when .*?\. This is what happened there\:'),
('loopend', r'Alas, I digress\.'),
('store', r'Preparing for the storm, he carved .*? into the stone\.'),
('copyval', r'One day he stole his neighbor\'s goods\.'),
('pasteval', r'He repented and returned the property\.'),
('s', r'\s+')
]
ms = re.compile('|'.join(['(?P<%s>%s)' % tup for tup in t]))
output = []
lastend = 0
f = [x for x in re.finditer(ms, s)]
for m in f:
if m.lastgroup == 's':
lastend = m.end()
continue
if m.start() != lastend:
self._has_error = True
self._error = 'Problem with syntax in position %s' % m.start()
return output
if m.lastgroup in ['mr', 'ml', 'incr', 'decr']:
output.append(m.lastgroup)
output.append(self._processDigitToken(m))
elif m.lastgroup == 'store':
output.append(m.lastgroup)
output.append(self._processStoreToken(m))
elif m.lastgroup == 'while':
output.append(m.lastgroup)
output.extend(self._processCond(m))
else:
output.append(m.lastgroup)
lastend = m.end()
if lastend != len(s) and s[-1]!=' ':
self._has_error = True
self._error = 'Problem with syntax in position'
output.reverse()
return output
def interpret(self, abraham_code, *args):
self._buffer = [a for a in args]
self._i = 0
self._tape = [0]
self._tokens = list()
self._loopcons = list()
self._loopactions = list()
self._cval = 0
self._output = ''
self._tokens = self._tokenize(abraham_code)
self._consumeTokenList()
if self._has_error:
return self._error
else:
return self._output