In the tried and true tradition of building esoteric things to deal with
brainfuck, nelhage nerdsniped me into writing a brainfuck compiler
in rust.
I’m gunna gloss over tons of stuff, and only write about the interesting parts.
I’m also not going to actually walk through the code as I wrote it because it
was and is incredibly sketchy, but it’s better seperated now so we’re going to
look at master (at time of writing).
Writing a parser
Rust makes this comically simple.
We define a recursive enum containing all the opcodes, and a Vec to hold the
contents of any loops:
#[deriving(Show)] pub enum OpCode {
Lshift,
Rshift,
Putc,
Getc,
Inc,
Dec,
Loop(Vec<OpCode>),
}
By deriving Show
we’ll be able to use format!
, println!
and friends at
various points of debugging and get something plausible ish.
Our actual parser is just about as simple. I won’t inline the
code, but it should read pretty simply.
We create a mutable vec to hold our actual program, and a loop_stack to hold
the contents of each nested loop, inserting those loops into it’s parent each
time we enounter a closing bracket. This also makes it simple to test for
unbalanced brackets.
This then lets us return the Program. Using Option
was left as an escape
hatch (unbalanced braces could be caught, as could the file errors, but for now
failing is reasonable since it’s not exactly “production ready”).
Next time, the evaluator.