Created
January 4, 2017 13:32
-
-
Save emdete/b6eb64cab24a589db123d278b8d13ed9 to your computer and use it in GitHub Desktop.
brainfuck implementation in python with debugging
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 | |
DEBUG = True | |
def debug(ip, program, dp, tape, stack): | |
global DEBUG | |
if DEBUG: | |
print(program) | |
print('{}{}{}'.format(' ' * ip, '^', ip)) | |
for n, d in enumerate(tape): | |
if n == dp: | |
print('<{}>'.format(d), '', end='') | |
else: | |
print(d, '', end='') | |
print() | |
if input('q to quit debugging:') == 'q': | |
DEBUG = False | |
def main(program): | |
stack = list() | |
ip = 0 | |
dp = 0 | |
tape = [0, ] | |
while ip < len(program): | |
debug(ip, program, dp, tape, stack) | |
c = program[ip] | |
if c == '>': | |
dp += 1 | |
if dp >= len(tape): | |
tape.append(0) | |
elif c == '<': | |
if dp: | |
dp -= 1 | |
if not tape[-1]: | |
del tape[-1] | |
else: | |
print('warning: move pointer before tape') | |
elif c == '+': | |
tape[dp] += 1 | |
elif c == '-': | |
tape[dp] -= 1 | |
elif c == '.': | |
print(chr(tape[dp]), end='') | |
elif c == ',': | |
pass | |
elif c == '[': | |
if tape[dp]: | |
stack.append(ip) | |
else: | |
cnt = 1 | |
while cnt: | |
ip += 1 | |
if program[ip] == '[': | |
cnt += 1 | |
elif program[ip] == ']': | |
cnt -= 1 | |
elif c == ']': | |
if stack: | |
if tape[dp]: | |
ip = stack[-1] | |
else: | |
stack.pop() | |
else: | |
print('warning: to many ]') | |
ip += 1 | |
return tape[dp] | |
main('++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.+++.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment