diff --git a/RELEASES.md b/RELEASES.md index 89b05c36..d42f41e2 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -4,6 +4,12 @@ Rhai Release Notes Version 0.19.0 ============== +Bug fixes +--------- + +* Fixes bug that prevents calling functions in closures. +* Fixes bug that erroneously consumes the first argument to a module-qualified function call. + New features ------------ diff --git a/doc/src/language/json.md b/doc/src/language/json.md index 543ddfdb..d76877c9 100644 --- a/doc/src/language/json.md +++ b/doc/src/language/json.md @@ -3,11 +3,14 @@ Parse an Object Map from JSON {{#include ../links.md}} -The syntax for an [object map] is extremely similar to JSON, with the exception of `null` values which can -technically be mapped to [`()`]. A valid JSON string does not start with a hash character `#` while a -Rhai [object map] does - that's the major difference! +The syntax for an [object map] is extremely similar to the JSON representation of a object hash, +with the exception of `null` values which can technically be mapped to [`()`]. -Use the `Engine::parse_json` method to parse a piece of _simple_ JSON into an object map: +A valid JSON string does not start with a hash character `#` while a Rhai [object map] does - that's the major difference! + +Use the `Engine::parse_json` method to parse a piece of JSON into an object map. +The JSON text must represent a single object hash (i.e. must be wrapped within "`{ .. }`") +otherwise it returns a syntax error. ```rust // JSON string - notice that JSON property names are always quoted @@ -59,6 +62,8 @@ When `Engine::parse_json` encounters JSON with sub-objects, it fails with a synt If it is certain that no text string in the JSON will ever contain the character '`{`', then it is possible to parse it by first replacing all occupance of '`{`' with "`#{`". +A JSON object hash starting with `#{` is handled transparently by `Engine::parse_json`. + ```rust // JSON with sub-object 'b'. let json = r#"{"a":1, "b":{"x":true, "y":false}}"#; diff --git a/doc/src/rust/register-raw.md b/doc/src/rust/register-raw.md index 5a73cae7..210f419f 100644 --- a/doc/src/rust/register-raw.md +++ b/doc/src/rust/register-raw.md @@ -33,7 +33,7 @@ engine.register_raw_fn( // But remember this is Rust, so you can keep only one mutable reference at any one time! // Therefore, get a '&mut' reference to the first argument _last_. - // Alternatively, use `args.split_at_mut(1)` etc. to split the slice first. + // Alternatively, use `args.split_first_mut()` etc. to split the slice first. let y: i64 = *args[1].read_lock::() // get a reference to the second argument .unwrap(); // then copying it because it is a primary type @@ -163,15 +163,15 @@ Hold Multiple References ------------------------ In order to access a value argument that is expensive to clone _while_ holding a mutable reference -to the first argument, either _consume_ that argument via `mem::take` as above, or use `args.split_at` +to the first argument, either _consume_ that argument via `mem::take` as above, or use `args.split_first` to partition the slice: ```rust // Partition the slice -let (first, rest) = args.split_at_mut(1); +let (first, rest) = args.split_first_mut().unwrap(); // Mutable reference to the first parameter -let this_ptr: &mut A = &mut *first[0].write_lock::().unwrap(); +let this_ptr: &mut A = &mut *first.write_lock::().unwrap(); // Immutable reference to the second value parameter // This can be mutable but there is no point because the parameter is passed by value diff --git a/src/api.rs b/src/api.rs index 27a2d42b..8b91cd2a 100644 --- a/src/api.rs +++ b/src/api.rs @@ -2,7 +2,7 @@ use crate::any::{Dynamic, Variant}; use crate::engine::{Engine, Imports, State}; -use crate::error::ParseError; +use crate::error::{ParseError, ParseErrorType}; use crate::fn_native::{IteratorFn, SendSync}; use crate::module::{FuncReturn, Module}; use crate::optimize::OptimizationLevel; @@ -895,6 +895,8 @@ impl Engine { /// Parse a JSON string into a map. /// + /// The JSON string must be an object hash. It cannot be a simple JavaScript primitive. + /// /// Set `has_null` to `true` in order to map `null` values to `()`. /// Setting it to `false` will cause a _variable not found_ error during parsing. /// @@ -934,12 +936,20 @@ impl Engine { let mut scope = Scope::new(); // Trims the JSON string and add a '#' in front - let json = json.trim(); - let scripts = if json.starts_with(Token::MapStart.syntax().as_ref()) { - [json, ""] + let json_text = json.trim_start(); + let scripts = if json_text.starts_with(Token::MapStart.syntax().as_ref()) { + [json_text, ""] + } else if json_text.starts_with(Token::LeftBrace.syntax().as_ref()) { + ["#", json_text] } else { - ["#", json] + return Err(ParseErrorType::MissingToken( + Token::LeftBrace.syntax().to_string(), + "to start a JSON object hash".to_string(), + ) + .into_err(Position::new(1, (json.len() - json_text.len() + 1) as u16)) + .into()); }; + let stream = lex( &scripts, if has_null { diff --git a/src/fn_call.rs b/src/fn_call.rs index 65e2b8cb..792ccd4c 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -525,13 +525,13 @@ impl Engine { let result = if _is_method { // Method call of script function - map first argument to `this` - let (first, rest) = args.split_at_mut(1); + let (first, rest) = args.split_first_mut().unwrap(); self.call_script_fn( scope, mods, state, lib, - &mut Some(first[0]), + &mut Some(*first), fn_name, func, rest, @@ -978,6 +978,7 @@ impl Engine { ) -> Result> { let modules = modules.as_ref().unwrap(); let mut arg_values: StaticVec<_>; + let mut first_arg_value = None; let mut args: StaticVec<_>; if args_expr.is_empty() { @@ -992,17 +993,28 @@ impl Engine { Expr::Variable(x) if x.1.is_none() => { arg_values = args_expr .iter() - .skip(1) - .map(|expr| self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)) + .enumerate() + .map(|(i, expr)| { + // Skip the first argument + if i == 0 { + Ok(Default::default()) + } else { + self.eval_expr(scope, mods, state, lib, this_ptr, expr, level) + } + }) .collect::>()?; + // Get target reference to first argument let (target, _, _, pos) = search_scope_only(scope, state, this_ptr, args_expr.get(0).unwrap())?; self.inc_operations(state) .map_err(|err| err.new_position(pos))?; - args = once(target).chain(arg_values.iter_mut()).collect(); + let (first, rest) = arg_values.split_first_mut().unwrap(); + first_arg_value = Some(first); + + args = once(target).chain(rest.iter_mut()).collect(); } // func(..., ...) or func(mod::x, ...) _ => { @@ -1041,6 +1053,13 @@ impl Engine { match func { #[cfg(not(feature = "no_function"))] Some(f) if f.is_script() => { + // Clone first argument + if let Some(first) = first_arg_value { + let first_val = args[0].clone(); + args[0] = first; + *args[0] = first_val; + } + let args = args.as_mut(); let func = f.get_fn_def(); @@ -1060,7 +1079,19 @@ impl Engine { self.call_script_fn(scope, mods, state, lib, &mut None, name, func, args, level) } Some(f) if f.is_plugin_fn() => f.get_plugin_fn().call(args.as_mut(), Position::none()), - Some(f) => f.get_native_fn()(self, lib, args.as_mut()), + Some(f) if f.is_native() => { + if !f.is_method() { + // Clone first argument + if let Some(first) = first_arg_value { + let first_val = args[0].clone(); + args[0] = first; + *args[0] = first_val; + } + } + + f.get_native_fn()(self, lib, args.as_mut()) + } + Some(_) => unreachable!(), None if def_val.is_some() => Ok(def_val.unwrap().into()), None => EvalAltResult::ErrorFunctionNotFound( format!( diff --git a/tests/maps.rs b/tests/maps.rs index c57deaa6..988c51a3 100644 --- a/tests/maps.rs +++ b/tests/maps.rs @@ -1,6 +1,6 @@ #![cfg(not(feature = "no_object"))] -use rhai::{Engine, EvalAltResult, Map, Scope, INT}; +use rhai::{Engine, EvalAltResult, Map, ParseErrorType, Scope, INT}; #[test] fn test_map_indexing() -> Result<(), Box> { @@ -182,6 +182,14 @@ fn test_map_json() -> Result<(), Box> { ); } + engine.parse_json(&format!("#{}", json), true)?; + + assert!(matches!( + *engine.parse_json(" 123", true).expect_err("should error"), + EvalAltResult::ErrorParsing(ParseErrorType::MissingToken(token, _), pos) + if token == "{" && pos.position() == Some(4) + )); + Ok(()) } diff --git a/tests/modules.rs b/tests/modules.rs index 3b00ab17..06f5e37e 100644 --- a/tests/modules.rs +++ b/tests/modules.rs @@ -94,6 +94,31 @@ fn test_module_resolver() -> Result<(), Box> { 42 ); + assert_eq!( + engine.eval::( + r#" + import "hello" as h1; + import "hello" as h2; + let x = 42; + h1::sum(x, -10, 3, 7) + "# + )?, + 42 + ); + + assert_eq!( + engine.eval::( + r#" + import "hello" as h1; + import "hello" as h2; + let x = 42; + h1::sum(x, 0, 0, 0); + x + "# + )?, + 42 + ); + assert_eq!( engine.eval::( r#"