aboutsummaryrefslogtreecommitdiffstats
path: root/bfparse.c
blob: b844013852cad505659475590fcb319f65ce926f (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * bfparse brainfuck to C parser. It is not memory safe. Use at your own risk.
 *
 * Copyright (C) 2014  Tomasz Kramkowski <tk@the-tk.com>
 *
 * This program is free software. It is licensed under version 3 of the
 * GNU General Public License.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see [http://www.gnu.org/licenses/].
 */

#include<stdio.h>

void auto_indent(int);

int main(void)
{
	int indent_level;
	int c;

	printf("#include<stdio.h>\n");
	printf("#include<stdlib.h>\n");
	printf("\n");
	printf("int main() {\n");
	printf("\tchar *ptrt;\n");
	printf("\tptrt = calloc(1000, sizeof(char));\n");
	printf("\tchar *ptr;\n");
	printf("\tptr = ptrt;\n");

	indent_level = 1;
	while ((c = getchar()) != EOF) {
		switch (c) {
		case '>':
			auto_indent(indent_level);
			printf("++ptr;\n");
			break;
		case '<':
			auto_indent(indent_level);
			printf("--ptr;\n");
			break;
		case '-':
			auto_indent(indent_level);
			printf("++*ptr;\n");
			break;
		case '+':
			auto_indent(indent_level);
			printf("--*ptr;\n");
			break;
		case '.':
			auto_indent(indent_level);
			printf("putchar(*ptr);\n");
			break;
		case ',':
			auto_indent(indent_level);
			printf("*ptr = getchar();\n");
			break;
		case '[':
			auto_indent(indent_level);
			indent_level++;
			printf("while (*ptr) {\n");
			break;
		case ']':
			indent_level--;
			auto_indent(indent_level);
			printf("}\n");
			break;
		}
	}
	printf("\tfree(ptrt);\n");
	printf("\tputchar('\\n');\n");
	printf("\treturn 0;\n}\n");
	if (--indent_level != 0)
		fprintf(stderr, "Error: Square bracket mismatch.\n");
	return 0;
}

inline void auto_indent(int levels)
{
	for (int i = 0; i < levels; i++)
		putchar('\t');
}