Skip to content

Instantly share code, notes, and snippets.

@tcpj
Created June 7, 2016 13:57
Show Gist options
  • Save tcpj/30f0ea3930bc68977a45f0f9fcb16169 to your computer and use it in GitHub Desktop.
Save tcpj/30f0ea3930bc68977a45f0f9fcb16169 to your computer and use it in GitHub Desktop.
brainfuck interpreter
"""
Simple brainfuck interpreter
Copyright (c) <2016> <Jakub Dušek> [email protected]
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
def cleanup(source):
return [
tok for tok in source if tok in "><.,+-[]"
]
def exec(source):
code = cleanup(source)
stack = [0] * 400
loop_stack = []
cycle_count = 0
ptr = 0
addr = 0
stdout = ""
while ptr < len(code):
tok = code[ptr]
cycle_count += 1
if cycle_count > 8192:
return "Cycle count exceed"
if tok == "+":
stack[addr] += 1 if stack[addr] < 255 else -255
elif tok == "-":
stack[addr] -= 1 if stack[addr] > 0 else -255
elif tok == ">":
addr += 1 if addr < 399 else -399
elif tok == "<":
addr -= 1 if addr > 0 else -399
elif tok == "[" and ptr not in loop_stack:
loop_stack.append(ptr)
elif tok == "]":
if stack[addr] == 0:
loop_stack.pop()
if loop_stack:
ptr = loop_stack[-1] + 1
continue
elif tok == ".":
stdout += chr(stack[addr])
elif tok == ",":
stack[addr] = ord(input())
ptr += 1
return stdout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment