Last active
December 15, 2024 19:31
-
-
Save shiracamus/ec4415114ffecf753a5e8cf4dba0659b to your computer and use it in GitHub Desktop.
Brainf*ck to Python transpiler
This file contains hidden or 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 | |
import sys | |
import argparse | |
TRANS = { | |
# op: (nest, python_code) | |
'>': (0, 'index += 1'), | |
'<': (0, 'index -= 1'), | |
'+': (0, 'memory[index] = (memory[index] + 1) & 0xff'), | |
'-': (0, 'memory[index] = (memory[index] - 1) & 0xff'), | |
'.': (0, 'sys.stdout.write(chr(memory[index]))'), | |
',': (0, 'memory[index] = ord(sys.stdin.read(1))'), | |
'[': (1, 'while memory[index]:'), | |
']': (-1, ''), | |
} | |
def transpile(bf, memory_kib=8): | |
"""brainf*ckコードbfをpythonに変換(メモリサイズはmemory_kibキビバイト)""" | |
yield 'import sys' | |
yield f'memory = [0] * {memory_kib} * 1024' | |
yield 'index = 0' | |
indent = 0 | |
for op in bf: | |
nest, py = TRANS.get(op, (0, '')) | |
if py: | |
yield ' ' * indent + py | |
indent += nest | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filename', help='input file name of brainf*ck source code') | |
parser.add_argument('-e', '--execute', help='execute code', action='store_true') | |
parser.add_argument('-m', '--memory', type=int, default=8, help='memory size in KiB') | |
args = parser.parse_args() | |
with open(args.filename) as f: | |
(exec if args.execute else print)('\n'.join(transpile(f.read(), args.memory))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment