Created
March 7, 2024 21:59
-
-
Save umnikos/3452f6a1ead8144d684696b87cd0aa9e to your computer and use it in GitHub Desktop.
Fuckhard interpreter (Brainfuck derivative)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code = input("program: ") | |
data = [0] | |
ip = 0 | |
dp = 0 | |
input_buffer = "" | |
def error(msg): | |
raise Exception(msg) | |
while True: | |
if ip < 0 or ip >= len(code): | |
break | |
op = code[ip] | |
#print(op) | |
match op: | |
case '+': | |
data[dp] = 1 | |
ip += 1 | |
case '>': | |
dp += 1 | |
if dp >= len(data): | |
data.append(0) | |
ip += 1 | |
case '<': | |
dp = 0 | |
ip += 1 | |
case '(': | |
if data[dp] == 0: | |
ip += 1 | |
continue | |
depth = 1 | |
while depth > 0: | |
ip += 1 | |
if ip >= len(code): | |
# exited program, halt | |
break | |
if code[ip] == '(': | |
depth += 1 | |
elif code[ip] == ')': | |
depth -= 1 | |
case ']': | |
if data[dp] == 0: | |
ip += 1 | |
continue | |
depth = 1 | |
while depth > 0: | |
ip -= 1 | |
if ip < 0: | |
# exited program, halt | |
break | |
if code[ip] == ']': | |
depth += 1 | |
elif code[ip] == '[': | |
depth -= 1 | |
case ',': | |
while not input_buffer: | |
input_buffer = input('> ') | |
c = input_buffer[0] | |
input_buffer = input_buffer[1:] | |
match c: | |
case '1': | |
data[dp] = 1 | |
case '0': | |
pass | |
case _: | |
error("not a bit: "+c) | |
ip += 1 | |
case '.': | |
print(data[dp]) | |
ip += 1 | |
case _: | |
ip += 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment