diff --git a/Cargo.toml b/Cargo.toml index 324e0a02..a50bc0b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ only_i64 = [] # set INT=i64 (default) and disable support for all other in sync = [] # restrict to only types that implement Send + Sync # compiling for no-std -no_std = [ "num-traits/libm", "hashbrown", "core-error", "libm" ] +no_std = [ "num-traits/libm", "hashbrown", "core-error", "libm", "ahash" ] # other developer features no_stdlib = [] # do not register the standard library @@ -63,4 +63,5 @@ optional = true [dependencies.ahash] version = "0.3.2" default-features = false +features = ["compile-time-rng"] optional = true diff --git a/README.md b/README.md index 868cfe43..0e8d4b77 100644 --- a/README.md +++ b/README.md @@ -13,19 +13,20 @@ to add scripting to any application. Rhai's current features set: -* `no-std` support -* Easy integration with Rust native functions and types, including getter/setter/methods -* Easily call a script-defined function from Rust +* Easy-to-use language similar to JS+Rust +* Easy integration with Rust [native functions](#working-with-functions) and [types](#custom-types-and-methods), + including [getter/setter](#getters-and-setters)/[methods](#members-and-methods) +* Easily [call a script-defined function](#calling-rhai-functions-from-rust) from Rust * Freely pass variables/constants into a script via an external [`Scope`] * Fairly efficient (1 million iterations in 0.75 sec on my 5 year old laptop) * Low compile-time overhead (~0.6 sec debug/~3 sec release for script runner app) -* Easy-to-use language similar to JS+Rust -* Support for function overloading -* Support for operator overloading -* Compiled script is optimized for repeat evaluations -* Support for minimal builds by excluding unneeded language features +* [`no-std`](#optional-features) support +* Support for [function overloading](#function-overloading) +* Support for [operator overloading](#operator-overloading) +* Compiled script is [optimized](#script-optimization) for repeat evaluations +* Support for [minimal builds](#minimal-builds) by excluding unneeded language [features](#optional-features) * Very few additional dependencies (right now only [`num-traits`](https://crates.io/crates/num-traits/) - to do checked arithmetic operations); for [`no_std`] builds, a number of additional dependencies are + to do checked arithmetic operations); for [`no-std`](#optional-features) builds, a number of additional dependencies are pulled in to provide for functionalities that used to be in `std`. **Note:** Currently, the version is 0.13.0, so the language and API's may change before they stabilize. @@ -116,10 +117,13 @@ Opt out of as many features as possible, if they are not needed, to reduce code all code is compiled in as what a script requires cannot be predicted. If a language feature is not needed, omitting them via special features is a prudent strategy to optimize the build for size. -Start by using [`Engine::new_raw`](#raw-engine) to create a _raw_ engine which does not register the standard library of utility -functions. Secondly, omitting arrays (`no_index`) yields the most code-size savings, followed by floating-point support -(`no_float`), checked arithmetic (`unchecked`) and finally object maps and custom types (`no_object`). Disable script-defined -functions (`no_function`) only when the feature is not needed because code size savings is minimal. +Omitting arrays (`no_index`) yields the most code-size savings, followed by floating-point support +(`no_float`), checked arithmetic (`unchecked`) and finally object maps and custom types (`no_object`). +Disable script-defined functions (`no_function`) only when the feature is not needed because code size savings is minimal. + +[`Engine::new_raw`](#raw-engine) creates a _raw_ engine which does not register _any_ utility functions. +This makes the scripting language quite useless as even basic arithmetic operators are not supported. +Selectively include the necessary operators by loading specific [packages](#packages) while minimizing the code footprint. Related ------- @@ -199,7 +203,7 @@ To get going with Rhai, create an instance of the scripting engine via `Engine:: ```rust use rhai::{Engine, EvalAltResult}; -fn main() -> Result<(), EvalAltResult> +fn main() -> Result<(), Box> { let engine = Engine::new(); @@ -320,7 +324,7 @@ let script = "fn calc(x, y) { x + y.len() < 42 }"; // 1) a tuple made up of the types of the script function's parameters // 2) the return type of the script function // -// 'func' will have type Box Result> and is callable! +// 'func' will have type Box Result>> and is callable! let func = Func::<(i64, String), bool>::create_from_script( // ^^^^^^^^^^^^^ function parameter types in tuple @@ -336,7 +340,7 @@ schedule_callback(func); // pass it as a callback to anot // Although there is nothing you can't do by manually writing out the closure yourself... let engine = Engine::new(); let ast = engine.compile(script)?; -schedule_callback(Box::new(move |x: i64, y: String| -> Result { +schedule_callback(Box::new(move |x: i64, y: String| -> Result> { engine.call_fn(&mut Scope::new(), &ast, "calc", (x, y)) })); ``` @@ -349,17 +353,41 @@ Raw `Engine` `Engine::new` creates a scripting [`Engine`] with common functionalities (e.g. printing to the console via `print`). In many controlled embedded environments, however, these are not needed. -Use `Engine::new_raw` to create a _raw_ `Engine`, in which: +Use `Engine::new_raw` to create a _raw_ `Engine`, in which _nothing_ is added, not even basic arithmetic and logic operators! -* the `print` and `debug` statements do nothing instead of displaying to the console (see [`print` and `debug`](#print-and-debug) below) -* the _standard library_ of utility functions is _not_ loaded by default (load it using the `register_stdlib` method). +### Packages + +Rhai functional features are provided in different _packages_ that can be loaded via a call to `load_package`. +Packages reside under `rhai::packages::*` and the trait `rhai::packages::Package` must be imported in order for +packages to be used. ```rust -let mut engine = Engine::new_raw(); // create a 'raw' Engine +use rhai::Engine; +use rhai::packages::Package // load the 'Package' trait to use packages +use rhai::packages::CorePackage; // the 'core' package contains basic functionalities (e.g. arithmetic) -engine.register_stdlib(); // register the standard library manually +let mut engine = Engine::new_raw(); // create a 'raw' Engine +let package = CorePackage::new(); // create a package - can be shared among multiple `Engine` instances + +engine.load_package(package.get()); // load the package manually ``` +The follow packages are available: + +| Package | Description | In `CorePackage` | In `StandardPackage` | +| ------------------------ | ----------------------------------------------- | :--------------: | :------------------: | +| `BasicArithmeticPackage` | Arithmetic operators (e.g. `+`, `-`, `*`, `/`) | Yes | Yes | +| `BasicIteratorPackage` | Numeric ranges (e.g. `range(1, 10)`) | Yes | Yes | +| `LogicPackage` | Logic and comparison operators (e.g. `==`, `>`) | Yes | Yes | +| `BasicStringPackage` | Basic string functions | Yes | Yes | +| `BasicTimePackage` | Basic time functions (e.g. [timestamps]) | Yes | Yes | +| `MoreStringPackage` | Additional string functions | No | Yes | +| `BasicMathPackage` | Basic math functions (e.g. `sin`, `sqrt`) | No | Yes | +| `BasicArrayPackage` | Basic [array] functions | No | Yes | +| `BasicMapPackage` | Basic [object map] functions | No | Yes | +| `CorePackage` | Basic essentials | | | +| `StandardPackage` | Standard library | | | + Evaluate expressions only ------------------------- @@ -401,7 +429,7 @@ The following primitive types are supported natively: | **Unicode string** | `String` (_not_ `&str`) | `"string"` | `"hello"` etc. | | **Array** (disabled with [`no_index`]) | `rhai::Array` | `"array"` | `"[ ? ? ? ]"` | | **Object map** (disabled with [`no_object`]) | `rhai::Map` | `"map"` | `#{ "a": 1, "b": 2 }` | -| **Timestamp** (implemented in standard library) | `std::time::Instant` | `"timestamp"` | _not supported_ | +| **Timestamp** (implemented in the [`BasicTimePackage`](#packages)) | `std::time::Instant` | `"timestamp"` | _not supported_ | | **Dynamic value** (i.e. can be anything) | `rhai::Dynamic` | _the actual type_ | _actual value_ | | **System integer** (current configuration) | `rhai::INT` (`i32` or `i64`) | `"i32"` or `"i64"` | `"42"`, `"123"` etc. | | **System floating-point** (current configuration, disabled with [`no_float`]) | `rhai::FLOAT` (`f32` or `f64`) | `"f32"` or `"f64"` | `"123.456"` etc. | @@ -428,7 +456,7 @@ type_of('c') == "char"; type_of(42) == "i64"; let x = 123; -x.type_of(); // <- error: 'type_of' cannot use method-call style +x.type_of() == "i64"; // method-call style is also OK type_of(x) == "i64"; x = 99.999; @@ -507,6 +535,16 @@ match item.type_name() { // 'type_name' returns the name } ``` +The following conversion traits are implemented for `Dynamic`: + +* `From` (`i32` if [`only_i32`]) +* `From` (if not [`no_float`]) +* `From` +* `From` +* `From` +* `From>` (into an [array]) +* `From>` (into an [object map]). + Value conversions ----------------- @@ -532,12 +570,12 @@ Traits A number of traits, under the `rhai::` module namespace, provide additional functionalities. -| Trait | Description | Methods | -| ------------------- | --------------------------------------------------------------------------------- | --------------------------------------- | -| `RegisterFn` | Trait for registering functions | `register_fn` | -| `RegisterDynamicFn` | Trait for registering functions returning [`Dynamic`] | `register_dynamic_fn` | -| `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, EvalAltResult>` | `register_result_fn` | -| `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` | +| Trait | Description | Methods | +| ------------------- | -------------------------------------------------------------------------------------- | --------------------------------------- | +| `RegisterFn` | Trait for registering functions | `register_fn` | +| `RegisterDynamicFn` | Trait for registering functions returning [`Dynamic`] | `register_dynamic_fn` | +| `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, Box>` | `register_result_fn` | +| `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` | Working with functions ---------------------- @@ -560,7 +598,7 @@ fn get_an_any() -> Dynamic { Dynamic::from(42_i64) } -fn main() -> Result<(), EvalAltResult> +fn main() -> Result<(), Box> { let engine = Engine::new(); @@ -629,18 +667,20 @@ Fallible functions If a function is _fallible_ (i.e. it returns a `Result<_, Error>`), it can be registered with `register_result_fn` (using the `RegisterResultFn` trait). -The function must return `Result<_, EvalAltResult>`. `EvalAltResult` implements `From<&str>` and `From` etc. -and the error text gets converted into `EvalAltResult::ErrorRuntime`. +The function must return `Result<_, Box>`. `Box` implements `From<&str>` and `From` etc. +and the error text gets converted into `Box`. + +The error values are `Box`-ed in order to reduce memory footprint of the error path, which should be hit rarely. ```rust use rhai::{Engine, EvalAltResult, Position}; use rhai::RegisterResultFn; // use 'RegisterResultFn' trait for 'register_result_fn' // Function that may fail -fn safe_divide(x: i64, y: i64) -> Result { +fn safe_divide(x: i64, y: i64) -> Result> { if y == 0 { // Return an error if y is zero - Err("Division by zero!".into()) // short-cut to create EvalAltResult + Err("Division by zero!".into()) // short-cut to create Box } else { Ok(x / y) } @@ -654,7 +694,7 @@ fn main() engine.register_result_fn("divide", safe_divide); if let Err(error) = engine.eval::("divide(40, 0)") { - println!("Error: {:?}", error); // prints ErrorRuntime("Division by zero detected!", (1, 1)") + println!("Error: {:?}", *error); // prints ErrorRuntime("Division by zero detected!", (1, 1)") } } ``` @@ -741,7 +781,7 @@ impl TestStruct { } } -fn main() -> Result<(), EvalAltResult> +fn main() -> Result<(), Box> { let engine = Engine::new(); @@ -838,12 +878,12 @@ with a special "pretty-print" name, [`type_of()`] will return that name instead. engine.register_type::(); engine.register_fn("new_ts", TestStruct::new); let x = new_ts(); -print(type_of(x)); // prints "path::to::module::TestStruct" +print(x.type_of()); // prints "path::to::module::TestStruct" engine.register_type_with_name::("Hello"); engine.register_fn("new_ts", TestStruct::new); let x = new_ts(); -print(type_of(x)); // prints "Hello" +print(x.type_of()); // prints "Hello" ``` Getters and setters @@ -905,7 +945,7 @@ threaded through multiple invocations: ```rust use rhai::{Engine, Scope, EvalAltResult}; -fn main() -> Result<(), EvalAltResult> +fn main() -> Result<(), Box> { let engine = Engine::new(); @@ -1116,7 +1156,7 @@ number = -5 - +5; Numeric functions ----------------- -The following standard functions (defined in the standard library but excluded if using a [raw `Engine`]) operate on +The following standard functions (defined in the [`BasicMathPackage`] but excluded if using a [raw `Engine`]) operate on `i8`, `i16`, `i32`, `i64`, `f32` and `f64` only: | Function | Description | @@ -1127,7 +1167,7 @@ The following standard functions (defined in the standard library but excluded i Floating-point functions ------------------------ -The following standard functions (defined in the standard library but excluded if using a [raw `Engine`]) operate on `f64` only: +The following standard functions (defined in the [`BasicMathPackage`](#packages) but excluded if using a [raw `Engine`]) operate on `f64` only: | Category | Functions | | ---------------- | ------------------------------------------------------------ | @@ -1174,8 +1214,8 @@ Unicode characters. Individual characters within a Rhai string can also be replaced just as if the string is an array of Unicode characters. In Rhai, there is also no separate concepts of `String` and `&str` as in Rust. -Strings can be built up from other strings and types via the `+` operator (provided by the standard library but excluded -if using a [raw `Engine`]). This is particularly useful when printing output. +Strings can be built up from other strings and types via the `+` operator (provided by the [`MoreStringPackage`](#packages) +but excluded if using a [raw `Engine`]). This is particularly useful when printing output. [`type_of()`] a string returns `"string"`. @@ -1225,7 +1265,7 @@ record == "Bob X. Davis: age 42 ❤\n"; ### Built-in functions -The following standard methods (defined in the standard library but excluded if using a [raw `Engine`]) operate on strings: +The following standard methods (defined in the [`MoreStringPackage`](#packages) but excluded if using a [raw `Engine`]) operate on strings: | Function | Parameter(s) | Description | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | @@ -1300,7 +1340,7 @@ Arrays are disabled via the [`no_index`] feature. ### Built-in functions -The following methods (defined in the standard library but excluded if using a [raw `Engine`]) operate on arrays: +The following methods (defined in the [`BasicArrayPackage`](#packages) but excluded if using a [raw `Engine`]) operate on arrays: | Function | Parameter(s) | Description | | ------------ | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | @@ -1400,6 +1440,7 @@ engine.register_fn("push", |list: &mut Array, item: MyType| list.push(Box::new(i Object maps ----------- +[`Map`]: #object-maps [object map]: #object-maps [object maps]: #object-maps @@ -1420,7 +1461,7 @@ Object maps are disabled via the [`no_object`] feature. ### Built-in functions -The following methods (defined in the standard library but excluded if using a [raw `Engine`]) operate on object maps: +The following methods (defined in the [`BasicMapPackage`](#packages) but excluded if using a [raw `Engine`]) operate on object maps: | Function | Parameter(s) | Description | | ------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | @@ -1430,8 +1471,8 @@ The following methods (defined in the standard library but excluded if using a [ | `remove` | property name | removes a certain property and returns it ([`()`] if the property does not exist) | | `mixin` | second object map | mixes in all the properties of the second object map to the first (values of properties with the same names replace the existing values) | | `+` operator | first object map, second object map | merges the first object map with the second | -| `keys` | _none_ | returns an [array] of all the property names (in random order) | -| `values` | _none_ | returns an [array] of all the property values (in random order) | +| `keys` | _none_ | returns an [array] of all the property names (in random order), not available under [`no_index`] | +| `values` | _none_ | returns an [array] of all the property values (in random order), not available under [`no_index`] | ### Examples @@ -1530,7 +1571,7 @@ let json = r#"{ // Set the second boolean parameter to true in order to map 'null' to '()' let map = engine.parse_json(json, true)?; -map.len() == 6; // 'map' contains all properties int the JSON string +map.len() == 6; // 'map' contains all properties in the JSON string // Put the object map into a 'Scope' let mut scope = Scope::new(); @@ -1543,16 +1584,19 @@ result == 3; // the object map is successfully used i `timestamp`'s ------------- -[`timestamp`]: #timestamp-s -Timestamps are provided by the standard library (excluded if using a [raw `Engine`]) via the `timestamp` +[`timestamp`]: #timestamps +[timestamp]: #timestamps +[timestamps]: #timestamps + +Timestamps are provided by the [`BasicTimePackage`](#packages) (excluded if using a [raw `Engine`]) via the `timestamp` function. The Rust type of a timestamp is `std::time::Instant`. [`type_of()`] a timestamp returns `"timestamp"`. ### Built-in functions -The following methods (defined in the standard library but excluded if using a [raw `Engine`]) operate on timestamps: +The following methods (defined in the [`BasicTimePackage`](#packages) but excluded if using a [raw `Engine`]) operate on timestamps: | Function | Parameter(s) | Description | | ------------ | ---------------------------------- | -------------------------------------------------------- | @@ -1600,13 +1644,13 @@ ts == 42; // false - types are not the same Boolean operators ----------------- -| Operator | Description | -| -------- | ------------------------------- | -| `!` | Boolean _Not_ | -| `&&` | Boolean _And_ (short-circuits) | -| `\|\|` | Boolean _Or_ (short-circuits) | -| `&` | Boolean _And_ (full evaluation) | -| `\|` | Boolean _Or_ (full evaluation) | +| Operator | Description | +| -------- | ------------------------------------- | +| `!` | Boolean _Not_ | +| `&&` | Boolean _And_ (short-circuits) | +| `\|\|` | Boolean _Or_ (short-circuits) | +| `&` | Boolean _And_ (doesn't short-circuit) | +| `\|` | Boolean _Or_ (doesn't short-circuit) | Double boolean operators `&&` and `||` _short-circuit_, meaning that the second operand will not be evaluated if the first one already proves the condition wrong. @@ -1766,7 +1810,7 @@ return 123 + 456; // returns 579 Errors and `throw`-ing exceptions -------------------------------- -All of [`Engine`]'s evaluation/consuming methods return `Result` with `EvalAltResult` +All of [`Engine`]'s evaluation/consuming methods return `Result>` with `EvalAltResult` holding error information. To deliberately return an error during an evaluation, use the `throw` keyword. ```rust @@ -1876,7 +1920,7 @@ Unlike C/C++, functions can be defined _anywhere_ within the global level. A fun prior to being used in a script; a statement in the script can freely call a function defined afterwards. This is similar to Rust and many other modern languages. -### Functions overloading +### Function overloading Functions can be _overloaded_ and are resolved purely upon the function's _name_ and the _number_ of parameters (but not parameter _types_, since all parameters are the same type - [`Dynamic`]). @@ -1903,7 +1947,7 @@ Properties and methods in a Rust custom type registered with the [`Engine`] can ```rust let a = new_ts(); // constructor function a.field = 500; // property access -a.update(); // method call +a.update(); // method call, 'a' can be changed update(a); // this works, but 'a' is unchanged because only // a COPY of 'a' is passed to 'update' by VALUE @@ -2205,7 +2249,7 @@ eval("{ let z = y }"); // to keep a variable local, use a statement block print("z = " + z); // <- error: variable 'z' not found -"print(42)".eval(); // <- nope... just like 'type_of', method-call style doesn't work +"print(42)".eval(); // <- nope... method-call style doesn't work ``` Script segments passed to `eval` execute inside the current [`Scope`], so they can access and modify _everything_, diff --git a/benches/engine.rs b/benches/engine.rs index e505129f..254288de 100644 --- a/benches/engine.rs +++ b/benches/engine.rs @@ -16,6 +16,17 @@ fn bench_engine_new_raw(bench: &mut Bencher) { bench.iter(|| Engine::new_raw()); } +#[bench] +fn bench_engine_new_raw_core(bench: &mut Bencher) { + use rhai::packages::*; + let package = CorePackage::new(); + + bench.iter(|| { + let mut engine = Engine::new_raw(); + engine.load_package(package.get()); + }); +} + #[bench] fn bench_engine_register_fn(bench: &mut Bencher) { fn hello(a: INT, b: Array, c: Map) -> bool { @@ -23,7 +34,7 @@ fn bench_engine_register_fn(bench: &mut Bencher) { } bench.iter(|| { - let mut engine = Engine::new(); + let mut engine = Engine::new_raw(); engine.register_fn("hello", hello); }); } diff --git a/benches/eval_array.rs b/benches/eval_array.rs index 687f22f5..d97e1164 100644 --- a/benches/eval_array.rs +++ b/benches/eval_array.rs @@ -51,7 +51,7 @@ fn bench_eval_array_large_set(bench: &mut Bencher) { let script = r#"let x = [ 1, 2.345, "hello", true, [ 1, 2, 3, [ "hey", [ "deeply", "nested" ], "jude" ] ] ]; - x[4] = 42 + x[4][3][1][1] = 42 "#; let mut engine = Engine::new(); diff --git a/benches/iterations.rs b/benches/iterations.rs index 073f0a91..23eb7621 100644 --- a/benches/iterations.rs +++ b/benches/iterations.rs @@ -3,7 +3,7 @@ ///! Test 1,000 iterations extern crate test; -use rhai::{Engine, OptimizationLevel, Scope, INT}; +use rhai::{Engine, OptimizationLevel, INT}; use test::Bencher; #[bench] @@ -34,6 +34,8 @@ fn bench_iterations_fibonacci(bench: &mut Bencher) { fibonacci(n-1) + fibonacci(n-2) } } + + fibonacci(20) "#; let mut engine = Engine::new(); @@ -41,9 +43,5 @@ fn bench_iterations_fibonacci(bench: &mut Bencher) { let ast = engine.compile(script).unwrap(); - bench.iter(|| { - engine - .call_fn::<_, INT>(&mut Scope::new(), &ast, "fibonacci", (20 as INT,)) - .unwrap() - }); + bench.iter(|| engine.eval_ast::(&ast).unwrap()); } diff --git a/benches/parsing.rs b/benches/parsing.rs index 7acf47b3..c4486bd5 100644 --- a/benches/parsing.rs +++ b/benches/parsing.rs @@ -74,7 +74,8 @@ fn bench_parse_primes(bench: &mut Bencher) { let prime_mask = []; prime_mask.pad(MAX_NUMBER_TO_CHECK, true); - prime_mask[0] = prime_mask[1] = false; + prime_mask[0] = false; + prime_mask[1] = false; let total_primes_found = 0; diff --git a/benches/primes.rs b/benches/primes.rs index 4144d2ad..1b1b022b 100644 --- a/benches/primes.rs +++ b/benches/primes.rs @@ -9,14 +9,13 @@ use test::Bencher; // This script uses the Sieve of Eratosthenes to calculate prime numbers. const SCRIPT: &str = r#" -let now = timestamp(); - const MAX_NUMBER_TO_CHECK = 1_000; // 168 primes <= 1000 let prime_mask = []; prime_mask.pad(MAX_NUMBER_TO_CHECK, true); -prime_mask[0] = prime_mask[1] = false; +prime_mask[0] = false; +prime_mask[1] = false; let total_primes_found = 0; diff --git a/examples/custom_types_and_methods.rs b/examples/custom_types_and_methods.rs index c912520d..d152dc9b 100644 --- a/examples/custom_types_and_methods.rs +++ b/examples/custom_types_and_methods.rs @@ -16,7 +16,7 @@ impl TestStruct { } #[cfg(not(feature = "no_object"))] -fn main() -> Result<(), EvalAltResult> { +fn main() -> Result<(), Box> { let mut engine = Engine::new(); engine.register_type::(); diff --git a/examples/hello.rs b/examples/hello.rs index c72a38b5..edec8cb8 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,7 +1,9 @@ -use rhai::{Engine, EvalAltResult, INT}; +use rhai::{packages::*, Engine, EvalAltResult, INT}; +use std::rc::Rc; -fn main() -> Result<(), EvalAltResult> { - let engine = Engine::new(); +fn main() -> Result<(), Box> { + let mut engine = Engine::new_raw(); + engine.load_package(ArithmeticPackage::new().get()); let result = engine.eval::("40 + 2")?; diff --git a/examples/no_std.rs b/examples/no_std.rs index ad9d9a8a..a6902f72 100644 --- a/examples/no_std.rs +++ b/examples/no_std.rs @@ -2,7 +2,13 @@ use rhai::{Engine, EvalAltResult, INT}; -fn main() -> Result<(), EvalAltResult> { +#[cfg(feature = "no_std")] +extern crate alloc; + +#[cfg(feature = "no_std")] +use alloc::boxed::Box; + +fn main() -> Result<(), Box> { let engine = Engine::new(); let result = engine.eval::("40 + 2")?; diff --git a/examples/repl.rs b/examples/repl.rs index 4c807814..4ae1c44f 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -157,7 +157,7 @@ fn main() { Ok(_) => (), Err(err) => { println!(); - print_error(&input, err); + print_error(&input, *err); println!(); } } diff --git a/examples/reuse_scope.rs b/examples/reuse_scope.rs index ab936656..a762ac8a 100644 --- a/examples/reuse_scope.rs +++ b/examples/reuse_scope.rs @@ -1,6 +1,6 @@ use rhai::{Engine, EvalAltResult, Scope, INT}; -fn main() -> Result<(), EvalAltResult> { +fn main() -> Result<(), Box> { let engine = Engine::new(); let mut scope = Scope::new(); diff --git a/examples/rhai_runner.rs b/examples/rhai_runner.rs index 166e1c3e..2bc273e2 100644 --- a/examples/rhai_runner.rs +++ b/examples/rhai_runner.rs @@ -72,7 +72,7 @@ fn main() { eprintln!("{:=<1$}", "", filename.len()); eprintln!(""); - eprint_error(&contents, err); + eprint_error(&contents, *err); } } } diff --git a/examples/simple_fn.rs b/examples/simple_fn.rs index 796b8114..21f532ae 100644 --- a/examples/simple_fn.rs +++ b/examples/simple_fn.rs @@ -1,6 +1,6 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT}; -fn main() -> Result<(), EvalAltResult> { +fn main() -> Result<(), Box> { let mut engine = Engine::new(); fn add(x: INT, y: INT) -> INT { diff --git a/scripts/mat_mul.rhai b/scripts/mat_mul.rhai index c7c00ae9..59011e22 100644 --- a/scripts/mat_mul.rhai +++ b/scripts/mat_mul.rhai @@ -16,9 +16,7 @@ fn mat_gen(n) { for i in range(0, n) { for j in range(0, n) { - let foo = m[i]; - foo[j] = tmp * (i.to_float() - j.to_float()) * (i.to_float() + j.to_float()); - m[i] = foo; + m[i][j] = tmp * (i.to_float() - j.to_float()) * (i.to_float() + j.to_float()); } } @@ -34,9 +32,7 @@ fn mat_mul(a, b) { for i in range(0, n) { for j in range(0, p) { - let foo = b2[j]; - foo[i] = b[i][j]; - b2[j] = foo; + b2[j][i] = b[i][j]; } } diff --git a/scripts/primes.rhai b/scripts/primes.rhai index 6d5a49d5..22defcb4 100644 --- a/scripts/primes.rhai +++ b/scripts/primes.rhai @@ -2,12 +2,13 @@ let now = timestamp(); -const MAX_NUMBER_TO_CHECK = 10_000; // 1229 primes <= 10000 +const MAX_NUMBER_TO_CHECK = 100_000; // 9592 primes <= 100000 let prime_mask = []; prime_mask.pad(MAX_NUMBER_TO_CHECK, true); -prime_mask[0] = prime_mask[1] = false; +prime_mask[0] = false; +prime_mask[1] = false; let total_primes_found = 0; diff --git a/src/any.rs b/src/any.rs index cb60384e..46ae6044 100644 --- a/src/any.rs +++ b/src/any.rs @@ -9,8 +9,10 @@ use crate::parser::FLOAT; use crate::stdlib::{ any::{type_name, Any, TypeId}, boxed::Box, + collections::HashMap, fmt, string::String, + vec::Vec, }; #[cfg(not(feature = "no_std"))] @@ -65,6 +67,9 @@ impl Variant for T { } /// A trait to represent any type. +/// +/// `From<_>` is implemented for `i64` (`i32` if `only_i32`), `f64` (if not `no_float`), +/// `bool`, `String`, `char`, `Vec` (into `Array`) and `HashMap` (into `Map`). #[cfg(feature = "sync")] pub trait Variant: Any + Send + Sync { /// Convert this `Variant` trait object to `&dyn Any`. @@ -207,7 +212,7 @@ impl fmt::Display for Dynamic { #[cfg(not(feature = "no_float"))] Union::Float(value) => write!(f, "{}", value), Union::Array(value) => write!(f, "{:?}", value), - Union::Map(value) => write!(f, "{:?}", value), + Union::Map(value) => write!(f, "#{:?}", value), Union::Variant(_) => write!(f, "?"), } } @@ -224,7 +229,7 @@ impl fmt::Debug for Dynamic { #[cfg(not(feature = "no_float"))] Union::Float(value) => write!(f, "{:?}", value), Union::Array(value) => write!(f, "{:?}", value), - Union::Map(value) => write!(f, "{:?}", value), + Union::Map(value) => write!(f, "#{:?}", value), Union::Variant(_) => write!(f, ""), } } @@ -263,16 +268,6 @@ fn cast_box(item: Box) -> Result> { } impl Dynamic { - /// Get a reference to the inner `Union`. - pub(crate) fn get_ref(&self) -> &Union { - &self.0 - } - - /// Get a mutable reference to the inner `Union`. - pub(crate) fn get_mut(&mut self) -> &mut Union { - &mut self.0 - } - /// Create a `Dynamic` from any type. A `Dynamic` value is simply returned as is. /// /// Beware that you need to pass in an `Array` type for it to be recognized as an `Array`. @@ -450,7 +445,7 @@ impl Dynamic { /// Cast the `Dynamic` as the system integer type `INT` and return it. /// Returns the name of the actual type if the cast fails. - pub(crate) fn as_int(&self) -> Result { + pub fn as_int(&self) -> Result { match self.0 { Union::Int(n) => Ok(n), _ => Err(self.type_name()), @@ -459,7 +454,7 @@ impl Dynamic { /// Cast the `Dynamic` as a `bool` and return it. /// Returns the name of the actual type if the cast fails. - pub(crate) fn as_bool(&self) -> Result { + pub fn as_bool(&self) -> Result { match self.0 { Union::Bool(b) => Ok(b), _ => Err(self.type_name()), @@ -468,7 +463,7 @@ impl Dynamic { /// Cast the `Dynamic` as a `char` and return it. /// Returns the name of the actual type if the cast fails. - pub(crate) fn as_char(&self) -> Result { + pub fn as_char(&self) -> Result { match self.0 { Union::Char(n) => Ok(n), _ => Err(self.type_name()), @@ -477,7 +472,7 @@ impl Dynamic { /// Cast the `Dynamic` as a string and return the string slice. /// Returns the name of the actual type if the cast fails. - pub(crate) fn as_str(&self) -> Result<&str, &'static str> { + pub fn as_str(&self) -> Result<&str, &'static str> { match &self.0 { Union::Str(s) => Ok(s), _ => Err(self.type_name()), @@ -486,33 +481,62 @@ impl Dynamic { /// Convert the `Dynamic` into `String` and return it. /// Returns the name of the actual type if the cast fails. - pub(crate) fn take_string(self) -> Result { + pub fn take_string(self) -> Result { match self.0 { Union::Str(s) => Ok(*s), _ => Err(self.type_name()), } } +} - pub(crate) fn from_unit() -> Self { - Self(Union::Unit(())) +impl From<()> for Dynamic { + fn from(value: ()) -> Self { + Self(Union::Unit(value)) } - pub(crate) fn from_bool(value: bool) -> Self { +} +impl From for Dynamic { + fn from(value: bool) -> Self { Self(Union::Bool(value)) } - pub(crate) fn from_int(value: INT) -> Self { +} +impl From for Dynamic { + fn from(value: INT) -> Self { Self(Union::Int(value)) } - #[cfg(not(feature = "no_float"))] - pub(crate) fn from_float(value: FLOAT) -> Self { +} +#[cfg(not(feature = "no_float"))] +impl From for Dynamic { + fn from(value: FLOAT) -> Self { Self(Union::Float(value)) } - pub(crate) fn from_char(value: char) -> Self { +} +impl From for Dynamic { + fn from(value: char) -> Self { Self(Union::Char(value)) } - pub(crate) fn from_string(value: String) -> Self { +} +impl From for Dynamic { + fn from(value: String) -> Self { Self(Union::Str(Box::new(value))) } } +impl From> for Dynamic { + fn from(value: Vec) -> Self { + Self(Union::Array(Box::new( + value.into_iter().map(Dynamic::from).collect(), + ))) + } +} +impl From> for Dynamic { + fn from(value: HashMap) -> Self { + Self(Union::Map(Box::new( + value + .into_iter() + .map(|(k, v)| (k, Dynamic::from(v))) + .collect(), + ))) + } +} /// Private type which ensures that `rhai::Any` and `rhai::AnyExt` can only /// be implemented by this crate. diff --git a/src/api.rs b/src/api.rs index 4bc12510..9377bc68 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,7 +1,7 @@ //! Module that defines the extern API of `Engine`. use crate::any::{Dynamic, Variant}; -use crate::engine::{calc_fn_spec, make_getter, make_setter, Engine, FnAny, Map}; +use crate::engine::{make_getter, make_setter, Engine, Map, State}; use crate::error::ParseError; use crate::fn_call::FuncArgs; use crate::fn_register::RegisterFn; @@ -44,28 +44,22 @@ impl ObjectSetCallback for F {} #[cfg(feature = "sync")] pub trait IteratorCallback: - Fn(&Dynamic) -> Box> + Send + Sync + 'static + Fn(Dynamic) -> Box> + Send + Sync + 'static { } #[cfg(feature = "sync")] -impl Box> + Send + Sync + 'static> IteratorCallback +impl Box> + Send + Sync + 'static> IteratorCallback for F { } #[cfg(not(feature = "sync"))] -pub trait IteratorCallback: Fn(&Dynamic) -> Box> + 'static {} +pub trait IteratorCallback: Fn(Dynamic) -> Box> + 'static {} #[cfg(not(feature = "sync"))] -impl Box> + 'static> IteratorCallback for F {} +impl Box> + 'static> IteratorCallback for F {} /// Engine public API impl Engine { - /// Register a custom function. - pub(crate) fn register_fn_raw(&mut self, fn_name: &str, args: Vec, f: Box) { - self.functions - .insert(calc_fn_spec(fn_name, args.into_iter()), f); - } - /// Register a custom type for use with the `Engine`. /// The type must implement `Clone`. /// @@ -82,7 +76,7 @@ impl Engine { /// fn update(&mut self, offset: i64) { self.field += offset; } /// } /// - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// let mut engine = Engine::new(); @@ -122,7 +116,7 @@ impl Engine { /// fn new() -> Self { TestStruct { field: 1 } } /// } /// - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// let mut engine = Engine::new(); @@ -152,14 +146,8 @@ impl Engine { /// ``` #[cfg(not(feature = "no_object"))] pub fn register_type_with_name(&mut self, name: &str) { - if self.type_names.is_none() { - self.type_names = Some(HashMap::new()); - } - // Add the pretty-print type name into the map self.type_names - .as_mut() - .unwrap() .insert(type_name::().to_string(), name.to_string()); } @@ -188,7 +176,7 @@ impl Engine { /// fn get_field(&mut self) -> i64 { self.field } /// } /// - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// let mut engine = Engine::new(); @@ -230,7 +218,7 @@ impl Engine { /// fn set_field(&mut self, new_val: i64) { self.field = new_val; } /// } /// - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// let mut engine = Engine::new(); @@ -281,7 +269,7 @@ impl Engine { /// fn set_field(&mut self, new_val: i64) { self.field = new_val; } /// } /// - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// let mut engine = Engine::new(); @@ -316,7 +304,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -330,7 +318,7 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn compile(&self, script: &str) -> Result { + pub fn compile(&self, script: &str) -> Result> { self.compile_with_scope(&Scope::new(), script) } @@ -341,7 +329,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # #[cfg(not(feature = "no_optimize"))] /// # { /// use rhai::{Engine, Scope, OptimizationLevel}; @@ -371,7 +359,7 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result { + pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result> { self.compile_with_scope_and_optimization_level(scope, script, self.optimization_level) } @@ -381,22 +369,22 @@ impl Engine { scope: &Scope, script: &str, optimization_level: OptimizationLevel, - ) -> Result { + ) -> Result> { let scripts = [script]; let stream = lex(&scripts); - parse(&mut stream.peekable(), self, scope, optimization_level).map_err(|err| *err) + parse(&mut stream.peekable(), self, scope, optimization_level) } /// Read the contents of a file into a string. #[cfg(not(feature = "no_std"))] - fn read_file(path: PathBuf) -> Result { + fn read_file(path: PathBuf) -> Result> { let mut f = File::open(path.clone()) - .map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?; + .map_err(|err| Box::new(EvalAltResult::ErrorReadingScriptFile(path.clone(), err)))?; let mut contents = String::new(); f.read_to_string(&mut contents) - .map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?; + .map_err(|err| Box::new(EvalAltResult::ErrorReadingScriptFile(path.clone(), err)))?; Ok(contents) } @@ -406,7 +394,7 @@ impl Engine { /// # Example /// /// ```no_run - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -422,7 +410,7 @@ impl Engine { /// # } /// ``` #[cfg(not(feature = "no_std"))] - pub fn compile_file(&self, path: PathBuf) -> Result { + pub fn compile_file(&self, path: PathBuf) -> Result> { self.compile_file_with_scope(&Scope::new(), path) } @@ -433,7 +421,7 @@ impl Engine { /// # Example /// /// ```no_run - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # #[cfg(not(feature = "no_optimize"))] /// # { /// use rhai::{Engine, Scope, OptimizationLevel}; @@ -461,7 +449,7 @@ impl Engine { &self, scope: &Scope, path: PathBuf, - ) -> Result { + ) -> Result> { Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?)) } @@ -473,7 +461,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -489,7 +477,7 @@ impl Engine { /// # } /// ``` #[cfg(not(feature = "no_object"))] - pub fn parse_json(&self, json: &str, has_null: bool) -> Result { + pub fn parse_json(&self, json: &str, has_null: bool) -> Result> { let mut scope = Scope::new(); // Trims the JSON string and add a '#' in front @@ -516,7 +504,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -530,7 +518,7 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn compile_expression(&self, script: &str) -> Result { + pub fn compile_expression(&self, script: &str) -> Result> { self.compile_expression_with_scope(&Scope::new(), script) } @@ -543,7 +531,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # #[cfg(not(feature = "no_optimize"))] /// # { /// use rhai::{Engine, Scope, OptimizationLevel}; @@ -577,12 +565,11 @@ impl Engine { &self, scope: &Scope, script: &str, - ) -> Result { + ) -> Result> { let scripts = [script]; let stream = lex(&scripts); parse_global_expr(&mut stream.peekable(), self, scope, self.optimization_level) - .map_err(|err| *err) } /// Evaluate a script file. @@ -590,7 +577,7 @@ impl Engine { /// # Example /// /// ```no_run - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -601,7 +588,7 @@ impl Engine { /// # } /// ``` #[cfg(not(feature = "no_std"))] - pub fn eval_file(&self, path: PathBuf) -> Result { + pub fn eval_file(&self, path: PathBuf) -> Result> { Self::read_file(path).and_then(|contents| self.eval::(&contents)) } @@ -610,7 +597,7 @@ impl Engine { /// # Example /// /// ```no_run - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Scope}; /// /// let engine = Engine::new(); @@ -629,7 +616,7 @@ impl Engine { &self, scope: &mut Scope, path: PathBuf, - ) -> Result { + ) -> Result> { Self::read_file(path).and_then(|contents| self.eval_with_scope::(scope, &contents)) } @@ -638,7 +625,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -647,7 +634,7 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn eval(&self, script: &str) -> Result { + pub fn eval(&self, script: &str) -> Result> { self.eval_with_scope(&mut Scope::new(), script) } @@ -656,7 +643,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Scope}; /// /// let engine = Engine::new(); @@ -677,7 +664,7 @@ impl Engine { &self, scope: &mut Scope, script: &str, - ) -> Result { + ) -> Result> { // Since the AST will be thrown away afterwards, don't bother to optimize it let ast = self.compile_with_scope_and_optimization_level(scope, script, OptimizationLevel::None)?; @@ -689,7 +676,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -698,7 +685,10 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn eval_expression(&self, script: &str) -> Result { + pub fn eval_expression( + &self, + script: &str, + ) -> Result> { self.eval_expression_with_scope(&mut Scope::new(), script) } @@ -707,7 +697,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Scope}; /// /// let engine = Engine::new(); @@ -724,7 +714,7 @@ impl Engine { &self, scope: &mut Scope, script: &str, - ) -> Result { + ) -> Result> { let scripts = [script]; let stream = lex(&scripts); // Since the AST will be thrown away afterwards, don't bother to optimize it @@ -737,7 +727,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -750,7 +740,7 @@ impl Engine { /// # Ok(()) /// # } /// ``` - pub fn eval_ast(&self, ast: &AST) -> Result { + pub fn eval_ast(&self, ast: &AST) -> Result> { self.eval_ast_with_scope(&mut Scope::new(), ast) } @@ -759,7 +749,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Scope}; /// /// let engine = Engine::new(); @@ -787,15 +777,16 @@ impl Engine { &self, scope: &mut Scope, ast: &AST, - ) -> Result { - let result = self - .eval_ast_with_scope_raw(scope, ast) - .map_err(|err| *err)?; + ) -> Result> { + let result = self.eval_ast_with_scope_raw(scope, ast)?; let return_type = self.map_type_name(result.type_name()); return result.try_cast::().ok_or_else(|| { - EvalAltResult::ErrorMismatchOutputType(return_type.to_string(), Position::none()) + Box::new(EvalAltResult::ErrorMismatchOutputType( + return_type.to_string(), + Position::none(), + )) }); } @@ -804,10 +795,12 @@ impl Engine { scope: &mut Scope, ast: &AST, ) -> Result> { + let mut state = State::new(); + ast.0 .iter() - .try_fold(Dynamic::from_unit(), |_, stmt| { - self.eval_stmt(scope, Some(ast.1.as_ref()), stmt, 0) + .try_fold(().into(), |_, stmt| { + self.eval_stmt(scope, &mut state, ast.1.as_ref(), stmt, 0) }) .or_else(|err| match *err { EvalAltResult::Return(out, _) => Ok(out), @@ -818,7 +811,7 @@ impl Engine { /// Evaluate a file, but throw away the result and only return error (if any). /// Useful for when you don't need the result, but still need to keep track of possible errors. #[cfg(not(feature = "no_std"))] - pub fn consume_file(&self, path: PathBuf) -> Result<(), EvalAltResult> { + pub fn consume_file(&self, path: PathBuf) -> Result<(), Box> { Self::read_file(path).and_then(|contents| self.consume(&contents)) } @@ -829,19 +822,23 @@ impl Engine { &self, scope: &mut Scope, path: PathBuf, - ) -> Result<(), EvalAltResult> { + ) -> Result<(), Box> { Self::read_file(path).and_then(|contents| self.consume_with_scope(scope, &contents)) } /// Evaluate a string, but throw away the result and only return error (if any). /// Useful for when you don't need the result, but still need to keep track of possible errors. - pub fn consume(&self, script: &str) -> Result<(), EvalAltResult> { + pub fn consume(&self, script: &str) -> Result<(), Box> { self.consume_with_scope(&mut Scope::new(), script) } /// Evaluate a string with own scope, but throw away the result and only return error (if any). /// Useful for when you don't need the result, but still need to keep track of possible errors. - pub fn consume_with_scope(&self, scope: &mut Scope, script: &str) -> Result<(), EvalAltResult> { + pub fn consume_with_scope( + &self, + scope: &mut Scope, + script: &str, + ) -> Result<(), Box> { let scripts = [script]; let stream = lex(&scripts); @@ -852,7 +849,7 @@ impl Engine { /// Evaluate an AST, but throw away the result and only return error (if any). /// Useful for when you don't need the result, but still need to keep track of possible errors. - pub fn consume_ast(&self, ast: &AST) -> Result<(), EvalAltResult> { + pub fn consume_ast(&self, ast: &AST) -> Result<(), Box> { self.consume_ast_with_scope(&mut Scope::new(), ast) } @@ -862,16 +859,18 @@ impl Engine { &self, scope: &mut Scope, ast: &AST, - ) -> Result<(), EvalAltResult> { + ) -> Result<(), Box> { + let mut state = State::new(); + ast.0 .iter() - .try_fold(Dynamic::from_unit(), |_, stmt| { - self.eval_stmt(scope, Some(ast.1.as_ref()), stmt, 0) + .try_fold(().into(), |_, stmt| { + self.eval_stmt(scope, &mut state, ast.1.as_ref(), stmt, 0) }) .map_or_else( |err| match *err { EvalAltResult::Return(_, _) => Ok(()), - err => Err(err), + err => Err(Box::new(err)), }, |_| Ok(()), ) @@ -882,7 +881,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # #[cfg(not(feature = "no_function"))] /// # { /// use rhai::{Engine, Scope}; @@ -919,21 +918,26 @@ impl Engine { ast: &AST, name: &str, args: A, - ) -> Result { + ) -> Result> { let mut arg_values = args.into_vec(); let mut args: Vec<_> = arg_values.iter_mut().collect(); - let fn_lib = Some(ast.1.as_ref()); + let fn_lib = ast.1.as_ref(); let pos = Position::none(); - let result = self - .call_fn_raw(Some(scope), fn_lib, name, &mut args, None, pos, 0) - .map_err(|err| *err)?; + let fn_def = fn_lib + .get_function(name, args.len()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorFunctionNotFound(name.to_string(), pos)))?; + + let result = self.call_fn_from_lib(Some(scope), fn_lib, fn_def, &mut args, pos, 0)?; let return_type = self.map_type_name(result.type_name()); - return result - .try_cast() - .ok_or_else(|| EvalAltResult::ErrorMismatchOutputType(return_type.into(), pos)); + return result.try_cast().ok_or_else(|| { + Box::new(EvalAltResult::ErrorMismatchOutputType( + return_type.into(), + pos, + )) + }); } /// Optimize the `AST` with constants defined in an external Scope. @@ -967,7 +971,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # use std::sync::RwLock; /// # use std::sync::Arc; /// use rhai::Engine; @@ -988,14 +992,14 @@ impl Engine { /// ``` #[cfg(feature = "sync")] pub fn on_print(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) { - self.on_print = Some(Box::new(callback)); + self.print = Box::new(callback); } /// Override default action of `print` (print to stdout using `println!`) /// /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # use std::sync::RwLock; /// # use std::sync::Arc; /// use rhai::Engine; @@ -1016,7 +1020,7 @@ impl Engine { /// ``` #[cfg(not(feature = "sync"))] pub fn on_print(&mut self, callback: impl Fn(&str) + 'static) { - self.on_print = Some(Box::new(callback)); + self.print = Box::new(callback); } /// Override default action of `debug` (print to stdout using `println!`) @@ -1024,7 +1028,7 @@ impl Engine { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # use std::sync::RwLock; /// # use std::sync::Arc; /// use rhai::Engine; @@ -1045,14 +1049,14 @@ impl Engine { /// ``` #[cfg(feature = "sync")] pub fn on_debug(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) { - self.on_debug = Some(Box::new(callback)); + self.debug = Box::new(callback); } /// Override default action of `debug` (print to stdout using `println!`) /// /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # use std::sync::RwLock; /// # use std::sync::Arc; /// use rhai::Engine; @@ -1073,6 +1077,6 @@ impl Engine { /// ``` #[cfg(not(feature = "sync"))] pub fn on_debug(&mut self, callback: impl Fn(&str) + 'static) { - self.on_debug = Some(Box::new(callback)); + self.debug = Box::new(callback); } } diff --git a/src/builtin.rs b/src/builtin.rs deleted file mode 100644 index 428de9b7..00000000 --- a/src/builtin.rs +++ /dev/null @@ -1,1238 +0,0 @@ -//! Helper module that allows registration of the _core library_ and -//! _standard library_ of utility functions. - -use crate::any::{Dynamic, Variant}; -use crate::engine::{Engine, FUNC_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT}; -use crate::fn_register::{RegisterDynamicFn, RegisterFn, RegisterResultFn}; -use crate::parser::INT; -use crate::result::EvalAltResult; -use crate::token::Position; - -#[cfg(not(feature = "no_index"))] -use crate::engine::Array; - -#[cfg(not(feature = "no_object"))] -use crate::engine::Map; - -#[cfg(not(feature = "no_float"))] -use crate::parser::FLOAT; - -use num_traits::{ - identities::Zero, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, - CheckedShr, CheckedSub, -}; - -use crate::stdlib::{ - boxed::Box, - fmt::{Debug, Display}, - format, - ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Range, Rem, Shl, Shr, Sub}, - string::{String, ToString}, - vec::Vec, - {i32, i64, u32}, -}; - -#[cfg(not(feature = "no_std"))] -use crate::stdlib::time::Instant; - -#[cfg(feature = "only_i32")] -const MAX_INT: INT = i32::MAX; -#[cfg(not(feature = "only_i32"))] -const MAX_INT: INT = i64::MAX; - -macro_rules! reg_op { - ($self:expr, $x:expr, $op:expr, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $y, y: $y)->$y); - )* - ) -} - -#[cfg(not(feature = "unchecked"))] -macro_rules! reg_op_result { - ($self:expr, $x:expr, $op:expr, $( $y:ty ),*) => ( - $( - $self.register_result_fn($x, $op as fn(x: $y, y: $y)->Result<$y,EvalAltResult>); - )* - ) -} - -#[cfg(not(feature = "unchecked"))] -macro_rules! reg_op_result1 { - ($self:expr, $x:expr, $op:expr, $v:ty, $( $y:ty ),*) => ( - $( - $self.register_result_fn($x, $op as fn(x: $y, y: $v)->Result<$y,EvalAltResult>); - )* - ) -} - -macro_rules! reg_cmp { - ($self:expr, $x:expr, $op:expr, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $y, y: $y)->bool); - )* - ) -} - -// Comparison operators -fn lt(x: T, y: T) -> bool { - x < y -} -fn lte(x: T, y: T) -> bool { - x <= y -} -fn gt(x: T, y: T) -> bool { - x > y -} -fn gte(x: T, y: T) -> bool { - x >= y -} -fn eq(x: T, y: T) -> bool { - x == y -} -fn ne(x: T, y: T) -> bool { - x != y -} - -impl Engine { - /// Register the core built-in library. - pub(crate) fn register_core_lib(&mut self) { - // Checked add - #[cfg(not(feature = "unchecked"))] - fn add(x: T, y: T) -> Result { - x.checked_add(&y).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Addition overflow: {} + {}", x, y), - Position::none(), - ) - }) - } - // Checked subtract - #[cfg(not(feature = "unchecked"))] - fn sub(x: T, y: T) -> Result { - x.checked_sub(&y).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Subtraction underflow: {} - {}", x, y), - Position::none(), - ) - }) - } - // Checked multiply - #[cfg(not(feature = "unchecked"))] - fn mul(x: T, y: T) -> Result { - x.checked_mul(&y).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Multiplication overflow: {} * {}", x, y), - Position::none(), - ) - }) - } - // Checked divide - #[cfg(not(feature = "unchecked"))] - fn div(x: T, y: T) -> Result - where - T: Display + CheckedDiv + PartialEq + Zero, - { - // Detect division by zero - if y == T::zero() { - return Err(EvalAltResult::ErrorArithmetic( - format!("Division by zero: {} / {}", x, y), - Position::none(), - )); - } - - x.checked_div(&y).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Division overflow: {} / {}", x, y), - Position::none(), - ) - }) - } - // Checked negative - e.g. -(i32::MIN) will overflow i32::MAX - #[cfg(not(feature = "unchecked"))] - fn neg(x: T) -> Result { - x.checked_neg().ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Negation overflow: -{}", x), - Position::none(), - ) - }) - } - // Checked absolute - #[cfg(not(feature = "unchecked"))] - fn abs(x: T) -> Result { - // FIX - We don't use Signed::abs() here because, contrary to documentation, it panics - // when the number is ::MIN instead of returning ::MIN itself. - if x >= ::zero() { - Ok(x) - } else { - x.checked_neg().ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Negation overflow: -{}", x), - Position::none(), - ) - }) - } - } - // Unchecked add - may panic on overflow - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn add_u(x: T, y: T) -> ::Output { - x + y - } - // Unchecked subtract - may panic on underflow - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn sub_u(x: T, y: T) -> ::Output { - x - y - } - // Unchecked multiply - may panic on overflow - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn mul_u(x: T, y: T) -> ::Output { - x * y - } - // Unchecked divide - may panic when dividing by zero - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn div_u(x: T, y: T) -> ::Output { - x / y - } - // Unchecked negative - may panic on overflow - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn neg_u(x: T) -> ::Output { - -x - } - // Unchecked absolute - may panic on overflow - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn abs_u(x: T) -> ::Output - where - T: Neg + PartialOrd + Default + Into<::Output>, - { - // Numbers should default to zero - if x < Default::default() { - -x - } else { - x.into() - } - } - - // Logic operators - fn and(x: bool, y: bool) -> bool { - x && y - } - fn or(x: bool, y: bool) -> bool { - x || y - } - fn not(x: bool) -> bool { - !x - } - - // Bit operators - fn binary_and(x: T, y: T) -> ::Output { - x & y - } - fn binary_or(x: T, y: T) -> ::Output { - x | y - } - fn binary_xor(x: T, y: T) -> ::Output { - x ^ y - } - - // Checked left-shift - #[cfg(not(feature = "unchecked"))] - fn shl(x: T, y: INT) -> Result { - // Cannot shift by a negative number of bits - if y < 0 { - return Err(EvalAltResult::ErrorArithmetic( - format!("Left-shift by a negative number: {} << {}", x, y), - Position::none(), - )); - } - - CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Left-shift by too many bits: {} << {}", x, y), - Position::none(), - ) - }) - } - // Checked right-shift - #[cfg(not(feature = "unchecked"))] - fn shr(x: T, y: INT) -> Result { - // Cannot shift by a negative number of bits - if y < 0 { - return Err(EvalAltResult::ErrorArithmetic( - format!("Right-shift by a negative number: {} >> {}", x, y), - Position::none(), - )); - } - - CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Right-shift by too many bits: {} % {}", x, y), - Position::none(), - ) - }) - } - // Unchecked left-shift - may panic if shifting by a negative number of bits - #[cfg(feature = "unchecked")] - fn shl_u>(x: T, y: T) -> >::Output { - x.shl(y) - } - // Unchecked right-shift - may panic if shifting by a negative number of bits - #[cfg(feature = "unchecked")] - fn shr_u>(x: T, y: T) -> >::Output { - x.shr(y) - } - // Checked modulo - #[cfg(not(feature = "unchecked"))] - fn modulo(x: T, y: T) -> Result { - x.checked_rem(&y).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Modulo division by zero or overflow: {} % {}", x, y), - Position::none(), - ) - }) - } - // Unchecked modulo - may panic if dividing by zero - #[cfg(any(feature = "unchecked", not(feature = "no_float")))] - fn modulo_u(x: T, y: T) -> ::Output { - x % y - } - // Checked power - #[cfg(not(feature = "unchecked"))] - fn pow_i_i(x: INT, y: INT) -> Result { - #[cfg(not(feature = "only_i32"))] - { - if y > (u32::MAX as INT) { - Err(EvalAltResult::ErrorArithmetic( - format!("Integer raised to too large an index: {} ~ {}", x, y), - Position::none(), - )) - } else if y < 0 { - Err(EvalAltResult::ErrorArithmetic( - format!("Integer raised to a negative index: {} ~ {}", x, y), - Position::none(), - )) - } else { - x.checked_pow(y as u32).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Power overflow: {} ~ {}", x, y), - Position::none(), - ) - }) - } - } - - #[cfg(feature = "only_i32")] - { - if y < 0 { - Err(EvalAltResult::ErrorArithmetic( - format!("Integer raised to a negative index: {} ~ {}", x, y), - Position::none(), - )) - } else { - x.checked_pow(y as u32).ok_or_else(|| { - EvalAltResult::ErrorArithmetic( - format!("Power overflow: {} ~ {}", x, y), - Position::none(), - ) - }) - } - } - } - // Unchecked integer power - may panic on overflow or if the power index is too high (> u32::MAX) - #[cfg(feature = "unchecked")] - fn pow_i_i_u(x: INT, y: INT) -> INT { - x.pow(y as u32) - } - // Floating-point power - always well-defined - #[cfg(not(feature = "no_float"))] - fn pow_f_f(x: FLOAT, y: FLOAT) -> FLOAT { - x.powf(y) - } - // Checked power - #[cfg(not(feature = "unchecked"))] - #[cfg(not(feature = "no_float"))] - fn pow_f_i(x: FLOAT, y: INT) -> Result { - // Raise to power that is larger than an i32 - if y > (i32::MAX as INT) { - return Err(EvalAltResult::ErrorArithmetic( - format!("Number raised to too large an index: {} ~ {}", x, y), - Position::none(), - )); - } - - Ok(x.powi(y as i32)) - } - // Unchecked power - may be incorrect if the power index is too high (> i32::MAX) - #[cfg(feature = "unchecked")] - #[cfg(not(feature = "no_float"))] - fn pow_f_i_u(x: FLOAT, y: INT) -> FLOAT { - x.powi(y as i32) - } - - #[cfg(not(feature = "unchecked"))] - { - reg_op_result!(self, "+", add, INT); - reg_op_result!(self, "-", sub, INT); - reg_op_result!(self, "*", mul, INT); - reg_op_result!(self, "/", div, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_op_result!(self, "+", add, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op_result!(self, "-", sub, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op_result!(self, "*", mul, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op_result!(self, "/", div, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - } - - #[cfg(feature = "unchecked")] - { - reg_op!(self, "+", add_u, INT); - reg_op!(self, "-", sub_u, INT); - reg_op!(self, "*", mul_u, INT); - reg_op!(self, "/", div_u, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_op!(self, "+", add_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "-", sub_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "*", mul_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "/", div_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - } - - #[cfg(not(feature = "no_float"))] - { - reg_op!(self, "+", add_u, f32, f64); - reg_op!(self, "-", sub_u, f32, f64); - reg_op!(self, "*", mul_u, f32, f64); - reg_op!(self, "/", div_u, f32, f64); - } - - { - reg_cmp!(self, "<", lt, INT, String, char); - reg_cmp!(self, "<=", lte, INT, String, char); - reg_cmp!(self, ">", gt, INT, String, char); - reg_cmp!(self, ">=", gte, INT, String, char); - reg_cmp!(self, "==", eq, INT, String, char, bool); - reg_cmp!(self, "!=", ne, INT, String, char, bool); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_cmp!(self, "<", lt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_cmp!(self, "<=", lte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_cmp!(self, ">", gt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_cmp!(self, ">=", gte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_cmp!(self, "==", eq, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_cmp!(self, "!=", ne, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - - #[cfg(not(feature = "no_float"))] - { - reg_cmp!(self, "<", lt, f32, f64); - reg_cmp!(self, "<=", lte, f32, f64); - reg_cmp!(self, ">", gt, f32, f64); - reg_cmp!(self, ">=", gte, f32, f64); - reg_cmp!(self, "==", eq, f32, f64); - reg_cmp!(self, "!=", ne, f32, f64); - } - } - - // `&&` and `||` are treated specially as they short-circuit. - // They are implemented as special `Expr` Instants, not function calls. - //reg_op!(self, "||", or, bool); - //reg_op!(self, "&&", and, bool); - - reg_op!(self, "|", or, bool); - reg_op!(self, "&", and, bool); - - reg_op!(self, "|", binary_or, INT); - reg_op!(self, "&", binary_and, INT); - reg_op!(self, "^", binary_xor, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_op!(self, "|", binary_or, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "&", binary_and, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "^", binary_xor, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - - #[cfg(not(feature = "unchecked"))] - { - reg_op_result1!(self, "<<", shl, INT, INT); - reg_op_result1!(self, ">>", shr, INT, INT); - reg_op_result!(self, "%", modulo, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_op_result1!( - self, "<<", shl, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128 - ); - reg_op_result1!( - self, ">>", shr, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128 - ); - reg_op_result!(self, "%", modulo, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - } - - #[cfg(feature = "unchecked")] - { - reg_op!(self, "<<", shl_u, INT, INT); - reg_op!(self, ">>", shr_u, INT, INT); - reg_op!(self, "%", modulo_u, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_op!(self, "<<", shl_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, ">>", shr_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - reg_op!(self, "%", modulo_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - } - - #[cfg(not(feature = "no_float"))] - { - reg_op!(self, "%", modulo_u, f32, f64); - self.register_fn("~", pow_f_f); - } - - #[cfg(not(feature = "unchecked"))] - { - self.register_result_fn("~", pow_i_i); - - #[cfg(not(feature = "no_float"))] - self.register_result_fn("~", pow_f_i); - } - - #[cfg(feature = "unchecked")] - { - self.register_fn("~", pow_i_i_u); - - #[cfg(not(feature = "no_float"))] - self.register_fn("~", pow_f_i_u); - } - - { - macro_rules! reg_un { - ($self:expr, $x:expr, $op:expr, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $y)->$y); - )* - ) - } - - #[cfg(not(feature = "unchecked"))] - macro_rules! reg_un_result { - ($self:expr, $x:expr, $op:expr, $( $y:ty ),*) => ( - $( - $self.register_result_fn($x, $op as fn(x: $y)->Result<$y,EvalAltResult>); - )* - ) - } - - #[cfg(not(feature = "unchecked"))] - { - reg_un_result!(self, "-", neg, INT); - reg_un_result!(self, "abs", abs, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_un_result!(self, "-", neg, i8, i16, i32, i64); - reg_un_result!(self, "abs", abs, i8, i16, i32, i64); - } - } - - #[cfg(feature = "unchecked")] - { - reg_un!(self, "-", neg_u, INT); - reg_un!(self, "abs", abs_u, INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_un!(self, "-", neg_u, i8, i16, i32, i64); - reg_un!(self, "abs", abs_u, i8, i16, i32, i64); - } - } - - #[cfg(not(feature = "no_float"))] - { - reg_un!(self, "-", neg_u, f32, f64); - reg_un!(self, "abs", abs_u, f32, f64); - } - - reg_un!(self, "!", not, bool); - } - - self.register_fn("+", |x: String, y: String| x + &y); // String + String - self.register_fn("==", |_: (), _: ()| true); // () == () - - // Register print and debug - fn to_debug(x: T) -> String { - format!("{:?}", x) - } - fn to_string(x: T) -> String { - format!("{}", x) - } - - { - macro_rules! reg_fn1 { - ($self:expr, $x:expr, $op:expr, $r:ty, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $y)->$r); - )* - ) - } - - reg_fn1!(self, KEYWORD_PRINT, to_string, String, INT, bool); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, INT, bool); - reg_fn1!(self, KEYWORD_PRINT, to_string, String, char, String); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, char, String); - self.register_fn(KEYWORD_PRINT, || "".to_string()); - self.register_fn(KEYWORD_PRINT, |_: ()| "".to_string()); - self.register_fn(FUNC_TO_STRING, |_: ()| "".to_string()); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, INT, bool, ()); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, char, String); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_fn1!(self, KEYWORD_PRINT, to_string, String, i8, u8, i16, u16); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, i8, u8, i16, u16); - reg_fn1!(self, KEYWORD_PRINT, to_string, String, i32, i64, u32, u64); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, i32, i64, u32, u64); - reg_fn1!(self, KEYWORD_PRINT, to_string, String, i128, u128); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, i128, u128); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, i8, u8, i16, u16); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, i32, i64, u32, u64); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, i128, u128); - } - - #[cfg(not(feature = "no_float"))] - { - reg_fn1!(self, KEYWORD_PRINT, to_string, String, f32, f64); - reg_fn1!(self, FUNC_TO_STRING, to_string, String, f32, f64); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, f32, f64); - } - - #[cfg(not(feature = "no_index"))] - { - reg_fn1!(self, KEYWORD_PRINT, to_debug, String, Array); - reg_fn1!(self, FUNC_TO_STRING, to_debug, String, Array); - reg_fn1!(self, KEYWORD_DEBUG, to_debug, String, Array); - - // Register array iterator - self.register_iterator::(|a: &Dynamic| { - Box::new(a.downcast_ref::().unwrap().clone().into_iter()) - as Box> - }); - } - - #[cfg(not(feature = "no_object"))] - { - self.register_fn(KEYWORD_PRINT, |x: &mut Map| format!("#{:?}", x)); - self.register_fn(FUNC_TO_STRING, |x: &mut Map| format!("#{:?}", x)); - self.register_fn(KEYWORD_DEBUG, |x: &mut Map| format!("#{:?}", x)); - - // Register map access functions - #[cfg(not(feature = "no_index"))] - self.register_fn("keys", |map: Map| { - map.iter() - .map(|(k, _)| Dynamic::from(k.clone())) - .collect::>() - }); - - #[cfg(not(feature = "no_index"))] - self.register_fn("values", |map: Map| { - map.into_iter().map(|(_, v)| v).collect::>() - }); - } - } - - // Register range function - fn reg_range(engine: &mut Engine) - where - Range: Iterator, - { - engine.register_iterator::, _>(|source: &Dynamic| { - Box::new( - source - .downcast_ref::>() - .cloned() - .unwrap() - .map(|x| x.into_dynamic()), - ) as Box> - }); - } - - reg_range::(self); - self.register_fn("range", |i1: INT, i2: INT| (i1..i2)); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - macro_rules! reg_range { - ($self:expr, $x:expr, $( $y:ty ),*) => ( - $( - reg_range::<$y>(self); - $self.register_fn($x, (|x: $y, y: $y| x..y) as fn(x: $y, y: $y)->Range<$y>); - )* - ) - } - - reg_range!(self, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - - // Register range function with step - #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] - struct StepRange(T, T, T) - where - for<'a> &'a T: Add<&'a T, Output = T>, - T: Variant + Clone + PartialOrd; - - impl Iterator for StepRange - where - for<'a> &'a T: Add<&'a T, Output = T>, - T: Variant + Clone + PartialOrd, - { - type Item = T; - - fn next(&mut self) -> Option { - if self.0 < self.1 { - let v = self.0.clone(); - self.0 = &v + &self.2; - Some(v) - } else { - None - } - } - } - - fn reg_step(engine: &mut Engine) - where - for<'a> &'a T: Add<&'a T, Output = T>, - T: Variant + Clone + PartialOrd, - StepRange: Iterator, - { - engine.register_iterator::, _>(|source: &Dynamic| { - Box::new( - source - .downcast_ref::>() - .cloned() - .unwrap() - .map(|x| x.into_dynamic()), - ) as Box> - }); - } - - reg_step::(self); - self.register_fn("range", |i1: INT, i2: INT, step: INT| { - StepRange(i1, i2, step) - }); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - macro_rules! reg_step { - ($self:expr, $x:expr, $( $y:ty ),*) => ( - $( - reg_step::<$y>(self); - $self.register_fn($x, (|x: $y, y: $y, step: $y| StepRange(x,y,step)) as fn(x: $y, y: $y, step: $y)->StepRange<$y>); - )* - ) - } - - reg_step!(self, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); - } - } -} - -macro_rules! reg_fn2x { - ($self:expr, $x:expr, $op:expr, $v:ty, $r:ty, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $v, y: $y)->$r); - )* - ) -} - -macro_rules! reg_fn2y { - ($self:expr, $x:expr, $op:expr, $v:ty, $r:ty, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(y: $y, x: $v)->$r); - )* - ) -} - -/// Register the built-in library. -impl Engine { - pub fn register_stdlib(&mut self) { - #[cfg(not(feature = "no_float"))] - { - // Advanced math functions - self.register_fn("sin", |x: FLOAT| x.to_radians().sin()); - self.register_fn("cos", |x: FLOAT| x.to_radians().cos()); - self.register_fn("tan", |x: FLOAT| x.to_radians().tan()); - self.register_fn("sinh", |x: FLOAT| x.to_radians().sinh()); - self.register_fn("cosh", |x: FLOAT| x.to_radians().cosh()); - self.register_fn("tanh", |x: FLOAT| x.to_radians().tanh()); - self.register_fn("asin", |x: FLOAT| x.asin().to_degrees()); - self.register_fn("acos", |x: FLOAT| x.acos().to_degrees()); - self.register_fn("atan", |x: FLOAT| x.atan().to_degrees()); - self.register_fn("asinh", |x: FLOAT| x.asinh().to_degrees()); - self.register_fn("acosh", |x: FLOAT| x.acosh().to_degrees()); - self.register_fn("atanh", |x: FLOAT| x.atanh().to_degrees()); - self.register_fn("sqrt", |x: FLOAT| x.sqrt()); - self.register_fn("exp", |x: FLOAT| x.exp()); - self.register_fn("ln", |x: FLOAT| x.ln()); - self.register_fn("log", |x: FLOAT, base: FLOAT| x.log(base)); - self.register_fn("log10", |x: FLOAT| x.log10()); - self.register_fn("floor", |x: FLOAT| x.floor()); - self.register_fn("ceiling", |x: FLOAT| x.ceil()); - self.register_fn("round", |x: FLOAT| x.ceil()); - self.register_fn("int", |x: FLOAT| x.trunc()); - self.register_fn("fraction", |x: FLOAT| x.fract()); - self.register_fn("is_nan", |x: FLOAT| x.is_nan()); - self.register_fn("is_finite", |x: FLOAT| x.is_finite()); - self.register_fn("is_infinite", |x: FLOAT| x.is_infinite()); - - // Register conversion functions - self.register_fn("to_float", |x: INT| x as FLOAT); - self.register_fn("to_float", |x: f32| x as FLOAT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - self.register_fn("to_float", |x: i8| x as FLOAT); - self.register_fn("to_float", |x: u8| x as FLOAT); - self.register_fn("to_float", |x: i16| x as FLOAT); - self.register_fn("to_float", |x: u16| x as FLOAT); - self.register_fn("to_float", |x: i32| x as FLOAT); - self.register_fn("to_float", |x: u32| x as FLOAT); - self.register_fn("to_float", |x: i64| x as FLOAT); - self.register_fn("to_float", |x: u64| x as FLOAT); - self.register_fn("to_float", |x: i128| x as FLOAT); - self.register_fn("to_float", |x: u128| x as FLOAT); - } - } - - self.register_fn("to_int", |ch: char| ch as INT); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - self.register_fn("to_int", |x: i8| x as INT); - self.register_fn("to_int", |x: u8| x as INT); - self.register_fn("to_int", |x: i16| x as INT); - self.register_fn("to_int", |x: u16| x as INT); - } - - #[cfg(not(feature = "only_i32"))] - { - self.register_fn("to_int", |x: i32| x as INT); - self.register_fn("to_int", |x: u64| x as INT); - - #[cfg(feature = "only_i64")] - self.register_fn("to_int", |x: u32| x as INT); - } - - #[cfg(not(feature = "no_float"))] - { - #[cfg(not(feature = "unchecked"))] - { - self.register_result_fn("to_int", |x: f32| { - if x > (MAX_INT as f32) { - return Err(EvalAltResult::ErrorArithmetic( - format!("Integer overflow: to_int({})", x), - Position::none(), - )); - } - - Ok(x.trunc() as INT) - }); - self.register_result_fn("to_int", |x: FLOAT| { - if x > (MAX_INT as FLOAT) { - return Err(EvalAltResult::ErrorArithmetic( - format!("Integer overflow: to_int({})", x), - Position::none(), - )); - } - - Ok(x.trunc() as INT) - }); - } - - #[cfg(feature = "unchecked")] - { - self.register_fn("to_int", |x: f32| x as INT); - self.register_fn("to_int", |x: f64| x as INT); - } - } - - #[cfg(not(feature = "no_index"))] - { - macro_rules! reg_fn3 { - ($self:expr, $x:expr, $op:expr, $v:ty, $w:ty, $r:ty, $( $y:ty ),*) => ( - $( - $self.register_fn($x, $op as fn(x: $v, y: $w, z: $y)->$r); - )* - ) - } - - // Register array utility functions - fn push(list: &mut Array, item: T) { - list.push(Dynamic::from(item)); - } - fn ins(list: &mut Array, position: INT, item: T) { - if position <= 0 { - list.insert(0, Dynamic::from(item)); - } else if (position as usize) >= list.len() - 1 { - push(list, item); - } else { - list.insert(position as usize, Dynamic::from(item)); - } - } - fn pad(list: &mut Array, len: INT, item: T) { - if len >= 0 { - while list.len() < len as usize { - push(list, item.clone()); - } - } - } - - reg_fn2x!(self, "push", push, &mut Array, (), INT, bool, char); - reg_fn2x!(self, "push", push, &mut Array, (), String, Array, ()); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), INT, bool, char); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), String, Array, ()); - reg_fn3!(self, "insert", ins, &mut Array, INT, (), String, Array, ()); - - self.register_fn("append", |list: &mut Array, array: Array| { - list.extend(array) - }); - self.register_fn("+", |mut list: Array, array: Array| { - list.extend(array); - list - }); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_fn2x!(self, "push", push, &mut Array, (), i8, u8, i16, u16); - reg_fn2x!(self, "push", push, &mut Array, (), i32, i64, u32, u64); - reg_fn2x!(self, "push", push, &mut Array, (), i128, u128); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), i8, u8, i16, u16); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), i32, u32, i64, u64); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), i128, u128); - reg_fn3!(self, "insert", ins, &mut Array, INT, (), i8, u8, i16, u16); - reg_fn3!(self, "insert", ins, &mut Array, INT, (), i32, i64, u32, u64); - reg_fn3!(self, "insert", ins, &mut Array, INT, (), i128, u128); - } - - #[cfg(not(feature = "no_float"))] - { - reg_fn2x!(self, "push", push, &mut Array, (), f32, f64); - reg_fn3!(self, "pad", pad, &mut Array, INT, (), f32, f64); - reg_fn3!(self, "insert", ins, &mut Array, INT, (), f32, f64); - } - - self.register_dynamic_fn("pop", |list: &mut Array| { - list.pop().unwrap_or_else(|| Dynamic::from_unit()) - }); - self.register_dynamic_fn("shift", |list: &mut Array| { - if !list.is_empty() { - Dynamic::from_unit() - } else { - list.remove(0) - } - }); - self.register_dynamic_fn("remove", |list: &mut Array, len: INT| { - if len < 0 || (len as usize) >= list.len() { - Dynamic::from_unit() - } else { - list.remove(len as usize) - } - }); - self.register_fn("len", |list: &mut Array| list.len() as INT); - self.register_fn("clear", |list: &mut Array| list.clear()); - self.register_fn("truncate", |list: &mut Array, len: INT| { - if len >= 0 { - list.truncate(len as usize); - } - }); - } - - // Register map functions - #[cfg(not(feature = "no_object"))] - { - self.register_fn("has", |map: &mut Map, prop: String| map.contains_key(&prop)); - self.register_fn("len", |map: &mut Map| map.len() as INT); - self.register_fn("clear", |map: &mut Map| map.clear()); - self.register_dynamic_fn("remove", |x: &mut Map, name: String| { - x.remove(&name).unwrap_or_else(|| Dynamic::from_unit()) - }); - self.register_fn("mixin", |map1: &mut Map, map2: Map| { - map2.into_iter().for_each(|(key, value)| { - map1.insert(key, value); - }); - }); - self.register_fn("+", |mut map1: Map, map2: Map| { - map2.into_iter().for_each(|(key, value)| { - map1.insert(key, value); - }); - map1 - }); - } - - // Register string concatenate functions - fn prepend(x: T, y: String) -> String { - format!("{}{}", x, y) - } - fn append(x: String, y: T) -> String { - format!("{}{}", x, y) - } - - reg_fn2x!(self, "+", append, String, String, INT, bool, char); - self.register_fn("+", |x: String, _: ()| x); - - reg_fn2y!(self, "+", prepend, String, String, INT, bool, char); - self.register_fn("+", |_: (), y: String| y); - - #[cfg(not(feature = "only_i32"))] - #[cfg(not(feature = "only_i64"))] - { - reg_fn2x!( - self, "+", append, String, String, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128 - ); - reg_fn2y!( - self, "+", prepend, String, String, i8, u8, i16, u16, i32, i64, u32, u64, i128, - u128 - ); - } - - #[cfg(not(feature = "no_float"))] - { - reg_fn2x!(self, "+", append, String, String, f32, f64); - reg_fn2y!(self, "+", prepend, String, String, f32, f64); - } - - #[cfg(not(feature = "no_index"))] - { - self.register_fn("+", |x: String, y: Array| format!("{}{:?}", x, y)); - self.register_fn("+", |x: Array, y: String| format!("{:?}{}", x, y)); - } - - // Register string utility functions - fn sub_string(s: &mut String, start: INT, len: INT) -> String { - let offset = if s.is_empty() || len <= 0 { - return "".to_string(); - } else if start < 0 { - 0 - } else if (start as usize) >= s.chars().count() { - return "".to_string(); - } else { - start as usize - }; - - let chars: Vec<_> = s.chars().collect(); - - let len = if offset + (len as usize) > chars.len() { - chars.len() - offset - } else { - len as usize - }; - - chars[offset..][..len].into_iter().collect::() - } - - fn crop_string(s: &mut String, start: INT, len: INT) { - let offset = if s.is_empty() || len <= 0 { - s.clear(); - return; - } else if start < 0 { - 0 - } else if (start as usize) >= s.chars().count() { - s.clear(); - return; - } else { - start as usize - }; - - let chars: Vec<_> = s.chars().collect(); - - let len = if offset + (len as usize) > chars.len() { - chars.len() - offset - } else { - len as usize - }; - - s.clear(); - - chars[offset..][..len] - .into_iter() - .for_each(|&ch| s.push(ch)); - } - - self.register_fn("len", |s: &mut String| s.chars().count() as INT); - self.register_fn("contains", |s: &mut String, ch: char| s.contains(ch)); - self.register_fn("contains", |s: &mut String, find: String| s.contains(&find)); - self.register_fn("index_of", |s: &mut String, ch: char, start: INT| { - let start = if start < 0 { - 0 - } else if (start as usize) >= s.chars().count() { - return -1 as INT; - } else { - s.chars().take(start as usize).collect::().len() - }; - - s[start..] - .find(ch) - .map(|index| s[0..start + index].chars().count() as INT) - .unwrap_or(-1 as INT) - }); - self.register_fn("index_of", |s: &mut String, ch: char| { - s.find(ch) - .map(|index| s[0..index].chars().count() as INT) - .unwrap_or(-1 as INT) - }); - self.register_fn("index_of", |s: &mut String, find: String, start: INT| { - let start = if start < 0 { - 0 - } else if (start as usize) >= s.chars().count() { - return -1 as INT; - } else { - s.chars().take(start as usize).collect::().len() - }; - - s[start..] - .find(&find) - .map(|index| s[0..start + index].chars().count() as INT) - .unwrap_or(-1 as INT) - }); - self.register_fn("index_of", |s: &mut String, find: String| { - s.find(&find) - .map(|index| s[0..index].chars().count() as INT) - .unwrap_or(-1 as INT) - }); - self.register_fn("clear", |s: &mut String| s.clear()); - self.register_fn("append", |s: &mut String, ch: char| s.push(ch)); - self.register_fn("append", |s: &mut String, add: String| s.push_str(&add)); - self.register_fn("sub_string", sub_string); - self.register_fn("sub_string", |s: &mut String, start: INT| { - sub_string(s, start, s.len() as INT) - }); - self.register_fn("crop", crop_string); - self.register_fn("crop", |s: &mut String, start: INT| { - crop_string(s, start, s.len() as INT) - }); - self.register_fn("truncate", |s: &mut String, len: INT| { - if len >= 0 { - let chars: Vec<_> = s.chars().take(len as usize).collect(); - s.clear(); - chars.into_iter().for_each(|ch| s.push(ch)); - } else { - s.clear(); - } - }); - self.register_fn("pad", |s: &mut String, len: INT, ch: char| { - for _ in 0..s.chars().count() - len as usize { - s.push(ch); - } - }); - self.register_fn("replace", |s: &mut String, find: String, sub: String| { - let new_str = s.replace(&find, &sub); - s.clear(); - s.push_str(&new_str); - }); - self.register_fn("trim", |s: &mut String| { - let trimmed = s.trim(); - - if trimmed.len() < s.len() { - *s = trimmed.to_string(); - } - }); - - #[cfg(not(feature = "no_std"))] - { - // Register date/time functions - self.register_fn("timestamp", || Instant::now()); - - self.register_result_fn("-", |ts1: Instant, ts2: Instant| { - if ts2 > ts1 { - #[cfg(not(feature = "no_float"))] - return Ok(-(ts2 - ts1).as_secs_f64()); - - #[cfg(feature = "no_float")] - { - let seconds = (ts2 - ts1).as_secs(); - - #[cfg(not(feature = "unchecked"))] - { - if seconds > (MAX_INT as u64) { - return Err(EvalAltResult::ErrorArithmetic( - format!( - "Integer overflow for timestamp duration: {}", - -(seconds as i64) - ), - Position::none(), - )); - } - } - return Ok(-(seconds as INT)); - } - } else { - #[cfg(not(feature = "no_float"))] - return Ok((ts1 - ts2).as_secs_f64()); - - #[cfg(feature = "no_float")] - { - let seconds = (ts1 - ts2).as_secs(); - - #[cfg(not(feature = "unchecked"))] - { - if seconds > (MAX_INT as u64) { - return Err(EvalAltResult::ErrorArithmetic( - format!("Integer overflow for timestamp duration: {}", seconds), - Position::none(), - )); - } - } - return Ok(seconds as INT); - } - } - }); - - reg_cmp!(self, "<", lt, Instant); - reg_cmp!(self, "<=", lte, Instant); - reg_cmp!(self, ">", gt, Instant); - reg_cmp!(self, ">=", gte, Instant); - reg_cmp!(self, "==", eq, Instant); - reg_cmp!(self, "!=", ne, Instant); - - self.register_result_fn("elapsed", |timestamp: Instant| { - #[cfg(not(feature = "no_float"))] - return Ok(timestamp.elapsed().as_secs_f64()); - - #[cfg(feature = "no_float")] - { - let seconds = timestamp.elapsed().as_secs(); - - #[cfg(not(feature = "unchecked"))] - { - if seconds > (MAX_INT as u64) { - return Err(EvalAltResult::ErrorArithmetic( - format!("Integer overflow for timestamp.elapsed(): {}", seconds), - Position::none(), - )); - } - } - return Ok(seconds as INT); - } - }); - } - } -} diff --git a/src/engine.rs b/src/engine.rs index ad995cda..9c0ed804 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1,20 +1,23 @@ //! Main module defining the script evaluation `Engine`. use crate::any::{Dynamic, Union}; +use crate::calc_fn_hash; use crate::error::ParseErrorType; use crate::optimize::OptimizationLevel; -use crate::parser::{Expr, FnDef, ReturnType, Stmt, INT}; +use crate::packages::{CorePackage, Package, PackageLibrary, StandardPackage}; +use crate::parser::{Expr, FnDef, ReturnType, Stmt}; use crate::result::EvalAltResult; -use crate::scope::{EntryRef as ScopeSource, EntryType as ScopeEntryType, Scope}; +use crate::scope::{EntryType as ScopeEntryType, Scope}; use crate::token::Position; use crate::stdlib::{ any::TypeId, boxed::Box, - collections::{hash_map::DefaultHasher, HashMap}, + collections::HashMap, format, hash::{Hash, Hasher}, iter::once, + mem, ops::{Deref, DerefMut}, rc::Rc, string::{String, ToString}, @@ -22,6 +25,12 @@ use crate::stdlib::{ vec::Vec, }; +#[cfg(not(feature = "no_std"))] +use crate::stdlib::collections::hash_map::DefaultHasher; + +#[cfg(feature = "no_std")] +use ahash::AHasher; + /// An dynamic array of `Dynamic` values. /// /// Not available under the `no_index` feature. @@ -41,9 +50,9 @@ pub type FnAny = pub type FnAny = dyn Fn(&mut FnCallArgs, Position) -> Result>; #[cfg(feature = "sync")] -type IteratorFn = dyn Fn(&Dynamic) -> Box> + Send + Sync; +pub type IteratorFn = dyn Fn(Dynamic) -> Box> + Send + Sync; #[cfg(not(feature = "sync"))] -type IteratorFn = dyn Fn(&Dynamic) -> Box>; +pub type IteratorFn = dyn Fn(Dynamic) -> Box>; #[cfg(debug_assertions)] pub const MAX_CALL_STACK_DEPTH: usize = 28; @@ -51,6 +60,13 @@ pub const MAX_CALL_STACK_DEPTH: usize = 28; #[cfg(not(debug_assertions))] pub const MAX_CALL_STACK_DEPTH: usize = 256; +#[cfg(not(feature = "only_i32"))] +#[cfg(not(feature = "only_i64"))] +const FUNCTIONS_COUNT: usize = 512; + +#[cfg(any(feature = "only_i32", feature = "only_i64"))] +const FUNCTIONS_COUNT: usize = 256; + pub const KEYWORD_PRINT: &str = "print"; pub const KEYWORD_DEBUG: &str = "debug"; pub const KEYWORD_TYPE_OF: &str = "type_of"; @@ -59,77 +75,143 @@ pub const FUNC_TO_STRING: &str = "to_string"; pub const FUNC_GETTER: &str = "get$"; pub const FUNC_SETTER: &str = "set$"; -#[cfg(not(feature = "only_i32"))] -#[cfg(not(feature = "only_i64"))] -const FUNCTIONS_COUNT: usize = 512; - -#[cfg(any(feature = "only_i32", feature = "only_i64"))] -const FUNCTIONS_COUNT: usize = 256; - -#[derive(Debug, Eq, PartialEq, Hash, Clone)] -enum IndexValue { - Num(usize), - Str(String), -} - -impl IndexValue { - fn from_num(idx: INT) -> Self { - Self::Num(idx as usize) - } - fn from_str(name: String) -> Self { - Self::Str(name) - } - fn as_num(self) -> usize { - match self { - Self::Num(n) => n, - _ => panic!("index value is numeric"), - } - } - fn as_str(self) -> String { - match self { - Self::Str(s) => s, - _ => panic!("index value is string"), - } - } -} - -#[derive(Debug)] +/// A type that encapsulates a mutation target for an expression with side effects. enum Target<'a> { - Scope(ScopeSource<'a>), - Value(&'a mut Dynamic), + /// The target is a mutable reference to a `Dynamic` value somewhere. + Ref(&'a mut Dynamic), + /// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects). + Value(Box), + /// The target is a character inside a String. + /// This is necessary because directly pointing to a char inside a String is impossible. + StringChar(Box<(&'a mut Dynamic, usize, Dynamic)>), } -impl<'a> Target<'a> { - fn get_mut(self, scope: &'a mut Scope) -> &'a mut Dynamic { +impl Target<'_> { + /// Get the value of the `Target` as a `Dynamic`. + pub fn into_dynamic(self) -> Dynamic { match self { - Self::Value(t) => t, - Self::Scope(src) => scope.get_mut(src), + Target::Ref(r) => r.clone(), + Target::Value(v) => *v, + Target::StringChar(s) => s.2, } } -} -impl<'a> From> for Target<'a> { - fn from(src: ScopeSource<'a>) -> Self { - Self::Scope(src) + /// Update the value of the `Target`. + pub fn set_value(&mut self, new_val: Dynamic, pos: Position) -> Result<(), Box> { + match self { + Target::Ref(r) => **r = new_val, + Target::Value(_) => { + return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(pos))) + } + Target::StringChar(x) => match x.0 { + Dynamic(Union::Str(s)) => { + // Replace the character at the specified index position + let new_ch = new_val + .as_char() + .map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?; + + let mut chars: Vec = s.chars().collect(); + let ch = *chars.get(x.1).expect("string index out of bounds"); + + // See if changed - if so, update the String + if ch != new_ch { + chars[x.1] = new_ch; + s.clear(); + chars.iter().for_each(|&ch| s.push(ch)); + } + } + _ => panic!("should be String"), + }, + } + + Ok(()) } } impl<'a> From<&'a mut Dynamic> for Target<'a> { fn from(value: &'a mut Dynamic) -> Self { - Self::Value(value) + Self::Ref(value) + } +} +impl> From for Target<'_> { + fn from(value: T) -> Self { + Self::Value(Box::new(value.into())) } } -/// A type that holds a library of script-defined functions. +/// A type to hold a number of `Dynamic` values in static storage for speed, +/// and any spill-overs in a `Vec`. +struct StaticVec { + /// Total number of values held. + len: usize, + /// Static storage. + list: [Dynamic; 4], + /// Dynamic storage. + more: Vec, +} + +impl StaticVec { + /// Create a new `StaticVec`. + pub fn new() -> Self { + Self { + len: 0, + list: [().into(), ().into(), ().into(), ().into()], + more: Vec::new(), + } + } + /// Push a new value to the end of this `StaticVec`. + pub fn push>(&mut self, value: T) { + if self.len >= self.list.len() { + self.more.push(value.into()); + } else { + self.list[self.len] = value.into(); + } + self.len += 1; + } + /// Pop a value from the end of this `StaticVec`. + /// + /// # Panics + /// + /// Panics if the `StaticVec` is empty. + pub fn pop(&mut self) -> Dynamic { + let result = if self.len <= 0 { + panic!("nothing to pop!") + } else if self.len <= self.list.len() { + mem::replace(self.list.get_mut(self.len - 1).unwrap(), ().into()) + } else { + self.more.pop().unwrap() + }; + + self.len -= 1; + + result + } +} + +/// A type that holds all the current states of the Engine. +#[derive(Debug, Clone, Copy)] +pub struct State { + /// Normally, access to variables are parsed with a relative offset into the scope to avoid a lookup. + /// In some situation, e.g. after running an `eval` statement, subsequent offsets may become mis-aligned. + /// When that happens, this flag is turned on to force a scope lookup by name. + pub always_search: bool, +} + +impl State { + /// Create a new `State`. + pub fn new() -> Self { + Self { + always_search: false, + } + } +} + +/// A type that holds a library (`HashMap`) of script-defined functions. /// /// Since script-defined functions have `Dynamic` parameters, functions with the same name /// and number of parameters are considered equivalent. /// -/// Since the key is a combination of the function name (a String) plus the number of parameters, -/// we cannot use a `HashMap` because we don't want to clone the function name string just -/// to search for it. -/// -/// So instead this is implemented as a sorted list and binary searched. +/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_def`. #[derive(Debug, Clone)] pub struct FunctionsLib( #[cfg(feature = "sync")] HashMap>, @@ -207,7 +289,7 @@ impl DerefMut for FunctionsLib { /// Rhai main scripting engine. /// /// ``` -/// # fn main() -> Result<(), rhai::EvalAltResult> { +/// # fn main() -> Result<(), Box> { /// use rhai::Engine; /// /// let engine = Engine::new(); @@ -221,27 +303,31 @@ impl DerefMut for FunctionsLib { /// /// Currently, `Engine` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`. pub struct Engine { - /// A hashmap containing all compiled functions known to the engine. + /// A collection of all library packages loaded into the engine. + pub(crate) packages: Vec, + /// A `HashMap` containing all compiled functions known to the engine. + /// + /// The key of the `HashMap` is a `u64` hash calculated by the function `crate::calc_fn_hash`. pub(crate) functions: HashMap>, /// A hashmap containing all iterators known to the engine. pub(crate) type_iterators: HashMap>, /// A hashmap mapping type names to pretty-print names. - pub(crate) type_names: Option>, + pub(crate) type_names: HashMap, /// Closure for implementing the `print` command. #[cfg(feature = "sync")] - pub(crate) on_print: Option>, + pub(crate) print: Box, /// Closure for implementing the `print` command. #[cfg(not(feature = "sync"))] - pub(crate) on_print: Option>, + pub(crate) print: Box, /// Closure for implementing the `debug` command. #[cfg(feature = "sync")] - pub(crate) on_debug: Option>, + pub(crate) debug: Box, /// Closure for implementing the `debug` command. #[cfg(not(feature = "sync"))] - pub(crate) on_debug: Option>, + pub(crate) debug: Box, /// Optimize the AST after compilation. pub(crate) optimization_level: OptimizationLevel, @@ -255,14 +341,15 @@ pub struct Engine { impl Default for Engine { fn default() -> Self { // Create the new scripting Engine - let mut engine = Engine { + let mut engine = Self { + packages: Vec::new(), functions: HashMap::with_capacity(FUNCTIONS_COUNT), type_iterators: HashMap::new(), - type_names: None, + type_names: HashMap::new(), // default print/debug implementations - on_print: Some(Box::new(default_print)), - on_debug: Some(Box::new(default_print)), + print: Box::new(default_print), + debug: Box::new(default_print), // optimization level #[cfg(feature = "no_optimize")] @@ -279,10 +366,11 @@ impl Default for Engine { max_call_stack_depth: MAX_CALL_STACK_DEPTH, }; - engine.register_core_lib(); + #[cfg(feature = "no_stdlib")] + engine.load_package(CorePackage::new().get()); #[cfg(not(feature = "no_stdlib"))] - engine.register_stdlib(); + engine.load_package(StandardPackage::new().get()); engine } @@ -330,17 +418,30 @@ fn extract_prop_from_setter(fn_name: &str) -> Option<&str> { } } -pub(crate) fn calc_fn_spec(fn_name: &str, params: impl Iterator) -> u64 { +/// Calculate a `u64` hash key from a function name and parameter types. +/// +/// Parameter types are passed in via `TypeId` values from an iterator +/// which can come from any source. +pub fn calc_fn_spec(fn_name: &str, params: impl Iterator) -> u64 { + #[cfg(feature = "no_std")] + let mut s: AHasher = Default::default(); + #[cfg(not(feature = "no_std"))] let mut s = DefaultHasher::new(); - fn_name.hash(&mut s); + + s.write(fn_name.as_bytes()); params.for_each(|t| t.hash(&mut s)); s.finish() } +/// Calculate a `u64` hash key from a function name and number of parameters (without regard to types). pub(crate) fn calc_fn_def(fn_name: &str, params: usize) -> u64 { + #[cfg(feature = "no_std")] + let mut s: AHasher = Default::default(); + #[cfg(not(feature = "no_std"))] let mut s = DefaultHasher::new(); - fn_name.hash(&mut s); - params.hash(&mut s); + + s.write(fn_name.as_bytes()); + s.write_usize(params); s.finish() } @@ -352,88 +453,15 @@ fn default_print(s: &str) { /// Search for a variable within the scope, returning its value and index inside the Scope fn search_scope<'a>( - scope: &'a Scope, - id: &str, + scope: &'a mut Scope, + name: &str, begin: Position, -) -> Result<(ScopeSource<'a>, Dynamic), Box> { - scope - .get(id) - .ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(id.into(), begin))) -} +) -> Result<(&'a mut Dynamic, ScopeEntryType), Box> { + let (index, _) = scope + .get(name) + .ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.into(), begin)))?; -/// Replace a character at an index position in a mutable string -fn str_replace_char(s: &mut String, idx: usize, new_ch: char) { - let mut chars: Vec = s.chars().collect(); - let ch = *chars.get(idx).expect("string index out of bounds"); - - // See if changed - if so, update the String - if ch != new_ch { - chars[idx] = new_ch; - s.clear(); - chars.iter().for_each(|&ch| s.push(ch)); - } -} - -/// Update the value at an index position -fn update_indexed_val( - mut target: Dynamic, - idx: IndexValue, - new_val: Dynamic, - pos: Position, -) -> Result> { - match target.get_mut() { - Union::Array(arr) => { - arr[idx.as_num()] = new_val; - } - Union::Map(map) => { - map.insert(idx.as_str(), new_val); - } - Union::Str(s) => { - // Value must be a character - let ch = new_val - .as_char() - .map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?; - str_replace_char(s, idx.as_num(), ch); - } - // All other variable types should be an error - _ => panic!("invalid type for indexing: {}", target.type_name()), - } - - Ok(target) -} - -/// Update the value at an index position in a variable inside the scope -fn update_indexed_scope_var( - scope: &mut Scope, - src: ScopeSource, - idx: IndexValue, - new_val: Dynamic, - pos: Position, -) -> Result> { - let target = scope.get_mut(src); - - match target.get_mut() { - // array_id[idx] = val - Union::Array(arr) => { - arr[idx.as_num()] = new_val; - } - // map_id[idx] = val - Union::Map(map) => { - map.insert(idx.as_str(), new_val); - } - // string_id[idx] = val - Union::Str(s) => { - // Value must be a character - let ch = new_val - .as_char() - .map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?; - str_replace_char(s, idx.as_num(), ch); - } - // All other variable types should be an error - _ => panic!("invalid type for indexing: {}", target.type_name()), - } - - Ok(Dynamic::from_unit()) + Ok(scope.get_mut(index)) } impl Engine { @@ -442,14 +470,16 @@ impl Engine { Default::default() } - /// Create a new `Engine` with minimal configurations without the standard library etc. + /// Create a new `Engine` with _no_ built-in functions. + /// Use the `load_package` method to load packages of functions. pub fn new_raw() -> Self { - let mut engine = Engine { + Self { + packages: Vec::new(), functions: HashMap::with_capacity(FUNCTIONS_COUNT / 2), type_iterators: HashMap::new(), - type_names: None, - on_print: None, - on_debug: None, + type_names: HashMap::new(), + print: Box::new(|_| {}), + debug: Box::new(|_| {}), #[cfg(feature = "no_optimize")] optimization_level: OptimizationLevel::None, @@ -463,11 +493,16 @@ impl Engine { optimization_level: OptimizationLevel::Full, max_call_stack_depth: MAX_CALL_STACK_DEPTH, - }; + } + } - engine.register_core_lib(); - - engine + /// Load a new package into the `Engine`. + /// + /// When searching for functions, packages loaded later are preferred. + /// In other words, loaded packages are searched in reverse order. + pub fn load_package(&mut self, package: PackageLibrary) { + // Push the package to the top - packages are searched in reverse order + self.packages.insert(0, package); } /// Control whether and how the `Engine` will optimize an AST after compilation @@ -488,7 +523,7 @@ impl Engine { pub(crate) fn call_fn_raw( &self, scope: Option<&mut Scope>, - fn_lib: Option<&FunctionsLib>, + fn_lib: &FunctionsLib, fn_name: &str, args: &mut FnCallArgs, def_val: Option<&Dynamic>, @@ -500,128 +535,57 @@ impl Engine { return Err(Box::new(EvalAltResult::ErrorStackOverflow(pos))); } - #[cfg(feature = "no_function")] - const fn_lib: Option<&FunctionsLib> = None; - // First search in script-defined functions (can override built-in) - if let Some(fn_def) = fn_lib.and_then(|lib| lib.get_function(fn_name, args.len())) { - match scope { - // Extern scope passed in which is not empty - Some(scope) if scope.len() > 0 => { - let scope_len = scope.len(); - - scope.extend( - // Put arguments into scope as variables - variable name is copied - // TODO - avoid copying variable name - fn_def - .params - .iter() - .zip(args.into_iter().map(|v| v.clone())) - .map(|(name, value)| (name.clone(), ScopeEntryType::Normal, value)), - ); - - // Evaluate the function at one higher level of call depth - let result = self - .eval_stmt(scope, fn_lib, &fn_def.body, level + 1) - .or_else(|err| match *err { - // Convert return statement to return value - EvalAltResult::Return(x, _) => Ok(x), - err => Err(Box::new(err.set_position(pos))), - }); - - scope.rewind(scope_len); - - return result; - } - // No new scope - create internal scope - _ => { - let mut scope = Scope::new(); - - scope.extend( - // Put arguments into scope as variables - fn_def - .params - .iter() - .zip(args.into_iter().map(|v| v.clone())) - .map(|(name, value)| (name, ScopeEntryType::Normal, value)), - ); - - // Evaluate the function at one higher level of call depth - return self - .eval_stmt(&mut scope, fn_lib, &fn_def.body, level + 1) - .or_else(|err| match *err { - // Convert return statement to return value - EvalAltResult::Return(x, _) => Ok(x), - err => Err(Box::new(err.set_position(pos))), - }); - } - } - } - - // Argument must be a string - fn cast_to_string(r: &Dynamic, pos: Position) -> Result<&str, Box> { - r.as_str().map_err(|type_name| { - Box::new(EvalAltResult::ErrorMismatchOutputType( - type_name.into(), - pos, - )) - }) + if let Some(fn_def) = fn_lib.get_function(fn_name, args.len()) { + return self.call_fn_from_lib(scope, fn_lib, fn_def, args, pos, level); } // Search built-in's and external functions - let fn_spec = calc_fn_spec(fn_name, args.iter().map(|a| a.type_id())); + let fn_spec = calc_fn_hash(fn_name, args.iter().map(|a| a.type_id())); - if let Some(func) = self.functions.get(&fn_spec) { + if let Some(func) = self.functions.get(&fn_spec).or_else(|| { + self.packages + .iter() + .find(|pkg| pkg.functions.contains_key(&fn_spec)) + .and_then(|pkg| pkg.functions.get(&fn_spec)) + }) { // Run external function let result = func(args, pos)?; // See if the function match print/debug (which requires special processing) - return match fn_name { - KEYWORD_PRINT if self.on_print.is_some() => { - self.on_print.as_ref().unwrap()(cast_to_string(&result, pos)?); - Ok(Dynamic::from_unit()) - } - KEYWORD_DEBUG if self.on_debug.is_some() => { - self.on_debug.as_ref().unwrap()(cast_to_string(&result, pos)?); - Ok(Dynamic::from_unit()) - } - KEYWORD_PRINT | KEYWORD_DEBUG => Ok(Dynamic::from_unit()), - _ => Ok(result), - }; + return Ok(match fn_name { + KEYWORD_PRINT => (self.print)(result.as_str().map_err(|type_name| { + Box::new(EvalAltResult::ErrorMismatchOutputType( + type_name.into(), + pos, + )) + })?) + .into(), + KEYWORD_DEBUG => (self.debug)(result.as_str().map_err(|type_name| { + Box::new(EvalAltResult::ErrorMismatchOutputType( + type_name.into(), + pos, + )) + })?) + .into(), + _ => result, + }); } if let Some(prop) = extract_prop_from_getter(fn_name) { - return match args[0] { - // Map property access - Dynamic(Union::Map(map)) => Ok(map - .get(prop) - .cloned() - .unwrap_or_else(|| Dynamic::from_unit())), - - // Getter function not found - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - format!("- property '{}' unknown or write-only", prop), - pos, - ))), - }; + // Getter function not found + return Err(Box::new(EvalAltResult::ErrorDotExpr( + format!("- property '{}' unknown or write-only", prop), + pos, + ))); } if let Some(prop) = extract_prop_from_setter(fn_name) { - let (arg, value) = args.split_at_mut(1); - - return match arg[0] { - // Map property update - Dynamic(Union::Map(map)) => { - map.insert(prop.to_string(), value[0].clone()); - Ok(Dynamic::from_unit()) - } - - // Setter function not found - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - format!("- property '{}' unknown or read-only", prop), - pos, - ))), - }; + // Setter function not found + return Err(Box::new(EvalAltResult::ErrorDotExpr( + format!("- property '{}' unknown or read-only", prop), + pos, + ))); } if let Some(val) = def_val { @@ -632,8 +596,7 @@ impl Engine { // Raise error let types_list: Vec<_> = args .iter() - .map(|x| x.type_name()) - .map(|name| self.map_type_name(name)) + .map(|name| self.map_type_name(name.type_name())) .collect(); Err(Box::new(EvalAltResult::ErrorFunctionNotFound( @@ -642,204 +605,436 @@ impl Engine { ))) } - /// Chain-evaluate a dot setter. - fn dot_get_helper( + /// Call a script-defined function. + pub(crate) fn call_fn_from_lib( &self, - scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, - target: Target, - dot_rhs: &Expr, + scope: Option<&mut Scope>, + fn_lib: &FunctionsLib, + fn_def: &FnDef, + args: &mut FnCallArgs, + pos: Position, level: usize, ) -> Result> { - match dot_rhs { - // xxx.fn_name(arg_expr_list) - Expr::FunctionCall(fn_name, arg_expr_list, def_val, pos) => { - let mut values = arg_expr_list - .iter() - .map(|arg_expr| self.eval_expr(scope, fn_lib, arg_expr, level)) - .collect::, _>>()?; - let mut args: Vec<_> = once(target.get_mut(scope)) - .chain(values.iter_mut()) - .collect(); - let def_val = def_val.as_ref(); - self.call_fn_raw(None, fn_lib, fn_name, &mut args, def_val, *pos, 0) + match scope { + // Extern scope passed in which is not empty + Some(scope) if scope.len() > 0 => { + let scope_len = scope.len(); + let mut state = State::new(); + + scope.extend( + // Put arguments into scope as variables - variable name is copied + // TODO - avoid copying variable name + fn_def + .params + .iter() + .zip(args.into_iter().map(|v| v.clone())) + .map(|(name, value)| (name.clone(), ScopeEntryType::Normal, value)), + ); + + // Evaluate the function at one higher level of call depth + let result = self + .eval_stmt(scope, &mut state, fn_lib, &fn_def.body, level + 1) + .or_else(|err| match *err { + // Convert return statement to return value + EvalAltResult::Return(x, _) => Ok(x), + _ => Err(EvalAltResult::set_position(err, pos)), + }); + + scope.rewind(scope_len); + + return result; + } + // No new scope - create internal scope + _ => { + let mut scope = Scope::new(); + let mut state = State::new(); + + scope.extend( + // Put arguments into scope as variables + fn_def + .params + .iter() + .zip(args.into_iter().map(|v| v.clone())) + .map(|(name, value)| (name, ScopeEntryType::Normal, value)), + ); + + // Evaluate the function at one higher level of call depth + return self + .eval_stmt(&mut scope, &mut state, fn_lib, &fn_def.body, level + 1) + .or_else(|err| match *err { + // Convert return statement to return value + EvalAltResult::Return(x, _) => Ok(x), + _ => Err(EvalAltResult::set_position(err, pos)), + }); + } + } + } + + // Has a system function an override? + fn has_override(&self, fn_lib: &FunctionsLib, name: &str) -> bool { + let hash = calc_fn_hash(name, once(TypeId::of::())); + + // First check registered functions + self.functions.contains_key(&hash) + // Then check packages + || self.packages.iter().any(|p| p.functions.contains_key(&hash)) + // Then check script-defined functions + || fn_lib.has_function(name, 1) + } + + // Perform an actual function call, taking care of special functions + fn exec_fn_call( + &self, + fn_lib: &FunctionsLib, + fn_name: &str, + args: &mut [&mut Dynamic], + def_val: Option<&Dynamic>, + pos: Position, + level: usize, + ) -> Result> { + match fn_name { + // type_of + KEYWORD_TYPE_OF if args.len() == 1 && !self.has_override(fn_lib, KEYWORD_TYPE_OF) => { + Ok(self.map_type_name(args[0].type_name()).to_string().into()) } - // xxx.id - Expr::Property(id, pos) => { - let mut args = [target.get_mut(scope)]; - self.call_fn_raw(None, fn_lib, &make_getter(id), &mut args, None, *pos, 0) + // eval + KEYWORD_EVAL if args.len() == 1 && !self.has_override(fn_lib, KEYWORD_EVAL) => { + Err(Box::new(EvalAltResult::ErrorRuntime( + "'eval' should not be called in method style. Try eval(...);".into(), + pos, + ))) } - // xxx.idx_lhs[idx_expr] - Expr::Index(idx_lhs, idx_expr, op_pos) => { - let lhs_value = match idx_lhs.as_ref() { - // xxx.id[idx_expr] - Expr::Property(id, pos) => { - let mut args = [target.get_mut(scope)]; - self.call_fn_raw(None, fn_lib, &make_getter(id), &mut args, None, *pos, 0)? - } - // xxx.???[???][idx_expr] - Expr::Index(_, _, _) => { - // Chain the indexing - self.dot_get_helper(scope, fn_lib, target, idx_lhs, level)? - } - // Syntax error - _ => { + _ => self.call_fn_raw(None, fn_lib, fn_name, args, def_val, pos, level), + } + } + + /// Evaluate a text string as a script - used primarily for 'eval'. + fn eval_script_expr( + &self, + scope: &mut Scope, + fn_lib: &FunctionsLib, + script: &Dynamic, + pos: Position, + ) -> Result> { + let script = script + .as_str() + .map_err(|type_name| EvalAltResult::ErrorMismatchOutputType(type_name.into(), pos))?; + + // Compile the script text + // No optimizations because we only run it once + let mut ast = self.compile_with_scope_and_optimization_level( + &Scope::new(), + script, + OptimizationLevel::None, + )?; + + // If new functions are defined within the eval string, it is an error + if ast.1.len() > 0 { + return Err(Box::new(EvalAltResult::ErrorParsing( + ParseErrorType::WrongFnDefinition.into_err(pos), + ))); + } + + #[cfg(feature = "sync")] + { + ast.1 = Arc::new(fn_lib.clone()); + } + #[cfg(not(feature = "sync"))] + { + ast.1 = Rc::new(fn_lib.clone()); + } + + // Evaluate the AST + self.eval_ast_with_scope_raw(scope, &ast) + .map_err(|err| EvalAltResult::set_position(err, pos)) + } + + /// Chain-evaluate a dot/index chain. + fn eval_dot_index_chain_helper( + &self, + fn_lib: &FunctionsLib, + mut target: Target, + rhs: &Expr, + idx_values: &mut StaticVec, + is_index: bool, + op_pos: Position, + level: usize, + mut new_val: Option, + ) -> Result<(Dynamic, bool), Box> { + // Get a reference to the mutation target Dynamic + let obj = match target { + Target::Ref(r) => r, + Target::Value(ref mut r) => r.as_mut(), + Target::StringChar(ref mut x) => &mut x.2, + }; + + // Pop the last index value + let mut idx_val = idx_values.pop(); + + if is_index { + match rhs { + // xxx[idx].dot_rhs... + Expr::Dot(idx, idx_rhs, pos) | + // xxx[idx][dot_rhs]... + Expr::Index(idx, idx_rhs, pos) => { + let is_index = matches!(rhs, Expr::Index(_,_,_)); + + let indexed_val = self.get_indexed_mut(obj, idx_val, idx.position(), op_pos, false)?; + self.eval_dot_index_chain_helper( + fn_lib, indexed_val, idx_rhs.as_ref(), idx_values, is_index, *pos, level, new_val + ) + } + // xxx[rhs] = new_val + _ if new_val.is_some() => { + let mut indexed_val = self.get_indexed_mut(obj, idx_val, rhs.position(), op_pos, true)?; + indexed_val.set_value(new_val.unwrap(), rhs.position())?; + Ok((().into(), true)) + } + // xxx[rhs] + _ => self + .get_indexed_mut(obj, idx_val, rhs.position(), op_pos, false) + .map(|v| (v.into_dynamic(), false)) + } + } else { + match rhs { + // xxx.fn_name(arg_expr_list) + Expr::FunctionCall(fn_name, _, def_val, pos) => { + let mut args: Vec<_> = once(obj) + .chain(idx_val.downcast_mut::().unwrap().iter_mut()) + .collect(); + let def_val = def_val.as_deref(); + // A function call is assumed to have side effects, so the value is changed + // TODO - Remove assumption of side effects by checking whether the first parameter is &mut + self.exec_fn_call(fn_lib, fn_name, &mut args, def_val, *pos, 0).map(|v| (v, true)) + } + // {xxx:map}.id = ??? + Expr::Property(id, pos) if obj.is::() && new_val.is_some() => { + let mut indexed_val = + self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, true)?; + indexed_val.set_value(new_val.unwrap(), rhs.position())?; + Ok((().into(), true)) + } + // {xxx:map}.id + Expr::Property(id, pos) if obj.is::() => { + let indexed_val = + self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)?; + Ok((indexed_val.into_dynamic(), false)) + } + // xxx.id = ??? + Expr::Property(id, pos) if new_val.is_some() => { + let fn_name = make_setter(id); + let mut args = [obj, new_val.as_mut().unwrap()]; + self.exec_fn_call(fn_lib, &fn_name, &mut args, None, *pos, 0).map(|v| (v, true)) + } + // xxx.id + Expr::Property(id, pos) => { + let fn_name = make_getter(id); + let mut args = [obj]; + self.exec_fn_call(fn_lib, &fn_name, &mut args, None, *pos, 0).map(|v| (v, false)) + } + // {xxx:map}.idx_lhs[idx_expr] + Expr::Index(dot_lhs, dot_rhs, pos) | + // {xxx:map}.dot_lhs.rhs + Expr::Dot(dot_lhs, dot_rhs, pos) if obj.is::() => { + let is_index = matches!(rhs, Expr::Index(_,_,_)); + + let indexed_val = if let Expr::Property(id, pos) = dot_lhs.as_ref() { + self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)? + } else { + // Syntax error return Err(Box::new(EvalAltResult::ErrorDotExpr( "".to_string(), - dot_rhs.position(), - ))) - } - }; - - self.get_indexed_val(scope, fn_lib, &lhs_value, idx_expr, *op_pos, level, false) - .map(|(val, _)| val) - } - - // xxx.dot_lhs.rhs - Expr::Dot(dot_lhs, rhs, _) => match dot_lhs.as_ref() { - // xxx.id.rhs - Expr::Property(id, pos) => { - let mut args = [target.get_mut(scope)]; - self.call_fn_raw(None, fn_lib, &make_getter(id), &mut args, None, *pos, 0) - .and_then(|mut val| { - self.dot_get_helper(scope, fn_lib, (&mut val).into(), rhs, level) - }) - } - // xxx.idx_lhs[idx_expr].rhs - Expr::Index(idx_lhs, idx_expr, op_pos) => { - let val = match idx_lhs.as_ref() { - // xxx.id[idx_expr].rhs - Expr::Property(id, pos) => { - let fn_name = make_getter(id); - let mut args = [target.get_mut(scope)]; - self.call_fn_raw(None, fn_lib, &fn_name, &mut args, None, *pos, 0)? - } - // xxx.???[???][idx_expr].rhs - Expr::Index(_, _, _) => { - self.dot_get_helper(scope, fn_lib, target, idx_lhs, level)? - } - // Syntax error - _ => { - return Err(Box::new(EvalAltResult::ErrorDotExpr( - "".to_string(), - dot_rhs.position(), - ))) - } + rhs.position(), + ))); }; + self.eval_dot_index_chain_helper( + fn_lib, indexed_val, dot_rhs, idx_values, is_index, *pos, level, new_val + ) + } + // xxx.idx_lhs[idx_expr] + Expr::Index(dot_lhs, dot_rhs, pos) | + // xxx.dot_lhs.rhs + Expr::Dot(dot_lhs, dot_rhs, pos) => { + let is_index = matches!(rhs, Expr::Index(_,_,_)); + let mut buf: Dynamic = ().into(); + let mut args = [obj, &mut buf]; - self.get_indexed_val(scope, fn_lib, &val, idx_expr, *op_pos, level, false) - .and_then(|(mut val, _)| { - self.dot_get_helper(scope, fn_lib, (&mut val).into(), rhs, level) - }) + let indexed_val = &mut (if let Expr::Property(id, pos) = dot_lhs.as_ref() { + let fn_name = make_getter(id); + self.exec_fn_call(fn_lib, &fn_name, &mut args[..1], None, *pos, 0)? + } else { + // Syntax error + return Err(Box::new(EvalAltResult::ErrorDotExpr( + "".to_string(), + rhs.position(), + ))); + }); + let (result, changed) = self.eval_dot_index_chain_helper( + fn_lib, indexed_val.into(), dot_rhs, idx_values, is_index, *pos, level, new_val + )?; + + // Feed the value back via a setter just in case it has been updated + if changed { + if let Expr::Property(id, pos) = dot_lhs.as_ref() { + let fn_name = make_setter(id); + args[1] = indexed_val; + self.exec_fn_call(fn_lib, &fn_name, &mut args, None, *pos, 0)?; + } + } + + Ok((result, changed)) } // Syntax error _ => Err(Box::new(EvalAltResult::ErrorDotExpr( "".to_string(), - dot_lhs.position(), + rhs.position(), ))), - }, - - // Syntax error - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "".to_string(), - dot_rhs.position(), - ))), + } } } - /// Evaluate a dot chain getter - fn dot_get( + /// Evaluate a dot/index chain. + fn eval_dot_index_chain( &self, scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, + state: &mut State, + fn_lib: &FunctionsLib, dot_lhs: &Expr, dot_rhs: &Expr, + is_index: bool, + op_pos: Position, level: usize, + new_val: Option, ) -> Result> { + let idx_values = &mut StaticVec::new(); + + self.eval_indexed_chain(scope, state, fn_lib, dot_rhs, idx_values, 0, level)?; + match dot_lhs { - // id.??? - Expr::Variable(id, pos) => { - let (entry, _) = search_scope(scope, id, *pos)?; + // id.??? or id[???] + Expr::Variable(id, index, pos) => { + let (target, typ) = match index { + Some(i) if !state.always_search => scope.get_mut(scope.len() - i.get()), + _ => search_scope(scope, id, *pos)?, + }; - // Avoid referencing scope which is used below as mut - let entry = ScopeSource { name: id, ..entry }; - - // This is a variable property access (potential function call). - // Use a direct index into `scope` to directly mutate the variable value. - self.dot_get_helper(scope, fn_lib, entry.into(), dot_rhs, level) - } - - // idx_lhs[idx_expr].??? - Expr::Index(idx_lhs, idx_expr, op_pos) => { - let (src, index, mut val) = - self.eval_index_expr(scope, fn_lib, idx_lhs, idx_expr, *op_pos, level)?; - let value = self.dot_get_helper(scope, fn_lib, (&mut val).into(), dot_rhs, level); - - // In case the expression mutated `target`, we need to update it back into the scope because it is cloned. - if let Some(src) = src { - match src.typ { - ScopeEntryType::Constant => { - return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( - src.name.to_string(), - idx_lhs.position(), - ))); - } - - ScopeEntryType::Normal => { - update_indexed_scope_var(scope, src, index, val, dot_rhs.position())?; - } + // Constants cannot be modified + match typ { + ScopeEntryType::Constant if new_val.is_some() => { + return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( + id.to_string(), + *pos, + ))); } + _ => (), } - value + self.eval_dot_index_chain_helper( + fn_lib, + target.into(), + dot_rhs, + idx_values, + is_index, + op_pos, + level, + new_val, + ) + .map(|(v, _)| v) } - - // {expr}.??? + // {expr}.??? = ??? or {expr}[???] = ??? + expr if new_val.is_some() => { + return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS( + expr.position(), + ))); + } + // {expr}.??? or {expr}[???] expr => { - let mut val = self.eval_expr(scope, fn_lib, expr, level)?; - self.dot_get_helper(scope, fn_lib, (&mut val).into(), dot_rhs, level) + let val = self.eval_expr(scope, state, fn_lib, expr, level)?; + + self.eval_dot_index_chain_helper( + fn_lib, + val.into(), + dot_rhs, + idx_values, + is_index, + op_pos, + level, + new_val, + ) + .map(|(v, _)| v) } } } + /// Evaluate a chain of indexes and store the results in a list. + /// The first few results are stored in the array `list` which is of fixed length. + /// Any spill-overs are stored in `more`, which is dynamic. + /// The fixed length array is used to avoid an allocation in the overwhelming cases of just a few levels of indexing. + /// The total number of values is returned. + fn eval_indexed_chain( + &self, + scope: &mut Scope, + state: &mut State, + fn_lib: &FunctionsLib, + expr: &Expr, + idx_values: &mut StaticVec, + size: usize, + level: usize, + ) -> Result<(), Box> { + match expr { + Expr::FunctionCall(_, arg_exprs, _, _) => { + let arg_values = arg_exprs + .iter() + .map(|arg_expr| self.eval_expr(scope, state, fn_lib, arg_expr, level)) + .collect::, _>>()?; + + idx_values.push(arg_values) + } + // Store a placeholder - no need to copy the property name + Expr::Property(_, _) => idx_values.push(()), + Expr::Index(lhs, rhs, _) | Expr::Dot(lhs, rhs, _) => { + // Evaluate in left-to-right order + let lhs_val = match lhs.as_ref() { + Expr::Property(_, _) => ().into(), // Store a placeholder in case of a property + _ => self.eval_expr(scope, state, fn_lib, lhs, level)?, + }; + + // Push in reverse order + self.eval_indexed_chain(scope, state, fn_lib, rhs, idx_values, size, level)?; + + idx_values.push(lhs_val); + } + _ => idx_values.push(self.eval_expr(scope, state, fn_lib, expr, level)?), + } + + Ok(()) + } + /// Get the value at the indexed position of a base type - fn get_indexed_val( + fn get_indexed_mut<'a>( &self, - scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, - val: &Dynamic, - idx_expr: &Expr, + val: &'a mut Dynamic, + idx: Dynamic, + idx_pos: Position, op_pos: Position, - level: usize, - only_index: bool, - ) -> Result<(Dynamic, IndexValue), Box> { - let idx_pos = idx_expr.position(); + create: bool, + ) -> Result, Box> { let type_name = self.map_type_name(val.type_name()); - match val.get_ref() { - Union::Array(arr) => { + match val { + Dynamic(Union::Array(arr)) => { // val_array[idx] - let index = self - .eval_expr(scope, fn_lib, idx_expr, level)? + let index = idx .as_int() - .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_expr.position()))?; + .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?; let arr_len = arr.len(); if index >= 0 { - arr.get(index as usize) - .map(|v| { - ( - if only_index { - Dynamic::from_unit() - } else { - v.clone() - }, - IndexValue::from_num(index), - ) - }) + arr.get_mut(index as usize) + .map(Target::from) .ok_or_else(|| { Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)) }) @@ -850,43 +1045,33 @@ impl Engine { } } - Union::Map(map) => { + Dynamic(Union::Map(map)) => { // val_map[idx] - let index = self - .eval_expr(scope, fn_lib, idx_expr, level)? + let index = idx .take_string() - .map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_expr.position()))?; + .map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?; - Ok(( - map.get(&index) - .map(|v| { - if only_index { - Dynamic::from_unit() - } else { - v.clone() - } - }) - .unwrap_or_else(|| Dynamic::from_unit()), - IndexValue::from_str(index), - )) + Ok(if create { + map.entry(index).or_insert(().into()).into() + } else { + map.get_mut(&index) + .map(Target::from) + .unwrap_or_else(|| Target::from(())) + }) } - Union::Str(s) => { + Dynamic(Union::Str(s)) => { // val_string[idx] - let index = self - .eval_expr(scope, fn_lib, idx_expr, level)? + let index = idx .as_int() - .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_expr.position()))?; + .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?; let num_chars = s.chars().count(); if index >= 0 { - s.chars() - .nth(index as usize) - .map(|ch| (Dynamic::from_char(ch), IndexValue::from_num(index))) - .ok_or_else(|| { - Box::new(EvalAltResult::ErrorStringBounds(num_chars, index, idx_pos)) - }) + let index = index as usize; + let ch = s.chars().nth(index).unwrap(); + Ok(Target::StringChar(Box::new((val, index, ch.into())))) } else { Err(Box::new(EvalAltResult::ErrorStringBounds( num_chars, index, idx_pos, @@ -902,236 +1087,22 @@ impl Engine { } } - /// Evaluate an index expression - fn eval_index_expr<'a>( - &self, - scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, - lhs: &'a Expr, - idx_expr: &Expr, - op_pos: Position, - level: usize, - ) -> Result<(Option>, IndexValue, Dynamic), Box> { - match lhs { - // id[idx_expr] - Expr::Variable(name, _) => { - let (ScopeSource { typ, index, .. }, val) = - search_scope(scope, &name, lhs.position())?; - let (val, idx) = - self.get_indexed_val(scope, fn_lib, &val, idx_expr, op_pos, level, false)?; - - Ok((Some(ScopeSource { name, typ, index }), idx, val)) - } - - // (expr)[idx_expr] - expr => { - let val = self.eval_expr(scope, fn_lib, expr, level)?; - self.get_indexed_val(scope, fn_lib, &val, idx_expr, op_pos, level, false) - .map(|(val, index)| (None, index, val)) - } - } - } - - /// Chain-evaluate a dot setter - fn dot_set_helper( - &self, - scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, - this_ptr: &mut Dynamic, - dot_rhs: &Expr, - new_val: &mut Dynamic, - val_pos: Position, - level: usize, - ) -> Result> { - match dot_rhs { - // xxx.id - Expr::Property(id, pos) => { - let mut args = [this_ptr, new_val]; - self.call_fn_raw(None, fn_lib, &make_setter(id), &mut args, None, *pos, 0) - } - - // xxx.lhs[idx_expr] - // TODO - Allow chaining of indexing! - Expr::Index(lhs, idx_expr, op_pos) => match lhs.as_ref() { - // xxx.id[idx_expr] - Expr::Property(id, pos) => { - let fn_name = make_getter(id); - self.call_fn_raw(None, fn_lib, &fn_name, &mut [this_ptr], None, *pos, 0) - .and_then(|val| { - let (_, index) = self.get_indexed_val( - scope, fn_lib, &val, idx_expr, *op_pos, level, true, - )?; - - update_indexed_val(val, index, new_val.clone(), val_pos) - }) - .and_then(|mut val| { - let fn_name = make_setter(id); - let mut args = [this_ptr, &mut val]; - self.call_fn_raw(None, fn_lib, &fn_name, &mut args, None, *pos, 0) - }) - } - - // All others - syntax error for setters chain - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "for assignment".to_string(), - *op_pos, - ))), - }, - - // xxx.lhs.{...} - Expr::Dot(lhs, rhs, _) => match lhs.as_ref() { - // xxx.id.rhs - Expr::Property(id, pos) => { - let fn_name = make_getter(id); - self.call_fn_raw(None, fn_lib, &fn_name, &mut [this_ptr], None, *pos, 0) - .and_then(|mut val| { - self.dot_set_helper( - scope, fn_lib, &mut val, rhs, new_val, val_pos, level, - )?; - Ok(val) - }) - .and_then(|mut val| { - let fn_name = make_setter(id); - let mut args = [this_ptr, &mut val]; - self.call_fn_raw(None, fn_lib, &fn_name, &mut args, None, *pos, 0) - }) - } - - // xxx.lhs[idx_expr].rhs - // TODO - Allow chaining of indexing! - Expr::Index(lhs, idx_expr, op_pos) => match lhs.as_ref() { - // xxx.id[idx_expr].rhs - Expr::Property(id, pos) => { - let fn_name = make_getter(id); - self.call_fn_raw(None, fn_lib, &fn_name, &mut [this_ptr], None, *pos, 0) - .and_then(|v| { - let (mut value, index) = self.get_indexed_val( - scope, fn_lib, &v, idx_expr, *op_pos, level, false, - )?; - - self.dot_set_helper( - scope, fn_lib, &mut value, rhs, new_val, val_pos, level, - )?; - - // In case the expression mutated `target`, we need to update it back into the scope because it is cloned. - update_indexed_val(v, index, value, val_pos) - }) - .and_then(|mut v| { - let fn_name = make_setter(id); - let mut args = [this_ptr, &mut v]; - self.call_fn_raw(None, fn_lib, &fn_name, &mut args, None, *pos, 0) - }) - } - - // All others - syntax error for setters chain - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "for assignment".to_string(), - *op_pos, - ))), - }, - - // All others - syntax error for setters chain - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "for assignment".to_string(), - lhs.position(), - ))), - }, - - // Syntax error - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "for assignment".to_string(), - dot_rhs.position(), - ))), - } - } - - // Evaluate a dot chain setter - fn dot_set( - &self, - scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, - dot_lhs: &Expr, - dot_rhs: &Expr, - new_val: &mut Dynamic, - val_pos: Position, - op_pos: Position, - level: usize, - ) -> Result> { - match dot_lhs { - // id.??? - Expr::Variable(id, pos) => { - let (src, mut target) = search_scope(scope, id, *pos)?; - - match src.typ { - ScopeEntryType::Constant => Err(Box::new( - EvalAltResult::ErrorAssignmentToConstant(id.to_string(), op_pos), - )), - _ => { - // Avoid referencing scope which is used below as mut - let entry = ScopeSource { name: id, ..src }; - let this_ptr = &mut target; - let value = self.dot_set_helper( - scope, fn_lib, this_ptr, dot_rhs, new_val, val_pos, level, - ); - - // In case the expression mutated `target`, we need to update it back into the scope because it is cloned. - *scope.get_mut(entry) = target; - - value - } - } - } - - // lhs[idx_expr].??? - // TODO - Allow chaining of indexing! - Expr::Index(lhs, idx_expr, op_pos) => { - let (src, index, mut target) = - self.eval_index_expr(scope, fn_lib, lhs, idx_expr, *op_pos, level)?; - let this_ptr = &mut target; - let value = - self.dot_set_helper(scope, fn_lib, this_ptr, dot_rhs, new_val, val_pos, level); - - // In case the expression mutated `target`, we need to update it back into the scope because it is cloned. - if let Some(src) = src { - match src.typ { - ScopeEntryType::Constant => { - return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( - src.name.to_string(), - lhs.position(), - ))); - } - ScopeEntryType::Normal => { - update_indexed_scope_var(scope, src, index, target, val_pos)?; - } - } - } - - value - } - - // Syntax error - _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "for assignment".to_string(), - dot_lhs.position(), - ))), - } - } - // Evaluate an 'in' expression fn eval_in_expr( &self, scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, + state: &mut State, + fn_lib: &FunctionsLib, lhs: &Expr, rhs: &Expr, level: usize, ) -> Result> { - let mut lhs_value = self.eval_expr(scope, fn_lib, lhs, level)?; - let rhs_value = self.eval_expr(scope, fn_lib, rhs, level)?; + let mut lhs_value = self.eval_expr(scope, state, fn_lib, lhs, level)?; + let rhs_value = self.eval_expr(scope, state, fn_lib, rhs, level)?; match rhs_value { Dynamic(Union::Array(mut rhs_value)) => { - let def_value = Dynamic::from_bool(false); + let def_value = false.into(); let mut result = false; // Call the '==' operator to compare each value @@ -1148,27 +1119,21 @@ impl Engine { } } - Ok(Dynamic::from_bool(result)) + Ok(result.into()) } Dynamic(Union::Map(rhs_value)) => { // Only allows String or char match lhs_value { - Dynamic(Union::Str(s)) => { - Ok(Dynamic::from_bool(rhs_value.contains_key(s.as_ref()))) - } - Dynamic(Union::Char(c)) => { - Ok(Dynamic::from_bool(rhs_value.contains_key(&c.to_string()))) - } + Dynamic(Union::Str(s)) => Ok(rhs_value.contains_key(s.as_ref()).into()), + Dynamic(Union::Char(c)) => Ok(rhs_value.contains_key(&c.to_string()).into()), _ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))), } } Dynamic(Union::Str(rhs_value)) => { // Only allows String or char match lhs_value { - Dynamic(Union::Str(s)) => { - Ok(Dynamic::from_bool(rhs_value.contains(s.as_ref()))) - } - Dynamic(Union::Char(c)) => Ok(Dynamic::from_bool(rhs_value.contains(c))), + Dynamic(Union::Str(s)) => Ok(rhs_value.contains(s.as_ref()).into()), + Dynamic(Union::Char(c)) => Ok(rhs_value.contains(c).into()), _ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))), } } @@ -1180,29 +1145,33 @@ impl Engine { fn eval_expr( &self, scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, + state: &mut State, + fn_lib: &FunctionsLib, expr: &Expr, level: usize, ) -> Result> { match expr { - Expr::IntegerConstant(i, _) => Ok(Dynamic::from_int(*i)), + Expr::IntegerConstant(i, _) => Ok((*i).into()), #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(f, _) => Ok(Dynamic::from_float(*f)), - Expr::StringConstant(s, _) => Ok(Dynamic::from_string(s.to_string())), - Expr::CharConstant(c, _) => Ok(Dynamic::from_char(*c)), - Expr::Variable(id, pos) => search_scope(scope, id, *pos).map(|(_, val)| val), + Expr::FloatConstant(f, _) => Ok((*f).into()), + Expr::StringConstant(s, _) => Ok(s.to_string().into()), + Expr::CharConstant(c, _) => Ok((*c).into()), + Expr::Variable(_, Some(index), _) if !state.always_search => { + Ok(scope.get_mut(scope.len() - index.get()).0.clone()) + } + Expr::Variable(id, _, pos) => search_scope(scope, id, *pos).map(|(v, _)| v.clone()), Expr::Property(_, _) => panic!("unexpected property."), // Statement block - Expr::Stmt(stmt, _) => self.eval_stmt(scope, fn_lib, stmt, level), + Expr::Stmt(stmt, _) => self.eval_stmt(scope, state, fn_lib, stmt, level), // lhs = rhs Expr::Assignment(lhs, rhs, op_pos) => { - let mut rhs_val = self.eval_expr(scope, fn_lib, rhs, level)?; + let rhs_val = self.eval_expr(scope, state, fn_lib, rhs, level)?; match lhs.as_ref() { // name = rhs - Expr::Variable(name, pos) => match scope.get(name) { + Expr::Variable(name, _, pos) => match scope.get(name) { None => { return Err(Box::new(EvalAltResult::ErrorVariableNotFound( name.to_string(), @@ -1210,69 +1179,33 @@ impl Engine { ))) } - Some(( - entry - @ - ScopeSource { - typ: ScopeEntryType::Normal, - .. - }, - _, - )) => { + Some((index, ScopeEntryType::Normal)) => { // Avoid referencing scope which is used below as mut - let entry = ScopeSource { name, ..entry }; - *scope.get_mut(entry) = rhs_val.clone(); + *scope.get_mut(index).0 = rhs_val.clone(); Ok(rhs_val) } - Some(( - ScopeSource { - typ: ScopeEntryType::Constant, - .. - }, - _, - )) => Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( - name.to_string(), - *op_pos, - ))), + Some((_, ScopeEntryType::Constant)) => Err(Box::new( + EvalAltResult::ErrorAssignmentToConstant(name.to_string(), *op_pos), + )), }, // idx_lhs[idx_expr] = rhs #[cfg(not(feature = "no_index"))] Expr::Index(idx_lhs, idx_expr, op_pos) => { - let (src, index, _) = - self.eval_index_expr(scope, fn_lib, idx_lhs, idx_expr, *op_pos, level)?; - - if let Some(src) = src { - match src.typ { - ScopeEntryType::Constant => { - Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( - src.name.to_string(), - idx_lhs.position(), - ))) - } - ScopeEntryType::Normal => { - let pos = rhs.position(); - Ok(update_indexed_scope_var(scope, src, index, rhs_val, pos)?) - } - } - } else { - Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS( - idx_lhs.position(), - ))) - } + let new_val = Some(rhs_val); + self.eval_dot_index_chain( + scope, state, fn_lib, idx_lhs, idx_expr, true, *op_pos, level, new_val, + ) } - // dot_lhs.dot_rhs = rhs #[cfg(not(feature = "no_object"))] Expr::Dot(dot_lhs, dot_rhs, _) => { - let new_val = &mut rhs_val; - let val_pos = rhs.position(); - self.dot_set( - scope, fn_lib, dot_lhs, dot_rhs, new_val, val_pos, *op_pos, level, + let new_val = Some(rhs_val); + self.eval_dot_index_chain( + scope, state, fn_lib, dot_lhs, dot_rhs, false, *op_pos, level, new_val, ) } - // Error assignment to constant expr if expr.is_constant() => { Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( @@ -1290,19 +1223,22 @@ impl Engine { // lhs[idx_expr] #[cfg(not(feature = "no_index"))] - Expr::Index(lhs, idx_expr, op_pos) => self - .eval_index_expr(scope, fn_lib, lhs, idx_expr, *op_pos, level) - .map(|(_, _, x)| x), + Expr::Index(lhs, idx_expr, op_pos) => self.eval_dot_index_chain( + scope, state, fn_lib, lhs, idx_expr, true, *op_pos, level, None, + ), + // lhs.dot_rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(lhs, rhs, _) => self.dot_get(scope, fn_lib, lhs, rhs, level), + Expr::Dot(lhs, dot_rhs, op_pos) => self.eval_dot_index_chain( + scope, state, fn_lib, lhs, dot_rhs, false, *op_pos, level, None, + ), #[cfg(not(feature = "no_index"))] Expr::Array(contents, _) => { let mut arr = Array::new(); contents.into_iter().try_for_each(|item| { - self.eval_expr(scope, fn_lib, item, level) + self.eval_expr(scope, state, fn_lib, item, level) .map(|val| arr.push(val)) })?; @@ -1314,138 +1250,85 @@ impl Engine { let mut map = Map::new(); contents.into_iter().try_for_each(|(key, expr, _)| { - self.eval_expr(scope, fn_lib, &expr, level).map(|val| { - map.insert(key.clone(), val); - }) + self.eval_expr(scope, state, fn_lib, &expr, level) + .map(|val| { + map.insert(key.clone(), val); + }) })?; Ok(Dynamic(Union::Map(Box::new(map)))) } - Expr::FunctionCall(fn_name, args_expr_list, def_val, pos) => { - // Has a system function an override? - fn has_override( - engine: &Engine, - fn_lib: Option<&FunctionsLib>, - name: &str, - ) -> bool { - engine - .functions - .contains_key(&calc_fn_spec(name, once(TypeId::of::()))) - || fn_lib.map_or(false, |lib| lib.has_function(name, 1)) + Expr::FunctionCall(fn_name, arg_exprs, def_val, pos) => { + let mut arg_values = arg_exprs + .iter() + .map(|expr| self.eval_expr(scope, state, fn_lib, expr, level)) + .collect::, _>>()?; + + let mut args: Vec<_> = arg_values.iter_mut().collect(); + + // eval - only in function call style + if fn_name == KEYWORD_EVAL + && args.len() == 1 + && !self.has_override(fn_lib, KEYWORD_EVAL) + { + let prev_len = scope.len(); + + // Evaluate the text string as a script + let result = + self.eval_script_expr(scope, fn_lib, args[0], arg_exprs[0].position()); + + if scope.len() != prev_len { + // IMPORTANT! If the eval defines new variables in the current scope, + // all variable offsets from this point on will be mis-aligned. + state.always_search = true; + } + + return result; } - match fn_name.as_ref() { - // type_of - KEYWORD_TYPE_OF - if args_expr_list.len() == 1 - && !has_override(self, fn_lib, KEYWORD_TYPE_OF) => - { - let result = self.eval_expr(scope, fn_lib, &args_expr_list[0], level)?; - Ok(Dynamic::from_string( - self.map_type_name(result.type_name()).to_string(), - )) - } - - // eval - KEYWORD_EVAL - if args_expr_list.len() == 1 - && !has_override(self, fn_lib, KEYWORD_EVAL) => - { - let pos = args_expr_list[0].position(); - let result = self.eval_expr(scope, fn_lib, &args_expr_list[0], level)?; - - // Get the script text by evaluating the expression - let script = result.as_str().map_err(|type_name| { - EvalAltResult::ErrorMismatchOutputType(type_name.into(), pos) - })?; - - // Compile the script text - // No optimizations because we only run it once - let mut ast = self - .compile_with_scope_and_optimization_level( - &Scope::new(), - script, - OptimizationLevel::None, - ) - .map_err(|err| EvalAltResult::ErrorParsing(Box::new(err)))?; - - // If new functions are defined within the eval string, it is an error - if ast.1.len() > 0 { - return Err(Box::new(EvalAltResult::ErrorParsing( - ParseErrorType::WrongFnDefinition.into_err(pos), - ))); - } - - if let Some(lib) = fn_lib { - #[cfg(feature = "sync")] - { - ast.1 = Arc::new(lib.clone()); - } - #[cfg(not(feature = "sync"))] - { - ast.1 = Rc::new(lib.clone()); - } - } - - // Evaluate the AST - self.eval_ast_with_scope_raw(scope, &ast) - .map_err(|err| Box::new(err.set_position(pos))) - } - - // Normal function call - _ => { - let mut arg_values = args_expr_list - .iter() - .map(|expr| self.eval_expr(scope, fn_lib, expr, level)) - .collect::, _>>()?; - - let mut args: Vec<_> = arg_values.iter_mut().collect(); - let def_val = def_val.as_ref(); - self.call_fn_raw(None, fn_lib, fn_name, &mut args, def_val, *pos, level) - } - } + // Normal function call + let def_val = def_val.as_deref(); + self.exec_fn_call(fn_lib, fn_name, &mut args, def_val, *pos, level) } Expr::In(lhs, rhs, _) => { - self.eval_in_expr(scope, fn_lib, lhs.as_ref(), rhs.as_ref(), level) + self.eval_in_expr(scope, state, fn_lib, lhs.as_ref(), rhs.as_ref(), level) } - Expr::And(lhs, rhs, _) => Ok(Dynamic::from_bool( - self - .eval_expr(scope, fn_lib,lhs.as_ref(), level)? + Expr::And(lhs, rhs, _) => Ok((self + .eval_expr(scope, state, fn_lib, lhs.as_ref(), level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position()) })? && // Short-circuit using && self - .eval_expr(scope, fn_lib,rhs.as_ref(), level)? + .eval_expr(scope, state, fn_lib, rhs.as_ref(), level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("AND".into(), rhs.position()) - })?, - )), + })?) + .into()), - Expr::Or(lhs, rhs, _) => Ok(Dynamic::from_bool( - self - .eval_expr(scope,fn_lib, lhs.as_ref(), level)? + Expr::Or(lhs, rhs, _) => Ok((self + .eval_expr(scope, state, fn_lib, lhs.as_ref(), level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position()) })? || // Short-circuit using || self - .eval_expr(scope,fn_lib, rhs.as_ref(), level)? + .eval_expr(scope, state, fn_lib, rhs.as_ref(), level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("OR".into(), rhs.position()) - })?, - )), + })?) + .into()), - Expr::True(_) => Ok(Dynamic::from_bool(true)), - Expr::False(_) => Ok(Dynamic::from_bool(false)), - Expr::Unit(_) => Ok(Dynamic::from_unit()), + Expr::True(_) => Ok(true.into()), + Expr::False(_) => Ok(false.into()), + Expr::Unit(_) => Ok(().into()), _ => panic!("should not appear: {:?}", expr), } @@ -1455,23 +1338,24 @@ impl Engine { pub(crate) fn eval_stmt( &self, scope: &mut Scope, - fn_lib: Option<&FunctionsLib>, + state: &mut State, + fn_lib: &FunctionsLib, stmt: &Stmt, level: usize, ) -> Result> { match stmt { // No-op - Stmt::Noop(_) => Ok(Dynamic::from_unit()), + Stmt::Noop(_) => Ok(().into()), // Expression as statement Stmt::Expr(expr) => { - let result = self.eval_expr(scope, fn_lib, expr, level)?; + let result = self.eval_expr(scope, state, fn_lib, expr, level)?; - Ok(if !matches!(expr.as_ref(), Expr::Assignment(_, _, _)) { - result - } else { + Ok(if let Expr::Assignment(_, _, _) = *expr.as_ref() { // If it is an assignment, erase the result at the root - Dynamic::from_unit() + ().into() + } else { + result }) } @@ -1479,44 +1363,49 @@ impl Engine { Stmt::Block(block, _) => { let prev_len = scope.len(); - let result = block.iter().try_fold(Dynamic::from_unit(), |_, stmt| { - self.eval_stmt(scope, fn_lib, stmt, level) + let result = block.iter().try_fold(().into(), |_, stmt| { + self.eval_stmt(scope, state, fn_lib, stmt, level) }); scope.rewind(prev_len); + // The impact of an eval statement goes away at the end of a block + // because any new variables introduced will go out of scope + state.always_search = false; + result } // If-else statement Stmt::IfThenElse(guard, if_body, else_body) => self - .eval_expr(scope, fn_lib, guard, level)? + .eval_expr(scope, state, fn_lib, guard, level)? .as_bool() .map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(guard.position()))) .and_then(|guard_val| { if guard_val { - self.eval_stmt(scope, fn_lib, if_body, level) + self.eval_stmt(scope, state, fn_lib, if_body, level) } else if let Some(stmt) = else_body { - self.eval_stmt(scope, fn_lib, stmt.as_ref(), level) + self.eval_stmt(scope, state, fn_lib, stmt.as_ref(), level) } else { - Ok(Dynamic::from_unit()) + Ok(().into()) } }), // While loop Stmt::While(guard, body) => loop { - match self.eval_expr(scope, fn_lib, guard, level)?.as_bool() { - Ok(true) => match self.eval_stmt(scope, fn_lib, body, level) { + match self + .eval_expr(scope, state, fn_lib, guard, level)? + .as_bool() + { + Ok(true) => match self.eval_stmt(scope, state, fn_lib, body, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), - EvalAltResult::ErrorLoopBreak(true, _) => { - return Ok(Dynamic::from_unit()) - } + EvalAltResult::ErrorLoopBreak(true, _) => return Ok(().into()), _ => return Err(err), }, }, - Ok(false) => return Ok(Dynamic::from_unit()), + Ok(false) => return Ok(().into()), Err(_) => { return Err(Box::new(EvalAltResult::ErrorLogicGuard(guard.position()))) } @@ -1525,11 +1414,11 @@ impl Engine { // Loop statement Stmt::Loop(body) => loop { - match self.eval_stmt(scope, fn_lib, body, level) { + match self.eval_stmt(scope, state, fn_lib, body, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), - EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Dynamic::from_unit()), + EvalAltResult::ErrorLoopBreak(true, _) => return Ok(().into()), _ => return Err(err), }, } @@ -1537,24 +1426,23 @@ impl Engine { // For loop Stmt::For(name, expr, body) => { - let arr = self.eval_expr(scope, fn_lib, expr, level)?; + let arr = self.eval_expr(scope, state, fn_lib, expr, level)?; let tid = arr.type_id(); - if let Some(iter_fn) = self.type_iterators.get(&tid) { - // Add the loop variable - variable name is copied - // TODO - avoid copying variable name + if let Some(iter_fn) = self.type_iterators.get(&tid).or_else(|| { + self.packages + .iter() + .find(|pkg| pkg.type_iterators.contains_key(&tid)) + .and_then(|pkg| pkg.type_iterators.get(&tid)) + }) { + // Add the loop variable scope.push(name.clone(), ()); + let index = scope.len() - 1; - let entry = ScopeSource { - name, - index: scope.len() - 1, - typ: ScopeEntryType::Normal, - }; + for a in iter_fn(arr) { + *scope.get_mut(index).0 = a; - for a in iter_fn(&arr) { - *scope.get_mut(entry) = a; - - match self.eval_stmt(scope, fn_lib, body, level) { + match self.eval_stmt(scope, state, fn_lib, body, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), @@ -1565,7 +1453,7 @@ impl Engine { } scope.rewind(scope.len() - 1); - Ok(Dynamic::from_unit()) + Ok(().into()) } else { Err(Box::new(EvalAltResult::ErrorFor(expr.position()))) } @@ -1579,12 +1467,12 @@ impl Engine { // Empty return Stmt::ReturnWithVal(None, ReturnType::Return, pos) => { - Err(Box::new(EvalAltResult::Return(Dynamic::from_unit(), *pos))) + Err(Box::new(EvalAltResult::Return(().into(), *pos))) } // Return value Stmt::ReturnWithVal(Some(a), ReturnType::Return, pos) => Err(Box::new( - EvalAltResult::Return(self.eval_expr(scope, fn_lib, a, level)?, *pos), + EvalAltResult::Return(self.eval_expr(scope, state, fn_lib, a, level)?, *pos), )), // Empty throw @@ -1594,7 +1482,7 @@ impl Engine { // Throw value Stmt::ReturnWithVal(Some(a), ReturnType::Exception, pos) => { - let val = self.eval_expr(scope, fn_lib, a, level)?; + let val = self.eval_expr(scope, state, fn_lib, a, level)?; Err(Box::new(EvalAltResult::ErrorRuntime( val.take_string().unwrap_or_else(|_| "".to_string()), *pos, @@ -1603,24 +1491,24 @@ impl Engine { // Let statement Stmt::Let(name, Some(expr), _) => { - let val = self.eval_expr(scope, fn_lib, expr, level)?; + let val = self.eval_expr(scope, state, fn_lib, expr, level)?; // TODO - avoid copying variable name in inner block? scope.push_dynamic_value(name.clone(), ScopeEntryType::Normal, val, false); - Ok(Dynamic::from_unit()) + Ok(().into()) } Stmt::Let(name, None, _) => { // TODO - avoid copying variable name in inner block? scope.push(name.clone(), ()); - Ok(Dynamic::from_unit()) + Ok(().into()) } // Const statement Stmt::Const(name, expr, _) if expr.is_constant() => { - let val = self.eval_expr(scope, fn_lib, expr, level)?; + let val = self.eval_expr(scope, state, fn_lib, expr, level)?; // TODO - avoid copying variable name in inner block? scope.push_dynamic_value(name.clone(), ScopeEntryType::Constant, val, true); - Ok(Dynamic::from_unit()) + Ok(().into()) } Stmt::Const(_, _, _) => panic!("constant expression not constant!"), @@ -1630,8 +1518,8 @@ impl Engine { /// Map a type_name into a pretty-print name pub(crate) fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str { self.type_names - .as_ref() - .and_then(|list| list.get(name).map(String::as_str)) + .get(name) + .map(String::as_str) .unwrap_or(name) } } diff --git a/src/error.rs b/src/error.rs index 4de71bbf..b08e5975 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,7 +2,7 @@ use crate::token::Position; -use crate::stdlib::{char, error::Error, fmt, string::String}; +use crate::stdlib::{boxed::Box, char, error::Error, fmt, string::String}; /// Error when tokenizing the script text. #[derive(Debug, Eq, PartialEq, Hash, Clone)] @@ -19,6 +19,8 @@ pub enum LexError { MalformedChar(String), /// An identifier is in an invalid format. MalformedIdentifier(String), + /// Bad keyword encountered when tokenizing the script text. + ImproperKeyword(String), } impl Error for LexError {} @@ -32,6 +34,7 @@ impl fmt::Display for LexError { Self::MalformedChar(s) => write!(f, "Invalid character: '{}'", s), Self::MalformedIdentifier(s) => write!(f, "Variable name is not proper: '{}'", s), Self::UnterminatedString => write!(f, "Open string is not terminated"), + Self::ImproperKeyword(s) => write!(f, "{}", s), } } } @@ -97,8 +100,6 @@ pub enum ParseErrorType { FnMissingBody(String), /// Assignment to an inappropriate LHS (left-hand-side) expression. AssignmentToInvalidLHS, - /// Assignment to a copy of a value. - AssignmentToCopy, /// Assignment to an a constant variable. AssignmentToConstant(String), /// Break statement not inside a loop. @@ -147,7 +148,6 @@ impl ParseError { ParseErrorType::FnMissingBody(_) => "Expecting body statement block for function declaration", ParseErrorType::WrongFnDefinition => "Function definitions must be at global level and cannot be inside a block or another function", ParseErrorType::AssignmentToInvalidLHS => "Cannot assign to this expression", - ParseErrorType::AssignmentToCopy => "Cannot assign to this expression because it will only be changing a copy of the value", ParseErrorType::AssignmentToConstant(_) => "Cannot assign to a constant variable.", ParseErrorType::LoopBreak => "Break statement should only be used inside a loop" } diff --git a/src/fn_call.rs b/src/fn_call.rs index 29a9c056..a28522de 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -5,15 +5,15 @@ use crate::any::{Dynamic, Variant}; use crate::stdlib::vec::Vec; -/// Trait that represent arguments to a function call. -/// Any data type that can be converted into a `Vec` of `Dynamic` values can be used +/// Trait that represents arguments to a function call. +/// Any data type that can be converted into a `Vec` can be used /// as arguments to a function call. pub trait FuncArgs { - /// Convert to a `Vec` of `Dynamic` arguments. + /// Convert to a `Vec` of the function call arguments. fn into_vec(self) -> Vec; } -// Macro to implement `FuncArgs` for tuples of standard types (each can be +/// Macro to implement `FuncArgs` for tuples of standard types (each can be /// converted into `Dynamic`). macro_rules! impl_args { ($($p:ident),*) => { diff --git a/src/fn_func.rs b/src/fn_func.rs index 4c3544de..b9add7e4 100644 --- a/src/fn_func.rs +++ b/src/fn_func.rs @@ -21,18 +21,18 @@ pub trait Func { /// # Examples /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Func}; // use 'Func' for 'create_from_ast' /// /// let engine = Engine::new(); // create a new 'Engine' just for this /// - /// let ast = engine.compile("fn calc(x, y) { x + y.len() < 42 }")?; + /// let ast = engine.compile("fn calc(x, y) { x + len(y) < 42 }")?; /// /// // Func takes two type parameters: /// // 1) a tuple made up of the types of the script function's parameters /// // 2) the return type of the script function /// // - /// // 'func' will have type Box Result> and is callable! + /// // 'func' will have type Box Result>> and is callable! /// let func = Func::<(i64, String), bool>::create_from_ast( /// // ^^^^^^^^^^^^^ function parameter types in tuple /// @@ -52,18 +52,18 @@ pub trait Func { /// # Examples /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Func}; // use 'Func' for 'create_from_script' /// /// let engine = Engine::new(); // create a new 'Engine' just for this /// - /// let script = "fn calc(x, y) { x + y.len() < 42 }"; + /// let script = "fn calc(x, y) { x + len(y) < 42 }"; /// /// // Func takes two type parameters: /// // 1) a tuple made up of the types of the script function's parameters /// // 2) the return type of the script function /// // - /// // 'func' will have type Box Result> and is callable! + /// // 'func' will have type Box Result>> and is callable! /// let func = Func::<(i64, String), bool>::create_from_script( /// // ^^^^^^^^^^^^^ function parameter types in tuple /// @@ -80,7 +80,7 @@ pub trait Func { self, script: &str, entry_point: &str, - ) -> Result; + ) -> Result>; } macro_rules! def_anonymous_fn { @@ -91,10 +91,10 @@ macro_rules! def_anonymous_fn { impl<$($par: Variant + Clone,)* RET: Variant + Clone> Func<($($par,)*), RET> for Engine { #[cfg(feature = "sync")] - type Output = Box Result + Send + Sync>; + type Output = Box Result> + Send + Sync>; #[cfg(not(feature = "sync"))] - type Output = Box Result>; + type Output = Box Result>>; fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output { let name = entry_point.to_string(); @@ -104,7 +104,7 @@ macro_rules! def_anonymous_fn { }) } - fn create_from_script(self, script: &str, entry_point: &str) -> Result { + fn create_from_script(self, script: &str, entry_point: &str) -> Result> { let ast = self.compile(script)?; Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point)) } diff --git a/src/fn_register.rs b/src/fn_register.rs index 5941095e..e711ee54 100644 --- a/src/fn_register.rs +++ b/src/fn_register.rs @@ -3,11 +3,11 @@ #![allow(non_snake_case)] use crate::any::{Dynamic, Variant}; -use crate::engine::{Engine, FnCallArgs}; +use crate::engine::{calc_fn_spec, Engine, FnCallArgs}; use crate::result::EvalAltResult; use crate::token::Position; -use crate::stdlib::{any::TypeId, boxed::Box, string::ToString, vec}; +use crate::stdlib::{any::TypeId, boxed::Box, string::ToString}; /// A trait to register custom functions with the `Engine`. pub trait RegisterFn { @@ -16,7 +16,7 @@ pub trait RegisterFn { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, RegisterFn}; /// /// // Normal function @@ -48,7 +48,7 @@ pub trait RegisterDynamicFn { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Dynamic, RegisterDynamicFn}; /// /// // Function that returns a Dynamic value @@ -68,7 +68,7 @@ pub trait RegisterDynamicFn { fn register_dynamic_fn(&mut self, name: &str, f: FN); } -/// A trait to register fallible custom functions returning Result<_, EvalAltResult> with the `Engine`. +/// A trait to register fallible custom functions returning `Result<_, Box>` with the `Engine`. pub trait RegisterResultFn { /// Register a custom fallible function with the `Engine`. /// @@ -78,9 +78,9 @@ pub trait RegisterResultFn { /// use rhai::{Engine, RegisterResultFn, EvalAltResult}; /// /// // Normal function - /// fn div(x: i64, y: i64) -> Result { + /// fn div(x: i64, y: i64) -> Result> { /// if y == 0 { - /// // '.into()' automatically converts to 'EvalAltResult::ErrorRuntime' + /// // '.into()' automatically converts to 'Box' /// Err("division by zero!".into()) /// } else { /// Ok(x / y) @@ -117,16 +117,79 @@ pub struct Mut(T); /// Identity dereferencing function. #[inline] -fn identity(data: T) -> T { +pub fn identity(data: &mut T) -> &mut T { data } +/// Clone dereferencing function. +#[inline] +pub fn cloned(data: &mut T) -> T { + data.clone() +} + /// This macro counts the number of arguments via recursion. macro_rules! count_args { () => { 0_usize }; ( $head:ident $($tail:ident)* ) => { 1_usize + count_args!($($tail)*) }; } +/// This macro creates a closure wrapping a registered function. +macro_rules! make_func { + ($fn_name:ident : $fn:ident : $map:expr ; $($par:ident => $clone:expr),*) => { +// ^ function name +// ^ function pointer +// ^ result mapping function +// ^ function parameter generic type name (A, B, C etc.) +// ^ dereferencing function + + move |args: &mut FnCallArgs, pos: Position| { + // Check for length at the beginning to avoid per-element bound checks. + const NUM_ARGS: usize = count_args!($($par)*); + + if args.len() != NUM_ARGS { + return Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch($fn_name.clone(), NUM_ARGS, args.len(), pos))); + } + + #[allow(unused_variables, unused_mut)] + let mut drain = args.iter_mut(); + $( + // Downcast every element, return in case of a type mismatch + let $par: &mut $par = drain.next().unwrap().downcast_mut().unwrap(); + )* + + // Call the user-supplied function using ($clone) to + // potentially clone the value, otherwise pass the reference. + let r = $fn($(($clone)($par)),*); + $map(r, pos) + }; + }; +} + +/// To Dynamic mapping function. +#[inline] +pub fn map_dynamic( + data: T, + _pos: Position, +) -> Result> { + Ok(data.into_dynamic()) +} + +/// To Dynamic mapping function. +#[inline] +pub fn map_identity(data: Dynamic, _pos: Position) -> Result> { + Ok(data) +} + +/// To `Result>` mapping function. +#[inline] +pub fn map_result( + data: Result>, + pos: Position, +) -> Result> { + data.map(|v| v.into_dynamic()) + .map_err(|err| EvalAltResult::set_position(err, pos)) +} + macro_rules! def_register { () => { def_register!(imp); @@ -150,29 +213,9 @@ macro_rules! def_register { { fn register_fn(&mut self, name: &str, f: FN) { let fn_name = name.to_string(); - - let func = move |args: &mut FnCallArgs, pos: Position| { - // Check for length at the beginning to avoid per-element bound checks. - const NUM_ARGS: usize = count_args!($($par)*); - - if args.len() != NUM_ARGS { - return Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch(fn_name.clone(), NUM_ARGS, args.len(), pos))); - } - - #[allow(unused_variables, unused_mut)] - let mut drain = args.iter_mut(); - $( - // Downcast every element, return in case of a type mismatch - let $par: &mut $par = drain.next().unwrap().downcast_mut().unwrap(); - )* - - // Call the user-supplied function using ($clone) to - // potentially clone the value, otherwise pass the reference. - let r = f($(($clone)($par)),*); - Ok(r.into_dynamic()) - }; - - self.register_fn_raw(name, vec![$(TypeId::of::<$par>()),*], Box::new(func)); + let func = make_func!(fn_name : f : map_dynamic ; $($par => $clone),*); + let hash = calc_fn_spec(name, [$(TypeId::of::<$par>()),*].iter().cloned()); + self.functions.insert(hash, Box::new(func)); } } @@ -188,27 +231,9 @@ macro_rules! def_register { { fn register_dynamic_fn(&mut self, name: &str, f: FN) { let fn_name = name.to_string(); - - let func = move |args: &mut FnCallArgs, pos: Position| { - // Check for length at the beginning to avoid per-element bound checks. - const NUM_ARGS: usize = count_args!($($par)*); - - if args.len() != NUM_ARGS { - return Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch(fn_name.clone(), NUM_ARGS, args.len(), pos))); - } - - #[allow(unused_variables, unused_mut)] - let mut drain = args.iter_mut(); - $( - // Downcast every element, return in case of a type mismatch - let $par: &mut $par = drain.next().unwrap().downcast_mut().unwrap(); - )* - - // Call the user-supplied function using ($clone) to - // potentially clone the value, otherwise pass the reference. - Ok(f($(($clone)($par)),*)) - }; - self.register_fn_raw(name, vec![$(TypeId::of::<$par>()),*], Box::new(func)); + let func = make_func!(fn_name : f : map_identity ; $($par => $clone),*); + let hash = calc_fn_spec(name, [$(TypeId::of::<$par>()),*].iter().cloned()); + self.functions.insert(hash, Box::new(func)); } } @@ -216,45 +241,26 @@ macro_rules! def_register { $($par: Variant + Clone,)* #[cfg(feature = "sync")] - FN: Fn($($param),*) -> Result + Send + Sync + 'static, + FN: Fn($($param),*) -> Result> + Send + Sync + 'static, #[cfg(not(feature = "sync"))] - FN: Fn($($param),*) -> Result + 'static, + FN: Fn($($param),*) -> Result> + 'static, RET: Variant + Clone > RegisterResultFn for Engine { fn register_result_fn(&mut self, name: &str, f: FN) { let fn_name = name.to_string(); - - let func = move |args: &mut FnCallArgs, pos: Position| { - // Check for length at the beginning to avoid per-element bound checks. - const NUM_ARGS: usize = count_args!($($par)*); - - if args.len() != NUM_ARGS { - return Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch(fn_name.clone(), NUM_ARGS, args.len(), pos))); - } - - #[allow(unused_variables, unused_mut)] - let mut drain = args.iter_mut(); - $( - // Downcast every element, return in case of a type mismatch - let $par: &mut $par = drain.next().unwrap().downcast_mut().unwrap(); - )* - - // Call the user-supplied function using ($clone) to - // potentially clone the value, otherwise pass the reference. - f($(($clone)($par)),*).map(|r| r.into_dynamic()) - .map_err(|err| Box::new(err.set_position(pos))) - }; - self.register_fn_raw(name, vec![$(TypeId::of::<$par>()),*], Box::new(func)); + let func = make_func!(fn_name : f : map_result ; $($par => $clone),*); + let hash = calc_fn_spec(name, [$(TypeId::of::<$par>()),*].iter().cloned()); + self.functions.insert(hash, Box::new(func)); } } //def_register!(imp_pop $($par => $mark => $param),*); }; ($p0:ident $(, $p:ident)*) => { - def_register!(imp $p0 => $p0 => $p0 => Clone::clone $(, $p => $p => $p => Clone::clone)*); - def_register!(imp $p0 => Mut<$p0> => &mut $p0 => identity $(, $p => $p => $p => Clone::clone)*); + def_register!(imp $p0 => $p0 => $p0 => cloned $(, $p => $p => $p => cloned)*); + def_register!(imp $p0 => Mut<$p0> => &mut $p0 => identity $(, $p => $p => $p => cloned)*); // handle the first parameter ^ first parameter passed through // ^ others passed by value (cloned) diff --git a/src/lib.rs b/src/lib.rs index de8e80db..e13eaf0f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,7 +23,7 @@ //! ```,no_run //! use rhai::{Engine, EvalAltResult, RegisterFn}; //! -//! fn main() -> Result<(), EvalAltResult> +//! fn main() -> Result<(), Box> //! { //! // Define external function //! fn compute_something(x: i64) -> bool { @@ -71,13 +71,13 @@ extern crate alloc; mod any; mod api; -mod builtin; mod engine; mod error; mod fn_call; mod fn_func; mod fn_register; mod optimize; +pub mod packages; mod parser; mod result; mod scope; @@ -85,7 +85,7 @@ mod stdlib; mod token; pub use any::Dynamic; -pub use engine::Engine; +pub use engine::{calc_fn_spec as calc_fn_hash, Engine}; pub use error::{ParseError, ParseErrorType}; pub use fn_call::FuncArgs; pub use fn_register::{RegisterDynamicFn, RegisterFn, RegisterResultFn}; diff --git a/src/optimize.rs b/src/optimize.rs index 39a5b995..a63075a3 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -1,8 +1,10 @@ use crate::any::Dynamic; +use crate::calc_fn_hash; use crate::engine::{ - calc_fn_spec, Engine, FnAny, FnCallArgs, FunctionsLib, KEYWORD_DEBUG, KEYWORD_EVAL, - KEYWORD_PRINT, KEYWORD_TYPE_OF, + Engine, FnAny, FnCallArgs, FunctionsLib, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_PRINT, + KEYWORD_TYPE_OF, }; +use crate::packages::PackageLibrary; use crate::parser::{map_dynamic_to_expr, Expr, FnDef, ReturnType, Stmt, AST}; use crate::result::EvalAltResult; use crate::scope::{Entry as ScopeEntry, EntryType as ScopeEntryType, Scope}; @@ -110,14 +112,23 @@ impl<'a> State<'a> { /// Call a registered function fn call_fn( + packages: &Vec, functions: &HashMap>, fn_name: &str, args: &mut FnCallArgs, pos: Position, ) -> Result, Box> { // Search built-in's and external functions + let hash = calc_fn_hash(fn_name, args.iter().map(|a| a.type_id())); + functions - .get(&calc_fn_spec(fn_name, args.iter().map(|a| a.type_id()))) + .get(&hash) + .or_else(|| { + packages + .iter() + .find(|p| p.functions.contains_key(&hash)) + .and_then(|p| p.functions.get(&hash)) + }) .map(|func| func(args, pos)) .transpose() } @@ -167,7 +178,7 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - Box::new(optimize_expr(expr, state)), Box::new(optimize_stmt(*if_block, state, true)), match optimize_stmt(*else_block, state, true) { - stmt if matches!(stmt, Stmt::Noop(_)) => None, // Noop -> no else block + Stmt::Noop(_) => None, // Noop -> no else block stmt => Some(Box::new(stmt)), }, ), @@ -357,12 +368,12 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { //id = id2 = expr2 Expr::Assignment(id2, expr2, pos2) => match (*id, *id2) { // var = var = expr2 -> var = expr2 - (Expr::Variable(var, _), Expr::Variable(var2, _)) if var == var2 => { + (Expr::Variable(var, sp, _), Expr::Variable(var2, sp2, _)) if var == var2 && sp == sp2 => { // Assignment to the same variable - fold state.set_dirty(); Expr::Assignment( - Box::new(Expr::Variable(var, pos)), + Box::new(Expr::Variable(var, sp, pos)), Box::new(optimize_expr(*expr2, state)), pos, ) @@ -386,13 +397,11 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { #[cfg(not(feature = "no_object"))] Expr::Dot(lhs, rhs, pos) => match (*lhs, *rhs) { // map.string - (Expr::Map(items, pos), Expr::Property(s, _)) - if items.iter().all(|(_, x, _)| x.is_pure()) => - { + (Expr::Map(items, pos), Expr::Property(s, _)) if items.iter().all(|(_, x, _)| x.is_pure()) => { // Map literal where everything is pure - promote the indexed item. // All other items can be thrown away. state.set_dirty(); - items.into_iter().find(|(name, _, _)| name == s.as_ref()) + items.into_iter().find(|(name, _, _)| name == &s) .map(|(_, expr, _)| expr.set_position(pos)) .unwrap_or_else(|| Expr::Unit(pos)) } @@ -417,13 +426,11 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { items.remove(i as usize).set_position(pos) } // map[string] - (Expr::Map(items, pos), Expr::StringConstant(s, _)) - if items.iter().all(|(_, x, _)| x.is_pure()) => - { + (Expr::Map(items, pos), Expr::StringConstant(s, _)) if items.iter().all(|(_, x, _)| x.is_pure()) => { // Map literal where everything is pure - promote the indexed item. // All other items can be thrown away. state.set_dirty(); - items.into_iter().find(|(name, _, _)| name == s.as_ref()) + items.into_iter().find(|(name, _, _)| name == &s) .map(|(_, expr, _)| expr.set_position(pos)) .unwrap_or_else(|| Expr::Unit(pos)) } @@ -459,7 +466,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { // "xxx" in "xxxxx" (Expr::StringConstant(lhs, pos), Expr::StringConstant(rhs, _)) => { state.set_dirty(); - if rhs.contains(lhs.as_ref()) { + if rhs.contains(&lhs) { Expr::True(pos) } else { Expr::False(pos) @@ -552,7 +559,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { // Do not call some special keywords Expr::FunctionCall(id, args, def_value, pos) if DONT_EVAL_KEYWORDS.contains(&id.as_ref())=> - Expr::FunctionCall(id, args.into_iter().map(|a| optimize_expr(a, state)).collect(), def_value, pos), + Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), // Eagerly call functions Expr::FunctionCall(id, args, def_value, pos) @@ -562,7 +569,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { // First search in script-defined functions (can override built-in) if state.fn_lib.iter().find(|(name, len)| name == &id && *len == args.len()).is_some() { // A script-defined function overrides the built-in function - do not make the call - return Expr::FunctionCall(id, args.into_iter().map(|a| optimize_expr(a, state)).collect(), def_value, pos); + return Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos); } let mut arg_values: Vec<_> = args.iter().map(Expr::get_constant_value).collect(); @@ -576,15 +583,15 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { "" }; - call_fn(&state.engine.functions, &id, &mut call_args, pos).ok() + call_fn(&state.engine.packages, &state.engine.functions, &id, &mut call_args, pos).ok() .and_then(|result| result.or_else(|| { if !arg_for_type_of.is_empty() { // Handle `type_of()` - Some(Dynamic::from_string(arg_for_type_of.to_string())) + Some(arg_for_type_of.to_string().into()) } else { // Otherwise use the default value, if any - def_value.clone() + def_value.clone().map(|v| *v) } }).and_then(|result| map_dynamic_to_expr(result, pos)) .map(|expr| { @@ -593,16 +600,16 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { }) ).unwrap_or_else(|| // Optimize function call arguments - Expr::FunctionCall(id, args.into_iter().map(|a| optimize_expr(a, state)).collect(), def_value, pos) + Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos) ) } // id(args ..) -> optimize function call arguments Expr::FunctionCall(id, args, def_value, pos) => - Expr::FunctionCall(id, args.into_iter().map(|a| optimize_expr(a, state)).collect(), def_value, pos), + Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), // constant-name - Expr::Variable(name, pos) if state.contains_constant(&name) => { + Expr::Variable(name, _, pos) if state.contains_constant(&name) => { state.set_dirty(); // Replace constant with value @@ -635,12 +642,12 @@ fn optimize<'a>( .filter(|ScopeEntry { typ, expr, .. }| { // Get all the constants with definite constant expressions *typ == ScopeEntryType::Constant - && expr.as_ref().map(Expr::is_constant).unwrap_or(false) + && expr.as_ref().map(|v| v.is_constant()).unwrap_or(false) }) .for_each(|ScopeEntry { name, expr, .. }| { state.push_constant( name.as_ref(), - expr.as_ref().expect("should be Some(expr)").clone(), + (**expr.as_ref().expect("should be Some(expr)")).clone(), ) }); @@ -722,10 +729,10 @@ pub fn optimize_into_ast( // Optimize the function body let mut body = - optimize(vec![fn_def.body], engine, &Scope::new(), &fn_lib, level); + optimize(vec![*fn_def.body], engine, &Scope::new(), &fn_lib, level); // {} -> Noop - fn_def.body = match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) { + fn_def.body = Box::new(match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) { // { return val; } -> val Stmt::ReturnWithVal(Some(val), ReturnType::Return, _) => Stmt::Expr(val), // { return; } -> () @@ -734,7 +741,7 @@ pub fn optimize_into_ast( } // All others stmt => stmt, - }; + }); } fn_def }) diff --git a/src/packages/arithmetic.rs b/src/packages/arithmetic.rs new file mode 100644 index 00000000..c788fbb2 --- /dev/null +++ b/src/packages/arithmetic.rs @@ -0,0 +1,425 @@ +use super::{reg_binary, reg_unary}; + +use crate::def_package; +use crate::fn_register::{map_dynamic as map, map_result as result}; +use crate::parser::INT; +use crate::result::EvalAltResult; +use crate::token::Position; + +#[cfg(not(feature = "no_float"))] +use crate::parser::FLOAT; + +use num_traits::{ + identities::Zero, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, + CheckedShr, CheckedSub, +}; + +use crate::stdlib::{ + boxed::Box, + fmt::Display, + format, + ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub}, +}; + +// Checked add +fn add(x: T, y: T) -> Result> { + x.checked_add(&y).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Addition overflow: {} + {}", x, y), + Position::none(), + )) + }) +} +// Checked subtract +fn sub(x: T, y: T) -> Result> { + x.checked_sub(&y).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Subtraction underflow: {} - {}", x, y), + Position::none(), + )) + }) +} +// Checked multiply +fn mul(x: T, y: T) -> Result> { + x.checked_mul(&y).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Multiplication overflow: {} * {}", x, y), + Position::none(), + )) + }) +} +// Checked divide +fn div(x: T, y: T) -> Result> +where + T: Display + CheckedDiv + PartialEq + Zero, +{ + // Detect division by zero + if y == T::zero() { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Division by zero: {} / {}", x, y), + Position::none(), + ))); + } + + x.checked_div(&y).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Division overflow: {} / {}", x, y), + Position::none(), + )) + }) +} +// Checked negative - e.g. -(i32::MIN) will overflow i32::MAX +fn neg(x: T) -> Result> { + x.checked_neg().ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Negation overflow: -{}", x), + Position::none(), + )) + }) +} +// Checked absolute +fn abs(x: T) -> Result> { + // FIX - We don't use Signed::abs() here because, contrary to documentation, it panics + // when the number is ::MIN instead of returning ::MIN itself. + if x >= ::zero() { + Ok(x) + } else { + x.checked_neg().ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Negation overflow: -{}", x), + Position::none(), + )) + }) + } +} +// Unchecked add - may panic on overflow +fn add_u(x: T, y: T) -> ::Output { + x + y +} +// Unchecked subtract - may panic on underflow +fn sub_u(x: T, y: T) -> ::Output { + x - y +} +// Unchecked multiply - may panic on overflow +fn mul_u(x: T, y: T) -> ::Output { + x * y +} +// Unchecked divide - may panic when dividing by zero +fn div_u(x: T, y: T) -> ::Output { + x / y +} +// Unchecked negative - may panic on overflow +fn neg_u(x: T) -> ::Output { + -x +} +// Unchecked absolute - may panic on overflow +fn abs_u(x: T) -> ::Output +where + T: Neg + PartialOrd + Default + Into<::Output>, +{ + // Numbers should default to zero + if x < Default::default() { + -x + } else { + x.into() + } +} +// Bit operators +fn binary_and(x: T, y: T) -> ::Output { + x & y +} +fn binary_or(x: T, y: T) -> ::Output { + x | y +} +fn binary_xor(x: T, y: T) -> ::Output { + x ^ y +} +// Checked left-shift +fn shl(x: T, y: INT) -> Result> { + // Cannot shift by a negative number of bits + if y < 0 { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Left-shift by a negative number: {} << {}", x, y), + Position::none(), + ))); + } + + CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Left-shift by too many bits: {} << {}", x, y), + Position::none(), + )) + }) +} +// Checked right-shift +fn shr(x: T, y: INT) -> Result> { + // Cannot shift by a negative number of bits + if y < 0 { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Right-shift by a negative number: {} >> {}", x, y), + Position::none(), + ))); + } + + CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Right-shift by too many bits: {} % {}", x, y), + Position::none(), + )) + }) +} +// Unchecked left-shift - may panic if shifting by a negative number of bits +fn shl_u>(x: T, y: T) -> >::Output { + x.shl(y) +} +// Unchecked right-shift - may panic if shifting by a negative number of bits +fn shr_u>(x: T, y: T) -> >::Output { + x.shr(y) +} +// Checked modulo +fn modulo(x: T, y: T) -> Result> { + x.checked_rem(&y).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Modulo division by zero or overflow: {} % {}", x, y), + Position::none(), + )) + }) +} +// Unchecked modulo - may panic if dividing by zero +fn modulo_u(x: T, y: T) -> ::Output { + x % y +} +// Checked power +fn pow_i_i(x: INT, y: INT) -> Result> { + #[cfg(not(feature = "only_i32"))] + { + if y > (u32::MAX as INT) { + Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer raised to too large an index: {} ~ {}", x, y), + Position::none(), + ))) + } else if y < 0 { + Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer raised to a negative index: {} ~ {}", x, y), + Position::none(), + ))) + } else { + x.checked_pow(y as u32).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Power overflow: {} ~ {}", x, y), + Position::none(), + )) + }) + } + } + + #[cfg(feature = "only_i32")] + { + if y < 0 { + Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer raised to a negative index: {} ~ {}", x, y), + Position::none(), + ))) + } else { + x.checked_pow(y as u32).ok_or_else(|| { + Box::new(EvalAltResult::ErrorArithmetic( + format!("Power overflow: {} ~ {}", x, y), + Position::none(), + )) + }) + } + } +} +// Unchecked integer power - may panic on overflow or if the power index is too high (> u32::MAX) +fn pow_i_i_u(x: INT, y: INT) -> INT { + x.pow(y as u32) +} +// Floating-point power - always well-defined +#[cfg(not(feature = "no_float"))] +fn pow_f_f(x: FLOAT, y: FLOAT) -> FLOAT { + x.powf(y) +} +// Checked power +#[cfg(not(feature = "no_float"))] +fn pow_f_i(x: FLOAT, y: INT) -> Result> { + // Raise to power that is larger than an i32 + if y > (i32::MAX as INT) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Number raised to too large an index: {} ~ {}", x, y), + Position::none(), + ))); + } + + Ok(x.powi(y as i32)) +} +// Unchecked power - may be incorrect if the power index is too high (> i32::MAX) +#[cfg(feature = "unchecked")] +#[cfg(not(feature = "no_float"))] +fn pow_f_i_u(x: FLOAT, y: INT) -> FLOAT { + x.powi(y as i32) +} + +macro_rules! reg_unary_x { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_unary($lib, $op, $func::<$par>, result);)* }; +} +macro_rules! reg_unary { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_unary($lib, $op, $func::<$par>, map);)* }; +} +macro_rules! reg_op_x { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_binary($lib, $op, $func::<$par>, result);)* }; +} +macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_binary($lib, $op, $func::<$par>, map);)* }; +} + +def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, { + // Checked basic arithmetic + #[cfg(not(feature = "unchecked"))] + { + reg_op_x!(lib, "+", add, INT); + reg_op_x!(lib, "-", sub, INT); + reg_op_x!(lib, "*", mul, INT); + reg_op_x!(lib, "/", div, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op_x!(lib, "+", add, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op_x!(lib, "-", sub, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op_x!(lib, "*", mul, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op_x!(lib, "/", div, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + } + + // Unchecked basic arithmetic + #[cfg(feature = "unchecked")] + { + reg_op!(lib, "+", add_u, INT); + reg_op!(lib, "-", sub_u, INT); + reg_op!(lib, "*", mul_u, INT); + reg_op!(lib, "/", div_u, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "+", add_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "-", sub_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "*", mul_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "/", div_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + } + + // Basic arithmetic for floating-point - no need to check + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, "+", add_u, f32, f64); + reg_op!(lib, "-", sub_u, f32, f64); + reg_op!(lib, "*", mul_u, f32, f64); + reg_op!(lib, "/", div_u, f32, f64); + } + + // Bit operations + reg_op!(lib, "|", binary_or, INT); + reg_op!(lib, "&", binary_and, INT); + reg_op!(lib, "^", binary_xor, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "|", binary_or, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "&", binary_and, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "^", binary_xor, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + + // Checked bit shifts + #[cfg(not(feature = "unchecked"))] + { + reg_op_x!(lib, "<<", shl, INT); + reg_op_x!(lib, ">>", shr, INT); + reg_op_x!(lib, "%", modulo, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op_x!(lib, "<<", shl, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op_x!(lib, ">>", shr, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op_x!(lib, "%", modulo, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + } + + // Unchecked bit shifts + #[cfg(feature = "unchecked")] + { + reg_op!(lib, "<<", shl_u, INT, INT); + reg_op!(lib, ">>", shr_u, INT, INT); + reg_op!(lib, "%", modulo_u, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "<<", shl_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, ">>", shr_u, i64, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "%", modulo_u, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + } + + // Checked power + #[cfg(not(feature = "unchecked"))] + { + reg_binary(lib, "~", pow_i_i, result); + + #[cfg(not(feature = "no_float"))] + reg_binary(lib, "~", pow_f_i, result); + } + + // Unchecked power + #[cfg(feature = "unchecked")] + { + reg_binary(lib, "~", pow_i_i_u, map); + + #[cfg(not(feature = "no_float"))] + reg_binary(lib, "~", pow_f_i_u, map); + } + + // Floating-point modulo and power + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, "%", modulo_u, f32, f64); + reg_binary(lib, "~", pow_f_f, map); + } + + // Checked unary + #[cfg(not(feature = "unchecked"))] + { + reg_unary_x!(lib, "-", neg, INT); + reg_unary_x!(lib, "abs", abs, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_unary_x!(lib, "-", neg, i8, i16, i32, i64, i128); + reg_unary_x!(lib, "abs", abs, i8, i16, i32, i64, i128); + } + } + + // Unchecked unary + #[cfg(feature = "unchecked")] + { + reg_unary!(lib, "-", neg_u, INT); + reg_unary!(lib, "abs", abs_u, INT); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_unary!(lib, "-", neg_u, i8, i16, i32, i64, i128); + reg_unary!(lib, "abs", abs_u, i8, i16, i32, i64, i128); + } + } + + // Floating-point unary + #[cfg(not(feature = "no_float"))] + { + reg_unary!(lib, "-", neg_u, f32, f64); + reg_unary!(lib, "abs", abs_u, f32, f64); + } +}); diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs new file mode 100644 index 00000000..ca69f3fc --- /dev/null +++ b/src/packages/array_basic.rs @@ -0,0 +1,124 @@ +use super::{reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut}; + +use crate::any::{Dynamic, Variant}; +use crate::def_package; +use crate::engine::Array; +use crate::fn_register::{map_dynamic as map, map_identity as pass}; +use crate::parser::INT; + +use crate::stdlib::{any::TypeId, boxed::Box, string::String}; + +// Register array utility functions +fn push(list: &mut Array, item: T) { + list.push(Dynamic::from(item)); +} +fn ins(list: &mut Array, position: INT, item: T) { + if position <= 0 { + list.insert(0, Dynamic::from(item)); + } else if (position as usize) >= list.len() - 1 { + push(list, item); + } else { + list.insert(position as usize, Dynamic::from(item)); + } +} +fn pad(list: &mut Array, len: INT, item: T) { + if len >= 0 { + while list.len() < len as usize { + push(list, item.clone()); + } + } +} + +macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_binary_mut($lib, $op, $func::<$par>, map);)* }; +} +macro_rules! reg_tri { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_trinary_mut($lib, $op, $func::<$par>, map);)* }; +} + +#[cfg(not(feature = "no_index"))] +def_package!(crate:BasicArrayPackage:"Basic array utilities.", lib, { + reg_op!(lib, "push", push, INT, bool, char, String, Array, ()); + reg_tri!(lib, "pad", pad, INT, bool, char, String, Array, ()); + reg_tri!(lib, "insert", ins, INT, bool, char, String, Array, ()); + + reg_binary_mut(lib, "append", |x: &mut Array, y: Array| x.extend(y), map); + reg_binary( + lib, + "+", + |mut x: Array, y: Array| { + x.extend(y); + x + }, + map, + ); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "push", push, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_tri!(lib, "pad", pad, i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); + reg_tri!(lib, "insert", ins, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, "push", push, f32, f64); + reg_tri!(lib, "pad", pad, f32, f64); + reg_tri!(lib, "insert", ins, f32, f64); + } + + reg_unary_mut( + lib, + "pop", + |list: &mut Array| list.pop().unwrap_or_else(|| ().into()), + pass, + ); + reg_unary_mut( + lib, + "shift", + |list: &mut Array| { + if list.is_empty() { + ().into() + } else { + list.remove(0) + } + }, + pass, + ); + reg_binary_mut( + lib, + "remove", + |list: &mut Array, len: INT| { + if len < 0 || (len as usize) >= list.len() { + ().into() + } else { + list.remove(len as usize) + } + }, + pass, + ); + reg_unary_mut(lib, "len", |list: &mut Array| list.len() as INT, map); + reg_unary_mut(lib, "clear", |list: &mut Array| list.clear(), map); + reg_binary_mut( + lib, + "truncate", + |list: &mut Array, len: INT| { + if len >= 0 { + list.truncate(len as usize); + } else { + list.clear(); + } + }, + map, + ); + + // Register array iterator + lib.type_iterators.insert( + TypeId::of::(), + Box::new(|a: Dynamic| { + Box::new(a.cast::().into_iter()) + as Box> + }), + ); +}); diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs new file mode 100644 index 00000000..9672d61c --- /dev/null +++ b/src/packages/iter_basic.rs @@ -0,0 +1,109 @@ +use super::{reg_binary, reg_trinary, reg_unary_mut, PackageStore}; + +use crate::any::{Dynamic, Union, Variant}; +use crate::def_package; +use crate::engine::{Array, Map}; +use crate::fn_register::map_dynamic as map; +use crate::parser::INT; + +use crate::stdlib::{ + any::TypeId, + boxed::Box, + ops::{Add, Range}, +}; + +// Register range function +fn reg_range(lib: &mut PackageStore) +where + Range: Iterator, +{ + lib.type_iterators.insert( + TypeId::of::>(), + Box::new(|source: Dynamic| { + Box::new(source.cast::>().map(|x| x.into_dynamic())) + as Box> + }), + ); +} + +// Register range function with step +#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] +struct StepRange(T, T, T) +where + for<'a> &'a T: Add<&'a T, Output = T>, + T: Variant + Clone + PartialOrd; + +impl Iterator for StepRange +where + for<'a> &'a T: Add<&'a T, Output = T>, + T: Variant + Clone + PartialOrd, +{ + type Item = T; + + fn next(&mut self) -> Option { + if self.0 < self.1 { + let v = self.0.clone(); + self.0 = &v + &self.2; + Some(v) + } else { + None + } + } +} + +fn reg_step(lib: &mut PackageStore) +where + for<'a> &'a T: Add<&'a T, Output = T>, + T: Variant + Clone + PartialOrd, + StepRange: Iterator, +{ + lib.type_iterators.insert( + TypeId::of::>(), + Box::new(|source: Dynamic| { + Box::new(source.cast::>().map(|x| x.into_dynamic())) + as Box> + }), + ); +} + +def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { + fn get_range(from: T, to: T) -> Range { + from..to + } + + reg_range::(lib); + reg_binary(lib, "range", get_range::, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + macro_rules! reg_range { + ($self:expr, $x:expr, $( $y:ty ),*) => ( + $( + reg_range::<$y>($self); + reg_binary($self, $x, get_range::<$y>, map); + )* + ) + } + + reg_range!(lib, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + + reg_step::(lib); + reg_trinary(lib, "range", StepRange::, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + macro_rules! reg_step { + ($self:expr, $x:expr, $( $y:ty ),*) => ( + $( + reg_step::<$y>($self); + reg_trinary($self, $x, StepRange::<$y>, map); + )* + ) + } + + reg_step!(lib, "range", i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } +}); diff --git a/src/packages/logic.rs b/src/packages/logic.rs new file mode 100644 index 00000000..f993044a --- /dev/null +++ b/src/packages/logic.rs @@ -0,0 +1,91 @@ +use super::{reg_binary, reg_binary_mut, reg_unary}; + +use crate::def_package; +use crate::fn_register::map_dynamic as map; +use crate::parser::INT; + +use crate::stdlib::string::String; + +// Comparison operators +pub fn lt(x: T, y: T) -> bool { + x < y +} +pub fn lte(x: T, y: T) -> bool { + x <= y +} +pub fn gt(x: T, y: T) -> bool { + x > y +} +pub fn gte(x: T, y: T) -> bool { + x >= y +} +pub fn eq(x: T, y: T) -> bool { + x == y +} +pub fn ne(x: T, y: T) -> bool { + x != y +} + +// Logic operators +fn and(x: bool, y: bool) -> bool { + x && y +} +fn or(x: bool, y: bool) -> bool { + x || y +} +fn not(x: bool) -> bool { + !x +} + +macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_binary($lib, $op, $func::<$par>, map);)* }; +} + +def_package!(crate:LogicPackage:"Logical operators.", lib, { + reg_op!(lib, "<", lt, INT, char); + reg_op!(lib, "<=", lte, INT, char); + reg_op!(lib, ">", gt, INT, char); + reg_op!(lib, ">=", gte, INT, char); + reg_op!(lib, "==", eq, INT, char, bool, ()); + reg_op!(lib, "!=", ne, INT, char, bool, ()); + + // Special versions for strings - at least avoid copying the first string + // use super::utils::reg_test; + // reg_test(lib, "<", |x: &mut String, y: String| *x < y, |v| v, map); + reg_binary_mut(lib, "<", |x: &mut String, y: String| *x < y, map); + reg_binary_mut(lib, "<=", |x: &mut String, y: String| *x <= y, map); + reg_binary_mut(lib, ">", |x: &mut String, y: String| *x > y, map); + reg_binary_mut(lib, ">=", |x: &mut String, y: String| *x >= y, map); + reg_binary_mut(lib, "==", |x: &mut String, y: String| *x == y, map); + reg_binary_mut(lib, "!=", |x: &mut String, y: String| *x != y, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "<", lt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "<=", lte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, ">", gt, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, ">=", gte, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "==", eq, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "!=", ne, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, "<", lt, f32, f64); + reg_op!(lib, "<=", lte, f32, f64); + reg_op!(lib, ">", gt, f32, f64); + reg_op!(lib, ">=", gte, f32, f64); + reg_op!(lib, "==", eq, f32, f64); + reg_op!(lib, "!=", ne, f32, f64); + } + + // `&&` and `||` are treated specially as they short-circuit. + // They are implemented as special `Expr` instances, not function calls. + //reg_op!(lib, "||", or, bool); + //reg_op!(lib, "&&", and, bool); + + reg_binary(lib, "|", or, map); + reg_binary(lib, "&", and, map); + reg_unary(lib, "!", not, map); +}); diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs new file mode 100644 index 00000000..40e2cec0 --- /dev/null +++ b/src/packages/map_basic.rs @@ -0,0 +1,65 @@ +use super::{reg_binary, reg_binary_mut, reg_unary_mut}; + +use crate::any::Dynamic; +use crate::def_package; +use crate::engine::Map; +use crate::fn_register::map_dynamic as map; +use crate::parser::INT; + +use crate::stdlib::{ + string::{String, ToString}, + vec::Vec, +}; + +fn map_get_keys(map: &mut Map) -> Vec { + map.iter().map(|(k, _)| k.to_string().into()).collect() +} +fn map_get_values(map: &mut Map) -> Vec { + map.iter().map(|(_, v)| v.clone()).collect() +} + +#[cfg(not(feature = "no_object"))] +def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, { + reg_binary_mut( + lib, + "has", + |map: &mut Map, prop: String| map.contains_key(&prop), + map, + ); + reg_unary_mut(lib, "len", |map: &mut Map| map.len() as INT, map); + reg_unary_mut(lib, "clear", |map: &mut Map| map.clear(), map); + reg_binary_mut( + lib, + "remove", + |x: &mut Map, name: String| x.remove(&name).unwrap_or_else(|| ().into()), + map, + ); + reg_binary_mut( + lib, + "mixin", + |map1: &mut Map, map2: Map| { + map2.into_iter().for_each(|(key, value)| { + map1.insert(key, value); + }); + }, + map, + ); + reg_binary( + lib, + "+", + |mut map1: Map, map2: Map| { + map2.into_iter().for_each(|(key, value)| { + map1.insert(key, value); + }); + map1 + }, + map, + ); + + // Register map access functions + #[cfg(not(feature = "no_index"))] + reg_unary_mut(lib, "keys", map_get_keys, map); + + #[cfg(not(feature = "no_index"))] + reg_unary_mut(lib, "values", map_get_values, map); +}); diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs new file mode 100644 index 00000000..a39f477c --- /dev/null +++ b/src/packages/math_basic.rs @@ -0,0 +1,131 @@ +use super::{reg_binary, reg_unary}; + +use crate::def_package; +use crate::fn_register::{map_dynamic as map, map_result as result}; +use crate::parser::INT; +use crate::result::EvalAltResult; +use crate::token::Position; + +#[cfg(not(feature = "no_float"))] +use crate::parser::FLOAT; + +use crate::stdlib::{boxed::Box, format, i32, i64}; + +#[cfg(feature = "only_i32")] +pub const MAX_INT: INT = i32::MAX; +#[cfg(not(feature = "only_i32"))] +pub const MAX_INT: INT = i64::MAX; + +def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, { + #[cfg(not(feature = "no_float"))] + { + // Advanced math functions + reg_unary(lib, "sin", |x: FLOAT| x.to_radians().sin(), map); + reg_unary(lib, "cos", |x: FLOAT| x.to_radians().cos(), map); + reg_unary(lib, "tan", |x: FLOAT| x.to_radians().tan(), map); + reg_unary(lib, "sinh", |x: FLOAT| x.to_radians().sinh(), map); + reg_unary(lib, "cosh", |x: FLOAT| x.to_radians().cosh(), map); + reg_unary(lib, "tanh", |x: FLOAT| x.to_radians().tanh(), map); + reg_unary(lib, "asin", |x: FLOAT| x.asin().to_degrees(), map); + reg_unary(lib, "acos", |x: FLOAT| x.acos().to_degrees(), map); + reg_unary(lib, "atan", |x: FLOAT| x.atan().to_degrees(), map); + reg_unary(lib, "asinh", |x: FLOAT| x.asinh().to_degrees(), map); + reg_unary(lib, "acosh", |x: FLOAT| x.acosh().to_degrees(), map); + reg_unary(lib, "atanh", |x: FLOAT| x.atanh().to_degrees(), map); + reg_unary(lib, "sqrt", |x: FLOAT| x.sqrt(), map); + reg_unary(lib, "exp", |x: FLOAT| x.exp(), map); + reg_unary(lib, "ln", |x: FLOAT| x.ln(), map); + reg_binary(lib, "log", |x: FLOAT, base: FLOAT| x.log(base), map); + reg_unary(lib, "log10", |x: FLOAT| x.log10(), map); + reg_unary(lib, "floor", |x: FLOAT| x.floor(), map); + reg_unary(lib, "ceiling", |x: FLOAT| x.ceil(), map); + reg_unary(lib, "round", |x: FLOAT| x.ceil(), map); + reg_unary(lib, "int", |x: FLOAT| x.trunc(), map); + reg_unary(lib, "fraction", |x: FLOAT| x.fract(), map); + reg_unary(lib, "is_nan", |x: FLOAT| x.is_nan(), map); + reg_unary(lib, "is_finite", |x: FLOAT| x.is_finite(), map); + reg_unary(lib, "is_infinite", |x: FLOAT| x.is_infinite(), map); + + // Register conversion functions + reg_unary(lib, "to_float", |x: INT| x as FLOAT, map); + reg_unary(lib, "to_float", |x: f32| x as FLOAT, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_unary(lib, "to_float", |x: i8| x as FLOAT, map); + reg_unary(lib, "to_float", |x: u8| x as FLOAT, map); + reg_unary(lib, "to_float", |x: i16| x as FLOAT, map); + reg_unary(lib, "to_float", |x: u16| x as FLOAT, map); + reg_unary(lib, "to_float", |x: i32| x as FLOAT, map); + reg_unary(lib, "to_float", |x: u32| x as FLOAT, map); + reg_unary(lib, "to_float", |x: i64| x as FLOAT, map); + reg_unary(lib, "to_float", |x: u64| x as FLOAT, map); + reg_unary(lib, "to_float", |x: i128| x as FLOAT, map); + reg_unary(lib, "to_float", |x: u128| x as FLOAT, map); + } + } + + reg_unary(lib, "to_int", |ch: char| ch as INT, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_unary(lib, "to_int", |x: i8| x as INT, map); + reg_unary(lib, "to_int", |x: u8| x as INT, map); + reg_unary(lib, "to_int", |x: i16| x as INT, map); + reg_unary(lib, "to_int", |x: u16| x as INT, map); + } + + #[cfg(not(feature = "only_i32"))] + { + reg_unary(lib, "to_int", |x: i32| x as INT, map); + reg_unary(lib, "to_int", |x: u64| x as INT, map); + + #[cfg(feature = "only_i64")] + reg_unary(lib, "to_int", |x: u32| x as INT, map); + } + + #[cfg(not(feature = "no_float"))] + { + #[cfg(not(feature = "unchecked"))] + { + reg_unary( + lib, + "to_int", + |x: f32| { + if x > (MAX_INT as f32) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer overflow: to_int({})", x), + Position::none(), + ))); + } + + Ok(x.trunc() as INT) + }, + result, + ); + reg_unary( + lib, + "to_int", + |x: FLOAT| { + if x > (MAX_INT as FLOAT) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer overflow: to_int({})", x), + Position::none(), + ))); + } + + Ok(x.trunc() as INT) + }, + result, + ); + } + + #[cfg(feature = "unchecked")] + { + reg_unary(lib, "to_int", |x: f32| x as INT, map); + reg_unary(lib, "to_int", |x: f64| x as INT, map); + } + } +}); diff --git a/src/packages/mod.rs b/src/packages/mod.rs new file mode 100644 index 00000000..54c3f177 --- /dev/null +++ b/src/packages/mod.rs @@ -0,0 +1,74 @@ +//! This module contains all built-in _packages_ available to Rhai, plus facilities to define custom packages. + +use crate::engine::{FnAny, IteratorFn}; + +use crate::stdlib::{any::TypeId, boxed::Box, collections::HashMap, rc::Rc, sync::Arc}; + +mod arithmetic; +mod array_basic; +mod iter_basic; +mod logic; +mod map_basic; +mod math_basic; +mod pkg_core; +mod pkg_std; +mod string_basic; +mod string_more; +mod time_basic; +mod utils; + +pub use arithmetic::ArithmeticPackage; +#[cfg(not(feature = "no_index"))] +pub use array_basic::BasicArrayPackage; +pub use iter_basic::BasicIteratorPackage; +pub use logic::LogicPackage; +#[cfg(not(feature = "no_object"))] +pub use map_basic::BasicMapPackage; +pub use math_basic::BasicMathPackage; +pub use pkg_core::CorePackage; +pub use pkg_std::StandardPackage; +pub use string_basic::BasicStringPackage; +pub use string_more::MoreStringPackage; +#[cfg(not(feature = "no_std"))] +pub use time_basic::BasicTimePackage; + +pub use utils::*; + +/// Trait that all packages must implement. +pub trait Package { + /// Create a new instance of a package. + fn new() -> Self; + + /// Register all the functions in a package into a store. + fn init(lib: &mut PackageStore); + + /// Retrieve the generic package library from this package. + fn get(&self) -> PackageLibrary; +} + +/// Type to store all functions in the package. +pub struct PackageStore { + /// All functions, keyed by a hash created from the function name and parameter types. + pub functions: HashMap>, + + /// All iterator functions, keyed by the type producing the iterator. + pub type_iterators: HashMap>, +} + +impl PackageStore { + /// Create a new `PackageStore`. + pub fn new() -> Self { + Self { + functions: HashMap::new(), + type_iterators: HashMap::new(), + } + } +} + +/// Type which `Rc`-wraps a `PackageStore` to facilitate sharing library instances. +#[cfg(not(feature = "sync"))] +pub type PackageLibrary = Rc; + +/// Type which `Arc`-wraps a `PackageStore` to facilitate sharing library instances. +#[cfg(feature = "sync")] +pub type PackageLibrary = Arc; diff --git a/src/packages/pkg_core.rs b/src/packages/pkg_core.rs new file mode 100644 index 00000000..9ceae0d9 --- /dev/null +++ b/src/packages/pkg_core.rs @@ -0,0 +1,13 @@ +use super::arithmetic::ArithmeticPackage; +use super::iter_basic::BasicIteratorPackage; +use super::logic::LogicPackage; +use super::string_basic::BasicStringPackage; + +use crate::def_package; + +def_package!(crate:CorePackage:"_Core_ package containing basic facilities.", lib, { + ArithmeticPackage::init(lib); + LogicPackage::init(lib); + BasicStringPackage::init(lib); + BasicIteratorPackage::init(lib); +}); diff --git a/src/packages/pkg_std.rs b/src/packages/pkg_std.rs new file mode 100644 index 00000000..d2790d50 --- /dev/null +++ b/src/packages/pkg_std.rs @@ -0,0 +1,23 @@ +#[cfg(not(feature = "no_index"))] +use super::array_basic::BasicArrayPackage; +#[cfg(not(feature = "no_object"))] +use super::map_basic::BasicMapPackage; +use super::math_basic::BasicMathPackage; +use super::pkg_core::CorePackage; +use super::string_more::MoreStringPackage; +#[cfg(not(feature = "no_std"))] +use super::time_basic::BasicTimePackage; + +use crate::def_package; + +def_package!(crate:StandardPackage:"_Standard_ package containing all built-in features.", lib, { + CorePackage::init(lib); + BasicMathPackage::init(lib); + #[cfg(not(feature = "no_index"))] + BasicArrayPackage::init(lib); + #[cfg(not(feature = "no_object"))] + BasicMapPackage::init(lib); + #[cfg(not(feature = "no_std"))] + BasicTimePackage::init(lib); + MoreStringPackage::init(lib); +}); diff --git a/src/packages/string_basic.rs b/src/packages/string_basic.rs new file mode 100644 index 00000000..87807d70 --- /dev/null +++ b/src/packages/string_basic.rs @@ -0,0 +1,99 @@ +use super::{reg_binary, reg_binary_mut, reg_none, reg_unary, reg_unary_mut}; + +use crate::def_package; +use crate::engine::{Array, Map, FUNC_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT}; +use crate::fn_register::map_dynamic as map; +use crate::parser::INT; + +use crate::stdlib::{ + fmt::{Debug, Display}, + format, + string::{String, ToString}, +}; + +// Register print and debug +fn to_debug(x: &mut T) -> String { + format!("{:?}", x) +} +fn to_string(x: &mut T) -> String { + format!("{}", x) +} +fn format_map(x: &mut Map) -> String { + format!("#{:?}", x) +} + +macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_unary_mut($lib, $op, $func::<$par>, map);)* }; +} + +def_package!(crate:BasicStringPackage:"Basic string utilities, including printing.", lib, { + reg_op!(lib, KEYWORD_PRINT, to_string, INT, bool, char); + reg_op!(lib, FUNC_TO_STRING, to_string, INT, bool, char); + + reg_none(lib, KEYWORD_PRINT, || "".to_string(), map); + reg_unary(lib, KEYWORD_PRINT, |_: ()| "".to_string(), map); + reg_unary(lib, FUNC_TO_STRING, |_: ()| "".to_string(), map); + + reg_unary_mut(lib, KEYWORD_PRINT, |s: &mut String| s.clone(), map); + reg_unary_mut(lib, FUNC_TO_STRING, |s: &mut String| s.clone(), map); + + reg_op!(lib, KEYWORD_DEBUG, to_debug, INT, bool, (), char, String); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, KEYWORD_PRINT, to_string, i8, u8, i16, u16, i32, u32); + reg_op!(lib, FUNC_TO_STRING, to_string, i8, u8, i16, u16, i32, u32); + reg_op!(lib, KEYWORD_DEBUG, to_debug, i8, u8, i16, u16, i32, u32); + reg_op!(lib, KEYWORD_PRINT, to_string, i64, u64, i128, u128); + reg_op!(lib, FUNC_TO_STRING, to_string, i64, u64, i128, u128); + reg_op!(lib, KEYWORD_DEBUG, to_debug, i64, u64, i128, u128); + } + + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, KEYWORD_PRINT, to_string, f32, f64); + reg_op!(lib, FUNC_TO_STRING, to_string, f32, f64); + reg_op!(lib, KEYWORD_DEBUG, to_debug, f32, f64); + } + + #[cfg(not(feature = "no_index"))] + { + reg_op!(lib, KEYWORD_PRINT, to_debug, Array); + reg_op!(lib, FUNC_TO_STRING, to_debug, Array); + reg_op!(lib, KEYWORD_DEBUG, to_debug, Array); + } + + #[cfg(not(feature = "no_object"))] + { + reg_unary_mut(lib, KEYWORD_PRINT, format_map, map); + reg_unary_mut(lib, FUNC_TO_STRING, format_map, map); + reg_unary_mut(lib, KEYWORD_DEBUG, format_map, map); + } + + reg_binary( + lib, + "+", + |mut s: String, ch: char| { + s.push(ch); + s + }, + map, + ); + reg_binary( + lib, + "+", + |mut s: String, s2: String| { + s.push_str(&s2); + s + }, + map, + ); + reg_binary_mut(lib, "append", |s: &mut String, ch: char| s.push(ch), map); + reg_binary_mut( + lib, + "append", + |s: &mut String, s2: String| s.push_str(&s2), + map, + ); +}); diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs new file mode 100644 index 00000000..0144792e --- /dev/null +++ b/src/packages/string_more.rs @@ -0,0 +1,239 @@ +use super::{reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut}; + +use crate::def_package; +use crate::engine::Array; +use crate::fn_register::map_dynamic as map; +use crate::parser::INT; + +use crate::stdlib::{ + fmt::Display, + format, + string::{String, ToString}, + vec::Vec, +}; + +fn prepend(x: T, y: String) -> String { + format!("{}{}", x, y) +} +fn append(x: String, y: T) -> String { + format!("{}{}", x, y) +} +fn sub_string(s: &mut String, start: INT, len: INT) -> String { + let offset = if s.is_empty() || len <= 0 { + return "".to_string(); + } else if start < 0 { + 0 + } else if (start as usize) >= s.chars().count() { + return "".to_string(); + } else { + start as usize + }; + + let chars: Vec<_> = s.chars().collect(); + + let len = if offset + (len as usize) > chars.len() { + chars.len() - offset + } else { + len as usize + }; + + chars[offset..][..len].into_iter().collect() +} +fn crop_string(s: &mut String, start: INT, len: INT) { + let offset = if s.is_empty() || len <= 0 { + s.clear(); + return; + } else if start < 0 { + 0 + } else if (start as usize) >= s.chars().count() { + s.clear(); + return; + } else { + start as usize + }; + + let chars: Vec<_> = s.chars().collect(); + + let len = if offset + (len as usize) > chars.len() { + chars.len() - offset + } else { + len as usize + }; + + s.clear(); + + chars[offset..][..len] + .into_iter() + .for_each(|&ch| s.push(ch)); +} + +macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $(reg_binary($lib, $op, $func::<$par>, map);)* }; +} + +def_package!(crate:MoreStringPackage:"Additional string utilities, including string building.", lib, { + reg_op!(lib, "+", append, INT, bool, char); + reg_binary_mut(lib, "+", |x: &mut String, _: ()| x.clone(), map); + + reg_op!(lib, "+", prepend, INT, bool, char); + reg_binary(lib, "+", |_: (), y: String| y, map); + + #[cfg(not(feature = "only_i32"))] + #[cfg(not(feature = "only_i64"))] + { + reg_op!(lib, "+", append, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "+", prepend, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + } + + #[cfg(not(feature = "no_float"))] + { + reg_op!(lib, "+", append, f32, f64); + reg_op!(lib, "+", prepend, f32, f64); + } + + #[cfg(not(feature = "no_index"))] + { + reg_binary(lib, "+", |x: String, y: Array| format!("{}{:?}", x, y), map); + reg_binary(lib, "+", |x: Array, y: String| format!("{:?}{}", x, y), map); + } + + reg_unary_mut(lib, "len", |s: &mut String| s.chars().count() as INT, map); + reg_binary_mut( + lib, + "contains", + |s: &mut String, ch: char| s.contains(ch), + map, + ); + reg_binary_mut( + lib, + "contains", + |s: &mut String, find: String| s.contains(&find), + map, + ); + reg_trinary_mut( + lib, + "index_of", + |s: &mut String, ch: char, start: INT| { + let start = if start < 0 { + 0 + } else if (start as usize) >= s.chars().count() { + return -1 as INT; + } else { + s.chars().take(start as usize).collect::().len() + }; + + s[start..] + .find(ch) + .map(|index| s[0..start + index].chars().count() as INT) + .unwrap_or(-1 as INT) + }, + map, + ); + reg_binary_mut( + lib, + "index_of", + |s: &mut String, ch: char| { + s.find(ch) + .map(|index| s[0..index].chars().count() as INT) + .unwrap_or(-1 as INT) + }, + map, + ); + reg_trinary_mut( + lib, + "index_of", + |s: &mut String, find: String, start: INT| { + let start = if start < 0 { + 0 + } else if (start as usize) >= s.chars().count() { + return -1 as INT; + } else { + s.chars().take(start as usize).collect::().len() + }; + + s[start..] + .find(&find) + .map(|index| s[0..start + index].chars().count() as INT) + .unwrap_or(-1 as INT) + }, + map, + ); + reg_binary_mut( + lib, + "index_of", + |s: &mut String, find: String| { + s.find(&find) + .map(|index| s[0..index].chars().count() as INT) + .unwrap_or(-1 as INT) + }, + map, + ); + reg_unary_mut(lib, "clear", |s: &mut String| s.clear(), map); + reg_binary_mut(lib, "append", |s: &mut String, ch: char| s.push(ch), map); + reg_binary_mut( + lib, + "append", + |s: &mut String, add: String| s.push_str(&add), + map, + ); + reg_trinary_mut(lib, "sub_string", sub_string, map); + reg_binary_mut( + lib, + "sub_string", + |s: &mut String, start: INT| sub_string(s, start, s.len() as INT), + map, + ); + reg_trinary_mut(lib, "crop", crop_string, map); + reg_binary_mut( + lib, + "crop", + |s: &mut String, start: INT| crop_string(s, start, s.len() as INT), + map, + ); + reg_binary_mut( + lib, + "truncate", + |s: &mut String, len: INT| { + if len >= 0 { + let chars: Vec<_> = s.chars().take(len as usize).collect(); + s.clear(); + chars.into_iter().for_each(|ch| s.push(ch)); + } else { + s.clear(); + } + }, + map, + ); + reg_trinary_mut( + lib, + "pad", + |s: &mut String, len: INT, ch: char| { + for _ in 0..s.chars().count() - len as usize { + s.push(ch); + } + }, + map, + ); + reg_trinary_mut( + lib, + "replace", + |s: &mut String, find: String, sub: String| { + let new_str = s.replace(&find, &sub); + s.clear(); + s.push_str(&new_str); + }, + map, + ); + reg_unary_mut( + lib, + "trim", + |s: &mut String| { + let trimmed = s.trim(); + + if trimmed.len() < s.len() { + *s = trimmed.to_string(); + } + }, + map, + ); +}); diff --git a/src/packages/time_basic.rs b/src/packages/time_basic.rs new file mode 100644 index 00000000..173c3e22 --- /dev/null +++ b/src/packages/time_basic.rs @@ -0,0 +1,101 @@ +use super::logic::{eq, gt, gte, lt, lte, ne}; +use super::math_basic::MAX_INT; +use super::{reg_binary, reg_none, reg_unary}; + +use crate::def_package; +use crate::fn_register::{map_dynamic as map, map_result as result}; +use crate::parser::INT; +use crate::result::EvalAltResult; +use crate::token::Position; + +#[cfg(not(feature = "no_std"))] +use crate::stdlib::time::Instant; + +#[cfg(not(feature = "no_std"))] +def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, { + // Register date/time functions + reg_none(lib, "timestamp", || Instant::now(), map); + + reg_binary( + lib, + "-", + |ts1: Instant, ts2: Instant| { + if ts2 > ts1 { + #[cfg(not(feature = "no_float"))] + return Ok(-(ts2 - ts1).as_secs_f64()); + + #[cfg(feature = "no_float")] + { + let seconds = (ts2 - ts1).as_secs(); + + #[cfg(not(feature = "unchecked"))] + { + if seconds > (MAX_INT as u64) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!( + "Integer overflow for timestamp duration: {}", + -(seconds as i64) + ), + Position::none(), + ))); + } + } + return Ok(-(seconds as INT)); + } + } else { + #[cfg(not(feature = "no_float"))] + return Ok((ts1 - ts2).as_secs_f64()); + + #[cfg(feature = "no_float")] + { + let seconds = (ts1 - ts2).as_secs(); + + #[cfg(not(feature = "unchecked"))] + { + if seconds > (MAX_INT as u64) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer overflow for timestamp duration: {}", seconds), + Position::none(), + ))); + } + } + return Ok(seconds as INT); + } + } + }, + result, + ); + + reg_binary(lib, "<", lt::, map); + reg_binary(lib, "<=", lte::, map); + reg_binary(lib, ">", gt::, map); + reg_binary(lib, ">=", gte::, map); + reg_binary(lib, "==", eq::, map); + reg_binary(lib, "!=", ne::, map); + + reg_unary( + lib, + "elapsed", + |timestamp: Instant| { + #[cfg(not(feature = "no_float"))] + return Ok(timestamp.elapsed().as_secs_f64()); + + #[cfg(feature = "no_float")] + { + let seconds = timestamp.elapsed().as_secs(); + + #[cfg(not(feature = "unchecked"))] + { + if seconds > (MAX_INT as u64) { + return Err(Box::new(EvalAltResult::ErrorArithmetic( + format!("Integer overflow for timestamp.elapsed(): {}", seconds), + Position::none(), + ))); + } + } + return Ok(seconds as INT); + } + }, + result, + ); +}); diff --git a/src/packages/utils.rs b/src/packages/utils.rs new file mode 100644 index 00000000..122bb63a --- /dev/null +++ b/src/packages/utils.rs @@ -0,0 +1,481 @@ +use super::PackageStore; + +use crate::any::{Dynamic, Variant}; +use crate::calc_fn_hash; +use crate::engine::FnCallArgs; +use crate::result::EvalAltResult; +use crate::token::Position; + +use crate::stdlib::{ + any::TypeId, + boxed::Box, + string::{String, ToString}, +}; + +/// This macro makes it easy to define a _package_ and register functions into it. +/// +/// Functions can be added to the package using a number of helper functions under the `packages` module, +/// such as `reg_unary`, `reg_binary_mut`, `reg_trinary_mut` etc. +/// +/// # Examples +/// +/// ``` +/// use rhai::Dynamic; +/// use rhai::def_package; +/// use rhai::packages::reg_binary; +/// +/// fn add(x: i64, y: i64) -> i64 { x + y } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_binary(lib, "my_add", add, |v, _| Ok(v.into())); +/// // ^^^^^^^^^^^^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single function named 'my_add'. +#[macro_export] +macro_rules! def_package { + ($root:ident : $package:ident : $comment:expr , $lib:ident , $block:stmt) => { + #[doc=$comment] + pub struct $package($root::packages::PackageLibrary); + + impl $root::packages::Package for $package { + fn new() -> Self { + let mut pkg = $root::packages::PackageStore::new(); + Self::init(&mut pkg); + Self(pkg.into()) + } + + fn get(&self) -> $root::packages::PackageLibrary { + self.0.clone() + } + + fn init($lib: &mut $root::packages::PackageStore) { + $block + } + } + }; +} + +/// Check whether the correct number of arguments is passed to the function. +fn check_num_args( + name: &str, + num_args: usize, + args: &mut FnCallArgs, + pos: Position, +) -> Result<(), Box> { + if args.len() != num_args { + Err(Box::new(EvalAltResult::ErrorFunctionArgsMismatch( + name.to_string(), + num_args, + args.len(), + pos, + ))) + } else { + Ok(()) + } +} + +/// Add a function with no parameters to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +/// +/// # Examples +/// +/// ``` +/// use rhai::Dynamic; +/// use rhai::def_package; +/// use rhai::packages::reg_none; +/// +/// fn get_answer() -> i64 { 42 } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_none(lib, "my_answer", get_answer, |v, _| Ok(v.into())); +/// // ^^^^^^^^^^^^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single function named 'my_add_1'. +pub fn reg_none( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn() -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn() -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + let hash = calc_fn_hash(fn_name, ([] as [TypeId; 0]).iter().cloned()); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 0, args, pos)?; + + let r = func(); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with one parameter to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +/// +/// # Examples +/// +/// ``` +/// use rhai::Dynamic; +/// use rhai::def_package; +/// use rhai::packages::reg_unary; +/// +/// fn add_1(x: i64) -> i64 { x + 1 } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_unary(lib, "my_add_1", add_1, |v, _| Ok(v.into())); +/// // ^^^^^^^^^^^^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single function named 'my_add_1'. +pub fn reg_unary( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(T) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(T) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}({})", fn_name, crate::std::any::type_name::()); + + let hash = calc_fn_hash(fn_name, [TypeId::of::()].iter().cloned()); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 1, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut T = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x.clone()); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with one mutable reference parameter to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +/// +/// # Examples +/// +/// ``` +/// use rhai::{Dynamic, EvalAltResult}; +/// use rhai::def_package; +/// use rhai::packages::reg_unary_mut; +/// +/// fn inc(x: &mut i64) -> Result> { +/// if *x == 0 { +/// return Err("boo! zero cannot be incremented!".into()) +/// } +/// *x += 1; +/// Ok(().into()) +/// } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_unary_mut(lib, "try_inc", inc, |r, _| r); +/// // ^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single fallible function named 'try_inc' +/// which takes a first argument of `&mut`, return a `Result>`. +pub fn reg_unary_mut( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(&mut T) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(&mut T) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}(&mut {})", fn_name, crate::std::any::type_name::()); + + let hash = calc_fn_hash(fn_name, [TypeId::of::()].iter().cloned()); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 1, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut T = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +#[cfg(not(feature = "sync"))] +pub(crate) fn reg_test<'a, A: Variant + Clone, B: Variant + Clone, X, R>( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(X, B) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(X, B) -> R + Send + Sync + 'static, + + map: impl Fn(&mut A) -> X + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}({}, {})", fn_name, crate::std::any::type_name::(), crate::std::any::type_name::()); + + let hash = calc_fn_hash( + fn_name, + [TypeId::of::(), TypeId::of::()].iter().cloned(), + ); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 2, args, pos)?; + + let mut drain = args.iter_mut(); + let x: X = map(drain.next().unwrap().downcast_mut::().unwrap()); + let y: B = drain.next().unwrap().downcast_mut::().unwrap().clone(); + + let r = func(x, y); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with two parameters to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +/// +/// # Examples +/// +/// ``` +/// use rhai::Dynamic; +/// use rhai::def_package; +/// use rhai::packages::reg_binary; +/// +/// fn add(x: i64, y: i64) -> i64 { x + y } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_binary(lib, "my_add", add, |v, _| Ok(v.into())); +/// // ^^^^^^^^^^^^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single function named 'my_add'. +pub fn reg_binary( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(A, B) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(A, B) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}({}, {})", fn_name, crate::std::any::type_name::(), crate::std::any::type_name::()); + + let hash = calc_fn_hash( + fn_name, + [TypeId::of::(), TypeId::of::()].iter().cloned(), + ); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 2, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut A = drain.next().unwrap().downcast_mut().unwrap(); + let y: &mut B = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x.clone(), y.clone()); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with two parameters (the first one being a mutable reference) to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +/// +/// # Examples +/// +/// ``` +/// use rhai::{Dynamic, EvalAltResult}; +/// use rhai::def_package; +/// use rhai::packages::reg_binary_mut; +/// +/// fn add(x: &mut i64, y: i64) -> Result> { +/// if y == 0 { +/// return Err("boo! cannot add zero!".into()) +/// } +/// *x += y; +/// Ok(().into()) +/// } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// reg_binary_mut(lib, "try_add", add, |r, _| r); +/// // ^^^^^^^^ +/// // map into Result> +/// }); +/// ``` +/// +/// The above defines a package named 'MyPackage' with a single fallible function named 'try_add' +/// which takes a first argument of `&mut`, return a `Result>`. +pub fn reg_binary_mut( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(&mut A, B) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}(&mut {}, {})", fn_name, crate::std::any::type_name::(), crate::std::any::type_name::()); + + let hash = calc_fn_hash( + fn_name, + [TypeId::of::(), TypeId::of::()].iter().cloned(), + ); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 2, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut A = drain.next().unwrap().downcast_mut().unwrap(); + let y: &mut B = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x, y.clone()); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with three parameters to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +pub fn reg_trinary( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(A, B, C) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(A, B, C) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}({}, {}, {})", fn_name, crate::std::any::type_name::(), crate::std::any::type_name::(), crate::std::any::type_name::()); + + let hash = calc_fn_hash( + fn_name, + [TypeId::of::(), TypeId::of::(), TypeId::of::()] + .iter() + .cloned(), + ); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 3, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut A = drain.next().unwrap().downcast_mut().unwrap(); + let y: &mut B = drain.next().unwrap().downcast_mut().unwrap(); + let z: &mut C = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x.clone(), y.clone(), z.clone()); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} + +/// Add a function with three parameters (the first one is a mutable reference) to the package. +/// +/// `map_result` is a function that maps the return type of the function to `Result`. +pub fn reg_trinary_mut( + lib: &mut PackageStore, + fn_name: &'static str, + + #[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B, C) -> R + 'static, + #[cfg(feature = "sync")] func: impl Fn(&mut A, B, C) -> R + Send + Sync + 'static, + + #[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result> + + 'static, + #[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result> + + Send + + Sync + + 'static, +) { + //println!("register {}(&mut {}, {}, {})", fn_name, crate::std::any::type_name::(), crate::std::any::type_name::(), crate::std::any::type_name::()); + + let hash = calc_fn_hash( + fn_name, + [TypeId::of::(), TypeId::of::(), TypeId::of::()] + .iter() + .cloned(), + ); + + let f = Box::new(move |args: &mut FnCallArgs, pos: Position| { + check_num_args(fn_name, 3, args, pos)?; + + let mut drain = args.iter_mut(); + let x: &mut A = drain.next().unwrap().downcast_mut().unwrap(); + let y: &mut B = drain.next().unwrap().downcast_mut().unwrap(); + let z: &mut C = drain.next().unwrap().downcast_mut().unwrap(); + + let r = func(x, y.clone(), z.clone()); + map_result(r, pos) + }); + + lib.functions.insert(hash, f); +} diff --git a/src/parser.rs b/src/parser.rs index 802f8679..dccad46e 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -12,9 +12,9 @@ use crate::stdlib::{ boxed::Box, char, collections::HashMap, - fmt::Display, format, iter::Peekable, + num::NonZeroUsize, ops::Add, rc::Rc, string::{String, ToString}, @@ -72,7 +72,7 @@ impl AST { /// # Example /// /// ``` - /// # fn main() -> Result<(), rhai::EvalAltResult> { + /// # fn main() -> Result<(), Box> { /// # #[cfg(not(feature = "no_function"))] /// # { /// use rhai::Engine; @@ -170,7 +170,7 @@ pub struct FnDef { /// Names of function parameters. pub params: Vec, /// Function body. - pub body: Stmt, + pub body: Box, /// Position of the function definition. pub pos: Position, } @@ -184,6 +184,41 @@ pub enum ReturnType { Exception, } +/// A type that encapsulates a local stack with variable names to simulate an actual runtime scope. +#[derive(Debug, Clone)] +struct Stack(Vec); + +impl Stack { + /// Create a new `Stack`. + pub fn new() -> Self { + Self(Vec::new()) + } + /// Get the number of variables in the `Stack`. + pub fn len(&self) -> usize { + self.0.len() + } + /// Push (add) a new variable onto the `Stack`. + pub fn push(&mut self, name: String) { + self.0.push(name); + } + /// Rewind the stack to a previous size. + pub fn rewind(&mut self, len: usize) { + self.0.truncate(len); + } + /// Find a variable by name in the `Stack`, searching in reverse. + /// The return value is the offset to be deducted from `Stack::len`, + /// i.e. the top element of the `Stack` is offset 1. + /// Return zero when the variable name is not found in the `Stack`. + pub fn find(&self, name: &str) -> Option { + self.0 + .iter() + .rev() + .enumerate() + .find(|(_, n)| *n == name) + .and_then(|(i, _)| NonZeroUsize::new(i + 1)) + } +} + /// A statement. #[derive(Debug, Clone)] pub enum Stmt { @@ -196,11 +231,11 @@ pub enum Stmt { /// loop { stmt } Loop(Box), /// for id in expr { stmt } - For(Cow<'static, str>, Box, Box), + For(String, Box, Box), /// let id = expr - Let(Cow<'static, str>, Option>, Position), + Let(String, Option>, Position), /// const id = expr - Const(Cow<'static, str>, Box, Position), + Const(String, Box, Position), /// { stmt; ... } Block(Vec, Position), /// { stmt } @@ -280,15 +315,22 @@ pub enum Expr { /// Character constant. CharConstant(char, Position), /// String constant. - StringConstant(Cow<'static, str>, Position), + StringConstant(String, Position), /// Variable access. - Variable(Cow<'static, str>, Position), + Variable(String, Option, Position), /// Property access. - Property(Cow<'static, str>, Position), + Property(String, Position), /// { stmt } Stmt(Box, Position), /// func(expr, ... ) - FunctionCall(Cow<'static, str>, Vec, Option, Position), + /// Use `Cow<'static, str>` because a lot of operators (e.g. `==`, `>=`) are implemented as function calls + /// and the function names are predictable, so no need to allocate a new `String`. + FunctionCall( + Cow<'static, str>, + Box>, + Option>, + Position, + ), /// expr = expr Assignment(Box, Box, Position), /// lhs.rhs @@ -321,14 +363,14 @@ impl Expr { /// Panics when the expression is not constant. pub fn get_constant_value(&self) -> Dynamic { match self { - Self::IntegerConstant(i, _) => Dynamic::from_int(*i), + Self::IntegerConstant(i, _) => (*i).into(), #[cfg(not(feature = "no_float"))] - Self::FloatConstant(f, _) => Dynamic::from_float(*f), - Self::CharConstant(c, _) => Dynamic::from_char(*c), - Self::StringConstant(s, _) => Dynamic::from_string(s.to_string()), - Self::True(_) => Dynamic::from_bool(true), - Self::False(_) => Dynamic::from_bool(false), - Self::Unit(_) => Dynamic::from_unit(), + Self::FloatConstant(f, _) => (*f).into(), + Self::CharConstant(c, _) => (*c).into(), + Self::StringConstant(s, _) => s.clone().into(), + Self::True(_) => true.into(), + Self::False(_) => false.into(), + Self::Unit(_) => ().into(), Self::Array(items, _) if items.iter().all(Self::is_constant) => { Dynamic(Union::Array(Box::new( @@ -382,7 +424,7 @@ impl Expr { | Self::StringConstant(_, pos) | Self::Array(_, pos) | Self::Map(_, pos) - | Self::Variable(_, pos) + | Self::Variable(_, _, pos) | Self::Property(_, pos) | Self::Stmt(_, pos) | Self::FunctionCall(_, _, _, pos) @@ -408,7 +450,7 @@ impl Expr { | Self::StringConstant(_, pos) | Self::Array(_, pos) | Self::Map(_, pos) - | Self::Variable(_, pos) + | Self::Variable(_, _, pos) | Self::Property(_, pos) | Self::Stmt(_, pos) | Self::FunctionCall(_, _, _, pos) @@ -439,7 +481,7 @@ impl Expr { Self::Stmt(stmt, _) => stmt.is_pure(), - Self::Variable(_, _) => true, + Self::Variable(_, _, _) => true, expr => expr.is_constant(), } @@ -476,51 +518,57 @@ impl Expr { /// Is a particular token allowed as a postfix operator to this expression? pub fn is_valid_postfix(&self, token: &Token) -> bool { match self { - Expr::IntegerConstant(_, _) - | Expr::FloatConstant(_, _) - | Expr::CharConstant(_, _) - | Expr::In(_, _, _) - | Expr::And(_, _, _) - | Expr::Or(_, _, _) - | Expr::True(_) - | Expr::False(_) - | Expr::Unit(_) => false, + Self::IntegerConstant(_, _) + | Self::FloatConstant(_, _) + | Self::CharConstant(_, _) + | Self::In(_, _, _) + | Self::And(_, _, _) + | Self::Or(_, _, _) + | Self::True(_) + | Self::False(_) + | Self::Unit(_) => false, - Expr::StringConstant(_, _) - | Expr::Stmt(_, _) - | Expr::FunctionCall(_, _, _, _) - | Expr::Assignment(_, _, _) - | Expr::Dot(_, _, _) - | Expr::Index(_, _, _) - | Expr::Array(_, _) - | Expr::Map(_, _) => match token { + Self::StringConstant(_, _) + | Self::Stmt(_, _) + | Self::FunctionCall(_, _, _, _) + | Self::Assignment(_, _, _) + | Self::Dot(_, _, _) + | Self::Index(_, _, _) + | Self::Array(_, _) + | Self::Map(_, _) => match token { Token::LeftBracket => true, _ => false, }, - Expr::Variable(_, _) | Expr::Property(_, _) => match token { + Self::Variable(_, _, _) | Self::Property(_, _) => match token { Token::LeftBracket | Token::LeftParen => true, _ => false, }, } } + + /// Convert a `Variable` into a `Property`. All other variants are untouched. + pub(crate) fn into_property(self) -> Self { + match self { + Self::Variable(id, _, pos) => Self::Property(id, pos), + _ => self, + } + } } /// Consume a particular token, checking that it is the expected one. fn eat_token(input: &mut Peekable, token: Token) -> Position { - if let Some((t, pos)) = input.next() { - if t != token { - panic!( - "expecting {} (found {}) at {}", - token.syntax(), - t.syntax(), - pos - ); - } - pos - } else { - panic!("expecting {} but already EOF", token.syntax()); + let (t, pos) = input.next().unwrap(); + + if t != token { + panic!( + "expecting {} (found {}) at {}", + token.syntax(), + t.syntax(), + pos + ); } + pos } /// Match a particular token, consuming it if matched. @@ -537,6 +585,7 @@ fn match_token(input: &mut Peekable, token: Token) -> Result( input: &mut Peekable>, + stack: &mut Stack, begin: Position, allow_stmt_expr: bool, ) -> Result> { @@ -544,11 +593,13 @@ fn parse_paren_expr<'a>( return Ok(Expr::Unit(begin)); } - let expr = parse_expr(input, allow_stmt_expr)?; + let expr = parse_expr(input, stack, allow_stmt_expr)?; match input.next().unwrap() { // ( xxx ) (Token::RightParen, _) => Ok(expr), + // ( + (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(pos)), // ( xxx ??? (_, pos) => Err(PERR::MissingToken( ")".into(), @@ -559,16 +610,17 @@ fn parse_paren_expr<'a>( } /// Parse a function call. -fn parse_call_expr<'a, S: Into> + Display>( - id: S, +fn parse_call_expr<'a>( input: &mut Peekable>, + stack: &mut Stack, + id: String, begin: Position, allow_stmt_expr: bool, ) -> Result> { - let mut args_expr_list = Vec::new(); + let mut args = Vec::new(); match input.peek().unwrap() { - //id {EOF} + // id (Token::EOF, pos) => { return Err(PERR::MissingToken( ")".into(), @@ -576,19 +628,28 @@ fn parse_call_expr<'a, S: Into> + Display>( ) .into_err(*pos)) } + // id + (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(*pos)), // id() (Token::RightParen, _) => { eat_token(input, Token::RightParen); - return Ok(Expr::FunctionCall(id.into(), args_expr_list, None, begin)); + return Ok(Expr::FunctionCall(id.into(), Box::new(args), None, begin)); } // id... _ => (), } loop { - args_expr_list.push(parse_expr(input, allow_stmt_expr)?); + args.push(parse_expr(input, stack, allow_stmt_expr)?); match input.peek().unwrap() { + (Token::RightParen, _) => { + eat_token(input, Token::RightParen); + return Ok(Expr::FunctionCall(id.into(), Box::new(args), None, begin)); + } + (Token::Comma, _) => { + eat_token(input, Token::Comma); + } (Token::EOF, pos) => { return Err(PERR::MissingToken( ")".into(), @@ -596,12 +657,8 @@ fn parse_call_expr<'a, S: Into> + Display>( ) .into_err(*pos)) } - (Token::RightParen, _) => { - eat_token(input, Token::RightParen); - return Ok(Expr::FunctionCall(id.into(), args_expr_list, None, begin)); - } - (Token::Comma, _) => { - eat_token(input, Token::Comma); + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(*pos)) } (_, pos) => { return Err(PERR::MissingToken( @@ -614,14 +671,16 @@ fn parse_call_expr<'a, S: Into> + Display>( } } -/// Parse an indexing expression. -fn parse_index_expr<'a>( - lhs: Box, +/// Parse an indexing chain. +/// Indexing binds to the right, so this call parses all possible levels of indexing following in the input. +fn parse_index_chain<'a>( input: &mut Peekable>, + stack: &mut Stack, + lhs: Expr, pos: Position, allow_stmt_expr: bool, ) -> Result> { - let idx_expr = parse_expr(input, allow_stmt_expr)?; + let idx_expr = parse_expr(input, stack, allow_stmt_expr)?; // Check type of indexing - must be integer or string match &idx_expr { @@ -633,7 +692,7 @@ fn parse_index_expr<'a>( )) .into_err(*pos)) } - Expr::IntegerConstant(_, pos) => match *lhs { + Expr::IntegerConstant(_, pos) => match lhs { Expr::Array(_, _) | Expr::StringConstant(_, _) => (), Expr::Map(_, _) => { @@ -662,7 +721,7 @@ fn parse_index_expr<'a>( }, // lhs[string] - Expr::StringConstant(_, pos) => match *lhs { + Expr::StringConstant(_, pos) => match lhs { Expr::Map(_, _) => (), Expr::Array(_, _) | Expr::StringConstant(_, _) => { @@ -729,8 +788,23 @@ fn parse_index_expr<'a>( match input.peek().unwrap() { (Token::RightBracket, _) => { eat_token(input, Token::RightBracket); - Ok(Expr::Index(lhs, Box::new(idx_expr), pos)) + + // Any more indexing following? + match input.peek().unwrap() { + // If another indexing level, right-bind it + (Token::LeftBracket, _) => { + let follow_pos = eat_token(input, Token::LeftBracket); + // Recursively parse the indexing chain, right-binding each + let follow = + parse_index_chain(input, stack, idx_expr, follow_pos, allow_stmt_expr)?; + // Indexing binds to right + Ok(Expr::Index(Box::new(lhs), Box::new(follow), pos)) + } + // Otherwise terminate the indexing chain + _ => Ok(Expr::Index(Box::new(lhs), Box::new(idx_expr), pos)), + } } + (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(*pos)), (_, pos) => Err(PERR::MissingToken( "]".into(), "for a matching [ in this index expression".into(), @@ -742,6 +816,7 @@ fn parse_index_expr<'a>( /// Parse an array literal. fn parse_array_literal<'a>( input: &mut Peekable>, + stack: &mut Stack, begin: Position, allow_stmt_expr: bool, ) -> Result> { @@ -749,19 +824,22 @@ fn parse_array_literal<'a>( if !match_token(input, Token::RightBracket)? { while !input.peek().unwrap().0.is_eof() { - arr.push(parse_expr(input, allow_stmt_expr)?); + arr.push(parse_expr(input, stack, allow_stmt_expr)?); match input.peek().unwrap() { + (Token::Comma, _) => eat_token(input, Token::Comma), + (Token::RightBracket, _) => { + eat_token(input, Token::RightBracket); + break; + } (Token::EOF, pos) => { return Err( PERR::MissingToken("]".into(), "to end this array literal".into()) .into_err(*pos), ) } - (Token::Comma, _) => eat_token(input, Token::Comma), - (Token::RightBracket, _) => { - eat_token(input, Token::RightBracket); - break; + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(*pos)) } (_, pos) => { return Err(PERR::MissingToken( @@ -780,6 +858,7 @@ fn parse_array_literal<'a>( /// Parse a map literal. fn parse_map_literal<'a>( input: &mut Peekable>, + stack: &mut Stack, begin: Position, allow_stmt_expr: bool, ) -> Result> { @@ -792,6 +871,9 @@ fn parse_map_literal<'a>( let (name, pos) = match input.next().unwrap() { (Token::Identifier(s), pos) => (s, pos), (Token::StringConst(s), pos) => (s, pos), + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(pos)) + } (_, pos) if map.is_empty() => { return Err(PERR::MissingToken("}".into(), MISSING_RBRACE.into()).into_err(pos)) } @@ -803,6 +885,9 @@ fn parse_map_literal<'a>( match input.next().unwrap() { (Token::Colon, _) => (), + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(pos)) + } (_, pos) => { return Err(PERR::MissingToken( ":".into(), @@ -815,7 +900,7 @@ fn parse_map_literal<'a>( } }; - let expr = parse_expr(input, allow_stmt_expr)?; + let expr = parse_expr(input, stack, allow_stmt_expr)?; map.push((name, expr, pos)); @@ -834,6 +919,9 @@ fn parse_map_literal<'a>( ) .into_err(*pos)) } + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(*pos)) + } (_, pos) => { return Err(PERR::MissingToken("}".into(), MISSING_RBRACE.into()).into_err(*pos)) } @@ -858,13 +946,14 @@ fn parse_map_literal<'a>( /// Parse a primary expression. fn parse_primary<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { let (token, pos) = match input.peek().unwrap() { // { - block statement as expression (Token::LeftBrace, pos) if allow_stmt_expr => { let pos = *pos; - return parse_block(input, false, allow_stmt_expr) + return parse_block(input, stack, false, allow_stmt_expr) .map(|block| Expr::Stmt(Box::new(block), pos)); } (Token::EOF, pos) => return Err(PERR::UnexpectedEOF.into_err(*pos)), @@ -876,13 +965,16 @@ fn parse_primary<'a>( #[cfg(not(feature = "no_float"))] Token::FloatConstant(x) => Expr::FloatConstant(x, pos), Token::CharConstant(c) => Expr::CharConstant(c, pos), - Token::StringConst(s) => Expr::StringConstant(s.into(), pos), - Token::Identifier(s) => Expr::Variable(s.into(), pos), - Token::LeftParen => parse_paren_expr(input, pos, allow_stmt_expr)?, + Token::StringConst(s) => Expr::StringConstant(s, pos), + Token::Identifier(s) => { + let index = stack.find(&s); + Expr::Variable(s, index, pos) + } + Token::LeftParen => parse_paren_expr(input, stack, pos, allow_stmt_expr)?, #[cfg(not(feature = "no_index"))] - Token::LeftBracket => parse_array_literal(input, pos, allow_stmt_expr)?, + Token::LeftBracket => parse_array_literal(input, stack, pos, allow_stmt_expr)?, #[cfg(not(feature = "no_object"))] - Token::MapStart => parse_map_literal(input, pos, allow_stmt_expr)?, + Token::MapStart => parse_map_literal(input, stack, pos, allow_stmt_expr)?, Token::True => Expr::True(pos), Token::False => Expr::False(pos), Token::LexError(err) => return Err(PERR::BadInput(err.to_string()).into_err(pos)), @@ -903,13 +995,13 @@ fn parse_primary<'a>( root_expr = match (root_expr, token) { // Function call - (Expr::Variable(id, pos), Token::LeftParen) + (Expr::Variable(id, _, pos), Token::LeftParen) | (Expr::Property(id, pos), Token::LeftParen) => { - parse_call_expr(id, input, pos, allow_stmt_expr)? + parse_call_expr(input, stack, id, pos, allow_stmt_expr)? } // Indexing (expr, Token::LeftBracket) => { - parse_index_expr(Box::new(expr), input, pos, allow_stmt_expr)? + parse_index_chain(input, stack, expr, pos, allow_stmt_expr)? } // Unknown postfix operator (expr, token) => panic!("unknown postfix operator {:?} for {:?}", token, expr), @@ -922,6 +1014,7 @@ fn parse_primary<'a>( /// Parse a potential unary operator. fn parse_unary<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { match input.peek().unwrap() { @@ -929,7 +1022,7 @@ fn parse_unary<'a>( (Token::If, pos) => { let pos = *pos; Ok(Expr::Stmt( - Box::new(parse_if(input, false, allow_stmt_expr)?), + Box::new(parse_if(input, stack, false, allow_stmt_expr)?), pos, )) } @@ -937,7 +1030,7 @@ fn parse_unary<'a>( (Token::UnaryMinus, _) => { let pos = eat_token(input, Token::UnaryMinus); - match parse_unary(input, allow_stmt_expr)? { + match parse_unary(input, stack, allow_stmt_expr)? { // Negative integer Expr::IntegerConstant(i, _) => i .checked_neg() @@ -962,115 +1055,117 @@ fn parse_unary<'a>( Expr::FloatConstant(f, pos) => Ok(Expr::FloatConstant(-f, pos)), // Call negative function - expr => Ok(Expr::FunctionCall("-".into(), vec![expr], None, pos)), + e => Ok(Expr::FunctionCall("-".into(), Box::new(vec![e]), None, pos)), } } // +expr (Token::UnaryPlus, _) => { eat_token(input, Token::UnaryPlus); - parse_unary(input, allow_stmt_expr) + parse_unary(input, stack, allow_stmt_expr) } // !expr (Token::Bang, _) => { let pos = eat_token(input, Token::Bang); Ok(Expr::FunctionCall( "!".into(), - vec![parse_primary(input, allow_stmt_expr)?], - Some(Dynamic::from_bool(false)), // NOT operator, when operating on invalid operand, defaults to false + Box::new(vec![parse_primary(input, stack, allow_stmt_expr)?]), + Some(Box::new(false.into())), // NOT operator, when operating on invalid operand, defaults to false pos, )) } - // {EOF} + // (Token::EOF, pos) => Err(PERR::UnexpectedEOF.into_err(*pos)), // All other tokens - _ => parse_primary(input, allow_stmt_expr), + _ => parse_primary(input, stack, allow_stmt_expr), } } -/// Parse an assignment. -fn parse_assignment(lhs: Expr, rhs: Expr, pos: Position) -> Result> { - // Is the LHS in a valid format for an assignment target? - fn valid_assignment_chain(expr: &Expr, is_top: bool) -> Option> { - match expr { - // var - Expr::Variable(_, _) => { - assert!(is_top, "property expected but gets variable"); - None - } - // property - Expr::Property(_, _) => { - assert!(!is_top, "variable expected but gets property"); - None - } - - // idx_lhs[...] - Expr::Index(idx_lhs, _, pos) => match idx_lhs.as_ref() { - // var[...] - Expr::Variable(_, _) => { - assert!(is_top, "property expected but gets variable"); - None - } - // property[...] - Expr::Property(_, _) => { - assert!(!is_top, "variable expected but gets property"); - None - } - // ???[...][...] - Expr::Index(_, _, _) => Some(ParseErrorType::AssignmentToCopy.into_err(*pos)), - // idx_lhs[...] - _ => Some(ParseErrorType::AssignmentToInvalidLHS.into_err(*pos)), - }, - - // dot_lhs.dot_rhs - Expr::Dot(dot_lhs, dot_rhs, pos) => match dot_lhs.as_ref() { - // var.dot_rhs - Expr::Variable(_, _) if is_top => valid_assignment_chain(dot_rhs, false), - // property.dot_rhs - Expr::Property(_, _) if !is_top => valid_assignment_chain(dot_rhs, false), - // idx_lhs[...].dot_rhs - Expr::Index(idx_lhs, _, _) => match idx_lhs.as_ref() { - // var[...].dot_rhs - Expr::Variable(_, _) if is_top => valid_assignment_chain(dot_rhs, false), - // property[...].dot_rhs - Expr::Property(_, _) if !is_top => valid_assignment_chain(dot_rhs, false), - // ???[...][...].dot_rhs - Expr::Index(_, _, _) => Some(ParseErrorType::AssignmentToCopy.into_err(*pos)), - // idx_lhs[...].dot_rhs - _ => Some(ParseErrorType::AssignmentToCopy.into_err(idx_lhs.position())), - }, - - expr => panic!("unexpected dot expression {:#?}", expr), - }, - - _ => Some(ParseErrorType::AssignmentToInvalidLHS.into_err(expr.position())), - } - } - - match valid_assignment_chain(&lhs, true) { - None => Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs), pos)), - Some(err) => Err(err), - } +fn parse_assignment_stmt<'a>( + input: &mut Peekable>, + stack: &mut Stack, + lhs: Expr, + allow_stmt_expr: bool, +) -> Result> { + let pos = eat_token(input, Token::Equals); + let rhs = parse_expr(input, stack, allow_stmt_expr)?; + Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs), pos)) } /// Parse an operator-assignment expression. -fn parse_op_assignment>>( - op: S, +fn parse_op_assignment_stmt<'a>( + input: &mut Peekable>, + stack: &mut Stack, lhs: Expr, - rhs: Expr, - pos: Position, + allow_stmt_expr: bool, ) -> Result> { + let (op, pos) = match *input.peek().unwrap() { + (Token::Equals, _) => return parse_assignment_stmt(input, stack, lhs, allow_stmt_expr), + (Token::PlusAssign, pos) => ("+", pos), + (Token::MinusAssign, pos) => ("-", pos), + (Token::MultiplyAssign, pos) => ("*", pos), + (Token::DivideAssign, pos) => ("/", pos), + (Token::LeftShiftAssign, pos) => ("<<", pos), + (Token::RightShiftAssign, pos) => (">>", pos), + (Token::ModuloAssign, pos) => ("%", pos), + (Token::PowerOfAssign, pos) => ("~", pos), + (Token::AndAssign, pos) => ("&", pos), + (Token::OrAssign, pos) => ("|", pos), + (Token::XOrAssign, pos) => ("^", pos), + (_, _) => return Ok(lhs), + }; + + input.next(); + let lhs_copy = lhs.clone(); + let rhs = parse_expr(input, stack, allow_stmt_expr)?; // lhs op= rhs -> lhs = op(lhs, rhs) - parse_assignment( - lhs, - Expr::FunctionCall(op.into(), vec![lhs_copy, rhs], None, pos), - pos, - ) + let rhs_expr = Expr::FunctionCall(op.into(), Box::new(vec![lhs_copy, rhs]), None, pos); + Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs_expr), pos)) } -/// Parse an 'in' expression. -fn parse_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result> { +/// Make a dot expression. +fn make_dot_expr(lhs: Expr, rhs: Expr, op_pos: Position, is_index: bool) -> Expr { + match (lhs, rhs) { + // idx_lhs[idx_rhs].rhs + // Attach dot chain to the bottom level of indexing chain + (Expr::Index(idx_lhs, idx_rhs, idx_pos), rhs) => Expr::Index( + idx_lhs, + Box::new(make_dot_expr(*idx_rhs, rhs, op_pos, true)), + idx_pos, + ), + // lhs.id + (lhs, rhs @ Expr::Variable(_, _, _)) | (lhs, rhs @ Expr::Property(_, _)) => { + let lhs = if is_index { lhs.into_property() } else { lhs }; + Expr::Dot(Box::new(lhs), Box::new(rhs.into_property()), op_pos) + } + // lhs.dot_lhs.dot_rhs + (lhs, Expr::Dot(dot_lhs, dot_rhs, dot_pos)) => Expr::Dot( + Box::new(lhs), + Box::new(Expr::Dot( + Box::new(dot_lhs.into_property()), + Box::new(dot_rhs.into_property()), + dot_pos, + )), + op_pos, + ), + // lhs.idx_lhs[idx_rhs] + (lhs, Expr::Index(idx_lhs, idx_rhs, idx_pos)) => Expr::Dot( + Box::new(lhs), + Box::new(Expr::Index( + Box::new(idx_lhs.into_property()), + Box::new(idx_rhs.into_property()), + idx_pos, + )), + op_pos, + ), + // lhs.rhs + (lhs, rhs) => Expr::Dot(Box::new(lhs), Box::new(rhs.into_property()), op_pos), + } +} + +/// Make an 'in' expression. +fn make_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result> { match (&lhs, &rhs) { (_, Expr::IntegerConstant(_, pos)) | (_, Expr::FloatConstant(_, pos)) @@ -1201,6 +1296,7 @@ fn parse_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result( input: &mut Peekable>, + stack: &mut Stack, parent_precedence: u8, lhs: Expr, allow_stmt_expr: bool, @@ -1221,147 +1317,123 @@ fn parse_binary_op<'a>( return Ok(current_lhs); } - if let Some((op_token, pos)) = input.next() { - let rhs = parse_unary(input, allow_stmt_expr)?; + let (op_token, pos) = input.next().unwrap(); - let next_precedence = if let Some((next_op, _)) = input.peek() { - next_op.precedence() - } else { - 0 - }; + let rhs = parse_unary(input, stack, allow_stmt_expr)?; - // Bind to right if the next operator has higher precedence - // If same precedence, then check if the operator binds right - let rhs = if (current_precedence == next_precedence && bind_right) - || current_precedence < next_precedence - { - parse_binary_op(input, current_precedence, rhs, allow_stmt_expr)? - } else { - // Otherwise bind to left (even if next operator has the same precedence) - rhs - }; + let next_precedence = input.peek().unwrap().0.precedence(); - current_lhs = match op_token { - Token::Plus => Expr::FunctionCall("+".into(), vec![current_lhs, rhs], None, pos), - Token::Minus => Expr::FunctionCall("-".into(), vec![current_lhs, rhs], None, pos), - Token::Multiply => { - Expr::FunctionCall("*".into(), vec![current_lhs, rhs], None, pos) - } - Token::Divide => Expr::FunctionCall("/".into(), vec![current_lhs, rhs], None, pos), + // Bind to right if the next operator has higher precedence + // If same precedence, then check if the operator binds right + let rhs = if (current_precedence == next_precedence && bind_right) + || current_precedence < next_precedence + { + parse_binary_op(input, stack, current_precedence, rhs, allow_stmt_expr)? + } else { + // Otherwise bind to left (even if next operator has the same precedence) + rhs + }; - Token::Equals => parse_assignment(current_lhs, rhs, pos)?, - Token::PlusAssign => parse_op_assignment("+", current_lhs, rhs, pos)?, - Token::MinusAssign => parse_op_assignment("-", current_lhs, rhs, pos)?, + let cmp_default = Some(Box::new(false.into())); - #[cfg(not(feature = "no_object"))] - Token::Period => { - fn check_property(expr: Expr) -> Result> { - match expr { - // xxx.lhs.rhs - Expr::Dot(lhs, rhs, pos) => Ok(Expr::Dot( - Box::new(check_property(*lhs)?), - Box::new(check_property(*rhs)?), - pos, - )), - // xxx.lhs[idx] - Expr::Index(lhs, idx, pos) => { - Ok(Expr::Index(Box::new(check_property(*lhs)?), idx, pos)) - } - // xxx.id - Expr::Variable(id, pos) => Ok(Expr::Property(id, pos)), - // xxx.prop - expr @ Expr::Property(_, _) => Ok(expr), - // xxx.fn() - expr @ Expr::FunctionCall(_, _, _, _) => Ok(expr), - expr => Err(PERR::PropertyExpected.into_err(expr.position())), - } - } + current_lhs = match op_token { + Token::Plus => { + Expr::FunctionCall("+".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::Minus => { + Expr::FunctionCall("-".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::Multiply => { + Expr::FunctionCall("*".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::Divide => { + Expr::FunctionCall("/".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } - Expr::Dot(Box::new(current_lhs), Box::new(check_property(rhs)?), pos) - } + Token::LeftShift => { + Expr::FunctionCall("<<".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::RightShift => { + Expr::FunctionCall(">>".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::Modulo => { + Expr::FunctionCall("%".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::PowerOf => { + Expr::FunctionCall("~".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } - // Comparison operators default to false when passed invalid operands - Token::EqualsTo => Expr::FunctionCall( - "==".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), - Token::NotEqualsTo => Expr::FunctionCall( - "!=".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), - Token::LessThan => Expr::FunctionCall( - "<".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), - Token::LessThanEqualsTo => Expr::FunctionCall( - "<=".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), - Token::GreaterThan => Expr::FunctionCall( - ">".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), - Token::GreaterThanEqualsTo => Expr::FunctionCall( - ">=".into(), - vec![current_lhs, rhs], - Some(Dynamic::from_bool(false)), - pos, - ), + // Comparison operators default to false when passed invalid operands + Token::EqualsTo => Expr::FunctionCall( + "==".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), + Token::NotEqualsTo => Expr::FunctionCall( + "!=".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), + Token::LessThan => Expr::FunctionCall( + "<".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), + Token::LessThanEqualsTo => Expr::FunctionCall( + "<=".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), + Token::GreaterThan => Expr::FunctionCall( + ">".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), + Token::GreaterThanEqualsTo => Expr::FunctionCall( + ">=".into(), + Box::new(vec![current_lhs, rhs]), + cmp_default, + pos, + ), - Token::Or => Expr::Or(Box::new(current_lhs), Box::new(rhs), pos), - Token::And => Expr::And(Box::new(current_lhs), Box::new(rhs), pos), + Token::Or => Expr::Or(Box::new(current_lhs), Box::new(rhs), pos), + Token::And => Expr::And(Box::new(current_lhs), Box::new(rhs), pos), + Token::Ampersand => { + Expr::FunctionCall("&".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::Pipe => { + Expr::FunctionCall("|".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } + Token::XOr => { + Expr::FunctionCall("^".into(), Box::new(vec![current_lhs, rhs]), None, pos) + } - Token::In => parse_in_expr(current_lhs, rhs, pos)?, + Token::In => make_in_expr(current_lhs, rhs, pos)?, - Token::XOr => Expr::FunctionCall("^".into(), vec![current_lhs, rhs], None, pos), - Token::OrAssign => parse_op_assignment("|", current_lhs, rhs, pos)?, - Token::AndAssign => parse_op_assignment("&", current_lhs, rhs, pos)?, - Token::XOrAssign => parse_op_assignment("^", current_lhs, rhs, pos)?, - Token::MultiplyAssign => parse_op_assignment("*", current_lhs, rhs, pos)?, - Token::DivideAssign => parse_op_assignment("/", current_lhs, rhs, pos)?, - Token::Pipe => Expr::FunctionCall("|".into(), vec![current_lhs, rhs], None, pos), - Token::LeftShift => { - Expr::FunctionCall("<<".into(), vec![current_lhs, rhs], None, pos) - } - Token::RightShift => { - Expr::FunctionCall(">>".into(), vec![current_lhs, rhs], None, pos) - } - Token::LeftShiftAssign => parse_op_assignment("<<", current_lhs, rhs, pos)?, - Token::RightShiftAssign => parse_op_assignment(">>", current_lhs, rhs, pos)?, - Token::Ampersand => { - Expr::FunctionCall("&".into(), vec![current_lhs, rhs], None, pos) - } - Token::Modulo => Expr::FunctionCall("%".into(), vec![current_lhs, rhs], None, pos), - Token::ModuloAssign => parse_op_assignment("%", current_lhs, rhs, pos)?, - Token::PowerOf => Expr::FunctionCall("~".into(), vec![current_lhs, rhs], None, pos), - Token::PowerOfAssign => parse_op_assignment("~", current_lhs, rhs, pos)?, - token => return Err(PERR::UnknownOperator(token.syntax().into()).into_err(pos)), - }; - } + #[cfg(not(feature = "no_object"))] + Token::Period => make_dot_expr(current_lhs, rhs, pos, false), + + token => return Err(PERR::UnknownOperator(token.syntax().into()).into_err(pos)), + }; } } /// Parse an expression. fn parse_expr<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { - // Parse a real expression - let lhs = parse_unary(input, allow_stmt_expr)?; - parse_binary_op(input, 1, lhs, allow_stmt_expr) + let lhs = parse_unary(input, stack, allow_stmt_expr)?; + parse_binary_op(input, stack, 1, lhs, allow_stmt_expr) } -/// Make sure that the expression is not a statement expression (i.e. wrapped in {}) +/// Make sure that the expression is not a statement expression (i.e. wrapped in `{}`). fn ensure_not_statement_expr<'a>( input: &mut Peekable>, type_name: &str, @@ -1376,9 +1448,39 @@ fn ensure_not_statement_expr<'a>( } } +/// Make sure that the expression is not a mis-typed assignment (i.e. `a = b` instead of `a == b`). +fn ensure_not_assignment<'a>( + input: &mut Peekable>, +) -> Result<(), Box> { + match input.peek().unwrap() { + (Token::Equals, pos) => { + return Err(PERR::BadInput("Possibly a typo of '=='?".to_string()).into_err(*pos)) + } + (Token::PlusAssign, pos) + | (Token::MinusAssign, pos) + | (Token::MultiplyAssign, pos) + | (Token::DivideAssign, pos) + | (Token::LeftShiftAssign, pos) + | (Token::RightShiftAssign, pos) + | (Token::ModuloAssign, pos) + | (Token::PowerOfAssign, pos) + | (Token::AndAssign, pos) + | (Token::OrAssign, pos) + | (Token::XOrAssign, pos) => { + return Err(PERR::BadInput( + "Expecting a boolean expression, not an assignment".to_string(), + ) + .into_err(*pos)) + } + + _ => Ok(()), + } +} + /// Parse an if statement. fn parse_if<'a>( input: &mut Peekable>, + stack: &mut Stack, breakable: bool, allow_stmt_expr: bool, ) -> Result> { @@ -1387,17 +1489,18 @@ fn parse_if<'a>( // if guard { if_body } ensure_not_statement_expr(input, "a boolean")?; - let guard = parse_expr(input, allow_stmt_expr)?; - let if_body = parse_block(input, breakable, allow_stmt_expr)?; + let guard = parse_expr(input, stack, allow_stmt_expr)?; + ensure_not_assignment(input)?; + let if_body = parse_block(input, stack, breakable, allow_stmt_expr)?; // if guard { if_body } else ... let else_body = if match_token(input, Token::Else).unwrap_or(false) { - Some(Box::new(if matches!(input.peek(), Some((Token::If, _))) { + Some(Box::new(if let (Token::If, _) = input.peek().unwrap() { // if guard { if_body } else if ... - parse_if(input, breakable, allow_stmt_expr)? + parse_if(input, stack, breakable, allow_stmt_expr)? } else { // if guard { if_body } else { else-body } - parse_block(input, breakable, allow_stmt_expr)? + parse_block(input, stack, breakable, allow_stmt_expr)? })) } else { None @@ -1413,6 +1516,7 @@ fn parse_if<'a>( /// Parse a while loop. fn parse_while<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { // while ... @@ -1420,8 +1524,9 @@ fn parse_while<'a>( // while guard { body } ensure_not_statement_expr(input, "a boolean")?; - let guard = parse_expr(input, allow_stmt_expr)?; - let body = parse_block(input, true, allow_stmt_expr)?; + let guard = parse_expr(input, stack, allow_stmt_expr)?; + ensure_not_assignment(input)?; + let body = parse_block(input, stack, true, allow_stmt_expr)?; Ok(Stmt::While(Box::new(guard), Box::new(body))) } @@ -1429,13 +1534,14 @@ fn parse_while<'a>( /// Parse a loop statement. fn parse_loop<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { // loop ... eat_token(input, Token::Loop); // loop { body } - let body = parse_block(input, true, allow_stmt_expr)?; + let body = parse_block(input, stack, true, allow_stmt_expr)?; Ok(Stmt::Loop(Box::new(body))) } @@ -1443,6 +1549,7 @@ fn parse_loop<'a>( /// Parse a for loop. fn parse_for<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { // for ... @@ -1463,6 +1570,7 @@ fn parse_for<'a>( // for name in ... match input.next().unwrap() { (Token::In, _) => (), + (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(pos)), (_, pos) => { return Err( PERR::MissingToken("in".into(), "after the iteration variable".into()) @@ -1473,15 +1581,22 @@ fn parse_for<'a>( // for name in expr { body } ensure_not_statement_expr(input, "a boolean")?; - let expr = parse_expr(input, allow_stmt_expr)?; - let body = parse_block(input, true, allow_stmt_expr)?; + let expr = parse_expr(input, stack, allow_stmt_expr)?; - Ok(Stmt::For(name.into(), Box::new(expr), Box::new(body))) + let prev_len = stack.len(); + stack.push(name.clone()); + + let body = parse_block(input, stack, true, allow_stmt_expr)?; + + stack.rewind(prev_len); + + Ok(Stmt::For(name, Box::new(expr), Box::new(body))) } /// Parse a variable definition statement. fn parse_let<'a>( input: &mut Peekable>, + stack: &mut Stack, var_type: ScopeEntryType, allow_stmt_expr: bool, ) -> Result> { @@ -1498,14 +1613,18 @@ fn parse_let<'a>( // let name = ... if match_token(input, Token::Equals)? { // let name = expr - let init_value = parse_expr(input, allow_stmt_expr)?; + let init_value = parse_expr(input, stack, allow_stmt_expr)?; match var_type { // let name = expr - ScopeEntryType::Normal => Ok(Stmt::Let(name.into(), Some(Box::new(init_value)), pos)), + ScopeEntryType::Normal => { + stack.push(name.clone()); + Ok(Stmt::Let(name, Some(Box::new(init_value)), pos)) + } // const name = { expr:constant } ScopeEntryType::Constant if init_value.is_constant() => { - Ok(Stmt::Const(name.into(), Box::new(init_value), pos)) + stack.push(name.clone()); + Ok(Stmt::Const(name, Box::new(init_value), pos)) } // const name = expr - error ScopeEntryType::Constant => { @@ -1514,19 +1633,21 @@ fn parse_let<'a>( } } else { // let name - Ok(Stmt::Let(name.into(), None, pos)) + Ok(Stmt::Let(name, None, pos)) } } /// Parse a statement block. fn parse_block<'a>( input: &mut Peekable>, + stack: &mut Stack, breakable: bool, allow_stmt_expr: bool, ) -> Result> { // Must start with { let pos = match input.next().unwrap() { (Token::LeftBrace, pos) => pos, + (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(pos)), (_, pos) => { return Err( PERR::MissingToken("{".into(), "to start a statement block".into()).into_err(pos), @@ -1535,10 +1656,11 @@ fn parse_block<'a>( }; let mut statements = Vec::new(); + let prev_len = stack.len(); while !match_token(input, Token::RightBrace)? { // Parse statements inside the block - let stmt = parse_stmt(input, breakable, allow_stmt_expr)?; + let stmt = parse_stmt(input, stack, breakable, allow_stmt_expr)?; // See if it needs a terminating semicolon let need_semicolon = !stmt.is_self_terminated(); @@ -1559,7 +1681,11 @@ fn parse_block<'a>( (Token::SemiColon, _) if !need_semicolon => (), // { ... { stmt } ??? (_, _) if !need_semicolon => (), - // { ... stmt ??? - error + // { ... stmt + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(*pos)) + } + // { ... stmt ??? (_, pos) => { // Semicolons are not optional between statements return Err( @@ -1570,20 +1696,26 @@ fn parse_block<'a>( } } + stack.rewind(prev_len); + Ok(Stmt::Block(statements, pos)) } /// Parse an expression as a statement. fn parse_expr_stmt<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { - Ok(Stmt::Expr(Box::new(parse_expr(input, allow_stmt_expr)?))) + let expr = parse_expr(input, stack, allow_stmt_expr)?; + let expr = parse_op_assignment_stmt(input, stack, expr, allow_stmt_expr)?; + Ok(Stmt::Expr(Box::new(expr))) } /// Parse a single statement. fn parse_stmt<'a>( input: &mut Peekable>, + stack: &mut Stack, breakable: bool, allow_stmt_expr: bool, ) -> Result> { @@ -1596,16 +1728,16 @@ fn parse_stmt<'a>( // Semicolon - empty statement Token::SemiColon => Ok(Stmt::Noop(*pos)), - Token::LeftBrace => parse_block(input, breakable, allow_stmt_expr), + Token::LeftBrace => parse_block(input, stack, breakable, allow_stmt_expr), // fn ... #[cfg(not(feature = "no_function"))] Token::Fn => Err(PERR::WrongFnDefinition.into_err(*pos)), - Token::If => parse_if(input, breakable, allow_stmt_expr), - Token::While => parse_while(input, allow_stmt_expr), - Token::Loop => parse_loop(input, allow_stmt_expr), - Token::For => parse_for(input, allow_stmt_expr), + Token::If => parse_if(input, stack, breakable, allow_stmt_expr), + Token::While => parse_while(input, stack, allow_stmt_expr), + Token::Loop => parse_loop(input, stack, allow_stmt_expr), + Token::For => parse_for(input, stack, allow_stmt_expr), Token::Continue if breakable => { let pos = eat_token(input, Token::Continue); @@ -1620,36 +1752,37 @@ fn parse_stmt<'a>( Token::Return | Token::Throw => { let pos = *pos; - let return_type = match input.next() { - Some((Token::Return, _)) => ReturnType::Return, - Some((Token::Throw, _)) => ReturnType::Exception, + let return_type = match input.next().unwrap() { + (Token::Return, _) => ReturnType::Return, + (Token::Throw, _) => ReturnType::Exception, _ => panic!("token should be return or throw"), }; match input.peek().unwrap() { - // `return`/`throw` at {EOF} + // `return`/`throw` at (Token::EOF, pos) => Ok(Stmt::ReturnWithVal(None, return_type, *pos)), // `return;` or `throw;` (Token::SemiColon, _) => Ok(Stmt::ReturnWithVal(None, return_type, pos)), // `return` or `throw` with expression (_, _) => { - let expr = parse_expr(input, allow_stmt_expr)?; + let expr = parse_expr(input, stack, allow_stmt_expr)?; let pos = expr.position(); Ok(Stmt::ReturnWithVal(Some(Box::new(expr)), return_type, pos)) } } } - Token::Let => parse_let(input, ScopeEntryType::Normal, allow_stmt_expr), - Token::Const => parse_let(input, ScopeEntryType::Constant, allow_stmt_expr), + Token::Let => parse_let(input, stack, ScopeEntryType::Normal, allow_stmt_expr), + Token::Const => parse_let(input, stack, ScopeEntryType::Constant, allow_stmt_expr), - _ => parse_expr_stmt(input, allow_stmt_expr), + _ => parse_expr_stmt(input, stack, allow_stmt_expr), } } /// Parse a function definition. fn parse_fn<'a>( input: &mut Peekable>, + stack: &mut Stack, allow_stmt_expr: bool, ) -> Result> { let pos = input.next().expect("should be fn").1; @@ -1672,7 +1805,13 @@ fn parse_fn<'a>( loop { match input.next().unwrap() { - (Token::Identifier(s), pos) => params.push((s, pos)), + (Token::Identifier(s), pos) => { + stack.push(s.clone()); + params.push((s, pos)) + } + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(pos)) + } (_, pos) => return Err(PERR::MissingToken(")".into(), end_err).into_err(pos)), } @@ -1682,6 +1821,9 @@ fn parse_fn<'a>( (Token::Identifier(_), pos) => { return Err(PERR::MissingToken(",".into(), sep_err).into_err(pos)) } + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(pos)) + } (_, pos) => return Err(PERR::MissingToken(",".into(), sep_err).into_err(pos)), } } @@ -1703,10 +1845,10 @@ fn parse_fn<'a>( })?; // Parse function body - let body = match input.peek().unwrap() { - (Token::LeftBrace, _) => parse_block(input, false, allow_stmt_expr)?, + let body = Box::new(match input.peek().unwrap() { + (Token::LeftBrace, _) => parse_block(input, stack, false, allow_stmt_expr)?, (_, pos) => return Err(PERR::FnMissingBody(name).into_err(*pos)), - }; + }); let params = params.into_iter().map(|(p, _)| p).collect(); @@ -1724,7 +1866,8 @@ pub fn parse_global_expr<'a>( scope: &Scope, optimization_level: OptimizationLevel, ) -> Result> { - let expr = parse_expr(input, false)?; + let mut stack = Stack::new(); + let expr = parse_expr(input, &mut stack, false)?; match input.peek().unwrap() { (Token::EOF, _) => (), @@ -1752,20 +1895,22 @@ fn parse_global_level<'a>( ) -> Result<(Vec, HashMap), Box> { let mut statements = Vec::::new(); let mut functions = HashMap::::new(); + let mut stack = Stack::new(); while !input.peek().unwrap().0.is_eof() { // Collect all the function definitions #[cfg(not(feature = "no_function"))] { - if matches!(input.peek().expect("should not be None"), (Token::Fn, _)) { - let f = parse_fn(input, true)?; + if let (Token::Fn, _) = input.peek().unwrap() { + let mut stack = Stack::new(); + let f = parse_fn(input, &mut stack, true)?; functions.insert(calc_fn_def(&f.name, f.params.len()), f); continue; } } // Actual statement - let stmt = parse_stmt(input, false, true)?; + let stmt = parse_stmt(input, &mut stack, false, true)?; let need_semicolon = !stmt.is_self_terminated(); @@ -1782,7 +1927,11 @@ fn parse_global_level<'a>( (Token::SemiColon, _) if !need_semicolon => (), // { stmt } ??? (_, _) if !need_semicolon => (), - // stmt ??? - error + // stmt + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(*pos)) + } + // stmt ??? (_, pos) => { // Semicolons are not optional between statements return Err( @@ -1820,7 +1969,7 @@ pub fn map_dynamic_to_expr(value: Dynamic, pos: Position) -> Option { Union::Unit(_) => Some(Expr::Unit(pos)), Union::Int(value) => Some(Expr::IntegerConstant(value, pos)), Union::Char(value) => Some(Expr::CharConstant(value, pos)), - Union::Str(value) => Some(Expr::StringConstant((*value).into(), pos)), + Union::Str(value) => Some(Expr::StringConstant((*value).clone(), pos)), Union::Bool(true) => Some(Expr::True(pos)), Union::Bool(false) => Some(Expr::False(pos)), #[cfg(not(feature = "no_index"))] diff --git a/src/result.rs b/src/result.rs index 21fe7ef8..17fe389a 100644 --- a/src/result.rs +++ b/src/result.rs @@ -6,6 +6,7 @@ use crate::parser::INT; use crate::token::Position; use crate::stdlib::{ + boxed::Box, error::Error, fmt, string::{String, ToString}, @@ -228,20 +229,23 @@ impl fmt::Display for EvalAltResult { } } -impl From for EvalAltResult { +impl From for Box { fn from(err: ParseError) -> Self { - Self::ErrorParsing(Box::new(err)) + Box::new(EvalAltResult::ErrorParsing(Box::new(err))) } } -impl From> for EvalAltResult { +impl From> for Box { fn from(err: Box) -> Self { - Self::ErrorParsing(err) + Box::new(EvalAltResult::ErrorParsing(err)) } } -impl> From for EvalAltResult { +impl> From for Box { fn from(err: T) -> Self { - Self::ErrorRuntime(err.as_ref().to_string(), Position::none()) + Box::new(EvalAltResult::ErrorRuntime( + err.as_ref().to_string(), + Position::none(), + )) } } @@ -280,8 +284,8 @@ impl EvalAltResult { /// Consume the current `EvalAltResult` and return a new one /// with the specified `Position`. - pub(crate) fn set_position(mut self, new_position: Position) -> Self { - match &mut self { + pub(crate) fn set_position(mut err: Box, new_position: Position) -> Box { + match err.as_mut() { #[cfg(not(feature = "no_std"))] Self::ErrorReadingScriptFile(_, _) => (), @@ -311,6 +315,6 @@ impl EvalAltResult { | Self::Return(_, pos) => *pos = new_position, } - self + err } } diff --git a/src/scope.rs b/src/scope.rs index a9fd579c..b50d1af3 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -4,7 +4,7 @@ use crate::any::{Dynamic, Variant}; use crate::parser::{map_dynamic_to_expr, Expr}; use crate::token::Position; -use crate::stdlib::{borrow::Cow, iter, vec::Vec}; +use crate::stdlib::{borrow::Cow, boxed::Box, iter, vec::Vec}; /// Type of an entry in the Scope. #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] @@ -25,15 +25,7 @@ pub struct Entry<'a> { /// Current value of the entry. pub value: Dynamic, /// A constant expression if the initial value matches one of the recognized types. - pub expr: Option, -} - -/// Information about a particular entry in the Scope. -#[derive(Debug, Hash, Copy, Clone)] -pub(crate) struct EntryRef<'a> { - pub name: &'a str, - pub index: usize, - pub typ: EntryType, + pub expr: Option>, } /// A type containing information about the current scope. @@ -42,7 +34,7 @@ pub(crate) struct EntryRef<'a> { /// # Example /// /// ``` -/// # fn main() -> Result<(), rhai::EvalAltResult> { +/// # fn main() -> Result<(), Box> { /// use rhai::{Engine, Scope}; /// /// let engine = Engine::new(); @@ -226,15 +218,17 @@ impl<'a> Scope<'a> { value: Dynamic, map_expr: bool, ) { + let expr = if map_expr { + map_dynamic_to_expr(value.clone(), Position::none()).map(Box::new) + } else { + None + }; + self.0.push(Entry { name: name.into(), typ: entry_type, - value: value.clone(), - expr: if map_expr { - map_dynamic_to_expr(value, Position::none()) - } else { - None - }, + value: value.into(), + expr, }); } @@ -289,35 +283,18 @@ impl<'a> Scope<'a> { } /// Find an entry in the Scope, starting from the last. - pub(crate) fn get(&self, name: &str) -> Option<(EntryRef, Dynamic)> { + pub(crate) fn get(&self, name: &str) -> Option<(usize, EntryType)> { self.0 .iter() .enumerate() .rev() // Always search a Scope in reverse order - .find_map( - |( - index, - Entry { - name: key, - typ, - value, - .. - }, - )| { - if name == key { - Some(( - EntryRef { - name: key, - index, - typ: *typ, - }, - value.clone(), - )) - } else { - None - } - }, - ) + .find_map(|(index, Entry { name: key, typ, .. })| { + if name == key { + Some((index, *typ)) + } else { + None + } + }) } /// Get the value of an entry in the Scope, starting from the last. @@ -363,42 +340,29 @@ impl<'a> Scope<'a> { /// ``` pub fn set_value(&mut self, name: &'a str, value: T) { match self.get(name) { - Some(( - EntryRef { - typ: EntryType::Constant, - .. - }, - _, - )) => panic!("variable {} is constant", name), - Some(( - EntryRef { - index, - typ: EntryType::Normal, - .. - }, - _, - )) => self.0.get_mut(index).unwrap().value = Dynamic::from(value), + Some((_, EntryType::Constant)) => panic!("variable {} is constant", name), + Some((index, EntryType::Normal)) => { + self.0.get_mut(index).unwrap().value = Dynamic::from(value) + } None => self.push(name, value), } } /// Get a mutable reference to an entry in the Scope. - pub(crate) fn get_mut(&mut self, key: EntryRef) -> &mut Dynamic { - let entry = self.0.get_mut(key.index).expect("invalid index in Scope"); - assert_eq!(entry.typ, key.typ, "entry type not matched"); + pub(crate) fn get_mut(&mut self, index: usize) -> (&mut Dynamic, EntryType) { + let entry = self.0.get_mut(index).expect("invalid index in Scope"); // assert_ne!( // entry.typ, // EntryType::Constant, // "get mut of constant entry" // ); - assert_eq!(entry.name, key.name, "incorrect key at Scope entry"); - &mut entry.value + (&mut entry.value, entry.typ) } /// Get an iterator to entries in the Scope. - pub fn iter(&self) -> impl Iterator { + pub(crate) fn iter(&self) -> impl Iterator { self.0.iter().rev() // Always search a Scope in reverse order } } @@ -409,16 +373,13 @@ impl Default for Scope<'_> { } } -impl<'a, K> iter::Extend<(K, EntryType, Dynamic)> for Scope<'a> -where - K: Into>, -{ +impl<'a, K: Into>> iter::Extend<(K, EntryType, Dynamic)> for Scope<'a> { fn extend>(&mut self, iter: T) { self.0 .extend(iter.into_iter().map(|(name, typ, value)| Entry { name: name.into(), typ, - value, + value: value.into(), expr: None, })); } diff --git a/src/token.rs b/src/token.rs index aa11a3c6..f202bccd 100644 --- a/src/token.rs +++ b/src/token.rs @@ -13,29 +13,28 @@ use crate::stdlib::{ iter::Peekable, str::{Chars, FromStr}, string::{String, ToString}, - usize, vec::Vec, }; type LERR = LexError; /// A location (line number + character position) in the input script. +/// +/// In order to keep footprint small, both line number and character position have 16-bit resolution, +/// meaning they go up to a maximum of 65,535 lines/characters per line. +/// Advancing beyond the maximum line length or maximum number of lines is not an error but has no effect. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] pub struct Position { /// Line number - 0 = none - line: usize, + line: u16, /// Character position - 0 = BOL - pos: usize, + pos: u16, } impl Position { /// Create a new `Position`. - pub fn new(line: usize, position: usize) -> Self { + pub fn new(line: u16, position: u16) -> Self { assert!(line != 0, "line cannot be zero"); - assert!( - line != usize::MAX || position != usize::MAX, - "invalid position" - ); Self { line, @@ -48,7 +47,7 @@ impl Position { if self.is_none() { None } else { - Some(self.line) + Some(self.line as usize) } } @@ -57,13 +56,18 @@ impl Position { if self.is_none() || self.pos == 0 { None } else { - Some(self.pos) + Some(self.pos as usize) } } /// Advance by one character position. pub(crate) fn advance(&mut self) { - self.pos += 1; + assert!(!self.is_none(), "cannot advance Position::none"); + + // Advance up to maximum position + if self.pos < u16::MAX { + self.pos += 1; + } } /// Go backwards by one character position. @@ -73,14 +77,20 @@ impl Position { /// Panics if already at beginning of a line - cannot rewind to a previous line. /// pub(crate) fn rewind(&mut self) { + assert!(!self.is_none(), "cannot rewind Position::none"); assert!(self.pos > 0, "cannot rewind at position 0"); self.pos -= 1; } /// Advance to the next line. pub(crate) fn new_line(&mut self) { - self.line += 1; - self.pos = 0; + assert!(!self.is_none(), "cannot advance Position::none"); + + // Advance up to maximum position + if self.line < u16::MAX { + self.line += 1; + self.pos = 0; + } } /// Create a `Position` representing no position. @@ -350,9 +360,10 @@ impl Token { use Token::*; match self { + // Assignments are not considered expressions - set to zero Equals | PlusAssign | MinusAssign | MultiplyAssign | DivideAssign | LeftShiftAssign | RightShiftAssign | AndAssign | OrAssign | XOrAssign | ModuloAssign - | PowerOfAssign => 10, + | PowerOfAssign => 0, Or | XOr | Pipe => 40, @@ -659,7 +670,7 @@ impl<'a> TokenIterator<'a> { .map(Token::IntegerConstant) .unwrap_or_else(|_| { Token::LexError(Box::new(LERR::MalformedNumber( - result.iter().collect(), + result.into_iter().collect(), ))) }), pos, @@ -675,7 +686,7 @@ impl<'a> TokenIterator<'a> { return Some(( num.unwrap_or_else(|_| { Token::LexError(Box::new(LERR::MalformedNumber( - result.iter().collect(), + result.into_iter().collect(), ))) }), pos, @@ -869,6 +880,18 @@ impl<'a> TokenIterator<'a> { ('=', '=') => { self.eat_next(); + + // Warn against `===` + if self.peek_next() == Some('=') { + return Some(( + Token::LexError(Box::new(LERR::ImproperKeyword( + "'===' is not a valid operator. This is not JavaScript! Should it be '=='?" + .to_string(), + ))), + pos, + )); + } + return Some((Token::EqualsTo, pos)); } ('=', _) => return Some((Token::Equals, pos)), @@ -913,6 +936,18 @@ impl<'a> TokenIterator<'a> { ('!', '=') => { self.eat_next(); + + // Warn against `!==` + if self.peek_next() == Some('=') { + return Some(( + Token::LexError(Box::new(LERR::ImproperKeyword( + "'!==' is not a valid operator. This is not JavaScript! Should it be '!='?" + .to_string(), + ))), + pos, + )); + } + return Some((Token::NotEqualsTo, pos)); } ('!', _) => return Some((Token::Bang, pos)), @@ -955,6 +990,8 @@ impl<'a> TokenIterator<'a> { } ('~', _) => return Some((Token::PowerOf, pos)), + ('\0', _) => panic!("should not be EOF"), + (ch, _) if ch.is_whitespace() => (), (ch, _) => return Some((Token::LexError(Box::new(LERR::UnexpectedChar(ch))), pos)), } diff --git a/tests/arrays.rs b/tests/arrays.rs index a41f0a63..ea710eba 100644 --- a/tests/arrays.rs +++ b/tests/arrays.rs @@ -2,7 +2,7 @@ use rhai::{Array, Engine, EvalAltResult, RegisterFn, INT}; #[test] -fn test_arrays() -> Result<(), EvalAltResult> { +fn test_arrays() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = [1, 2, 3]; x[1]")?, 2); @@ -13,6 +13,7 @@ fn test_arrays() -> Result<(), EvalAltResult> { ); assert!(engine.eval::("let y = [1, 2, 3]; 2 in y")?); + #[cfg(not(feature = "no_object"))] assert_eq!( engine.eval::( r" @@ -35,7 +36,7 @@ fn test_arrays() -> Result<(), EvalAltResult> { r" let x = [1, 2, 3]; x += [4, 5]; - x.len() + len(x) " )?, 5 @@ -58,7 +59,7 @@ fn test_arrays() -> Result<(), EvalAltResult> { #[test] #[cfg(not(feature = "no_object"))] -fn test_array_with_structs() -> Result<(), EvalAltResult> { +fn test_array_with_structs() -> Result<(), Box> { #[derive(Clone)] struct TestStruct { x: INT, diff --git a/tests/binary_ops.rs b/tests/binary_ops.rs index 922c6a43..7ede89fb 100644 --- a/tests/binary_ops.rs +++ b/tests/binary_ops.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_binary_ops() -> Result<(), EvalAltResult> { +fn test_binary_ops() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("10 % 4")?, 2); diff --git a/tests/bit_shift.rs b/tests/bit_shift.rs index e8e360f3..0b888e32 100644 --- a/tests/bit_shift.rs +++ b/tests/bit_shift.rs @@ -1,14 +1,14 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_left_shift() -> Result<(), EvalAltResult> { +fn test_left_shift() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("4 << 2")?, 16); Ok(()) } #[test] -fn test_right_shift() -> Result<(), EvalAltResult> { +fn test_right_shift() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("9 >> 1")?, 4); Ok(()) diff --git a/tests/bool_op.rs b/tests/bool_op.rs index 3bd5859a..913106e6 100644 --- a/tests/bool_op.rs +++ b/tests/bool_op.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult}; #[test] -fn test_bool_op1() -> Result<(), EvalAltResult> { +fn test_bool_op1() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("true && (false || true)")?, true); @@ -11,7 +11,7 @@ fn test_bool_op1() -> Result<(), EvalAltResult> { } #[test] -fn test_bool_op2() -> Result<(), EvalAltResult> { +fn test_bool_op2() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("false && (false || true)")?, false); @@ -21,7 +21,7 @@ fn test_bool_op2() -> Result<(), EvalAltResult> { } #[test] -fn test_bool_op3() -> Result<(), EvalAltResult> { +fn test_bool_op3() -> Result<(), Box> { let engine = Engine::new(); assert!(engine.eval::("true && (false || 123)").is_err()); @@ -33,7 +33,7 @@ fn test_bool_op3() -> Result<(), EvalAltResult> { } #[test] -fn test_bool_op_short_circuit() -> Result<(), EvalAltResult> { +fn test_bool_op_short_circuit() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/call_fn.rs b/tests/call_fn.rs index fc658a15..f3d2a689 100644 --- a/tests/call_fn.rs +++ b/tests/call_fn.rs @@ -2,7 +2,7 @@ use rhai::{Engine, EvalAltResult, Func, ParseErrorType, Scope, INT}; #[test] -fn test_fn() -> Result<(), EvalAltResult> { +fn test_fn() -> Result<(), Box> { let engine = Engine::new(); // Expect duplicated parameters error @@ -19,7 +19,7 @@ fn test_fn() -> Result<(), EvalAltResult> { } #[test] -fn test_call_fn() -> Result<(), EvalAltResult> { +fn test_call_fn() -> Result<(), Box> { let engine = Engine::new(); let mut scope = Scope::new(); @@ -61,7 +61,7 @@ fn test_call_fn() -> Result<(), EvalAltResult> { } #[test] -fn test_anonymous_fn() -> Result<(), EvalAltResult> { +fn test_anonymous_fn() -> Result<(), Box> { let calc_func = Func::<(INT, INT, INT), INT>::create_from_script( Engine::new(), "fn calc(x, y, z) { (x + y) * z }", diff --git a/tests/chars.rs b/tests/chars.rs index db13f840..6882633a 100644 --- a/tests/chars.rs +++ b/tests/chars.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult}; #[test] -fn test_chars() -> Result<(), EvalAltResult> { +fn test_chars() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("'y'")?, 'y'); diff --git a/tests/compound_equality.rs b/tests/compound_equality.rs index b516bb97..b09115a0 100644 --- a/tests/compound_equality.rs +++ b/tests/compound_equality.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_or_equals() -> Result<(), EvalAltResult> { +fn test_or_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 16; x |= 74; x")?, 90); @@ -12,7 +12,7 @@ fn test_or_equals() -> Result<(), EvalAltResult> { } #[test] -fn test_and_equals() -> Result<(), EvalAltResult> { +fn test_and_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 16; x &= 31; x")?, 16); @@ -24,42 +24,42 @@ fn test_and_equals() -> Result<(), EvalAltResult> { } #[test] -fn test_xor_equals() -> Result<(), EvalAltResult> { +fn test_xor_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 90; x ^= 12; x")?, 86); Ok(()) } #[test] -fn test_multiply_equals() -> Result<(), EvalAltResult> { +fn test_multiply_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 2; x *= 3; x")?, 6); Ok(()) } #[test] -fn test_divide_equals() -> Result<(), EvalAltResult> { +fn test_divide_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 6; x /= 2; x")?, 3); Ok(()) } #[test] -fn test_left_shift_equals() -> Result<(), EvalAltResult> { +fn test_left_shift_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 9; x >>=1; x")?, 4); Ok(()) } #[test] -fn test_right_shift_equals() -> Result<(), EvalAltResult> { +fn test_right_shift_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 4; x<<= 2; x")?, 16); Ok(()) } #[test] -fn test_modulo_equals() -> Result<(), EvalAltResult> { +fn test_modulo_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 10; x %= 4; x")?, 2); Ok(()) diff --git a/tests/constants.rs b/tests/constants.rs index 2dd62000..55752d28 100644 --- a/tests/constants.rs +++ b/tests/constants.rs @@ -1,21 +1,21 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_constant() -> Result<(), EvalAltResult> { +fn test_constant() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("const x = 123; x")?, 123); - assert!( - matches!(engine.eval::("const x = 123; x = 42;").expect_err("expects error"), - EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x") - ); + assert!(matches!( + *engine.eval::("const x = 123; x = 42;").expect_err("expects error"), + EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x" + )); #[cfg(not(feature = "no_index"))] - assert!( - matches!(engine.eval::("const x = [1, 2, 3, 4, 5]; x[2] = 42;").expect_err("expects error"), - EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x") - ); + assert!(matches!( + *engine.eval::("const x = [1, 2, 3, 4, 5]; x[2] = 42;").expect_err("expects error"), + EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x" + )); Ok(()) } diff --git a/tests/decrement.rs b/tests/decrement.rs index a8cb2634..ab1f9376 100644 --- a/tests/decrement.rs +++ b/tests/decrement.rs @@ -1,14 +1,15 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_decrement() -> Result<(), EvalAltResult> { +fn test_decrement() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 10; x -= 7; x")?, 3); - assert!(matches!(engine - .eval::(r#"let s = "test"; s -= "ing"; s"#) - .expect_err("expects error"), EvalAltResult::ErrorFunctionNotFound(err, _) if err == "- (string, string)")); + assert!(matches!( + *engine.eval::(r#"let s = "test"; s -= "ing"; s"#).expect_err("expects error"), + EvalAltResult::ErrorFunctionNotFound(err, _) if err == "- (string, string)" + )); Ok(()) } diff --git a/tests/eval.rs b/tests/eval.rs index bf6f750f..28618fc5 100644 --- a/tests/eval.rs +++ b/tests/eval.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, Scope, INT}; #[test] -fn test_eval() -> Result<(), EvalAltResult> { +fn test_eval() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -18,7 +18,7 @@ fn test_eval() -> Result<(), EvalAltResult> { #[test] #[cfg(not(feature = "no_function"))] -fn test_eval_function() -> Result<(), EvalAltResult> { +fn test_eval_function() -> Result<(), Box> { let engine = Engine::new(); let mut scope = Scope::new(); @@ -34,10 +34,10 @@ fn test_eval_function() -> Result<(), EvalAltResult> { script += "y += foo(y);"; script += "x + y"; - eval(script) + eval(script) + x + y "# )?, - 42 + 84 ); assert_eq!( @@ -54,14 +54,15 @@ fn test_eval_function() -> Result<(), EvalAltResult> { 32 ); - assert!(!scope.contains("z")); + assert!(scope.contains("script")); + assert_eq!(scope.len(), 3); Ok(()) } #[test] #[cfg(not(feature = "no_function"))] -fn test_eval_override() -> Result<(), EvalAltResult> { +fn test_eval_override() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/expressions.rs b/tests/expressions.rs index 2091fe4e..35a6b90c 100644 --- a/tests/expressions.rs +++ b/tests/expressions.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, Scope, INT}; #[test] -fn test_expressions() -> Result<(), EvalAltResult> { +fn test_expressions() -> Result<(), Box> { let engine = Engine::new(); let mut scope = Scope::new(); @@ -28,7 +28,7 @@ fn test_expressions() -> Result<(), EvalAltResult> { /// This example taken from https://github.com/jonathandturner/rhai/issues/115 #[test] #[cfg(not(feature = "no_object"))] -fn test_expressions_eval() -> Result<(), EvalAltResult> { +fn test_expressions_eval() -> Result<(), Box> { #[derive(Debug, Clone)] struct AGENT { pub gender: String, diff --git a/tests/float.rs b/tests/float.rs index 94ec7a03..8d70c7b3 100644 --- a/tests/float.rs +++ b/tests/float.rs @@ -4,7 +4,7 @@ use rhai::{Engine, EvalAltResult, RegisterFn, FLOAT}; const EPSILON: FLOAT = 0.000_000_000_1; #[test] -fn test_float() -> Result<(), EvalAltResult> { +fn test_float() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -22,7 +22,7 @@ fn test_float() -> Result<(), EvalAltResult> { #[test] #[cfg(not(feature = "no_object"))] -fn struct_with_float() -> Result<(), EvalAltResult> { +fn struct_with_float() -> Result<(), Box> { #[derive(Clone)] struct TestStruct { x: f64, diff --git a/tests/for.rs b/tests/for.rs index f36f3ae3..2512ec72 100644 --- a/tests/for.rs +++ b/tests/for.rs @@ -2,7 +2,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[cfg(not(feature = "no_index"))] #[test] -fn test_for_array() -> Result<(), EvalAltResult> { +fn test_for_array() -> Result<(), Box> { let engine = Engine::new(); let script = r" @@ -31,8 +31,9 @@ fn test_for_array() -> Result<(), EvalAltResult> { } #[cfg(not(feature = "no_object"))] +#[cfg(not(feature = "no_index"))] #[test] -fn test_for_object() -> Result<(), EvalAltResult> { +fn test_for_object() -> Result<(), Box> { let engine = Engine::new(); let script = r#" diff --git a/tests/get_set.rs b/tests/get_set.rs index 9f63a365..5859ea2e 100644 --- a/tests/get_set.rs +++ b/tests/get_set.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT}; #[test] -fn test_get_set() -> Result<(), EvalAltResult> { +fn test_get_set() -> Result<(), Box> { #[derive(Clone)] struct TestStruct { x: INT, @@ -36,7 +36,7 @@ fn test_get_set() -> Result<(), EvalAltResult> { } #[test] -fn test_big_get_set() -> Result<(), EvalAltResult> { +fn test_big_get_set() -> Result<(), Box> { #[derive(Clone)] struct TestChild { x: INT, diff --git a/tests/if_block.rs b/tests/if_block.rs index dcde8143..a5d5125a 100644 --- a/tests/if_block.rs +++ b/tests/if_block.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_if() -> Result<(), EvalAltResult> { +fn test_if() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("if true { 55 }")?, 55); @@ -29,7 +29,7 @@ fn test_if() -> Result<(), EvalAltResult> { } #[test] -fn test_if_expr() -> Result<(), EvalAltResult> { +fn test_if_expr() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/increment.rs b/tests/increment.rs index 4be9397a..f622ab21 100644 --- a/tests/increment.rs +++ b/tests/increment.rs @@ -1,10 +1,11 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_increment() -> Result<(), EvalAltResult> { +fn test_increment() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 1; x += 2; x")?, 3); + assert_eq!( engine.eval::("let s = \"test\"; s += \"ing\"; s")?, "testing" diff --git a/tests/internal_fn.rs b/tests/internal_fn.rs index cc99187a..764cf601 100644 --- a/tests/internal_fn.rs +++ b/tests/internal_fn.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_internal_fn() -> Result<(), EvalAltResult> { +fn test_internal_fn() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -16,7 +16,7 @@ fn test_internal_fn() -> Result<(), EvalAltResult> { } #[test] -fn test_big_internal_fn() -> Result<(), EvalAltResult> { +fn test_big_internal_fn() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -35,7 +35,7 @@ fn test_big_internal_fn() -> Result<(), EvalAltResult> { } #[test] -fn test_internal_fn_overloading() -> Result<(), EvalAltResult> { +fn test_internal_fn_overloading() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/looping.rs b/tests/looping.rs index c7aace27..a973c98f 100644 --- a/tests/looping.rs +++ b/tests/looping.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_loop() -> Result<(), EvalAltResult> { +fn test_loop() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/maps.rs b/tests/maps.rs index c1b91187..64c5a4c2 100644 --- a/tests/maps.rs +++ b/tests/maps.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, Map, Scope, INT}; #[test] -fn test_map_indexing() -> Result<(), EvalAltResult> { +fn test_map_indexing() -> Result<(), Box> { let engine = Engine::new(); #[cfg(not(feature = "no_index"))] @@ -81,7 +81,7 @@ fn test_map_indexing() -> Result<(), EvalAltResult> { } #[test] -fn test_map_assign() -> Result<(), EvalAltResult> { +fn test_map_assign() -> Result<(), Box> { let engine = Engine::new(); let x = engine.eval::(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?; @@ -112,7 +112,7 @@ fn test_map_assign() -> Result<(), EvalAltResult> { } #[test] -fn test_map_return() -> Result<(), EvalAltResult> { +fn test_map_return() -> Result<(), Box> { let engine = Engine::new(); let x = engine.eval::(r#"#{a: 1, b: true, "c$": "hello"}"#)?; @@ -143,7 +143,8 @@ fn test_map_return() -> Result<(), EvalAltResult> { } #[test] -fn test_map_for() -> Result<(), EvalAltResult> { +#[cfg(not(feature = "no_index"))] +fn test_map_for() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -170,7 +171,7 @@ fn test_map_for() -> Result<(), EvalAltResult> { #[test] /// Because a Rhai object map literal is almost the same as JSON, /// it is possible to convert from JSON into a Rhai object map. -fn test_map_json() -> Result<(), EvalAltResult> { +fn test_map_json() -> Result<(), Box> { let engine = Engine::new(); let json = r#"{"a":1, "b":true, "c":42, "$d e f!":"hello", "z":null}"#; diff --git a/tests/math.rs b/tests/math.rs index 500b35b8..4e4a5d4b 100644 --- a/tests/math.rs +++ b/tests/math.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_math() -> Result<(), EvalAltResult> { +fn test_math() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("1 + 2")?, 3); @@ -25,37 +25,37 @@ fn test_math() -> Result<(), EvalAltResult> { #[cfg(not(feature = "only_i32"))] { assert!(matches!( - engine + *engine .eval::("abs(-9223372036854775808)") .expect_err("expects negation overflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("9223372036854775807 + 1") .expect_err("expects overflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("-9223372036854775808 - 1") .expect_err("expects underflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("9223372036854775807 * 9223372036854775807") .expect_err("expects overflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("9223372036854775807 / 0") .expect_err("expects division by zero"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("9223372036854775807 % 0") .expect_err("expects division by zero"), EvalAltResult::ErrorArithmetic(_, _) @@ -65,31 +65,31 @@ fn test_math() -> Result<(), EvalAltResult> { #[cfg(feature = "only_i32")] { assert!(matches!( - engine + *engine .eval::("2147483647 + 1") .expect_err("expects overflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("-2147483648 - 1") .expect_err("expects underflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("2147483647 * 2147483647") .expect_err("expects overflow"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("2147483647 / 0") .expect_err("expects division by zero"), EvalAltResult::ErrorArithmetic(_, _) )); assert!(matches!( - engine + *engine .eval::("2147483647 % 0") .expect_err("expects division by zero"), EvalAltResult::ErrorArithmetic(_, _) diff --git a/tests/method_call.rs b/tests/method_call.rs index a4e19251..99d1d0bd 100644 --- a/tests/method_call.rs +++ b/tests/method_call.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT}; #[test] -fn test_method_call() -> Result<(), EvalAltResult> { +fn test_method_call() -> Result<(), Box> { #[derive(Debug, Clone, Eq, PartialEq)] struct TestStruct { x: INT, diff --git a/tests/mismatched_op.rs b/tests/mismatched_op.rs index e6e6e15d..b129f29b 100644 --- a/tests/mismatched_op.rs +++ b/tests/mismatched_op.rs @@ -4,10 +4,10 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT}; fn test_mismatched_op() { let engine = Engine::new(); - assert!( - matches!(engine.eval::(r#""hello, " + "world!""#).expect_err("expects error"), - EvalAltResult::ErrorMismatchOutputType(err, _) if err == "string") - ); + assert!(matches!( + *engine.eval::(r#""hello, " + "world!""#).expect_err("expects error"), + EvalAltResult::ErrorMismatchOutputType(err, _) if err == "string" + )); } #[test] @@ -33,12 +33,14 @@ fn test_mismatched_op_custom_type() { .expect_err("expects error"); #[cfg(feature = "only_i32")] - assert!( - matches!(r, EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i32, TestStruct)") - ); + assert!(matches!( + *r, + EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i32, TestStruct)" + )); #[cfg(not(feature = "only_i32"))] - assert!( - matches!(r, EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i64, TestStruct)") - ); + assert!(matches!( + *r, + EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i64, TestStruct)" + )); } diff --git a/tests/not.rs b/tests/not.rs index 4ce9cd3e..ffc1d21d 100644 --- a/tests/not.rs +++ b/tests/not.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult}; #[test] -fn test_not() -> Result<(), EvalAltResult> { +fn test_not() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/number_literals.rs b/tests/number_literals.rs index 3fe8c78f..699de19a 100644 --- a/tests/number_literals.rs +++ b/tests/number_literals.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_number_literal() -> Result<(), EvalAltResult> { +fn test_number_literal() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("65")?, 65); @@ -10,7 +10,7 @@ fn test_number_literal() -> Result<(), EvalAltResult> { } #[test] -fn test_hex_literal() -> Result<(), EvalAltResult> { +fn test_hex_literal() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 0xf; x")?, 15); @@ -20,7 +20,7 @@ fn test_hex_literal() -> Result<(), EvalAltResult> { } #[test] -fn test_octal_literal() -> Result<(), EvalAltResult> { +fn test_octal_literal() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 0o77; x")?, 63); @@ -30,7 +30,7 @@ fn test_octal_literal() -> Result<(), EvalAltResult> { } #[test] -fn test_binary_literal() -> Result<(), EvalAltResult> { +fn test_binary_literal() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 0b1111; x")?, 15); diff --git a/tests/ops.rs b/tests/ops.rs index c817d65d..e087a8d0 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_ops() -> Result<(), EvalAltResult> { +fn test_ops() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("60 + 5")?, 65); @@ -11,7 +11,7 @@ fn test_ops() -> Result<(), EvalAltResult> { } #[test] -fn test_op_precedence() -> Result<(), EvalAltResult> { +fn test_op_precedence() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/optimizer.rs b/tests/optimizer.rs index eb9f1d5c..49b15c25 100644 --- a/tests/optimizer.rs +++ b/tests/optimizer.rs @@ -3,8 +3,8 @@ use rhai::{Engine, EvalAltResult, OptimizationLevel, INT}; #[test] -fn test_optimizer() -> Result<(), EvalAltResult> { - fn run_test(engine: &mut Engine) -> Result<(), EvalAltResult> { +fn test_optimizer() -> Result<(), Box> { + fn run_test(engine: &mut Engine) -> Result<(), Box> { assert_eq!(engine.eval::(r"if true { 42 } else { 123 }")?, 42); assert_eq!( engine.eval::(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?, diff --git a/tests/power_of.rs b/tests/power_of.rs index 3762ff0f..a3b6fd43 100644 --- a/tests/power_of.rs +++ b/tests/power_of.rs @@ -7,7 +7,7 @@ use rhai::FLOAT; const EPSILON: FLOAT = 0.000_000_000_1; #[test] -fn test_power_of() -> Result<(), EvalAltResult> { +fn test_power_of() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("2 ~ 3")?, 8); @@ -28,7 +28,7 @@ fn test_power_of() -> Result<(), EvalAltResult> { } #[test] -fn test_power_of_equals() -> Result<(), EvalAltResult> { +fn test_power_of_equals() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = 2; x ~= 3; x")?, 8); diff --git a/tests/side_effects.rs b/tests/side_effects.rs index 259d1f63..fb364747 100644 --- a/tests/side_effects.rs +++ b/tests/side_effects.rs @@ -40,7 +40,7 @@ impl CommandWrapper { #[cfg(not(feature = "no_object"))] #[test] -fn test_side_effects_command() -> Result<(), EvalAltResult> { +fn test_side_effects_command() -> Result<(), Box> { let mut engine = Engine::new(); let mut scope = Scope::new(); @@ -80,7 +80,7 @@ fn test_side_effects_command() -> Result<(), EvalAltResult> { } #[test] -fn test_side_effects_print() -> Result<(), EvalAltResult> { +fn test_side_effects_print() -> Result<(), Box> { use std::sync::Arc; use std::sync::RwLock; diff --git a/tests/stack.rs b/tests/stack.rs index 8efc759e..503bcbde 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -2,7 +2,7 @@ use rhai::{Engine, EvalAltResult}; #[test] -fn test_stack_overflow() -> Result<(), EvalAltResult> { +fn test_stack_overflow() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -22,8 +22,10 @@ fn test_stack_overflow() -> Result<(), EvalAltResult> { ", ) { Ok(_) => panic!("should be stack overflow"), - Err(EvalAltResult::ErrorStackOverflow(_)) => (), - Err(_) => panic!("should be stack overflow"), + Err(err) => match *err { + EvalAltResult::ErrorStackOverflow(_) => (), + _ => panic!("should be stack overflow"), + }, } Ok(()) diff --git a/tests/string.rs b/tests/string.rs index 1ec77e2e..981d19eb 100644 --- a/tests/string.rs +++ b/tests/string.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_string() -> Result<(), EvalAltResult> { +fn test_string() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( @@ -37,7 +37,7 @@ fn test_string() -> Result<(), EvalAltResult> { #[cfg(not(feature = "no_stdlib"))] #[cfg(not(feature = "no_object"))] #[test] -fn test_string_substring() -> Result<(), EvalAltResult> { +fn test_string_substring() -> Result<(), Box> { let engine = Engine::new(); assert_eq!( diff --git a/tests/throw.rs b/tests/throw.rs index 6e55303c..5f5c58a0 100644 --- a/tests/throw.rs +++ b/tests/throw.rs @@ -5,10 +5,12 @@ fn test_throw() { let engine = Engine::new(); assert!(matches!( - engine.eval::<()>(r#"if true { throw "hello" }"#).expect_err("expects error"), - EvalAltResult::ErrorRuntime(s, _) if s == "hello")); + *engine.eval::<()>(r#"if true { throw "hello" }"#).expect_err("expects error"), + EvalAltResult::ErrorRuntime(s, _) if s == "hello" + )); assert!(matches!( - engine.eval::<()>(r#"throw"#).expect_err("expects error"), - EvalAltResult::ErrorRuntime(s, _) if s == "")); + *engine.eval::<()>(r#"throw"#).expect_err("expects error"), + EvalAltResult::ErrorRuntime(s, _) if s == "" + )); } diff --git a/tests/time.rs b/tests/time.rs index eddb652d..aa5239b1 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -7,7 +7,7 @@ use rhai::{Engine, EvalAltResult, INT}; use rhai::FLOAT; #[test] -fn test_timestamp() -> Result<(), EvalAltResult> { +fn test_timestamp() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("type_of(timestamp())")?, "timestamp"); diff --git a/tests/types.rs b/tests/types.rs index 658d8b3f..d5a5928e 100644 --- a/tests/types.rs +++ b/tests/types.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT}; #[test] -fn test_type_of() -> Result<(), EvalAltResult> { +fn test_type_of() -> Result<(), Box> { #[derive(Clone)] struct TestStruct { x: INT, diff --git a/tests/unary_after_binary.rs b/tests/unary_after_binary.rs index ba74c9f9..d2366be7 100644 --- a/tests/unary_after_binary.rs +++ b/tests/unary_after_binary.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] // TODO also add test case for unary after compound // Hah, turns out unary + has a good use after all! -fn test_unary_after_binary() -> Result<(), EvalAltResult> { +fn test_unary_after_binary() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("10 % +4")?, 2); diff --git a/tests/unary_minus.rs b/tests/unary_minus.rs index e1a359d7..87e2aa2b 100644 --- a/tests/unary_minus.rs +++ b/tests/unary_minus.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_unary_minus() -> Result<(), EvalAltResult> { +fn test_unary_minus() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = -5; x")?, -5); diff --git a/tests/unit.rs b/tests/unit.rs index 465c7b48..2777ae54 100644 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -1,21 +1,21 @@ use rhai::{Engine, EvalAltResult}; #[test] -fn test_unit() -> Result<(), EvalAltResult> { +fn test_unit() -> Result<(), Box> { let engine = Engine::new(); engine.eval::<()>("let x = (); x")?; Ok(()) } #[test] -fn test_unit_eq() -> Result<(), EvalAltResult> { +fn test_unit_eq() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(engine.eval::("let x = (); let y = (); x == y")?, true); Ok(()) } #[test] -fn test_unit_with_spaces() -> Result<(), EvalAltResult> { +fn test_unit_with_spaces() -> Result<(), Box> { let engine = Engine::new(); engine.eval::<()>("let x = ( ); x")?; Ok(()) diff --git a/tests/var_scope.rs b/tests/var_scope.rs index 8d5244c8..fde83a05 100644 --- a/tests/var_scope.rs +++ b/tests/var_scope.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, Scope, INT}; #[test] -fn test_var_scope() -> Result<(), EvalAltResult> { +fn test_var_scope() -> Result<(), Box> { let engine = Engine::new(); let mut scope = Scope::new(); @@ -20,7 +20,7 @@ fn test_var_scope() -> Result<(), EvalAltResult> { } #[test] -fn test_scope_eval() -> Result<(), EvalAltResult> { +fn test_scope_eval() -> Result<(), Box> { let engine = Engine::new(); // First create the state diff --git a/tests/while_loop.rs b/tests/while_loop.rs index 3a035039..8916cd7c 100644 --- a/tests/while_loop.rs +++ b/tests/while_loop.rs @@ -1,7 +1,7 @@ use rhai::{Engine, EvalAltResult, INT}; #[test] -fn test_while() -> Result<(), EvalAltResult> { +fn test_while() -> Result<(), Box> { let engine = Engine::new(); assert_eq!(