Skip to content

Instantly share code, notes, and snippets.

@bcc32
Created January 7, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcc32/43240f17f210c3128e29047e3feb5bdb to your computer and use it in GitHub Desktop.
Save bcc32/43240f17f210c3128e29047e3feb5bdb to your computer and use it in GitHub Desktop.
Brainfuck-C transpiler in Ruby
#!/usr/bin/env ruby -w
program = ARGF.read.tr('^[],.<>+-', '')
c_program = []
label_counter = -1
labels = []
program.each_char do |c|
c_program <<
case c
when '+'
' memory[index]++;'
when '-'
' memory[index]--;'
when '<'
' index--;'
when '>'
' index++;'
when ','
' memory[index] = fgetc(stdin);'
when '.'
' fputc(memory[index], stdout);'
when '['
label_counter += 1
labels << label_counter
<<~CODE
A#{label_counter}:
if (!memory[index])
goto B#{label_counter};
CODE
when ']'
label = labels.pop
<<~CODE
goto A#{label};
B#{label}:;
CODE
end
end
print <<~OUTPUT
#include <stdint.h>
#include <stdio.h>
#define MEMORY_SIZE (1<<16)
static uint16_t index;
static uint8_t memory[MEMORY_SIZE];
int main() {
#{c_program.join("\n")}
}
OUTPUT
@illtellyoulater
Copy link

illtellyoulater commented Apr 26, 2017

What it does is it parses a brainfuck source file and it transpiles to C, correct? Similar to https://github.com/prophittcorey/bft then?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment