-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterpreter.py
76 lines (72 loc) · 2.11 KB
/
Interpreter.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
from Stack import Stack
import re
'''Replace nilads with single character commands'''
def atomize(snippet):
for nilad,atom in zip(["()","{}","<>","[]"],"ABCD"):
snippet = snippet.replace(nilad,atom)
return snippet
'''Interpreter object'''
class Interpreter(object):
def __init__(self,source):
self.pointer = [0]
self.stacks = (Stack(),Stack())
self.scope = []
self.source = [atomize(source)]
self.functions = [atomize(source)]
def insert(self,array):
self.stacks[0].extend(array)
def perform(self,action):
if action == "{":
#We will parse until the end of the current brace
stack = ["{"]
matches = ["{}","()","[]","<>"]
start = self.pointer[-1]+1
while stack:
self.pointer[-1] += 1
if stack[-1]+self.source[-1][self.pointer[-1]] in matches:
stack.pop()
elif self.source[-1][self.pointer[-1]] in "".join(matches):
stack.append(self.source[-1][self.pointer[-1]])
self.functions.append(self.source[-1][start:self.pointer[-1]])
self.pointer[-1]+=1
elif action in "([<":
self.scope.append([action,self.pointer[-1],0])
self.pointer[-1] += 1
elif action == ")":
value = self.scope.pop()[-1]
self.stacks[0].append(value)
if self.scope:
self.scope[-1][-1]+=value
self.pointer[-1] += 1
elif action == "]":
value = self.scope.pop()[-1]
if self.scope:
self.scope[-1][-1]-=value
self.pointer[-1] += 1
elif action == ">":
value = self.scope.pop()[-1]
self.pointer[-1] += 1
self.source.append(self.functions[value])
self.pointer.append(0)
elif action == "A":
if self.scope:
self.scope[-1][-1]+=1
self.pointer[-1] += 1
elif action == "B":
if self.scope:
self.scope[-1][-1]+=self.stacks[0].pop()
self.pointer[-1] += 1
elif action == "C":
self.stacks = self.stacks[::-1]
self.pointer[-1] += 1
elif action == "D":
if self.scope:
self.scope[-1][-1]+=len(self.stacks[0])
self.pointer[-1] += 1
#Remove spent fucntions
while self.source and self.pointer[-1] >= len(self.source[-1]):
self.source.pop()
self.pointer.pop()
def run(self):
while self.source:
self.perform(self.source[-1][self.pointer[-1]])