-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainf_ck_compiler.py
52 lines (38 loc) · 1.27 KB
/
brainf_ck_compiler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import click
@click.command()
@click.argument('brainf_ck', type=click.File('r'))
@click.option('-o', nargs=1, type=click.File('w'))
def c_compiler(brainf_ck, o):
bfck_dict = {
">": "++ptr;\n",
"<": "--ptr;\n",
"+": "++(*ptr);\n",
"-": "--(*ptr);\n",
".": """printf("%c",(*ptr));\n""",
",": """scanf("%c",ptr);\n""",
"[": """while(*ptr) {\n""",
"]": "}\n",
}
c_init = """#include <stdio.h>
#include <stdlib.h>
int main(void) {
\tchar *tape = malloc(sizeof(char)*40000);
\tchar *ptr = &tape[0];
"""
number_indentations = 1
source = brainf_ck.read()
for data in source:
if data in bfck_dict:
if data == "[":
c_init = c_init + "\n" + ("\t" * number_indentations) + bfck_dict[data]
number_indentations = number_indentations + 1
elif data == "]":
number_indentations = number_indentations - 1
c_init = c_init + ("\t" * number_indentations) + bfck_dict[data] + "\n"
else:
c_init = c_init + ("\t" * number_indentations) + bfck_dict[data]
c_init = c_init + """\tprintf("\\n");\n\treturn 0;\n}"""
o.write(c_init)
o.flush()
if __name__ == "__main__":
op = c_compiler()