Merge pull request #224 from schungx/master

Bug fix - Allow module access in closures.
This commit is contained in:
Stephen Chung 2020-08-22 23:09:26 +08:00 committed by GitHub
commit 99aaf8fb46
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 121 additions and 9 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "rhai" name = "rhai"
version = "0.19.0" version = "0.18.3"
edition = "2018" edition = "2018"
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung"] authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung"]
description = "Embedded scripting for Rust" description = "Embedded scripting for Rust"

View File

@ -1,7 +1,17 @@
Rhai Release Notes Rhai Release Notes
================== ==================
Version 0.19.0 Version 0.18.3
==============
Bug fixes
---------
* `Engine::compile_expression`, `Engine::eval_expression` etc. no longer parse anonymous functions and closures.
* Imported modules now work inside closures.
Version 0.18.2
============== ==============
Bug fixes Bug fixes

View File

@ -11,9 +11,11 @@ In these cases, use the `Engine::compile_expression` and `Engine::eval_expressio
let result = engine.eval_expression::<i64>("2 + (10 + 10) * 2")?; let result = engine.eval_expression::<i64>("2 + (10 + 10) * 2")?;
``` ```
When evaluating _expressions_, no full-blown statement (e.g. `if`, `while`, `for`) - not even variable assignment - When evaluating _expressions_, no full-blown statement (e.g. `if`, `while`, `for`, `fn`) - not even variable assignment -
is supported and will be considered parse errors when encountered. is supported and will be considered parse errors when encountered.
[Closures] and [anonymous functions] are also not supported because in the background they compile to functions.
```rust ```rust
// The following are all syntax errors because the script is not an expression. // The following are all syntax errors because the script is not an expression.

View File

@ -2,7 +2,7 @@
use crate::any::{Dynamic, Variant}; use crate::any::{Dynamic, Variant};
use crate::engine::{Engine, Imports, State}; use crate::engine::{Engine, Imports, State};
use crate::error::{ParseError, ParseErrorType}; use crate::error::ParseError;
use crate::fn_native::{IteratorFn, SendSync}; use crate::fn_native::{IteratorFn, SendSync};
use crate::module::{FuncReturn, Module}; use crate::module::{FuncReturn, Module};
use crate::optimize::OptimizationLevel; use crate::optimize::OptimizationLevel;
@ -18,6 +18,7 @@ use crate::engine::{FN_IDX_GET, FN_IDX_SET};
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
use crate::{ use crate::{
engine::{make_getter, make_setter, Map}, engine::{make_getter, make_setter, Map},
error::ParseErrorType,
fn_register::{RegisterFn, RegisterResultFn}, fn_register::{RegisterFn, RegisterResultFn},
token::Token, token::Token,
}; };
@ -34,7 +35,6 @@ use crate::optimize::optimize_into_ast;
use crate::stdlib::{ use crate::stdlib::{
any::{type_name, TypeId}, any::{type_name, TypeId},
boxed::Box, boxed::Box,
string::ToString,
}; };
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
@ -944,8 +944,8 @@ impl Engine {
["#", json_text] ["#", json_text]
} else { } else {
return Err(ParseErrorType::MissingToken( return Err(ParseErrorType::MissingToken(
Token::LeftBrace.syntax().to_string(), Token::LeftBrace.syntax().into(),
"to start a JSON object hash".to_string(), "to start a JSON object hash".into(),
) )
.into_err(Position::new(1, (json.len() - json_text.len() + 1) as u16)) .into_err(Position::new(1, (json.len() - json_text.len() + 1) as u16))
.into()); .into());

View File

@ -1645,11 +1645,22 @@ fn parse_primary(
} }
Expr::Variable(Box::new(((s, settings.pos), None, 0, None))) Expr::Variable(Box::new(((s, settings.pos), None, 0, None)))
} }
// Module qualification
#[cfg(not(feature = "no_module"))]
Token::Identifier(s) if *next_token == Token::DoubleColon => {
// Once the identifier consumed we must enable next variables capturing
#[cfg(not(feature = "no_closure"))]
{
state.allow_capture = true;
}
Expr::Variable(Box::new(((s, settings.pos), None, 0, None)))
}
// Normal variable access // Normal variable access
Token::Identifier(s) => { Token::Identifier(s) => {
let index = state.access_var(&s, settings.pos); let index = state.access_var(&s, settings.pos);
Expr::Variable(Box::new(((s, settings.pos), None, 0, index))) Expr::Variable(Box::new(((s, settings.pos), None, 0, index)))
} }
// Function call is allowed to have reserved keyword // Function call is allowed to have reserved keyword
Token::Reserved(s) if *next_token == Token::LeftParen || *next_token == Token::Bang => { Token::Reserved(s) if *next_token == Token::LeftParen || *next_token == Token::Bang => {
if is_keyword_function(&s) { if is_keyword_function(&s) {
@ -1658,6 +1669,7 @@ fn parse_primary(
return Err(PERR::Reserved(s).into_err(settings.pos)); return Err(PERR::Reserved(s).into_err(settings.pos));
} }
} }
// Access to `this` as a variable is OK // Access to `this` as a variable is OK
Token::Reserved(s) if s == KEYWORD_THIS && *next_token != Token::LeftParen => { Token::Reserved(s) if s == KEYWORD_THIS && *next_token != Token::LeftParen => {
if !settings.is_function_scope { if !settings.is_function_scope {
@ -1669,9 +1681,11 @@ fn parse_primary(
Expr::Variable(Box::new(((s, settings.pos), None, 0, None))) Expr::Variable(Box::new(((s, settings.pos), None, 0, None)))
} }
} }
Token::Reserved(s) if is_valid_identifier(s.chars()) => { Token::Reserved(s) if is_valid_identifier(s.chars()) => {
return Err(PERR::Reserved(s).into_err(settings.pos)); return Err(PERR::Reserved(s).into_err(settings.pos));
} }
Token::LeftParen => parse_paren_expr(input, state, lib, settings.level_up())?, Token::LeftParen => parse_paren_expr(input, state, lib, settings.level_up())?,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Token::LeftBracket => parse_array_literal(input, state, lib, settings.level_up())?, Token::LeftBracket => parse_array_literal(input, state, lib, settings.level_up())?,
@ -1680,6 +1694,7 @@ fn parse_primary(
Token::True => Expr::True(settings.pos), Token::True => Expr::True(settings.pos),
Token::False => Expr::False(settings.pos), Token::False => Expr::False(settings.pos),
Token::LexError(err) => return Err(err.into_err(settings.pos)), Token::LexError(err) => return Err(err.into_err(settings.pos)),
_ => { _ => {
return Err( return Err(
PERR::BadInput(format!("Unexpected '{}'", token.syntax())).into_err(settings.pos) PERR::BadInput(format!("Unexpected '{}'", token.syntax())).into_err(settings.pos)
@ -1862,7 +1877,7 @@ fn parse_unary(
} }
// | ... // | ...
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
Token::Pipe | Token::Or => { Token::Pipe | Token::Or if settings.allow_anonymous_fn => {
let mut new_state = ParseState::new( let mut new_state = ParseState::new(
state.engine, state.engine,
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
@ -3353,6 +3368,8 @@ impl Engine {
}; };
let expr = parse_expr(input, &mut state, &mut functions, settings)?; let expr = parse_expr(input, &mut state, &mut functions, settings)?;
assert!(functions.is_empty());
match input.peek().unwrap() { match input.peek().unwrap() {
(Token::EOF, _) => (), (Token::EOF, _) => (),
// Return error if the expression doesn't end // Return error if the expression doesn't end

View File

@ -120,6 +120,20 @@ fn test_fn_ptr_raw() -> Result<(), Box<EvalAltResult>> {
42 42
); );
assert_eq!(
engine.eval::<INT>(
r#"
fn foo(x, y) { this += x + y; }
let x = 40;
let v = 1;
x.bar(Fn("foo").curry(v), 1);
x
"#
)?,
42
);
assert!(matches!( assert!(matches!(
*engine.eval::<INT>( *engine.eval::<INT>(
r#" r#"

View File

@ -1,7 +1,12 @@
#![cfg(not(feature = "no_function"))] #![cfg(not(feature = "no_function"))]
use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, Module, RegisterFn, INT}; use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, Module, ParseErrorType, RegisterFn, Scope, INT};
use std::any::TypeId; use std::any::TypeId;
use std::cell::RefCell;
use std::mem::take; use std::mem::take;
use std::rc::Rc;
#[cfg(not(feature = "no_object"))]
use rhai::Map;
#[test] #[test]
fn test_fn_ptr_curry_call() -> Result<(), Box<EvalAltResult>> { fn test_fn_ptr_curry_call() -> Result<(), Box<EvalAltResult>> {
@ -39,6 +44,14 @@ fn test_fn_ptr_curry_call() -> Result<(), Box<EvalAltResult>> {
fn test_closures() -> Result<(), Box<EvalAltResult>> { fn test_closures() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
assert!(matches!(
*engine
.compile_expression("let f = |x| {};")
.expect_err("should error")
.0,
ParseErrorType::BadInput(_)
));
assert_eq!( assert_eq!(
engine.eval::<INT>( engine.eval::<INT>(
r#" r#"
@ -181,3 +194,59 @@ fn test_closures_data_race() -> Result<(), Box<EvalAltResult>> {
Ok(()) Ok(())
} }
type MyType = Rc<RefCell<INT>>;
#[test]
#[cfg(not(feature = "no_object"))]
#[cfg(not(feature = "sync"))]
fn test_closure_shared_obj() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
// Register API on MyType
engine
.register_type_with_name::<MyType>("MyType")
.register_get_set(
"data",
|p: &mut MyType| *p.borrow(),
|p: &mut MyType, value: INT| *p.borrow_mut() = value,
)
.register_fn("+=", |p1: &mut MyType, p2: MyType| {
*p1.borrow_mut() += *p2.borrow()
})
.register_fn("-=", |p1: &mut MyType, p2: MyType| {
*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
let f = move |p1: MyType, p2: MyType| -> Result<(), Box<EvalAltResult>> {
let action_ptr = res["action"].clone().cast::<FnPtr>();
let name = action_ptr.fn_name();
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));
f(p1.clone(), p2.clone())?;
assert_eq!(*p1.borrow(), 42);
Ok(())
}