From 45d021c7efa7ae90ba26d1b83923919903a52400 Mon Sep 17 00:00:00 2001 From: Ilya Lakhin Date: Sat, 8 Aug 2020 17:55:58 +0700 Subject: [PATCH 1/2] Function names capturing as external variables bug --- src/parser.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/parser.rs b/src/parser.rs index 8b3bf3ea..8c9c2940 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1635,6 +1635,11 @@ fn parse_primary( Token::CharConstant(c) => Expr::CharConstant(Box::new((c, settings.pos))), Token::StringConstant(s) => Expr::StringConstant(Box::new((s.into(), settings.pos))), Token::Identifier(s) => { + // prevents capturing of the function call + #[cfg(not(feature = "no_closure"))] + if *next_token == Token::LeftParen || *next_token == Token::Bang { + state.allow_capture = false; + } let index = state.access_var(&s, settings.pos); Expr::Variable(Box::new(((s, settings.pos), None, 0, index))) } From 9c6584240f32c3d4c3574cf89754fca008148895 Mon Sep 17 00:00:00 2001 From: Ilya Lakhin Date: Sat, 8 Aug 2020 19:09:18 +0700 Subject: [PATCH 2/2] Unit test for registered functions in anon function context --- tests/closures.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/tests/closures.rs b/tests/closures.rs index 3fc1cbd5..bbc91653 100644 --- a/tests/closures.rs +++ b/tests/closures.rs @@ -38,7 +38,7 @@ fn test_fn_ptr_curry_call() -> Result<(), Box> { #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_object"))] fn test_closures() -> Result<(), Box> { - let engine = Engine::new(); + let mut engine = Engine::new(); assert_eq!( engine.eval::( @@ -77,6 +77,23 @@ fn test_closures() -> Result<(), Box> { "# )?); + let mut module = Module::new(); + + module.set_fn_1("plus_one", |x: INT| Ok(x + 1)); + + engine.load_package(module); + + assert_eq!( + engine.eval::( + r#" + let a = 41; + let f = || plus_one(a); + f.call() + "# + )?, + 42 + ); + Ok(()) }