Created
October 1, 2018 21:26
-
-
Save Isan-Rivkin/c9ee113602ada82e09a250dc8ac97293 to your computer and use it in GitHub Desktop.
Brain Fuck Compiler In Rust to C
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
#[derive(PartialEq,Debug,Clone, Copy)] | |
enum Token{ | |
Add, // + | |
Sub, // _ | |
Right, // > | |
Left, // < | |
Read, // , | |
Write, // . | |
BeginLoop, // [ | |
EndLoop, // ] | |
} | |
use self::Token::*; | |
fn tokenize(input : &str)->Vec<Token>{ | |
let mut tokens = Vec::<Token>::new(); | |
let mut chars = input.chars(); | |
while let Some(c) = chars.next() { | |
match c { | |
'+' => tokens.push(Add), | |
'-' => tokens.push(Sub), | |
'>' => tokens.push(Right), | |
'<' => tokens.push(Left), | |
',' => tokens.push(Read), | |
'.' => tokens.push(Write), | |
'[' => tokens.push(BeginLoop), | |
']' => tokens.push(EndLoop), | |
_ => {} | |
} | |
} | |
tokens | |
} | |
/// take tokens and generate a c source file | |
fn generate(tokens : &[Token]) -> String{ | |
let mut output = String::new();let mut output = String::from(include_str!("preface.c")); | |
for &token in tokens{ | |
match token{ | |
Add => { | |
// Increment the value at the selected cell | |
output.push_str("++*ptr;\n"); | |
}, | |
Sub => { | |
// Decrement the value at the selected cell | |
output.push_str("--*ptr;\n"); | |
}, | |
Right => { | |
// Change our selected cell to the next to the right | |
output.push_str("++ptr;\n"); | |
}, | |
Left => { | |
// Change our selected cell to the next to the left | |
output.push_str("--ptr;\n"); | |
}, | |
Read => { | |
// Read a single character into the selected cell | |
output.push_str("*ptr=getchar();\n"); | |
}, | |
Write => { | |
// Print the character at the selected cell | |
output.push_str("putchar(*ptr);\n"); | |
}, | |
BeginLoop => { | |
// Begin a loop at the current cell | |
output.push_str("while (*ptr) {\n"); | |
}, | |
EndLoop => { | |
// Close a loop | |
output.push_str("}\n"); | |
}, | |
}; | |
} | |
output | |
} | |
static PROGRAM: &'static str = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; | |
fn main() { | |
let p = "+-><,.[] > + - ABC , .. DE . F"; | |
let tokens = tokenize(PROGRAM); | |
println!("{:?}", tokens); | |
let generated_code = generate(&tokens); | |
println!("Generated code:\n{}", generated_code); | |
} |
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
#include stdio.h | |
int main() | |
{ | |
char tape[20000] = {0}; | |
char *ptr = tape; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment