-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrainfInterpreter.py
More file actions
149 lines (138 loc) · 5.27 KB
/
brainfInterpreter.py
File metadata and controls
149 lines (138 loc) · 5.27 KB
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
import colorama
def run(program) -> None:
"""runs a program"""
program = "".join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'],program)) #deal with disallowed characters before running for speed improvements
for line in _iterRunner(program):
pass
def _iterRunner(program,position=0,variables=[0],pointer=0) -> tuple:
"""
Runs brainfuck code as an iterable
Keyword arguments
-----------------
program : iterable
The program to run
position : int
The position to start at (default 0)
variables : list or other mutable iterable
Mutable list of variables to start the program with (default [0])
pointer : int
Pointer position to start at (default 0)
Yield
------
yields a tuple containing
position : int
current position
variables : list
current variables (can be other mutable iterable it's the same one given as argument)
pointer : int
current position in variables
"""
variables = [0]
while position < len(program):
match program[position]:
case ">":
pointer += 1
if len(variables) <= pointer:
variables.append(0)
case "<":
if pointer > 0:
pointer -= 1
else:
raise ValueError("Invalid pointer. you were at 0 and moved to the left")
case "+":
variables[pointer] += 1
case "-":
variables[pointer] -= 1
case ".":
print(chr(variables[pointer]),end="")
case ",":
variables[pointer] = ord((input("")+"\x00")[0])
case "[":
if variables[pointer]==0:
brackets = 1 #find matching close
for i in range(position+1,len(program)):
match program[i]:
case "[":
brackets+=1
case "]":
brackets-=1
if brackets==0:
position=i
break
else:
raise ValueError(f"never found a ] at position {position}")
case "]":
brackets = 1 #find matching open
for i in range(1,position+1):
match program[position-i]:
case "[":
brackets-=1
case "]":
brackets+=1
if brackets==0:
position=position-i-1
break
else:
raise ValueError(f"never found a [ at position {position}")
position+=1
yield (position,variables,pointer)
def _printMem(mem,pointer):
"""prints memory with highlighting on pointer position"""
print("[",end="")
for i in mem[:pointer]:
print(f"{i}, ",end="")
print(f"{colorama.Back.YELLOW}{colorama.Fore.BLACK}{mem[pointer]}{colorama.Style.RESET_ALL}",end="")
if pointer == len(mem)-1:
print("]")
return
print(", ",end="")
for i in mem[pointer+1:-1]:
print(f"{i}, ",end="")
print(mem[-1],"]")
def debug(program):
"""debug a program
debug points should be marked with ! exclamation marks"""
program = "".join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-', '!'],program)) #deal with disallowed characters
running = True
if "!" not in program:
running = False
program = " "+program
lastCommand = None
for line in _iterRunner(program):
if running:
if line[0]>=len(program):
return
if program[line[0]]=="!":
running = False
print(f"stopped at command #{line[0]}")
else:
continue
if line[0]>=len(program):
return
print("\n\nmemory: ",end="")
_printMem(line[1],line[2])
print(program[(line[0]-20) if line[0]>20 else 0:line[0]]+colorama.Back.YELLOW+colorama.Fore.BLACK+program[line[0]]+colorama.Style.RESET_ALL+program[line[0]+1:line[0]+20])
command=input(": ")
while True:
match command:
case "n":
break
case "c":
running= True
break
case "q":
return
case "":
if lastCommand:
command = lastCommand
else:
print("command wasn't passed")
command=input(": ")
case _:
print("command wasn't passed")
command=input(": ")
lastCommand=command
if __name__ == "__main__":
run("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")
print()
debug("++++++++[>++++[>++>+++<<-]>+>+[<]<-]>>.>+.")