-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhitespace_interpreter.py
More file actions
561 lines (459 loc) · 18.7 KB
/
whitespace_interpreter.py
File metadata and controls
561 lines (459 loc) · 18.7 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
from collections import OrderedDict
class WhitespaceInt(int):
"""Helper class to manage integers in Whitespace."""
def __new__(cls, num):
return super().__new__(cls, num)
def __str__(self):
return super().__str__()
@classmethod
def from_whitespace(cls, code):
"""Converts the Whitespace representation of a number to an integer."""
if len(code) == 1:
num = 0
return cls(num)
keys = [' ', '\t']
sign = 2 * (1 - keys.index(code[0])) - 1
binary = ''.join([str(keys.index(x)) for x in code[1:]])
num = int(binary, 2) * sign
return cls(num)
class Interpreter:
"""The main interpreter for the program handles our state and responds to input."""
"""Instruction Modification Parameters (IMPs)
[space]: Stack Manipulation
[tab][space]: Arithmetic
[tab][tab]: Heap Access
[tab][line-feed]: Input/Output
[line-feed]: Flow Control
"""
IMP = OrderedDict({
' ': 'Stack',
'\t ': 'Arithmetic',
'\t\t': 'Heap',
'\t\n': 'IO',
'\n': 'FlowControl'
})
def __init__(self, code, inp=''):
self.stack = []
self.heap = {}
self.pos = 0
self.code = code
self.code_length = len(code)
self.inp = inp
self.input = list(inp)
self.output = ''
self.loading = True
self.instruction = ''
self.command = ''
self.labels = {}
self.return_positions = []
@property
def stack_size(self):
"""Alias for the size of the stack."""
return len(self.stack)
def clean(self, s):
"""Returns a readable string representation of whitespace."""
return s.replace(' ', 's').replace('\t', 't').replace('\n', 'n')
def num_parameter(self):
"""Retrieves the next number in the sequence.
Format of a number:
sign - binary - terminator
sign: [space] + / [tab] -
binary: [space] 0 / [tab] 1
terminator: \n
"""
code = self.code
index = code.find('\n', self.pos)
# Only including a terminal causes an error
if index == self.pos:
raise SyntaxError('Number must include more than just the terminal.')
item = WhitespaceInt.from_whitespace(code[self.pos:index])
return index, item
def label_parameter(self):
"""Sets a label in the sequence if possible.
Format of a label:
name - terminator
*name: any number of [space] and [tab]
terminator: \n
*Must be unique.
"""
code = self.code
index = code.find('\n', self.pos) + 1
# Empty string is a valid label
name = code[self.pos:index]
return index, name
def get_command(self, imp):
"""Gets the token for an IMP category."""
pos = self.pos
code = self.code
token = code[pos:pos + 1]
if token not in imp:
token = code[pos:pos + 2]
# Check if our token is a valid IMP
for key, value in imp.items():
if key == token:
self.command = value
self.pos += len(key)
break
else:
raise KeyError(f'No IMP found for token: {token}')
def run(self):
"""Main loop of the program goes through each instruction."""
if self.code_length == 0:
raise SyntaxError('Unclean termination of program')
if self.loading:
print(f'Code: {self.clean(self.code)}')
print(f'Input: {self.input}')
while self.pos < self.code_length:
pos = self.pos
code = self.code
token = code[pos:pos + 1]
if token not in self.IMP:
token = code[pos:pos + 2]
# Check if our token is a valid IMP
for key, value in self.IMP.items():
if key == token:
self.instruction = value
break
else:
print(self.clean(code))
raise SyntaxError(f'Unknown instruction ' + self.instruction)
if not self.loading:
print(f'({self.pos}) Instruction: {self.instruction} - Stack: {self.stack} - Heap: {self.heap}')
self.pos += len(key)
getattr(self, self.instruction).parse(self)
if self.loading:
print(f'Finished marking labels. Starting program sequence...')
self.pos = 0
self.loading = False
self.run()
elif self.return_positions and self.pos != float('inf'):
raise SyntaxError('Subroutine does not properly exit or return')
elif self.pos == self.code_length:
raise RuntimeError('Unclean termination')
#raise Exception('Unclean termination')
class Stack:
"""Handles stack manipulation instructions."""
"""Instructions
[space] (number): Push n onto the stack.
[tab][space] (number): Duplicate the nth value from the top of the stack.
[tab][line-feed] (number): Discard the top n values below the top of the stack from the stack.
(For n<0 or n>=stack.length, remove everything but the top value.)
[line-feed][space]: Duplicate the top value on the stack.
[line-feed][tab]: Swap the top two value on the stack.
[line-feed][line-feed]: Discard the top value on the stack.
"""
STACK_IMP = OrderedDict({
' ': 'push_num',
'\t ': 'duplicate_nth',
'\t\n': 'discard_n',
'\n ': 'duplicate_top',
'\n\t': 'swap',
'\n\n': 'discard_top'
})
def parse(self):
"""Parses the next stack IMP."""
Stack = self.Stack
self.get_command(Stack.STACK_IMP)
if self.command == 'push_num':
index, item = self.num_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({item})')
Stack.push_num(self, item)
self.pos = index + 1
elif self.command == 'duplicate_nth':
index, item = self.num_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({item})')
Stack.duplicate_nth(self, item)
self.pos = index + 1
elif self.command == 'discard_n':
index, item = self.num_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({item})')
Stack.discard_n(self, item)
self.pos = index + 1
elif self.command == 'duplicate_top':
if not self.loading:
print(f'\tCommand: {self.command}')
Stack.duplicate_nth(self, 0)
elif self.command == 'swap':
if not self.loading:
print(f'\tCommand: {self.command}')
Stack.swap(self)
elif self.command == 'discard_top':
if not self.loading:
print(f'\tCommand: {self.command}')
Stack.discard_top(self)
def push_num(self, item):
self.stack.append(item)
def duplicate_nth(self, n):
if n > self.stack_size - 1:
raise ValueError('Cannot duplicate - Value exceeds stack size limit')
elif n < 0:
raise IndexError('Cannot duplicate negative stack index')
item = self.stack[-n - 1]
self.stack.append(item)
def discard_n(self, n):
if n >= self.stack_size or n < 0:
n = self.stack_size - 1
top = self.stack.pop()
for _ in range(n):
self.stack.pop()
self.stack.append(top)
def discard_top(self):
self.stack.pop()
def swap(self):
a, b = self.stack.pop(), self.stack.pop()
self.stack.append(a)
self.stack.append(b)
class IO:
"""Handles input/output operations."""
"""Instructions
[space][space]: Pop a value off the stack and output it as a character.
[space][tab]: Pop a value off the stack and output it as a number.
[tab][space]: Read a character from input, a, Pop a value off the stack, b, then store the ASCII value of a at heap address b.
[tab][tab]: Read a number from input, a, Pop a value off the stack, b, then store a at heap address b.
"""
IO_IMP = {
' ': 'output_char',
' \t': 'output_num',
'\t ': 'input_char',
'\t\t': 'input_num'
}
def parse(self):
"""Parses the next I/O IMP."""
IO = self.IO
self.get_command(IO.IO_IMP)
if self.loading:
return
print(f'\tCommand: {self.command}')
if self.command == 'output_char':
IO.output_char(self)
elif self.command == 'output_num':
IO.output_num(self)
elif self.command == 'input_char':
IO.input_char(self)
elif self.command == 'input_num':
IO.input_num(self)
def output_char(self):
char = chr(self.stack.pop())
self.output += char
print(f'>>> {char}')
def output_num(self):
num = int(self.stack.pop())
self.output += str(num)
print(f'>>> {num}')
def input_char(self):
a = self.input.pop(0)
b = self.stack.pop()
self.heap[b] = ord(a)
def input_num(self):
b = self.stack.pop()
index = self.input.index('\n')
num = ''.join(self.input[:index])
self.input = self.input[index + 1:]
self.heap[b] = int(num)
class FlowControl:
"""Handles flow control operations."""
"""Instructions
[space][space] (label): Mark a location in the program with label n.
[space][tab] (label): Call a subroutine with the location specified by label n.
[space][line-feed] (label): Jump unconditionally to the position specified by label n.
[tab][space] (label): Pop a value off the stack and jump to the label specified by n if the value is zero.
[tab][tab] (label): Pop a value off the stack and jump to the label specified by n if the value is less than zero.
[tab][line-feed]: Exit a subroutine and return control to the location from which the subroutine was called.
[line-feed][line-feed]: Exit the program.
"""
FLOW_IMP = {
' ': 'mark_label',
' \t': 'call_subroutine',
' \n': 'jump',
'\t ': 'jump_zero',
'\t\t': 'jump_lt_zero',
'\t\n': 'exit_subroutine',
'\n\n': 'exit'
}
def parse(self):
"""Parses the next flow control IMP."""
Flow = self.FlowControl
self.get_command(Flow.FLOW_IMP)
if self.command == 'exit':
if not self.loading:
print(f'\tCommand: {self.command}')
Flow.exit(self)
elif self.command == 'mark_label':
index, label = self.label_parameter()
if self.loading:
print(f'\tCommand: {self.command}({self.clean(label)})')
Flow.mark_label(self, label)
else:
print(f'\tIgnoring label marker')
self.pos = index
elif self.command == 'jump':
index, label = self.label_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({self.clean(label)})')
Flow.jump(self, label)
else:
self.pos = index
elif self.command == 'jump_zero':
index, label = self.label_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({self.clean(label)})')
num = self.stack.pop()
if num == 0:
Flow.jump(self, label)
else:
self.pos = index
else:
self.pos = index
elif self.command == 'jump_lt_zero':
index, label = self.label_parameter()
if not self.loading:
print(f'\tCommand: {self.command}({self.clean(label)})')
num = self.stack.pop()
if num < 0:
Flow.jump(self, label)
else:
self.pos = index
else:
self.pos = index
elif self.command == 'exit_subroutine':
if not self.loading:
print(f'\tCommand: {self.command}')
Flow.exit_subroutine(self)
elif self.command == 'call_subroutine':
index, label = self.label_parameter()
self.pos = index
if not self.loading:
print(f'\tCommand: {self.command}({self.clean(label)})')
Flow.call_subroutine(self, label)
def exit(self):
print('Program terminated.')
self.pos = float('inf')
def mark_label(self, label):
if label in self.labels:
raise ValueError('Label already exists')
self.labels[label] = self.pos + len(label)
print(f'\t{self.labels}')
def jump(self, label):
self.pos = self.labels[label]
def exit_subroutine(self):
if self.return_positions:
self.pos = self.return_positions.pop()
else:
raise SyntaxError('Return outside of subroutine')
def call_subroutine(self, label):
self.return_positions.append(self.pos)
self.pos = self.labels[label]
class Arithmetic:
"""Handles arithmetic operations on the stack."""
"""Instructions
[space][space]: Pop a and b, then push b+a.
[space][tab]: Pop a and b, then push b-a.
[space][line-feed]: Pop a and b, then push b*a.
[tab][space]: Pop a and b, then push b/a*. If a is zero, throw an error.
*Note that the result is defined as the floor of the quotient.
[tab][tab]: Pop a and b, then push b%a*. If a is zero, throw an error.
*Note that the result is defined as the remainder after division and sign (+/-) of the divisor (a).
"""
ARITHMETIC_IMP = {
' ': 'add',
' \t': 'sub',
' \n': 'mul',
'\t ': 'floordiv',
'\t\t': 'mod'
}
def parse(self):
"""Parses the next arithmetic IMP."""
Arithmetic = self.Arithmetic
self.get_command(Arithmetic.ARITHMETIC_IMP)
if self.loading:
return
if self.command == 'add':
print(f'\tCommand: {self.command}')
Arithmetic.add(self)
elif self.command == 'sub':
print(f'\tCommand: {self.command}')
Arithmetic.sub(self)
elif self.command == 'mul':
print(f'\tCommand: {self.command}')
Arithmetic.mul(self)
elif self.command == 'floordiv':
print(f'\tCommand: {self.command}')
Arithmetic.floordiv(self)
elif self.command == 'mod':
print(f'\tCommand: {self.command}')
Arithmetic.mod(self)
def add(self):
a, b = self.stack.pop(), self.stack.pop()
c = b + a
self.stack.append(c)
def sub(self):
a, b = self.stack.pop(), self.stack.pop()
c = b - a
self.stack.append(c)
def mul(self):
a, b = self.stack.pop(), self.stack.pop()
c = b * a
self.stack.append(c)
def floordiv(self):
a, b = self.stack.pop(), self.stack.pop()
if a == 0:
raise ZeroDivisionError('Cannot divide by zero')
c = b // a
self.stack.append(c)
def mod(self):
a, b = self.stack.pop(), self.stack.pop()
if a == 0:
raise ZeroDivisionError('Cannot divide by zero')
c = b % a
self.stack.append(c)
class Heap:
"""Handles operations on the heap."""
"""Instructions
[space]: Pop a and b, then store a at heap address b.
[tab]: Pop a and then push the value at heap address a onto the stack.
"""
HEAP_IMP = {
' ': 'store',
'\t': 'push'
}
def parse(self):
"""Parses the next heap IMP."""
Heap = self.Heap
self.get_command(Heap.HEAP_IMP)
if self.loading:
return
if self.command == 'store':
print(f'\tCommand: {self.command}')
Heap.store(self)
elif self.command == 'push':
print(f'\tCommand: {self.command}')
Heap.push(self)
def store(self):
a, b = self.stack.pop(), self.stack.pop()
self.heap[b] = a
def push(self):
a = self.stack.pop()
self.stack.append(self.heap[a])
def uncomment(s):
"""Removes extranneous characters from the code input."""
return ''.join(char for char in s if char in ' \t\n')
def whitespace(code, inp = ''):
code = uncomment(code)
interpreter = Interpreter(code, inp)
interpreter.run()
print(f'Output: {interpreter.output}')
return interpreter.output
def to_whitespace(s):
s = ''.join([char.lower() for char in s if char in 'STNstn'])
return s.replace('s',' ').replace('t','\t').replace('n','\n')
# Sample Code - Fibonacci Sequence
fibonacci_whitespace = """Ask the user how many
fibonacci numbers
they want from the sequence
and print
that many one number per line.
"""
whitespace(fibonacci_whitespace)