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

View File

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