Created
August 27, 2018 02:58
-
-
Save victorazzam/9b07948678d59ba8637f5914967a26c5 to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in Python 3
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
#!/usr/bin/env python3 | |
import os, sys | |
if not sys.argv[1:]: | |
sys.exit("Usage: bfi.py file [input]") | |
if not os.path.isfile(sys.argv[1]): | |
sys.exit("File not found.") | |
# Interpret a bf program | |
with open(sys.argv[1]) as f: | |
bf = list(filter(lambda x: x in "+-><.,[]", f.read())) | |
# Input processing | |
userinput = sys.argv[2] if sys.argv[2:] else "" | |
pos = 0 # Instruction | |
array = {0:0} # Cells | |
current = 0 # Current cell, incremented with '>' and decremented with '<' | |
while pos < len(bf): | |
# Current instruction | |
inst = bf[pos] | |
# Increment pointer | |
if inst == "+": | |
if current not in array: | |
array[current] = 1 | |
else: | |
array[current] += 1 | |
array[current] %= 256 # Wrap around the ASCII table | |
# Decrement pointer | |
elif inst == "-": | |
if current not in array: | |
array[current] = -1 | |
else: | |
array[current] -= 1 | |
array[current] %= 256 # Wrap around the ASCII table | |
# Next cell | |
elif inst == ">": | |
current += 1 | |
if current not in array: | |
array[current] = 0 | |
# Previous cell | |
elif inst == "<": | |
current -= 1 | |
if current not in array: | |
array[current] = 0 | |
# Output ASCII character of cell value | |
elif inst == ".": | |
sys.stdout.write(chr(array[current])) | |
elif inst == "," and userinput: | |
array[current] = ord(userinput[0]) | |
userinput = userinput[1:] | |
# Start loop | |
elif inst == "[": | |
if array[current] == 0: | |
loops = 1 | |
while loops: | |
pos += 1 | |
if bf[pos] == "[": | |
loops += 1 | |
elif bf[pos] == "]": | |
loops -= 1 | |
# End loop | |
elif inst == "]": | |
loops = 1 | |
while loops: | |
pos -= 1 | |
if bf[pos] == "[": | |
loops -= 1 | |
elif bf[pos] == "]": | |
loops += 1 | |
pos -= 1 | |
pos += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment