Skip to content

Instantly share code, notes, and snippets.

@ronbeltran
Created December 31, 2020 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronbeltran/99576a5f536f4969ea90fb3c263585ed to your computer and use it in GitHub Desktop.
Save ronbeltran/99576a5f536f4969ea90fb3c263585ed to your computer and use it in GitHub Desktop.
Naive Brainfuck Interpreter
# https://en.wikipedia.org/wiki/Brainfuck
import sys
from typing import List
class BF:
def __init__(self, code: str) -> None:
self.memory: List[int] = [0] * 30000
self.code = code
self.ip: int = 0
self.dp: int = 0
def __readChar(self, c: str) -> None:
# print(f"readChar: {c}")
self.memory[self.dp] = ord(c[0])
def __putChar(self) -> None:
# print(f"putChar: {self.memory[self.dp]}")
print(chr(int(self.memory[self.dp])), end='')
def execute(self) -> None:
while self.ip < len(self.code):
ins = self.code[self.ip]
if ins == "+":
self.memory[self.dp] += 1
elif ins == "-":
self.memory[self.dp] -= 1
elif ins == ">":
self.dp += 1
elif ins == "<":
self.dp -= 1
elif ins == ",":
self.__readChar(ins)
elif ins == ".":
self.__putChar()
elif ins == "[":
if self.memory[self.dp] == 0:
depth = 1
while depth != 0:
self.ip += 1
if self.code[self.ip] == '[':
depth += 1
elif self.code[self.ip] == ']':
depth -= 1
elif ins == "]":
if self.memory[self.dp] != 0:
depth = 1
while depth != 0:
self.ip -= 1
if self.code[self.ip] == ']':
depth += 1
elif self.code[self.ip] == '[':
depth -= 1
self.ip += 1
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: python3 bf.py <filename>.b")
sys.exit()
code = None
with open(sys.argv[1]) as f:
code = f.read()
bf = BF(code)
bf.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment