This commit is contained in:
Andreas Koepf 2025-01-30 22:55:04 +01:00
parent 21c47db6c1
commit ebb88e6c6a
24 changed files with 1215 additions and 814 deletions

View file

@ -1,7 +1,7 @@
#!/usr/bin/env python3
import sys
import argparse
import sys
def create_jumps_dictionary(program):
@ -9,9 +9,9 @@ def create_jumps_dictionary(program):
res = dict()
for index, command in enumerate(program):
if command == '[':
if command == "[":
lbraces.append(index)
elif command == ']':
elif command == "]":
if len(lbraces) == 0:
raise SyntaxError("Brainfuck: mismatched parentheses (at index: %s)" % index)
@ -35,26 +35,26 @@ def brainfuck(program, bits=8):
while instruction_pointer < len(program):
command = program[instruction_pointer]
if command == '>':
if command == ">":
data_pointer += 1
elif command == '<':
elif command == "<":
data_pointer -= 1
elif command == '+':
data[data_pointer] = (data.get(data_pointer, 0) + 1)
if data[data_pointer] == 2 ** bits:
elif command == "+":
data[data_pointer] = data.get(data_pointer, 0) + 1
if data[data_pointer] == 2**bits:
data[data_pointer] = 0
elif command == '-':
data[data_pointer] = (data.get(data_pointer, 0) - 1)
elif command == "-":
data[data_pointer] = data.get(data_pointer, 0) - 1
if data[data_pointer] == -1:
data[data_pointer] = 2 ** bits - 1
elif command == ',':
data[data_pointer] = 2**bits - 1
elif command == ",":
data[data_pointer] = ord(sys.stdin.read(1)) % 256
elif command == '.':
print(chr(data.get(data_pointer, 0)), end='', flush=True)
elif command == '[':
elif command == ".":
print(chr(data.get(data_pointer, 0)), end="", flush=True)
elif command == "[":
if data.get(data_pointer, 0) == 0:
instruction_pointer = jumps[instruction_pointer]
elif command == ']':
elif command == "]":
if data.get(data_pointer, 0) != 0:
instruction_pointer = jumps[instruction_pointer]
else: # everything else is comment
@ -63,16 +63,19 @@ def brainfuck(program, bits=8):
instruction_pointer += 1
if data_pointer != 0:
print("WARNING (interpreter) - at the end of the execution the data pointer is %s instead of 0 (possibly a compiler issue)" % str(data_pointer))
print(
"WARNING (interpreter) - at the end of the execution the data pointer is %s instead of 0 (possibly a compiler issue)"
% str(data_pointer)
)
if __name__ == '__main__':
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("filepath")
parser.add_argument("--bits", "-b", "--interpreter-bits", type=int, default=8, help="Amount of bits each cell uses")
args = parser.parse_args()
with open(args.filepath, 'r') as f:
with open(args.filepath, "r") as f:
code = f.read()
brainfuck(code, args.bits)