-
Notifications
You must be signed in to change notification settings - Fork 0
/
ook.py
144 lines (105 loc) · 2.92 KB
/
ook.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
import os
import sys
def mainloop(tokens, bracket_map):
pc = 0
tape = Tape()
while pc < len(tokens):
token = tokens[pc]
if token == "Ook. Ook?":
tape.advance()
elif token == "Ook? Ook.":
tape.devance()
elif token == "Ook. Ook.":
tape.inc()
elif token == "Ook! Ook!":
tape.dec()
elif token == "Ook! Ook.":
# print
os.write(1, chr(tape.get()))
elif token == "Ook. Ook!":
# read from stdin
tape.set(ord(os.read(0, 1)[0]))
elif token == "Ook! Ook?" and tape.get() == 0:
# Skip forward to the matching ]
pc = bracket_map[pc]
elif token == "Ook? Ook!" and tape.get() != 0:
# Skip back to the matching [
pc = bracket_map[pc]
pc += 1
class Tape(object):
def __init__(self):
self.thetape = [0]
self.position = 0
def get(self):
return self.thetape[self.position]
def set(self, val):
self.thetape[self.position] = val
def inc(self):
self.thetape[self.position] += 1
def dec(self):
self.thetape[self.position] -= 1
def advance(self):
self.position += 1
if len(self.thetape) <= self.position:
self.thetape.append(0)
def devance(self):
self.position -= 1
def split(program):
tokens = []
fragments = program.split(" ")
length = len(fragments)
for i in range(0, length, 2):
tokens.append(fragments[i] + " " + fragments[i + 1])
return tokens
def parse(program):
tokens = split(program)
parsed = []
bracket_map = {}
leftstack = []
pc = 0
for token in tokens:
if token in (
"Ook! Ook?",
"Ook? Ook!",
"Ook? Ook.",
"Ook. Ook?",
"Ook. Ook.",
"Ook! Ook!",
"Ook. Ook!",
"Ook! Ook.",
):
parsed.append(token)
if token == "Ook! Ook?":
leftstack.append(pc)
elif token == "Ook? Ook!":
left = leftstack.pop()
right = pc
bracket_map[left] = right
bracket_map[right] = left
pc += 1
return parsed, bracket_map
def run(fp):
program_contents = ""
while True:
read = os.read(fp, 4096)
if len(read) == 0:
break
program_contents += read
os.close(fp)
tokens, bm = parse(program_contents)
mainloop(tokens, bm)
def entry_point(argv):
if len(argv) > 2:
print("Too many arguments.")
return 1
try:
filename = argv[1]
except IndexError:
print("You must supply a filename.")
return 1
run(os.open(filename, os.O_RDONLY, 0777))
return 0
def target(*args):
return entry_point, None
if __name__ == "__main__":
entry_point(sys.argv)