2023-10-02 00:50:50 +00:00
|
|
|
use lunar_wave_vm as lwvm;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn embedding () {
|
|
|
|
use lwvm::{
|
|
|
|
State,
|
|
|
|
Value,
|
|
|
|
};
|
|
|
|
|
|
|
|
let src = br#"
|
|
|
|
return host_lib.add (14, 12)
|
|
|
|
"#;
|
|
|
|
|
|
|
|
fn host_add (l: &mut State, num_args: usize) -> usize {
|
|
|
|
assert_eq! (num_args, 2);
|
|
|
|
let a = l.reg (0).as_int ().unwrap ();
|
|
|
|
let b = l.reg (1).as_int ().unwrap ();
|
|
|
|
*l.reg_mut (0) = Value::from (a + b + 1993);
|
|
|
|
1
|
|
|
|
}
|
|
|
|
|
2023-10-02 02:26:47 +00:00
|
|
|
let bytecode = lwvm::compile_bytecode (src.to_vec ());
|
2023-10-02 00:50:50 +00:00
|
|
|
let mut rdr = std::io::Cursor::new (bytecode);
|
|
|
|
let chunk = lwvm::parse_chunk (&mut rdr).unwrap ();
|
|
|
|
|
|
|
|
let host_lib = [
|
|
|
|
("add", Value::RsFunc (host_add)),
|
|
|
|
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
|
|
|
|
|
|
|
let env = [
|
|
|
|
("host_lib", Value::from_iter (host_lib.into_iter ())),
|
|
|
|
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
|
|
|
|
|
|
|
let upvalues = vec! [
|
|
|
|
Value::from_iter (env.into_iter ()),
|
|
|
|
];
|
|
|
|
|
2023-10-02 01:31:30 +00:00
|
|
|
let mut vm = State::new (chunk, upvalues);
|
2023-10-02 00:50:50 +00:00
|
|
|
let output = vm.execute_chunk (&vec! []).unwrap ();
|
|
|
|
|
|
|
|
assert_eq! (output, vec! [Value::from (2019)]);
|
|
|
|
}
|