fast_brainfuck 0.0.3

A Brainfuck JIT compiler
#![feature(globs, phase, macro_rules, slicing_syntax)]
extern crate getopts;
#[phase(plugin, link)]
extern crate jit;

use getopts::*;
use jit::{Context, UncompiledFunction, Label, flags, get};
use std::cell::RefCell;
use std::iter::FilterMap;
use std::io;
use std::io::fs::File;
use std::mem;
use std::os;
use std::path::Path;
use std::rc::Rc;
use std::str::Chars;

macro_rules! count(
    ($func:ident, $code:ident, $curr:ident) => ({
        let mut amount = 1u;
        while $code.peek() == Some(&$curr) {
            amount += 1;
            $code.next();
        }
        $func.insn_of(&amount)
    })
)

static PROMPT:&'static str = "> ";
type WrappedLoop<'a> = Rc<RefCell<Loop<'a>>>;
struct Loop<'a> {
    start: Label<'a>,
    end: Label<'a>,
    parent: Option<WrappedLoop<'a>>
}
impl<'a> Loop<'a> {
    fn new(func: &UncompiledFunction<'a>, current_loop: Option<WrappedLoop<'a>>) -> Loop<'a> {
        let mut new_loop = Loop {
            start: Label::new(func),
            end: Label::new(func),
            parent: current_loop
        };
        func.insn_label(&mut new_loop.start);
        new_loop
    }
    fn end(&mut self, func: &UncompiledFunction<'a>) -> Option<WrappedLoop<'a>> {
        func.insn_branch(&mut self.start);
        func.insn_label(&mut self.end);
        let mut parent = None;
        mem::swap(&mut parent, &mut self.parent);
        parent
    }
}

#[deriving(Eq, PartialEq, Copy)]
#[repr(u8)]
pub enum Op {
    IncPointer,
    DecPointer,
    IncByte,
    DecByte,
    Output,
    Input,
    JumpAhead,
    JumpBack
}
impl Op {
    fn from_char(c: char) -> Option<Op> {
        match c {
            '>' => Some(Op::IncPointer),
            '<' => Some(Op::DecPointer),
            '+' => Some(Op::IncByte),
            '-' => Some(Op::DecByte),
            '.' => Some(Op::Output),
            ',' => Some(Op::Input),
            '[' => Some(Op::JumpAhead),
            ']' => Some(Op::JumpBack),
            _ => None
        }
    }
}

fn parse(code: &str) -> FilterMap<char, Op, Chars> {
    code.chars().filter_map(|c| Op::from_char(c))
}
fn compile<'a, T:Iterator<Op>>(func: &UncompiledFunction<'a>, code: T) {
    let ubyte = get::<u8>();
    let putchar_sig = get::<fn(u8)>();
    let readchar_sig = get::<fn() -> u8>();
    let ref data = func[0];
    let mut current_loop = None;
    let mut code = code.peekable();
    while let Some(c) = code.next() {
        match c {
            Op::IncPointer => {
                let ref amount = count!(func, code, c);
                jit!(func, data += amount);
            },
            Op::DecPointer => {
                let ref amount = count!(func, code, c);
                jit!(func, data -= amount)
            },
            Op::IncByte => {
                let ref amount = count!(func, code, c);
                let mut value = func.insn_load_relative(data, 0, ubyte.clone());
                value = func.insn_add(&value, amount);
                value = func.insn_convert(&value, ubyte.clone(), false);
                func.insn_store_relative(data, 0, &value)
            },
            Op::DecByte => {
                let ref amount = count!(func, code, c);
                let mut value = func.insn_load_relative(data, 0, ubyte.clone());
                value = func.insn_sub(&value, amount);
                value = func.insn_convert(&value, ubyte.clone(), false);
                func.insn_store_relative(data, 0, &value)
            },
            Op::Output => {
                fn putchar(c: u8) {
                    io::stdout().write_u8(c).unwrap();
                }
                let ref value = func.insn_load_relative(data, 0, ubyte.clone());
                func.insn_call_native1(Some("putchar"), putchar, putchar_sig.clone(), [value], flags::JIT_CALL_NO_THROW);
            },
            Op::Input => {
                fn readchar() -> u8 {
                    io::stdin().read_byte().unwrap()
                }
                let ref value = func.insn_call_native0(Some("readchar"), readchar, readchar_sig.clone(), flags::JIT_CALL_NO_THROW);
                func.insn_store_relative(data, 0, value);
            },
            Op::JumpAhead => {
                let wrapped_loop = Rc::new(RefCell::new(Loop::new(func, current_loop)));
                let ref tmp = func.insn_load_relative(data, 0, ubyte.clone());
                {
                    let mut borrow = wrapped_loop.borrow_mut();
                    func.insn_branch_if_not(tmp, &mut borrow.end);
                }
                current_loop = Some(wrapped_loop);
            },
            Op::JumpBack => {
                current_loop = match current_loop {
                    Some(ref inner_loop) => {
                        let mut borrow = inner_loop.borrow_mut();
                        borrow.end(func)
                    },
                    None => None
                }
            }
        }
    };
    func.insn_default_return();
}
fn run(code: &str) {
    let ref ctx = Context::new();
    ctx.build_func(get::<fn(*mut u8)>(), |func| compile(func, parse(code[]))).with(|func:extern fn(*mut u8)| {
        let mut data: [u8, ..3000] = unsafe { mem::zeroed() };
        func(data.as_mut_ptr());
    });
}
fn main() {
    let args = os::args();
    let opts = &[
        optopt("s", "script", "run a brainfuck script", "FILE"),
        optflag("i", "interactive", "run in interactive mode"),
        optflag("h", "help", "print this help menu")
    ];
    let matches = getopts(args.tail(), opts).unwrap();
    if matches.opt_present("i") {
        io::print(PROMPT);
        for line in io::stdin().lock().lines() {
            run(line.unwrap()[]);
            io::print(PROMPT);
        }
    } else if let Some(script) = matches.opt_str("s") {
        let ref script = Path::new(script[]);
        let contents = File::open(script).unwrap().read_to_string().unwrap();
        run(contents[]);
    } else {
        println!("{}", usage("", opts));
    }
}