-
Notifications
You must be signed in to change notification settings - Fork 0
/
whitespace.py
320 lines (275 loc) · 8.93 KB
/
whitespace.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
import re
class Compiler(object):
def parse(self):
i = 0
while i < len(self.code):
j = i
code = self.code[i:]
for r, op in self.regexs.items():
match = re.match(r, code)
if match:
d = {'start':i, 'next':i+match.end(), 'op': op, 'exp': match.group()}
if any(match.groups()):
d['arg'] = match.groups()[0]
i += match.end()
yield d
if j == i:
i+=1
raise Exception('parse failed')
def __init__(self, code):
self.code = code
self.regexs = {
'^\t\n ': 'output_char',
'^\t\n \t': 'output_number',
'^\t\n\t ': 'read_chr',
'^\t\n\t\t': 'read_num',
'^ ([^\n]+)\n': 'append',
'^ \t ([^\n]+)\n': 'dup_at',
'^ \t\n([^\n]+)\n': 'pop_x',
'^ \n ': 'dupe',
'^ \n\t': 'swap',
'^ \n\n': 'pop',
'^\t ': 'add',
'^\t \t': 'sub',
'^\t \n': 'mul',
'^\t \t ': 'div',
'^\t \t\t': 'mod',
'^\n ([^\n]*\n)': 'mark_sub',
'^\n \t([^\n]*\n)': 'call_sub',
'^\n \n([^\n]*\n)': 'jmp',
'^\n\t ([^\n]*\n)': 'jmp_eq',
'^\n\t\t([^\n]*\n)': 'jmp_lt',
'^\n\t\n': 'exit_sub',
'^\n\n\n': 'terminate',
'^\t\t ': 'heap_store',
'^\t\t\t': 'heap_retrieve'
}
class Interpreter(object):
def parse_number(self):
start = self.ip
s_bin = ''
sign = self.npsc[self.code[self.ip]]
if sign is str:
raise Exception('bad sign')
self.ip += 1
while self.code[self.ip] != '\n':
s_bin += self.npbc[self.code[self.ip]]
self.ip += 1
self.ip+=1
return int(s_bin, 2) * sign if s_bin != '' else 0
def swap(self):
self.stack[-1],self.stack[-2] = self.stack[-2],self.stack[-1]
return 'swap'
def output_number(self):
self.output += str(self.stack.pop())
return 'output_number'
def output_char(self):
cur = self.stack.pop()
if type(cur) is int:
self.output += chr(cur)
else:
self.output += cur
return 'output_char'
def terminate(self):
self.ip = len(self.code)
self.terminated = True
return 'term'
def dup_at(self):
parsed = self.parse_number() + 1
if parsed <= 0 or parsed > len(self.stack):
raise Exception('Out of bounds')
self.stack.append(self.stack[-parsed])
return 'dup_at'
def append(self):
self.stack.append(self.parse_number())
return 'append read'
def pop_x(self):
x = self.parse_number()
top = self.stack.pop()
if x > len(self.stack) or x < 0:
x = len(self.stack)
for _ in range(x):
self.stack.pop()
self.stack.append(top)
return 'pop_x'
def heap_store(self):
a = self.stack.pop()
b = self.stack.pop()
self.heap[b] = a
return 'heap store'
def heap_retrieve(self):
a = self.stack.pop()
self.stack.append(self.heap[a])
return 'heap ret'
def add(self):
a,b = self.stack.pop(), self.stack.pop()
self.stack.append(b+a)
return 'add'
def sub(self):
a,b = self.stack.pop(), self.stack.pop()
self.stack.append(b-a)
return 'sub'
def mul(self):
a,b = self.stack.pop(), self.stack.pop()
self.stack.append(b*a)
return 'mul'
def div(self):
a,b = self.stack.pop(), self.stack.pop()
self.stack.append(b//a)
return 'div'
def mod(self):
a,b = self.stack.pop(), self.stack.pop()
self.stack.append(b%a)
return 'mod'
def read_chr(self):
self.heap[self.stack.pop()] = self.input[self.inp]
self.inp+=1
return 'read_chr'
def read_num(self):
remaining = self.input[self.inp:]
index = remaining.find('\n')
val = int(remaining[:index])
self.heap[self.stack.pop()] = val
self.inp+=index+1
return 'read_num'
def mark_sub(self):
code = self.code[self.ip:]
label = code[:code.find('\n')+1]
self.subroutines[label] = self.ip+len(label) # +1 ??
self.ip+= len(label)
return 'mark_sub'
def call_sub(self):
code = self.code[self.ip:]
label = code[:code.find('\n')+1]
self.call_stack.append(self.ip+len(label))
self.ip = self.subroutines[label]
return 'call_sub'
def exit_sub(self):
self.ip = self.call_stack.pop()
return 'exit_sub'
def jmp(self):
code = self.code[self.ip:]
label = code[:code.find('\n')+1]
self.ip = self.subroutines[label]
return 'jmp'
def jmp_eq(self):
if self.stack.pop() == 0:
self.jmp()
else:
self.ip += 1
return 'jmp_eq'
def jmp_lt(self):
if self.stack.pop() < 0:
self.jmp()
else:
self.ip += 1
return 'jmp_lt'
def __init__(self, code, input):
def only_whitespace(s):
return ''.join([c for c in s if c in ' \t\n'])
self.code = only_whitespace(code)
self.input = input
self.ip = 0
self.inp = 0
self.stack = []
self.call_stack = []
self.heap = {}
self.subroutines = {}
self.output = ''
self.terminated = False
labels = list([d for d in Compiler(self.code).parse() if d['op'] == 'mark_sub'])
for label in labels:
if label['arg'] in self.subroutines:
raise Exception('Doublely Declared Label')
self.subroutines[label['arg']] = label['next']
self.ioc = {
' ': self.output_char,
' \t': self.output_number,
'\t ': self.read_chr,
'\t\t': self.read_num
}
self.smc = {
' ': self.append,
'\n ': lambda: self.stack.append(self.stack[-1]),
'\t\n': self.pop_x,
'\t ': self.dup_at,
'\n\t': self.swap,
'\n\n': self.stack.pop
}
self.ac = {
' ': self.add,
' \t': self.sub,
' \n': self.mul,
'\t ': self.div,
'\t\t': self.mod
}
self.fcc = {
' ': self.mark_sub,
' \t': self.call_sub,
' \n': self.jmp,
'\t ': self.jmp_eq,
'\t\t': self.jmp_lt,
'\t\n': self.exit_sub,
'\n\n': self.terminate
}
# HEAP
self.hac = {
' ': self.heap_store,
'\t': self.heap_retrieve
}
self.imp = {
'\t\n': self.ioc,
'\t ': self.ac,
'\t\t': self.hac,
'\n': self.fcc,
' ': self.smc,
}
self.npsc = {'\t': -1, ' ': 1, '\n': '\n'}
self.npbc = {'\t': '1', ' ': '0', '\n': '\n'}
regexs = {
'\t\n ': self.output_char,
'\t\n \t': self.output_number,
'\t\n\t ': self.read_chr,
'\t\n\t\t': self.read_num,
' ([^\n]+)\n': self.append,
' \t ([^\n]+)\n': self.dup_at,
' \t\n([^\n]+)\n': self.pop_x,
' \n ': lambda: self.stack.append(self.stack[-1]),
' \n\t': self.swap,
' \n\n': self.stack.pop,
'\t ': self.add,
'\t \t': self.sub,
'\t \n': self.mul,
'\t \t ': self.div,
'\t \t\t': self.mod,
'\n ([^\n]*\n)': self.mark_sub,
'\n \t([^\n]*\n)': self.call_sub,
'\n \n([^\n]*\n)': self.jmp,
'\n\t ([^\n]*\n)': self.jmp_eq,
'\n\t\t([^\n]*\n)': self.jmp_lt,
'\n\t\n': self.exit_sub,
'\n\n\n': self.terminate,
'\t\t ': self.heap_store,
'\t\t\t': self.heap_retrieve
}
def parse(self):
while self.ip < len(self.code):
imp1 = self.code[self.ip:self.ip + 2]
for iden, lookup in self.imp.items():
if imp1.startswith(iden):
oip = self.ip
self.ip += len(iden)
imp2 = self.code[self.ip:self.ip + 2]
for jden, definition in lookup.items():
if imp2.startswith(jden):
self.ip += len(jden)
out = definition()
break
break
if not self.terminated:
raise Exception('not terminated')
# solution
def whitespace(code, inp=''):
interpreter = Interpreter(code, inp)
interpreter.parse()
return interpreter.output