1use super::context::Context;
4use super::trap::Trap;
5use alloc::boxed::Box;
6
7pub type Func<'a> = Box<dyn Callable + 'a>;
9
10pub trait Callable {
12 fn call(&self, ctx: &mut Context) -> Result<(), Trap>;
13}
14
15#[cfg(test)]
16pub(crate) mod tests {
17 use super::*;
18 use alloc::string::ToString;
19
20 pub struct Add(pub &'static str, pub &'static str);
21
22 impl Callable for Add {
23 fn call(&self, ctx: &mut Context) -> Result<(), Trap> {
24 let a = *ctx
25 .get_global::<_, i32>(self.0)?
26 .ok_or_else(|| Trap::MissingGlobal(self.0.to_string()))?;
27 let b = *ctx
28 .get_global::<_, i32>(self.1)?
29 .ok_or_else(|| Trap::MissingGlobal(self.1.to_string()))?;
30 ctx.set_global::<_, i32>("c", a + b);
31 Ok(())
32 }
33 }
34
35 #[test]
36 fn add() {
37 let mut ctx = Context::new();
38 ctx.set_global::<_, i32>("a", 1);
39 ctx.set_global::<_, i32>("b", 2);
40 Add("a", "b").call(&mut ctx).unwrap();
41 assert_eq!(ctx.get_global::<_, i32>("c").unwrap(), Some(&3));
42 }
43}