#! /usr/bin/python ############################################################################# ## ## ## bfi.py --- BrainFuck interpreter ## ## ## ## Copyright (C) 2002 Philippe Biondi ## ## ## ## This program is free software; you can redistribute it and/or modify it ## ## under the terms of the GNU General Public License as published by the ## ## Free Software Foundation; either version 2, or (at your option) any ## ## later version. ## ## ## ## This program is distributed in the hope that it will be useful, but ## ## WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## ## General Public License for more details. ## ## ## ############################################################################# import sys,string,os f=open(sys.argv[1]); prog=string.join(f.readlines()) tape = [0] ip = 0 p = 0 level = 0 while 1: op = 1; x = prog[ip] ip += 1 if x == '+': tape[p] = (tape[p]+1)%256 elif x == '-': tape[p] = (tape[p]-1)%256 elif x == '>': p += 1 if len(tape) <= p: tape.append(0) elif x == '<': if p: p -= 1 else: debug("Warning: inserting one element at the begining\n"); tape.insert(0,0) elif x == '.': os.write(1,chr(tape[p]%256)) elif x == ',': tape[p] = ord(os.read(0,1)[0]) elif x == '[': if not tape[p]: while 1: if prog[ip] == '[': level += 1; if prog[ip] == ']': if level: level -= 1 else: break ip += 1 ip += 1 elif x == ']': ip -= 2; while 1: if prog[ip] == ']': level += 1 if prog[ip] == '[': if level: level -= 1 else: break ip -= 1 else: op = 0 if op: t2 = tape[:] t2[p] = "<%i>" % t2[p] os.write(2, "%s %s %i %s\n" % (x,t2.__repr__(),ip,prog[ip])) if ip >= len(prog): break;