106 lines
2.6 KiB
Rust
106 lines
2.6 KiB
Rust
mod ast;
|
|
mod cg;
|
|
mod parse;
|
|
|
|
fn main() {
|
|
println!("Hello world! Please run cargo test.");
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn branch_test_inner(expected: i32, body: &str) {
|
|
let ast = parse::parse_branch(body);
|
|
println!("{:#?}", ast);
|
|
|
|
use wasm_encoder::{
|
|
CodeSection, ExportKind, ExportSection, FunctionSection, TypeSection, ValType,
|
|
};
|
|
|
|
let mut builder = cg::FunctionBuilder::new();
|
|
cg::codegen_branch(&mut builder, &ast);
|
|
let f = builder.finish();
|
|
|
|
let mut module = wasm_encoder::Module::new();
|
|
|
|
let mut types = TypeSection::new();
|
|
let params = vec![];
|
|
let results = vec![ValType::I32];
|
|
types.function(params, results);
|
|
module.section(&types);
|
|
|
|
let mut functions = FunctionSection::new();
|
|
functions.function(0);
|
|
module.section(&functions);
|
|
|
|
let mut exports = ExportSection::new();
|
|
exports.export("f", ExportKind::Func, 0);
|
|
module.section(&exports);
|
|
|
|
let mut codes = CodeSection::new();
|
|
codes.function(&f);
|
|
module.section(&codes);
|
|
|
|
let wasm_bytes = module.finish();
|
|
|
|
let wasm_text = wasmprinter::print_bytes(&wasm_bytes).unwrap();
|
|
println!("{}", wasm_text);
|
|
|
|
use wasmi::{Engine, Extern, Linker, Module, Store};
|
|
let engine = Engine::default();
|
|
let module = Module::new(&engine, &wasm_bytes[..]).unwrap();
|
|
let mut store = Store::new(&engine, ());
|
|
let mut linker = <Linker<()>>::new();
|
|
let instance_pre = linker.instantiate(&mut store, &module).unwrap();
|
|
let instance = instance_pre.start(&mut store).unwrap();
|
|
let f = instance
|
|
.get_export(&store, "f")
|
|
.and_then(Extern::into_func)
|
|
.unwrap()
|
|
.typed::<(), i32, _>(&mut store)
|
|
.unwrap();
|
|
|
|
let result = f.call(&mut store, ()).unwrap();
|
|
assert_eq!(result, expected);
|
|
}
|
|
|
|
macro_rules! branch_test {
|
|
($name: ident, $expected:expr, $body:expr) => {
|
|
#[test]
|
|
fn $name() {
|
|
let body = concat!("{", $body, "}");
|
|
branch_test_inner($expected, body);
|
|
}
|
|
};
|
|
}
|
|
|
|
branch_test!(add, 3, "1 + 2");
|
|
|
|
branch_test!(chained_add, 5, "1 + 1 + 1 + 1 + 1");
|
|
|
|
branch_test!(
|
|
vars,
|
|
5,
|
|
r#"
|
|
let a = 2;
|
|
let b = 3;
|
|
let c = a + b;
|
|
c
|
|
"#
|
|
);
|
|
|
|
branch_test!(
|
|
let_shadowing,
|
|
5,
|
|
r#"
|
|
let a = 1;
|
|
let a = 1 + a;
|
|
let a = 1 + a;
|
|
let a = 1 + a;
|
|
let a = 1 + a;
|
|
a
|
|
"#
|
|
);
|
|
}
|