Created
January 7, 2017 22:33
-
-
Save bcc32/43240f17f210c3128e29047e3feb5bdb to your computer and use it in GitHub Desktop.
Brainfuck-C transpiler in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What it does is it parses a brainfuck source file and it transpiles to C, correct? Similar to https://github.com/prophittcorey/bft then?