Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active July 31, 2019 16:47
Show Gist options
  • Save pedrominicz/f5180e2d18965c4162c1ebab2d8acfd4 to your computer and use it in GitHub Desktop.
Save pedrominicz/f5180e2d18965c4162c1ebab2d8acfd4 to your computer and use it in GitHub Desktop.
Brainfuck to C compiler.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
void die(const char* msg) {
puts(msg);
exit(1);
}
void cp(FILE* a, FILE* b) {
int c;
while((c = fgetc(a)) != EOF)
fputc(c, b);
}
void compile(FILE* in, FILE* out) {
int c;
int nest = 0;
fputs("void run(void) {", out);
while((c = fgetc(in)) != EOF) {
switch(c) {
case '>': fputs("i = (i + 1) % SIZE;", out); break;
case '<': fputs("i = (i - 1) % SIZE;", out); break;
case '+': fputs("++a[i];", out); break;
case '-': fputs("--a[i];", out); break;
case '.': fputs("putchar(a[i]);", out); break;
case ',': fputs("a[i] = getchar();", out); break;
case '[':
fputs("while(a[i]) {", out);
++nest;
break;
case ']':
fputs("}", out);
if(--nest < 0) die("unbalanced square brackets");
break;
default: continue;
}
fputc('\n', out);
}
if(nest != 0) die("unbalanced square brackets");
fputs("}", out);
}
int main(int argc, char** argv) {
if(argc != 2)
die("provide exactly one argument (the file to compile)");
FILE* in = fopen(argv[1], "r");
if(!in) die("cannot open file");
FILE* out = fopen("out.c", "w");
if(!out) die("cannot open file: out.c");
FILE* template = fopen("template.c", "r");
if(!template) die("cannot open file: template.c");
cp(template, out);
fclose(template);
compile(in, out);
fclose(in);
fclose(out);
return 0;
}
#!/bin/sh
# ./run <(echo ',+[-.,+]')
gcc -pedantic -Wall -Wextra -Werror bf.c || exit
./a.out $1 || exit
gcc -pedantic -Wall -Wextra -Werror -o out out.c || exit
./out
rm -f a.out out out.c
#include <stddef.h>
#include <stdio.h>
#define SIZE 0x10000
char a[SIZE];
size_t i = 0;
void run(void);
int main(void) {
run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment