Created
May 13, 2012 01:07
-
-
Save 7shi/2670049 to your computer and use it in GitHub Desktop.
[py]Brainf*ckでループのアンローリング
This file contains 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 python | |
import sys | |
mem = [0] * 30000 | |
ptr = 0 | |
def bfexec(src): | |
global mem, ptr | |
i = 0 | |
start = [] | |
while i < len(src): | |
cmd = src[i] | |
if cmd == '+': | |
mem[ptr] += 1 | |
f.write(" (*ptr)++;\n") | |
elif cmd == '-': | |
mem[ptr] -= 1 | |
f.write(" (*ptr)--;\n") | |
elif cmd == '>': | |
ptr += 1 | |
f.write(" ptr++;\n") | |
elif cmd == '<': | |
ptr -= 1 | |
f.write(" ptr--;\n") | |
elif cmd == '.': | |
sys.stdout.write(chr(mem[ptr])) | |
f.write(" putchar(*ptr);\n") | |
elif cmd == ',': | |
mem[ptr] = sys.stdin.read(1) | |
f.write(" *ptr = getchar();\n") | |
elif cmd == '[': | |
start.append(i) | |
if mem[ptr] == 0: | |
ind = 0 | |
while i < len(src): | |
cmd = src[i] | |
if cmd == '[': | |
ind += 1 | |
elif cmd == ']': | |
ind -= 1 | |
if ind == 0: break | |
i += 1 | |
if ind > 0: | |
print "block end required." | |
exit(1) | |
elif cmd == ']': | |
if len(start) == 0: | |
print "block start required." | |
exit(1) | |
i = start.pop() - 1 | |
i += 1 | |
if len(sys.argv) != 2: | |
print "usage: " + sys.argv[0] + " source.bf" | |
exit(1) | |
f = open(sys.argv[1], "r") | |
bf_src = f.read() | |
f.close() | |
f = open("bf.c", "w") | |
f.write("#include <stdio.h>\n") | |
f.write("char mem[30000];\n") | |
f.write("int main(void) {\n") | |
f.write(" char *ptr = mem;\n") | |
bfexec(bf_src) | |
f.write(" return 0;\n") | |
f.write("}\n") | |
f.close() |
This file contains 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
>++[<++>-] |
This file contains 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
#include <stdio.h> | |
char mem[30000]; | |
int main(void) { | |
char *ptr = mem; | |
ptr++; | |
(*ptr)++; | |
(*ptr)++; | |
ptr--; | |
(*ptr)++; | |
(*ptr)++; | |
ptr++; | |
(*ptr)--; | |
ptr--; | |
(*ptr)++; | |
(*ptr)++; | |
ptr++; | |
(*ptr)--; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment