-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.py
176 lines (130 loc) · 4.82 KB
/
brainfuck.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
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
from os import name as osname, path
from sys import argv, stdin, stdout
import readline
class _Getch:
def __init__(self) -> None:
if osname == "posix":
self.ch = _GetchUnix()
elif osname == "nt":
self.ch = _GetchWin()
def __call__(self): return self.ch()
class _GetchUnix:
def __init__(self):
pass
def __call__(self):
import tty,termios
fd = stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(stdin.fileno())
char = stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return char
class _GetchWin:
def __init__(self) -> None:
pass
def __call__(self):
import msvcrt
return msvcrt.getch()
def read(filename):
if path.isfile(filename):
f = open(filename, 'r')
interpreter(f.read())
f.close
else:
interpreter(filename)
def clean(code):
return ''.join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))
def buildbracemap(code):
temp, bracemap = [], {}
for pos, char in enumerate(code):
if char == '[': temp.append(pos)
if char == ']':
if not temp:
print("Error: Mismatched brackets at position", pos)
return {}
start = temp.pop()
bracemap[start] = pos
bracemap[pos] = start
if temp:
print("Error: Unclosed brackets at positions", temp)
return {}
return bracemap
def interpreter(code):
code = clean(list(code))
bracemap = buildbracemap(code)
getch = _Getch()
cells, ptr, cellptr = [0], 0, 0
while ptr < len(code):
command = code[ptr]
if command == '>':
cellptr += 1
if cellptr == len(cells): cells.append(0)
elif command == '<':
cellptr = 0 if cellptr <= 0 else cellptr - 1
if command == "+":
# cells[cellptr] = cells[cellptr] + 1 if cells[cellptr] < 255 else 0
cells[cellptr] = (cells[cellptr] + 1) % 256 # Use modulo to wrap around
if command == "-":
# cells[cellptr] = cells[cellptr] - 1 if cells[cellptr] > 0 else 255
cells[cellptr] = (cells[cellptr] - 1) % 256 # Use modulo to wrap around
if command == "[" and cells[cellptr] == 0: ptr = bracemap[ptr]
if command == "]" and cells[cellptr] != 0: ptr = bracemap[ptr]
if command == ".": stdout.write(chr(cells[cellptr]))
if command == ",": cells[cellptr] = ord(getch())
ptr += 1
def usage():
error_message = f"Error: Invalid command line arguments \n" \
f"Usage: {argv[0]} com <filename> \n" \
f" brainfuck.py -> Run in interpreter mode\n" \
f" brainfuck.py com <filename> -> Interpret code from file\n" \
print(error_message)
exit(1)
def main():
if len(argv) == 1:
try:
readline.read_history_file('history.txt')
except FileNotFoundError:
pass # Ignore if there's no history file yet
readline.set_history_length(1000) # Adjust the number of history entries to keep
count = 0
while True:
try:
command = input("bf [%s] # " % count)
if command.lower() == "exit" or command.lower() == "quit":
exit()
elif command.lower() == "help":
print("\nBrainfuck Live Interpreter")
print("Commands:")
print(" - Type 'exit' or 'quit' or 'Ctrl-D'to quit.")
print(" - Type 'help' for this help message.")
print(" - Enter Brainfuck code to interpret.")
print("Here is and Hello World! example")
print("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.")
print("Just copy and paste")
print()
else:
read(command)
count += 1
except (KeyboardInterrupt) or (EOFError) as e:
print("KeyboardInterrupt %s" % e)
print("- Use exit or quit")
continue
elif len(argv) == 2 and argv[1] == "com":
print("Missing file for interpretation")
exit(1)
elif len(argv) == 3 and argv[1] == "com":
if path.isfile(argv[2]):
read(argv[2])
else:
print("can't open file: '%s' " % path.abspath(argv[2]))
print("No such file or directory '%s'" % argv[2])
else:
usage()
readline.write_history_file('.history.txt')
if __name__ == "__main__":
try:
main()
except EOFError:
exit()