#Wrote this to entertain myself, on a slow day at work. #Üstün Ergenoglu import sys class Instructions: SUBP = 0 INCP = 1 DECP = 2 INCV = 3 DECV = 4 OUTPUT = 5 INPUT = 6 RET = 7 class BFInterp: def __init__(self, text): self.programTree = list() self.__parse(text) def __parse(self, text): stack = list() stack.append(self.programTree) for c in text: if c == ">": stack[-1].append((Instructions.INCP, 0)) elif c == "<": stack[-1].append((Instructions.DECP, 0)) elif c == "+": stack[-1].append((Instructions.INCV, 0)) elif c == "-": stack[-1].append((Instructions.DECV, 0)) elif c == ".": stack[-1].append((Instructions.OUTPUT, 0)) elif c == ",": stack[-1].append((Instructions.INPUT, 0)) elif c == "[": newList = list() stack[-1].append((Instructions.SUBP, newList)) stack.append(newList) elif c == "]": stack[-1].append((Instructions.RET, 0)) stack.pop() def run(self): self.tape = [0] * (16 * 1024 * 1024) self.pointer = 0 self.__runList(self.programTree) def __runList(self, plist): pc = 0 while pc < len(plist): i = plist[pc] instr = i[0] param = i[1] if instr == Instructions.INCP: self.pointer += 1 elif instr == Instructions.DECP: self.pointer -= 1 elif instr == Instructions.INCV: self.tape[self.pointer] += 1 elif instr == Instructions.DECV: self.tape[self.pointer] -= 1 elif instr == Instructions.OUTPUT: print(chr(self.tape[self.pointer]), end="") elif instr == Instructions.INPUT: self.tape[self.pointer] = ord(sys.stdin.read(1)[0]) elif instr == Instructions.SUBP: if self.tape[self.pointer] != 0: self.__runList(param) elif instr == Instructions.RET: if self.tape[self.pointer] != 0: pc = 0 continue pc += 1 if __name__ == "__main__": if len(sys.argv) < 2: print("usage:", sys.argv[0], "") sys.exit(-1) sourcefilename = sys.argv[1] sourcefile = open(sourcefilename, "rt") programText = sourcefile.read() sourcefile.close() interp = BFInterp(programText) interp.run()