diff --git a/README.md b/README.md index cd95c92f..0b359294 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,11 @@ Rhai's current features set: * 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) +* Relatively little `unsafe` code (yes there are some for performance reasons) * [`no-std`](#optional-features) support -* Support for [function overloading](#function-overloading) -* Support for [operator overloading](#operator-overloading) -* Support for loading external [modules] +* [Function overloading](#function-overloading) +* [Operator overloading](#operator-overloading) +* [Modules] * 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/) @@ -126,7 +127,8 @@ Disable script-defined functions (`no_function`) only when the feature is not ne [`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. +Selectively include the necessary functionalities by loading specific [packages](#packages) to minimize the footprint. +Packages are sharable (even across threads via the [`sync`] feature), so they only have to be created once. Related ------- @@ -268,6 +270,7 @@ let ast = engine.compile_file("hello_world.rhai".into())?; ### Calling Rhai functions from Rust Rhai also allows working _backwards_ from the other direction - i.e. calling a Rhai-scripted function from Rust via `call_fn`. +Functions declared with `private` are hidden and cannot be called from Rust (see also [modules]). ```rust // Define functions in a script. @@ -287,6 +290,11 @@ let ast = engine.compile(true, fn hello() { 42 } + + // this one is private and cannot be called by 'call_fn' + private hidden() { + throw "you shouldn't see me!"; + } ")?; // A custom scope can also contain any variables/constants available to the functions @@ -300,11 +308,15 @@ let result: i64 = engine.call_fn(&mut scope, &ast, "hello", ( String::from("abc" // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // put arguments in a tuple -let result: i64 = engine.call_fn(&mut scope, &ast, "hello", (123_i64,) )? +let result: i64 = engine.call_fn(&mut scope, &ast, "hello", (123_i64,) )?; // ^^^^^^^^^^ tuple of one -let result: i64 = engine.call_fn(&mut scope, &ast, "hello", () )? +let result: i64 = engine.call_fn(&mut scope, &ast, "hello", () )?; // ^^ unit = tuple of zero + +// The following call will return a function-not-found error because +// 'hidden' is declared with 'private'. +let result: () = engine.call_fn(&mut scope, &ast, "hidden", ())?; ``` ### Creating Rust anonymous functions from Rhai script @@ -361,7 +373,7 @@ Use `Engine::new_raw` to create a _raw_ `Engine`, in which _nothing_ is added, n ### 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 reside under `rhai::packages::*` and the trait `rhai::packages::Package` must be loaded in order for packages to be used. ```rust @@ -372,7 +384,7 @@ use rhai::packages::CorePackage; // the 'core' package contains b 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 +engine.load_package(package.get()); // load the package manually. 'get' returns a reference to the shared package ``` The follow packages are available: @@ -391,6 +403,20 @@ The follow packages are available: | `CorePackage` | Basic essentials | | | | `StandardPackage` | Standard library | | | +Packages typically contain Rust functions that are callable within a Rhai script. +All functions registered in a package is loaded under the _global namespace_ (i.e. they're available without module qualifiers). +Once a package is created (e.g. via `new`), it can be _shared_ (via `get`) among multiple instances of [`Engine`], +even across threads (if the [`sync`] feature is turned on). +Therefore, a package only has to be created _once_. + +Packages are actually implemented as [modules], so they share a lot of behavior and characteristics. +The main difference is that a package loads under the _global_ namespace, while a module loads under its own +namespace alias specified in an `import` statement (see also [modules]). +A package is _static_ (i.e. pre-loaded into an [`Engine`]), while a module is _dynamic_ (i.e. loaded with +the `import` statement). + +Custom packages can also be created. See the macro [`def_package!`](https://docs.rs/rhai/0.13.0/rhai/macro.def_package.html). + Evaluate expressions only ------------------------- @@ -752,11 +778,17 @@ println!("result: {}", result); // prints 42 let result: f64 = engine.eval("1.0 + 0.0"); // '+' operator for two floats not overloaded println!("result: {}", result); // prints 1.0 + +fn mixed_add(a: i64, b: f64) -> f64 { (a as f64) + b } + +engine.register_fn("+", mixed_add); // register '+' operator for an integer and a float + +let result: i64 = engine.eval("1 + 1.0"); // prints 2.0 (normally an error) ``` -Use operator overloading for custom types (described below) only. Be very careful when overloading built-in operators because -script writers expect standard operators to behave in a consistent and predictable manner, and will be annoyed if a calculation -for '+' turns into a subtraction, for example. +Use operator overloading for custom types (described below) only. +Be very careful when overloading built-in operators because script writers expect standard operators to behave in a +consistent and predictable manner, and will be annoyed if a calculation for '`+`' turns into a subtraction, for example. Operator overloading also impacts script optimization when using [`OptimizationLevel::Full`]. See the [relevant section](#script-optimization) for more details. @@ -1318,7 +1350,7 @@ The following standard methods (defined in the [`MoreStringPackage`](#packages) | `index_of` | character/sub-string to search for, start index _(optional)_ | returns the index that a certain character or sub-string occurs in the string, or -1 if not found | | `sub_string` | start index, length _(optional)_ | extracts a sub-string (to the end of the string if length is not specified) | | `crop` | start index, length _(optional)_ | retains only a portion of the string (to the end of the string if length is not specified) | -| `replace` | target sub-string, replacement string | replaces a sub-string with another | +| `replace` | target character/sub-string, replacement character/string | replaces a sub-string with another | | `trim` | _none_ | trims the string of whitespace at the beginning and end | ### Examples @@ -2038,32 +2070,62 @@ for entry in logbook.read().unwrap().iter() { } ``` -Using external modules ----------------------- +Modules +------- -[module]: #using-external-modules -[modules]: #using-external-modules +[module]: #modules +[modules]: #modules -Rhai allows organizing code (functions and variables) into _modules_. A module is a single script file -with `export` statements that _exports_ certain global variables and functions as contents of the module. +Rhai allows organizing code (functions, both Rust-based or script-based, and variables) into _modules_. +Modules can be disabled via the [`no_module`] feature. -Everything exported as part of a module is constant and read-only. +### Exporting variables and functions from modules + +A _module_ is a single script (or pre-compiled `AST`) containing global variables and functions. +The `export` statement, which can only be at global level, exposes selected variables as members of a module. +Variables not exported are _private_ and invisible to the outside. +On the other hand, all functions are automatically exported, _unless_ it is explicitly opt-out with the `private` prefix. +Functions declared `private` are invisible to the outside. + +Everything exported from a module is **constant** (**read-only**). + +```rust +// This is a module script. + +fn inc(x) { x + 1 } // script-defined function - default public + +private fn foo() {} // private function - invisible to outside + +let private = 123; // variable not exported - default invisible to outside +let x = 42; // this will be exported below + +export x; // the variable 'x' is exported under its own name + +export x as answer; // the variable 'x' is exported under the alias 'answer' + // another script can load this module and access 'x' as 'module::answer' +``` ### Importing modules -A module can be _imported_ via the `import` statement, and its members accessed via '`::`' similar to C++. +A module can be _imported_ via the `import` statement, and its members are accessed via '`::`' similar to C++. ```rust import "crypto" as crypto; // import the script file 'crypto.rhai' as a module crypto::encrypt(secret); // use functions defined under the module via '::' +crypto::hash::sha256(key); // sub-modules are also supported + print(crypto::status); // module variables are constants -crypto::hash::sha256(key); // sub-modules are also supported +crypto::status = "off"; // <- runtime error - cannot modify a constant ``` `import` statements are _scoped_, meaning that they are only accessible inside the scope that they're imported. +They can appear anywhere a normal statement can be, but in the vast majority of cases `import` statements are +group at the beginning of a script. It is not advised to deviate from this common practice unless there is +a _Very Good Reason™_. Especially, do not place an `import` statement within a loop; doing so will repeatedly +re-load the same module during every iteration of the loop! ```rust let mod = "crypto"; @@ -2076,11 +2138,17 @@ if secured { // new block scope crypto::encrypt(others); // <- this causes a run-time error because the 'crypto' module // is no longer available! + +for x in range(0, 1000) { + import "crypto" as c; // <- importing a module inside a loop is a Very Bad Idea™ + + c.encrypt(something); +} ``` -### Creating custom modules from Rust +### Creating custom modules with Rust -To load a custom module into an [`Engine`], first create a `Module` type, add variables/functions into it, +To load a custom module (written in Rust) into an [`Engine`], first create a `Module` type, add variables/functions into it, then finally push it into a custom [`Scope`]. This has the equivalent effect of putting an `import` statement at the beginning of any script run. @@ -2105,6 +2173,56 @@ engine.eval_expression_with_scope::(&scope, "question::answer + 1")? == 42; engine.eval_expression_with_scope::(&scope, "question::inc(question::answer)")? == 42; ``` +### Creating a module from an `AST` + +It is easy to convert a pre-compiled `AST` into a module: just use `Module::eval_ast_as_new`. +Don't forget the `export` statement, otherwise there will be no variables exposed by the module +other than non-`private` functions (unless that's intentional). + +```rust +use rhai::{Engine, Module}; + +let engine = Engine::new(); + +// Compile a script into an 'AST' +let ast = engine.compile(r#" + // Functions become module functions + fn calc(x) { + x + 1 + } + fn add_len(x, y) { + x + y.len() + } + + // Imported modules can become sub-modules + import "another module" as extra; + + // Variables defined at global level can become module variables + const x = 123; + let foo = 41; + let hello; + + // Variable values become constant module variable values + foo = calc(foo); + hello = "hello, " + foo + " worlds!"; + + // Finally, export the variables and modules + export + x as abc, // aliased variable name + foo, + hello, + extra as foobar; // export sub-module +"#)?; + +// Convert the 'AST' into a module, using the 'Engine' to evaluate it first +let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?; + +// 'module' now can be loaded into a custom 'Scope' for future use. It contains: +// - sub-module: 'foobar' (renamed from 'extra') +// - functions: 'calc', 'add_len' +// - variables: 'abc' (renamed from 'x'), 'foo', 'hello' +``` + ### Module resolvers When encountering an `import` statement, Rhai attempts to _resolve_ the module based on the path string. @@ -2114,10 +2232,10 @@ which simply loads a script file based on the path (with `.rhai` extension attac Built-in module resolvers are grouped under the `rhai::module_resolvers` module namespace. -| Module Resolver | Description | -| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `FileModuleResolver` | The default module resolution service, not available under the [`no_std`] feature. Loads a script file (based off the current directory) with `.rhai` extension.
The base directory can be changed via the `FileModuleResolver::new_with_path()` constructor function. | -| `StaticModuleResolver` | Loads modules that are statically added. This can be used when the [`no_std`] feature is turned on. | +| Module Resolver | Description | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `FileModuleResolver` | The default module resolution service, not available under the [`no_std`] feature. Loads a script file (based off the current directory) with `.rhai` extension.
The base directory can be changed via the `FileModuleResolver::new_with_path()` constructor function.
`FileModuleResolver::create_module()` loads a script file and returns a module. | +| `StaticModuleResolver` | Loads modules that are statically added. This can be used when the [`no_std`] feature is turned on. | An [`Engine`]'s module resolver is set via a call to `set_module_resolver`: diff --git a/examples/hello.rs b/examples/hello.rs index edec8cb8..af5e8b9c 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,5 +1,4 @@ use rhai::{packages::*, Engine, EvalAltResult, INT}; -use std::rc::Rc; fn main() -> Result<(), Box> { let mut engine = Engine::new_raw(); diff --git a/examples/repl.rs b/examples/repl.rs index a8763e28..f980a98e 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -1,12 +1,9 @@ -use rhai::{Dynamic, Engine, EvalAltResult, Scope, AST, INT}; +use rhai::{Dynamic, Engine, EvalAltResult, Scope, AST}; #[cfg(not(feature = "no_optimize"))] use rhai::OptimizationLevel; -use std::{ - io::{stdin, stdout, Write}, - iter, -}; +use std::io::{stdin, stdout, Write}; fn print_error(input: &str, err: EvalAltResult) { let lines: Vec<_> = input.trim().split('\n').collect(); diff --git a/examples/rhai_runner.rs b/examples/rhai_runner.rs index 2bc273e2..c5c5128d 100644 --- a/examples/rhai_runner.rs +++ b/examples/rhai_runner.rs @@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult}; #[cfg(not(feature = "no_optimize"))] use rhai::OptimizationLevel; -use std::{env, fs::File, io::Read, iter, process::exit}; +use std::{env, fs::File, io::Read, process::exit}; fn eprint_error(input: &str, err: EvalAltResult) { fn eprint_line(lines: &[&str], line: usize, pos: usize, err: &str) { diff --git a/scripts/fibonacci.rhai b/scripts/fibonacci.rhai index a9a54c3a..730dadae 100644 --- a/scripts/fibonacci.rhai +++ b/scripts/fibonacci.rhai @@ -3,8 +3,6 @@ const target = 30; -let now = timestamp(); - fn fib(n) { if n < 2 { n @@ -15,8 +13,14 @@ fn fib(n) { print("Ready... Go!"); +let now = timestamp(); + let result = fib(target); +print("Finished. Run time = " + now.elapsed() + " seconds."); + print("Fibonacci number #" + target + " = " + result); -print("Finished. Run time = " + now.elapsed() + " seconds."); +if result != 832_040 { + print("The answer is WRONG! Should be 832,040!"); +} \ No newline at end of file diff --git a/scripts/primes.rhai b/scripts/primes.rhai index 668fa250..2b67ec50 100644 --- a/scripts/primes.rhai +++ b/scripts/primes.rhai @@ -27,3 +27,7 @@ for p in range(2, MAX_NUMBER_TO_CHECK) { print("Total " + total_primes_found + " primes <= " + MAX_NUMBER_TO_CHECK); print("Run time = " + now.elapsed() + " seconds."); + +if total_primes_found != 9_592 { + print("The answer is WRONG! Should be 9,592!"); +} \ No newline at end of file diff --git a/src/any.rs b/src/any.rs index 16bb8ae7..483eee84 100644 --- a/src/any.rs +++ b/src/any.rs @@ -1,10 +1,11 @@ //! Helper module which defines the `Any` trait to to allow dynamic value handling. +use crate::parser::INT; +use crate::r#unsafe::{unsafe_cast_box, unsafe_try_cast}; + #[cfg(not(feature = "no_module"))] use crate::module::Module; -use crate::parser::INT; - #[cfg(not(feature = "no_float"))] use crate::parser::FLOAT; @@ -18,7 +19,7 @@ use crate::stdlib::{ any::{type_name, Any, TypeId}, boxed::Box, collections::HashMap, - fmt, + fmt, mem, ptr, string::String, vec::Vec, }; @@ -38,6 +39,9 @@ pub trait Variant: Any { /// Convert this `Variant` trait object to `&mut dyn Any`. fn as_mut_any(&mut self) -> &mut dyn Any; + /// Convert this `Variant` trait object to an `Any` trait object. + fn as_box_any(self: Box) -> Box; + /// Get the name of this type. fn type_name(&self) -> &'static str; @@ -60,6 +64,9 @@ impl Variant for T { fn as_mut_any(&mut self) -> &mut dyn Any { self as &mut dyn Any } + fn as_box_any(self: Box) -> Box { + self as Box + } fn type_name(&self) -> &'static str { type_name::() } @@ -86,6 +93,9 @@ pub trait Variant: Any + Send + Sync { /// Convert this `Variant` trait object to `&mut dyn Any`. fn as_mut_any(&mut self) -> &mut dyn Any; + /// Convert this `Variant` trait object to an `Any` trait object. + fn as_box_any(self: Box) -> Box; + /// Get the name of this type. fn type_name(&self) -> &'static str; @@ -108,6 +118,9 @@ impl Variant for T { fn as_mut_any(&mut self) -> &mut dyn Any { self as &mut dyn Any } + fn as_box_any(self: Box) -> Box { + self as Box + } fn type_name(&self) -> &'static str { type_name::() } @@ -133,6 +146,8 @@ impl dyn Variant { pub struct Dynamic(pub(crate) Union); /// Internal `Dynamic` representation. +/// +/// Most variants are boxed to reduce the size. pub enum Union { Unit(()), Bool(bool), @@ -284,24 +299,15 @@ impl Default for Dynamic { } } -/// Cast a Boxed type into another type. -fn cast_box(item: Box) -> Result, Box> { - // Only allow casting to the exact same type - if TypeId::of::() == TypeId::of::() { - // SAFETY: just checked whether we are pointing to the correct type - unsafe { - let raw: *mut dyn Any = Box::into_raw(item as Box); - Ok(Box::from_raw(raw as *mut T)) - } - } else { - // Return the consumed item for chaining. - Err(item) - } -} - impl Dynamic { /// Create a `Dynamic` from any type. A `Dynamic` value is simply returned as is. /// + /// # Safety + /// + /// This type uses some unsafe code, mainly for type casting. + /// + /// # Notes + /// /// Beware that you need to pass in an `Array` type for it to be recognized as an `Array`. /// A `Vec` does not get automatically converted to an `Array`, but will be a generic /// restricted trait object instead, because `Vec` is not a supported standard type. @@ -347,17 +353,17 @@ impl Dynamic { let mut var = Box::new(value); - var = match cast_box::<_, Dynamic>(var) { + var = match unsafe_cast_box::<_, Dynamic>(var) { Ok(d) => return *d, Err(var) => var, }; - var = match cast_box::<_, String>(var) { + var = match unsafe_cast_box::<_, String>(var) { Ok(s) => return Self(Union::Str(s)), Err(var) => var, }; #[cfg(not(feature = "no_index"))] { - var = match cast_box::<_, Array>(var) { + var = match unsafe_cast_box::<_, Array>(var) { Ok(array) => return Self(Union::Array(array)), Err(var) => var, }; @@ -365,7 +371,7 @@ impl Dynamic { #[cfg(not(feature = "no_object"))] { - var = match cast_box::<_, Map>(var) { + var = match unsafe_cast_box::<_, Map>(var) { Ok(map) => return Self(Union::Map(map)), Err(var) => var, } @@ -388,26 +394,26 @@ impl Dynamic { /// /// assert_eq!(x.try_cast::().unwrap(), 42); /// ``` - pub fn try_cast(self) -> Option { + pub fn try_cast(self) -> Option { if TypeId::of::() == TypeId::of::() { - return cast_box::<_, T>(Box::new(self)).ok().map(|v| *v); + return unsafe_cast_box::<_, T>(Box::new(self)).ok().map(|v| *v); } match self.0 { - Union::Unit(ref value) => (value as &dyn Any).downcast_ref::().cloned(), - Union::Bool(ref value) => (value as &dyn Any).downcast_ref::().cloned(), - Union::Str(value) => cast_box::<_, T>(value).ok().map(|v| *v), - Union::Char(ref value) => (value as &dyn Any).downcast_ref::().cloned(), - Union::Int(ref value) => (value as &dyn Any).downcast_ref::().cloned(), + Union::Unit(value) => unsafe_try_cast(value), + Union::Bool(value) => unsafe_try_cast(value), + Union::Str(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v), + Union::Char(value) => unsafe_try_cast(value), + Union::Int(value) => unsafe_try_cast(value), #[cfg(not(feature = "no_float"))] - Union::Float(ref value) => (value as &dyn Any).downcast_ref::().cloned(), + Union::Float(value) => unsafe_try_cast(value), #[cfg(not(feature = "no_index"))] - Union::Array(value) => cast_box::<_, T>(value).ok().map(|v| *v), + Union::Array(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v), #[cfg(not(feature = "no_object"))] - Union::Map(value) => cast_box::<_, T>(value).ok().map(|v| *v), + Union::Map(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v), #[cfg(not(feature = "no_module"))] - Union::Module(value) => cast_box::<_, T>(value).ok().map(|v| *v), - Union::Variant(value) => value.as_any().downcast_ref::().cloned(), + Union::Module(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v), + Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).ok(), } } @@ -431,24 +437,24 @@ impl Dynamic { //self.try_cast::().unwrap() if TypeId::of::() == TypeId::of::() { - return *cast_box::<_, T>(Box::new(self)).unwrap(); + return *unsafe_cast_box::<_, T>(Box::new(self)).unwrap(); } match self.0 { - Union::Unit(ref value) => (value as &dyn Any).downcast_ref::().unwrap().clone(), - Union::Bool(ref value) => (value as &dyn Any).downcast_ref::().unwrap().clone(), - Union::Str(value) => *cast_box::<_, T>(value).unwrap(), - Union::Char(ref value) => (value as &dyn Any).downcast_ref::().unwrap().clone(), - Union::Int(ref value) => (value as &dyn Any).downcast_ref::().unwrap().clone(), + Union::Unit(value) => unsafe_try_cast(value).unwrap(), + Union::Bool(value) => unsafe_try_cast(value).unwrap(), + Union::Str(value) => *unsafe_cast_box::<_, T>(value).unwrap(), + Union::Char(value) => unsafe_try_cast(value).unwrap(), + Union::Int(value) => unsafe_try_cast(value).unwrap(), #[cfg(not(feature = "no_float"))] - Union::Float(ref value) => (value as &dyn Any).downcast_ref::().unwrap().clone(), + Union::Float(value) => unsafe_try_cast(value).unwrap(), #[cfg(not(feature = "no_index"))] - Union::Array(value) => *cast_box::<_, T>(value).unwrap(), + Union::Array(value) => *unsafe_cast_box::<_, T>(value).unwrap(), #[cfg(not(feature = "no_object"))] - Union::Map(value) => *cast_box::<_, T>(value).unwrap(), + Union::Map(value) => *unsafe_cast_box::<_, T>(value).unwrap(), #[cfg(not(feature = "no_module"))] - Union::Module(value) => *cast_box::<_, T>(value).unwrap(), - Union::Variant(value) => value.as_any().downcast_ref::().unwrap().clone(), + Union::Module(value) => *unsafe_cast_box::<_, T>(value).unwrap(), + Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).unwrap(), } } diff --git a/src/api.rs b/src/api.rs index d0193549..24b28474 100644 --- a/src/api.rs +++ b/src/api.rs @@ -4,12 +4,16 @@ use crate::any::{Dynamic, Variant}; use crate::engine::{make_getter, make_setter, Engine, State, FUNC_INDEXER}; use crate::error::ParseError; use crate::fn_call::FuncArgs; +use crate::fn_native::{ + IteratorCallback, ObjectGetCallback, ObjectIndexerCallback, ObjectSetCallback, +}; use crate::fn_register::RegisterFn; use crate::optimize::{optimize_into_ast, OptimizationLevel}; use crate::parser::{parse, parse_global_expr, AST}; use crate::result::EvalAltResult; use crate::scope::Scope; use crate::token::{lex, Position}; +use crate::utils::StaticVec; #[cfg(not(feature = "no_object"))] use crate::engine::Map; @@ -20,58 +24,11 @@ use crate::stdlib::{ collections::HashMap, mem, string::{String, ToString}, - vec::Vec, }; + #[cfg(not(feature = "no_std"))] use crate::stdlib::{fs::File, io::prelude::*, path::PathBuf}; -// Define callback function types -#[cfg(feature = "sync")] -pub trait ObjectGetCallback: Fn(&mut T) -> U + Send + Sync + 'static {} -#[cfg(feature = "sync")] -impl U + Send + Sync + 'static, T, U> ObjectGetCallback for F {} - -#[cfg(not(feature = "sync"))] -pub trait ObjectGetCallback: Fn(&mut T) -> U + 'static {} -#[cfg(not(feature = "sync"))] -impl U + 'static, T, U> ObjectGetCallback for F {} - -#[cfg(feature = "sync")] -pub trait ObjectSetCallback: Fn(&mut T, U) + Send + Sync + 'static {} -#[cfg(feature = "sync")] -impl ObjectSetCallback for F {} - -#[cfg(not(feature = "sync"))] -pub trait ObjectSetCallback: Fn(&mut T, U) + 'static {} -#[cfg(not(feature = "sync"))] -impl ObjectSetCallback for F {} - -#[cfg(feature = "sync")] -pub trait ObjectIndexerCallback: Fn(&mut T, X) -> U + Send + Sync + 'static {} -#[cfg(feature = "sync")] -impl U + Send + Sync + 'static, T, X, U> ObjectIndexerCallback for F {} - -#[cfg(not(feature = "sync"))] -pub trait ObjectIndexerCallback: Fn(&mut T, X) -> U + 'static {} -#[cfg(not(feature = "sync"))] -impl U + 'static, T, X, U> ObjectIndexerCallback for F {} - -#[cfg(feature = "sync")] -pub trait IteratorCallback: - Fn(Dynamic) -> Box> + Send + Sync + 'static -{ -} -#[cfg(feature = "sync")] -impl Box> + Send + Sync + 'static> IteratorCallback - for F -{ -} - -#[cfg(not(feature = "sync"))] -pub trait IteratorCallback: Fn(Dynamic) -> Box> + 'static {} -#[cfg(not(feature = "sync"))] -impl Box> + 'static> IteratorCallback for F {} - /// Engine public API impl Engine { /// Register a custom type for use with the `Engine`. @@ -168,7 +125,7 @@ impl Engine { /// Register an iterator adapter for a type with the `Engine`. /// This is an advanced feature. pub fn register_iterator(&mut self, f: F) { - self.type_iterators.insert(TypeId::of::(), Box::new(f)); + self.global_module.set_iter(TypeId::of::(), Box::new(f)); } /// Register a getter function for a member of a registered type with the `Engine`. @@ -385,6 +342,7 @@ impl Engine { } /// Compile a string into an `AST` using own scope, which can be used later for evaluation. + /// /// The scope is useful for passing constants into the script for optimization /// when using `OptimizationLevel::Full`. /// @@ -422,18 +380,71 @@ impl Engine { /// # } /// ``` pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result> { - self.compile_with_scope_and_optimization_level(scope, script, self.optimization_level) + self.compile_scripts_with_scope(scope, &[script]) } - /// Compile a string into an `AST` using own scope at a specific optimization level. + /// When passed a list of strings, first join the strings into one large script, + /// and then compile them into an `AST` using own scope, which can be used later for evaluation. + /// + /// The scope is useful for passing constants into the script for optimization + /// when using `OptimizationLevel::Full`. + /// + /// ## Note + /// + /// All strings are simply parsed one after another with nothing inserted in between, not even + /// a newline or space. + /// + /// # Example + /// + /// ``` + /// # fn main() -> Result<(), Box> { + /// # #[cfg(not(feature = "no_optimize"))] + /// # { + /// use rhai::{Engine, Scope, OptimizationLevel}; + /// + /// let mut engine = Engine::new(); + /// + /// // Set optimization level to 'Full' so the Engine can fold constants + /// // into function calls and operators. + /// engine.set_optimization_level(OptimizationLevel::Full); + /// + /// // Create initialized scope + /// let mut scope = Scope::new(); + /// scope.push_constant("x", 42_i64); // 'x' is a constant + /// + /// // Compile a script made up of script segments to an AST and store it for later evaluation. + /// // Notice that `Full` optimization is on, so constants are folded + /// // into function calls and operators. + /// let ast = engine.compile_scripts_with_scope(&mut scope, &[ + /// "if x > 40", // all 'x' are replaced with 42 + /// "{ x } el", + /// "se { 0 }" // segments do not need to be valid scripts! + /// ])?; + /// + /// // Normally this would have failed because no scope is passed into the 'eval_ast' + /// // call and so the variable 'x' does not exist. Here, it passes because the script + /// // has been optimized and all references to 'x' are already gone. + /// assert_eq!(engine.eval_ast::(&ast)?, 42); + /// # } + /// # Ok(()) + /// # } + /// ``` + pub fn compile_scripts_with_scope( + &self, + scope: &Scope, + scripts: &[&str], + ) -> Result> { + self.compile_with_scope_and_optimization_level(scope, scripts, self.optimization_level) + } + + /// Join a list of strings and compile into an `AST` using own scope at a specific optimization level. pub(crate) fn compile_with_scope_and_optimization_level( &self, scope: &Scope, - script: &str, + scripts: &[&str], optimization_level: OptimizationLevel, ) -> Result> { - let scripts = [script]; - let stream = lex(&scripts); + let stream = lex(scripts); parse(&mut stream.peekable(), self, scope, optimization_level) } @@ -487,6 +498,7 @@ impl Engine { } /// Compile a script file into an `AST` using own scope, which can be used later for evaluation. + /// /// The scope is useful for passing constants into the script for optimization /// when using `OptimizationLevel::Full`. /// @@ -738,8 +750,11 @@ impl Engine { script: &str, ) -> 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)?; + let ast = self.compile_with_scope_and_optimization_level( + scope, + &[script], + OptimizationLevel::None, + )?; self.eval_ast_with_scope(scope, &ast) } @@ -856,7 +871,7 @@ impl Engine { return result.try_cast::().ok_or_else(|| { Box::new(EvalAltResult::ErrorMismatchOutputType( - return_type.to_string(), + return_type.into(), Position::none(), )) }); @@ -867,12 +882,12 @@ impl Engine { scope: &mut Scope, ast: &AST, ) -> Result> { - let mut state = State::new(); + let mut state = State::new(ast.fn_lib()); ast.statements() .iter() .try_fold(().into(), |_, stmt| { - self.eval_stmt(scope, &mut state, ast.fn_lib(), stmt, 0) + self.eval_stmt(scope, &mut state, stmt, 0) }) .or_else(|err| match *err { EvalAltResult::Return(out, _) => Ok(out), @@ -932,12 +947,12 @@ impl Engine { scope: &mut Scope, ast: &AST, ) -> Result<(), Box> { - let mut state = State::new(); + let mut state = State::new(ast.fn_lib()); ast.statements() .iter() .try_fold(().into(), |_, stmt| { - self.eval_stmt(scope, &mut state, ast.fn_lib(), stmt, 0) + self.eval_stmt(scope, &mut state, stmt, 0) }) .map_or_else( |err| match *err { @@ -992,15 +1007,18 @@ impl Engine { args: A, ) -> Result> { let mut arg_values = args.into_vec(); - let mut args: Vec<_> = arg_values.iter_mut().collect(); + let mut args: StaticVec<_> = arg_values.iter_mut().collect(); let fn_lib = ast.fn_lib(); let pos = Position::none(); let fn_def = fn_lib - .get_function(name, args.len()) - .ok_or_else(|| Box::new(EvalAltResult::ErrorFunctionNotFound(name.to_string(), pos)))?; + .get_function_by_signature(name, args.len(), true) + .ok_or_else(|| Box::new(EvalAltResult::ErrorFunctionNotFound(name.into(), pos)))?; - let result = self.call_fn_from_lib(Some(scope), fn_lib, fn_def, &mut args, pos, 0)?; + let state = State::new(fn_lib); + + let result = + self.call_script_fn(Some(scope), &state, name, fn_def, args.as_mut(), pos, 0)?; let return_type = self.map_type_name(result.type_name()); diff --git a/src/engine.rs b/src/engine.rs index 1375e73a..7ef00d45 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -3,23 +3,30 @@ use crate::any::{Dynamic, Union}; use crate::calc_fn_hash; use crate::error::ParseErrorType; +use crate::fn_native::{FnCallArgs, NativeFunctionABI, PrintCallback}; +use crate::module::Module; use crate::optimize::OptimizationLevel; -use crate::packages::{CorePackage, Package, PackageLibrary, StandardPackage}; -use crate::parser::{Expr, FnDef, ModuleRef, ReturnType, Stmt, AST}; +use crate::packages::{CorePackage, Package, PackageLibrary, PackagesCollection, StandardPackage}; +use crate::parser::{Expr, FnAccess, FnDef, ReturnType, SharedFnDef, Stmt, AST}; +use crate::r#unsafe::unsafe_cast_var_name; use crate::result::EvalAltResult; use crate::scope::{EntryType as ScopeEntryType, Scope}; use crate::token::Position; -use crate::utils::{calc_fn_def, StaticVec}; +use crate::utils::{StaticVec, EMPTY_TYPE_ID}; #[cfg(not(feature = "no_module"))] -use crate::module::{resolvers, Module, ModuleResolver}; +use crate::module::{resolvers, ModuleRef, ModuleResolver}; + +#[cfg(feature = "no_module")] +use crate::parser::ModuleRef; use crate::stdlib::{ any::TypeId, + borrow::Cow, boxed::Box, collections::HashMap, format, - iter::once, + iter::{empty, once, repeat}, mem, num::NonZeroUsize, ops::{Deref, DerefMut}, @@ -41,32 +48,12 @@ pub type Array = Vec; #[cfg(not(feature = "no_object"))] pub type Map = HashMap; -pub type FnCallArgs<'a> = [&'a mut Dynamic]; - -#[cfg(feature = "sync")] -pub type FnAny = - dyn Fn(&mut FnCallArgs, Position) -> Result> + Send + Sync; -#[cfg(not(feature = "sync"))] -pub type FnAny = dyn Fn(&mut FnCallArgs, Position) -> Result>; - -#[cfg(feature = "sync")] -pub type IteratorFn = dyn Fn(Dynamic) -> Box> + Send + Sync; -#[cfg(not(feature = "sync"))] -pub type IteratorFn = dyn Fn(Dynamic) -> Box>; - #[cfg(debug_assertions)] 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"; @@ -111,12 +98,12 @@ impl Target<'_> { .as_char() .map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?; - let mut chars: Vec = s.chars().collect(); - let ch = chars[x.1]; + let mut chars: StaticVec = s.chars().collect(); + let ch = *chars.get_ref(x.1); // See if changed - if so, update the String if ch != new_ch { - chars[x.1] = new_ch; + *chars.get_mut(x.1) = new_ch; s.clear(); chars.iter().for_each(|&ch| s.push(ch)); } @@ -141,21 +128,43 @@ impl> From for Target<'_> { } /// A type that holds all the current states of the Engine. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct State { +/// +/// # Safety +/// +/// This type uses some unsafe code, mainly for avoiding cloning of local variable names via +/// direct lifetime casting. +#[derive(Debug, Clone, Copy)] +pub struct State<'a> { + /// Global script-defined functions. + pub fn_lib: &'a FunctionsLib, + /// 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, + + /// Level of the current scope. The global (root) level is zero, a new block (or function call) + /// is one level higher, and so on. + pub scope_level: usize, } -impl State { +impl<'a> State<'a> { /// Create a new `State`. - pub fn new() -> Self { + pub fn new(fn_lib: &'a FunctionsLib) -> Self { Self { always_search: false, + fn_lib, + scope_level: 0, } } + /// Does a certain script-defined function exist in the `State`? + pub fn has_function(&self, hash: u64) -> bool { + self.fn_lib.contains_key(&hash) + } + /// Get a script-defined function definition from the `State`. + pub fn get_function(&self, hash: u64) -> Option<&FnDef> { + self.fn_lib.get(&hash).map(|f| f.as_ref()) + } } /// A type that holds a library (`HashMap`) of script-defined functions. @@ -163,44 +172,62 @@ impl State { /// Since script-defined functions have `Dynamic` parameters, functions with the same name /// and number of parameters are considered equivalent. /// -/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_def`. +/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_hash` +/// with dummy parameter types `EMPTY_TYPE_ID()` repeated the correct number of times. #[derive(Debug, Clone, Default)] -pub struct FunctionsLib( - #[cfg(feature = "sync")] HashMap>, - #[cfg(not(feature = "sync"))] HashMap>, -); +pub struct FunctionsLib(HashMap); impl FunctionsLib { - /// Create a new `FunctionsLib`. - pub fn new() -> Self { - Default::default() - } /// Create a new `FunctionsLib` from a collection of `FnDef`. - pub fn from_vec(vec: Vec) -> Self { + pub fn from_iter(vec: impl IntoIterator) -> Self { FunctionsLib( vec.into_iter() - .map(|f| { - let hash = calc_fn_def(&f.name, f.params.len()); + .map(|fn_def| { + // Qualifiers (none) + function name + placeholders (one for each parameter). + let args_iter = repeat(EMPTY_TYPE_ID()).take(fn_def.params.len()); + let hash = calc_fn_hash(empty(), &fn_def.name, args_iter); #[cfg(feature = "sync")] { - (hash, Arc::new(f)) + (hash, Arc::new(fn_def)) } #[cfg(not(feature = "sync"))] { - (hash, Rc::new(f)) + (hash, Rc::new(fn_def)) } }) .collect(), ) } /// Does a certain function exist in the `FunctionsLib`? - pub fn has_function(&self, name: &str, params: usize) -> bool { - self.contains_key(&calc_fn_def(name, params)) + /// + /// The `u64` hash is calculated by the function `crate::calc_fn_hash`. + pub fn has_function(&self, hash_fn_def: u64) -> bool { + self.contains_key(&hash_fn_def) } /// Get a function definition from the `FunctionsLib`. - pub fn get_function(&self, name: &str, params: usize) -> Option<&FnDef> { - self.get(&calc_fn_def(name, params)).map(|f| f.as_ref()) + /// + /// The `u64` hash is calculated by the function `crate::calc_fn_hash`. + pub fn get_function(&self, hash_fn_def: u64) -> Option<&FnDef> { + self.get(&hash_fn_def).map(|fn_def| fn_def.as_ref()) + } + /// Get a function definition from the `FunctionsLib`. + pub fn get_function_by_signature( + &self, + name: &str, + params: usize, + public_only: bool, + ) -> Option<&FnDef> { + // Qualifiers (none) + function name + placeholders (one for each parameter). + let hash_fn_def = calc_fn_hash(empty(), name, repeat(EMPTY_TYPE_ID()).take(params)); + let fn_def = self.get_function(hash_fn_def); + + match fn_def.as_ref().map(|f| f.access) { + None => None, + Some(FnAccess::Private) if public_only => None, + Some(FnAccess::Private) => fn_def, + Some(FnAccess::Public) => fn_def, + } } /// Merge another `FunctionsLib` into this `FunctionsLib`. pub fn merge(&self, other: &Self) -> Self { @@ -216,6 +243,12 @@ impl FunctionsLib { } } +impl From> for FunctionsLib { + fn from(values: Vec<(u64, SharedFnDef)>) -> Self { + FunctionsLib(values.into_iter().collect()) + } +} + impl Deref for FunctionsLib { #[cfg(feature = "sync")] type Target = HashMap>; @@ -255,15 +288,10 @@ 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 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 module containing all functions directly loaded into the Engine. + pub(crate) global_module: Module, + /// A collection of all library packages loaded into the Engine. + pub(crate) packages: PackagesCollection, /// A module resolution service. #[cfg(not(feature = "no_module"))] @@ -273,22 +301,12 @@ pub struct Engine { pub(crate) type_names: HashMap, /// Closure for implementing the `print` command. - #[cfg(feature = "sync")] - pub(crate) print: Box, - /// Closure for implementing the `print` command. - #[cfg(not(feature = "sync"))] - pub(crate) print: Box, - + pub(crate) print: Box, /// Closure for implementing the `debug` command. - #[cfg(feature = "sync")] - pub(crate) debug: Box, - /// Closure for implementing the `debug` command. - #[cfg(not(feature = "sync"))] - pub(crate) debug: Box, + pub(crate) debug: Box, /// Optimize the AST after compilation. pub(crate) optimization_level: OptimizationLevel, - /// Maximum levels of call-stack to prevent infinite recursion. /// /// Defaults to 28 for debug builds and 256 for non-debug builds. @@ -300,8 +318,7 @@ impl Default for Engine { // Create the new scripting Engine let mut engine = Self { packages: Default::default(), - functions: HashMap::with_capacity(FUNCTIONS_COUNT), - type_iterators: Default::default(), + global_module: Default::default(), #[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_std"))] @@ -393,29 +410,30 @@ fn default_print(s: &str) { fn search_scope<'a>( scope: &'a mut Scope, name: &str, - modules: &ModuleRef, + #[cfg(not(feature = "no_module"))] modules: Option<(&Box, u64)>, + #[cfg(feature = "no_module")] _: Option<(&ModuleRef, u64)>, index: Option, pos: Position, ) -> Result<(&'a mut Dynamic, ScopeEntryType), Box> { #[cfg(not(feature = "no_module"))] { - if let Some(modules) = modules { - let (id, root_pos) = modules.get(0); // First module - - let module = if let Some(index) = index { + if let Some((modules, hash_var)) = modules { + let module = if let Some(index) = modules.index() { scope .get_mut(scope.len() - index.get()) .0 .downcast_mut::() .unwrap() } else { + let (id, root_pos) = modules.get_ref(0); + scope.find_module(id).ok_or_else(|| { Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos)) })? }; return Ok(( - module.get_qualified_var_mut(name, modules.as_ref(), pos)?, + module.get_qualified_var_mut(name, hash_var, pos)?, // Module variables are constant ScopeEntryType::Constant, )); @@ -445,8 +463,7 @@ impl Engine { pub fn new_raw() -> Self { Self { packages: Default::default(), - functions: HashMap::with_capacity(FUNCTIONS_COUNT / 2), - type_iterators: Default::default(), + global_module: Default::default(), #[cfg(not(feature = "no_module"))] module_resolver: None, @@ -476,7 +493,16 @@ impl Engine { /// 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); + self.packages.push(package); + } + + /// 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_packages(&mut self, package: PackageLibrary) { + // Push the package to the top - packages are searched in reverse order + self.packages.push(package); } /// Control whether and how the `Engine` will optimize an AST after compilation. @@ -511,58 +537,92 @@ impl Engine { pub(crate) fn call_fn_raw( &self, scope: Option<&mut Scope>, - fn_lib: &FunctionsLib, + state: &State, fn_name: &str, + hashes: (u64, u64), args: &mut FnCallArgs, + is_ref: bool, def_val: Option<&Dynamic>, pos: Position, level: usize, - ) -> Result> { + ) -> Result<(Dynamic, bool), Box> { // Check for stack overflow if level > self.max_call_stack_depth { return Err(Box::new(EvalAltResult::ErrorStackOverflow(pos))); } // First search in script-defined functions (can override built-in) - 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); + if hashes.1 > 0 { + if let Some(fn_def) = state.get_function(hashes.1) { + return self + .call_script_fn(scope, state, fn_name, fn_def, args, pos, level) + .map(|v| (v, false)); + } } // Search built-in's and external functions - let fn_spec = calc_fn_hash(fn_name, args.iter().map(|a| a.type_id())); + if let Some(func) = self + .global_module + .get_fn(hashes.0) + .or_else(|| self.packages.get_fn(hashes.0)) + { + let mut backup: Dynamic = Default::default(); + + let (updated, restore) = match func.abi() { + // Calling pure function in method-call + NativeFunctionABI::Pure if is_ref && args.len() > 0 => { + // Backup the original value. It'll be consumed because the function + // is pure and doesn't know that the first value is a reference (i.e. `is_ref`) + backup = args[0].clone(); + (false, true) + } + NativeFunctionABI::Pure => (false, false), + NativeFunctionABI::Method => (true, false), + }; - 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)?; + let result = match func.call(args) { + Ok(r) => { + // Restore the backup value for the first argument since it has been consumed! + if restore { + *args[0] = backup; + } + r + } + Err(err) => { + return Err(err.new_position(pos)); + } + }; // See if the function match print/debug (which requires special processing) 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, + KEYWORD_PRINT => ( + (self.print)(result.as_str().map_err(|type_name| { + Box::new(EvalAltResult::ErrorMismatchOutputType( + type_name.into(), + pos, + )) + })?) + .into(), + false, + ), + KEYWORD_DEBUG => ( + (self.debug)(result.as_str().map_err(|type_name| { + Box::new(EvalAltResult::ErrorMismatchOutputType( + type_name.into(), + pos, + )) + })?) + .into(), + false, + ), + _ => (result, updated), }); } // Return default value (if any) if let Some(val) = def_val { - return Ok(val.clone()); + return Ok((val.clone(), false)); } // Getter function not found? @@ -608,10 +668,11 @@ impl Engine { /// Function call arguments may be _consumed_ when the function requires them to be passed by value. /// All function arguments not in the first position are always passed by value and thus consumed. /// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`! - pub(crate) fn call_fn_from_lib( + pub(crate) fn call_script_fn<'s>( &self, - scope: Option<&mut Scope>, - fn_lib: &FunctionsLib, + scope: Option<&mut Scope<'s>>, + state: &State, + fn_name: &str, fn_def: &FnDef, args: &mut FnCallArgs, pos: Position, @@ -621,9 +682,11 @@ impl Engine { // Extern scope passed in which is not empty Some(scope) if scope.len() > 0 => { let scope_len = scope.len(); - let mut state = State::new(); + let mut state = State::new(state.fn_lib); - // Put arguments into scope as variables - variable name is copied + state.scope_level += 1; + + // Put arguments into scope as variables scope.extend( fn_def .params @@ -632,18 +695,34 @@ impl Engine { // Actually consume the arguments instead of cloning them args.into_iter().map(|v| mem::take(*v)), ) - .map(|(name, value)| (name.clone(), ScopeEntryType::Normal, value)), + .map(|(name, value)| { + let var_name = unsafe_cast_var_name(name.as_str(), &state); + (var_name, 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) + .eval_stmt(scope, &mut state, &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)), + EvalAltResult::ErrorInFunctionCall(name, err, _) => { + Err(Box::new(EvalAltResult::ErrorInFunctionCall( + format!("{} > {}", fn_name, name), + err, + pos, + ))) + } + _ => Err(Box::new(EvalAltResult::ErrorInFunctionCall( + fn_name.to_string(), + err, + pos, + ))), }); + // Remove all local variables + // No need to reset `state.scope_level` because it is thrown away scope.rewind(scope_len); return result; @@ -651,7 +730,8 @@ impl Engine { // No new scope - create internal scope _ => { let mut scope = Scope::new(); - let mut state = State::new(); + let mut state = State::new(state.fn_lib); + state.scope_level += 1; // Put arguments into scope as variables scope.extend( @@ -666,27 +746,37 @@ impl Engine { ); // Evaluate the function at one higher level of call depth + // No need to reset `state.scope_level` because it is thrown away return self - .eval_stmt(&mut scope, &mut state, fn_lib, &fn_def.body, level + 1) + .eval_stmt(&mut scope, &mut state, &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)), + EvalAltResult::ErrorInFunctionCall(name, err, _) => { + Err(Box::new(EvalAltResult::ErrorInFunctionCall( + format!("{} > {}", fn_name, name), + err, + pos, + ))) + } + _ => Err(Box::new(EvalAltResult::ErrorInFunctionCall( + fn_name.to_string(), + 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::())); - + fn has_override(&self, state: &State, hashes: (u64, u64)) -> bool { // First check registered functions - self.functions.contains_key(&hash) + self.global_module.contains_fn(hashes.0) // Then check packages - || self.packages.iter().any(|p| p.functions.contains_key(&hash)) + || self.packages.contains_fn(hashes.0) // Then check script-defined functions - || fn_lib.has_function(name, 1) + || state.has_function(hashes.1) } // Perform an actual function call, taking care of special functions @@ -698,28 +788,38 @@ impl Engine { /// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`! fn exec_fn_call( &self, - fn_lib: &FunctionsLib, + state: &State, fn_name: &str, + hash_fn_def: u64, args: &mut FnCallArgs, + is_ref: bool, def_val: Option<&Dynamic>, pos: Position, level: usize, - ) -> Result> { + ) -> Result<(Dynamic, bool), Box> { + // Qualifiers (none) + function name + argument `TypeId`'s. + let hash_fn = calc_fn_hash(empty(), fn_name, args.iter().map(|a| a.type_id())); + let hashes = (hash_fn, hash_fn_def); + 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()) - } + KEYWORD_TYPE_OF if args.len() == 1 && !self.has_override(state, hashes) => Ok(( + self.map_type_name(args[0].type_name()).to_string().into(), + false, + )), // eval - reaching this point it must be a method-style call - KEYWORD_EVAL if args.len() == 1 && !self.has_override(fn_lib, KEYWORD_EVAL) => { + KEYWORD_EVAL if args.len() == 1 && !self.has_override(state, hashes) => { Err(Box::new(EvalAltResult::ErrorRuntime( "'eval' should not be called in method style. Try eval(...);".into(), pos, ))) } - // Normal method call - _ => self.call_fn_raw(None, fn_lib, fn_name, args, def_val, pos, level), + + // Normal function call + _ => self.call_fn_raw( + None, state, fn_name, hashes, args, is_ref, def_val, pos, level, + ), } } @@ -727,7 +827,7 @@ impl Engine { fn eval_script_expr( &self, scope: &mut Scope, - fn_lib: &FunctionsLib, + state: &State, script: &Dynamic, pos: Position, ) -> Result> { @@ -739,7 +839,7 @@ impl Engine { // No optimizations because we only run it once let mut ast = self.compile_with_scope_and_optimization_level( &Scope::new(), - script, + &[script], OptimizationLevel::None, )?; @@ -751,17 +851,17 @@ impl Engine { } let statements = mem::take(ast.statements_mut()); - let ast = AST::new(statements, fn_lib.clone()); + let ast = AST::new(statements, state.fn_lib.clone()); // Evaluate the AST self.eval_ast_with_scope_raw(scope, &ast) - .map_err(|err| EvalAltResult::set_position(err, pos)) + .map_err(|err| err.new_position(pos)) } /// Chain-evaluate a dot/index chain. fn eval_dot_index_chain_helper( &self, - fn_lib: &FunctionsLib, + state: &State, mut target: Target, rhs: &Expr, idx_values: &mut StaticVec, @@ -771,10 +871,10 @@ impl Engine { 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, + let (obj, is_ref) = match target { + Target::Ref(r) => (r, true), + Target::Value(ref mut r) => (r.as_mut(), false), + Target::StringChar(ref mut x) => (&mut x.2, false), }; // Pop the last index value @@ -782,121 +882,148 @@ impl Engine { 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(_,_,_)); + // xxx[idx].dot_rhs... | xxx[idx][dot_rhs]... + Expr::Dot(x) | Expr::Index(x) => { + let is_idx = matches!(rhs, Expr::Index(_)); + let pos = x.0.position(); + let val = + self.get_indexed_mut(state, obj, is_ref, idx_val, pos, op_pos, false)?; - let indexed_val = self.get_indexed_mut(fn_lib, 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 + state, val, &x.1, idx_values, is_idx, x.2, level, new_val, ) } // xxx[rhs] = new_val _ if new_val.is_some() => { - let mut indexed_val = self.get_indexed_mut(fn_lib, obj, idx_val, rhs.position(), op_pos, true)?; - indexed_val.set_value(new_val.unwrap(), rhs.position())?; + let pos = rhs.position(); + let mut val = + self.get_indexed_mut(state, obj, is_ref, idx_val, pos, op_pos, true)?; + + val.set_value(new_val.unwrap(), rhs.position())?; Ok((Default::default(), true)) } // xxx[rhs] _ => self - .get_indexed_mut(fn_lib, obj, idx_val, rhs.position(), op_pos, false) - .map(|v| (v.clone_into_dynamic(), false)) + .get_indexed_mut(state, obj, is_ref, idx_val, rhs.position(), op_pos, false) + .map(|v| (v.clone_into_dynamic(), false)), } } else { match rhs { // xxx.fn_name(arg_expr_list) - Expr::FnCall(fn_name, None,_, def_val, pos) => { - let mut args: Vec<_> = once(obj) - .chain(idx_val.downcast_mut::>().unwrap().iter_mut()) + Expr::FnCall(x) if x.1.is_none() => { + let ((name, pos), _, hash_fn_def, _, def_val) = x.as_ref(); + let def_val = def_val.as_ref(); + + let mut arg_values: StaticVec<_> = 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)) + let args = arg_values.as_mut(); + + self.exec_fn_call(state, name, *hash_fn_def, args, is_ref, def_val, *pos, 0) } // xxx.module::fn_name(...) - syntax error - Expr::FnCall(_,_,_,_,_) => unreachable!(), + Expr::FnCall(_) => unreachable!(), // {xxx:map}.id = ??? #[cfg(not(feature = "no_object"))] - Expr::Property(id, pos) if obj.is::() && new_val.is_some() => { - let mut indexed_val = - self.get_indexed_mut(fn_lib, obj, id.to_string().into(), *pos, op_pos, true)?; - indexed_val.set_value(new_val.unwrap(), rhs.position())?; + Expr::Property(x) if obj.is::() && new_val.is_some() => { + let ((prop, _, _), pos) = x.as_ref(); + let index = prop.clone().into(); + let mut val = + self.get_indexed_mut(state, obj, is_ref, index, *pos, op_pos, true)?; + + val.set_value(new_val.unwrap(), rhs.position())?; Ok((Default::default(), true)) } // {xxx:map}.id #[cfg(not(feature = "no_object"))] - Expr::Property(id, pos) if obj.is::() => { - let indexed_val = - self.get_indexed_mut(fn_lib, obj, id.to_string().into(), *pos, op_pos, false)?; - Ok((indexed_val.clone_into_dynamic(), false)) + Expr::Property(x) if obj.is::() => { + let ((prop, _, _), pos) = x.as_ref(); + let index = prop.clone().into(); + let val = + self.get_indexed_mut(state, obj, is_ref, index, *pos, op_pos, false)?; + + Ok((val.clone_into_dynamic(), false)) } - // xxx.id = ??? a - Expr::Property(id, pos) if new_val.is_some() => { - let fn_name = make_setter(id); + // xxx.id = ??? + Expr::Property(x) if new_val.is_some() => { + let ((_, _, setter), pos) = x.as_ref(); 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)) + self.exec_fn_call(state, setter, 0, &mut args, is_ref, None, *pos, 0) + .map(|(v, _)| (v, true)) } // xxx.id - Expr::Property(id, pos) => { - let fn_name = make_getter(id); + Expr::Property(x) => { + let ((_, getter, _), pos) = x.as_ref(); let mut args = [obj]; - self.exec_fn_call(fn_lib, &fn_name, &mut args, None, *pos, 0).map(|v| (v, false)) + self.exec_fn_call(state, getter, 0, &mut args, is_ref, None, *pos, 0) + .map(|(v, _)| (v, false)) } #[cfg(not(feature = "no_object"))] - // {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(_,_,_)); + // {xxx:map}.idx_lhs[idx_expr] | {xxx:map}.dot_lhs.rhs + Expr::Index(x) | Expr::Dot(x) if obj.is::() => { + let is_idx = matches!(rhs, Expr::Index(_)); - let indexed_val = if let Expr::Property(id, pos) = dot_lhs.as_ref() { - self.get_indexed_mut(fn_lib, obj, id.to_string().into(), *pos, op_pos, false)? + let val = if let Expr::Property(p) = &x.0 { + let ((prop, _, _), _) = p.as_ref(); + let index = prop.clone().into(); + self.get_indexed_mut(state, obj, is_ref, index, x.2, op_pos, false)? } else { // Syntax error return Err(Box::new(EvalAltResult::ErrorDotExpr( - "".to_string(), + "".into(), rhs.position(), ))); }; + self.eval_dot_index_chain_helper( - fn_lib, indexed_val, dot_rhs, idx_values, is_index, *pos, level, new_val + state, val, &x.1, idx_values, is_idx, x.2, 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 args = [obj, &mut Default::default()]; + // xxx.idx_lhs[idx_expr] | xxx.dot_lhs.rhs + Expr::Index(x) | Expr::Dot(x) => { + let is_idx = matches!(rhs, Expr::Index(_)); + let args = &mut [obj, &mut Default::default()]; - 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)? + let (mut val, updated) = if let Expr::Property(p) = &x.0 { + let ((_, getter, _), _) = p.as_ref(); + self.exec_fn_call(state, getter, 0, &mut args[..1], is_ref, None, x.2, 0)? } else { // Syntax error return Err(Box::new(EvalAltResult::ErrorDotExpr( - "".to_string(), + "".into(), rhs.position(), ))); - }); + }; + let val = &mut val; + let (result, may_be_changed) = self.eval_dot_index_chain_helper( - fn_lib, indexed_val.into(), dot_rhs, idx_values, is_index, *pos, level, new_val + state, + val.into(), + &x.1, + idx_values, + is_idx, + x.2, + level, + new_val, )?; // Feed the value back via a setter just in case it has been updated - if may_be_changed { - if let Expr::Property(id, pos) = dot_lhs.as_ref() { - let fn_name = make_setter(id); + if updated || may_be_changed { + if let Expr::Property(p) = &x.0 { + let ((_, _, setter), _) = p.as_ref(); // Re-use args because the first &mut parameter will not be consumed - args[1] = indexed_val; - self.exec_fn_call(fn_lib, &fn_name, &mut args, None, *pos, 0).or_else(|err| match *err { - // If there is no setter, no need to feed it back because the property is read-only - EvalAltResult::ErrorDotExpr(_,_) => Ok(Default::default()), - err => Err(Box::new(err)) - })?; + args[1] = val; + self.exec_fn_call(state, setter, 0, args, is_ref, None, x.2, 0) + .or_else(|err| match *err { + // If there is no setter, no need to feed it back because the property is read-only + EvalAltResult::ErrorDotExpr(_, _) => Ok(Default::default()), + err => Err(Box::new(err)), + })?; } } @@ -904,7 +1031,7 @@ impl Engine { } // Syntax error _ => Err(Box::new(EvalAltResult::ErrorDotExpr( - "".to_string(), + "".into(), rhs.position(), ))), } @@ -916,7 +1043,6 @@ impl Engine { &self, scope: &mut Scope, state: &mut State, - fn_lib: &FunctionsLib, dot_lhs: &Expr, dot_rhs: &Expr, is_index: bool, @@ -926,20 +1052,22 @@ impl Engine { ) -> Result> { let idx_values = &mut StaticVec::new(); - self.eval_indexed_chain(scope, state, fn_lib, dot_rhs, idx_values, 0, level)?; + self.eval_indexed_chain(scope, state, dot_rhs, idx_values, 0, level)?; match dot_lhs { // id.??? or id[???] - Expr::Variable(id, modules, index, pos) => { + Expr::Variable(x) => { + let ((name, pos), modules, hash_var, index) = x.as_ref(); let index = if state.always_search { None } else { *index }; - let (target, typ) = search_scope(scope, id, modules, index, *pos)?; + let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var)); + let (target, typ) = search_scope(scope, &name, mod_and_hash, index, *pos)?; // Constants cannot be modified match typ { ScopeEntryType::Module => unreachable!(), ScopeEntryType::Constant if new_val.is_some() => { return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( - id.to_string(), + name.clone(), *pos, ))); } @@ -948,7 +1076,7 @@ impl Engine { let this_ptr = target.into(); self.eval_dot_index_chain_helper( - fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val, + state, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val, ) .map(|(v, _)| v) } @@ -960,10 +1088,10 @@ impl Engine { } // {expr}.??? or {expr}[???] expr => { - let val = self.eval_expr(scope, state, fn_lib, expr, level)?; + let val = self.eval_expr(scope, state, expr, level)?; let this_ptr = val.into(); self.eval_dot_index_chain_helper( - fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val, + state, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val, ) .map(|(v, _)| v) } @@ -979,39 +1107,36 @@ impl Engine { &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::FnCall(_, None, arg_exprs, _, _) => { - let arg_values = arg_exprs - .iter() - .map(|arg_expr| self.eval_expr(scope, state, fn_lib, arg_expr, level)) - .collect::, _>>()?; + Expr::FnCall(x) if x.1.is_none() => { + let mut arg_values = StaticVec::::new(); + + for arg_expr in x.3.iter() { + arg_values.push(self.eval_expr(scope, state, arg_expr, level)?); + } - #[cfg(not(feature = "no_index"))] - idx_values.push(arg_values); - #[cfg(feature = "no_index")] idx_values.push(Dynamic::from(arg_values)); } - Expr::FnCall(_, _, _, _, _) => unreachable!(), - Expr::Property(_, _) => idx_values.push(()), // Store a placeholder - no need to copy the property name - Expr::Index(lhs, rhs, _) | Expr::Dot(lhs, rhs, _) => { + Expr::FnCall(_) => unreachable!(), + Expr::Property(_) => idx_values.push(()), // Store a placeholder - no need to copy the property name + Expr::Index(x) | Expr::Dot(x) => { // Evaluate in left-to-right order - let lhs_val = match lhs.as_ref() { - Expr::Property(_, _) => Default::default(), // Store a placeholder in case of a property - _ => self.eval_expr(scope, state, fn_lib, lhs, level)?, + let lhs_val = match x.0 { + Expr::Property(_) => Default::default(), // Store a placeholder in case of a property + _ => self.eval_expr(scope, state, &x.0, level)?, }; // Push in reverse order - self.eval_indexed_chain(scope, state, fn_lib, rhs, idx_values, size, level)?; + self.eval_indexed_chain(scope, state, &x.1, idx_values, size, level)?; idx_values.push(lhs_val); } - _ => idx_values.push(self.eval_expr(scope, state, fn_lib, expr, level)?), + _ => idx_values.push(self.eval_expr(scope, state, expr, level)?), } Ok(()) @@ -1020,15 +1145,14 @@ impl Engine { /// Get the value at the indexed position of a base type fn get_indexed_mut<'a>( &self, - fn_lib: &FunctionsLib, + state: &State, val: &'a mut Dynamic, + is_ref: bool, mut idx: Dynamic, idx_pos: Position, op_pos: Position, create: bool, ) -> Result, Box> { - let type_name = self.map_type_name(val.type_name()); - match val { #[cfg(not(feature = "no_index"))] Dynamic(Union::Array(arr)) => { @@ -1071,43 +1195,31 @@ impl Engine { #[cfg(not(feature = "no_index"))] Dynamic(Union::Str(s)) => { // val_string[idx] + let chars_len = s.chars().count(); let index = idx .as_int() .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?; if index >= 0 { - let ch = s.chars().nth(index as usize).ok_or_else(|| { - Box::new(EvalAltResult::ErrorStringBounds( - s.chars().count(), - index, - idx_pos, - )) + let offset = index as usize; + let ch = s.chars().nth(offset).ok_or_else(|| { + Box::new(EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)) })?; - - Ok(Target::StringChar(Box::new(( - val, - index as usize, - ch.into(), - )))) + Ok(Target::StringChar(Box::new((val, offset, ch.into())))) } else { Err(Box::new(EvalAltResult::ErrorStringBounds( - s.chars().count(), - index, - idx_pos, + chars_len, index, idx_pos, ))) } } _ => { + let type_name = self.map_type_name(val.type_name()); let args = &mut [val, &mut idx]; - self.exec_fn_call(fn_lib, FUNC_INDEXER, args, None, op_pos, 0) - .map(|v| v.into()) + self.exec_fn_call(state, FUNC_INDEXER, 0, args, is_ref, None, op_pos, 0) + .map(|(v, _)| v.into()) .map_err(|_| { - Box::new(EvalAltResult::ErrorIndexingType( - // Error - cannot be indexed - type_name.to_string(), - op_pos, - )) + Box::new(EvalAltResult::ErrorIndexingType(type_name.into(), op_pos)) }) } } @@ -1118,33 +1230,33 @@ impl Engine { &self, scope: &mut Scope, state: &mut State, - fn_lib: &FunctionsLib, lhs: &Expr, rhs: &Expr, level: usize, ) -> Result> { - let lhs_value = self.eval_expr(scope, state, fn_lib, lhs, level)?; - let rhs_value = self.eval_expr(scope, state, fn_lib, rhs, level)?; + let mut lhs_value = self.eval_expr(scope, state, lhs, level)?; + let rhs_value = self.eval_expr(scope, state, rhs, level)?; match rhs_value { #[cfg(not(feature = "no_index"))] - Dynamic(Union::Array(rhs_value)) => { + Dynamic(Union::Array(mut rhs_value)) => { + let op = "=="; let def_value = false.into(); + let hash_fn_def = calc_fn_hash(empty(), op, repeat(EMPTY_TYPE_ID()).take(2)); // Call the `==` operator to compare each value - for value in rhs_value.iter() { - // WARNING - Always clone the values here because they'll be consumed by the function call. - // Do not pass the `&mut` straight through because the `==` implementation - // very likely takes parameters passed by value! - let args = &mut [&mut lhs_value.clone(), &mut value.clone()]; + for value in rhs_value.iter_mut() { + let args = &mut [&mut lhs_value, value]; let def_value = Some(&def_value); let pos = rhs.position(); - if self - .call_fn_raw(None, fn_lib, "==", args, def_value, pos, level)? - .as_bool() - .unwrap_or(false) - { + // Qualifiers (none) + function name + argument `TypeId`'s. + let hash_fn = calc_fn_hash(empty(), op, args.iter().map(|a| a.type_id())); + let hashes = (hash_fn, hash_fn_def); + + let (r, _) = self + .call_fn_raw(None, state, op, hashes, args, true, def_value, pos, level)?; + if r.as_bool().unwrap_or(false) { return Ok(true.into()); } } @@ -1173,207 +1285,242 @@ impl Engine { &self, scope: &mut Scope, state: &mut State, - fn_lib: &FunctionsLib, expr: &Expr, level: usize, ) -> Result> { match expr { - Expr::IntegerConstant(i, _) => Ok((*i).into()), + Expr::IntegerConstant(x) => Ok(x.0.into()), #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(f, _) => Ok((*f).into()), - Expr::StringConstant(s, _) => Ok(s.to_string().into()), - Expr::CharConstant(c, _) => Ok((*c).into()), - Expr::Variable(id, modules, index, pos) => { + Expr::FloatConstant(x) => Ok(x.0.into()), + Expr::StringConstant(x) => Ok(x.0.to_string().into()), + Expr::CharConstant(x) => Ok(x.0.into()), + Expr::Variable(x) => { + let ((name, pos), modules, hash_var, index) = x.as_ref(); let index = if state.always_search { None } else { *index }; - let val = search_scope(scope, id, modules, index, *pos)?; - Ok(val.0.clone()) + let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var)); + let (val, _) = search_scope(scope, name, mod_and_hash, index, *pos)?; + Ok(val.clone()) } - Expr::Property(_, _) => unreachable!(), + Expr::Property(_) => unreachable!(), // Statement block - Expr::Stmt(stmt, _) => self.eval_stmt(scope, state, fn_lib, stmt, level), + Expr::Stmt(stmt) => self.eval_stmt(scope, state, &stmt.0, level), // lhs = rhs - Expr::Assignment(lhs, rhs, op_pos) => { - let rhs_val = self.eval_expr(scope, state, fn_lib, rhs, level)?; + Expr::Assignment(x) => { + let op_pos = x.2; + let rhs_val = self.eval_expr(scope, state, &x.1, level)?; - match lhs.as_ref() { + match &x.0 { // name = rhs - Expr::Variable(name, modules, index, pos) => { + Expr::Variable(x) => { + let ((name, pos), modules, hash_var, index) = x.as_ref(); let index = if state.always_search { None } else { *index }; - match search_scope(scope, name, modules, index, *pos)? { - (_, ScopeEntryType::Constant) => Err(Box::new( - EvalAltResult::ErrorAssignmentToConstant(name.to_string(), *op_pos), + let mod_and_hash = modules.as_ref().map(|m| (m, *hash_var)); + let (lhs_ptr, typ) = search_scope(scope, name, mod_and_hash, index, *pos)?; + match typ { + ScopeEntryType::Constant => Err(Box::new( + EvalAltResult::ErrorAssignmentToConstant(name.clone(), *pos), )), - (value_ptr, ScopeEntryType::Normal) => { - *value_ptr = rhs_val; + ScopeEntryType::Normal => { + *lhs_ptr = rhs_val; Ok(Default::default()) } // End variable cannot be a module - (_, ScopeEntryType::Module) => unreachable!(), + ScopeEntryType::Module => unreachable!(), } } // idx_lhs[idx_expr] = rhs #[cfg(not(feature = "no_index"))] - Expr::Index(idx_lhs, idx_expr, op_pos) => { + Expr::Index(x) => { 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, + scope, state, &x.0, &x.1, true, x.2, level, new_val, ) } // dot_lhs.dot_rhs = rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(dot_lhs, dot_rhs, _) => { + Expr::Dot(x) => { 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, + scope, state, &x.0, &x.1, false, op_pos, level, new_val, ) } // Error assignment to constant expr if expr.is_constant() => { Err(Box::new(EvalAltResult::ErrorAssignmentToConstant( expr.get_constant_str(), - lhs.position(), + expr.position(), ))) } // Syntax error - _ => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS( - lhs.position(), + expr => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS( + expr.position(), ))), } } // lhs[idx_expr] #[cfg(not(feature = "no_index"))] - Expr::Index(lhs, idx_expr, op_pos) => self.eval_dot_index_chain( - scope, state, fn_lib, lhs, idx_expr, true, *op_pos, level, None, - ), + Expr::Index(x) => { + self.eval_dot_index_chain(scope, state, &x.0, &x.1, true, x.2, level, None) + } // lhs.dot_rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(lhs, dot_rhs, op_pos) => self.eval_dot_index_chain( - scope, state, fn_lib, lhs, dot_rhs, false, *op_pos, level, None, - ), + Expr::Dot(x) => { + self.eval_dot_index_chain(scope, state, &x.0, &x.1, false, x.2, level, None) + } #[cfg(not(feature = "no_index"))] - Expr::Array(contents, _) => Ok(Dynamic(Union::Array(Box::new( - contents - .iter() - .map(|item| self.eval_expr(scope, state, fn_lib, item, level)) + Expr::Array(x) => Ok(Dynamic(Union::Array(Box::new( + x.0.iter() + .map(|item| self.eval_expr(scope, state, item, level)) .collect::, _>>()?, )))), #[cfg(not(feature = "no_object"))] - Expr::Map(contents, _) => Ok(Dynamic(Union::Map(Box::new( - contents - .iter() - .map(|(key, expr, _)| { - self.eval_expr(scope, state, fn_lib, expr, level) + Expr::Map(x) => Ok(Dynamic(Union::Map(Box::new( + x.0.iter() + .map(|((key, _), expr)| { + self.eval_expr(scope, state, expr, level) .map(|val| (key.clone(), val)) }) .collect::, _>>()?, )))), // Normal function call - Expr::FnCall(fn_name, None, arg_exprs, def_val, pos) => { - let mut arg_values = arg_exprs + Expr::FnCall(x) if x.1.is_none() => { + let ((name, pos), _, hash_fn_def, args_expr, def_val) = x.as_ref(); + let def_val = def_val.as_ref(); + + let mut arg_values = args_expr .iter() - .map(|expr| self.eval_expr(scope, state, fn_lib, expr, level)) - .collect::, _>>()?; + .map(|expr| self.eval_expr(scope, state, expr, level)) + .collect::, _>>()?; - let mut args: Vec<_> = arg_values.iter_mut().collect(); + let mut args: StaticVec<_> = arg_values.iter_mut().collect(); - if fn_name.as_ref() == KEYWORD_EVAL - && args.len() == 1 - && !self.has_override(fn_lib, KEYWORD_EVAL) - { - // eval - only in function call style - let prev_len = scope.len(); + if name == KEYWORD_EVAL && args.len() == 1 && args.get_ref(0).is::() { + let hash_fn = calc_fn_hash(empty(), name, once(TypeId::of::())); - // Evaluate the text string as a script - let result = - self.eval_script_expr(scope, fn_lib, args[0], arg_exprs[0].position()); + if !self.has_override(state, (hash_fn, *hash_fn_def)) { + // eval - only in function call style + let prev_len = scope.len(); - 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; + // Evaluate the text string as a script + let result = self.eval_script_expr( + scope, + state, + args.pop(), + args_expr[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; } - - result - } else { - // Normal function call - except for eval (handled above) - let def_value = def_val.as_deref(); - self.exec_fn_call(fn_lib, fn_name, &mut args, def_value, *pos, level) } + + // Normal function call - except for eval (handled above) + let args = args.as_mut(); + self.exec_fn_call(state, name, *hash_fn_def, args, false, def_val, *pos, level) + .map(|(v, _)| v) } // Module-qualified function call #[cfg(not(feature = "no_module"))] - Expr::FnCall(fn_name, Some(modules), arg_exprs, def_val, pos) => { - let modules = modules.as_ref(); + Expr::FnCall(x) if x.1.is_some() => { + let ((name, pos), modules, hash_fn_def, args_expr, def_val) = x.as_ref(); + let modules = modules.as_ref().unwrap(); - let mut arg_values = arg_exprs + let mut arg_values = args_expr .iter() - .map(|expr| self.eval_expr(scope, state, fn_lib, expr, level)) - .collect::, _>>()?; + .map(|expr| self.eval_expr(scope, state, expr, level)) + .collect::, _>>()?; - let mut args: Vec<_> = arg_values.iter_mut().collect(); + let mut args: StaticVec<_> = arg_values.iter_mut().collect(); - let (id, root_pos) = modules.get(0); // First module + let (id, root_pos) = modules.get_ref(0); // First module - let module = scope.find_module(id).ok_or_else(|| { - Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos)) - })?; + let module = if let Some(index) = modules.index() { + scope + .get_mut(scope.len() - index.get()) + .0 + .downcast_mut::() + .unwrap() + } else { + scope.find_module(id).ok_or_else(|| { + Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos)) + })? + }; // First search in script-defined functions (can override built-in) - if let Some(fn_def) = module.get_qualified_fn_lib(fn_name, args.len(), modules)? { - self.call_fn_from_lib(None, fn_lib, fn_def, &mut args, *pos, level) + if let Some(fn_def) = module.get_qualified_scripted_fn(*hash_fn_def) { + self.call_script_fn(None, state, name, fn_def, args.as_mut(), *pos, level) } else { // Then search in Rust functions - let hash = calc_fn_hash(fn_name, args.iter().map(|a| a.type_id())); - match module.get_qualified_fn(fn_name, hash, modules, *pos) { - Ok(func) => func(&mut args, *pos), - Err(_) if def_val.is_some() => Ok(def_val.as_deref().unwrap().clone()), + // Rust functions are indexed in two steps: + // 1) Calculate a hash in a similar manner to script-defined functions, + // i.e. qualifiers + function name + dummy parameter types (one for each parameter). + // 2) Calculate a second hash with no qualifiers, empty function name, and + // the actual list of parameter `TypeId`'.s + let hash_fn_args = calc_fn_hash(empty(), "", args.iter().map(|a| a.type_id())); + // 3) The final hash is the XOR of the two hashes. + let hash_fn_native = *hash_fn_def ^ hash_fn_args; + + match module.get_qualified_fn(name, hash_fn_native) { + Ok(func) => func + .call(args.as_mut()) + .map_err(|err| err.new_position(*pos)), + Err(_) if def_val.is_some() => Ok(def_val.clone().unwrap()), Err(err) => Err(err), } } } - Expr::In(lhs, rhs, _) => { - self.eval_in_expr(scope, state, fn_lib, lhs.as_ref(), rhs.as_ref(), level) - } + Expr::In(x) => self.eval_in_expr(scope, state, &x.0, &x.1, level), - Expr::And(lhs, rhs, _) => Ok((self - .eval_expr(scope, state, fn_lib, lhs.as_ref(), level)? + Expr::And(x) => { + let (lhs, rhs, _) = x.as_ref(); + Ok((self + .eval_expr(scope, state, lhs, level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position()) })? && // Short-circuit using && self - .eval_expr(scope, state, fn_lib, rhs.as_ref(), level)? + .eval_expr(scope, state, rhs, level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("AND".into(), rhs.position()) })?) - .into()), + .into()) + } - Expr::Or(lhs, rhs, _) => Ok((self - .eval_expr(scope, state, fn_lib, lhs.as_ref(), level)? + Expr::Or(x) => { + let (lhs, rhs, _) = x.as_ref(); + Ok((self + .eval_expr(scope, state, lhs, level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position()) })? || // Short-circuit using || self - .eval_expr(scope, state, fn_lib, rhs.as_ref(), level)? + .eval_expr(scope, state, rhs, level)? .as_bool() .map_err(|_| { EvalAltResult::ErrorBooleanArgMismatch("OR".into(), rhs.position()) })?) - .into()), + .into()) + } Expr::True(_) => Ok(true.into()), Expr::False(_) => Ok(false.into()), @@ -1384,11 +1531,10 @@ impl Engine { } /// Evaluate a statement - pub(crate) fn eval_stmt( + pub(crate) fn eval_stmt<'s>( &self, - scope: &mut Scope, + scope: &mut Scope<'s>, state: &mut State, - fn_lib: &FunctionsLib, stmt: &Stmt, level: usize, ) -> Result> { @@ -1398,9 +1544,9 @@ impl Engine { // Expression as statement Stmt::Expr(expr) => { - let result = self.eval_expr(scope, state, fn_lib, expr, level)?; + let result = self.eval_expr(scope, state, expr, level)?; - Ok(if let Expr::Assignment(_, _, _) = *expr.as_ref() { + Ok(if let Expr::Assignment(_) = *expr.as_ref() { // If it is an assignment, erase the result at the root Default::default() } else { @@ -1409,14 +1555,16 @@ impl Engine { } // Block scope - Stmt::Block(block, _) => { + Stmt::Block(x) => { let prev_len = scope.len(); + state.scope_level += 1; - let result = block.iter().try_fold(Default::default(), |_, stmt| { - self.eval_stmt(scope, state, fn_lib, stmt, level) + let result = x.0.iter().try_fold(Default::default(), |_, stmt| { + self.eval_stmt(scope, state, stmt, level) }); scope.rewind(prev_len); + state.scope_level -= 1; // The impact of an eval statement goes away at the end of a block // because any new variables introduced will go out of scope @@ -1426,27 +1574,24 @@ impl Engine { } // If-else statement - Stmt::IfThenElse(guard, if_body, else_body) => self - .eval_expr(scope, state, fn_lib, guard, level)? + Stmt::IfThenElse(x) => self + .eval_expr(scope, state, &x.0, level)? .as_bool() - .map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(guard.position()))) + .map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(x.0.position()))) .and_then(|guard_val| { if guard_val { - self.eval_stmt(scope, state, fn_lib, if_body, level) - } else if let Some(stmt) = else_body { - self.eval_stmt(scope, state, fn_lib, stmt.as_ref(), level) + self.eval_stmt(scope, state, &x.1, level) + } else if let Some(stmt) = &x.2 { + self.eval_stmt(scope, state, stmt, level) } else { Ok(Default::default()) } }), // While loop - Stmt::While(guard, body) => loop { - match self - .eval_expr(scope, state, fn_lib, guard, level)? - .as_bool() - { - Ok(true) => match self.eval_stmt(scope, state, fn_lib, body, level) { + Stmt::While(x) => loop { + match self.eval_expr(scope, state, &x.0, level)?.as_bool() { + Ok(true) => match self.eval_stmt(scope, state, &x.1, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), @@ -1455,15 +1600,13 @@ impl Engine { }, }, Ok(false) => return Ok(Default::default()), - Err(_) => { - return Err(Box::new(EvalAltResult::ErrorLogicGuard(guard.position()))) - } + Err(_) => return Err(Box::new(EvalAltResult::ErrorLogicGuard(x.0.position()))), } }, // Loop statement Stmt::Loop(body) => loop { - match self.eval_stmt(scope, state, fn_lib, body, level) { + match self.eval_stmt(scope, state, body, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), @@ -1474,25 +1617,25 @@ impl Engine { }, // For loop - Stmt::For(name, expr, body) => { - let arr = self.eval_expr(scope, state, fn_lib, expr, level)?; - let tid = arr.type_id(); + Stmt::For(x) => { + let iter_type = self.eval_expr(scope, state, &x.1, level)?; + let tid = iter_type.type_id(); - 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)) - }) { + if let Some(iter_fn) = self + .global_module + .get_iter(tid) + .or_else(|| self.packages.get_iter(tid)) + { // Add the loop variable - let var_name = name.as_ref().clone(); + let var_name = unsafe_cast_var_name(&x.0, &state); scope.push(var_name, ()); let index = scope.len() - 1; + state.scope_level += 1; - for a in iter_fn(arr) { - *scope.get_mut(index).0 = a; + for loop_var in iter_fn(iter_type) { + *scope.get_mut(index).0 = loop_var; - match self.eval_stmt(scope, state, fn_lib, body, level) { + match self.eval_stmt(scope, state, &x.2, level) { Ok(_) => (), Err(err) => match *err { EvalAltResult::ErrorLoopBreak(false, _) => (), @@ -1503,9 +1646,10 @@ impl Engine { } scope.rewind(scope.len() - 1); + state.scope_level -= 1; Ok(Default::default()) } else { - Err(Box::new(EvalAltResult::ErrorFor(expr.position()))) + Err(Box::new(EvalAltResult::ErrorFor(x.1.position()))) } } @@ -1515,74 +1659,82 @@ impl Engine { // Break statement Stmt::Break(pos) => Err(Box::new(EvalAltResult::ErrorLoopBreak(true, *pos))), - // Empty return - Stmt::ReturnWithVal(None, ReturnType::Return, pos) => { - Err(Box::new(EvalAltResult::Return(Default::default(), *pos))) - } - // Return value - Stmt::ReturnWithVal(Some(a), ReturnType::Return, pos) => Err(Box::new( - EvalAltResult::Return(self.eval_expr(scope, state, fn_lib, a, level)?, *pos), - )), - - // Empty throw - Stmt::ReturnWithVal(None, ReturnType::Exception, pos) => { - Err(Box::new(EvalAltResult::ErrorRuntime("".into(), *pos))) - } - - // Throw value - Stmt::ReturnWithVal(Some(a), ReturnType::Exception, pos) => { - 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, + Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => { + Err(Box::new(EvalAltResult::Return( + self.eval_expr(scope, state, x.1.as_ref().unwrap(), level)?, + (x.0).1, ))) } + // Empty return + Stmt::ReturnWithVal(x) if (x.0).0 == ReturnType::Return => { + Err(Box::new(EvalAltResult::Return(Default::default(), (x.0).1))) + } + + // Throw value + Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Exception => { + let val = self.eval_expr(scope, state, x.1.as_ref().unwrap(), level)?; + Err(Box::new(EvalAltResult::ErrorRuntime( + val.take_string().unwrap_or_else(|_| "".into()), + (x.0).1, + ))) + } + + // Empty throw + Stmt::ReturnWithVal(x) if (x.0).0 == ReturnType::Exception => { + Err(Box::new(EvalAltResult::ErrorRuntime("".into(), (x.0).1))) + } + + Stmt::ReturnWithVal(_) => unreachable!(), + // Let statement - Stmt::Let(name, Some(expr), _) => { - let val = self.eval_expr(scope, state, fn_lib, expr, level)?; - // TODO - avoid copying variable name in inner block? - let var_name = name.as_ref().clone(); + Stmt::Let(x) if x.1.is_some() => { + let ((var_name, _), expr) = x.as_ref(); + let val = self.eval_expr(scope, state, expr.as_ref().unwrap(), level)?; + let var_name = unsafe_cast_var_name(var_name, &state); scope.push_dynamic_value(var_name, ScopeEntryType::Normal, val, false); Ok(Default::default()) } - Stmt::Let(name, None, _) => { - // TODO - avoid copying variable name in inner block? - let var_name = name.as_ref().clone(); + Stmt::Let(x) => { + let ((var_name, _), _) = x.as_ref(); + let var_name = unsafe_cast_var_name(var_name, &state); scope.push(var_name, ()); Ok(Default::default()) } // Const statement - Stmt::Const(name, expr, _) if expr.is_constant() => { - let val = self.eval_expr(scope, state, fn_lib, expr, level)?; - // TODO - avoid copying variable name in inner block? - let var_name = name.as_ref().clone(); + Stmt::Const(x) if x.1.is_constant() => { + let ((var_name, _), expr) = x.as_ref(); + let val = self.eval_expr(scope, state, &expr, level)?; + let var_name = unsafe_cast_var_name(var_name, &state); scope.push_dynamic_value(var_name, ScopeEntryType::Constant, val, true); Ok(Default::default()) } // Const expression not constant - Stmt::Const(_, _, _) => unreachable!(), + Stmt::Const(_) => unreachable!(), // Import statement - Stmt::Import(expr, name, _) => { + Stmt::Import(x) => { + let (expr, (name, _)) = x.as_ref(); + #[cfg(feature = "no_module")] unreachable!(); #[cfg(not(feature = "no_module"))] { if let Some(path) = self - .eval_expr(scope, state, fn_lib, expr, level)? + .eval_expr(scope, state, &expr, level)? .try_cast::() { if let Some(resolver) = self.module_resolver.as_ref() { - let module = resolver.resolve(self, &path, expr.position())?; + // Use an empty scope to create a module + let module = + resolver.resolve(self, Scope::new(), &path, expr.position())?; - // TODO - avoid copying module name in inner block? - let mod_name = name.as_ref().clone(); + let mod_name = unsafe_cast_var_name(name, &state); scope.push_module(mod_name, module); Ok(Default::default()) } else { @@ -1596,6 +1748,31 @@ impl Engine { } } } + + // Export statement + Stmt::Export(list) => { + for ((id, id_pos), rename) in list.as_ref() { + // Mark scope variables as public + if let Some(index) = scope + .get_index(id) + .map(|(i, _)| i) + .or_else(|| scope.get_module_index(id)) + { + let alias = rename + .as_ref() + .map(|(n, _)| n.clone()) + .unwrap_or_else(|| id.clone()); + + scope.set_entry_alias(index, alias); + } else { + return Err(Box::new(EvalAltResult::ErrorVariableNotFound( + id.into(), + *id_pos, + ))); + } + } + Ok(Default::default()) + } } } diff --git a/src/error.rs b/src/error.rs index b08e5975..11b7c9e2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,7 +5,7 @@ use crate::token::Position; use crate::stdlib::{boxed::Box, char, error::Error, fmt, string::String}; /// Error when tokenizing the script text. -#[derive(Debug, Eq, PartialEq, Hash, Clone)] +#[derive(Debug, Eq, PartialEq, Clone, Hash)] pub enum LexError { /// An unexpected character is encountered when tokenizing the script text. UnexpectedChar(char), @@ -44,7 +44,7 @@ impl fmt::Display for LexError { /// Some errors never appear when certain features are turned on. /// They still exist so that the application can turn features on and off without going through /// massive code changes to remove/add back enum variants in match statements. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, Eq, PartialEq, Clone, Hash)] pub enum ParseErrorType { /// Error in the script text. Wrapped value is the error message. BadInput(String), @@ -98,8 +98,16 @@ pub enum ParseErrorType { /// /// Never appears under the `no_function` feature. FnMissingBody(String), - /// Assignment to an inappropriate LHS (left-hand-side) expression. - AssignmentToInvalidLHS, + /// An export statement has duplicated names. + /// + /// Never appears under the `no_module` feature. + DuplicatedExport(String), + /// Export statement not at global level. + /// + /// Never appears under the `no_module` feature. + WrongExport, + /// Assignment to a copy of a value. + AssignmentToCopy, /// Assignment to an a constant variable. AssignmentToConstant(String), /// Break statement not inside a loop. @@ -114,7 +122,7 @@ impl ParseErrorType { } /// Error when parsing a script. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct ParseError(pub(crate) ParseErrorType, pub(crate) Position); impl ParseError { @@ -147,8 +155,10 @@ impl ParseError { ParseErrorType::FnDuplicatedParam(_,_) => "Duplicated parameters in function declaration", 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::AssignmentToConstant(_) => "Cannot assign to a constant variable.", + ParseErrorType::DuplicatedExport(_) => "Duplicated variable/function in export statement", + ParseErrorType::WrongExport => "Export statement can only appear at global level", + ParseErrorType::AssignmentToCopy => "Only a copy of the value is change with this assignment", + ParseErrorType::AssignmentToConstant(_) => "Cannot assign to a constant value.", ParseErrorType::LoopBreak => "Break statement should only be used inside a loop" } } @@ -193,6 +203,12 @@ impl fmt::Display for ParseError { write!(f, "Duplicated parameter '{}' for function '{}'", arg, s)? } + ParseErrorType::DuplicatedExport(s) => write!( + f, + "Duplicated variable/function '{}' in export statement", + s + )?, + ParseErrorType::MissingToken(token, s) => write!(f, "Expecting '{}' {}", token, s)?, ParseErrorType::AssignmentToConstant(s) if s.is_empty() => { diff --git a/src/fn_call.rs b/src/fn_call.rs index c64ba035..e1da767b 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -3,14 +3,14 @@ #![allow(non_snake_case)] use crate::any::{Dynamic, Variant}; -use crate::stdlib::vec::Vec; +use crate::utils::StaticVec; /// 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 the function call arguments. - fn into_vec(self) -> Vec; + fn into_vec(self) -> StaticVec; } /// Macro to implement `FuncArgs` for tuples of standard types (each can be @@ -19,11 +19,11 @@ macro_rules! impl_args { ($($p:ident),*) => { impl<$($p: Variant + Clone),*> FuncArgs for ($($p,)*) { - fn into_vec(self) -> Vec { + fn into_vec(self) -> StaticVec { let ($($p,)*) = self; #[allow(unused_mut)] - let mut v = Vec::new(); + let mut v = StaticVec::new(); $(v.push($p.into_dynamic());)* v diff --git a/src/fn_func.rs b/src/fn_func.rs index af538306..e619ebdf 100644 --- a/src/fn_func.rs +++ b/src/fn_func.rs @@ -92,15 +92,14 @@ macro_rules! def_anonymous_fn { { #[cfg(feature = "sync")] type Output = Box Result> + Send + Sync>; - #[cfg(not(feature = "sync"))] type Output = Box Result>>; fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output { - let name = entry_point.to_string(); + let fn_name = entry_point.to_string(); Box::new(move |$($par: $par),*| { - self.call_fn(&mut Scope::new(), &ast, &name, ($($par,)*)) + self.call_fn(&mut Scope::new(), &ast, &fn_name, ($($par,)*)) }) } diff --git a/src/fn_native.rs b/src/fn_native.rs new file mode 100644 index 00000000..a8daac5f --- /dev/null +++ b/src/fn_native.rs @@ -0,0 +1,134 @@ +use crate::any::Dynamic; +use crate::result::EvalAltResult; + +use crate::stdlib::{boxed::Box, rc::Rc, sync::Arc}; + +pub type FnCallArgs<'a> = [&'a mut Dynamic]; + +#[cfg(feature = "sync")] +pub type FnAny = dyn Fn(&mut FnCallArgs) -> Result> + Send + Sync; +#[cfg(not(feature = "sync"))] +pub type FnAny = dyn Fn(&mut FnCallArgs) -> Result>; + +#[cfg(feature = "sync")] +pub type IteratorFn = dyn Fn(Dynamic) -> Box> + Send + Sync; +#[cfg(not(feature = "sync"))] +pub type IteratorFn = dyn Fn(Dynamic) -> Box>; + +#[cfg(feature = "sync")] +pub type PrintCallback = dyn Fn(&str) + Send + Sync + 'static; +#[cfg(not(feature = "sync"))] +pub type PrintCallback = dyn Fn(&str) + 'static; + +// Define callback function types +#[cfg(feature = "sync")] +pub trait ObjectGetCallback: Fn(&mut T) -> U + Send + Sync + 'static {} +#[cfg(feature = "sync")] +impl U + Send + Sync + 'static, T, U> ObjectGetCallback for F {} + +#[cfg(not(feature = "sync"))] +pub trait ObjectGetCallback: Fn(&mut T) -> U + 'static {} +#[cfg(not(feature = "sync"))] +impl U + 'static, T, U> ObjectGetCallback for F {} + +#[cfg(feature = "sync")] +pub trait ObjectSetCallback: Fn(&mut T, U) + Send + Sync + 'static {} +#[cfg(feature = "sync")] +impl ObjectSetCallback for F {} + +#[cfg(not(feature = "sync"))] +pub trait ObjectSetCallback: Fn(&mut T, U) + 'static {} +#[cfg(not(feature = "sync"))] +impl ObjectSetCallback for F {} + +#[cfg(feature = "sync")] +pub trait ObjectIndexerCallback: Fn(&mut T, X) -> U + Send + Sync + 'static {} +#[cfg(feature = "sync")] +impl U + Send + Sync + 'static, T, X, U> ObjectIndexerCallback for F {} + +#[cfg(not(feature = "sync"))] +pub trait ObjectIndexerCallback: Fn(&mut T, X) -> U + 'static {} +#[cfg(not(feature = "sync"))] +impl U + 'static, T, X, U> ObjectIndexerCallback for F {} + +#[cfg(feature = "sync")] +pub trait IteratorCallback: + Fn(Dynamic) -> Box> + Send + Sync + 'static +{ +} +#[cfg(feature = "sync")] +impl Box> + Send + Sync + 'static> IteratorCallback + for F +{ +} + +#[cfg(not(feature = "sync"))] +pub trait IteratorCallback: Fn(Dynamic) -> Box> + 'static {} +#[cfg(not(feature = "sync"))] +impl Box> + 'static> IteratorCallback for F {} + +/// A type representing the type of ABI of a native Rust function. +#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)] +pub enum NativeFunctionABI { + /// A pure function where all arguments are passed by value. + Pure, + /// An object method where the first argument is the object passed by mutable reference. + /// All other arguments are passed by value. + Method, +} + +/// A trait implemented by all native Rust functions that are callable by Rhai. +#[cfg(not(feature = "sync"))] +pub trait NativeCallable { + /// Get the ABI type of a native Rust function. + fn abi(&self) -> NativeFunctionABI; + /// Call a native Rust function. + fn call(&self, args: &mut FnCallArgs) -> Result>; +} + +/// A trait implemented by all native Rust functions that are callable by Rhai. +#[cfg(feature = "sync")] +pub trait NativeCallable: Send + Sync { + /// Get the ABI type of a native Rust function. + fn abi(&self) -> NativeFunctionABI; + /// Call a native Rust function. + fn call(&self, args: &mut FnCallArgs) -> Result>; +} + +/// A type encapsulating a native Rust function callable by Rhai. +pub struct NativeFunction(Box, NativeFunctionABI); + +impl NativeCallable for NativeFunction { + fn abi(&self) -> NativeFunctionABI { + self.1 + } + fn call(&self, args: &mut FnCallArgs) -> Result> { + (self.0)(args) + } +} + +impl From<(Box, NativeFunctionABI)> for NativeFunction { + fn from(func: (Box, NativeFunctionABI)) -> Self { + Self::new(func.0, func.1) + } +} +impl NativeFunction { + /// Create a new `NativeFunction`. + pub fn new(func: Box, abi: NativeFunctionABI) -> Self { + Self(func, abi) + } +} + +/// An external native Rust function. +#[cfg(not(feature = "sync"))] +pub type SharedNativeFunction = Rc>; +/// An external native Rust function. +#[cfg(feature = "sync")] +pub type SharedNativeFunction = Arc>; + +/// A type iterator function. +#[cfg(not(feature = "sync"))] +pub type SharedIteratorFunction = Rc>; +/// An external native Rust function. +#[cfg(feature = "sync")] +pub type SharedIteratorFunction = Arc>; diff --git a/src/fn_register.rs b/src/fn_register.rs index 9f798af1..8b91ea42 100644 --- a/src/fn_register.rs +++ b/src/fn_register.rs @@ -3,10 +3,10 @@ #![allow(non_snake_case)] use crate::any::{Dynamic, Variant}; -use crate::engine::{Engine, FnCallArgs}; +use crate::engine::Engine; +use crate::fn_native::{FnCallArgs, NativeFunctionABI::*}; +use crate::parser::FnAccess; use crate::result::EvalAltResult; -use crate::token::Position; -use crate::utils::calc_fn_spec; use crate::stdlib::{any::TypeId, boxed::Box, mem, string::ToString}; @@ -117,42 +117,30 @@ pub struct Mut(T); //pub struct Ref(T); /// Dereference into &mut. -#[inline] -pub fn by_ref(data: &mut Dynamic) -> &mut T { +#[inline(always)] +pub fn by_ref(data: &mut Dynamic) -> &mut T { // Directly cast the &mut Dynamic into &mut T to access the underlying data. data.downcast_mut::().unwrap() } /// Dereference into value. -#[inline] -pub fn by_value(data: &mut Dynamic) -> T { +#[inline(always)] +pub fn by_value(data: &mut Dynamic) -> T { // We consume the argument and then replace it with () - the argument is not supposed to be used again. // This way, we avoid having to clone the argument again, because it is already a clone when passed here. mem::take(data).cast::() } -/// 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 => $convert:expr),*) => { -// ^ function name -// ^ function pointer -// ^ result mapping function -// ^ function parameter generic type name (A, B, C etc.) -// ^ dereferencing function + ($fn:ident : $map:expr ; $($par:ident => $convert:expr),*) => { +// ^ 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))); - } + Box::new(move |args: &mut FnCallArgs| { + // The arguments are assumed to be of the correct number and types! #[allow(unused_variables, unused_mut)] let mut drain = args.iter_mut(); @@ -166,45 +154,41 @@ macro_rules! make_func { let r = $fn($($par),*); // Map the result - $map(r, pos) - }; + $map(r) + }) }; } /// To Dynamic mapping function. -#[inline] -pub fn map_dynamic( - data: T, - _pos: Position, -) -> Result> { +#[inline(always)] +pub fn map_dynamic(data: T) -> Result> { Ok(data.into_dynamic()) } /// To Dynamic mapping function. -#[inline] -pub fn map_identity(data: Dynamic, _pos: Position) -> Result> { +#[inline(always)] +pub fn map_identity(data: Dynamic) -> Result> { Ok(data) } /// To `Result>` mapping function. -#[inline] +#[inline(always)] 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); + def_register!(imp Pure;); }; - (imp $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => { - // ^ function parameter generic type name (A, B, C etc.) - // ^ function parameter marker type (T, Ref or Mut) - // ^ function parameter actual type (T, &T or &mut T) - // ^ dereferencing function + (imp $abi:expr ; $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => { + // ^ function ABI type + // ^ function parameter generic type name (A, B, C etc.) + // ^ function parameter marker type (T, Ref or Mut) + // ^ function parameter actual type (T, &T or &mut T) + // ^ dereferencing function impl< $($par: Variant + Clone,)* @@ -218,10 +202,10 @@ macro_rules! def_register { > RegisterFn for Engine { fn register_fn(&mut self, name: &str, f: FN) { - let fn_name = name.to_string(); - 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)); + self.global_module.set_fn(name.to_string(), $abi, FnAccess::Public, + &[$(TypeId::of::<$par>()),*], + make_func!(f : map_dynamic ; $($par => $clone),*) + ); } } @@ -236,10 +220,10 @@ macro_rules! def_register { > RegisterDynamicFn for Engine { fn register_dynamic_fn(&mut self, name: &str, f: FN) { - let fn_name = name.to_string(); - 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)); + self.global_module.set_fn(name.to_string(), $abi, FnAccess::Public, + &[$(TypeId::of::<$par>()),*], + make_func!(f : map_identity ; $($par => $clone),*) + ); } } @@ -255,20 +239,20 @@ macro_rules! def_register { > RegisterResultFn for Engine { fn register_result_fn(&mut self, name: &str, f: FN) { - let fn_name = name.to_string(); - 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)); + self.global_module.set_fn(name.to_string(), $abi, FnAccess::Public, + &[$(TypeId::of::<$par>()),*], + make_func!(f : map_result ; $($par => $clone),*) + ); } } //def_register!(imp_pop $($par => $mark => $param),*); }; ($p0:ident $(, $p:ident)*) => { - def_register!(imp $p0 => $p0 => $p0 => by_value $(, $p => $p => $p => by_value)*); - def_register!(imp $p0 => Mut<$p0> => &mut $p0 => by_ref $(, $p => $p => $p => by_value)*); - // handle the first parameter ^ first parameter passed through - // ^ others passed by value (by_value) + def_register!(imp Pure ; $p0 => $p0 => $p0 => by_value $(, $p => $p => $p => by_value)*); + def_register!(imp Method ; $p0 => Mut<$p0> => &mut $p0 => by_ref $(, $p => $p => $p => by_value)*); + // handle the first parameter ^ first parameter passed through + // ^ others passed by value (by_value) // Currently does not support first argument which is a reference, as there will be // conflicting implementations since &T: Any and T: Any cannot be distinguished diff --git a/src/lib.rs b/src/lib.rs index 1bdf8fd7..f5f1ad87 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,7 @@ mod engine; mod error; mod fn_call; mod fn_func; +mod fn_native; mod fn_register; mod module; mod optimize; @@ -84,13 +85,16 @@ mod result; mod scope; mod stdlib; mod token; +mod r#unsafe; mod utils; pub use any::Dynamic; pub use engine::Engine; pub use error::{ParseError, ParseErrorType}; pub use fn_call::FuncArgs; +pub use fn_native::NativeCallable; pub use fn_register::{RegisterDynamicFn, RegisterFn, RegisterResultFn}; +pub use module::Module; pub use parser::{AST, INT}; pub use result::EvalAltResult; pub use scope::Scope; @@ -110,7 +114,7 @@ pub use engine::Map; pub use parser::FLOAT; #[cfg(not(feature = "no_module"))] -pub use module::{Module, ModuleResolver}; +pub use module::ModuleResolver; #[cfg(not(feature = "no_module"))] pub mod module_resolvers { diff --git a/src/module.rs b/src/module.rs index bdb545b1..6e56a128 100644 --- a/src/module.rs +++ b/src/module.rs @@ -1,61 +1,69 @@ //! Module defining external-loaded modules for Rhai. -#![cfg(not(feature = "no_module"))] use crate::any::{Dynamic, Variant}; use crate::calc_fn_hash; -use crate::engine::{Engine, FnAny, FnCallArgs, FunctionsLib}; -use crate::parser::{FnDef, AST}; +use crate::engine::{Engine, FunctionsLib}; +use crate::fn_native::{ + FnAny, FnCallArgs, IteratorFn, NativeCallable, NativeFunction, NativeFunctionABI, + NativeFunctionABI::*, SharedIteratorFunction, SharedNativeFunction, +}; +use crate::parser::{FnAccess, FnDef, SharedFnDef, AST}; use crate::result::EvalAltResult; use crate::scope::{Entry as ScopeEntry, EntryType as ScopeEntryType, Scope}; -use crate::token::Position; -use crate::token::Token; -use crate::utils::StaticVec; +use crate::token::{Position, Token}; +use crate::utils::{StaticVec, EMPTY_TYPE_ID}; use crate::stdlib::{ any::TypeId, boxed::Box, collections::HashMap, - fmt, mem, + fmt, + iter::{empty, repeat}, + mem, + num::NonZeroUsize, ops::{Deref, DerefMut}, rc::Rc, string::{String, ToString}, sync::Arc, + vec, + vec::Vec, }; -/// A trait that encapsulates a module resolution service. -pub trait ModuleResolver { - /// Resolve a module based on a path string. - fn resolve( - &self, - engine: &Engine, - path: &str, - pos: Position, - ) -> Result>; -} +/// Default function access mode. +const DEF_ACCESS: FnAccess = FnAccess::Public; /// Return type of module-level Rust function. -type FuncReturn = Result>; +pub type FuncReturn = Result>; /// An imported module, which may contain variables, sub-modules, /// external Rust functions, and script-defined functions. /// /// Not available under the `no_module` feature. -#[derive(Default, Clone)] +#[derive(Clone, Default)] pub struct Module { /// Sub-modules. modules: HashMap, - /// Module variables, including sub-modules. + + /// Module variables. variables: HashMap, + /// Flattened collection of all module variables, including those in sub-modules. + all_variables: HashMap, + /// External Rust functions. - #[cfg(not(feature = "sync"))] - functions: HashMap>>, - /// External Rust functions. - #[cfg(feature = "sync")] - functions: HashMap>>, + functions: HashMap, SharedNativeFunction)>, + + /// Flattened collection of all external Rust functions, including those in sub-modules. + all_functions: HashMap, /// Script-defined functions. fn_lib: FunctionsLib, + + /// Flattened collection of all script-defined functions, including those in sub-modules. + all_fn_lib: FunctionsLib, + + /// Iterator functions, keyed by the type producing the iterator. + type_iterators: HashMap, } impl fmt::Debug for Module { @@ -86,6 +94,24 @@ impl Module { Default::default() } + /// Create a new module with a specified capacity for native Rust functions. + /// + /// # Examples + /// + /// ``` + /// use rhai::Module; + /// + /// let mut module = Module::new(); + /// module.set_var("answer", 42_i64); + /// assert_eq!(module.get_var_value::("answer").unwrap(), 42); + /// ``` + pub fn new_with_capacity(capacity: usize) -> Self { + Self { + functions: HashMap::with_capacity(capacity), + ..Default::default() + } + } + /// Does a variable exist in the module? /// /// # Examples @@ -113,7 +139,7 @@ impl Module { /// assert_eq!(module.get_var_value::("answer").unwrap(), 42); /// ``` pub fn get_var_value(&self, name: &str) -> Option { - self.get_var(name).and_then(|v| v.try_cast::()) + self.get_var(name).and_then(Dynamic::try_cast::) } /// Get a module variable as a `Dynamic`. @@ -131,11 +157,6 @@ impl Module { self.variables.get(name).cloned() } - /// Get a mutable reference to a module variable. - pub fn get_var_mut(&mut self, name: &str) -> Option<&mut Dynamic> { - self.variables.get_mut(name) - } - /// Set a variable into the module. /// /// If there is an existing variable of the same name, it is replaced. @@ -149,21 +170,22 @@ impl Module { /// module.set_var("answer", 42_i64); /// assert_eq!(module.get_var_value::("answer").unwrap(), 42); /// ``` - pub fn set_var, T: Into>(&mut self, name: K, value: T) { - self.variables.insert(name.into(), value.into()); + pub fn set_var, T: Variant + Clone>(&mut self, name: K, value: T) { + self.variables.insert(name.into(), Dynamic::from(value)); } /// Get a mutable reference to a modules-qualified variable. + /// + /// The `u64` hash is calculated by the function `crate::calc_fn_hash`. pub(crate) fn get_qualified_var_mut( &mut self, name: &str, - modules: &StaticVec<(String, Position)>, + hash_var: u64, pos: Position, ) -> Result<&mut Dynamic, Box> { - Ok(self - .get_qualified_module_mut(modules)? - .get_var_mut(name) - .ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.into(), pos)))?) + self.all_variables + .get_mut(&hash_var) + .ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.to_string(), pos))) } /// Does a sub-module exist in the module? @@ -232,26 +254,6 @@ impl Module { self.modules.insert(name.into(), sub_module.into()); } - /// Get a mutable reference to a modules chain. - /// The first module is always skipped and assumed to be the same as `self`. - pub(crate) fn get_qualified_module_mut( - &mut self, - modules: &StaticVec<(String, Position)>, - ) -> Result<&mut Module, Box> { - let mut drain = modules.iter(); - drain.next().unwrap(); // Skip first module - - let mut module = self; - - for (id, id_pos) in drain { - module = module - .get_sub_module_mut(id) - .ok_or_else(|| Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *id_pos)))?; - } - - Ok(module) - } - /// Does the particular Rust function exist in the module? /// /// The `u64` hash is calculated by the function `crate::calc_fn_hash`. @@ -266,22 +268,34 @@ impl Module { /// let hash = module.set_fn_0("calc", || Ok(42_i64)); /// assert!(module.contains_fn(hash)); /// ``` - pub fn contains_fn(&self, hash: u64) -> bool { - self.functions.contains_key(&hash) + pub fn contains_fn(&self, hash_fn: u64) -> bool { + self.functions.contains_key(&hash_fn) } /// Set a Rust function into the module, returning a hash key. /// /// If there is an existing Rust function of the same hash, it is replaced. - pub fn set_fn(&mut self, fn_name: &str, params: &[TypeId], func: Box) -> u64 { - let hash = calc_fn_hash(fn_name, params.iter().cloned()); + pub fn set_fn( + &mut self, + name: String, + abi: NativeFunctionABI, + access: FnAccess, + params: &[TypeId], + func: Box, + ) -> u64 { + let hash_fn = calc_fn_hash(empty(), &name, params.iter().cloned()); + + let f = Box::new(NativeFunction::from((func, abi))) as Box; #[cfg(not(feature = "sync"))] - self.functions.insert(hash, Rc::new(func)); + let func = Rc::new(f); #[cfg(feature = "sync")] - self.functions.insert(hash, Arc::new(func)); + let func = Arc::new(f); - hash + self.functions + .insert(hash_fn, (name, access, params.to_vec(), func)); + + hash_fn } /// Set a Rust function taking no parameters into the module, returning a hash key. @@ -297,19 +311,15 @@ impl Module { /// let hash = module.set_fn_0("calc", || Ok(42_i64)); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn set_fn_0>( + pub fn set_fn_0, T: Variant + Clone>( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn() -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn() -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |_: &mut FnCallArgs, pos| { - func() - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) - }; - let arg_types = &[]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let f = move |_: &mut FnCallArgs| func().map(Dynamic::from); + let arg_types = []; + self.set_fn(name.into(), Pure, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking one parameter into the module, returning a hash key. @@ -325,19 +335,16 @@ impl Module { /// let hash = module.set_fn_1("calc", |x: i64| Ok(x + 1)); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn set_fn_1>( + pub fn set_fn_1, A: Variant + Clone, T: Variant + Clone>( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(A) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(A) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { - func(mem::take(args[0]).cast::()) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) - }; - let arg_types = &[TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let f = + move |args: &mut FnCallArgs| func(mem::take(args[0]).cast::()).map(Dynamic::from); + let arg_types = [TypeId::of::()]; + self.set_fn(name.into(), Pure, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking one mutable parameter into the module, returning a hash key. @@ -353,19 +360,17 @@ impl Module { /// let hash = module.set_fn_1_mut("calc", |x: &mut i64| { *x += 1; Ok(*x) }); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn set_fn_1_mut>( + pub fn set_fn_1_mut, A: Variant + Clone, T: Variant + Clone>( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(&mut A) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(&mut A) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { - func(args[0].downcast_mut::().unwrap()) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) + let f = move |args: &mut FnCallArgs| { + func(args[0].downcast_mut::().unwrap()).map(Dynamic::from) }; - let arg_types = &[TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let arg_types = [TypeId::of::()]; + self.set_fn(name.into(), Method, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking two parameters into the module, returning a hash key. @@ -383,22 +388,20 @@ impl Module { /// }); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn set_fn_2>( + pub fn set_fn_2, A: Variant + Clone, B: Variant + Clone, T: Variant + Clone>( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(A, B) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(A, B) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { + let f = move |args: &mut FnCallArgs| { let a = mem::take(args[0]).cast::(); let b = mem::take(args[1]).cast::(); - func(a, b) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) + func(a, b).map(Dynamic::from) }; - let arg_types = &[TypeId::of::(), TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let arg_types = [TypeId::of::(), TypeId::of::()]; + self.set_fn(name.into(), Pure, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking two parameters (the first one mutable) into the module, @@ -415,22 +418,25 @@ impl Module { /// }); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn set_fn_2_mut>( + pub fn set_fn_2_mut< + K: Into, + A: Variant + Clone, + B: Variant + Clone, + T: Variant + Clone, + >( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(&mut A, B) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { + let f = move |args: &mut FnCallArgs| { let b = mem::take(args[1]).cast::(); let a = args[0].downcast_mut::().unwrap(); - func(a, b) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) + func(a, b).map(Dynamic::from) }; - let arg_types = &[TypeId::of::(), TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let arg_types = [TypeId::of::(), TypeId::of::()]; + self.set_fn(name.into(), Method, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking three parameters into the module, returning a hash key. @@ -449,27 +455,26 @@ impl Module { /// assert!(module.get_fn(hash).is_some()); /// ``` pub fn set_fn_3< + K: Into, A: Variant + Clone, B: Variant + Clone, C: Variant + Clone, - T: Into, + T: Variant + Clone, >( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(A, B, C) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(A, B, C) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { + let f = move |args: &mut FnCallArgs| { let a = mem::take(args[0]).cast::(); let b = mem::take(args[1]).cast::(); let c = mem::take(args[2]).cast::(); - func(a, b, c) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) + func(a, b, c).map(Dynamic::from) }; - let arg_types = &[TypeId::of::(), TypeId::of::(), TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let arg_types = [TypeId::of::(), TypeId::of::(), TypeId::of::()]; + self.set_fn(name.into(), Pure, DEF_ACCESS, &arg_types, Box::new(f)) } /// Set a Rust function taking three parameters (the first one mutable) into the module, @@ -489,27 +494,26 @@ impl Module { /// assert!(module.get_fn(hash).is_some()); /// ``` pub fn set_fn_3_mut< + K: Into, A: Variant + Clone, B: Variant + Clone, C: Variant + Clone, - T: Into, + T: Variant + Clone, >( &mut self, - fn_name: &str, + name: K, #[cfg(not(feature = "sync"))] func: impl Fn(&mut A, B, C) -> FuncReturn + 'static, #[cfg(feature = "sync")] func: impl Fn(&mut A, B, C) -> FuncReturn + Send + Sync + 'static, ) -> u64 { - let f = move |args: &mut FnCallArgs, pos| { + let f = move |args: &mut FnCallArgs| { let b = mem::take(args[1]).cast::(); let c = mem::take(args[2]).cast::(); let a = args[0].downcast_mut::().unwrap(); - func(a, b, c) - .map(|v| v.into()) - .map_err(|err| EvalAltResult::set_position(err, pos)) + func(a, b, c).map(Dynamic::from) }; - let arg_types = &[TypeId::of::(), TypeId::of::(), TypeId::of::()]; - self.set_fn(fn_name, arg_types, Box::new(f)) + let arg_types = [TypeId::of::(), TypeId::of::(), TypeId::of::()]; + self.set_fn(name.into(), Method, DEF_ACCESS, &arg_types, Box::new(f)) } /// Get a Rust function. @@ -526,8 +530,8 @@ impl Module { /// let hash = module.set_fn_1("calc", |x: i64| Ok(x + 1)); /// assert!(module.get_fn(hash).is_some()); /// ``` - pub fn get_fn(&self, hash: u64) -> Option<&Box> { - self.functions.get(&hash).map(|v| v.as_ref()) + pub fn get_fn(&self, hash_fn: u64) -> Option<&Box> { + self.functions.get(&hash_fn).map(|(_, _, _, v)| v.as_ref()) } /// Get a modules-qualified function. @@ -537,52 +541,24 @@ impl Module { pub(crate) fn get_qualified_fn( &mut self, name: &str, - hash: u64, - modules: &StaticVec<(String, Position)>, - pos: Position, - ) -> Result<&Box, Box> { - Ok(self - .get_qualified_module_mut(modules)? - .get_fn(hash) + hash_fn_native: u64, + ) -> Result<&Box, Box> { + self.all_functions + .get(&hash_fn_native) + .map(|f| f.as_ref()) .ok_or_else(|| { - let mut fn_name: String = Default::default(); - - modules.iter().for_each(|(n, _)| { - fn_name.push_str(n); - fn_name.push_str(Token::DoubleColon.syntax().as_ref()); - }); - - fn_name.push_str(name); - - Box::new(EvalAltResult::ErrorFunctionNotFound(fn_name, pos)) - })?) + Box::new(EvalAltResult::ErrorFunctionNotFound( + name.to_string(), + Position::none(), + )) + }) } - /// Get the script-defined functions. + /// Get a modules-qualified script-defined functions. /// - /// # Examples - /// - /// ``` - /// use rhai::Module; - /// - /// let mut module = Module::new(); - /// assert_eq!(module.get_fn_lib().len(), 0); - /// ``` - pub fn get_fn_lib(&self) -> &FunctionsLib { - &self.fn_lib - } - - /// Get a modules-qualified functions library. - pub(crate) fn get_qualified_fn_lib( - &mut self, - name: &str, - args: usize, - modules: &StaticVec<(String, Position)>, - ) -> Result, Box> { - Ok(self - .get_qualified_module_mut(modules)? - .fn_lib - .get_function(name, args)) + /// The `u64` hash is calculated by the function `crate::calc_fn_hash`. + pub(crate) fn get_qualified_scripted_fn(&mut self, hash_fn_def: u64) -> Option<&FnDef> { + self.all_fn_lib.get_function(hash_fn_def) } /// Create a new `Module` by evaluating an `AST`. @@ -591,20 +567,18 @@ impl Module { /// /// ``` /// # fn main() -> Result<(), Box> { - /// use rhai::{Engine, Module}; + /// use rhai::{Engine, Module, Scope}; /// /// let engine = Engine::new(); - /// let ast = engine.compile("let answer = 42;")?; - /// let module = Module::eval_ast_as_new(&ast, &engine)?; + /// let ast = engine.compile("let answer = 42; export answer;")?; + /// let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?; /// assert!(module.contains_var("answer")); /// assert_eq!(module.get_var_value::("answer").unwrap(), 42); /// # Ok(()) /// # } /// ``` - pub fn eval_ast_as_new(ast: &AST, engine: &Engine) -> FuncReturn { - // Use new scope - let mut scope = Scope::new(); - + #[cfg(not(feature = "no_module"))] + pub fn eval_ast_as_new(mut scope: Scope, ast: &AST, engine: &Engine) -> FuncReturn { // Run the script engine.eval_ast_with_scope_raw(&mut scope, &ast)?; @@ -613,19 +587,21 @@ impl Module { scope.into_iter().for_each( |ScopeEntry { - name, typ, value, .. + typ, value, alias, .. }| { match typ { - // Variables left in the scope become module variables - ScopeEntryType::Normal | ScopeEntryType::Constant => { - module.variables.insert(name.into_owned(), value); + // Variables with an alias left in the scope become module variables + ScopeEntryType::Normal | ScopeEntryType::Constant if alias.is_some() => { + module.variables.insert(*alias.unwrap(), value); } // Modules left in the scope become sub-modules - ScopeEntryType::Module => { + ScopeEntryType::Module if alias.is_some() => { module .modules - .insert(name.into_owned(), value.cast::()); + .insert(*alias.unwrap(), value.cast::()); } + // Variables and modules with no alias are private and not exported + _ => (), } }, ); @@ -634,9 +610,195 @@ impl Module { Ok(module) } + + /// Scan through all the sub-modules in the `Module` build an index of all + /// variables and external Rust functions via hashing. + pub(crate) fn index_all_sub_modules(&mut self) { + // Collect a particular module. + fn index_module<'a>( + module: &'a mut Module, + qualifiers: &mut Vec<&'a str>, + variables: &mut Vec<(u64, Dynamic)>, + functions: &mut Vec<(u64, SharedNativeFunction)>, + fn_lib: &mut Vec<(u64, SharedFnDef)>, + ) { + for (name, m) in module.modules.iter_mut() { + // Index all the sub-modules first. + qualifiers.push(name); + index_module(m, qualifiers, variables, functions, fn_lib); + qualifiers.pop(); + } + + // Index all variables + for (var_name, value) in module.variables.iter() { + // Qualifiers + variable name + let hash_var = calc_fn_hash(qualifiers.iter().map(|&v| v), var_name, empty()); + variables.push((hash_var, value.clone())); + } + // Index all Rust functions + for (name, access, params, func) in module.functions.values() { + match access { + // Private functions are not exported + FnAccess::Private => continue, + FnAccess::Public => (), + } + // Rust functions are indexed in two steps: + // 1) Calculate a hash in a similar manner to script-defined functions, + // i.e. qualifiers + function name + dummy parameter types (one for each parameter). + let hash_fn_def = calc_fn_hash( + qualifiers.iter().map(|&v| v), + name, + repeat(EMPTY_TYPE_ID()).take(params.len()), + ); + // 2) Calculate a second hash with no qualifiers, empty function name, and + // the actual list of parameter `TypeId`'.s + let hash_fn_args = calc_fn_hash(empty(), "", params.iter().cloned()); + // 3) The final hash is the XOR of the two hashes. + let hash_fn_native = hash_fn_def ^ hash_fn_args; + + functions.push((hash_fn_native, func.clone())); + } + // Index all script-defined functions + for fn_def in module.fn_lib.values() { + match fn_def.access { + // Private functions are not exported + FnAccess::Private => continue, + DEF_ACCESS => (), + } + // Qualifiers + function name + placeholders (one for each parameter) + let hash_fn_def = calc_fn_hash( + qualifiers.iter().map(|&v| v), + &fn_def.name, + repeat(EMPTY_TYPE_ID()).take(fn_def.params.len()), + ); + fn_lib.push((hash_fn_def, fn_def.clone())); + } + } + + let mut variables = Vec::new(); + let mut functions = Vec::new(); + let mut fn_lib = Vec::new(); + + index_module( + self, + &mut vec!["root"], + &mut variables, + &mut functions, + &mut fn_lib, + ); + + self.all_variables = variables.into_iter().collect(); + self.all_functions = functions.into_iter().collect(); + self.all_fn_lib = fn_lib.into(); + } + + /// Does a type iterator exist in the module? + pub fn contains_iter(&self, id: TypeId) -> bool { + self.type_iterators.contains_key(&id) + } + + /// Set a type iterator into the module. + pub fn set_iter(&mut self, typ: TypeId, func: Box) { + #[cfg(not(feature = "sync"))] + self.type_iterators.insert(typ, Rc::new(func)); + #[cfg(feature = "sync")] + self.type_iterators.insert(typ, Arc::new(func)); + } + + /// Get the specified type iterator. + pub fn get_iter(&self, id: TypeId) -> Option<&SharedIteratorFunction> { + self.type_iterators.get(&id) + } +} + +/// A chain of module names to qualify a variable or function call. +/// A `u64` hash key is kept for quick search purposes. +/// +/// A `StaticVec` is used because most module-level access contains only one level, +/// and it is wasteful to always allocate a `Vec` with one element. +#[derive(Clone, Eq, PartialEq, Hash, Default)] +pub struct ModuleRef(StaticVec<(String, Position)>, Option); + +impl fmt::Debug for ModuleRef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f)?; + + if let Some(index) = self.1 { + write!(f, " -> {}", index) + } else { + Ok(()) + } + } +} + +impl Deref for ModuleRef { + type Target = StaticVec<(String, Position)>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for ModuleRef { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Display for ModuleRef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (m, _) in self.0.iter() { + write!(f, "{}{}", m, Token::DoubleColon.syntax())?; + } + Ok(()) + } +} + +impl From> for ModuleRef { + fn from(modules: StaticVec<(String, Position)>) -> Self { + Self(modules, None) + } +} + +impl ModuleRef { + pub(crate) fn index(&self) -> Option { + self.1 + } + pub(crate) fn set_index(&mut self, index: Option) { + self.1 = index + } +} + +/// A trait that encapsulates a module resolution service. +#[cfg(not(feature = "no_module"))] +#[cfg(not(feature = "sync"))] +pub trait ModuleResolver { + /// Resolve a module based on a path string. + fn resolve( + &self, + engine: &Engine, + scope: Scope, + path: &str, + pos: Position, + ) -> Result>; +} + +/// A trait that encapsulates a module resolution service. +#[cfg(not(feature = "no_module"))] +#[cfg(feature = "sync")] +pub trait ModuleResolver: Send + Sync { + /// Resolve a module based on a path string. + fn resolve( + &self, + engine: &Engine, + scope: Scope, + path: &str, + pos: Position, + ) -> Result>; } /// Re-export module resolvers. +#[cfg(not(feature = "no_module"))] pub mod resolvers { #[cfg(not(feature = "no_std"))] pub use super::file::FileModuleResolver; @@ -644,6 +806,7 @@ pub mod resolvers { } /// Script file-based module resolver. +#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_std"))] mod file { use super::*; @@ -669,12 +832,18 @@ mod file { /// let mut engine = Engine::new(); /// engine.set_module_resolver(Some(resolver)); /// ``` - #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Default)] + #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Clone, Hash)] pub struct FileModuleResolver { path: PathBuf, extension: String, } + impl Default for FileModuleResolver { + fn default() -> Self { + Self::new_with_path(PathBuf::default()) + } + } + impl FileModuleResolver { /// Create a new `FileModuleResolver` with a specific base path. /// @@ -740,12 +909,23 @@ mod file { pub fn new() -> Self { Default::default() } + + /// Create a `Module` from a file path. + pub fn create_module>( + &self, + engine: &Engine, + scope: Scope, + path: &str, + ) -> Result> { + self.resolve(engine, scope, path, Default::default()) + } } impl ModuleResolver for FileModuleResolver { fn resolve( &self, engine: &Engine, + scope: Scope, path: &str, pos: Position, ) -> Result> { @@ -757,15 +937,15 @@ mod file { // Compile it let ast = engine .compile_file(file_path) - .map_err(|err| EvalAltResult::set_position(err, pos))?; + .map_err(|err| err.new_position(pos))?; - Module::eval_ast_as_new(&ast, engine) - .map_err(|err| EvalAltResult::set_position(err, pos)) + Module::eval_ast_as_new(scope, &ast, engine).map_err(|err| err.new_position(pos)) } } } /// Static module resolver. +#[cfg(not(feature = "no_module"))] mod stat { use super::*; @@ -828,13 +1008,14 @@ mod stat { fn resolve( &self, _: &Engine, + _: Scope, path: &str, pos: Position, ) -> Result> { self.0 .get(path) .cloned() - .ok_or_else(|| Box::new(EvalAltResult::ErrorModuleNotFound(path.to_string(), pos))) + .ok_or_else(|| Box::new(EvalAltResult::ErrorModuleNotFound(path.into(), pos))) } } } diff --git a/src/optimize.rs b/src/optimize.rs index 33765a56..df385b74 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -1,10 +1,11 @@ use crate::any::Dynamic; use crate::calc_fn_hash; use crate::engine::{ - Engine, FnAny, FnCallArgs, FunctionsLib, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_PRINT, - KEYWORD_TYPE_OF, + Engine, FunctionsLib, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_PRINT, KEYWORD_TYPE_OF, }; -use crate::packages::PackageLibrary; +use crate::fn_native::FnCallArgs; +use crate::module::Module; +use crate::packages::PackagesCollection; 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}; @@ -13,6 +14,7 @@ use crate::token::Position; use crate::stdlib::{ boxed::Box, collections::HashMap, + iter::empty, string::{String, ToString}, vec, vec::Vec, @@ -94,7 +96,7 @@ impl<'a> State<'a> { } /// Add a new constant to the list. pub fn push_constant(&mut self, name: &str, value: Expr) { - self.constants.push((name.to_string(), value)) + self.constants.push((name.into(), value)) } /// Look up a constant from the list. pub fn find_constant(&self, name: &str) -> Option<&Expr> { @@ -110,88 +112,84 @@ impl<'a> State<'a> { /// Call a registered function fn call_fn( - packages: &Vec, - functions: &HashMap>, + packages: &PackagesCollection, + global_module: &Module, 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())); + let hash = calc_fn_hash(empty(), fn_name, args.iter().map(|a| a.type_id())); - functions - .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)) + global_module + .get_fn(hash) + .or_else(|| packages.get_fn(hash)) + .map(|func| func.call(args)) .transpose() + .map_err(|err| err.new_position(pos)) } /// Optimize a statement. fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) -> Stmt { match stmt { // if expr { Noop } - Stmt::IfThenElse(expr, if_block, None) if matches!(*if_block, Stmt::Noop(_)) => { + Stmt::IfThenElse(x) if matches!(x.1, Stmt::Noop(_)) => { state.set_dirty(); - let pos = expr.position(); - let expr = optimize_expr(*expr, state); + let pos = x.0.position(); + let expr = optimize_expr(x.0, state); if preserve_result { // -> { expr, Noop } - Stmt::Block(vec![Stmt::Expr(Box::new(expr)), *if_block], pos) + Stmt::Block(Box::new((vec![Stmt::Expr(Box::new(expr)), x.1], pos))) } else { // -> expr Stmt::Expr(Box::new(expr)) } } // if expr { if_block } - Stmt::IfThenElse(expr, if_block, None) => match *expr { + Stmt::IfThenElse(x) if x.2.is_none() => match x.0 { // if false { if_block } -> Noop Expr::False(pos) => { state.set_dirty(); Stmt::Noop(pos) } // if true { if_block } -> if_block - Expr::True(_) => optimize_stmt(*if_block, state, true), + Expr::True(_) => optimize_stmt(x.1, state, true), // if expr { if_block } - expr => Stmt::IfThenElse( - Box::new(optimize_expr(expr, state)), - Box::new(optimize_stmt(*if_block, state, true)), + expr => Stmt::IfThenElse(Box::new(( + optimize_expr(expr, state), + optimize_stmt(x.1, state, true), None, - ), + ))), }, // if expr { if_block } else { else_block } - Stmt::IfThenElse(expr, if_block, Some(else_block)) => match *expr { + Stmt::IfThenElse(x) if x.2.is_some() => match x.0 { // if false { if_block } else { else_block } -> else_block - Expr::False(_) => optimize_stmt(*else_block, state, true), + Expr::False(_) => optimize_stmt(x.2.unwrap(), state, true), // if true { if_block } else { else_block } -> if_block - Expr::True(_) => optimize_stmt(*if_block, state, true), + Expr::True(_) => optimize_stmt(x.1, state, true), // if expr { if_block } else { else_block } - expr => Stmt::IfThenElse( - Box::new(optimize_expr(expr, state)), - Box::new(optimize_stmt(*if_block, state, true)), - match optimize_stmt(*else_block, state, true) { + expr => Stmt::IfThenElse(Box::new(( + optimize_expr(expr, state), + optimize_stmt(x.1, state, true), + match optimize_stmt(x.2.unwrap(), state, true) { Stmt::Noop(_) => None, // Noop -> no else block - stmt => Some(Box::new(stmt)), + stmt => Some(stmt), }, - ), + ))), }, // while expr { block } - Stmt::While(expr, block) => match *expr { + Stmt::While(x) => match x.0 { // while false { block } -> Noop Expr::False(pos) => { state.set_dirty(); Stmt::Noop(pos) } // while true { block } -> loop { block } - Expr::True(_) => Stmt::Loop(Box::new(optimize_stmt(*block, state, false))), + Expr::True(_) => Stmt::Loop(Box::new(optimize_stmt(x.1, state, false))), // while expr { block } - expr => match optimize_stmt(*block, state, false) { + expr => match optimize_stmt(x.1, state, false) { // while expr { break; } -> { expr; } Stmt::Break(pos) => { // Only a single break statement - turn into running the guard expression once @@ -200,10 +198,10 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - if preserve_result { statements.push(Stmt::Noop(pos)) } - Stmt::Block(statements, pos) + Stmt::Block(Box::new((statements, pos))) } // while expr { block } - stmt => Stmt::While(Box::new(optimize_expr(expr, state)), Box::new(stmt)), + stmt => Stmt::While(Box::new((optimize_expr(expr, state), stmt))), }, }, // loop { block } @@ -218,38 +216,40 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - stmt => Stmt::Loop(Box::new(stmt)), }, // for id in expr { block } - Stmt::For(id, expr, block) => Stmt::For( - id, - Box::new(optimize_expr(*expr, state)), - Box::new(optimize_stmt(*block, state, false)), - ), + Stmt::For(x) => Stmt::For(Box::new(( + x.0, + optimize_expr(x.1, state), + optimize_stmt(x.2, state, false), + ))), // let id = expr; - Stmt::Let(id, Some(expr), pos) => { - Stmt::Let(id, Some(Box::new(optimize_expr(*expr, state))), pos) + Stmt::Let(x) if x.1.is_some() => { + Stmt::Let(Box::new((x.0, Some(optimize_expr(x.1.unwrap(), state))))) } // let id; - Stmt::Let(_, None, _) => stmt, + stmt @ Stmt::Let(_) => stmt, // import expr as id; - Stmt::Import(expr, id, pos) => Stmt::Import(Box::new(optimize_expr(*expr, state)), id, pos), + Stmt::Import(x) => Stmt::Import(Box::new((optimize_expr(x.0, state), x.1))), // { block } - Stmt::Block(block, pos) => { - let orig_len = block.len(); // Original number of statements in the block, for change detection + Stmt::Block(x) => { + let orig_len = x.0.len(); // Original number of statements in the block, for change detection let orig_constants_len = state.constants.len(); // Original number of constants in the state, for restore later + let pos = x.1; // Optimize each statement in the block - let mut result: Vec<_> = block - .into_iter() - .map(|stmt| match stmt { - // Add constant into the state - Stmt::Const(name, value, pos) => { - state.push_constant(&name, *value); - state.set_dirty(); - Stmt::Noop(pos) // No need to keep constants - } - // Optimize the statement - _ => optimize_stmt(stmt, state, preserve_result), - }) - .collect(); + let mut result: Vec<_> = + x.0.into_iter() + .map(|stmt| match stmt { + // Add constant into the state + Stmt::Const(v) => { + let ((name, pos), expr) = *v; + state.push_constant(&name, expr); + state.set_dirty(); + Stmt::Noop(pos) // No need to keep constants + } + // Optimize the statement + _ => optimize_stmt(stmt, state, preserve_result), + }) + .collect(); // Remove all raw expression statements that are pure except for the very last statement let last_stmt = if preserve_result { result.pop() } else { None }; @@ -267,9 +267,9 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - while let Some(expr) = result.pop() { match expr { - Stmt::Let(_, None, _) => removed = true, - Stmt::Let(_, Some(val_expr), _) => removed = val_expr.is_pure(), - Stmt::Import(expr, _, _) => removed = expr.is_pure(), + Stmt::Let(x) if x.1.is_none() => removed = true, + Stmt::Let(x) if x.1.is_some() => removed = x.1.unwrap().is_pure(), + Stmt::Import(x) => removed = x.0.is_pure(), _ => { result.push(expr); break; @@ -301,7 +301,7 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - } match stmt { - Stmt::ReturnWithVal(_, _, _) | Stmt::Break(_) => { + Stmt::ReturnWithVal(_) | Stmt::Break(_) => { dead_code = true; } _ => (), @@ -325,20 +325,20 @@ fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) - Stmt::Noop(pos) } // Only one let/import statement - leave it alone - [Stmt::Let(_, _, _)] | [Stmt::Import(_, _, _)] => Stmt::Block(result, pos), + [Stmt::Let(_)] | [Stmt::Import(_)] => Stmt::Block(Box::new((result, pos))), // Only one statement - promote [_] => { state.set_dirty(); result.remove(0) } - _ => Stmt::Block(result, pos), + _ => Stmt::Block(Box::new((result, pos))), } } // expr; Stmt::Expr(expr) => Stmt::Expr(Box::new(optimize_expr(*expr, state))), // return expr; - Stmt::ReturnWithVal(Some(expr), is_return, pos) => { - Stmt::ReturnWithVal(Some(Box::new(optimize_expr(*expr, state))), is_return, pos) + Stmt::ReturnWithVal(x) if x.1.is_some() => { + Stmt::ReturnWithVal(Box::new((x.0, Some(optimize_expr(x.1.unwrap(), state))))) } // All other statements - skip stmt => stmt, @@ -352,11 +352,11 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { match expr { // ( stmt ) - Expr::Stmt(stmt, pos) => match optimize_stmt(*stmt, state, true) { + Expr::Stmt(x) => match optimize_stmt(x.0, state, true) { // ( Noop ) -> () Stmt::Noop(_) => { state.set_dirty(); - Expr::Unit(pos) + Expr::Unit(x.1) } // ( expr ) -> expr Stmt::Expr(expr) => { @@ -364,150 +364,129 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { *expr } // ( stmt ) - stmt => Expr::Stmt(Box::new(stmt), pos), + stmt => Expr::Stmt(Box::new((stmt, x.1))), }, // id = expr - Expr::Assignment(id, expr, pos) => match *expr { + Expr::Assignment(x) => match x.1 { //id = id2 = expr2 - Expr::Assignment(id2, expr2, pos2) => match (*id, *id2) { + Expr::Assignment(x2) => match (x.0, x2.0) { // var = var = expr2 -> var = expr2 - (Expr::Variable(var, None, sp, _), Expr::Variable(var2, None, sp2, _)) - if var == var2 && sp == sp2 => + (Expr::Variable(a), Expr::Variable(b)) + if a.1.is_none() && b.1.is_none() && a.0 == b.0 && a.3 == b.3 => { // Assignment to the same variable - fold state.set_dirty(); - Expr::Assignment(Box::new(Expr::Variable(var, None, sp, pos)), Box::new(optimize_expr(*expr2, state)), pos) + Expr::Assignment(Box::new((Expr::Variable(a), optimize_expr(x2.1, state), x.2))) } // id1 = id2 = expr2 - (id1, id2) => Expr::Assignment( - Box::new(id1), - Box::new(Expr::Assignment( - Box::new(id2), - Box::new(optimize_expr(*expr2, state)), - pos2, - )), - pos, - ), + (id1, id2) => { + Expr::Assignment(Box::new(( + id1, Expr::Assignment(Box::new((id2, optimize_expr(x2.1, state), x2.2))), x.2, + ))) + } }, // id = expr - expr => Expr::Assignment(id, Box::new(optimize_expr(expr, state)), pos), + expr => Expr::Assignment(Box::new((x.0, optimize_expr(expr, state), x.2))), }, // lhs.rhs #[cfg(not(feature = "no_object"))] - Expr::Dot(lhs, rhs, pos) => match (*lhs, *rhs) { + Expr::Dot(x) => match (x.0, x.1) { // map.string - (Expr::Map(items, pos), Expr::Property(s, _)) if items.iter().all(|(_, x, _)| x.is_pure()) => { + (Expr::Map(m), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => { + let ((prop, _, _), _) = p.as_ref(); // 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) - .map(|(_, expr, _)| expr.set_position(pos)) + let pos = m.1; + m.0.into_iter().find(|((name, _), _)| name == prop) + .map(|(_, expr)| expr.set_position(pos)) .unwrap_or_else(|| Expr::Unit(pos)) } // lhs.rhs - (lhs, rhs) => Expr::Dot( - Box::new(optimize_expr(lhs, state)), - Box::new(optimize_expr(rhs, state)), - pos, - ) + (lhs, rhs) => Expr::Dot(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))) } // lhs[rhs] #[cfg(not(feature = "no_index"))] - Expr::Index(lhs, rhs, pos) => match (*lhs, *rhs) { + Expr::Index(x) => match (x.0, x.1) { // array[int] - (Expr::Array(mut items, pos), Expr::IntegerConstant(i, _)) - if i >= 0 && (i as usize) < items.len() && items.iter().all(Expr::is_pure) => + (Expr::Array(mut a), Expr::IntegerConstant(i)) + if i.0 >= 0 && (i.0 as usize) < a.0.len() && a.0.iter().all(Expr::is_pure) => { // Array literal where everything is pure - promote the indexed item. // All other items can be thrown away. state.set_dirty(); - items.remove(i as usize).set_position(pos) + a.0.remove(i.0 as usize).set_position(a.1) } // map[string] - (Expr::Map(items, pos), Expr::StringConstant(s, _)) if items.iter().all(|(_, x, _)| x.is_pure()) => { + (Expr::Map(m), Expr::StringConstant(s)) if m.0.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) - .map(|(_, expr, _)| expr.set_position(pos)) + let pos = m.1; + m.0.into_iter().find(|((name, _), _)| name == &s.0) + .map(|(_, expr)| expr.set_position(pos)) .unwrap_or_else(|| Expr::Unit(pos)) } // string[int] - (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if i >= 0 && (i as usize) < s.chars().count() => { + (Expr::StringConstant(s), Expr::IntegerConstant(i)) if i.0 >= 0 && (i.0 as usize) < s.0.chars().count() => { // String literal indexing - get the character state.set_dirty(); - Expr::CharConstant(s.chars().nth(i as usize).expect("should get char"), pos) + Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).expect("should get char"), s.1))) } // lhs[rhs] - (lhs, rhs) => Expr::Index( - Box::new(optimize_expr(lhs, state)), - Box::new(optimize_expr(rhs, state)), - pos, - ), + (lhs, rhs) => Expr::Index(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))), }, // [ items .. ] #[cfg(not(feature = "no_index"))] - Expr::Array(items, pos) => Expr::Array(items - .into_iter() - .map(|expr| optimize_expr(expr, state)) - .collect(), pos), + Expr::Array(a) => Expr::Array(Box::new((a.0 + .into_iter() + .map(|expr| optimize_expr(expr, state)) + .collect(), a.1))), // [ items .. ] #[cfg(not(feature = "no_object"))] - Expr::Map(items, pos) => Expr::Map(items - .into_iter() - .map(|(key, expr, pos)| (key, optimize_expr(expr, state), pos)) - .collect(), pos), + Expr::Map(m) => Expr::Map(Box::new((m.0 + .into_iter() + .map(|((key, pos), expr)| ((key, pos), optimize_expr(expr, state))) + .collect(), m.1))), // lhs in rhs - Expr::In(lhs, rhs, pos) => match (*lhs, *rhs) { + Expr::In(x) => match (x.0, x.1) { // "xxx" in "xxxxx" - (Expr::StringConstant(lhs, pos), Expr::StringConstant(rhs, _)) => { + (Expr::StringConstant(a), Expr::StringConstant(b)) => { state.set_dirty(); - if rhs.contains(&lhs) { - Expr::True(pos) - } else { - Expr::False(pos) - } + if b.0.contains(&a.0) { Expr::True(a.1) } else { Expr::False(a.1) } } // 'x' in "xxxxx" - (Expr::CharConstant(lhs, pos), Expr::StringConstant(rhs, _)) => { + (Expr::CharConstant(a), Expr::StringConstant(b)) => { state.set_dirty(); - if rhs.contains(&lhs.to_string()) { - Expr::True(pos) - } else { - Expr::False(pos) - } + if b.0.contains(a.0) { Expr::True(a.1) } else { Expr::False(a.1) } } // "xxx" in #{...} - (Expr::StringConstant(lhs, pos), Expr::Map(items, _)) => { + (Expr::StringConstant(a), Expr::Map(b)) => { state.set_dirty(); - if items.iter().find(|(name, _, _)| name == &lhs).is_some() { - Expr::True(pos) + if b.0.iter().find(|((name, _), _)| name == &a.0).is_some() { + Expr::True(a.1) } else { - Expr::False(pos) + Expr::False(a.1) } } // 'x' in #{...} - (Expr::CharConstant(lhs, pos), Expr::Map(items, _)) => { + (Expr::CharConstant(a), Expr::Map(b)) => { state.set_dirty(); - let lhs = lhs.to_string(); + let ch = a.0.to_string(); - if items.iter().find(|(name, _, _)| name == &lhs).is_some() { - Expr::True(pos) + if b.0.iter().find(|((name, _), _)| name == &ch).is_some() { + Expr::True(a.1) } else { - Expr::False(pos) + Expr::False(a.1) } } // lhs in rhs - (lhs, rhs) => Expr::In( - Box::new(optimize_expr(lhs, state)), - Box::new(optimize_expr(rhs, state)), - pos - ), + (lhs, rhs) => Expr::In(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))), }, // lhs && rhs - Expr::And(lhs, rhs, pos) => match (*lhs, *rhs) { + Expr::And(x) => match (x.0, x.1) { // true && rhs -> rhs (Expr::True(_), rhs) => { state.set_dirty(); @@ -524,14 +503,10 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { optimize_expr(lhs, state) } // lhs && rhs - (lhs, rhs) => Expr::And( - Box::new(optimize_expr(lhs, state)), - Box::new(optimize_expr(rhs, state)), - pos - ), + (lhs, rhs) => Expr::And(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))), }, // lhs || rhs - Expr::Or(lhs, rhs, pos) => match (*lhs, *rhs) { + Expr::Or(x) => match (x.0, x.1) { // false || rhs -> rhs (Expr::False(_), rhs) => { state.set_dirty(); @@ -548,22 +523,28 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { optimize_expr(lhs, state) } // lhs || rhs - (lhs, rhs) => Expr::Or(Box::new(optimize_expr(lhs, state)), Box::new(optimize_expr(rhs, state)), pos), + (lhs, rhs) => Expr::Or(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))), }, // Do not call some special keywords - Expr::FnCall(id, None, args, def_value, pos) if DONT_EVAL_KEYWORDS.contains(&id.as_ref().as_ref())=> - Expr::FnCall(id, None, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), + Expr::FnCall(mut x) if DONT_EVAL_KEYWORDS.contains(&(x.0).0.as_ref())=> { + x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect(); + Expr::FnCall(x) + } // Eagerly call functions - Expr::FnCall(id, None, args, def_value, pos) - if state.optimization_level == OptimizationLevel::Full // full optimizations - && args.iter().all(|expr| expr.is_constant()) // all arguments are constants + Expr::FnCall(mut x) + if x.1.is_none() // Non-qualified + && state.optimization_level == OptimizationLevel::Full // full optimizations + && x.3.iter().all(|expr| expr.is_constant()) // all arguments are constants => { + let ((name, pos), _, _, args, def_value) = x.as_mut(); + // First search in script-defined functions (can override built-in) - if state.fn_lib.iter().find(|(name, len)| name == id.as_ref() && *len == args.len()).is_some() { + if state.fn_lib.iter().find(|(id, len)| *id == name && *len == args.len()).is_some() { // A script-defined function overrides the built-in function - do not make the call - return Expr::FnCall(id, None, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos); + x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect(); + return Expr::FnCall(x); } let mut arg_values: Vec<_> = args.iter().map(Expr::get_constant_value).collect(); @@ -571,13 +552,13 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { // Save the typename of the first argument if it is `type_of()` // This is to avoid `call_args` being passed into the closure - let arg_for_type_of = if *id == KEYWORD_TYPE_OF && call_args.len() == 1 { + let arg_for_type_of = if name == KEYWORD_TYPE_OF && call_args.len() == 1 { state.engine.map_type_name(call_args[0].type_name()) } else { "" }; - call_fn(&state.engine.packages, &state.engine.functions, &id, &mut call_args, pos).ok() + call_fn(&state.engine.packages, &state.engine.global_module, name, &mut call_args, *pos).ok() .and_then(|result| result.or_else(|| { if !arg_for_type_of.is_empty() { @@ -585,25 +566,29 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr { Some(arg_for_type_of.to_string().into()) } else { // Otherwise use the default value, if any - def_value.clone().map(|v| *v) + def_value.clone() } - }).and_then(|result| map_dynamic_to_expr(result, pos)) + }).and_then(|result| map_dynamic_to_expr(result, *pos)) .map(|expr| { state.set_dirty(); expr }) - ).unwrap_or_else(|| + ).unwrap_or_else(|| { // Optimize function call arguments - Expr::FnCall(id, None, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos) - ) + x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect(); + Expr::FnCall(x) + }) } // id(args ..) -> optimize function call arguments - Expr::FnCall(id, modules, args, def_value, pos) => - Expr::FnCall(id, modules, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), + Expr::FnCall(mut x) => { + x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect(); + Expr::FnCall(x) + } // constant-name - Expr::Variable(name, None, _, pos) if state.contains_constant(&name) => { + Expr::Variable(x) if x.1.is_none() && state.contains_constant(&(x.0).0) => { + let (name, pos) = x.0; state.set_dirty(); // Replace constant with value @@ -660,17 +645,18 @@ fn optimize<'a>( .into_iter() .enumerate() .map(|(i, stmt)| { - match stmt { - Stmt::Const(ref name, ref value, _) => { + match &stmt { + Stmt::Const(v) => { // Load constants - state.push_constant(name.as_ref(), value.as_ref().clone()); + let ((name, _), expr) = v.as_ref(); + state.push_constant(&name, expr.clone()); stmt // Keep it in the global scope } _ => { // Keep all variable declarations at this level // and always keep the last return value let keep = match stmt { - Stmt::Let(_, _, _) | Stmt::Import(_, _, _) => true, + Stmt::Let(_) | Stmt::Import(_) => true, _ => i == num_statements - 1, }; optimize_stmt(stmt, &mut state, keep) @@ -721,34 +707,29 @@ pub fn optimize_into_ast( const fn_lib: &[(&str, usize)] = &[]; #[cfg(not(feature = "no_function"))] - let lib = FunctionsLib::from_vec( - functions - .iter() - .cloned() - .map(|mut fn_def| { - if !level.is_none() { - let pos = fn_def.body.position(); + let lib = FunctionsLib::from_iter(functions.iter().cloned().map(|mut fn_def| { + if !level.is_none() { + let pos = fn_def.body.position(); - // Optimize the function body - let mut body = - optimize(vec![*fn_def.body], engine, &Scope::new(), &fn_lib, level); + // Optimize the function body + let mut body = optimize(vec![fn_def.body], engine, &Scope::new(), &fn_lib, level); - // {} -> Noop - 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; } -> () - Stmt::ReturnWithVal(None, ReturnType::Return, pos) => { - Stmt::Expr(Box::new(Expr::Unit(pos))) - } - // All others - stmt => stmt, - }); + // {} -> Noop + fn_def.body = match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) { + // { return val; } -> val + Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => { + Stmt::Expr(Box::new(x.1.unwrap())) } - fn_def - }) - .collect(), - ); + // { return; } -> () + Stmt::ReturnWithVal(x) if x.1.is_none() && (x.0).0 == ReturnType::Return => { + Stmt::Expr(Box::new(Expr::Unit((x.0).1))) + } + // All others + stmt => stmt, + }; + } + fn_def + })); #[cfg(feature = "no_function")] let lib: FunctionsLib = Default::default(); diff --git a/src/packages/arithmetic.rs b/src/packages/arithmetic.rs index c788fbb2..e4a26844 100644 --- a/src/packages/arithmetic.rs +++ b/src/packages/arithmetic.rs @@ -1,7 +1,5 @@ -use super::{reg_binary, reg_unary}; - use crate::def_package; -use crate::fn_register::{map_dynamic as map, map_result as result}; +use crate::module::FuncReturn; use crate::parser::INT; use crate::result::EvalAltResult; use crate::token::Position; @@ -22,7 +20,7 @@ use crate::stdlib::{ }; // Checked add -fn add(x: T, y: T) -> Result> { +fn add(x: T, y: T) -> FuncReturn { x.checked_add(&y).ok_or_else(|| { Box::new(EvalAltResult::ErrorArithmetic( format!("Addition overflow: {} + {}", x, y), @@ -31,7 +29,7 @@ fn add(x: T, y: T) -> Result> { }) } // Checked subtract -fn sub(x: T, y: T) -> Result> { +fn sub(x: T, y: T) -> FuncReturn { x.checked_sub(&y).ok_or_else(|| { Box::new(EvalAltResult::ErrorArithmetic( format!("Subtraction underflow: {} - {}", x, y), @@ -40,7 +38,7 @@ fn sub(x: T, y: T) -> Result> { }) } // Checked multiply -fn mul(x: T, y: T) -> Result> { +fn mul(x: T, y: T) -> FuncReturn { x.checked_mul(&y).ok_or_else(|| { Box::new(EvalAltResult::ErrorArithmetic( format!("Multiplication overflow: {} * {}", x, y), @@ -49,7 +47,7 @@ fn mul(x: T, y: T) -> Result> { }) } // Checked divide -fn div(x: T, y: T) -> Result> +fn div(x: T, y: T) -> FuncReturn where T: Display + CheckedDiv + PartialEq + Zero, { @@ -69,7 +67,7 @@ where }) } // Checked negative - e.g. -(i32::MIN) will overflow i32::MAX -fn neg(x: T) -> Result> { +fn neg(x: T) -> FuncReturn { x.checked_neg().ok_or_else(|| { Box::new(EvalAltResult::ErrorArithmetic( format!("Negation overflow: -{}", x), @@ -78,7 +76,7 @@ fn neg(x: T) -> Result> { }) } // Checked absolute -fn abs(x: T) -> Result> { +fn abs(x: T) -> FuncReturn { // 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() { @@ -93,49 +91,49 @@ fn abs(x: T) -> Result(x: T, y: T) -> ::Output { - x + y +fn add_u(x: T, y: T) -> FuncReturn<::Output> { + Ok(x + y) } // Unchecked subtract - may panic on underflow -fn sub_u(x: T, y: T) -> ::Output { - x - y +fn sub_u(x: T, y: T) -> FuncReturn<::Output> { + Ok(x - y) } // Unchecked multiply - may panic on overflow -fn mul_u(x: T, y: T) -> ::Output { - x * y +fn mul_u(x: T, y: T) -> FuncReturn<::Output> { + Ok(x * y) } // Unchecked divide - may panic when dividing by zero -fn div_u(x: T, y: T) -> ::Output { - x / y +fn div_u(x: T, y: T) -> FuncReturn<::Output> { + Ok(x / y) } // Unchecked negative - may panic on overflow -fn neg_u(x: T) -> ::Output { - -x +fn neg_u(x: T) -> FuncReturn<::Output> { + Ok(-x) } // Unchecked absolute - may panic on overflow -fn abs_u(x: T) -> ::Output +fn abs_u(x: T) -> FuncReturn<::Output> where T: Neg + PartialOrd + Default + Into<::Output>, { // Numbers should default to zero if x < Default::default() { - -x + Ok(-x) } else { - x.into() + Ok(x.into()) } } // Bit operators -fn binary_and(x: T, y: T) -> ::Output { - x & y +fn binary_and(x: T, y: T) -> FuncReturn<::Output> { + Ok(x & y) } -fn binary_or(x: T, y: T) -> ::Output { - x | y +fn binary_or(x: T, y: T) -> FuncReturn<::Output> { + Ok(x | y) } -fn binary_xor(x: T, y: T) -> ::Output { - x ^ y +fn binary_xor(x: T, y: T) -> FuncReturn<::Output> { + Ok(x ^ y) } // Checked left-shift -fn shl(x: T, y: INT) -> Result> { +fn shl(x: T, y: INT) -> FuncReturn { // Cannot shift by a negative number of bits if y < 0 { return Err(Box::new(EvalAltResult::ErrorArithmetic( @@ -152,7 +150,7 @@ fn shl(x: T, y: INT) -> Result> { }) } // Checked right-shift -fn shr(x: T, y: INT) -> Result> { +fn shr(x: T, y: INT) -> FuncReturn { // Cannot shift by a negative number of bits if y < 0 { return Err(Box::new(EvalAltResult::ErrorArithmetic( @@ -169,15 +167,15 @@ fn shr(x: T, y: INT) -> Result> { }) } // Unchecked left-shift - may panic if shifting by a negative number of bits -fn shl_u>(x: T, y: T) -> >::Output { - x.shl(y) +fn shl_u>(x: T, y: T) -> FuncReturn<>::Output> { + Ok(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) +fn shr_u>(x: T, y: T) -> FuncReturn<>::Output> { + Ok(x.shr(y)) } // Checked modulo -fn modulo(x: T, y: T) -> Result> { +fn modulo(x: T, y: T) -> FuncReturn { x.checked_rem(&y).ok_or_else(|| { Box::new(EvalAltResult::ErrorArithmetic( format!("Modulo division by zero or overflow: {} % {}", x, y), @@ -186,11 +184,11 @@ fn modulo(x: T, y: T) -> Result> }) } // Unchecked modulo - may panic if dividing by zero -fn modulo_u(x: T, y: T) -> ::Output { - x % y +fn modulo_u(x: T, y: T) -> FuncReturn<::Output> { + Ok(x % y) } // Checked power -fn pow_i_i(x: INT, y: INT) -> Result> { +fn pow_i_i(x: INT, y: INT) -> FuncReturn { #[cfg(not(feature = "only_i32"))] { if y > (u32::MAX as INT) { @@ -231,17 +229,17 @@ fn pow_i_i(x: INT, y: INT) -> Result> { } } // 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) +fn pow_i_i_u(x: INT, y: INT) -> FuncReturn { + Ok(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) +fn pow_f_f(x: FLOAT, y: FLOAT) -> FuncReturn { + Ok(x.powf(y)) } // Checked power #[cfg(not(feature = "no_float"))] -fn pow_f_i(x: FLOAT, y: INT) -> Result> { +fn pow_f_i(x: FLOAT, y: INT) -> FuncReturn { // Raise to power that is larger than an i32 if y > (i32::MAX as INT) { return Err(Box::new(EvalAltResult::ErrorArithmetic( @@ -255,39 +253,37 @@ fn pow_f_i(x: FLOAT, y: INT) -> Result> { // 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) +fn pow_f_i_u(x: FLOAT, y: INT) -> FuncReturn { + Ok(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),*) => { + $( $lib.set_fn_1($op, $func::<$par>); )* + }; } -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);)* }; +macro_rules! reg_op { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_2($op, $func::<$par>); )* + }; } 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); + reg_op!(lib, "+", add, INT); + reg_op!(lib, "-", sub, INT); + reg_op!(lib, "*", mul, INT); + reg_op!(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); + reg_op!(lib, "+", add, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "-", sub, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "*", mul, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "/", div, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); } } @@ -334,16 +330,16 @@ def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, { // 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); + reg_op!(lib, "<<", shl, INT); + reg_op!(lib, ">>", shr, INT); + reg_op!(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); + reg_op!(lib, "<<", shl, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, ">>", shr, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); + reg_op!(lib, "%", modulo, i8, u8, i16, u16, i32, i64, u32, u64, i128, u128); } } @@ -366,39 +362,39 @@ def_package!(crate:ArithmeticPackage:"Basic arithmetic", lib, { // Checked power #[cfg(not(feature = "unchecked"))] { - reg_binary(lib, "~", pow_i_i, result); + lib.set_fn_2("~", pow_i_i); #[cfg(not(feature = "no_float"))] - reg_binary(lib, "~", pow_f_i, result); + lib.set_fn_2("~", pow_f_i); } // Unchecked power #[cfg(feature = "unchecked")] { - reg_binary(lib, "~", pow_i_i_u, map); + lib.set_fn_2("~", pow_i_i_u); #[cfg(not(feature = "no_float"))] - reg_binary(lib, "~", pow_f_i_u, map); + lib.set_fn_2("~", pow_f_i_u); } // Floating-point modulo and power #[cfg(not(feature = "no_float"))] { reg_op!(lib, "%", modulo_u, f32, f64); - reg_binary(lib, "~", pow_f_f, map); + lib.set_fn_2("~", pow_f_f); } // Checked unary #[cfg(not(feature = "unchecked"))] { - reg_unary_x!(lib, "-", neg, INT); - reg_unary_x!(lib, "abs", abs, INT); + reg_unary!(lib, "-", neg, INT); + reg_unary!(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); + reg_unary!(lib, "-", neg, i8, i16, i32, i64, i128); + reg_unary!(lib, "abs", abs, i8, i16, i32, i64, i128); } } diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index dfb80422..bdfd03aa 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -1,41 +1,46 @@ #![cfg(not(feature = "no_index"))] -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::module::FuncReturn; use crate::parser::INT; use crate::stdlib::{any::TypeId, boxed::Box, string::String}; // Register array utility functions -fn push(list: &mut Array, item: T) { +fn push(list: &mut Array, item: T) -> FuncReturn<()> { list.push(Dynamic::from(item)); + Ok(()) } -fn ins(list: &mut Array, position: INT, item: T) { +fn ins(list: &mut Array, position: INT, item: T) -> FuncReturn<()> { if position <= 0 { list.insert(0, Dynamic::from(item)); } else if (position as usize) >= list.len() - 1 { - push(list, item); + push(list, item)?; } else { list.insert(position as usize, Dynamic::from(item)); } + Ok(()) } -fn pad(list: &mut Array, len: INT, item: T) { +fn pad(list: &mut Array, len: INT, item: T) -> FuncReturn<()> { if len >= 0 { while list.len() < len as usize { - push(list, item.clone()); + push(list, item.clone())?; } } + Ok(()) } -macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { - $(reg_binary_mut($lib, $op, $func::<$par>, map);)* }; +macro_rules! reg_op { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_2_mut($op, $func::<$par>); )* + }; } -macro_rules! reg_tri { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { - $(reg_trinary_mut($lib, $op, $func::<$par>, map);)* }; +macro_rules! reg_tri { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_3_mut($op, $func::<$par>); )* + }; } #[cfg(not(feature = "no_index"))] @@ -44,15 +49,16 @@ def_package!(crate:BasicArrayPackage:"Basic array utilities.", lib, { 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, + lib.set_fn_2_mut("append", |x: &mut Array, y: Array| { + x.extend(y); + Ok(()) + }); + lib.set_fn_2( "+", |mut x: Array, y: Array| { x.extend(y); - x + Ok(x) }, - map, ); #[cfg(not(feature = "only_i32"))] @@ -70,40 +76,36 @@ def_package!(crate:BasicArrayPackage:"Basic array utilities.", lib, { reg_tri!(lib, "insert", ins, f32, f64); } - reg_unary_mut( - lib, + lib.set_fn_1_mut( "pop", - |list: &mut Array| list.pop().unwrap_or_else(|| ().into()), - pass, + |list: &mut Array| Ok(list.pop().unwrap_or_else(|| ().into())), ); - reg_unary_mut( - lib, + lib.set_fn_1_mut( "shift", |list: &mut Array| { - if list.is_empty() { + Ok(if list.is_empty() { ().into() } else { list.remove(0) - } + }) }, - pass, ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "remove", |list: &mut Array, len: INT| { - if len < 0 || (len as usize) >= list.len() { + Ok(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, + lib.set_fn_1_mut("len", |list: &mut Array| Ok(list.len() as INT)); + lib.set_fn_1_mut("clear", |list: &mut Array| { + list.clear(); + Ok(()) + }); + lib.set_fn_2_mut( "truncate", |list: &mut Array, len: INT| { if len >= 0 { @@ -111,16 +113,15 @@ def_package!(crate:BasicArrayPackage:"Basic array utilities.", lib, { } else { list.clear(); } + Ok(()) }, - map, ); // Register array iterator - lib.type_iterators.insert( + lib.set_iter( TypeId::of::(), - Box::new(|a: Dynamic| { - Box::new(a.cast::().into_iter()) - as Box> - }), + Box::new(|arr| Box::new( + arr.cast::().into_iter()) as Box> + ), ); }); diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs index 031ac095..553873e7 100644 --- a/src/packages/iter_basic.rs +++ b/src/packages/iter_basic.rs @@ -1,8 +1,6 @@ -use super::{reg_binary, reg_trinary, PackageStore}; - use crate::any::{Dynamic, Variant}; use crate::def_package; -use crate::fn_register::map_dynamic as map; +use crate::module::{FuncReturn, Module}; use crate::parser::INT; use crate::stdlib::{ @@ -12,19 +10,23 @@ use crate::stdlib::{ }; // Register range function -fn reg_range(lib: &mut PackageStore) +fn reg_range(lib: &mut Module) where Range: Iterator, { - lib.type_iterators.insert( + lib.set_iter( TypeId::of::>(), - Box::new(|source: Dynamic| { + Box::new(|source| { Box::new(source.cast::>().map(|x| x.into_dynamic())) as Box> }), ); } +fn get_range(from: T, to: T) -> FuncReturn> { + Ok(from..to) +} + // Register range function with step #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] struct StepRange(T, T, T) @@ -50,37 +52,41 @@ where } } -fn reg_step(lib: &mut PackageStore) +fn reg_step(lib: &mut Module) where for<'a> &'a T: Add<&'a T, Output = T>, T: Variant + Clone + PartialOrd, StepRange: Iterator, { - lib.type_iterators.insert( + lib.set_iter( TypeId::of::>(), - Box::new(|source: Dynamic| { + Box::new(|source| { 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 - } +fn get_step_range(from: T, to: T, step: T) -> FuncReturn> +where + for<'a> &'a T: Add<&'a T, Output = T>, + T: Variant + Clone + PartialOrd, +{ + Ok(StepRange::(from, to, step)) +} +def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { reg_range::(lib); - reg_binary(lib, "range", get_range::, map); + lib.set_fn_2("range", get_range::); #[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i64"))] { macro_rules! reg_range { - ($self:expr, $x:expr, $( $y:ty ),*) => ( + ($lib:expr, $x:expr, $( $y:ty ),*) => ( $( - reg_range::<$y>($self); - reg_binary($self, $x, get_range::<$y>, map); + reg_range::<$y>($lib); + $lib.set_fn_2($x, get_range::<$y>); )* ) } @@ -89,16 +95,16 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, { } reg_step::(lib); - reg_trinary(lib, "range", StepRange::, map); + lib.set_fn_3("range", get_step_range::); #[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i64"))] { macro_rules! reg_step { - ($self:expr, $x:expr, $( $y:ty ),*) => ( + ($lib:expr, $x:expr, $( $y:ty ),*) => ( $( - reg_step::<$y>($self); - reg_trinary($self, $x, StepRange::<$y>, map); + reg_step::<$y>($lib); + $lib.set_fn_3($x, get_step_range::<$y>); )* ) } diff --git a/src/packages/logic.rs b/src/packages/logic.rs index f993044a..ef771688 100644 --- a/src/packages/logic.rs +++ b/src/packages/logic.rs @@ -1,44 +1,44 @@ -use super::{reg_binary, reg_binary_mut, reg_unary}; - use crate::def_package; -use crate::fn_register::map_dynamic as map; +use crate::module::FuncReturn; use crate::parser::INT; use crate::stdlib::string::String; // Comparison operators -pub fn lt(x: T, y: T) -> bool { - x < y +pub fn lt(x: T, y: T) -> FuncReturn { + Ok(x < y) } -pub fn lte(x: T, y: T) -> bool { - x <= y +pub fn lte(x: T, y: T) -> FuncReturn { + Ok(x <= y) } -pub fn gt(x: T, y: T) -> bool { - x > y +pub fn gt(x: T, y: T) -> FuncReturn { + Ok(x > y) } -pub fn gte(x: T, y: T) -> bool { - x >= y +pub fn gte(x: T, y: T) -> FuncReturn { + Ok(x >= y) } -pub fn eq(x: T, y: T) -> bool { - x == y +pub fn eq(x: T, y: T) -> FuncReturn { + Ok(x == y) } -pub fn ne(x: T, y: T) -> bool { - x != y +pub fn ne(x: T, y: T) -> FuncReturn { + Ok(x != y) } // Logic operators -fn and(x: bool, y: bool) -> bool { - x && y +fn and(x: bool, y: bool) -> FuncReturn { + Ok(x && y) } -fn or(x: bool, y: bool) -> bool { - x || y +fn or(x: bool, y: bool) -> FuncReturn { + Ok(x || y) } -fn not(x: bool) -> bool { - !x +fn not(x: bool) -> FuncReturn { + Ok(!x) } -macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { - $(reg_binary($lib, $op, $func::<$par>, map);)* }; +macro_rules! reg_op { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_2($op, $func::<$par>); )* + }; } def_package!(crate:LogicPackage:"Logical operators.", lib, { @@ -50,14 +50,12 @@ def_package!(crate:LogicPackage:"Logical operators.", lib, { 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); + lib.set_fn_2_mut("<", |x: &mut String, y: String| Ok(*x < y)); + lib.set_fn_2_mut("<=", |x: &mut String, y: String| Ok(*x <= y)); + lib.set_fn_2_mut(">", |x: &mut String, y: String| Ok(*x > y)); + lib.set_fn_2_mut(">=", |x: &mut String, y: String| Ok(*x >= y)); + lib.set_fn_2_mut("==", |x: &mut String, y: String| Ok(*x == y)); + lib.set_fn_2_mut("!=", |x: &mut String, y: String| Ok(*x != y)); #[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i64"))] @@ -85,7 +83,7 @@ def_package!(crate:LogicPackage:"Logical operators.", lib, { //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); + lib.set_fn_2("|", or); + lib.set_fn_2("&", and); + lib.set_fn_1("!", not); }); diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs index 451897bf..c9f4e894 100644 --- a/src/packages/map_basic.rs +++ b/src/packages/map_basic.rs @@ -1,11 +1,9 @@ #![cfg(not(feature = "no_object"))] -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::module::FuncReturn; use crate::parser::INT; use crate::stdlib::{ @@ -13,55 +11,51 @@ use crate::stdlib::{ vec::Vec, }; -fn map_get_keys(map: &mut Map) -> Vec { - map.iter().map(|(k, _)| k.to_string().into()).collect() +fn map_get_keys(map: &mut Map) -> FuncReturn> { + Ok(map.iter().map(|(k, _)| k.to_string().into()).collect()) } -fn map_get_values(map: &mut Map) -> Vec { - map.iter().map(|(_, v)| v.clone()).collect() +fn map_get_values(map: &mut Map) -> FuncReturn> { + Ok(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, + lib.set_fn_2_mut( "has", - |map: &mut Map, prop: String| map.contains_key(&prop), - map, + |map: &mut Map, prop: String| Ok(map.contains_key(&prop)), ); - 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, + lib.set_fn_1_mut("len", |map: &mut Map| Ok(map.len() as INT)); + lib.set_fn_1_mut("clear", |map: &mut Map| { + map.clear(); + Ok(()) + }); + lib.set_fn_2_mut( "remove", - |x: &mut Map, name: String| x.remove(&name).unwrap_or_else(|| ().into()), - map, + |x: &mut Map, name: String| Ok(x.remove(&name).unwrap_or_else(|| ().into())), ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "mixin", |map1: &mut Map, map2: Map| { map2.into_iter().for_each(|(key, value)| { map1.insert(key, value); }); + Ok(()) }, - map, ); - reg_binary( - lib, + lib.set_fn_2( "+", |mut map1: Map, map2: Map| { map2.into_iter().for_each(|(key, value)| { map1.insert(key, value); }); - map1 + Ok(map1) }, - map, ); // Register map access functions #[cfg(not(feature = "no_index"))] - reg_unary_mut(lib, "keys", map_get_keys, map); + lib.set_fn_1_mut("keys", map_get_keys); #[cfg(not(feature = "no_index"))] - reg_unary_mut(lib, "values", map_get_values, map); + lib.set_fn_1_mut("values", map_get_values); }); diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs index a39f477c..9c7313ed 100644 --- a/src/packages/math_basic.rs +++ b/src/packages/math_basic.rs @@ -1,7 +1,4 @@ -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; @@ -20,78 +17,77 @@ 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); + lib.set_fn_1("sin", |x: FLOAT| Ok(x.to_radians().sin())); + lib.set_fn_1("cos", |x: FLOAT| Ok(x.to_radians().cos())); + lib.set_fn_1("tan", |x: FLOAT| Ok(x.to_radians().tan())); + lib.set_fn_1("sinh", |x: FLOAT| Ok(x.to_radians().sinh())); + lib.set_fn_1("cosh", |x: FLOAT| Ok(x.to_radians().cosh())); + lib.set_fn_1("tanh", |x: FLOAT| Ok(x.to_radians().tanh())); + lib.set_fn_1("asin", |x: FLOAT| Ok(x.asin().to_degrees())); + lib.set_fn_1("acos", |x: FLOAT| Ok(x.acos().to_degrees())); + lib.set_fn_1("atan", |x: FLOAT| Ok(x.atan().to_degrees())); + lib.set_fn_1("asinh", |x: FLOAT| Ok(x.asinh().to_degrees())); + lib.set_fn_1("acosh", |x: FLOAT| Ok(x.acosh().to_degrees())); + lib.set_fn_1("atanh", |x: FLOAT| Ok(x.atanh().to_degrees())); + lib.set_fn_1("sqrt", |x: FLOAT| Ok(x.sqrt())); + lib.set_fn_1("exp", |x: FLOAT| Ok(x.exp())); + lib.set_fn_1("ln", |x: FLOAT| Ok(x.ln())); + lib.set_fn_2("log", |x: FLOAT, base: FLOAT| Ok(x.log(base))); + lib.set_fn_1("log10", |x: FLOAT| Ok(x.log10())); + lib.set_fn_1("floor", |x: FLOAT| Ok(x.floor())); + lib.set_fn_1("ceiling", |x: FLOAT| Ok(x.ceil())); + lib.set_fn_1("round", |x: FLOAT| Ok(x.ceil())); + lib.set_fn_1("int", |x: FLOAT| Ok(x.trunc())); + lib.set_fn_1("fraction", |x: FLOAT| Ok(x.fract())); + lib.set_fn_1("is_nan", |x: FLOAT| Ok(x.is_nan())); + lib.set_fn_1("is_finite", |x: FLOAT| Ok(x.is_finite())); + lib.set_fn_1("is_infinite", |x: FLOAT| Ok(x.is_infinite())); // 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); + lib.set_fn_1("to_float", |x: INT| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: f32| Ok(x as FLOAT)); #[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); + lib.set_fn_1("to_float", |x: i8| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: u8| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: i16| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: u16| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: i32| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: u32| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: i64| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: u64| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: i128| Ok(x as FLOAT)); + lib.set_fn_1("to_float", |x: u128| Ok(x as FLOAT)); } } - reg_unary(lib, "to_int", |ch: char| ch as INT, map); + lib.set_fn_1("to_int", |ch: char| Ok(ch as INT)); #[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); + lib.set_fn_1("to_int", |x: i8| Ok(x as INT)); + lib.set_fn_1("to_int", |x: u8| Ok(x as INT)); + lib.set_fn_1("to_int", |x: i16| Ok(x as INT)); + lib.set_fn_1("to_int", |x: u16| Ok(x as INT)); } #[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); + lib.set_fn_1("to_int", |x: i32| Ok(x as INT)); + lib.set_fn_1("to_int", |x: u64| Ok(x as INT)); #[cfg(feature = "only_i64")] - reg_unary(lib, "to_int", |x: u32| x as INT, map); + lib.set_fn_1("to_int", |x: u32| Ok(x as INT)); } #[cfg(not(feature = "no_float"))] { #[cfg(not(feature = "unchecked"))] { - reg_unary( - lib, + lib.set_fn_1( "to_int", |x: f32| { if x > (MAX_INT as f32) { @@ -103,10 +99,8 @@ def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, { Ok(x.trunc() as INT) }, - result, ); - reg_unary( - lib, + lib.set_fn_1( "to_int", |x: FLOAT| { if x > (MAX_INT as FLOAT) { @@ -118,14 +112,13 @@ def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, { 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); + lib.set_fn_1("to_int", |x: f32| Ok(x as INT)); + lib.set_fn_1("to_int", |x: f64| Ok(x as INT)); } } }); diff --git a/src/packages/mod.rs b/src/packages/mod.rs index 3734bd25..5c2a6dd5 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -1,8 +1,9 @@ //! This module contains all built-in _packages_ available to Rhai, plus facilities to define custom packages. -use crate::engine::{FnAny, IteratorFn}; +use crate::fn_native::{NativeCallable, SharedIteratorFunction}; +use crate::module::Module; -use crate::stdlib::{any::TypeId, boxed::Box, collections::HashMap, rc::Rc, sync::Arc}; +use crate::stdlib::{any::TypeId, boxed::Box, collections::HashMap, rc::Rc, sync::Arc, vec::Vec}; mod arithmetic; mod array_basic; @@ -15,7 +16,6 @@ mod pkg_std; mod string_basic; mod string_more; mod time_basic; -mod utils; pub use arithmetic::ArithmeticPackage; #[cfg(not(feature = "no_index"))] @@ -32,41 +32,107 @@ 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); + fn init(lib: &mut Module); /// Retrieve the generic package library from this package. fn get(&self) -> PackageLibrary; } -/// Type to store all functions in the package. -#[derive(Default)] -pub struct PackageStore { - /// All functions, keyed by a hash created from the function name and parameter types. - pub functions: HashMap>, +/// Type which `Rc`-wraps a `Module` to facilitate sharing library instances. +#[cfg(not(feature = "sync"))] +pub type PackageLibrary = Rc; - /// All iterator functions, keyed by the type producing the iterator. - pub type_iterators: HashMap>, +/// Type which `Arc`-wraps a `Module` to facilitate sharing library instances. +#[cfg(feature = "sync")] +pub type PackageLibrary = Arc; + +/// Type containing a collection of `PackageLibrary` instances. +/// All function and type iterator keys in the loaded packages are indexed for fast access. +#[derive(Clone, Default)] +pub(crate) struct PackagesCollection { + /// Collection of `PackageLibrary` instances. + packages: Vec, } -impl PackageStore { - /// Create a new `PackageStore`. - pub fn new() -> Self { - Default::default() +impl PackagesCollection { + /// Add a `PackageLibrary` into the `PackagesCollection`. + pub fn push(&mut self, package: PackageLibrary) { + // Later packages override previous ones. + self.packages.insert(0, package); + } + /// Does the specified function hash key exist in the `PackagesCollection`? + pub fn contains_fn(&self, hash: u64) -> bool { + self.packages.iter().any(|p| p.contains_fn(hash)) + } + /// Get specified function via its hash key. + pub fn get_fn(&self, hash: u64) -> Option<&Box> { + self.packages + .iter() + .map(|p| p.get_fn(hash)) + .find(|f| f.is_some()) + .flatten() + } + /// Does the specified TypeId iterator exist in the `PackagesCollection`? + pub fn contains_iter(&self, id: TypeId) -> bool { + self.packages.iter().any(|p| p.contains_iter(id)) + } + /// Get the specified TypeId iterator. + pub fn get_iter(&self, id: TypeId) -> Option<&SharedIteratorFunction> { + self.packages + .iter() + .map(|p| p.get_iter(id)) + .find(|f| f.is_some()) + .flatten() } } -/// Type which `Rc`-wraps a `PackageStore` to facilitate sharing library instances. -#[cfg(not(feature = "sync"))] -pub type PackageLibrary = Rc; +/// This macro makes it easy to define a _package_ (which is basically a shared module) +/// and register functions into it. +/// +/// Functions can be added to the package using the standard module methods such as +/// `set_fn_2`, `set_fn_3_mut`, `set_fn_0` etc. +/// +/// # Examples +/// +/// ``` +/// use rhai::{Dynamic, EvalAltResult}; +/// use rhai::def_package; +/// +/// fn add(x: i64, y: i64) -> Result> { Ok(x + y) } +/// +/// def_package!(rhai:MyPackage:"My super-duper package", lib, +/// { +/// // Load a binary function with all value parameters. +/// lib.set_fn_2("my_add", add); +/// }); +/// ``` +/// +/// 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); -/// Type which `Arc`-wraps a `PackageStore` to facilitate sharing library instances. -#[cfg(feature = "sync")] -pub type PackageLibrary = Arc; + impl $root::packages::Package for $package { + fn get(&self) -> $root::packages::PackageLibrary { + self.0.clone() + } + + fn init($lib: &mut $root::Module) { + $block + } + } + + impl $package { + pub fn new() -> Self { + let mut module = $root::Module::new_with_capacity(512); + ::init(&mut module); + Self(module.into()) + } + } + }; +} diff --git a/src/packages/string_basic.rs b/src/packages/string_basic.rs index e58890d1..3b1689cf 100644 --- a/src/packages/string_basic.rs +++ b/src/packages/string_basic.rs @@ -1,8 +1,6 @@ -use super::{reg_binary, reg_binary_mut, reg_none, reg_unary, reg_unary_mut}; - use crate::def_package; use crate::engine::{FUNC_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT}; -use crate::fn_register::map_dynamic as map; +use crate::module::FuncReturn; use crate::parser::INT; #[cfg(not(feature = "no_index"))] @@ -18,31 +16,33 @@ use crate::stdlib::{ }; // Register print and debug -fn to_debug(x: &mut T) -> String { - format!("{:?}", x) +fn to_debug(x: &mut T) -> FuncReturn { + Ok(format!("{:?}", x)) } -fn to_string(x: &mut T) -> String { - format!("{}", x) +fn to_string(x: &mut T) -> FuncReturn { + Ok(format!("{}", x)) } #[cfg(not(feature = "no_object"))] -fn format_map(x: &mut Map) -> String { - format!("#{:?}", x) +fn format_map(x: &mut Map) -> FuncReturn { + Ok(format!("#{:?}", x)) } -macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { - $(reg_unary_mut($lib, $op, $func::<$par>, map);)* }; +macro_rules! reg_op { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_1_mut($op, $func::<$par>); )* + }; } 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); + lib.set_fn_0(KEYWORD_PRINT, || Ok("".to_string())); + lib.set_fn_1(KEYWORD_PRINT, |_: ()| Ok("".to_string())); + lib.set_fn_1(FUNC_TO_STRING, |_: ()| Ok("".to_string())); - 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); + lib.set_fn_1_mut(KEYWORD_PRINT, |s: &mut String| Ok(s.clone())); + lib.set_fn_1_mut(FUNC_TO_STRING, |s: &mut String| Ok(s.clone())); reg_op!(lib, KEYWORD_DEBUG, to_debug, INT, bool, (), char, String); @@ -73,34 +73,34 @@ def_package!(crate:BasicStringPackage:"Basic string utilities, including printin #[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); + lib.set_fn_1_mut(KEYWORD_PRINT, format_map); + lib.set_fn_1_mut(FUNC_TO_STRING, format_map); + lib.set_fn_1_mut(KEYWORD_DEBUG, format_map); } - reg_binary( - lib, + lib.set_fn_2( "+", |mut s: String, ch: char| { s.push(ch); - s + Ok(s) }, - map, ); - reg_binary( - lib, + lib.set_fn_2( "+", |mut s: String, s2: String| { s.push_str(&s2); - s + Ok(s) }, - map, ); - reg_binary_mut(lib, "append", |s: &mut String, ch: char| s.push(ch), map); - reg_binary_mut( - lib, + lib.set_fn_2_mut("append", |s: &mut String, ch: char| { + s.push(ch); + Ok(()) + }); + lib.set_fn_2_mut( "append", - |s: &mut String, s2: String| s.push_str(&s2), - map, + |s: &mut String, s2: String| { + s.push_str(&s2); + Ok(()) + } ); }); diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 2badac23..eb6208f1 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -1,7 +1,5 @@ -use super::{reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut}; - use crate::def_package; -use crate::fn_register::map_dynamic as map; +use crate::module::FuncReturn; use crate::parser::INT; #[cfg(not(feature = "no_index"))] @@ -14,19 +12,19 @@ use crate::stdlib::{ vec::Vec, }; -fn prepend(x: T, y: String) -> String { - format!("{}{}", x, y) +fn prepend(x: T, y: String) -> FuncReturn { + Ok(format!("{}{}", x, y)) } -fn append(x: String, y: T) -> String { - format!("{}{}", x, y) +fn append(x: String, y: T) -> FuncReturn { + Ok(format!("{}{}", x, y)) } -fn sub_string(s: &mut String, start: INT, len: INT) -> String { +fn sub_string(s: &mut String, start: INT, len: INT) -> FuncReturn { let offset = if s.is_empty() || len <= 0 { - return "".to_string(); + return Ok("".to_string()); } else if start < 0 { 0 } else if (start as usize) >= s.chars().count() { - return "".to_string(); + return Ok("".to_string()); } else { start as usize }; @@ -39,17 +37,17 @@ fn sub_string(s: &mut String, start: INT, len: INT) -> String { len as usize }; - chars[offset..][..len].into_iter().collect() + Ok(chars[offset..][..len].into_iter().collect()) } -fn crop_string(s: &mut String, start: INT, len: INT) { +fn crop_string(s: &mut String, start: INT, len: INT) -> FuncReturn<()> { let offset = if s.is_empty() || len <= 0 { s.clear(); - return; + return Ok(()); } else if start < 0 { 0 } else if (start as usize) >= s.chars().count() { s.clear(); - return; + return Ok(()); } else { start as usize }; @@ -67,18 +65,22 @@ fn crop_string(s: &mut String, start: INT, len: INT) { chars[offset..][..len] .into_iter() .for_each(|&ch| s.push(ch)); + + Ok(()) } -macro_rules! reg_op { ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { - $(reg_binary($lib, $op, $func::<$par>, map);)* }; +macro_rules! reg_op { + ($lib:expr, $op:expr, $func:ident, $($par:ty),*) => { + $( $lib.set_fn_2($op, $func::<$par>); )* + }; } 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); + lib.set_fn_2_mut( "+", |x: &mut String, _: ()| Ok(x.clone())); reg_op!(lib, "+", prepend, INT, bool, char); - reg_binary(lib, "+", |_: (), y: String| y, map); + lib.set_fn_2("+", |_: (), y: String| Ok(y)); #[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i64"))] @@ -95,105 +97,95 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str #[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); + lib.set_fn_2("+", |x: String, y: Array| Ok(format!("{}{:?}", x, y))); + lib.set_fn_2("+", |x: Array, y: String| Ok(format!("{:?}{}", x, y))); } - reg_unary_mut(lib, "len", |s: &mut String| s.chars().count() as INT, map); - reg_binary_mut( - lib, + lib.set_fn_1_mut("len", |s: &mut String| Ok(s.chars().count() as INT)); + lib.set_fn_2_mut( "contains", - |s: &mut String, ch: char| s.contains(ch), - map, + |s: &mut String, ch: char| Ok(s.contains(ch)), ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "contains", - |s: &mut String, find: String| s.contains(&find), - map, + |s: &mut String, find: String| Ok(s.contains(&find)), ); - reg_trinary_mut( - lib, + lib.set_fn_3_mut( "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; + return Ok(-1 as INT); } else { s.chars().take(start as usize).collect::().len() }; - s[start..] + Ok(s[start..] .find(ch) .map(|index| s[0..start + index].chars().count() as INT) - .unwrap_or(-1 as INT) + .unwrap_or(-1 as INT)) }, - map, ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "index_of", |s: &mut String, ch: char| { - s.find(ch) + Ok(s.find(ch) .map(|index| s[0..index].chars().count() as INT) - .unwrap_or(-1 as INT) + .unwrap_or(-1 as INT)) }, - map, ); - reg_trinary_mut( - lib, + lib.set_fn_3_mut( "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; + return Ok(-1 as INT); } else { s.chars().take(start as usize).collect::().len() }; - s[start..] + Ok(s[start..] .find(&find) .map(|index| s[0..start + index].chars().count() as INT) - .unwrap_or(-1 as INT) + .unwrap_or(-1 as INT)) }, - map, ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "index_of", |s: &mut String, find: String| { - s.find(&find) + Ok(s.find(&find) .map(|index| s[0..index].chars().count() as INT) - .unwrap_or(-1 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, + lib.set_fn_1_mut("clear", |s: &mut String| { + s.clear(); + Ok(()) + }); + lib.set_fn_2_mut( "append", |s: &mut String, ch: char| { + s.push(ch); + Ok(()) + }); + lib.set_fn_2_mut( "append", - |s: &mut String, add: String| s.push_str(&add), - map, + |s: &mut String, add: String| { + s.push_str(&add); + Ok(()) + } ); - reg_trinary_mut(lib, "sub_string", sub_string, map); - reg_binary_mut( - lib, + lib.set_fn_3_mut( "sub_string", sub_string); + lib.set_fn_2_mut( "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, + lib.set_fn_3_mut( "crop", crop_string); + lib.set_fn_2_mut( "crop", |s: &mut String, start: INT| crop_string(s, start, s.len() as INT), - map, ); - reg_binary_mut( - lib, + lib.set_fn_2_mut( "truncate", |s: &mut String, len: INT| { if len >= 0 { @@ -203,31 +195,55 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str } else { s.clear(); } + Ok(()) }, - map, ); - reg_trinary_mut( - lib, + lib.set_fn_3_mut( "pad", |s: &mut String, len: INT, ch: char| { for _ in 0..s.chars().count() - len as usize { s.push(ch); } + Ok(()) }, - map, ); - reg_trinary_mut( - lib, + lib.set_fn_3_mut( "replace", |s: &mut String, find: String, sub: String| { let new_str = s.replace(&find, &sub); s.clear(); s.push_str(&new_str); + Ok(()) }, - map, ); - reg_unary_mut( - lib, + lib.set_fn_3_mut( + "replace", + |s: &mut String, find: String, sub: char| { + let new_str = s.replace(&find, &sub.to_string()); + s.clear(); + s.push_str(&new_str); + Ok(()) + }, + ); + lib.set_fn_3_mut( + "replace", + |s: &mut String, find: char, sub: String| { + let new_str = s.replace(&find.to_string(), &sub); + s.clear(); + s.push_str(&new_str); + Ok(()) + }, + ); + lib.set_fn_3_mut( + "replace", + |s: &mut String, find: char, sub: char| { + let new_str = s.replace(&find.to_string(), &sub.to_string()); + s.clear(); + s.push_str(&new_str); + Ok(()) + }, + ); + lib.set_fn_1_mut( "trim", |s: &mut String| { let trimmed = s.trim(); @@ -235,7 +251,7 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str if trimmed.len() < s.len() { *s = trimmed.to_string(); } + Ok(()) }, - map, ); }); diff --git a/src/packages/time_basic.rs b/src/packages/time_basic.rs index 173c3e22..7d80344c 100644 --- a/src/packages/time_basic.rs +++ b/src/packages/time_basic.rs @@ -1,9 +1,8 @@ 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::module::FuncReturn; use crate::parser::INT; use crate::result::EvalAltResult; use crate::token::Position; @@ -14,10 +13,9 @@ 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); + lib.set_fn_0("timestamp", || Ok(Instant::now())); - reg_binary( - lib, + lib.set_fn_2( "-", |ts1: Instant, ts2: Instant| { if ts2 > ts1 { @@ -63,18 +61,16 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, { } } }, - 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); + lib.set_fn_2("<", lt::); + lib.set_fn_2("<=", lte::); + lib.set_fn_2(">", gt::); + lib.set_fn_2(">=", gte::); + lib.set_fn_2("==", eq::); + lib.set_fn_2("!=", ne::); - reg_unary( - lib, + lib.set_fn_1( "elapsed", |timestamp: Instant| { #[cfg(not(feature = "no_float"))] @@ -96,6 +92,5 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, { return Ok(seconds as INT); } }, - result, ); }); diff --git a/src/packages/utils.rs b/src/packages/utils.rs deleted file mode 100644 index a02e475c..00000000 --- a/src/packages/utils.rs +++ /dev/null @@ -1,444 +0,0 @@ -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, - mem, - 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 = mem::take(*drain.next().unwrap()).cast::(); - - let r = func(x); - 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); -} - -/// 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 = mem::take(*drain.next().unwrap()).cast::(); - let y = mem::take(*drain.next().unwrap()).cast::(); - - let r = func(x, y); - 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 = mem::take(*drain.next().unwrap()).cast::(); - - let r = func(x, y); - 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 = mem::take(*drain.next().unwrap()).cast::(); - let y = mem::take(*drain.next().unwrap()).cast::(); - let z = mem::take(*drain.next().unwrap()).cast::(); - - let r = func(x, y, z); - 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 = mem::take(*drain.next().unwrap()).cast::(); - let z = mem::take(*drain.next().unwrap()).cast::(); - - let r = func(x, y, z); - map_result(r, pos) - }); - - lib.functions.insert(hash, f); -} diff --git a/src/parser.rs b/src/parser.rs index 35b2d2e8..0fefc84c 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,12 +1,20 @@ //! Main module defining the lexer and parser. use crate::any::{Dynamic, Union}; -use crate::engine::{Engine, FunctionsLib}; +use crate::calc_fn_hash; +use crate::engine::{make_getter, make_setter, Engine, FunctionsLib}; use crate::error::{LexError, ParseError, ParseErrorType}; use crate::optimize::{optimize_into_ast, OptimizationLevel}; use crate::scope::{EntryType as ScopeEntryType, Scope}; use crate::token::{Position, Token, TokenIterator}; -use crate::utils::{calc_fn_def, StaticVec}; +use crate::utils::EMPTY_TYPE_ID; + +#[cfg(not(feature = "no_module"))] +use crate::module::ModuleRef; + +#[cfg(feature = "no_module")] +#[derive(Debug, Eq, PartialEq, Clone, Hash, Copy, Default)] +pub struct ModuleRef; use crate::stdlib::{ borrow::Cow, @@ -14,7 +22,7 @@ use crate::stdlib::{ char, collections::HashMap, format, - iter::Peekable, + iter::{empty, repeat, Peekable}, num::NonZeroUsize, ops::{Add, Deref, DerefMut}, rc::Rc, @@ -44,11 +52,6 @@ pub type FLOAT = f64; type PERR = ParseErrorType; -/// A chain of module names to qualify a variable or function call. -/// A `StaticVec` is used because most module-level access contains only one level, -/// and it is wasteful to always allocate a `Vec` with one element. -pub type ModuleRef = Option>>; - /// Compiled AST (abstract syntax tree) of a Rhai script. /// /// Currently, `AST` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`. @@ -152,11 +155,11 @@ impl AST { pub fn clear_functions(&mut self) { #[cfg(feature = "sync")] { - self.1 = Arc::new(FunctionsLib::new()); + self.1 = Arc::new(Default::default()); } #[cfg(not(feature = "sync"))] { - self.1 = Rc::new(FunctionsLib::new()); + self.1 = Rc::new(Default::default()); } } @@ -175,21 +178,39 @@ impl Add for &AST { } } -/// A script-function definition. +/// A type representing the access mode of a scripted function. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +pub enum FnAccess { + /// Private function. + Private, + /// Public function. + Public, +} + +/// A scripted function definition. #[derive(Debug, Clone)] pub struct FnDef { /// Function name. pub name: String, + /// Function access mode. + pub access: FnAccess, /// Names of function parameters. pub params: Vec, /// Function body. - pub body: Box, + pub body: Stmt, /// Position of the function definition. pub pos: Position, } +/// A sharable script-defined function. +#[cfg(feature = "sync")] +pub type SharedFnDef = Arc; +/// A sharable script-defined function. +#[cfg(not(feature = "sync"))] +pub type SharedFnDef = Rc; + /// `return`/`throw` statement. -#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] +#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)] pub enum ReturnType { /// `return` statement. Return, @@ -253,24 +274,27 @@ impl DerefMut for Stack { } /// A statement. +/// +/// Each variant is at most one pointer in size (for speed), +/// with everything being allocated together in one single tuple. #[derive(Debug, Clone)] pub enum Stmt { /// No-op. Noop(Position), /// if expr { stmt } else { stmt } - IfThenElse(Box, Box, Option>), + IfThenElse(Box<(Expr, Stmt, Option)>), /// while expr { stmt } - While(Box, Box), + While(Box<(Expr, Stmt)>), /// loop { stmt } Loop(Box), /// for id in expr { stmt } - For(Box, Box, Box), + For(Box<(String, Expr, Stmt)>), /// let id = expr - Let(Box, Option>, Position), + Let(Box<((String, Position), Option)>), /// const id = expr - Const(Box, Box, Position), + Const(Box<((String, Position), Expr)>), /// { stmt; ... } - Block(Vec, Position), + Block(Box<(Vec, Position)>), /// { stmt } Expr(Box), /// continue @@ -278,49 +302,52 @@ pub enum Stmt { /// break Break(Position), /// return/throw - ReturnWithVal(Option>, ReturnType, Position), + ReturnWithVal(Box<((ReturnType, Position), Option)>), /// import expr as module - Import(Box, Box, Position), + Import(Box<(Expr, (String, Position))>), + /// expr id as name, ... + Export(Box)>>), } impl Stmt { /// Get the `Position` of this statement. pub fn position(&self) -> Position { match self { - Stmt::Noop(pos) - | Stmt::Let(_, _, pos) - | Stmt::Const(_, _, pos) - | Stmt::Import(_, _, pos) - | Stmt::Block(_, pos) - | Stmt::Continue(pos) - | Stmt::Break(pos) - | Stmt::ReturnWithVal(_, _, pos) => *pos, - - Stmt::IfThenElse(expr, _, _) | Stmt::Expr(expr) => expr.position(), - - Stmt::While(_, stmt) | Stmt::Loop(stmt) | Stmt::For(_, _, stmt) => stmt.position(), + Stmt::Noop(pos) | Stmt::Continue(pos) | Stmt::Break(pos) => *pos, + Stmt::Let(x) => (x.0).1, + Stmt::Const(x) => (x.0).1, + Stmt::ReturnWithVal(x) => (x.0).1, + Stmt::Block(x) => x.1, + Stmt::IfThenElse(x) => x.0.position(), + Stmt::Expr(x) => x.position(), + Stmt::While(x) => x.1.position(), + Stmt::Loop(x) => x.position(), + Stmt::For(x) => x.2.position(), + Stmt::Import(x) => (x.1).1, + Stmt::Export(x) => (x.get(0).unwrap().0).1, } } /// Is this statement self-terminated (i.e. no need for a semicolon terminator)? pub fn is_self_terminated(&self) -> bool { match self { - Stmt::IfThenElse(_, _, _) - | Stmt::While(_, _) + Stmt::IfThenElse(_) + | Stmt::While(_) | Stmt::Loop(_) - | Stmt::For(_, _, _) - | Stmt::Block(_, _) => true, + | Stmt::For(_) + | Stmt::Block(_) => true, // A No-op requires a semicolon in order to know it is an empty statement! Stmt::Noop(_) => false, - Stmt::Let(_, _, _) - | Stmt::Const(_, _, _) - | Stmt::Import(_, _, _) + Stmt::Let(_) + | Stmt::Const(_) + | Stmt::Import(_) + | Stmt::Export(_) | Stmt::Expr(_) | Stmt::Continue(_) | Stmt::Break(_) - | Stmt::ReturnWithVal(_, _, _) => false, + | Stmt::ReturnWithVal(_) => false, } } @@ -329,66 +356,76 @@ impl Stmt { match self { Stmt::Noop(_) => true, Stmt::Expr(expr) => expr.is_pure(), - Stmt::IfThenElse(guard, if_block, Some(else_block)) => { - guard.is_pure() && if_block.is_pure() && else_block.is_pure() + Stmt::IfThenElse(x) if x.2.is_some() => { + x.0.is_pure() && x.1.is_pure() && x.2.as_ref().unwrap().is_pure() } - Stmt::IfThenElse(guard, block, None) | Stmt::While(guard, block) => { - guard.is_pure() && block.is_pure() - } - Stmt::Loop(block) => block.is_pure(), - Stmt::For(_, range, block) => range.is_pure() && block.is_pure(), - Stmt::Let(_, _, _) | Stmt::Const(_, _, _) => false, - Stmt::Block(statements, _) => statements.iter().all(Stmt::is_pure), - Stmt::Continue(_) | Stmt::Break(_) | Stmt::ReturnWithVal(_, _, _) => false, - Stmt::Import(_, _, _) => false, + Stmt::IfThenElse(x) => x.1.is_pure(), + Stmt::While(x) => x.0.is_pure() && x.1.is_pure(), + Stmt::Loop(x) => x.is_pure(), + Stmt::For(x) => x.1.is_pure() && x.2.is_pure(), + Stmt::Let(_) | Stmt::Const(_) => false, + Stmt::Block(x) => x.0.iter().all(Stmt::is_pure), + Stmt::Continue(_) | Stmt::Break(_) | Stmt::ReturnWithVal(_) => false, + Stmt::Import(_) => false, + Stmt::Export(_) => false, } } } +#[cfg(not(feature = "no_module"))] +type MRef = Option>; +#[cfg(feature = "no_module")] +type MRef = Option; + /// An expression. +/// +/// Each variant is at most one pointer in size (for speed), +/// with everything being allocated together in one single tuple. #[derive(Debug, Clone)] pub enum Expr { /// Integer constant. - IntegerConstant(INT, Position), + IntegerConstant(Box<(INT, Position)>), /// Floating-point constant. #[cfg(not(feature = "no_float"))] - FloatConstant(FLOAT, Position), + FloatConstant(Box<(FLOAT, Position)>), /// Character constant. - CharConstant(char, Position), + CharConstant(Box<(char, Position)>), /// String constant. - StringConstant(String, Position), - /// Variable access - (variable name, optional modules, optional index, position) - Variable(Box, ModuleRef, Option, Position), + StringConstant(Box<(String, Position)>), + /// Variable access - ((variable name, position), optional modules, hash, optional index) + Variable(Box<((String, Position), MRef, u64, Option)>), /// Property access. - Property(String, Position), + Property(Box<((String, String, String), Position)>), /// { stmt } - Stmt(Box, Position), - /// func(expr, ... ) - (function name, optional modules, arguments, optional default value, position) + Stmt(Box<(Stmt, Position)>), + /// func(expr, ... ) - ((function name, position), optional modules, hash, arguments, optional default value) /// 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`. FnCall( - Box>, - ModuleRef, - Box>, - Option>, - Position, + Box<( + (Cow<'static, str>, Position), + MRef, + u64, + Vec, + Option, + )>, ), /// expr = expr - Assignment(Box, Box, Position), + Assignment(Box<(Expr, Expr, Position)>), /// lhs.rhs - Dot(Box, Box, Position), + Dot(Box<(Expr, Expr, Position)>), /// expr[expr] - Index(Box, Box, Position), + Index(Box<(Expr, Expr, Position)>), /// [ expr, ... ] - Array(Vec, Position), + Array(Box<(Vec, Position)>), /// #{ name:expr, ... } - Map(Vec<(String, Expr, Position)>, Position), + Map(Box<(Vec<((String, Position), Expr)>, Position)>), /// lhs in rhs - In(Box, Box, Position), + In(Box<(Expr, Expr, Position)>), /// lhs && rhs - And(Box, Box, Position), + And(Box<(Expr, Expr, Position)>), /// lhs || rhs - Or(Box, Box, Position), + Or(Box<(Expr, Expr, Position)>), /// true True(Position), /// false @@ -405,31 +442,25 @@ impl Expr { /// Panics when the expression is not constant. pub fn get_constant_value(&self) -> Dynamic { match self { - Self::IntegerConstant(i, _) => (*i).into(), + Self::IntegerConstant(x) => x.0.into(), #[cfg(not(feature = "no_float"))] - Self::FloatConstant(f, _) => (*f).into(), - Self::CharConstant(c, _) => (*c).into(), - Self::StringConstant(s, _) => s.clone().into(), + Self::FloatConstant(x) => x.0.into(), + Self::CharConstant(x) => x.0.into(), + Self::StringConstant(x) => x.0.clone().into(), Self::True(_) => true.into(), Self::False(_) => false.into(), Self::Unit(_) => ().into(), #[cfg(not(feature = "no_index"))] - Self::Array(items, _) if items.iter().all(Self::is_constant) => { - Dynamic(Union::Array(Box::new( - items - .iter() - .map(Self::get_constant_value) - .collect::>(), - ))) - } + Self::Array(x) if x.0.iter().all(Self::is_constant) => Dynamic(Union::Array(Box::new( + x.0.iter().map(Self::get_constant_value).collect::>(), + ))), #[cfg(not(feature = "no_object"))] - Self::Map(items, _) if items.iter().all(|(_, v, _)| v.is_constant()) => { + Self::Map(x) if x.0.iter().all(|(_, v)| v.is_constant()) => { Dynamic(Union::Map(Box::new( - items - .iter() - .map(|(k, v, _)| (k.clone(), v.get_constant_value())) + x.0.iter() + .map(|((k, _), v)| (k.clone(), v.get_constant_value())) .collect::>(), ))) } @@ -446,16 +477,16 @@ impl Expr { pub fn get_constant_str(&self) -> String { match self { #[cfg(not(feature = "no_float"))] - Self::FloatConstant(f, _) => f.to_string(), + Self::FloatConstant(x) => x.0.to_string(), - Self::IntegerConstant(i, _) => i.to_string(), - Self::CharConstant(c, _) => c.to_string(), - Self::StringConstant(_, _) => "string".to_string(), + Self::IntegerConstant(x) => x.0.to_string(), + Self::CharConstant(x) => x.0.to_string(), + Self::StringConstant(_) => "string".to_string(), Self::True(_) => "true".to_string(), Self::False(_) => "false".to_string(), Self::Unit(_) => "()".to_string(), - Self::Array(items, _) if items.iter().all(Self::is_constant) => "array".to_string(), + Self::Array(x) if x.0.iter().all(Self::is_constant) => "array".to_string(), _ => panic!("cannot get value of non-constant expression"), } @@ -465,54 +496,50 @@ impl Expr { pub fn position(&self) -> Position { match self { #[cfg(not(feature = "no_float"))] - Self::FloatConstant(_, pos) => *pos, + Self::FloatConstant(x) => x.1, - Self::IntegerConstant(_, pos) - | Self::CharConstant(_, pos) - | Self::StringConstant(_, pos) - | Self::Array(_, pos) - | Self::Map(_, pos) - | Self::Variable(_, _, _, pos) - | Self::Property(_, pos) - | Self::Stmt(_, pos) - | Self::FnCall(_, _, _, _, pos) - | Self::And(_, _, pos) - | Self::Or(_, _, pos) - | Self::In(_, _, pos) - | Self::True(pos) - | Self::False(pos) - | Self::Unit(pos) => *pos, + Self::IntegerConstant(x) => x.1, + Self::CharConstant(x) => x.1, + Self::StringConstant(x) => x.1, + Self::Array(x) => x.1, + Self::Map(x) => x.1, + Self::Property(x) => x.1, + Self::Stmt(x) => x.1, + Self::Variable(x) => (x.0).1, + Self::FnCall(x) => (x.0).1, - Self::Assignment(expr, _, _) | Self::Dot(expr, _, _) | Self::Index(expr, _, _) => { - expr.position() - } + Self::And(x) | Self::Or(x) | Self::In(x) => x.2, + + Self::True(pos) | Self::False(pos) | Self::Unit(pos) => *pos, + + Self::Assignment(x) | Self::Dot(x) | Self::Index(x) => x.0.position(), } } - /// Get the `Position` of the expression. + /// Override the `Position` of the expression. pub(crate) fn set_position(mut self, new_pos: Position) -> Self { match &mut self { #[cfg(not(feature = "no_float"))] - Self::FloatConstant(_, pos) => *pos = new_pos, + Self::FloatConstant(x) => x.1 = new_pos, - Self::IntegerConstant(_, pos) - | Self::CharConstant(_, pos) - | Self::StringConstant(_, pos) - | Self::Array(_, pos) - | Self::Map(_, pos) - | Self::Variable(_, _, _, pos) - | Self::Property(_, pos) - | Self::Stmt(_, pos) - | Self::FnCall(_, _, _, _, pos) - | Self::And(_, _, pos) - | Self::Or(_, _, pos) - | Self::In(_, _, pos) - | Self::True(pos) - | Self::False(pos) - | Self::Unit(pos) - | Self::Assignment(_, _, pos) - | Self::Dot(_, _, pos) - | Self::Index(_, _, pos) => *pos = new_pos, + Self::IntegerConstant(x) => x.1 = new_pos, + Self::CharConstant(x) => x.1 = new_pos, + Self::StringConstant(x) => x.1 = new_pos, + Self::Array(x) => x.1 = new_pos, + Self::Map(x) => x.1 = new_pos, + Self::Variable(x) => (x.0).1 = new_pos, + Self::Property(x) => x.1 = new_pos, + Self::Stmt(x) => x.1 = new_pos, + Self::FnCall(x) => (x.0).1 = new_pos, + Self::And(x) => x.2 = new_pos, + Self::Or(x) => x.2 = new_pos, + Self::In(x) => x.2 = new_pos, + Self::True(pos) => *pos = new_pos, + Self::False(pos) => *pos = new_pos, + Self::Unit(pos) => *pos = new_pos, + Self::Assignment(x) => x.2 = new_pos, + Self::Dot(x) => x.2 = new_pos, + Self::Index(x) => x.2 = new_pos, } self @@ -523,15 +550,16 @@ impl Expr { /// A pure expression has no side effects. pub fn is_pure(&self) -> bool { match self { - Self::Array(expressions, _) => expressions.iter().all(Self::is_pure), + Self::Array(x) => x.0.iter().all(Self::is_pure), - Self::Index(x, y, _) | Self::And(x, y, _) | Self::Or(x, y, _) | Self::In(x, y, _) => { - x.is_pure() && y.is_pure() + Self::Index(x) | Self::And(x) | Self::Or(x) | Self::In(x) => { + let (lhs, rhs, _) = x.as_ref(); + lhs.is_pure() && rhs.is_pure() } - Self::Stmt(stmt, _) => stmt.is_pure(), + Self::Stmt(x) => x.0.is_pure(), - Self::Variable(_, _, _, _) => true, + Self::Variable(_) => true, expr => expr.is_constant(), } @@ -541,25 +569,25 @@ impl Expr { pub fn is_constant(&self) -> bool { match self { #[cfg(not(feature = "no_float"))] - Self::FloatConstant(_, _) => true, + Self::FloatConstant(_) => true, - Self::IntegerConstant(_, _) - | Self::CharConstant(_, _) - | Self::StringConstant(_, _) + Self::IntegerConstant(_) + | Self::CharConstant(_) + | Self::StringConstant(_) | Self::True(_) | Self::False(_) | Self::Unit(_) => true, // An array literal is constant if all items are constant - Self::Array(expressions, _) => expressions.iter().all(Self::is_constant), + Self::Array(x) => x.0.iter().all(Self::is_constant), // An map literal is constant if all items are constant - Self::Map(items, _) => items.iter().map(|(_, expr, _)| expr).all(Self::is_constant), + Self::Map(x) => x.0.iter().map(|(_, expr)| expr).all(Self::is_constant), // Check in expression - Self::In(lhs, rhs, _) => match (lhs.as_ref(), rhs.as_ref()) { - (Self::StringConstant(_, _), Self::StringConstant(_, _)) - | (Self::CharConstant(_, _), Self::StringConstant(_, _)) => true, + Self::In(x) => match (&x.0, &x.1) { + (Self::StringConstant(_), Self::StringConstant(_)) + | (Self::CharConstant(_), Self::StringConstant(_)) => true, _ => false, }, @@ -571,37 +599,37 @@ impl Expr { pub fn is_valid_postfix(&self, token: &Token) -> bool { match self { #[cfg(not(feature = "no_float"))] - Self::FloatConstant(_, _) => false, + Self::FloatConstant(_) => false, - Self::IntegerConstant(_, _) - | Self::CharConstant(_, _) - | Self::In(_, _, _) - | Self::And(_, _, _) - | Self::Or(_, _, _) + Self::IntegerConstant(_) + | Self::CharConstant(_) + | Self::In(_) + | Self::And(_) + | Self::Or(_) | Self::True(_) | Self::False(_) | Self::Unit(_) => false, - Self::StringConstant(_, _) - | Self::Stmt(_, _) - | Self::FnCall(_, _, _, _, _) - | Self::Assignment(_, _, _) - | Self::Dot(_, _, _) - | Self::Index(_, _, _) - | Self::Array(_, _) - | Self::Map(_, _) => match token { + Self::StringConstant(_) + | Self::Stmt(_) + | Self::FnCall(_) + | Self::Assignment(_) + | Self::Dot(_) + | Self::Index(_) + | Self::Array(_) + | Self::Map(_) => match token { Token::LeftBracket => true, _ => false, }, - Self::Variable(_, _, _, _) => match token { + Self::Variable(_) => match token { Token::LeftBracket | Token::LeftParen => true, #[cfg(not(feature = "no_module"))] Token::DoubleColon => true, _ => false, }, - Self::Property(_, _) => match token { + Self::Property(_) => match token { Token::LeftBracket | Token::LeftParen => true, _ => false, }, @@ -611,7 +639,12 @@ impl Expr { /// Convert a `Variable` into a `Property`. All other variants are untouched. pub(crate) fn into_property(self) -> Self { match self { - Self::Variable(id, None, _, pos) => Self::Property(*id, pos), + Self::Variable(x) if x.1.is_none() => { + let (name, pos) = x.0; + let getter = make_getter(&name); + let setter = make_setter(&name); + Self::Property(Box::new(((name.clone(), getter, setter), pos))) + } _ => self, } } @@ -675,7 +708,8 @@ fn parse_call_expr<'a>( input: &mut Peekable>, stack: &mut Stack, id: String, - modules: ModuleRef, + #[cfg(not(feature = "no_module"))] mut modules: Option>, + #[cfg(feature = "no_module")] modules: Option, begin: Position, allow_stmt_expr: bool, ) -> Result> { @@ -695,13 +729,34 @@ fn parse_call_expr<'a>( // id() (Token::RightParen, _) => { eat_token(input, Token::RightParen); - return Ok(Expr::FnCall( - Box::new(id.into()), + + #[cfg(not(feature = "no_module"))] + let hash_fn_def = { + if let Some(modules) = modules.as_mut() { + modules.set_index(stack.find_module(&modules.get_ref(0).0)); + + // Rust functions are indexed in two steps: + // 1) Calculate a hash in a similar manner to script-defined functions, + // i.e. qualifiers + function name + no parameters. + // 2) Calculate a second hash with no qualifiers, empty function name, and + // the actual list of parameter `TypeId`'.s + // 3) The final hash is the XOR of the two hashes. + calc_fn_hash(modules.iter().map(|(m, _)| m.as_str()), &id, empty()) + } else { + calc_fn_hash(empty(), &id, empty()) + } + }; + // Qualifiers (none) + function name + no parameters. + #[cfg(feature = "no_module")] + let hash_fn_def = calc_fn_hash(empty(), &id, empty()); + + return Ok(Expr::FnCall(Box::new(( + (id.into(), begin), modules, - Box::new(args), + hash_fn_def, + args, None, - begin, - )); + )))); } // id... _ => (), @@ -711,20 +766,44 @@ fn parse_call_expr<'a>( args.push(parse_expr(input, stack, allow_stmt_expr)?); match input.peek().unwrap() { + // id(...args) (Token::RightParen, _) => { eat_token(input, Token::RightParen); + let args_iter = repeat(EMPTY_TYPE_ID()).take(args.len()); - return Ok(Expr::FnCall( - Box::new(id.into()), + #[cfg(not(feature = "no_module"))] + let hash_fn_def = { + if let Some(modules) = modules.as_mut() { + modules.set_index(stack.find_module(&modules.get_ref(0).0)); + + // Rust functions are indexed in two steps: + // 1) Calculate a hash in a similar manner to script-defined functions, + // i.e. qualifiers + function name + dummy parameter types (one for each parameter). + // 2) Calculate a second hash with no qualifiers, empty function name, and + // the actual list of parameter `TypeId`'.s + // 3) The final hash is the XOR of the two hashes. + calc_fn_hash(modules.iter().map(|(m, _)| m.as_str()), &id, args_iter) + } else { + calc_fn_hash(empty(), &id, args_iter) + } + }; + // Qualifiers (none) + function name + dummy parameter types (one for each parameter). + #[cfg(feature = "no_module")] + let hash_fn_def = calc_fn_hash(empty(), &id, args_iter); + + return Ok(Expr::FnCall(Box::new(( + (id.into(), begin), modules, - Box::new(args), + hash_fn_def, + args, None, - begin, - )); + )))); } + // id(...args, (Token::Comma, _) => { eat_token(input, Token::Comma); } + // id(...args (Token::EOF, pos) => { return Err(PERR::MissingToken( Token::RightParen.into(), @@ -732,9 +811,11 @@ fn parse_call_expr<'a>( ) .into_err(*pos)) } + // id(...args (Token::LexError(err), pos) => { return Err(PERR::BadInput(err.to_string()).into_err(*pos)) } + // id(...args ??? (_, pos) => { return Err(PERR::MissingToken( Token::Comma.into(), @@ -760,39 +841,44 @@ fn parse_index_chain<'a>( // Check type of indexing - must be integer or string match &idx_expr { // lhs[int] - Expr::IntegerConstant(i, pos) if *i < 0 => { + Expr::IntegerConstant(x) if x.0 < 0 => { return Err(PERR::MalformedIndexExpr(format!( "Array access expects non-negative index: {} < 0", - i + x.0 )) - .into_err(*pos)) + .into_err(x.1)) } - Expr::IntegerConstant(_, pos) => match lhs { - Expr::Array(_, _) | Expr::StringConstant(_, _) => (), + Expr::IntegerConstant(x) => match lhs { + Expr::Array(_) | Expr::StringConstant(_) => (), - Expr::Map(_, _) => { + Expr::Map(_) => { return Err(PERR::MalformedIndexExpr( "Object map access expects string index, not a number".into(), ) - .into_err(*pos)) + .into_err(x.1)) } #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(_, pos) => { + Expr::FloatConstant(x) => { return Err(PERR::MalformedIndexExpr( "Only arrays, object maps and strings can be indexed".into(), ) - .into_err(pos)) + .into_err(x.1)) } - Expr::CharConstant(_, pos) - | Expr::Assignment(_, _, pos) - | Expr::And(_, _, pos) - | Expr::Or(_, _, pos) - | Expr::In(_, _, pos) - | Expr::True(pos) - | Expr::False(pos) - | Expr::Unit(pos) => { + Expr::CharConstant(x) => { + return Err(PERR::MalformedIndexExpr( + "Only arrays, object maps and strings can be indexed".into(), + ) + .into_err(x.1)) + } + Expr::Assignment(x) | Expr::And(x) | Expr::Or(x) | Expr::In(x) => { + return Err(PERR::MalformedIndexExpr( + "Only arrays, object maps and strings can be indexed".into(), + ) + .into_err(x.2)) + } + Expr::True(pos) | Expr::False(pos) | Expr::Unit(pos) => { return Err(PERR::MalformedIndexExpr( "Only arrays, object maps and strings can be indexed".into(), ) @@ -803,32 +889,39 @@ fn parse_index_chain<'a>( }, // lhs[string] - Expr::StringConstant(_, pos) => match lhs { - Expr::Map(_, _) => (), + Expr::StringConstant(x) => match lhs { + Expr::Map(_) => (), - Expr::Array(_, _) | Expr::StringConstant(_, _) => { + Expr::Array(_) | Expr::StringConstant(_) => { return Err(PERR::MalformedIndexExpr( "Array or string expects numeric index, not a string".into(), ) - .into_err(*pos)) + .into_err(x.1)) } #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(_, pos) => { + Expr::FloatConstant(x) => { return Err(PERR::MalformedIndexExpr( "Only arrays, object maps and strings can be indexed".into(), ) - .into_err(pos)) + .into_err(x.1)) } - Expr::CharConstant(_, pos) - | Expr::Assignment(_, _, pos) - | Expr::And(_, _, pos) - | Expr::Or(_, _, pos) - | Expr::In(_, _, pos) - | Expr::True(pos) - | Expr::False(pos) - | Expr::Unit(pos) => { + Expr::CharConstant(x) => { + return Err(PERR::MalformedIndexExpr( + "Only arrays, object maps and strings can be indexed".into(), + ) + .into_err(x.1)) + } + + Expr::Assignment(x) | Expr::And(x) | Expr::Or(x) | Expr::In(x) => { + return Err(PERR::MalformedIndexExpr( + "Only arrays, object maps and strings can be indexed".into(), + ) + .into_err(x.2)) + } + + Expr::True(pos) | Expr::False(pos) | Expr::Unit(pos) => { return Err(PERR::MalformedIndexExpr( "Only arrays, object maps and strings can be indexed".into(), ) @@ -840,32 +933,42 @@ fn parse_index_chain<'a>( // lhs[float] #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(_, pos) => { + Expr::FloatConstant(x) => { return Err(PERR::MalformedIndexExpr( "Array access expects integer index, not a float".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // lhs[char] - Expr::CharConstant(_, pos) => { + Expr::CharConstant(x) => { return Err(PERR::MalformedIndexExpr( "Array access expects integer index, not a character".into(), ) - .into_err(*pos)) + .into_err(x.1)) } - // lhs[??? = ??? ], lhs[()] - Expr::Assignment(_, _, pos) | Expr::Unit(pos) => { + // lhs[??? = ??? ] + Expr::Assignment(x) => { + return Err(PERR::MalformedIndexExpr( + "Array access expects integer index, not ()".into(), + ) + .into_err(x.2)) + } + // lhs[()] + Expr::Unit(pos) => { return Err(PERR::MalformedIndexExpr( "Array access expects integer index, not ()".into(), ) .into_err(*pos)) } - // lhs[??? && ???], lhs[??? || ???], lhs[??? in ???], lhs[true], lhs[false] - Expr::And(_, _, pos) - | Expr::Or(_, _, pos) - | Expr::In(_, _, pos) - | Expr::True(pos) - | Expr::False(pos) => { + // lhs[??? && ???], lhs[??? || ???], lhs[??? in ???] + Expr::And(x) | Expr::Or(x) | Expr::In(x) => { + return Err(PERR::MalformedIndexExpr( + "Array access expects integer index, not a boolean".into(), + ) + .into_err(x.2)) + } + // lhs[true], lhs[false] + Expr::True(pos) | Expr::False(pos) => { return Err(PERR::MalformedIndexExpr( "Array access expects integer index, not a boolean".into(), ) @@ -884,15 +987,14 @@ fn parse_index_chain<'a>( match input.peek().unwrap() { // If another indexing level, right-bind it (Token::LeftBracket, _) => { - let follow_pos = eat_token(input, Token::LeftBracket); + let idx_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)?; + let idx = parse_index_chain(input, stack, idx_expr, idx_pos, allow_stmt_expr)?; // Indexing binds to right - Ok(Expr::Index(Box::new(lhs), Box::new(follow), pos)) + Ok(Expr::Index(Box::new((lhs, idx, pos)))) } // Otherwise terminate the indexing chain - _ => Ok(Expr::Index(Box::new(lhs), Box::new(idx_expr), pos)), + _ => Ok(Expr::Index(Box::new((lhs, idx_expr, pos)))), } } (Token::LexError(err), pos) => return Err(PERR::BadInput(err.to_string()).into_err(*pos)), @@ -944,7 +1046,7 @@ fn parse_array_literal<'a>( } } - Ok(Expr::Array(arr, pos)) + Ok(Expr::Array(Box::new((arr, pos)))) } /// Parse a map literal. @@ -1000,7 +1102,7 @@ fn parse_map_literal<'a>( let expr = parse_expr(input, stack, allow_stmt_expr)?; - map.push((name, expr, pos)); + map.push(((name, pos), expr)); match input.peek().unwrap() { (Token::Comma, _) => { @@ -1033,15 +1135,15 @@ fn parse_map_literal<'a>( // Check for duplicating properties map.iter() .enumerate() - .try_for_each(|(i, (k1, _, _))| { + .try_for_each(|(i, ((k1, _), _))| { map.iter() .skip(i + 1) - .find(|(k2, _, _)| k2 == k1) - .map_or_else(|| Ok(()), |(k2, _, pos)| Err((k2, *pos))) + .find(|((k2, _), _)| k2 == k1) + .map_or_else(|| Ok(()), |((k2, pos), _)| Err((k2, *pos))) }) .map_err(|(key, pos)| PERR::DuplicatedProperty(key.to_string()).into_err(pos))?; - Ok(Expr::Map(map, pos)) + Ok(Expr::Map(Box::new((map, pos)))) } /// Parse a primary expression. @@ -1055,21 +1157,21 @@ fn parse_primary<'a>( (Token::LeftBrace, pos) if allow_stmt_expr => { let pos = *pos; return parse_block(input, stack, false, allow_stmt_expr) - .map(|block| Expr::Stmt(Box::new(block), pos)); + .map(|block| Expr::Stmt(Box::new((block, pos)))); } (Token::EOF, pos) => return Err(PERR::UnexpectedEOF.into_err(*pos)), _ => input.next().unwrap(), }; let mut root_expr = match token { - Token::IntegerConstant(x) => Expr::IntegerConstant(x, pos), + Token::IntegerConstant(x) => Expr::IntegerConstant(Box::new((x, pos))), #[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, pos), + Token::FloatConstant(x) => Expr::FloatConstant(Box::new((x, pos))), + Token::CharConstant(c) => Expr::CharConstant(Box::new((c, pos))), + Token::StringConst(s) => Expr::StringConstant(Box::new((s, pos))), Token::Identifier(s) => { let index = stack.find(&s); - Expr::Variable(Box::new(s), None, index, pos) + Expr::Variable(Box::new(((s, pos), None, 0, index))) } Token::LeftParen => parse_paren_expr(input, stack, pos, allow_stmt_expr)?, #[cfg(not(feature = "no_index"))] @@ -1096,33 +1198,28 @@ fn parse_primary<'a>( root_expr = match (root_expr, token) { // Function call - (Expr::Variable(id, modules, _, pos), Token::LeftParen) => { - parse_call_expr(input, stack, *id, modules, pos, allow_stmt_expr)? - } - (Expr::Property(id, pos), Token::LeftParen) => { - parse_call_expr(input, stack, id, None, pos, allow_stmt_expr)? + (Expr::Variable(x), Token::LeftParen) => { + let ((name, pos), modules, _, _) = *x; + parse_call_expr(input, stack, name, modules, pos, allow_stmt_expr)? } + (Expr::Property(_), _) => unreachable!(), // module access #[cfg(not(feature = "no_module"))] - (Expr::Variable(id, mut modules, mut index, pos), Token::DoubleColon) => { - match input.next().unwrap() { - (Token::Identifier(id2), pos2) => { - if let Some(ref mut modules) = modules { - modules.push((*id, pos)); - } else { - let mut vec = StaticVec::new(); - vec.push((*id, pos)); - modules = Some(Box::new(vec)); - - let root = modules.as_ref().unwrap().iter().next().unwrap(); - index = stack.find_module(&root.0); - } - - Expr::Variable(Box::new(id2), modules, index, pos2) + (Expr::Variable(x), Token::DoubleColon) => match input.next().unwrap() { + (Token::Identifier(id2), pos2) => { + let ((name, pos), mut modules, _, index) = *x; + if let Some(ref mut modules) = modules { + modules.push((name, pos)); + } else { + let mut m: ModuleRef = Default::default(); + m.push((name, pos)); + modules = Some(Box::new(m)); } - (_, pos2) => return Err(PERR::VariableExpected.into_err(pos2)), + + Expr::Variable(Box::new(((id2, pos2), modules, 0, index))) } - } + (_, pos2) => return Err(PERR::VariableExpected.into_err(pos2)), + }, // Indexing #[cfg(not(feature = "no_index"))] (expr, Token::LeftBracket) => { @@ -1133,6 +1230,20 @@ fn parse_primary<'a>( } } + match &mut root_expr { + // Cache the hash key for module-qualified variables + #[cfg(not(feature = "no_module"))] + Expr::Variable(x) if x.1.is_some() => { + let ((name, _), modules, hash, _) = x.as_mut(); + let modules = modules.as_mut().unwrap(); + + // Qualifiers + variable name + *hash = calc_fn_hash(modules.iter().map(|(v, _)| v.as_str()), name, empty()); + modules.set_index(stack.find_module(&modules.get_ref(0).0)); + } + _ => (), + } + Ok(root_expr) } @@ -1146,10 +1257,10 @@ fn parse_unary<'a>( // If statement is allowed to act as expressions (Token::If, pos) => { let pos = *pos; - Ok(Expr::Stmt( - Box::new(parse_if(input, stack, false, allow_stmt_expr)?), + Ok(Expr::Stmt(Box::new(( + parse_if(input, stack, false, allow_stmt_expr)?, pos, - )) + )))) } // -expr (Token::UnaryMinus, _) => { @@ -1157,36 +1268,46 @@ fn parse_unary<'a>( match parse_unary(input, stack, allow_stmt_expr)? { // Negative integer - Expr::IntegerConstant(i, _) => i - .checked_neg() - .map(|x| Expr::IntegerConstant(x, pos)) - .or_else(|| { - #[cfg(not(feature = "no_float"))] - { - Some(Expr::FloatConstant(-(i as FLOAT), pos)) - } - #[cfg(feature = "no_float")] - { - None - } - }) - .ok_or_else(|| { - PERR::BadInput(LexError::MalformedNumber(format!("-{}", i)).to_string()) + Expr::IntegerConstant(x) => { + let (num, pos) = *x; + + num.checked_neg() + .map(|i| Expr::IntegerConstant(Box::new((i, pos)))) + .or_else(|| { + #[cfg(not(feature = "no_float"))] + { + Some(Expr::FloatConstant(Box::new((-(x.0 as FLOAT), pos)))) + } + #[cfg(feature = "no_float")] + { + None + } + }) + .ok_or_else(|| { + PERR::BadInput( + LexError::MalformedNumber(format!("-{}", x.0)).to_string(), + ) .into_err(pos) - }), + }) + } // Negative float #[cfg(not(feature = "no_float"))] - Expr::FloatConstant(f, pos) => Ok(Expr::FloatConstant(-f, pos)), + Expr::FloatConstant(x) => Ok(Expr::FloatConstant(Box::new((-x.0, x.1)))), // Call negative function - e => Ok(Expr::FnCall( - Box::new("-".into()), - None, - Box::new(vec![e]), - None, - pos, - )), + e => { + let op = "-"; + let hash = calc_fn_hash(empty(), op, repeat(EMPTY_TYPE_ID()).take(2)); + + Ok(Expr::FnCall(Box::new(( + (op.into(), pos), + None, + hash, + vec![e], + None, + )))) + } } } // +expr @@ -1197,13 +1318,18 @@ fn parse_unary<'a>( // !expr (Token::Bang, _) => { let pos = eat_token(input, Token::Bang); - Ok(Expr::FnCall( - Box::new("!".into()), + let expr = vec![parse_primary(input, stack, allow_stmt_expr)?]; + + let op = "!"; + let hash = calc_fn_hash(empty(), op, repeat(EMPTY_TYPE_ID()).take(2)); + + Ok(Expr::FnCall(Box::new(( + (op.into(), pos), None, - 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, - )) + hash, + expr, + Some(false.into()), // NOT operator, when operating on invalid operand, defaults to false + )))) } // (Token::EOF, pos) => Err(PERR::UnexpectedEOF.into_err(*pos)), @@ -1212,15 +1338,45 @@ fn parse_unary<'a>( } } -fn parse_assignment_stmt<'a>( - input: &mut Peekable>, +fn make_assignment_stmt<'a>( stack: &mut Stack, lhs: Expr, - allow_stmt_expr: bool, + rhs: Expr, + pos: Position, ) -> 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)) + match &lhs { + Expr::Variable(x) if x.3.is_none() => Ok(Expr::Assignment(Box::new((lhs, rhs, pos)))), + Expr::Variable(x) => { + let ((name, name_pos), _, _, index) = x.as_ref(); + match stack[(stack.len() - index.unwrap().get())].1 { + ScopeEntryType::Normal => Ok(Expr::Assignment(Box::new((lhs, rhs, pos)))), + // Constant values cannot be assigned to + ScopeEntryType::Constant => { + Err(PERR::AssignmentToConstant(name.clone()).into_err(*name_pos)) + } + ScopeEntryType::Module => unreachable!(), + } + } + Expr::Index(x) | Expr::Dot(x) => match &x.0 { + Expr::Variable(x) if x.3.is_none() => Ok(Expr::Assignment(Box::new((lhs, rhs, pos)))), + Expr::Variable(x) => { + let ((name, name_pos), _, _, index) = x.as_ref(); + match stack[(stack.len() - index.unwrap().get())].1 { + ScopeEntryType::Normal => Ok(Expr::Assignment(Box::new((lhs, rhs, pos)))), + // Constant values cannot be assigned to + ScopeEntryType::Constant => { + Err(PERR::AssignmentToConstant(name.clone()).into_err(*name_pos)) + } + ScopeEntryType::Module => unreachable!(), + } + } + _ => Err(PERR::AssignmentToCopy.into_err(x.0.position())), + }, + expr if expr.is_constant() => { + Err(PERR::AssignmentToConstant("".into()).into_err(lhs.position())) + } + _ => Err(PERR::AssignmentToCopy.into_err(lhs.position())), + } } /// Parse an operator-assignment expression. @@ -1231,7 +1387,11 @@ fn parse_op_assignment_stmt<'a>( 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::Equals, _) => { + let pos = eat_token(input, Token::Equals); + let rhs = parse_expr(input, stack, allow_stmt_expr)?; + return make_assignment_stmt(stack, lhs, rhs, pos); + } (Token::PlusAssign, pos) => ("+", pos), (Token::MinusAssign, pos) => ("-", pos), (Token::MultiplyAssign, pos) => ("*", pos), @@ -1253,8 +1413,9 @@ fn parse_op_assignment_stmt<'a>( // lhs op= rhs -> lhs = op(lhs, rhs) let args = vec![lhs_copy, rhs]; - let rhs_expr = Expr::FnCall(Box::new(op.into()), None, Box::new(args), None, pos); - Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs_expr), pos)) + let hash = calc_fn_hash(empty(), op, repeat(EMPTY_TYPE_ID()).take(args.len())); + let rhs_expr = Expr::FnCall(Box::new(((op.into(), pos), None, hash, args, None))); + make_assignment_stmt(stack, lhs, rhs_expr, pos) } /// Make a dot expression. @@ -1267,56 +1428,81 @@ fn make_dot_expr( Ok(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, - ), + (Expr::Index(x), rhs) => { + Expr::Index(Box::new((x.0, make_dot_expr(x.1, rhs, op_pos, true)?, x.2))) + } // lhs.id - (lhs, rhs @ Expr::Variable(_, None, _, _)) | (lhs, rhs @ Expr::Property(_, _)) => { + (lhs, Expr::Variable(x)) if x.1.is_none() => { + let (name, pos) = x.0; let lhs = if is_index { lhs.into_property() } else { lhs }; - Expr::Dot(Box::new(lhs), Box::new(rhs.into_property()), op_pos) + + let getter = make_getter(&name); + let setter = make_setter(&name); + let rhs = Expr::Property(Box::new(((name, getter, setter), pos))); + + Expr::Dot(Box::new((lhs, rhs, op_pos))) + } + (lhs, Expr::Property(x)) => { + let lhs = if is_index { lhs.into_property() } else { lhs }; + let rhs = Expr::Property(x); + Expr::Dot(Box::new((lhs, rhs, op_pos))) } // lhs.module::id - syntax error - (_, Expr::Variable(_, Some(modules), _, _)) => { - return Err(PERR::PropertyExpected.into_err(modules.iter().next().unwrap().1)) + (_, Expr::Variable(x)) if x.1.is_some() => { + #[cfg(feature = "no_module")] + unreachable!(); + #[cfg(not(feature = "no_module"))] + return Err(PERR::PropertyExpected.into_err(x.1.unwrap().get_ref(0).1)); } // 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, Expr::Dot(x)) => { + let (dot_lhs, dot_rhs, pos) = *x; + Expr::Dot(Box::new(( + lhs, + Expr::Dot(Box::new(( + dot_lhs.into_property(), + dot_rhs.into_property(), + 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, Expr::Index(x)) => { + let (idx_lhs, idx_rhs, pos) = *x; + Expr::Dot(Box::new(( + lhs, + Expr::Index(Box::new(( + idx_lhs.into_property(), + idx_rhs.into_property(), + pos, + ))), + op_pos, + ))) + } // lhs.rhs - (lhs, rhs) => Expr::Dot(Box::new(lhs), Box::new(rhs.into_property()), op_pos), + (lhs, rhs) => Expr::Dot(Box::new((lhs, 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::And(_, _, pos)) - | (_, Expr::Or(_, _, pos)) - | (_, Expr::In(_, _, pos)) - | (_, Expr::True(pos)) - | (_, Expr::False(pos)) - | (_, Expr::Assignment(_, _, pos)) - | (_, Expr::Unit(pos)) => { + (_, Expr::IntegerConstant(x)) => { + return Err(PERR::MalformedInExpr( + "'in' expression expects a string, array or object map".into(), + ) + .into_err(x.1)) + } + + (_, Expr::And(x)) | (_, Expr::Or(x)) | (_, Expr::In(x)) | (_, Expr::Assignment(x)) => { + return Err(PERR::MalformedInExpr( + "'in' expression expects a string, array or object map".into(), + ) + .into_err(x.2)) + } + + (_, Expr::True(pos)) | (_, Expr::False(pos)) | (_, Expr::Unit(pos)) => { return Err(PERR::MalformedInExpr( "'in' expression expects a string, array or object map".into(), ) @@ -1324,61 +1510,72 @@ fn make_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result { + (_, Expr::FloatConstant(x)) => { return Err(PERR::MalformedInExpr( "'in' expression expects a string, array or object map".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // "xxx" in "xxxx", 'x' in "xxxx" - OK! - (Expr::StringConstant(_, _), Expr::StringConstant(_, _)) - | (Expr::CharConstant(_, _), Expr::StringConstant(_, _)) => (), + (Expr::StringConstant(_), Expr::StringConstant(_)) + | (Expr::CharConstant(_), Expr::StringConstant(_)) => (), // 123.456 in "xxxx" #[cfg(not(feature = "no_float"))] - (Expr::FloatConstant(_, pos), Expr::StringConstant(_, _)) => { + (Expr::FloatConstant(x), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not a float".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // 123 in "xxxx" - (Expr::IntegerConstant(_, pos), Expr::StringConstant(_, _)) => { + (Expr::IntegerConstant(x), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not a number".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // (??? && ???) in "xxxx", (??? || ???) in "xxxx", (??? in ???) in "xxxx", + (Expr::And(x), Expr::StringConstant(_)) + | (Expr::Or(x), Expr::StringConstant(_)) + | (Expr::In(x), Expr::StringConstant(_)) => { + return Err(PERR::MalformedInExpr( + "'in' expression for a string expects a string, not a boolean".into(), + ) + .into_err(x.2)) + } // true in "xxxx", false in "xxxx" - (Expr::And(_, _, pos), Expr::StringConstant(_, _)) - | (Expr::Or(_, _, pos), Expr::StringConstant(_, _)) - | (Expr::In(_, _, pos), Expr::StringConstant(_, _)) - | (Expr::True(pos), Expr::StringConstant(_, _)) - | (Expr::False(pos), Expr::StringConstant(_, _)) => { + (Expr::True(pos), Expr::StringConstant(_)) + | (Expr::False(pos), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not a boolean".into(), ) .into_err(*pos)) } // [???, ???, ???] in "xxxx" - (Expr::Array(_, pos), Expr::StringConstant(_, _)) => { + (Expr::Array(x), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not an array".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // #{...} in "xxxx" - (Expr::Map(_, pos), Expr::StringConstant(_, _)) => { + (Expr::Map(x), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not an object map".into(), ) - .into_err(*pos)) + .into_err(x.1)) } - // (??? = ???) in "xxxx", () in "xxxx" - (Expr::Assignment(_, _, pos), Expr::StringConstant(_, _)) - | (Expr::Unit(pos), Expr::StringConstant(_, _)) => { + // (??? = ???) in "xxxx" + (Expr::Assignment(x), Expr::StringConstant(_)) => { + return Err(PERR::MalformedInExpr( + "'in' expression for a string expects a string, not ()".into(), + ) + .into_err(x.2)) + } + // () in "xxxx" + (Expr::Unit(pos), Expr::StringConstant(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for a string expects a string, not ()".into(), ) @@ -1386,52 +1583,62 @@ fn make_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result (), + (Expr::StringConstant(_), Expr::Map(_)) | (Expr::CharConstant(_), Expr::Map(_)) => (), // 123.456 in #{...} #[cfg(not(feature = "no_float"))] - (Expr::FloatConstant(_, pos), Expr::Map(_, _)) => { + (Expr::FloatConstant(x), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not a float".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // 123 in #{...} - (Expr::IntegerConstant(_, pos), Expr::Map(_, _)) => { + (Expr::IntegerConstant(x), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not a number".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // (??? && ???) in #{...}, (??? || ???) in #{...}, (??? in ???) in #{...}, + (Expr::And(x), Expr::Map(_)) + | (Expr::Or(x), Expr::Map(_)) + | (Expr::In(x), Expr::Map(_)) => { + return Err(PERR::MalformedInExpr( + "'in' expression for an object map expects a string, not a boolean".into(), + ) + .into_err(x.2)) + } // true in #{...}, false in #{...} - (Expr::And(_, _, pos), Expr::Map(_, _)) - | (Expr::Or(_, _, pos), Expr::Map(_, _)) - | (Expr::In(_, _, pos), Expr::Map(_, _)) - | (Expr::True(pos), Expr::Map(_, _)) - | (Expr::False(pos), Expr::Map(_, _)) => { + (Expr::True(pos), Expr::Map(_)) | (Expr::False(pos), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not a boolean".into(), ) .into_err(*pos)) } // [???, ???, ???] in #{..} - (Expr::Array(_, pos), Expr::Map(_, _)) => { + (Expr::Array(x), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not an array".into(), ) - .into_err(*pos)) + .into_err(x.1)) } // #{...} in #{..} - (Expr::Map(_, pos), Expr::Map(_, _)) => { + (Expr::Map(x), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not an object map".into(), ) - .into_err(*pos)) + .into_err(x.1)) } - // (??? = ???) in #{...}, () in #{...} - (Expr::Assignment(_, _, pos), Expr::Map(_, _)) | (Expr::Unit(pos), Expr::Map(_, _)) => { + // (??? = ???) in #{...} + (Expr::Assignment(x), Expr::Map(_)) => { + return Err(PERR::MalformedInExpr( + "'in' expression for an object map expects a string, not ()".into(), + ) + .into_err(x.2)) + } + // () in #{...} + (Expr::Unit(pos), Expr::Map(_)) => { return Err(PERR::MalformedInExpr( "'in' expression for an object map expects a string, not ()".into(), ) @@ -1441,7 +1648,7 @@ fn make_in_expr(lhs: Expr, rhs: Expr, op_pos: Position) -> Result (), } - Ok(Expr::In(Box::new(lhs), Box::new(rhs), op_pos)) + Ok(Expr::In(Box::new((lhs, rhs, op_pos)))) } /// Parse a binary expression. @@ -1485,139 +1692,72 @@ fn parse_binary_op<'a>( rhs }; - let cmp_default = Some(Box::new(false.into())); + let cmp_def = Some(false.into()); + let op = op_token.syntax(); + let hash = calc_fn_hash(empty(), &op, repeat(EMPTY_TYPE_ID()).take(2)); + let mut args = vec![current_lhs, rhs]; current_lhs = match op_token { - Token::Plus => Expr::FnCall( - Box::new("+".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::Minus => Expr::FnCall( - Box::new("-".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::Multiply => Expr::FnCall( - Box::new("*".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::Divide => Expr::FnCall( - Box::new("/".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), + Token::Plus => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::Minus => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::Multiply => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::Divide => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), - Token::LeftShift => Expr::FnCall( - Box::new("<<".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::RightShift => Expr::FnCall( - Box::new(">>".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::Modulo => Expr::FnCall( - Box::new("%".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::PowerOf => Expr::FnCall( - Box::new("~".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), + Token::LeftShift => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::RightShift => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::Modulo => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::PowerOf => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), // Comparison operators default to false when passed invalid operands - Token::EqualsTo => Expr::FnCall( - Box::new("==".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), - Token::NotEqualsTo => Expr::FnCall( - Box::new("!=".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), - Token::LessThan => Expr::FnCall( - Box::new("<".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), - Token::LessThanEqualsTo => Expr::FnCall( - Box::new("<=".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), - Token::GreaterThan => Expr::FnCall( - Box::new(">".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), - Token::GreaterThanEqualsTo => Expr::FnCall( - Box::new(">=".into()), - None, - Box::new(vec![current_lhs, rhs]), - cmp_default, - pos, - ), + Token::EqualsTo => Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))), + Token::NotEqualsTo => Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))), + Token::LessThan => Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))), + Token::LessThanEqualsTo => { + Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))) + } + Token::GreaterThan => Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))), + Token::GreaterThanEqualsTo => { + Expr::FnCall(Box::new(((op, pos), None, hash, args, cmp_def))) + } - 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::FnCall( - Box::new("&".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::Pipe => Expr::FnCall( - Box::new("|".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), - Token::XOr => Expr::FnCall( - Box::new("^".into()), - None, - Box::new(vec![current_lhs, rhs]), - None, - pos, - ), + Token::Or => { + let rhs = args.pop().unwrap(); + let current_lhs = args.pop().unwrap(); + Expr::Or(Box::new((current_lhs, rhs, pos))) + } + Token::And => { + let rhs = args.pop().unwrap(); + let current_lhs = args.pop().unwrap(); + Expr::And(Box::new((current_lhs, rhs, pos))) + } + Token::Ampersand => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::Pipe => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), + Token::XOr => Expr::FnCall(Box::new(((op, pos), None, hash, args, None))), - Token::In => make_in_expr(current_lhs, rhs, pos)?, + Token::In => { + let rhs = args.pop().unwrap(); + let current_lhs = args.pop().unwrap(); + make_in_expr(current_lhs, rhs, pos)? + } #[cfg(not(feature = "no_object"))] - Token::Period => make_dot_expr(current_lhs, rhs, pos, false)?, + Token::Period => { + let mut rhs = args.pop().unwrap(); + let current_lhs = args.pop().unwrap(); + + match &mut rhs { + // current_lhs.rhs(...) - method call + Expr::FnCall(x) => { + let ((id, _), _, hash, args, _) = x.as_mut(); + // Recalculate function call hash because there is an additional argument + let args_iter = repeat(EMPTY_TYPE_ID()).take(args.len() + 1); + *hash = calc_fn_hash(empty(), id, args_iter); + } + _ => (), + } + + make_dot_expr(current_lhs, rhs, pos, false)? + } token => return Err(PERR::UnknownOperator(token.into()).into_err(pos)), }; @@ -1696,22 +1836,18 @@ fn parse_if<'a>( // if guard { if_body } else ... let else_body = if match_token(input, Token::Else).unwrap_or(false) { - Some(Box::new(if let (Token::If, _) = input.peek().unwrap() { + Some(if let (Token::If, _) = input.peek().unwrap() { // if guard { if_body } else if ... parse_if(input, stack, breakable, allow_stmt_expr)? } else { // if guard { if_body } else { else-body } parse_block(input, stack, breakable, allow_stmt_expr)? - })) + }) } else { None }; - Ok(Stmt::IfThenElse( - Box::new(guard), - Box::new(if_body), - else_body, - )) + Ok(Stmt::IfThenElse(Box::new((guard, if_body, else_body)))) } /// Parse a while loop. @@ -1729,7 +1865,7 @@ fn parse_while<'a>( ensure_not_assignment(input)?; let body = parse_block(input, stack, true, allow_stmt_expr)?; - Ok(Stmt::While(Box::new(guard), Box::new(body))) + Ok(Stmt::While(Box::new((guard, body)))) } /// Parse a loop statement. @@ -1791,7 +1927,7 @@ fn parse_for<'a>( stack.truncate(prev_len); - Ok(Stmt::For(Box::new(name), Box::new(expr), Box::new(body))) + Ok(Stmt::For(Box::new((name, expr, body)))) } /// Parse a variable definition statement. @@ -1820,12 +1956,12 @@ fn parse_let<'a>( // let name = expr ScopeEntryType::Normal => { stack.push((name.clone(), ScopeEntryType::Normal)); - Ok(Stmt::Let(Box::new(name), Some(Box::new(init_value)), pos)) + Ok(Stmt::Let(Box::new(((name, pos), Some(init_value))))) } // const name = { expr:constant } ScopeEntryType::Constant if init_value.is_constant() => { stack.push((name.clone(), ScopeEntryType::Constant)); - Ok(Stmt::Const(Box::new(name), Box::new(init_value), pos)) + Ok(Stmt::Const(Box::new(((name, pos), init_value)))) } // const name = expr - error ScopeEntryType::Constant => { @@ -1839,11 +1975,11 @@ fn parse_let<'a>( match var_type { ScopeEntryType::Normal => { stack.push((name.clone(), ScopeEntryType::Normal)); - Ok(Stmt::Let(Box::new(name), None, pos)) + Ok(Stmt::Let(Box::new(((name, pos), None)))) } ScopeEntryType::Constant => { stack.push((name.clone(), ScopeEntryType::Constant)); - Ok(Stmt::Const(Box::new(name), Box::new(Expr::Unit(pos)), pos)) + Ok(Stmt::Const(Box::new(((name, pos), Expr::Unit(pos))))) } // Variable cannot be a module ScopeEntryType::Module => unreachable!(), @@ -1882,7 +2018,64 @@ fn parse_import<'a>( }; stack.push((name.clone(), ScopeEntryType::Module)); - Ok(Stmt::Import(Box::new(expr), Box::new(name), pos)) + Ok(Stmt::Import(Box::new((expr, (name, pos))))) +} + +/// Parse an export statement. +fn parse_export<'a>(input: &mut Peekable>) -> Result> { + eat_token(input, Token::Export); + + let mut exports = Vec::new(); + + loop { + let (id, id_pos) = match input.next().unwrap() { + (Token::Identifier(s), pos) => (s.clone(), pos), + (Token::LexError(err), pos) => { + return Err(PERR::BadInput(err.to_string()).into_err(pos)) + } + (_, pos) => return Err(PERR::VariableExpected.into_err(pos)), + }; + + let rename = if match_token(input, Token::As)? { + match input.next().unwrap() { + (Token::Identifier(s), pos) => Some((s.clone(), pos)), + (_, pos) => return Err(PERR::VariableExpected.into_err(pos)), + } + } else { + None + }; + + exports.push(((id, id_pos), rename)); + + match input.peek().unwrap() { + (Token::Comma, _) => { + eat_token(input, Token::Comma); + } + (Token::Identifier(_), pos) => { + return Err(PERR::MissingToken( + Token::Comma.into(), + "to separate the list of exports".into(), + ) + .into_err(*pos)) + } + _ => break, + } + } + + // Check for duplicating parameters + exports + .iter() + .enumerate() + .try_for_each(|(i, ((id1, _), _))| { + exports + .iter() + .skip(i + 1) + .find(|((id2, _), _)| id2 == id1) + .map_or_else(|| Ok(()), |((id2, pos), _)| Err((id2, *pos))) + }) + .map_err(|(id2, pos)| PERR::DuplicatedExport(id2.to_string()).into_err(pos))?; + + Ok(Stmt::Export(Box::new(exports))) } /// Parse a statement block. @@ -1910,7 +2103,7 @@ fn parse_block<'a>( while !match_token(input, Token::RightBrace)? { // Parse statements inside the block - let stmt = parse_stmt(input, stack, breakable, allow_stmt_expr)?; + let stmt = parse_stmt(input, stack, breakable, false, allow_stmt_expr)?; // See if it needs a terminating semicolon let need_semicolon = !stmt.is_self_terminated(); @@ -1949,7 +2142,7 @@ fn parse_block<'a>( stack.truncate(prev_len); - Ok(Stmt::Block(statements, pos)) + Ok(Stmt::Block(Box::new((statements, pos)))) } /// Parse an expression as a statement. @@ -1968,6 +2161,7 @@ fn parse_stmt<'a>( input: &mut Peekable>, stack: &mut Stack, breakable: bool, + is_global: bool, allow_stmt_expr: bool, ) -> Result> { let (token, pos) = match input.peek().unwrap() { @@ -1982,7 +2176,8 @@ fn parse_stmt<'a>( Token::LeftBrace => parse_block(input, stack, breakable, allow_stmt_expr), // fn ... - Token::Fn => Err(PERR::WrongFnDefinition.into_err(*pos)), + Token::Fn if !is_global => Err(PERR::WrongFnDefinition.into_err(*pos)), + Token::Fn => unreachable!(), Token::If => parse_if(input, stack, breakable, allow_stmt_expr), Token::While => parse_while(input, stack, allow_stmt_expr), @@ -2010,14 +2205,20 @@ fn parse_stmt<'a>( match input.peek().unwrap() { // `return`/`throw` at - (Token::EOF, pos) => Ok(Stmt::ReturnWithVal(None, return_type, *pos)), + (Token::EOF, pos) => Ok(Stmt::ReturnWithVal(Box::new(((return_type, *pos), None)))), // `return;` or `throw;` - (Token::SemiColon, _) => Ok(Stmt::ReturnWithVal(None, return_type, pos)), + (Token::SemiColon, _) => { + Ok(Stmt::ReturnWithVal(Box::new(((return_type, pos), None)))) + } // `return` or `throw` with expression (_, _) => { let expr = parse_expr(input, stack, allow_stmt_expr)?; let pos = expr.position(); - Ok(Stmt::ReturnWithVal(Some(Box::new(expr)), return_type, pos)) + + Ok(Stmt::ReturnWithVal(Box::new(( + (return_type, pos), + Some(expr), + )))) } } } @@ -2028,6 +2229,12 @@ fn parse_stmt<'a>( #[cfg(not(feature = "no_module"))] Token::Import => parse_import(input, stack, allow_stmt_expr), + #[cfg(not(feature = "no_module"))] + Token::Export if !is_global => Err(PERR::WrongExport.into_err(*pos)), + + #[cfg(not(feature = "no_module"))] + Token::Export => parse_export(input), + _ => parse_expr_stmt(input, stack, allow_stmt_expr), } } @@ -2036,9 +2243,10 @@ fn parse_stmt<'a>( fn parse_fn<'a>( input: &mut Peekable>, stack: &mut Stack, + access: FnAccess, allow_stmt_expr: bool, ) -> Result> { - let pos = input.next().expect("should be fn").1; + let pos = eat_token(input, Token::Fn); let name = match input.next().unwrap() { (Token::Identifier(s), _) => s, @@ -2102,15 +2310,16 @@ fn parse_fn<'a>( })?; // Parse function body - let body = Box::new(match input.peek().unwrap() { + let body = 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(); Ok(FnDef { name, + access, params, body, pos, @@ -2158,15 +2367,41 @@ fn parse_global_level<'a>( // Collect all the function definitions #[cfg(not(feature = "no_function"))] { - 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; + let mut access = FnAccess::Public; + let mut must_be_fn = false; + + if match_token(input, Token::Private)? { + access = FnAccess::Private; + must_be_fn = true; + } + + match input.peek().unwrap() { + (Token::Fn, _) => { + let mut stack = Stack::new(); + let func = parse_fn(input, &mut stack, access, true)?; + + // Qualifiers (none) + function name + argument `TypeId`'s + let hash = calc_fn_hash( + empty(), + &func.name, + repeat(EMPTY_TYPE_ID()).take(func.params.len()), + ); + + functions.insert(hash, func); + continue; + } + (_, pos) if must_be_fn => { + return Err(PERR::MissingToken( + Token::Fn.into(), + format!("following '{}'", Token::Private.syntax()), + ) + .into_err(*pos)) + } + _ => (), } } // Actual statement - let stmt = parse_stmt(input, &mut stack, false, true)?; + let stmt = parse_stmt(input, &mut stack, false, true, true)?; let need_semicolon = !stmt.is_self_terminated(); @@ -2223,10 +2458,13 @@ pub fn parse<'a>( /// Returns Some(expression) if conversion is successful. Otherwise None. pub fn map_dynamic_to_expr(value: Dynamic, pos: Position) -> Option { match value.0 { + #[cfg(not(feature = "no_float"))] + Union::Float(value) => Some(Expr::FloatConstant(Box::new((value, pos)))), + 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).clone(), pos)), + Union::Int(value) => Some(Expr::IntegerConstant(Box::new((value, pos)))), + Union::Char(value) => Some(Expr::CharConstant(Box::new((value, pos)))), + Union::Str(value) => Some(Expr::StringConstant(Box::new(((*value).clone(), pos)))), Union::Bool(true) => Some(Expr::True(pos)), Union::Bool(false) => Some(Expr::False(pos)), #[cfg(not(feature = "no_index"))] @@ -2237,10 +2475,10 @@ pub fn map_dynamic_to_expr(value: Dynamic, pos: Position) -> Option { .collect(); if items.iter().all(Option::is_some) { - Some(Expr::Array( + Some(Expr::Array(Box::new(( items.into_iter().map(Option::unwrap).collect(), pos, - )) + )))) } else { None } @@ -2249,22 +2487,21 @@ pub fn map_dynamic_to_expr(value: Dynamic, pos: Position) -> Option { Union::Map(map) => { let items: Vec<_> = map .into_iter() - .map(|(k, v)| (k, map_dynamic_to_expr(v, pos), pos)) + .map(|(k, v)| ((k, pos), map_dynamic_to_expr(v, pos))) .collect(); - if items.iter().all(|(_, expr, _)| expr.is_some()) { - Some(Expr::Map( + + if items.iter().all(|(_, expr)| expr.is_some()) { + Some(Expr::Map(Box::new(( items .into_iter() - .map(|(k, expr, pos)| (k, expr.unwrap(), pos)) + .map(|((k, pos), expr)| ((k, pos), expr.unwrap())) .collect(), pos, - )) + )))) } else { None } } - #[cfg(not(feature = "no_float"))] - Union::Float(value) => Some(Expr::FloatConstant(value, pos)), _ => None, } diff --git a/src/result.rs b/src/result.rs index 5e38f8d9..c33c810b 100644 --- a/src/result.rs +++ b/src/result.rs @@ -33,6 +33,9 @@ pub enum EvalAltResult { /// Call to an unknown function. Wrapped value is the name of the function. ErrorFunctionNotFound(String, Position), + /// An error has occurred inside a called function. + /// Wrapped values re the name of the function and the interior error. + ErrorInFunctionCall(String, Box, Position), /// Function call has incorrect number of arguments. /// Wrapped values are the name of the function, the number of parameters required /// and the actual number of arguments passed. @@ -97,6 +100,7 @@ impl EvalAltResult { Self::ErrorReadingScriptFile(_, _, _) => "Cannot read from script file", Self::ErrorParsing(p) => p.desc(), + Self::ErrorInFunctionCall(_, _, _) => "Error in called function", Self::ErrorFunctionNotFound(_, _) => "Function not found", Self::ErrorFunctionArgsMismatch(_, _, _, _) => { "Function call with wrong number of arguments" @@ -160,6 +164,10 @@ impl fmt::Display for EvalAltResult { Self::ErrorParsing(p) => write!(f, "Syntax error: {}", p), + Self::ErrorInFunctionCall(s, err, pos) => { + write!(f, "Error in call to function '{}' ({}): {}", s, pos, err) + } + Self::ErrorFunctionNotFound(s, pos) | Self::ErrorVariableNotFound(s, pos) | Self::ErrorModuleNotFound(s, pos) => write!(f, "{}: '{}' ({})", desc, s, pos), @@ -262,6 +270,7 @@ impl> From for Box { } impl EvalAltResult { + /// Get the `Position` of this error. pub fn position(&self) -> Position { match self { #[cfg(not(feature = "no_std"))] @@ -270,6 +279,7 @@ impl EvalAltResult { Self::ErrorParsing(err) => err.position(), Self::ErrorFunctionNotFound(_, pos) + | Self::ErrorInFunctionCall(_, _, pos) | Self::ErrorFunctionArgsMismatch(_, _, _, pos) | Self::ErrorBooleanArgMismatch(_, pos) | Self::ErrorCharMismatch(pos) @@ -296,16 +306,16 @@ impl EvalAltResult { } } - /// Consume the current `EvalAltResult` and return a new one - /// with the specified `Position`. - pub(crate) fn set_position(mut err: Box, new_position: Position) -> Box { - match err.as_mut() { + /// Override the `Position` of this error. + pub fn set_position(&mut self, new_position: Position) { + match self { #[cfg(not(feature = "no_std"))] Self::ErrorReadingScriptFile(_, pos, _) => *pos = new_position, Self::ErrorParsing(err) => err.1 = new_position, Self::ErrorFunctionNotFound(_, pos) + | Self::ErrorInFunctionCall(_, _, pos) | Self::ErrorFunctionArgsMismatch(_, _, _, pos) | Self::ErrorBooleanArgMismatch(_, pos) | Self::ErrorCharMismatch(pos) @@ -330,7 +340,12 @@ impl EvalAltResult { | Self::ErrorLoopBreak(_, pos) | Self::Return(_, pos) => *pos = new_position, } + } - err + /// Consume the current `EvalAltResult` and return a new one + /// with the specified `Position`. + pub(crate) fn new_position(mut self: Box, new_position: Position) -> Box { + self.set_position(new_position); + self } } diff --git a/src/scope.rs b/src/scope.rs index 2411dcc1..17909970 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -7,7 +7,7 @@ use crate::token::Position; #[cfg(not(feature = "no_module"))] use crate::module::Module; -use crate::stdlib::{borrow::Cow, boxed::Box, iter, vec, vec::Vec}; +use crate::stdlib::{borrow::Cow, boxed::Box, iter, string::String, vec::Vec}; /// Type of an entry in the Scope. #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] @@ -22,7 +22,7 @@ pub enum EntryType { } /// An entry in the Scope. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Entry<'a> { /// Name of the entry. pub name: Cow<'a, str>, @@ -30,6 +30,8 @@ pub struct Entry<'a> { pub typ: EntryType, /// Current value of the entry. pub value: Dynamic, + /// Alias of the entry. + pub alias: Option>, /// A constant expression if the initial value matches one of the recognized types. pub expr: Option>, } @@ -62,7 +64,7 @@ pub struct Entry<'a> { /// allowing for automatic _shadowing_. /// /// Currently, `Scope` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`. -#[derive(Debug, Default)] +#[derive(Debug, Clone, Default)] pub struct Scope<'a>(Vec>); impl<'a> Scope<'a> { @@ -175,7 +177,9 @@ impl<'a> Scope<'a> { /// /// Modules are used for accessing member variables, functions and plugins under a namespace. #[cfg(not(feature = "no_module"))] - pub fn push_module>>(&mut self, name: K, value: Module) { + pub fn push_module>>(&mut self, name: K, mut value: Module) { + value.index_all_sub_modules(); + self.push_dynamic_value( name, EntryType::Module, @@ -246,6 +250,7 @@ impl<'a> Scope<'a> { self.0.push(Entry { name: name.into(), typ: entry_type, + alias: None, value: value.into(), expr, }); @@ -410,16 +415,15 @@ impl<'a> Scope<'a> { /// Get a mutable reference to an entry in the Scope. 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" - // ); - (&mut entry.value, entry.typ) } + /// Update the access type of an entry in the Scope. + pub(crate) fn set_entry_alias(&mut self, index: usize, alias: String) { + let entry = self.0.get_mut(index).expect("invalid index in Scope"); + entry.alias = Some(Box::new(alias)); + } + /// Get an iterator to entries in the Scope. pub(crate) fn into_iter(self) -> impl Iterator> { self.0.into_iter() @@ -437,6 +441,7 @@ impl<'a, K: Into>> iter::Extend<(K, EntryType, Dynamic)> for Scope< .extend(iter.into_iter().map(|(name, typ, value)| Entry { name: name.into(), typ, + alias: None, value: value.into(), expr: None, })); diff --git a/src/token.rs b/src/token.rs index f67a8e14..25d26ff7 100644 --- a/src/token.rs +++ b/src/token.rs @@ -196,6 +196,7 @@ pub enum Token { XOrAssign, ModuloAssign, PowerOfAssign, + Private, Import, Export, As, @@ -205,14 +206,14 @@ pub enum Token { impl Token { /// Get the syntax of the token. - pub fn syntax(&self) -> Cow { + pub fn syntax(&self) -> Cow<'static, str> { use Token::*; match self { IntegerConstant(i) => i.to_string().into(), #[cfg(not(feature = "no_float"))] FloatConstant(f) => f.to_string().into(), - Identifier(s) => s.into(), + Identifier(s) => s.clone().into(), CharConstant(c) => c.to_string().into(), LexError(err) => err.to_string().into(), @@ -279,6 +280,7 @@ impl Token { ModuloAssign => "%=", PowerOf => "~", PowerOfAssign => "~=", + Private => "private", Import => "import", Export => "export", As => "as", @@ -750,6 +752,7 @@ impl<'a> TokenIterator<'a> { "throw" => Token::Throw, "for" => Token::For, "in" => Token::In, + "private" => Token::Private, #[cfg(not(feature = "no_module"))] "import" => Token::Import, diff --git a/src/unsafe.rs b/src/unsafe.rs new file mode 100644 index 00000000..47d5b40c --- /dev/null +++ b/src/unsafe.rs @@ -0,0 +1,68 @@ +//! A module containing all unsafe code. + +use crate::any::Variant; +use crate::engine::State; +use crate::utils::StaticVec; + +use crate::stdlib::{ + any::{Any, TypeId}, + borrow::Cow, + boxed::Box, + mem, ptr, + string::ToString, + vec::Vec, +}; + +/// Cast a type into another type. +pub fn unsafe_try_cast(a: A) -> Option { + if TypeId::of::() == a.type_id() { + // SAFETY: Just checked we have the right type. We explicitly forget the + // value immediately after moving out, removing any chance of a destructor + // running or value otherwise being used again. + unsafe { + let ret: B = ptr::read(&a as *const _ as *const B); + mem::forget(a); + Some(ret) + } + } else { + None + } +} + +/// Cast a Boxed type into another type. +pub fn unsafe_cast_box(item: Box) -> Result, Box> { + // Only allow casting to the exact same type + if TypeId::of::() == TypeId::of::() { + // SAFETY: just checked whether we are pointing to the correct type + unsafe { + let raw: *mut dyn Any = Box::into_raw(item as Box); + Ok(Box::from_raw(raw as *mut T)) + } + } else { + // Return the consumed item for chaining. + Err(item) + } +} + +/// A dangerous function that blindly casts a `&str` from one lifetime to a `Cow` of +/// another lifetime. This is mainly used to let us push a block-local variable into the +/// current `Scope` without cloning the variable name. Doing this is safe because all local +/// variables in the `Scope` are cleared out before existing the block. +/// +/// Force-casting a local variable lifetime to the current `Scope`'s larger lifetime saves +/// on allocations and string cloning, thus avoids us having to maintain a chain of `Scope`'s. +pub fn unsafe_cast_var_name<'s>(name: &str, state: &State) -> Cow<'s, str> { + // If not at global level, we can force-cast + if state.scope_level > 0 { + // WARNING - force-cast the variable name into the scope's lifetime to avoid cloning it + // this is safe because all local variables are cleared at the end of the block + unsafe { mem::transmute::<_, &'s str>(name) }.into() + } else { + name.to_string().into() + } +} + +/// Provide a type instance that is memory-zeroed. +pub fn unsafe_zeroed() -> T { + unsafe { mem::MaybeUninit::zeroed().assume_init() } +} diff --git a/src/utils.rs b/src/utils.rs index 4a9479f1..f61d24ea 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,9 +1,12 @@ //! Module containing various utility types and functions. +use crate::r#unsafe::unsafe_zeroed; + use crate::stdlib::{ any::TypeId, fmt, hash::{Hash, Hasher}, + iter::FromIterator, mem, vec::Vec, }; @@ -14,30 +17,33 @@ use crate::stdlib::collections::hash_map::DefaultHasher; #[cfg(feature = "no_std")] use ahash::AHasher; -/// 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(); - - s.write(fn_name.as_bytes()); - params.for_each(|t| t.hash(&mut s)); - s.finish() +#[inline(always)] +pub fn EMPTY_TYPE_ID() -> TypeId { + TypeId::of::<()>() } -/// 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, num_params: usize) -> u64 { +/// Calculate a `u64` hash key from a module-qualified function name and parameter types. +/// +/// Module names are passed in via `&str` references from an iterator. +/// Parameter types are passed in via `TypeId` values from an iterator. +/// +/// # Note +/// +/// The first module name is skipped. Hashing starts from the _second_ module in the chain. +pub fn calc_fn_spec<'a>( + modules: impl Iterator, + 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(); + // We always skip the first module + modules.skip(1).for_each(|m| m.hash(&mut s)); s.write(fn_name.as_bytes()); - s.write_usize(num_params); + params.for_each(|t| t.hash(&mut s)); s.finish() } @@ -45,8 +51,14 @@ pub(crate) fn calc_fn_def(fn_name: &str, num_params: usize) -> u64 { /// /// This is essentially a knock-off of the [`staticvec`](https://crates.io/crates/staticvec) crate. /// This simplified implementation here is to avoid pulling in another crate. -#[derive(Clone, Default)] -pub struct StaticVec { +/// +/// # Safety +/// +/// This type uses some unsafe code (mainly to zero out unused array slots) for efficiency. +// +// TODO - remove unsafe code +#[derive(Clone, Hash)] +pub struct StaticVec { /// Total number of values held. len: usize, /// Static storage. 4 slots should be enough for most cases - i.e. four levels of indirection. @@ -55,14 +67,52 @@ pub struct StaticVec { more: Vec, } -impl StaticVec { +impl PartialEq for StaticVec { + fn eq(&self, other: &Self) -> bool { + self.len == other.len && self.list == other.list && self.more == other.more + } +} + +impl Eq for StaticVec {} + +impl FromIterator for StaticVec { + fn from_iter>(iter: X) -> Self { + let mut vec = StaticVec::new(); + + for x in iter { + vec.push(x); + } + + vec + } +} + +impl Default for StaticVec { + fn default() -> Self { + Self { + len: 0, + list: unsafe_zeroed(), + more: Vec::new(), + } + } +} + +impl StaticVec { /// Create a new `StaticVec`. pub fn new() -> Self { Default::default() } /// Push a new value to the end of this `StaticVec`. pub fn push>(&mut self, value: X) { - if self.len >= self.list.len() { + if self.len == self.list.len() { + // Move the fixed list to the Vec + for x in 0..self.list.len() { + let def_val: T = unsafe_zeroed(); + self.more + .push(mem::replace(self.list.get_mut(x).unwrap(), def_val)); + } + self.more.push(value.into()); + } else if self.len > self.list.len() { self.more.push(value.into()); } else { self.list[self.len] = value.into(); @@ -78,9 +128,19 @@ impl StaticVec { let result = if self.len <= 0 { panic!("nothing to pop!") } else if self.len <= self.list.len() { - mem::take(self.list.get_mut(self.len - 1).unwrap()) + let def_val: T = unsafe_zeroed(); + mem::replace(self.list.get_mut(self.len - 1).unwrap(), def_val) } else { - self.more.pop().unwrap() + let r = self.more.pop().unwrap(); + + // Move back to the fixed list + if self.more.len() == self.list.len() { + for x in 0..self.list.len() { + self.list[self.list.len() - 1 - x] = self.more.pop().unwrap(); + } + } + + r }; self.len -= 1; @@ -91,38 +151,99 @@ impl StaticVec { pub fn len(&self) -> usize { self.len } - /// Get an item at a particular index. + /// Get a reference to the item at a particular index. /// /// # Panics /// /// Panics if the index is out of bounds. - pub fn get(&self, index: usize) -> &T { + pub fn get_ref(&self, index: usize) -> &T { if index >= self.len { panic!("index OOB in StaticVec"); } - if index < self.list.len() { + if self.len < self.list.len() { self.list.get(index).unwrap() } else { - self.more.get(index - self.list.len()).unwrap() + self.more.get(index).unwrap() + } + } + /// Get a mutable reference to the item at a particular index. + /// + /// # Panics + /// + /// Panics if the index is out of bounds. + pub fn get_mut(&mut self, index: usize) -> &mut T { + if index >= self.len { + panic!("index OOB in StaticVec"); + } + + if self.len < self.list.len() { + self.list.get_mut(index).unwrap() + } else { + self.more.get_mut(index).unwrap() } } /// Get an iterator to entries in the `StaticVec`. pub fn iter(&self) -> impl Iterator { - let num = if self.len >= self.list.len() { - self.list.len() + if self.len > self.list.len() { + self.more.iter() } else { - self.len - }; - - self.list[..num].iter().chain(self.more.iter()) + self.list[..self.len].iter() + } + } + /// Get a mutable iterator to entries in the `StaticVec`. + pub fn iter_mut(&mut self) -> impl Iterator { + if self.len > self.list.len() { + self.more.iter_mut() + } else { + self.list[..self.len].iter_mut() + } } } -impl fmt::Debug for StaticVec { +impl StaticVec { + /// Get the item at a particular index. + /// + /// # Panics + /// + /// Panics if the index is out of bounds. + pub fn get(&self, index: usize) -> T { + if index >= self.len { + panic!("index OOB in StaticVec"); + } + + if self.len < self.list.len() { + *self.list.get(index).unwrap() + } else { + *self.more.get(index).unwrap() + } + } +} + +impl fmt::Debug for StaticVec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[ ")?; self.iter().try_for_each(|v| write!(f, "{:?}, ", v))?; write!(f, "]") } } + +impl AsRef<[T]> for StaticVec { + fn as_ref(&self) -> &[T] { + if self.len > self.list.len() { + &self.more[..] + } else { + &self.list[..self.len] + } + } +} + +impl AsMut<[T]> for StaticVec { + fn as_mut(&mut self) -> &mut [T] { + if self.len > self.list.len() { + &mut self.more[..] + } else { + &mut self.list[..self.len] + } + } +} diff --git a/tests/call_fn.rs b/tests/call_fn.rs index f3d2a689..e3c61765 100644 --- a/tests/call_fn.rs +++ b/tests/call_fn.rs @@ -41,13 +41,13 @@ fn test_call_fn() -> Result<(), Box> { ", )?; - let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?; + let r: INT = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?; assert_eq!(r, 165); - let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (123 as INT,))?; + let r: INT = engine.call_fn(&mut scope, &ast, "hello", (123 as INT,))?; assert_eq!(r, 5166); - let r: i64 = engine.call_fn(&mut scope, &ast, "hello", ())?; + let r: INT = engine.call_fn(&mut scope, &ast, "hello", ())?; assert_eq!(r, 42); assert_eq!( @@ -60,6 +60,27 @@ fn test_call_fn() -> Result<(), Box> { Ok(()) } +#[test] +fn test_call_fn_private() -> Result<(), Box> { + let engine = Engine::new(); + let mut scope = Scope::new(); + + let ast = engine.compile("fn add(x, n) { x + n }")?; + + let r: INT = engine.call_fn(&mut scope, &ast, "add", (40 as INT, 2 as INT))?; + assert_eq!(r, 42); + + let ast = engine.compile("private fn add(x, n) { x + n }")?; + + assert!(matches!( + *engine.call_fn::<_, INT>(&mut scope, &ast, "add", (40 as INT, 2 as INT)) + .expect_err("should error"), + EvalAltResult::ErrorFunctionNotFound(fn_name, _) if fn_name == "add" + )); + + Ok(()) +} + #[test] fn test_anonymous_fn() -> Result<(), Box> { let calc_func = Func::<(INT, INT, INT), INT>::create_from_script( @@ -70,5 +91,16 @@ fn test_anonymous_fn() -> Result<(), Box> { assert_eq!(calc_func(42, 123, 9)?, 1485); + let calc_func = Func::<(INT, INT, INT), INT>::create_from_script( + Engine::new(), + "private fn calc(x, y, z) { (x + y) * z }", + "calc", + )?; + + assert!(matches!( + *calc_func(42, 123, 9).expect_err("should error"), + EvalAltResult::ErrorFunctionNotFound(fn_name, _) if fn_name == "calc" + )); + Ok(()) } diff --git a/tests/constants.rs b/tests/constants.rs index 55752d28..d5e0820a 100644 --- a/tests/constants.rs +++ b/tests/constants.rs @@ -1,4 +1,4 @@ -use rhai::{Engine, EvalAltResult, INT}; +use rhai::{Engine, EvalAltResult, ParseErrorType, INT}; #[test] fn test_constant() -> Result<(), Box> { @@ -8,13 +8,13 @@ fn test_constant() -> Result<(), Box> { assert!(matches!( *engine.eval::("const x = 123; x = 42;").expect_err("expects error"), - EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x" + EvalAltResult::ErrorParsing(err) if err.error_type() == &ParseErrorType::AssignmentToConstant("x".to_string()) )); #[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" + EvalAltResult::ErrorParsing(err) if err.error_type() == &ParseErrorType::AssignmentToConstant("x".to_string()) )); Ok(()) diff --git a/tests/functions.rs b/tests/functions.rs new file mode 100644 index 00000000..26d9b387 --- /dev/null +++ b/tests/functions.rs @@ -0,0 +1,25 @@ +#![cfg(not(feature = "no_function"))] +use rhai::{Engine, EvalAltResult, INT}; + +#[test] +fn test_functions() -> Result<(), Box> { + let engine = Engine::new(); + + assert_eq!(engine.eval::("fn add(x, n) { x + n } add(40, 2)")?, 42); + + #[cfg(not(feature = "no_object"))] + assert_eq!( + engine.eval::("fn add(x, n) { x + n } let x = 40; x.add(2)")?, + 42 + ); + + assert_eq!(engine.eval::("fn mul2(x) { x * 2 } mul2(21)")?, 42); + + #[cfg(not(feature = "no_object"))] + assert_eq!( + engine.eval::("fn mul2(x) { x * 2 } let x = 21; x.mul2()")?, + 42 + ); + + Ok(()) +} diff --git a/tests/method_call.rs b/tests/method_call.rs index 99d1d0bd..850cf247 100644 --- a/tests/method_call.rs +++ b/tests/method_call.rs @@ -10,8 +10,8 @@ fn test_method_call() -> Result<(), Box> { } impl TestStruct { - fn update(&mut self) { - self.x += 1000; + fn update(&mut self, n: INT) { + self.x += n; } fn new() -> Self { @@ -27,14 +27,23 @@ fn test_method_call() -> Result<(), Box> { engine.register_fn("new_ts", TestStruct::new); assert_eq!( - engine.eval::("let x = new_ts(); x.update(); x")?, + engine.eval::("let x = new_ts(); x.update(1000); x")?, TestStruct { x: 1001 } ); assert_eq!( - engine.eval::("let x = new_ts(); update(x); x")?, + engine.eval::("let x = new_ts(); update(x, 1000); x")?, TestStruct { x: 1 } ); Ok(()) } + +#[test] +fn test_method_call_style() -> Result<(), Box> { + let engine = Engine::new(); + + assert_eq!(engine.eval::("let x = -123; x.abs(); x")?, -123); + + Ok(()) +} diff --git a/tests/modules.rs b/tests/modules.rs index e6028179..acf3c0e6 100644 --- a/tests/modules.rs +++ b/tests/modules.rs @@ -18,7 +18,7 @@ fn test_module_sub_module() -> Result<(), Box> { let mut sub_module2 = Module::new(); sub_module2.set_var("answer", 41 as INT); - let hash = sub_module2.set_fn_1("inc", |x: INT| Ok(x + 1)); + let hash_inc = sub_module2.set_fn_1("inc", |x: INT| Ok(x + 1)); sub_module.set_sub_module("universe", sub_module2); module.set_sub_module("life", sub_module); @@ -30,11 +30,11 @@ fn test_module_sub_module() -> Result<(), Box> { let m2 = m.get_sub_module("universe").unwrap(); assert!(m2.contains_var("answer")); - assert!(m2.contains_fn(hash)); + assert!(m2.contains_fn(hash_inc)); assert_eq!(m2.get_var_value::("answer").unwrap(), 41); - let mut engine = Engine::new(); + let engine = Engine::new(); let mut scope = Scope::new(); scope.push_module("question", module); @@ -81,3 +81,87 @@ fn test_module_resolver() -> Result<(), Box> { Ok(()) } + +#[test] +#[cfg(not(feature = "no_function"))] +fn test_module_from_ast() -> Result<(), Box> { + let mut engine = Engine::new(); + + let mut resolver = rhai::module_resolvers::StaticModuleResolver::new(); + let mut sub_module = Module::new(); + sub_module.set_var("foo", true); + resolver.insert("another module".to_string(), sub_module); + + engine.set_module_resolver(Some(resolver)); + + let ast = engine.compile( + r#" + // Functions become module functions + fn calc(x) { + x + 1 + } + fn add_len(x, y) { + x + len(y) + } + private fn hidden() { + throw "you shouldn't see me!"; + } + + // Imported modules become sub-modules + import "another module" as extra; + + // Variables defined at global level become module variables + const x = 123; + let foo = 41; + let hello; + + // Final variable values become constant module variable values + foo = calc(foo); + hello = "hello, " + foo + " worlds!"; + + export + x as abc, + foo, + hello, + extra as foobar; + "#, + )?; + + let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?; + + let mut scope = Scope::new(); + scope.push_module("testing", module); + + assert_eq!( + engine.eval_expression_with_scope::(&mut scope, "testing::abc")?, + 123 + ); + assert_eq!( + engine.eval_expression_with_scope::(&mut scope, "testing::foo")?, + 42 + ); + assert!(engine.eval_expression_with_scope::(&mut scope, "testing::foobar::foo")?); + assert_eq!( + engine.eval_expression_with_scope::(&mut scope, "testing::hello")?, + "hello, 42 worlds!" + ); + assert_eq!( + engine.eval_expression_with_scope::(&mut scope, "testing::calc(999)")?, + 1000 + ); + assert_eq!( + engine.eval_expression_with_scope::( + &mut scope, + "testing::add_len(testing::foo, testing::hello)" + )?, + 59 + ); + assert!(matches!( + *engine + .eval_expression_with_scope::<()>(&mut scope, "testing::hidden()") + .expect_err("should error"), + EvalAltResult::ErrorFunctionNotFound(fn_name, _) if fn_name == "hidden" + )); + + Ok(()) +} diff --git a/tests/stack.rs b/tests/stack.rs index 503bcbde..1eeb4250 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -23,7 +23,8 @@ fn test_stack_overflow() -> Result<(), Box> { ) { Ok(_) => panic!("should be stack overflow"), Err(err) => match *err { - EvalAltResult::ErrorStackOverflow(_) => (), + EvalAltResult::ErrorInFunctionCall(name, _, _) + if name.starts_with("foo > foo > foo") => {} _ => panic!("should be stack overflow"), }, }