Skip to content

Instantly share code, notes, and snippets.

@LyricLy
Created July 26, 2020 09:13
Show Gist options
  • Save LyricLy/92489ddc0154d30a9a8811218709769b to your computer and use it in GitHub Desktop.
Save LyricLy/92489ddc0154d30a9a8811218709769b to your computer and use it in GitHub Desktop.
Convert Brainfuck code (bigints, unsigned, saturating when going below 0) to Rui code that runs in drui.c.
# Convert Brainfuck code written for saturating unsigned bigint cells into Rui code.
# Targets the Rui variant implemented by drui.c, using R and W for ASCII I/O.
import sys
import re
from textwrap import dedent as _
SIZE = 9999
program = [f""":7
={SIZE}
:3
=1
:5
=1~.$!
"""]
line = 7
with open(sys.argv[1]) as f:
code = f.read()
stack = []
i = 0
while i < len(code):
c = code[i]
i += 1
if c == "+":
# this is the only one of the repeated-instruction optimizations that is trivial; the commands - > < are more complex and much harder to optimize
e = 1
while code[i] == "+":
i += 1
e += 1
if e == 1:
program.append("+4.")
else:
program.append(f"={e}*4=0")
elif c == "-":
program.append("-1+6..*5=0")
elif c == ">":
program.append("-1*2=1~=0")
elif c == "<":
program.append(f"=1$-{SIZE}*4.")
elif c == ",":
program.append("-1R*4.")
elif c == ".":
program.append("-1W*4.")
elif c == "[":
if code[i:i+2] == "-]":
# clear loop
program.append("-1")
i += 2
else:
line += 1
program.append(_(f"""
-1*{line+1}*4=0:"""))
stack.append((line, len(program)))
program.append(None)
program.append(_("""
..-0"""))
line += 1
elif c == "]":
start, idx = stack.pop()
program.append(_(f""":{start}
"""))
line += 1
program[idx] = str(line)
program.append(f"={SIZE}~-0!")
with open(sys.argv[2], "w") as f:
f.write("".join(program))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment