-
Notifications
You must be signed in to change notification settings - Fork 0
/
bf.c
105 lines (69 loc) · 1.47 KB
/
bf.c
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define START "#include <stdio.h>\n#include <string.h>\n" \
"int main(){char buf[3000],*ptr=buf;memset(buf,0,sizeof(buf));"
#define FORW "ptr++;"
#define BACKW "ptr--;"
#define SUM "(*ptr)++;"
#define SUB "(*ptr)--;"
#define READ "*ptr=getchar();"
#define PUTC "putchar(*ptr);"
#define WRITEDR(d) fwrite(d, 1, strlen(d), o)
#define WHILE "while(*ptr){"
#define RET "return 0;"
#define ENDBLOCK "}"
void parse(const char *in, const char *out) {
FILE *i, *o = fopen(out, "w");
if ((i = fopen(in, "r")) == NULL) {
perror(in);
exit(1);
}
WRITEDR(START);
size_t forOpened = 0;
for (int ch; (ch = fgetc(i)) != EOF; ) {
switch (ch) {
case '>':
WRITEDR(FORW);
break;
case '<':
WRITEDR(BACKW);
break;
case '+':
WRITEDR(SUM);
break;
case '-':
WRITEDR(SUB);
break;
case ',':
WRITEDR(READ);
break;
case '.':
WRITEDR(PUTC);
break;
case '[':
WRITEDR(WHILE);
forOpened++;
break;
case ']':
WRITEDR(ENDBLOCK);
forOpened--;
}
}
if (forOpened > 0) {
fprintf(stderr, "Unexpected end of file, output file will be broken.\n");
} else {
WRITEDR(RET);
WRITEDR(ENDBLOCK);
}
fclose(i);
fclose(o);
}
int main(int argc, char * const argv[]) {
if (argc == 1) {
fprintf(stderr, "Invalid usage. Should be %s source.bf [output]\n", *argv);
return 1;
}
parse(argv[1], argc > 2 ? argv[2] : "out.c");
}