Add more closure tests.

This commit is contained in:
Stephen Chung 2020-08-09 22:12:50 +08:00
parent dbf5cd13c8
commit 564d3bc339
2 changed files with 43 additions and 12 deletions

View File

@ -1639,7 +1639,8 @@ fn parse_primary(
// Function call // Function call
Token::Identifier(s) if *next_token == Token::LeftParen || *next_token == Token::Bang => { Token::Identifier(s) if *next_token == Token::LeftParen || *next_token == Token::Bang => {
// Once the identifier consumed we must enable next variables capturing // Once the identifier consumed we must enable next variables capturing
#[cfg(not(feature = "no_closure"))] { #[cfg(not(feature = "no_closure"))]
{
state.allow_capture = true; state.allow_capture = true;
} }
Expr::Variable(Box::new(((s, settings.pos), None, 0, None))) Expr::Variable(Box::new(((s, settings.pos), None, 0, None)))

View File

@ -89,6 +89,36 @@ fn test_closures() -> Result<(), Box<EvalAltResult>> {
42 42
); );
assert_eq!(
engine.eval::<INT>(
r#"
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)
"#
)?,
42
);
assert_eq!(
engine.eval::<INT>(
r#"
let a = 21;
let f = |x| a += x;
f.call(a);
a
"#
)?,
42
);
#[allow(deprecated)]
engine.register_raw_fn( engine.register_raw_fn(
"custom_call", "custom_call",
&[TypeId::of::<INT>(), TypeId::of::<FnPtr>()], &[TypeId::of::<INT>(), TypeId::of::<FnPtr>()],
@ -125,12 +155,12 @@ fn test_closures_data_race() -> Result<(), Box<EvalAltResult>> {
assert_eq!( assert_eq!(
engine.eval::<INT>( engine.eval::<INT>(
r#" r#"
let a = 1; let a = 1;
let b = 40; let b = 40;
let foo = |x| { this += a + x }; let foo = |x| { this += a + x };
b.call(foo, 1); b.call(foo, 1);
b b
"# "#
)?, )?,
42 42
); );
@ -139,11 +169,11 @@ fn test_closures_data_race() -> Result<(), Box<EvalAltResult>> {
*engine *engine
.eval::<INT>( .eval::<INT>(
r#" r#"
let a = 20; let a = 20;
let foo = |x| { this += a + x }; let foo = |x| { this += a + x };
a.call(foo, 1); a.call(foo, 1);
a a
"# "#
) )
.expect_err("should error"), .expect_err("should error"),
EvalAltResult::ErrorDataRace(_, _) EvalAltResult::ErrorDataRace(_, _)