Created
December 31, 2020 04:18
-
-
Save ronbeltran/99576a5f536f4969ea90fb3c263585ed to your computer and use it in GitHub Desktop.
Naive Brainfuck Interpreter
This file contains hidden or 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
# 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