rhai/tests/closures.rs

432 lines
9.4 KiB
Rust
Raw Permalink Normal View History

2020-07-29 16:43:57 +02:00
#![cfg(not(feature = "no_function"))]
use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, ParseErrorType, Scope, INT};
2020-07-31 07:08:14 +02:00
use std::any::TypeId;
use std::cell::RefCell;
use std::mem::take;
use std::rc::Rc;
2020-07-31 07:08:14 +02:00
2020-08-22 17:01:25 +02:00
#[cfg(not(feature = "no_object"))]
use rhai::Map;
2020-07-29 16:43:57 +02:00
#[test]
fn test_fn_ptr_curry_call() -> Result<(), Box<EvalAltResult>> {
2020-08-08 16:59:05 +02:00
let mut engine = Engine::new();
2020-07-29 16:43:57 +02:00
2020-08-08 16:59:05 +02:00
engine.register_raw_fn(
2020-07-29 16:43:57 +02:00
"call_with_arg",
2022-11-23 04:36:30 +01:00
[TypeId::of::<FnPtr>(), TypeId::of::<INT>()],
|context, args| {
2023-04-21 04:20:19 +02:00
let fn_ptr = args[0].take().cast::<FnPtr>();
fn_ptr.call_raw(&context, None, [args[1].take()])
2020-07-29 16:43:57 +02:00
},
);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-07-29 16:43:57 +02:00
let addition = |x, y| { x + y };
let curried = addition.curry(2);
call_with_arg(curried, 40)
2021-06-05 09:26:43 +02:00
"
2020-07-29 16:43:57 +02:00
)?,
42
);
Ok(())
}
#[test]
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
2020-07-29 16:43:57 +02:00
fn test_closures() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
let mut scope = Scope::new();
scope.push("x", 42 as INT);
2020-07-29 16:43:57 +02:00
assert!(matches!(
2023-04-10 17:23:59 +02:00
engine.compile_expression("|x| {}").unwrap_err().err_type(),
2022-02-08 02:46:14 +01:00
ParseErrorType::BadInput(..)
));
assert_eq!(
engine.eval_with_scope::<INT>(
&mut scope,
"
let f = || { x };
f.call()
",
)?,
42
);
2020-12-27 04:50:24 +01:00
assert_eq!(
engine.eval::<INT>(
2021-04-20 06:01:35 +02:00
"
2020-12-27 04:50:24 +01:00
let foo = #{ x: 42 };
let f = || { this.x };
foo.call(f)
2020-12-27 04:50:24 +01:00
",
)?,
42
);
2020-07-29 16:43:57 +02:00
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-07-29 16:43:57 +02:00
let x = 8;
let res = |y, z| {
let w = 12;
return (|| x + y + z + w).call();
}.curry(15).call(2);
res + (|| x - 3).call()
2021-06-05 09:26:43 +02:00
"
2020-07-29 16:43:57 +02:00
)?,
42
);
2020-08-03 06:10:20 +02:00
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
let a = 41;
let foo = |x| { a += x };
foo.call(1);
a
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
)?,
42
);
assert!(engine.eval::<bool>(
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
let a = 41;
let foo = |x| { a += x };
a.is_shared()
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
)?);
2021-03-01 15:44:56 +01:00
assert!(engine.eval::<bool>(
2021-06-05 09:26:43 +02:00
"
2021-03-01 15:44:56 +01:00
let a = 41;
let foo = |x| { a += x };
is_shared(a)
2021-06-05 09:26:43 +02:00
"
2021-03-01 15:44:56 +01:00
)?);
2020-08-08 16:59:05 +02:00
engine.register_fn("plus_one", |x: INT| x + 1);
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
let a = 41;
let f = || plus_one(a);
f.call()
2021-06-05 09:26:43 +02:00
"
)?,
42
);
2020-08-09 16:12:50 +02:00
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
let a = 40;
let f = |x| {
let f = |x| {
let f = |x| plus_one(a) + x;
f.call(x)
};
f.call(x)
};
f.call(1)
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
)?,
42
);
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
let a = 21;
let f = |x| a += x;
f.call(a);
a
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
)?,
42
);
engine.register_raw_fn(
"custom_call",
2022-11-23 04:36:30 +01:00
[TypeId::of::<INT>(), TypeId::of::<FnPtr>()],
|context, args| {
let func = take(args[1]).cast::<FnPtr>();
2021-11-29 05:43:59 +01:00
func.call_raw(&context, None, [])
},
);
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-09 13:55:01 +02:00
let a = 41;
let b = 0;
2020-08-09 13:55:01 +02:00
let f = || b.custom_call(|| a + 1);
f.call()
2021-06-05 09:26:43 +02:00
"
)?,
42
);
2020-08-03 06:10:20 +02:00
Ok(())
}
#[test]
#[cfg(not(feature = "no_closure"))]
fn test_closures_sharing() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("foo", |x: INT, s: &str| s.len() as INT + x);
engine.register_fn("bar", |x: INT, s: String| s.len() as INT + x);
assert_eq!(
engine.eval::<INT>(
r#"
let s = "hello";
let f = || s;
foo(1, s)
"#
)?,
6
);
assert_eq!(
engine.eval::<String>(
r#"
let s = "hello";
let f = || s;
let n = foo(1, s);
s
"#
)?,
"hello"
);
assert_eq!(
engine.eval::<INT>(
r#"
let s = "hello";
let f = || s;
bar(1, s)
"#
)?,
6
);
#[cfg(not(feature = "no_object"))]
{
let mut m = Map::new();
m.insert("hello".into(), "world".into());
let m = Dynamic::from(m).into_shared();
engine.register_fn("baz", move || m.clone());
assert!(!engine.eval::<bool>(
"
let m = baz();
m.is_shared()
"
)?);
assert_eq!(
engine.eval::<String>(
"
let m = baz();
m.hello
"
)?,
"world"
);
assert_eq!(engine.eval::<String>("baz().hello")?, "world");
}
Ok(())
}
2020-08-03 06:10:20 +02:00
#[test]
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "no_object"))]
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "sync"))]
2020-08-03 06:10:20 +02:00
fn test_closures_data_race() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
let a = 1;
let b = 40;
let foo = |x| { this += a + x };
b.call(foo, 1);
b
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
)?,
42
);
assert!(matches!(
*engine
.eval::<INT>(
2021-06-05 09:26:43 +02:00
"
2020-08-09 16:12:50 +02:00
let a = 20;
let foo = |x| { this += a + x };
a.call(foo, 1);
a
2021-06-05 09:26:43 +02:00
"
2020-08-03 06:10:20 +02:00
)
2023-04-10 17:23:59 +02:00
.unwrap_err(),
2022-02-08 02:02:15 +01:00
EvalAltResult::ErrorDataRace(..)
2020-08-03 06:10:20 +02:00
));
2020-07-29 16:43:57 +02:00
Ok(())
}
2020-12-16 07:57:28 +01:00
type TestStruct = Rc<RefCell<INT>>;
#[test]
#[cfg(not(feature = "no_object"))]
#[cfg(not(feature = "sync"))]
2020-08-23 10:29:15 +02:00
fn test_closures_shared_obj() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
2020-12-16 07:57:28 +01:00
// Register API on TestStruct
engine
2020-12-16 07:57:28 +01:00
.register_type_with_name::<TestStruct>("TestStruct")
.register_get_set(
"data",
2020-12-16 07:57:28 +01:00
|p: &mut TestStruct| *p.borrow(),
|p: &mut TestStruct, value: INT| *p.borrow_mut() = value,
)
2020-12-16 07:57:28 +01:00
.register_fn("+=", |p1: &mut TestStruct, p2: TestStruct| {
*p1.borrow_mut() += *p2.borrow()
})
2020-12-16 07:57:28 +01:00
.register_fn("-=", |p1: &mut TestStruct, p2: TestStruct| {
*p1.borrow_mut() -= *p2.borrow()
});
let engine = engine; // Make engine immutable
let code = r#"
#{
name: "A",
description: "B",
cost: 1,
health_added: 0,
action: |p1, p2| { p1 += p2 }
}
"#;
let ast = engine.compile(code)?;
let res = engine.eval_ast::<Map>(&ast)?;
// Make closure
2022-08-12 16:48:15 +02:00
let f = move |p1: TestStruct, p2: TestStruct| {
2021-03-30 12:57:16 +02:00
let action_ptr = res["action"].clone_cast::<FnPtr>();
let name = action_ptr.fn_name();
2020-12-26 06:05:57 +01:00
engine.call_fn(&mut Scope::new(), &ast, name, (p1, p2))
};
// Test closure
let p1 = Rc::new(RefCell::new(41));
let p2 = Rc::new(RefCell::new(1));
2022-11-23 04:36:30 +01:00
f(p1.clone(), p2)?;
assert_eq!(*p1.borrow(), 42);
Ok(())
}
2020-08-23 10:29:15 +02:00
#[test]
#[cfg(not(feature = "no_closure"))]
fn test_closures_external() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
let ast = engine.compile(
2020-08-23 10:29:15 +02:00
r#"
let test = "hello";
|x| test + x
2021-03-27 11:08:34 +01:00
"#,
2020-08-23 10:29:15 +02:00
)?;
let fn_ptr = engine.eval_ast::<FnPtr>(&ast)?;
2023-02-13 01:59:58 +01:00
let f = move |x: INT| fn_ptr.call::<String>(&engine, &ast, (x,));
2020-08-23 10:29:15 +02:00
2023-02-13 01:59:58 +01:00
assert_eq!(f(42)?, "hello42");
2020-08-23 10:29:15 +02:00
Ok(())
}
2022-09-10 07:37:33 +02:00
#[test]
#[cfg(not(feature = "no_closure"))]
2022-09-10 07:46:14 +02:00
#[cfg(not(feature = "sync"))]
2022-09-10 07:37:33 +02:00
fn test_closures_callback() -> Result<(), Box<EvalAltResult>> {
type SingleNode = Rc<dyn Node>;
trait Node {
2023-02-13 01:59:58 +01:00
fn run(&self, x: INT) -> Result<INT, Box<EvalAltResult>>;
2022-09-10 07:37:33 +02:00
}
struct PhaserNode {
2023-02-13 01:59:58 +01:00
func: Box<dyn Fn(INT) -> Result<INT, Box<EvalAltResult>>>,
2022-09-10 07:37:33 +02:00
}
impl Node for PhaserNode {
2023-02-13 01:59:58 +01:00
fn run(&self, x: INT) -> Result<INT, Box<EvalAltResult>> {
2022-09-10 07:37:33 +02:00
(self.func)(x)
}
}
2023-02-13 01:59:58 +01:00
fn phaser(callback: impl Fn(INT) -> Result<INT, Box<EvalAltResult>> + 'static) -> impl Node {
2022-09-10 07:37:33 +02:00
PhaserNode {
func: Box::new(callback),
}
}
let mut engine = Engine::new();
let ast = Rc::new(engine.compile(
"
const FACTOR = 2;
phaser(|x| x * FACTOR)
",
)?);
let shared_engine = Rc::new(RefCell::new(Engine::new_raw()));
let engine2 = shared_engine.clone();
let ast2 = ast.clone();
engine.register_fn("phaser", move |fp: FnPtr| {
let engine = engine2.clone();
let ast = ast2.clone();
2023-02-13 01:59:58 +01:00
let callback = Box::new(move |x: INT| fp.call(&engine.borrow(), &ast, (x,)));
2022-09-10 07:37:33 +02:00
Rc::new(phaser(callback)) as SingleNode
});
*shared_engine.borrow_mut() = engine;
let cb = shared_engine.borrow().eval_ast::<SingleNode>(&ast)?;
2023-02-13 01:59:58 +01:00
assert_eq!(cb.run(21)?, 42);
2022-09-10 07:37:33 +02:00
Ok(())
}