Skip to content

Instantly share code, notes, and snippets.

@rrthomas
Last active May 13, 2019 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrthomas/3f18eb8904ae35aaf28cf9fe5bfb6e57 to your computer and use it in GitHub Desktop.
Save rrthomas/3f18eb8904ae35aaf28cf9fe5bfb6e57 to your computer and use it in GitHub Desktop.
'''https://en.wikipedia.org/wiki/Brainfuck#Commands'''
import sys, mit
mit.State().globalize(globals())
def ass_inc(): ass(LIT_1); ass(ADD)
def ass_dec(): ass(LIT_1); ass(NEGATE); ass(ADD)
def ass_dup(): ass(LIT_0); ass(DUP);
def ass_over(): ass(LIT_1); ass(DUP);
def ass_loadb(): ass(LIT_0); ass(LOAD);
def ass_storeb(): ass(LIT_0); ass(STORE);
lit(0) # Data pointer.
stack = [] # [(start of loop, word to patch)]
for c in sys.stdin.read():
if c == '>': ass_inc()
elif c == '<': ass_dec()
elif c == '+': ass_dup(); ass_loadb(); ass_inc(); ass_over(); ass_storeb()
elif c == '-': ass_dup(); ass_loadb(); ass_dec(); ass_over(); ass_storeb()
elif c == '.':
ass_dup() # buffer
ass(LIT_1) # length
lit(LIB_C_STDOUT); ass_extra(LIB_C, type=BRANCH)
lit(LIB_C_WRITE); ass_extra(LIB_C, type=BRANCH)
ass(LIT_1); ass(POP);
elif c == ',':
ass_dup() # buffer
ass(LIT_1) # length
lit(LIB_C_STDIN); ass_extra(LIB_C, type=BRANCH)
lit(LIB_C_READ); ass_extra(LIB_C, type=BRANCH)
ass(LIT_1); ass(POP);
elif c == '[':
loop = label()
ass_dup()
ass_loadb()
lit(0xDEADBEEF)
patch = assembler.pc - mit.word_bytes
ass(BRANCHZ)
stack.append((loop, patch))
elif c == ']':
loop, patch = stack.pop()
lit(loop)
ass(BRANCH)
M_word[patch] = label()
ass_extra(EXTRA_HALT)
M_word[mit.word_bytes] = label() # Patch data pointer.
save(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment