-
Notifications
You must be signed in to change notification settings - Fork 1
/
brainfuck
executable file
·84 lines (67 loc) · 1.92 KB
/
brainfuck
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
#!/usr/bin/env python
#
# rotsix - (c) wtfpl 2017
# minimal brainfuck interpreter
import sys
import getopt
def usage():
print("./brainfuck -f|--file <file>")
print("./brainfuck -e|--exp <expression>")
print("./brainfuck -h|--help")
def clean(code):
return filter(lambda x: x in ".,[]<>+-", code)
def bracemap(code):
stack, map = [], {}
for pos, cmd in enumerate(code):
if cmd == "[":
stack.append(pos)
if cmd == "]":
start = stack.pop()
map[start] = pos
map[pos] = start
return map
def trans(code):
code = list(clean(list(code)))
braces = bracemap(code)
cells, head, ptr = [0], 0, 0
while head < len(code):
cmd = code[head]
if cmd == ">":
ptr += 1
if ptr == len(cells):
cells.append(0)
elif cmd == "<":
ptr = ptr - 1 if ptr > 0 else 0
elif cmd == "+":
cells[ptr] = cells[ptr] + 1 if cells[ptr] < 255 else 0
elif cmd == "-":
cells[ptr] = cells[ptr] - 1 if cells[ptr] > 0 else 255
elif cmd == "[" and cells[ptr] == 0:
head = braces[head]
elif cmd == "]" and cells[ptr] != 0:
head = braces[head]
elif cmd == ".":
sys.stdout.write(chr(cells[ptr]))
elif cmd == ",":
# TODO
a = 0
head += 1
def main(args):
try:
opts, args = getopt.getopt(args, "f:e:h", ["file", "exp", "help"])
except getopt.GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit(0)
elif opt in ("-f", "--file"):
with open(arg, "r") as file:
trans(file.read())
sys.exit(0)
elif opt in ("-e", "--exp"):
trans(arg)
sys.exit(0)
if __name__ == "__main__":
main(sys.argv[1:])