-
Notifications
You must be signed in to change notification settings - Fork 255
/
bf3.py
135 lines (105 loc) · 2.92 KB
/
bf3.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
import platform
import socket
import sys
import os
import itertools
from pathlib import Path
INC = 1
MOVE = 2
LOOP = 3
PRINT = 4
class Op(object):
def __init__(self, op, val):
self.op = op
self.val = val
class Tape(object):
def __init__(self):
self.tape = [0]
self.pos = 0
def get(self):
return self.tape[self.pos]
def inc(self, x):
self.tape[self.pos] += x
def move(self, x):
self.pos += x
while self.pos >= len(self.tape):
self.tape.extend(itertools.repeat(0, len(self.tape)))
class Printer(object):
def __init__(self, quiet):
self.sum1 = 0
self.sum2 = 0
self.quiet = quiet
def print(self, n):
if self.quiet:
self.sum1 = (self.sum1 + n) % 255
self.sum2 = (self.sum2 + self.sum1) % 255
else:
sys.stdout.write(chr(n))
sys.stdout.flush()
@property
def checksum(self):
return (self.sum2 << 8) | self.sum1
def parse(iterator):
res = []
while True:
try:
c = iterator.__next__()
except StopIteration:
break
if c == "+":
res.append(Op(INC, 1))
elif c == "-":
res.append(Op(INC, -1))
elif c == ">":
res.append(Op(MOVE, 1))
elif c == "<":
res.append(Op(MOVE, -1))
elif c == ".":
res.append(Op(PRINT, 0))
elif c == "[":
res.append(Op(LOOP, parse(iterator)))
elif c == "]":
break
return res
def _run(program, tape, p):
for op in program:
if op.op == INC:
tape.inc(op.val)
elif op.op == MOVE:
tape.move(op.val)
elif op.op == LOOP:
while tape.get() > 0:
_run(op.val, tape, p)
elif op.op == PRINT:
p.print(tape.get())
class Program(object):
def __init__(self, code):
self.ops = parse(iter(code))
def run(self, p):
_run(self.ops, Tape(), p)
def notify(msg):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if not s.connect_ex(("localhost", 9001)):
s.sendall(bytes(msg, "utf8"))
def verify():
text = """++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>
---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."""
p_left = Printer(True)
Program(text).run(p_left)
left = p_left.checksum
p_right = Printer(True)
for c in "Hello World!\n":
p_right.print(ord(c))
right = p_right.checksum
if left != right:
print("%s != %s" % (left, right), file=sys.stderr)
quit(1)
if __name__ == "__main__":
verify()
text = Path(sys.argv[1]).read_text()
p = Printer(os.getenv("QUIET"))
notify("%s\t%d" % (platform.python_implementation(), os.getpid()))
Program(text).run(p)
notify("stop")
if p.quiet:
print("Output checksum:", p.checksum)