Created
July 29, 2012 20:19
-
-
Save flags/3201641 to your computer and use it in GitHub Desktop.
Brainfuck interpreter that isn't complete garbage and does not abuse OOP like every other version I found online
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
#flags - 2012 | |
#wtfplv2 | |
import sys | |
if not len(sys.argv)==2: | |
print 'Usage: brainfuck.py <file>' | |
sys.exit(1) | |
PROGRAM = bytearray(9999) | |
CELL = 0 | |
LOOPS = [] | |
LOOP = -1 | |
INDEX = 0 | |
def compile(instructions): | |
global PROGRAM,CELL,LOOPS,LOOP,INDEX | |
_buffer = '' | |
END_INDEX = len(instructions) | |
while INDEX<=END_INDEX: | |
if INDEX == END_INDEX: | |
if INDEX >= len(instructions): | |
break | |
END_INDEX = len(instructions) | |
char = instructions[INDEX] | |
if char=='+': | |
PROGRAM[CELL]+=1 | |
elif char=='-': | |
PROGRAM[CELL]-=1 | |
elif char=='>': | |
CELL+=1 | |
elif char=='<': | |
CELL-=1 | |
elif char=='.': | |
_buffer+=str(chr(PROGRAM[CELL])) | |
elif char==',': | |
print '# ', | |
PROGRAM[CELL] = ord(raw_input()) | |
elif char=='[': | |
LOOP+=1 | |
LOOPS.append({'start':INDEX,'end':-1}) | |
elif char==']': | |
if LOOP>-1: | |
_loop = '' | |
LOOPS[LOOP]['end'] = INDEX | |
if PROGRAM[CELL]: | |
INDEX = LOOPS[LOOP]['start']-1 | |
END_INDEX = LOOPS[LOOP]['end'] | |
LOOPS.pop(LOOP) | |
LOOP-=1 | |
else: | |
raise Exception('Brace mismatch. No open loops.') | |
INDEX+=1 | |
return _buffer | |
with open(sys.argv[1],'r') as _source: | |
_instructions = '' | |
for line in _source.readlines(): | |
for char in line: | |
if char in ['+','-','<','>','[',']','.',',']: | |
_instructions+=char | |
print compile(_instructions), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment