Merge branch 'master' into plugins
This commit is contained in:
commit
1442cc9b7a
38
README.md
38
README.md
@ -472,8 +472,7 @@ The follow packages are available:
|
|||||||
Packages typically contain Rust functions that are callable within a Rhai script.
|
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).
|
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`],
|
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).
|
even across threads (under the [`sync`] feature). Therefore, a package only has to be created _once_.
|
||||||
Therefore, a package only has to be created _once_.
|
|
||||||
|
|
||||||
Packages are actually implemented as [modules], so they share a lot of behavior and characteristics.
|
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
|
The main difference is that a package loads under the _global_ namespace, while a module loads under its own
|
||||||
@ -573,7 +572,7 @@ if type_of(x) == "string" {
|
|||||||
|
|
||||||
[`Dynamic`]: #dynamic-values
|
[`Dynamic`]: #dynamic-values
|
||||||
|
|
||||||
A `Dynamic` value can be _any_ type. However, if the [`sync`] feature is used, then all types must be `Send + Sync`.
|
A `Dynamic` value can be _any_ type. However, under the [`sync`] feature, all types must be `Send + Sync`.
|
||||||
|
|
||||||
Because [`type_of()`] a `Dynamic` value returns the type of the actual value, it is usually used to perform type-specific
|
Because [`type_of()`] a `Dynamic` value returns the type of the actual value, it is usually used to perform type-specific
|
||||||
actions based on the actual value's type.
|
actions based on the actual value's type.
|
||||||
@ -976,7 +975,7 @@ let result = engine.eval::<i64>(
|
|||||||
println!("result: {}", result); // prints 1
|
println!("result: {}", result); // prints 1
|
||||||
```
|
```
|
||||||
|
|
||||||
If the [`no_object`] feature is turned on, however, the _method_ style of function calls
|
Under the [`no_object`] feature, however, the _method_ style of function calls
|
||||||
(i.e. calling a function as an object-method) is no longer supported.
|
(i.e. calling a function as an object-method) is no longer supported.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@ -1077,8 +1076,23 @@ println!("Answer: {}", result); // prints 42
|
|||||||
```
|
```
|
||||||
|
|
||||||
Needless to say, `register_type`, `register_type_with_name`, `register_get`, `register_set`, `register_get_set`
|
Needless to say, `register_type`, `register_type_with_name`, `register_get`, `register_set`, `register_get_set`
|
||||||
and `register_indexer` are not available when the [`no_object`] feature is turned on.
|
and `register_indexer` are not available under the [`no_object`] feature.
|
||||||
`register_indexer` is also not available when the [`no_index`] feature is turned on.
|
`register_indexer` is also not available under the [`no_index`] feature.
|
||||||
|
|
||||||
|
Printing for custom types
|
||||||
|
-------------------------
|
||||||
|
|
||||||
|
To use custom types for `print` and `debug`, or format its value into a [string], it is necessary that the following
|
||||||
|
functions be registered (assuming the custom type is `T` and it is `Display + Debug`):
|
||||||
|
|
||||||
|
| Function | Signature | Typical implementation | Usage |
|
||||||
|
| ----------- | ------------------------------------------------ | ------------------------------ | --------------------------------------------------------------------------------------- |
|
||||||
|
| `to_string` | `|s: &mut T| -> String` | `s.to_string()` | Converts the custom type into a [string] |
|
||||||
|
| `print` | `|s: &mut T| -> String` | `s.to_string()` | Converts the custom type into a [string] for the [`print`](#print-and-debug) statement |
|
||||||
|
| `debug` | `|s: &mut T| -> String` | `format!("{:?}", s)` | Converts the custom type into a [string] for the [`debug`](#print-and-debug) statement |
|
||||||
|
| `+` | `|s1: ImmutableString, s: T| -> ImmutableString` | `s1 + s` | Append the custom type to another [string], for `print("Answer: " + type);` usage |
|
||||||
|
| `+` | `|s: T, s2: ImmutableString| -> String` | `s.to_string().push_str(&s2);` | Append another [string] to the custom type, for `print(type + " is the answer");` usage |
|
||||||
|
| `+=` | `|s1: &mut ImmutableString, s: T|` | `s1 += s.to_string()` | Append the custom type to an existing [string], for `s += type;` usage |
|
||||||
|
|
||||||
`Scope` - Initializing and maintaining state
|
`Scope` - Initializing and maintaining state
|
||||||
-------------------------------------------
|
-------------------------------------------
|
||||||
@ -1089,8 +1103,8 @@ By default, Rhai treats each [`Engine`] invocation as a fresh one, persisting on
|
|||||||
but no global state. This gives each evaluation a clean starting slate. In order to continue using the same global state
|
but no global state. This gives each evaluation a clean starting slate. In order to continue using the same global state
|
||||||
from one invocation to the next, such a state must be manually created and passed in.
|
from one invocation to the next, such a state must be manually created and passed in.
|
||||||
|
|
||||||
All `Scope` variables are [`Dynamic`], meaning they can store values of any type. If the [`sync`] feature is used, however,
|
All `Scope` variables are [`Dynamic`], meaning they can store values of any type. Under the [`sync`] feature, however,
|
||||||
then only types that are `Send + Sync` are supported, and the entire `Scope` itself will also be `Send + Sync`.
|
only types that are `Send + Sync` are supported, and the entire `Scope` itself will also be `Send + Sync`.
|
||||||
This is extremely useful in multi-threaded applications.
|
This is extremely useful in multi-threaded applications.
|
||||||
|
|
||||||
In this example, a global state object (a `Scope`) is created with a few initialized variables, then the same state is
|
In this example, a global state object (a `Scope`) is created with a few initialized variables, then the same state is
|
||||||
@ -1191,7 +1205,7 @@ The following are reserved keywords in Rhai:
|
|||||||
| `import`, `export`, `as` | Modules | [`no_module`] |
|
| `import`, `export`, `as` | Modules | [`no_module`] |
|
||||||
|
|
||||||
Keywords cannot be the name of a [function] or [variable], unless the relevant exclusive feature is enabled.
|
Keywords cannot be the name of a [function] or [variable], unless the relevant exclusive feature is enabled.
|
||||||
For example, `fn` is a valid variable name if the [`no_function`] feature is used.
|
For example, `fn` is a valid variable name under the [`no_function`] feature.
|
||||||
|
|
||||||
Statements
|
Statements
|
||||||
----------
|
----------
|
||||||
@ -1729,7 +1743,7 @@ technically be mapped to [`()`]. A valid JSON string does not start with a hash
|
|||||||
Rhai object map does - that's the major difference!
|
Rhai object map does - that's the major difference!
|
||||||
|
|
||||||
JSON numbers are all floating-point while Rhai supports integers (`INT`) and floating-point (`FLOAT`) if
|
JSON numbers are all floating-point while Rhai supports integers (`INT`) and floating-point (`FLOAT`) if
|
||||||
the [`no_float`] feature is not turned on. Most common generators of JSON data distinguish between
|
the [`no_float`] feature is not enabled. Most common generators of JSON data distinguish between
|
||||||
integer and floating-point values by always serializing a floating-point number with a decimal point
|
integer and floating-point values by always serializing a floating-point number with a decimal point
|
||||||
(i.e. `123.0` instead of `123` which is assumed to be an integer). This style can be used successfully
|
(i.e. `123.0` instead of `123` which is assumed to be an integer). This style can be used successfully
|
||||||
with Rhai object maps.
|
with Rhai object maps.
|
||||||
@ -2364,7 +2378,7 @@ Built-in module resolvers are grouped under the `rhai::module_resolvers` module
|
|||||||
| Module Resolver | Description |
|
| 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.<br/>The base directory can be changed via the `FileModuleResolver::new_with_path()` constructor function.<br/>`FileModuleResolver::create_module()` loads a script file and returns a module. |
|
| `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.<br/>The base directory can be changed via the `FileModuleResolver::new_with_path()` constructor function.<br/>`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. |
|
| `StaticModuleResolver` | Loads modules that are statically added. This can be used under the [`no_std`] feature. |
|
||||||
|
|
||||||
An [`Engine`]'s module resolver is set via a call to `Engine::set_module_resolver`:
|
An [`Engine`]'s module resolver is set via a call to `Engine::set_module_resolver`:
|
||||||
|
|
||||||
@ -2439,7 +2453,7 @@ provide a closure to the `Engine::on_progress` method:
|
|||||||
```rust
|
```rust
|
||||||
let mut engine = Engine::new();
|
let mut engine = Engine::new();
|
||||||
|
|
||||||
engine.on_progress(|count| { // 'count' is the number of operations performed
|
engine.on_progress(|&count| { // 'count' is the number of operations performed
|
||||||
if count % 1000 == 0 {
|
if count % 1000 == 0 {
|
||||||
println!("{}", count); // print out a progress log every 1,000 operations
|
println!("{}", count); // print out a progress log every 1,000 operations
|
||||||
}
|
}
|
||||||
|
51
RELEASES.md
51
RELEASES.md
@ -4,6 +4,11 @@ Rhai Release Notes
|
|||||||
Version 0.16.0
|
Version 0.16.0
|
||||||
==============
|
==============
|
||||||
|
|
||||||
|
Breaking changes
|
||||||
|
----------------
|
||||||
|
|
||||||
|
* Callback closure passed to `Engine::on_progress` now takes `&u64` instead of `u64` to be consistent with other callback signatures.
|
||||||
|
|
||||||
|
|
||||||
Version 0.15.0
|
Version 0.15.0
|
||||||
==============
|
==============
|
||||||
@ -18,26 +23,18 @@ Bug fixes
|
|||||||
|
|
||||||
* Indexing with an index or dot expression now works property (it compiled wrongly before).
|
* Indexing with an index or dot expression now works property (it compiled wrongly before).
|
||||||
For example, `let s = "hello"; s[s.len-1] = 'x';` now works property instead of causing a runtime error.
|
For example, `let s = "hello"; s[s.len-1] = 'x';` now works property instead of causing a runtime error.
|
||||||
|
* `if` expressions are not supposed to be allowed when compiling for expressions only. This is fixed.
|
||||||
|
|
||||||
Breaking changes
|
Breaking changes
|
||||||
----------------
|
----------------
|
||||||
|
|
||||||
* `Engine::compile_XXX` functions now return `ParseError` instead of `Box<ParseError>`.
|
* `Engine::compile_XXX` functions now return `ParseError` instead of `Box<ParseError>`.
|
||||||
* The `RegisterDynamicFn` trait is merged into the `RegisterResultFn` trait which now always returns
|
* The `RegisterDynamicFn` trait is merged into the `RegisterResultFn` trait which now always returns `Result<Dynamic, Box<EvalAltResult>>`.
|
||||||
`Result<Dynamic, Box<EvalAltResult>>`.
|
|
||||||
* Default maximum limit on levels of nested function calls is fine-tuned and set to a different value.
|
* Default maximum limit on levels of nested function calls is fine-tuned and set to a different value.
|
||||||
* Some operator functions are now built in (see _Speed enhancements_ below), so they are available even
|
* Some operator functions are now built in (see _Speed enhancements_ below), so they are available even under `Engine::new_raw`.
|
||||||
under `Engine::new_raw`.
|
* Strings are now immutable. The type `rhai::ImmutableString` is used instead of `std::string::String`. This is to avoid excessive cloning of strings. All native-Rust functions taking string parameters should switch to `rhai::ImmutableString` (which is either `Rc<String>` or `Arc<String>` depending on whether the `sync` feature is used).
|
||||||
* Strings are now immutable. The type `rhai::ImmutableString` is used instead of `std::string::String`.
|
* Native Rust functions registered with the `Engine` also mutates the first argument when called in normal function-call style (previously the first argument will be passed by _value_ if not called in method-call style). Of course, if the first argument is a calculated value (e.g. result of an expression), then mutating it has no effect, but at least it is not cloned.
|
||||||
This is to avoid excessive cloning of strings. All native-Rust functions taking string parameters
|
* Some built-in methods (e.g. `len` for string, `floor` for `FLOAT`) now have _property_ versions in addition to methods to simplify coding.
|
||||||
should switch to `rhai::ImmutableString` (which is either `Rc<String>` or `Arc<String>` depending on
|
|
||||||
whether the `sync` feature is used).
|
|
||||||
* Native Rust functions registered with the `Engine` also mutates the first argument when called in
|
|
||||||
normal function-call style (previously the first argument will be passed by _value_ if not called
|
|
||||||
in method-call style). Of course, if the first argument is a calculated value (e.g. result of an
|
|
||||||
expression), then mutating it has no effect, but at least it is not cloned.
|
|
||||||
* Some built-in methods (e.g. `len` for string, `floor` for `FLOAT`) now have _property_ versions in
|
|
||||||
addition to methods to simplify coding.
|
|
||||||
|
|
||||||
New features
|
New features
|
||||||
------------
|
------------
|
||||||
@ -50,23 +47,13 @@ New features
|
|||||||
Speed enhancements
|
Speed enhancements
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
* Common operators (e.g. `+`, `>`, `==`) now call into highly efficient built-in implementations for standard types
|
* Common operators (e.g. `+`, `>`, `==`) now call into highly efficient built-in implementations for standard types (i.e. `INT`, `FLOAT`, `bool`, `char`, `()` and `ImmutableString`) if not overridden by a registered function. This yields a 5-10% speed benefit depending on script operator usage. Scripts running tight loops will see significant speed-up.
|
||||||
(i.e. `INT`, `FLOAT`, `bool`, `char`, `()` and `ImmutableString`) if not overridden by a registered function.
|
* Common assignment operators (e.g. `+=`, `%=`) now call into highly efficient built-in implementations for standard types (i.e. `INT`, `FLOAT`, `bool`, `char`, `()` and `ImmutableString`) if not overridden by a registered function.
|
||||||
This yields a 5-10% speed benefit depending on script operator usage. Scripts running tight loops will see
|
* Implementations of common operators for standard types are removed from the `ArithmeticPackage` and `LogicPackage` (and therefore the `CorePackage`) because they are now always available, even under `Engine::new_raw`.
|
||||||
significant speed-up.
|
|
||||||
* Common assignment operators (e.g. `+=`, `%=`) now call into highly efficient built-in implementations for
|
|
||||||
standard types (i.e. `INT`, `FLOAT`, `bool`, `char`, `()` and `ImmutableString`) if not overridden by a registered function.
|
|
||||||
* Implementations of common operators for standard types are removed from the `ArithmeticPackage` and `LogicPackage`
|
|
||||||
(and therefore the `CorePackage`) because they are now always available, even under `Engine::new_raw`.
|
|
||||||
* Operator-assignment statements (e.g. `+=`) are now handled directly and much faster.
|
* Operator-assignment statements (e.g. `+=`) are now handled directly and much faster.
|
||||||
* Strings are now _immutable_ and use the `rhai::ImmutableString` type, eliminating large amounts of cloning.
|
* Strings are now _immutable_ and use the `rhai::ImmutableString` type, eliminating large amounts of cloning.
|
||||||
* For Native Rust functions taking a first `&mut` parameter, the first argument is passed by reference instead of
|
* For Native Rust functions taking a first `&mut` parameter, the first argument is passed by reference instead of by value, even if not called in method-call style. This allows many functions declared with `&mut` parameter to avoid excessive cloning. For example, if `a` is a large array, getting its length in this manner: `len(a)` used to result in a full clone of `a` before taking the length and throwing the copy away. Now, `a` is simply passed by reference, avoiding the cloning altogether.
|
||||||
by value, even if not called in method-call style. This allows many functions declared with `&mut` parameter to avoid
|
* A custom hasher simply passes through `u64` keys without hashing to avoid function call hash keys (which are by themselves `u64`) being hashed twice.
|
||||||
excessive cloning. For example, if `a` is a large array, getting its length in this manner: `len(a)` used to result
|
|
||||||
in a full clone of `a` before taking the length and throwing the copy away. Now, `a` is simply passed by reference,
|
|
||||||
avoiding the cloning altogether.
|
|
||||||
* A custom hasher simply passes through `u64` keys without hashing to avoid function call hash keys
|
|
||||||
(which are by themselves `u64`) being hashed twice.
|
|
||||||
|
|
||||||
|
|
||||||
Version 0.14.1
|
Version 0.14.1
|
||||||
@ -78,15 +65,13 @@ The major features for this release is modules, script resource limits, and spee
|
|||||||
New features
|
New features
|
||||||
------------
|
------------
|
||||||
|
|
||||||
* Modules and _module resolvers_ allow loading external scripts under a module namespace.
|
* Modules and _module resolvers_ allow loading external scripts under a module namespace. A module can contain constant variables, Rust functions and Rhai functions.
|
||||||
A module can contain constant variables, Rust functions and Rhai functions.
|
|
||||||
* `export` variables and `private` functions.
|
* `export` variables and `private` functions.
|
||||||
* _Indexers_ for Rust types.
|
* _Indexers_ for Rust types.
|
||||||
* Track script evaluation progress and terminate script run.
|
* Track script evaluation progress and terminate script run.
|
||||||
* Set limit on maximum number of operations allowed per script run.
|
* Set limit on maximum number of operations allowed per script run.
|
||||||
* Set limit on maximum number of modules loaded per script run.
|
* Set limit on maximum number of modules loaded per script run.
|
||||||
* A new API, `Engine::compile_scripts_with_scope`, can compile a list of script segments without needing to
|
* A new API, `Engine::compile_scripts_with_scope`, can compile a list of script segments without needing to first concatenate them together into one large string.
|
||||||
first concatenate them together into one large string.
|
|
||||||
* Stepped `range` function with a custom step.
|
* Stepped `range` function with a custom step.
|
||||||
|
|
||||||
Speed improvements
|
Speed improvements
|
||||||
|
54
src/api.rs
54
src/api.rs
@ -7,7 +7,7 @@ use crate::fn_call::FuncArgs;
|
|||||||
use crate::fn_native::{IteratorFn, SendSync};
|
use crate::fn_native::{IteratorFn, SendSync};
|
||||||
use crate::fn_register::RegisterFn;
|
use crate::fn_register::RegisterFn;
|
||||||
use crate::optimize::{optimize_into_ast, OptimizationLevel};
|
use crate::optimize::{optimize_into_ast, OptimizationLevel};
|
||||||
use crate::parser::{parse, parse_global_expr, AST};
|
use crate::parser::AST;
|
||||||
use crate::result::EvalAltResult;
|
use crate::result::EvalAltResult;
|
||||||
use crate::scope::Scope;
|
use crate::scope::Scope;
|
||||||
use crate::token::{lex, Position};
|
use crate::token::{lex, Position};
|
||||||
@ -449,14 +449,7 @@ impl Engine {
|
|||||||
optimization_level: OptimizationLevel,
|
optimization_level: OptimizationLevel,
|
||||||
) -> Result<AST, ParseError> {
|
) -> Result<AST, ParseError> {
|
||||||
let stream = lex(scripts);
|
let stream = lex(scripts);
|
||||||
|
self.parse(&mut stream.peekable(), scope, optimization_level)
|
||||||
parse(
|
|
||||||
&mut stream.peekable(),
|
|
||||||
self,
|
|
||||||
scope,
|
|
||||||
optimization_level,
|
|
||||||
(self.max_expr_depth, self.max_function_expr_depth),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read the contents of a file into a string.
|
/// Read the contents of a file into a string.
|
||||||
@ -578,13 +571,8 @@ impl Engine {
|
|||||||
// Trims the JSON string and add a '#' in front
|
// Trims the JSON string and add a '#' in front
|
||||||
let scripts = ["#", json.trim()];
|
let scripts = ["#", json.trim()];
|
||||||
let stream = lex(&scripts);
|
let stream = lex(&scripts);
|
||||||
let ast = parse_global_expr(
|
let ast =
|
||||||
&mut stream.peekable(),
|
self.parse_global_expr(&mut stream.peekable(), &scope, OptimizationLevel::None)?;
|
||||||
self,
|
|
||||||
&scope,
|
|
||||||
OptimizationLevel::None,
|
|
||||||
self.max_expr_depth,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
// Handle null - map to ()
|
// Handle null - map to ()
|
||||||
if has_null {
|
if has_null {
|
||||||
@ -667,13 +655,7 @@ impl Engine {
|
|||||||
|
|
||||||
{
|
{
|
||||||
let mut peekable = stream.peekable();
|
let mut peekable = stream.peekable();
|
||||||
parse_global_expr(
|
self.parse_global_expr(&mut peekable, scope, self.optimization_level)
|
||||||
&mut peekable,
|
|
||||||
self,
|
|
||||||
scope,
|
|
||||||
self.optimization_level,
|
|
||||||
self.max_expr_depth,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -825,12 +807,10 @@ impl Engine {
|
|||||||
let scripts = [script];
|
let scripts = [script];
|
||||||
let stream = lex(&scripts);
|
let stream = lex(&scripts);
|
||||||
|
|
||||||
let ast = parse_global_expr(
|
let ast = self.parse_global_expr(
|
||||||
&mut stream.peekable(),
|
&mut stream.peekable(),
|
||||||
self,
|
|
||||||
scope,
|
scope,
|
||||||
OptimizationLevel::None, // No need to optimize a lone expression
|
OptimizationLevel::None, // No need to optimize a lone expression
|
||||||
self.max_expr_depth,
|
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
self.eval_ast_with_scope(scope, &ast)
|
self.eval_ast_with_scope(scope, &ast)
|
||||||
@ -957,13 +937,7 @@ impl Engine {
|
|||||||
let scripts = [script];
|
let scripts = [script];
|
||||||
let stream = lex(&scripts);
|
let stream = lex(&scripts);
|
||||||
|
|
||||||
let ast = parse(
|
let ast = self.parse(&mut stream.peekable(), scope, self.optimization_level)?;
|
||||||
&mut stream.peekable(),
|
|
||||||
self,
|
|
||||||
scope,
|
|
||||||
self.optimization_level,
|
|
||||||
(self.max_expr_depth, self.max_function_expr_depth),
|
|
||||||
)?;
|
|
||||||
self.consume_ast_with_scope(scope, &ast)
|
self.consume_ast_with_scope(scope, &ast)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1104,16 +1078,20 @@ impl Engine {
|
|||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
|
let mut args: StaticVec<_> = arg_values.iter_mut().collect();
|
||||||
let lib = ast.lib();
|
let lib = ast.lib();
|
||||||
let pos = Position::none();
|
|
||||||
|
|
||||||
let fn_def = lib
|
let fn_def = lib
|
||||||
.get_function_by_signature(name, args.len(), true)
|
.get_function_by_signature(name, args.len(), true)
|
||||||
.ok_or_else(|| Box::new(EvalAltResult::ErrorFunctionNotFound(name.into(), pos)))?;
|
.ok_or_else(|| {
|
||||||
|
Box::new(EvalAltResult::ErrorFunctionNotFound(
|
||||||
|
name.into(),
|
||||||
|
Position::none(),
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
let mut state = State::new();
|
let mut state = State::new();
|
||||||
let args = args.as_mut();
|
let args = args.as_mut();
|
||||||
|
|
||||||
self.call_script_fn(scope, &mut state, &lib, name, fn_def, args, pos, 0)
|
self.call_script_fn(scope, &mut state, &lib, name, fn_def, args, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Optimize the `AST` with constants defined in an external Scope.
|
/// Optimize the `AST` with constants defined in an external Scope.
|
||||||
@ -1159,7 +1137,7 @@ impl Engine {
|
|||||||
///
|
///
|
||||||
/// let mut engine = Engine::new();
|
/// let mut engine = Engine::new();
|
||||||
///
|
///
|
||||||
/// engine.on_progress(move |ops| {
|
/// engine.on_progress(move |&ops| {
|
||||||
/// if ops > 10000 {
|
/// if ops > 10000 {
|
||||||
/// false
|
/// false
|
||||||
/// } else if ops % 800 == 0 {
|
/// } else if ops % 800 == 0 {
|
||||||
@ -1178,7 +1156,7 @@ impl Engine {
|
|||||||
/// # Ok(())
|
/// # Ok(())
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn on_progress(&mut self, callback: impl Fn(u64) -> bool + SendSync + 'static) {
|
pub fn on_progress(&mut self, callback: impl Fn(&u64) -> bool + SendSync + 'static) {
|
||||||
self.progress = Some(Box::new(callback));
|
self.progress = Some(Box::new(callback));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
260
src/engine.rs
260
src/engine.rs
@ -3,7 +3,7 @@
|
|||||||
use crate::any::{Dynamic, Union};
|
use crate::any::{Dynamic, Union};
|
||||||
use crate::calc_fn_hash;
|
use crate::calc_fn_hash;
|
||||||
use crate::error::ParseErrorType;
|
use crate::error::ParseErrorType;
|
||||||
use crate::fn_native::{CallableFunction, FnCallArgs, Shared};
|
use crate::fn_native::{CallableFunction, Callback, FnCallArgs, Shared};
|
||||||
use crate::module::{resolvers, Module, ModuleResolver};
|
use crate::module::{resolvers, Module, ModuleResolver};
|
||||||
use crate::optimize::OptimizationLevel;
|
use crate::optimize::OptimizationLevel;
|
||||||
use crate::packages::{CorePackage, Package, PackageLibrary, PackagesCollection, StandardPackage};
|
use crate::packages::{CorePackage, Package, PackageLibrary, PackagesCollection, StandardPackage};
|
||||||
@ -116,17 +116,20 @@ impl Target<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Update the value of the `Target`.
|
/// Update the value of the `Target`.
|
||||||
pub fn set_value(&mut self, new_val: Dynamic, pos: Position) -> Result<(), Box<EvalAltResult>> {
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
|
pub fn set_value(&mut self, new_val: Dynamic) -> Result<(), Box<EvalAltResult>> {
|
||||||
match self {
|
match self {
|
||||||
Target::Ref(r) => **r = new_val,
|
Target::Ref(r) => **r = new_val,
|
||||||
Target::Value(_) => {
|
Target::Value(_) => {
|
||||||
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(pos)))
|
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
|
||||||
|
Position::none(),
|
||||||
|
)))
|
||||||
}
|
}
|
||||||
Target::StringChar(Dynamic(Union::Str(ref mut s)), index, _) => {
|
Target::StringChar(Dynamic(Union::Str(ref mut s)), index, _) => {
|
||||||
// Replace the character at the specified index position
|
// Replace the character at the specified index position
|
||||||
let new_ch = new_val
|
let new_ch = new_val
|
||||||
.as_char()
|
.as_char()
|
||||||
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
|
.map_err(|_| EvalAltResult::ErrorCharMismatch(Position::none()))?;
|
||||||
|
|
||||||
let mut chars: StaticVec<char> = s.chars().collect();
|
let mut chars: StaticVec<char> = s.chars().collect();
|
||||||
let ch = chars[*index];
|
let ch = chars[*index];
|
||||||
@ -299,26 +302,12 @@ pub struct Engine {
|
|||||||
/// A hashmap mapping type names to pretty-print names.
|
/// A hashmap mapping type names to pretty-print names.
|
||||||
pub(crate) type_names: HashMap<String, String>,
|
pub(crate) type_names: HashMap<String, String>,
|
||||||
|
|
||||||
/// Closure for implementing the `print` command.
|
/// Callback closure for implementing the `print` command.
|
||||||
#[cfg(not(feature = "sync"))]
|
pub(crate) print: Callback<str, ()>,
|
||||||
pub(crate) print: Box<dyn Fn(&str) + 'static>,
|
/// Callback closure for implementing the `debug` command.
|
||||||
/// Closure for implementing the `print` command.
|
pub(crate) debug: Callback<str, ()>,
|
||||||
#[cfg(feature = "sync")]
|
/// Callback closure for progress reporting.
|
||||||
pub(crate) print: Box<dyn Fn(&str) + Send + Sync + 'static>,
|
pub(crate) progress: Option<Callback<u64, bool>>,
|
||||||
|
|
||||||
/// Closure for implementing the `debug` command.
|
|
||||||
#[cfg(not(feature = "sync"))]
|
|
||||||
pub(crate) debug: Box<dyn Fn(&str) + 'static>,
|
|
||||||
/// Closure for implementing the `debug` command.
|
|
||||||
#[cfg(feature = "sync")]
|
|
||||||
pub(crate) debug: Box<dyn Fn(&str) + Send + Sync + 'static>,
|
|
||||||
|
|
||||||
/// Closure for progress reporting.
|
|
||||||
#[cfg(not(feature = "sync"))]
|
|
||||||
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + 'static>>,
|
|
||||||
/// Closure for progress reporting.
|
|
||||||
#[cfg(feature = "sync")]
|
|
||||||
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + Send + Sync + 'static>>,
|
|
||||||
|
|
||||||
/// Optimize the AST after compilation.
|
/// Optimize the AST after compilation.
|
||||||
pub(crate) optimization_level: OptimizationLevel,
|
pub(crate) optimization_level: OptimizationLevel,
|
||||||
@ -575,6 +564,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Universal method for calling functions either registered with the `Engine` or written in Rhai.
|
/// Universal method for calling functions either registered with the `Engine` or written in Rhai.
|
||||||
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
///
|
///
|
||||||
/// ## WARNING
|
/// ## WARNING
|
||||||
///
|
///
|
||||||
@ -591,10 +581,9 @@ impl Engine {
|
|||||||
args: &mut FnCallArgs,
|
args: &mut FnCallArgs,
|
||||||
is_ref: bool,
|
is_ref: bool,
|
||||||
def_val: Option<&Dynamic>,
|
def_val: Option<&Dynamic>,
|
||||||
pos: Position,
|
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, pos)?;
|
self.inc_operations(state)?;
|
||||||
|
|
||||||
let native_only = hashes.1 == 0;
|
let native_only = hashes.1 == 0;
|
||||||
|
|
||||||
@ -603,7 +592,9 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
{
|
{
|
||||||
if level > self.max_call_stack_depth {
|
if level > self.max_call_stack_depth {
|
||||||
return Err(Box::new(EvalAltResult::ErrorStackOverflow(pos)));
|
return Err(Box::new(
|
||||||
|
EvalAltResult::ErrorStackOverflow(Position::none()),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -650,7 +641,7 @@ impl Engine {
|
|||||||
|
|
||||||
// Run scripted function
|
// Run scripted function
|
||||||
let result =
|
let result =
|
||||||
self.call_script_fn(scope, state, lib, fn_name, fn_def, args, pos, level)?;
|
self.call_script_fn(scope, state, lib, fn_name, fn_def, args, level)?;
|
||||||
|
|
||||||
// Restore the original reference
|
// Restore the original reference
|
||||||
restore_first_arg(old_this_ptr, args);
|
restore_first_arg(old_this_ptr, args);
|
||||||
@ -674,20 +665,18 @@ impl Engine {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Run external function
|
// Run external function
|
||||||
let result = func.get_native_fn()(args);
|
let result = func.get_native_fn()(args)?;
|
||||||
|
|
||||||
// Restore the original reference
|
// Restore the original reference
|
||||||
restore_first_arg(old_this_ptr, args);
|
restore_first_arg(old_this_ptr, args);
|
||||||
|
|
||||||
let result = result.map_err(|err| err.new_position(pos))?;
|
|
||||||
|
|
||||||
// See if the function match print/debug (which requires special processing)
|
// See if the function match print/debug (which requires special processing)
|
||||||
return Ok(match fn_name {
|
return Ok(match fn_name {
|
||||||
KEYWORD_PRINT => (
|
KEYWORD_PRINT => (
|
||||||
(self.print)(result.as_str().map_err(|type_name| {
|
(self.print)(result.as_str().map_err(|type_name| {
|
||||||
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
||||||
type_name.into(),
|
type_name.into(),
|
||||||
pos,
|
Position::none(),
|
||||||
))
|
))
|
||||||
})?)
|
})?)
|
||||||
.into(),
|
.into(),
|
||||||
@ -697,7 +686,7 @@ impl Engine {
|
|||||||
(self.debug)(result.as_str().map_err(|type_name| {
|
(self.debug)(result.as_str().map_err(|type_name| {
|
||||||
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
||||||
type_name.into(),
|
type_name.into(),
|
||||||
pos,
|
Position::none(),
|
||||||
))
|
))
|
||||||
})?)
|
})?)
|
||||||
.into(),
|
.into(),
|
||||||
@ -724,7 +713,7 @@ impl Engine {
|
|||||||
if let Some(prop) = extract_prop_from_getter(fn_name) {
|
if let Some(prop) = extract_prop_from_getter(fn_name) {
|
||||||
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
||||||
format!("- property '{}' unknown or write-only", prop),
|
format!("- property '{}' unknown or write-only", prop),
|
||||||
pos,
|
Position::none(),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -732,7 +721,7 @@ impl Engine {
|
|||||||
if let Some(prop) = extract_prop_from_setter(fn_name) {
|
if let Some(prop) = extract_prop_from_setter(fn_name) {
|
||||||
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
||||||
format!("- property '{}' unknown or read-only", prop),
|
format!("- property '{}' unknown or read-only", prop),
|
||||||
pos,
|
Position::none(),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -745,18 +734,19 @@ impl Engine {
|
|||||||
if fn_name == FUNC_INDEXER {
|
if fn_name == FUNC_INDEXER {
|
||||||
return Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
|
return Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
|
||||||
format!("[]({})", types_list.join(", ")),
|
format!("[]({})", types_list.join(", ")),
|
||||||
pos,
|
Position::none(),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Raise error
|
// Raise error
|
||||||
Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
|
Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
|
||||||
format!("{} ({})", fn_name, types_list.join(", ")),
|
format!("{} ({})", fn_name, types_list.join(", ")),
|
||||||
pos,
|
Position::none(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Call a script-defined function.
|
/// Call a script-defined function.
|
||||||
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
///
|
///
|
||||||
/// ## WARNING
|
/// ## WARNING
|
||||||
///
|
///
|
||||||
@ -771,7 +761,6 @@ impl Engine {
|
|||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
fn_def: &FnDef,
|
fn_def: &FnDef,
|
||||||
args: &mut FnCallArgs,
|
args: &mut FnCallArgs,
|
||||||
pos: Position,
|
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
let orig_scope_level = state.scope_level;
|
let orig_scope_level = state.scope_level;
|
||||||
@ -798,13 +787,17 @@ impl Engine {
|
|||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
// Convert return statement to return value
|
// Convert return statement to return value
|
||||||
EvalAltResult::Return(x, _) => Ok(x),
|
EvalAltResult::Return(x, _) => Ok(x),
|
||||||
EvalAltResult::ErrorInFunctionCall(name, err, _) => Err(Box::new(
|
EvalAltResult::ErrorInFunctionCall(name, err, _) => {
|
||||||
EvalAltResult::ErrorInFunctionCall(format!("{} > {}", fn_name, name), err, pos),
|
Err(Box::new(EvalAltResult::ErrorInFunctionCall(
|
||||||
)),
|
format!("{} > {}", fn_name, name),
|
||||||
|
err,
|
||||||
|
Position::none(),
|
||||||
|
)))
|
||||||
|
}
|
||||||
_ => Err(Box::new(EvalAltResult::ErrorInFunctionCall(
|
_ => Err(Box::new(EvalAltResult::ErrorInFunctionCall(
|
||||||
fn_name.to_string(),
|
fn_name.to_string(),
|
||||||
err,
|
err,
|
||||||
pos,
|
Position::none(),
|
||||||
))),
|
))),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -825,7 +818,8 @@ impl Engine {
|
|||||||
|| lib.contains_key(&hashes.1)
|
|| lib.contains_key(&hashes.1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Perform an actual function call, taking care of special functions
|
/// Perform an actual function call, taking care of special functions
|
||||||
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
///
|
///
|
||||||
/// ## WARNING
|
/// ## WARNING
|
||||||
///
|
///
|
||||||
@ -842,7 +836,6 @@ impl Engine {
|
|||||||
args: &mut FnCallArgs,
|
args: &mut FnCallArgs,
|
||||||
is_ref: bool,
|
is_ref: bool,
|
||||||
def_val: Option<&Dynamic>,
|
def_val: Option<&Dynamic>,
|
||||||
pos: Position,
|
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
||||||
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
|
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
|
||||||
@ -865,7 +858,7 @@ impl Engine {
|
|||||||
KEYWORD_EVAL if args.len() == 1 && !self.has_override(lib, hashes) => {
|
KEYWORD_EVAL if args.len() == 1 && !self.has_override(lib, hashes) => {
|
||||||
Err(Box::new(EvalAltResult::ErrorRuntime(
|
Err(Box::new(EvalAltResult::ErrorRuntime(
|
||||||
"'eval' should not be called in method style. Try eval(...);".into(),
|
"'eval' should not be called in method style. Try eval(...);".into(),
|
||||||
pos,
|
Position::none(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -873,24 +866,24 @@ impl Engine {
|
|||||||
_ => {
|
_ => {
|
||||||
let mut scope = Scope::new();
|
let mut scope = Scope::new();
|
||||||
self.call_fn_raw(
|
self.call_fn_raw(
|
||||||
&mut scope, state, lib, fn_name, hashes, args, is_ref, def_val, pos, level,
|
&mut scope, state, lib, fn_name, hashes, args, is_ref, def_val, level,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate a text string as a script - used primarily for 'eval'.
|
/// Evaluate a text string as a script - used primarily for 'eval'.
|
||||||
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
fn eval_script_expr(
|
fn eval_script_expr(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
lib: &FunctionsLib,
|
lib: &FunctionsLib,
|
||||||
script: &Dynamic,
|
script: &Dynamic,
|
||||||
pos: Position,
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
let script = script
|
let script = script.as_str().map_err(|type_name| {
|
||||||
.as_str()
|
EvalAltResult::ErrorMismatchOutputType(type_name.into(), Position::none())
|
||||||
.map_err(|type_name| EvalAltResult::ErrorMismatchOutputType(type_name.into(), pos))?;
|
})?;
|
||||||
|
|
||||||
// Compile the script text
|
// Compile the script text
|
||||||
// No optimizations because we only run it once
|
// No optimizations because we only run it once
|
||||||
@ -903,7 +896,7 @@ impl Engine {
|
|||||||
// If new functions are defined within the eval string, it is an error
|
// If new functions are defined within the eval string, it is an error
|
||||||
if !ast.lib().is_empty() {
|
if !ast.lib().is_empty() {
|
||||||
return Err(Box::new(EvalAltResult::ErrorParsing(
|
return Err(Box::new(EvalAltResult::ErrorParsing(
|
||||||
ParseErrorType::WrongFnDefinition.into_err(pos),
|
ParseErrorType::WrongFnDefinition.into_err(Position::none()),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -911,17 +904,16 @@ impl Engine {
|
|||||||
let ast = AST::new(statements, lib.clone());
|
let ast = AST::new(statements, lib.clone());
|
||||||
|
|
||||||
// Evaluate the AST
|
// Evaluate the AST
|
||||||
let (result, operations) = self
|
let (result, operations) = self.eval_ast_with_scope_raw(scope, &ast)?;
|
||||||
.eval_ast_with_scope_raw(scope, &ast)
|
|
||||||
.map_err(|err| err.new_position(pos))?;
|
|
||||||
|
|
||||||
state.operations += operations;
|
state.operations += operations;
|
||||||
self.inc_operations(state, pos)?;
|
self.inc_operations(state)?;
|
||||||
|
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Chain-evaluate a dot/index chain.
|
/// Chain-evaluate a dot/index chain.
|
||||||
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
fn eval_dot_index_chain_helper(
|
fn eval_dot_index_chain_helper(
|
||||||
&self,
|
&self,
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
@ -930,7 +922,6 @@ impl Engine {
|
|||||||
rhs: &Expr,
|
rhs: &Expr,
|
||||||
idx_values: &mut StaticVec<Dynamic>,
|
idx_values: &mut StaticVec<Dynamic>,
|
||||||
is_index: bool,
|
is_index: bool,
|
||||||
op_pos: Position,
|
|
||||||
level: usize,
|
level: usize,
|
||||||
mut new_val: Option<Dynamic>,
|
mut new_val: Option<Dynamic>,
|
||||||
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
||||||
@ -951,25 +942,27 @@ impl Engine {
|
|||||||
let (idx, expr, pos) = x.as_ref();
|
let (idx, expr, pos) = x.as_ref();
|
||||||
let is_idx = matches!(rhs, Expr::Index(_));
|
let is_idx = matches!(rhs, Expr::Index(_));
|
||||||
let idx_pos = idx.position();
|
let idx_pos = idx.position();
|
||||||
let this_ptr = &mut self.get_indexed_mut(
|
let this_ptr = &mut self
|
||||||
state, lib, obj, is_ref, idx_val, idx_pos, op_pos, false,
|
.get_indexed_mut(state, lib, obj, is_ref, idx_val, idx_pos, false)?;
|
||||||
)?;
|
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
state, lib, this_ptr, expr, idx_values, is_idx, *pos, level, new_val,
|
state, lib, this_ptr, expr, idx_values, is_idx, level, new_val,
|
||||||
)
|
)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
// xxx[rhs] = new_val
|
// xxx[rhs] = new_val
|
||||||
_ if new_val.is_some() => {
|
_ if new_val.is_some() => {
|
||||||
let this_ptr = &mut self
|
let this_ptr =
|
||||||
.get_indexed_mut(state, lib, obj, is_ref, idx_val, pos, op_pos, true)?;
|
&mut self.get_indexed_mut(state, lib, obj, is_ref, idx_val, pos, true)?;
|
||||||
|
|
||||||
this_ptr.set_value(new_val.unwrap(), rhs.position())?;
|
this_ptr
|
||||||
|
.set_value(new_val.unwrap())
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, rhs.position()))?;
|
||||||
Ok((Default::default(), true))
|
Ok((Default::default(), true))
|
||||||
}
|
}
|
||||||
// xxx[rhs]
|
// xxx[rhs]
|
||||||
_ => self
|
_ => self
|
||||||
.get_indexed_mut(state, lib, obj, is_ref, idx_val, pos, op_pos, false)
|
.get_indexed_mut(state, lib, obj, is_ref, idx_val, pos, false)
|
||||||
.map(|v| (v.clone_into_dynamic(), false)),
|
.map(|v| (v.clone_into_dynamic(), false)),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -989,9 +982,8 @@ impl Engine {
|
|||||||
.collect();
|
.collect();
|
||||||
let args = arg_values.as_mut();
|
let args = arg_values.as_mut();
|
||||||
|
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(state, lib, name, *native, *hash, args, is_ref, def_val, 0)
|
||||||
state, lib, name, *native, *hash, args, is_ref, def_val, *pos, 0,
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
// xxx.module::fn_name(...) - syntax error
|
// xxx.module::fn_name(...) - syntax error
|
||||||
Expr::FnCall(_) => unreachable!(),
|
Expr::FnCall(_) => unreachable!(),
|
||||||
@ -1001,9 +993,10 @@ impl Engine {
|
|||||||
let ((prop, _, _), pos) = x.as_ref();
|
let ((prop, _, _), pos) = x.as_ref();
|
||||||
let index = prop.clone().into();
|
let index = prop.clone().into();
|
||||||
let mut val =
|
let mut val =
|
||||||
self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, op_pos, true)?;
|
self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, true)?;
|
||||||
|
|
||||||
val.set_value(new_val.unwrap(), rhs.position())?;
|
val.set_value(new_val.unwrap())
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, rhs.position()))?;
|
||||||
Ok((Default::default(), true))
|
Ok((Default::default(), true))
|
||||||
}
|
}
|
||||||
// {xxx:map}.id
|
// {xxx:map}.id
|
||||||
@ -1011,8 +1004,7 @@ impl Engine {
|
|||||||
Expr::Property(x) if obj.is::<Map>() => {
|
Expr::Property(x) if obj.is::<Map>() => {
|
||||||
let ((prop, _, _), pos) = x.as_ref();
|
let ((prop, _, _), pos) = x.as_ref();
|
||||||
let index = prop.clone().into();
|
let index = prop.clone().into();
|
||||||
let val =
|
let val = self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, false)?;
|
||||||
self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, op_pos, false)?;
|
|
||||||
|
|
||||||
Ok((val.clone_into_dynamic(), false))
|
Ok((val.clone_into_dynamic(), false))
|
||||||
}
|
}
|
||||||
@ -1020,19 +1012,17 @@ impl Engine {
|
|||||||
Expr::Property(x) if new_val.is_some() => {
|
Expr::Property(x) if new_val.is_some() => {
|
||||||
let ((_, _, setter), pos) = x.as_ref();
|
let ((_, _, setter), pos) = x.as_ref();
|
||||||
let mut args = [obj, new_val.as_mut().unwrap()];
|
let mut args = [obj, new_val.as_mut().unwrap()];
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(state, lib, setter, true, 0, &mut args, is_ref, None, 0)
|
||||||
state, lib, setter, true, 0, &mut args, is_ref, None, *pos, 0,
|
|
||||||
)
|
|
||||||
.map(|(v, _)| (v, true))
|
.map(|(v, _)| (v, true))
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
// xxx.id
|
// xxx.id
|
||||||
Expr::Property(x) => {
|
Expr::Property(x) => {
|
||||||
let ((_, getter, _), pos) = x.as_ref();
|
let ((_, getter, _), pos) = x.as_ref();
|
||||||
let mut args = [obj];
|
let mut args = [obj];
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(state, lib, getter, true, 0, &mut args, is_ref, None, 0)
|
||||||
state, lib, getter, true, 0, &mut args, is_ref, None, *pos, 0,
|
|
||||||
)
|
|
||||||
.map(|(v, _)| (v, false))
|
.map(|(v, _)| (v, false))
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
// {xxx:map}.prop[expr] | {xxx:map}.prop.expr
|
// {xxx:map}.prop[expr] | {xxx:map}.prop.expr
|
||||||
@ -1043,14 +1033,15 @@ impl Engine {
|
|||||||
let mut val = if let Expr::Property(p) = prop {
|
let mut val = if let Expr::Property(p) = prop {
|
||||||
let ((prop, _, _), _) = p.as_ref();
|
let ((prop, _, _), _) = p.as_ref();
|
||||||
let index = prop.clone().into();
|
let index = prop.clone().into();
|
||||||
self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, op_pos, false)?
|
self.get_indexed_mut(state, lib, obj, is_ref, index, *pos, false)?
|
||||||
} else {
|
} else {
|
||||||
unreachable!();
|
unreachable!();
|
||||||
};
|
};
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
state, lib, &mut val, expr, idx_values, is_idx, *pos, level, new_val,
|
state, lib, &mut val, expr, idx_values, is_idx, level, new_val,
|
||||||
)
|
)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
// xxx.prop[expr] | xxx.prop.expr
|
// xxx.prop[expr] | xxx.prop.expr
|
||||||
Expr::Index(x) | Expr::Dot(x) => {
|
Expr::Index(x) | Expr::Dot(x) => {
|
||||||
@ -1061,16 +1052,19 @@ impl Engine {
|
|||||||
let (mut val, updated) = if let Expr::Property(p) = prop {
|
let (mut val, updated) = if let Expr::Property(p) = prop {
|
||||||
let ((_, getter, _), _) = p.as_ref();
|
let ((_, getter, _), _) = p.as_ref();
|
||||||
let args = &mut args[..1];
|
let args = &mut args[..1];
|
||||||
self.exec_fn_call(state, lib, getter, true, 0, args, is_ref, None, *pos, 0)?
|
self.exec_fn_call(state, lib, getter, true, 0, args, is_ref, None, 0)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))?
|
||||||
} else {
|
} else {
|
||||||
unreachable!();
|
unreachable!();
|
||||||
};
|
};
|
||||||
let val = &mut val;
|
let val = &mut val;
|
||||||
let target = &mut val.into();
|
let target = &mut val.into();
|
||||||
|
|
||||||
let (result, may_be_changed) = self.eval_dot_index_chain_helper(
|
let (result, may_be_changed) = self
|
||||||
state, lib, target, expr, idx_values, is_idx, *pos, level, new_val,
|
.eval_dot_index_chain_helper(
|
||||||
)?;
|
state, lib, target, expr, idx_values, is_idx, level, new_val,
|
||||||
|
)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))?;
|
||||||
|
|
||||||
// Feed the value back via a setter just in case it has been updated
|
// Feed the value back via a setter just in case it has been updated
|
||||||
if updated || may_be_changed {
|
if updated || may_be_changed {
|
||||||
@ -1078,13 +1072,11 @@ impl Engine {
|
|||||||
let ((_, _, setter), _) = p.as_ref();
|
let ((_, _, setter), _) = p.as_ref();
|
||||||
// Re-use args because the first &mut parameter will not be consumed
|
// Re-use args because the first &mut parameter will not be consumed
|
||||||
args[1] = val;
|
args[1] = val;
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(state, lib, setter, true, 0, args, is_ref, None, 0)
|
||||||
state, lib, setter, true, 0, args, is_ref, None, *pos, 0,
|
|
||||||
)
|
|
||||||
.or_else(|err| match *err {
|
.or_else(|err| match *err {
|
||||||
// If there is no setter, no need to feed it back because the property is read-only
|
// If there is no setter, no need to feed it back because the property is read-only
|
||||||
EvalAltResult::ErrorDotExpr(_, _) => Ok(Default::default()),
|
EvalAltResult::ErrorDotExpr(_, _) => Ok(Default::default()),
|
||||||
err => Err(Box::new(err)),
|
err => Err(EvalAltResult::new_position(Box::new(err), *pos)),
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1124,7 +1116,8 @@ impl Engine {
|
|||||||
// id.??? or id[???]
|
// id.??? or id[???]
|
||||||
Expr::Variable(_) => {
|
Expr::Variable(_) => {
|
||||||
let (target, name, typ, pos) = search_scope(scope, state, dot_lhs)?;
|
let (target, name, typ, pos) = search_scope(scope, state, dot_lhs)?;
|
||||||
self.inc_operations(state, pos)?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, pos))?;
|
||||||
|
|
||||||
// Constants cannot be modified
|
// Constants cannot be modified
|
||||||
match typ {
|
match typ {
|
||||||
@ -1140,9 +1133,10 @@ impl Engine {
|
|||||||
|
|
||||||
let this_ptr = &mut target.into();
|
let this_ptr = &mut target.into();
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
state, lib, this_ptr, dot_rhs, idx_values, is_index, *op_pos, level, new_val,
|
state, lib, this_ptr, dot_rhs, idx_values, is_index, level, new_val,
|
||||||
)
|
)
|
||||||
.map(|(v, _)| v)
|
.map(|(v, _)| v)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *op_pos))
|
||||||
}
|
}
|
||||||
// {expr}.??? = ??? or {expr}[???] = ???
|
// {expr}.??? = ??? or {expr}[???] = ???
|
||||||
expr if new_val.is_some() => {
|
expr if new_val.is_some() => {
|
||||||
@ -1155,9 +1149,10 @@ impl Engine {
|
|||||||
let val = self.eval_expr(scope, state, lib, expr, level)?;
|
let val = self.eval_expr(scope, state, lib, expr, level)?;
|
||||||
let this_ptr = &mut val.into();
|
let this_ptr = &mut val.into();
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
state, lib, this_ptr, dot_rhs, idx_values, is_index, *op_pos, level, new_val,
|
state, lib, this_ptr, dot_rhs, idx_values, is_index, level, new_val,
|
||||||
)
|
)
|
||||||
.map(|(v, _)| v)
|
.map(|(v, _)| v)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *op_pos))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1177,7 +1172,8 @@ impl Engine {
|
|||||||
size: usize,
|
size: usize,
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<(), Box<EvalAltResult>> {
|
) -> Result<(), Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, expr.position())?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, expr.position()))?;
|
||||||
|
|
||||||
match expr {
|
match expr {
|
||||||
Expr::FnCall(x) if x.1.is_none() => {
|
Expr::FnCall(x) if x.1.is_none() => {
|
||||||
@ -1211,6 +1207,7 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get the value at the indexed position of a base type
|
/// Get the value at the indexed position of a base type
|
||||||
|
/// Position in `EvalAltResult` may be None and should be set afterwards.
|
||||||
fn get_indexed_mut<'a>(
|
fn get_indexed_mut<'a>(
|
||||||
&self,
|
&self,
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
@ -1219,10 +1216,9 @@ impl Engine {
|
|||||||
is_ref: bool,
|
is_ref: bool,
|
||||||
mut idx: Dynamic,
|
mut idx: Dynamic,
|
||||||
idx_pos: Position,
|
idx_pos: Position,
|
||||||
op_pos: Position,
|
|
||||||
create: bool,
|
create: bool,
|
||||||
) -> Result<Target<'a>, Box<EvalAltResult>> {
|
) -> Result<Target<'a>, Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, op_pos)?;
|
self.inc_operations(state)?;
|
||||||
|
|
||||||
match val {
|
match val {
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
@ -1292,10 +1288,13 @@ impl Engine {
|
|||||||
let fn_name = FUNC_INDEXER;
|
let fn_name = FUNC_INDEXER;
|
||||||
let type_name = self.map_type_name(val.type_name());
|
let type_name = self.map_type_name(val.type_name());
|
||||||
let args = &mut [val, &mut idx];
|
let args = &mut [val, &mut idx];
|
||||||
self.exec_fn_call(state, lib, fn_name, true, 0, args, is_ref, None, op_pos, 0)
|
self.exec_fn_call(state, lib, fn_name, true, 0, args, is_ref, None, 0)
|
||||||
.map(|(v, _)| v.into())
|
.map(|(v, _)| v.into())
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
Box::new(EvalAltResult::ErrorIndexingType(type_name.into(), op_pos))
|
Box::new(EvalAltResult::ErrorIndexingType(
|
||||||
|
type_name.into(),
|
||||||
|
Position::none(),
|
||||||
|
))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1311,7 +1310,8 @@ impl Engine {
|
|||||||
rhs: &Expr,
|
rhs: &Expr,
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, rhs.position())?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, rhs.position()))?;
|
||||||
|
|
||||||
let lhs_value = self.eval_expr(scope, state, lib, lhs, level)?;
|
let lhs_value = self.eval_expr(scope, state, lib, lhs, level)?;
|
||||||
let rhs_value = self.eval_expr(scope, state, lib, rhs, level)?;
|
let rhs_value = self.eval_expr(scope, state, lib, rhs, level)?;
|
||||||
@ -1327,7 +1327,6 @@ impl Engine {
|
|||||||
for value in rhs_value.iter_mut() {
|
for value in rhs_value.iter_mut() {
|
||||||
let args = &mut [&mut lhs_value.clone(), value];
|
let args = &mut [&mut lhs_value.clone(), value];
|
||||||
let def_value = Some(&def_value);
|
let def_value = Some(&def_value);
|
||||||
let pos = rhs.position();
|
|
||||||
|
|
||||||
let hashes = (
|
let hashes = (
|
||||||
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
|
// Qualifiers (none) + function name + number of arguments + argument `TypeId`'s.
|
||||||
@ -1335,9 +1334,11 @@ impl Engine {
|
|||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
|
||||||
let (r, _) = self.call_fn_raw(
|
let (r, _) = self
|
||||||
&mut scope, state, lib, op, hashes, args, false, def_value, pos, level,
|
.call_fn_raw(
|
||||||
)?;
|
&mut scope, state, lib, op, hashes, args, false, def_value, level,
|
||||||
|
)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, rhs.position()))?;
|
||||||
if r.as_bool().unwrap_or(false) {
|
if r.as_bool().unwrap_or(false) {
|
||||||
return Ok(true.into());
|
return Ok(true.into());
|
||||||
}
|
}
|
||||||
@ -1371,7 +1372,8 @@ impl Engine {
|
|||||||
expr: &Expr,
|
expr: &Expr,
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, expr.position())?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, expr.position()))?;
|
||||||
|
|
||||||
match expr {
|
match expr {
|
||||||
Expr::Expr(x) => self.eval_expr(scope, state, lib, x.as_ref(), level),
|
Expr::Expr(x) => self.eval_expr(scope, state, lib, x.as_ref(), level),
|
||||||
@ -1395,7 +1397,8 @@ impl Engine {
|
|||||||
let (lhs_expr, op, rhs_expr, op_pos) = x.as_ref();
|
let (lhs_expr, op, rhs_expr, op_pos) = x.as_ref();
|
||||||
let mut rhs_val = self.eval_expr(scope, state, lib, rhs_expr, level)?;
|
let mut rhs_val = self.eval_expr(scope, state, lib, rhs_expr, level)?;
|
||||||
let (lhs_ptr, name, typ, pos) = search_scope(scope, state, lhs_expr)?;
|
let (lhs_ptr, name, typ, pos) = search_scope(scope, state, lhs_expr)?;
|
||||||
self.inc_operations(state, pos)?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, pos))?;
|
||||||
|
|
||||||
match typ {
|
match typ {
|
||||||
// Assignment to constant variable
|
// Assignment to constant variable
|
||||||
@ -1432,10 +1435,9 @@ impl Engine {
|
|||||||
|
|
||||||
// Set variable value
|
// Set variable value
|
||||||
*lhs_ptr = self
|
*lhs_ptr = self
|
||||||
.exec_fn_call(
|
.exec_fn_call(state, lib, op, true, hash, args, false, None, level)
|
||||||
state, lib, op, true, hash, args, false, None, *op_pos, level,
|
.map(|(v, _)| v)
|
||||||
)
|
.map_err(|err| EvalAltResult::new_position(err, *op_pos))?;
|
||||||
.map(|(v, _)| v)?;
|
|
||||||
}
|
}
|
||||||
Ok(Default::default())
|
Ok(Default::default())
|
||||||
}
|
}
|
||||||
@ -1460,10 +1462,9 @@ impl Engine {
|
|||||||
&mut self.eval_expr(scope, state, lib, lhs_expr, level)?,
|
&mut self.eval_expr(scope, state, lib, lhs_expr, level)?,
|
||||||
&mut rhs_val,
|
&mut rhs_val,
|
||||||
];
|
];
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(state, lib, op, true, hash, args, false, None, level)
|
||||||
state, lib, op, true, hash, args, false, None, *op_pos, level,
|
.map(|(v, _)| v)
|
||||||
)
|
.map_err(|err| EvalAltResult::new_position(err, *op_pos))?
|
||||||
.map(|(v, _)| v)?
|
|
||||||
});
|
});
|
||||||
|
|
||||||
match lhs_expr {
|
match lhs_expr {
|
||||||
@ -1531,11 +1532,11 @@ impl Engine {
|
|||||||
if !self.has_override(lib, (hash_fn, *hash)) {
|
if !self.has_override(lib, (hash_fn, *hash)) {
|
||||||
// eval - only in function call style
|
// eval - only in function call style
|
||||||
let prev_len = scope.len();
|
let prev_len = scope.len();
|
||||||
let pos = args_expr.get(0).position();
|
let expr = args_expr.get(0);
|
||||||
|
let script = self.eval_expr(scope, state, lib, expr, level)?;
|
||||||
// Evaluate the text string as a script
|
let result = self
|
||||||
let script = self.eval_expr(scope, state, lib, args_expr.get(0), level)?;
|
.eval_script_expr(scope, state, lib, &script)
|
||||||
let result = self.eval_script_expr(scope, state, lib, &script, pos);
|
.map_err(|err| EvalAltResult::new_position(err, expr.position()));
|
||||||
|
|
||||||
if scope.len() != prev_len {
|
if scope.len() != prev_len {
|
||||||
// IMPORTANT! If the eval defines new variables in the current scope,
|
// IMPORTANT! If the eval defines new variables in the current scope,
|
||||||
@ -1568,7 +1569,8 @@ impl Engine {
|
|||||||
.collect::<Result<_, _>>()?;
|
.collect::<Result<_, _>>()?;
|
||||||
|
|
||||||
let (target, _, typ, pos) = search_scope(scope, state, lhs)?;
|
let (target, _, typ, pos) = search_scope(scope, state, lhs)?;
|
||||||
self.inc_operations(state, pos)?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, pos))?;
|
||||||
|
|
||||||
match typ {
|
match typ {
|
||||||
ScopeEntryType::Module => unreachable!(),
|
ScopeEntryType::Module => unreachable!(),
|
||||||
@ -1593,9 +1595,10 @@ impl Engine {
|
|||||||
|
|
||||||
let args = args.as_mut();
|
let args = args.as_mut();
|
||||||
self.exec_fn_call(
|
self.exec_fn_call(
|
||||||
state, lib, name, *native, *hash, args, is_ref, def_val, *pos, level,
|
state, lib, name, *native, *hash, args, is_ref, def_val, level,
|
||||||
)
|
)
|
||||||
.map(|(v, _)| v)
|
.map(|(v, _)| v)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Module-qualified function call
|
// Module-qualified function call
|
||||||
@ -1628,7 +1631,8 @@ impl Engine {
|
|||||||
let func = match module.get_qualified_fn(name, *hash_fn_def) {
|
let func = match module.get_qualified_fn(name, *hash_fn_def) {
|
||||||
Err(err) if matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) => {
|
Err(err) if matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) => {
|
||||||
// Then search in Rust functions
|
// Then search in Rust functions
|
||||||
self.inc_operations(state, *pos)?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))?;
|
||||||
|
|
||||||
// Rust functions are indexed in two steps:
|
// Rust functions are indexed in two steps:
|
||||||
// 1) Calculate a hash in a similar manner to script-defined functions,
|
// 1) Calculate a hash in a similar manner to script-defined functions,
|
||||||
@ -1650,7 +1654,8 @@ impl Engine {
|
|||||||
let args = args.as_mut();
|
let args = args.as_mut();
|
||||||
let fn_def = x.get_fn_def();
|
let fn_def = x.get_fn_def();
|
||||||
let mut scope = Scope::new();
|
let mut scope = Scope::new();
|
||||||
self.call_script_fn(&mut scope, state, lib, name, fn_def, args, *pos, level)
|
self.call_script_fn(&mut scope, state, lib, name, fn_def, args, level)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, *pos))
|
||||||
}
|
}
|
||||||
Ok(x) if x.is_plugin_fn() => x.get_plugin_fn().call(args.as_mut(), *pos),
|
Ok(x) if x.is_plugin_fn() => x.get_plugin_fn().call(args.as_mut(), *pos),
|
||||||
Ok(x) => x.get_native_fn()(args.as_mut()).map_err(|err| err.new_position(*pos)),
|
Ok(x) => x.get_native_fn()(args.as_mut()).map_err(|err| err.new_position(*pos)),
|
||||||
@ -1719,7 +1724,8 @@ impl Engine {
|
|||||||
stmt: &Stmt,
|
stmt: &Stmt,
|
||||||
level: usize,
|
level: usize,
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
self.inc_operations(state, stmt.position())?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, stmt.position()))?;
|
||||||
|
|
||||||
match stmt {
|
match stmt {
|
||||||
// No-op
|
// No-op
|
||||||
@ -1824,7 +1830,8 @@ impl Engine {
|
|||||||
|
|
||||||
for loop_var in func(iter_type) {
|
for loop_var in func(iter_type) {
|
||||||
*scope.get_mut(index).0 = loop_var;
|
*scope.get_mut(index).0 = loop_var;
|
||||||
self.inc_operations(state, stmt.position())?;
|
self.inc_operations(state)
|
||||||
|
.map_err(|err| EvalAltResult::new_position(err, stmt.position()))?;
|
||||||
|
|
||||||
match self.eval_stmt(scope, state, lib, stmt, level) {
|
match self.eval_stmt(scope, state, lib, stmt, level) {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
@ -1976,22 +1983,25 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Check if the number of operations stay within limit.
|
/// Check if the number of operations stay within limit.
|
||||||
fn inc_operations(&self, state: &mut State, pos: Position) -> Result<(), Box<EvalAltResult>> {
|
/// Position in `EvalAltResult` is None and must be set afterwards.
|
||||||
|
fn inc_operations(&self, state: &mut State) -> Result<(), Box<EvalAltResult>> {
|
||||||
state.operations += 1;
|
state.operations += 1;
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
{
|
{
|
||||||
// Guard against too many operations
|
// Guard against too many operations
|
||||||
if state.operations > self.max_operations {
|
if state.operations > self.max_operations {
|
||||||
return Err(Box::new(EvalAltResult::ErrorTooManyOperations(pos)));
|
return Err(Box::new(EvalAltResult::ErrorTooManyOperations(
|
||||||
|
Position::none(),
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Report progress - only in steps
|
// Report progress - only in steps
|
||||||
if let Some(progress) = &self.progress {
|
if let Some(progress) = &self.progress {
|
||||||
if !progress(state.operations) {
|
if !progress(&state.operations) {
|
||||||
// Terminate script if progress returns false
|
// Terminate script if progress returns false
|
||||||
return Err(Box::new(EvalAltResult::ErrorTerminated(pos)));
|
return Err(Box::new(EvalAltResult::ErrorTerminated(Position::none())));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use crate::any::Dynamic;
|
use crate::any::Dynamic;
|
||||||
use crate::parser::FnDef;
|
use crate::parser::FnDef;
|
||||||
|
use crate::plugin::PluginFunction;
|
||||||
use crate::result::EvalAltResult;
|
use crate::result::EvalAltResult;
|
||||||
use crate::token::Position;
|
|
||||||
|
|
||||||
use crate::stdlib::{boxed::Box, rc::Rc, sync::Arc};
|
use crate::stdlib::{boxed::Box, rc::Rc, sync::Arc};
|
||||||
|
|
||||||
@ -63,7 +63,10 @@ pub type SharedPluginFunction = Arc<dyn PluginFunction + Send + Sync>;
|
|||||||
#[cfg(not(feature = "sync"))]
|
#[cfg(not(feature = "sync"))]
|
||||||
pub type SharedPluginFunction = Rc<dyn PluginFunction>;
|
pub type SharedPluginFunction = Rc<dyn PluginFunction>;
|
||||||
|
|
||||||
use crate::plugin::PluginFunction;
|
#[cfg(not(feature = "sync"))]
|
||||||
|
pub type Callback<T, R> = Box<dyn Fn(&T) -> R + 'static>;
|
||||||
|
#[cfg(feature = "sync")]
|
||||||
|
pub type Callback<T, R> = Box<dyn Fn(&T) -> R + Send + Sync + 'static>;
|
||||||
|
|
||||||
/// A type encapsulating a function callable by Rhai.
|
/// A type encapsulating a function callable by Rhai.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
@ -5,9 +5,7 @@ use crate::engine::{
|
|||||||
KEYWORD_TYPE_OF,
|
KEYWORD_TYPE_OF,
|
||||||
};
|
};
|
||||||
use crate::parser::{map_dynamic_to_expr, Expr, FnDef, ReturnType, Stmt, AST};
|
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};
|
use crate::scope::{Entry as ScopeEntry, EntryType as ScopeEntryType, Scope};
|
||||||
use crate::token::Position;
|
|
||||||
use crate::utils::StaticVec;
|
use crate::utils::StaticVec;
|
||||||
|
|
||||||
use crate::stdlib::{
|
use crate::stdlib::{
|
||||||
@ -113,8 +111,7 @@ fn call_fn_with_constant_arguments(
|
|||||||
state: &State,
|
state: &State,
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
arg_values: &mut [Dynamic],
|
arg_values: &mut [Dynamic],
|
||||||
pos: Position,
|
) -> Option<Dynamic> {
|
||||||
) -> Result<Option<Dynamic>, Box<EvalAltResult>> {
|
|
||||||
// Search built-in's and external functions
|
// Search built-in's and external functions
|
||||||
let hash_fn = calc_fn_hash(
|
let hash_fn = calc_fn_hash(
|
||||||
empty(),
|
empty(),
|
||||||
@ -134,11 +131,10 @@ fn call_fn_with_constant_arguments(
|
|||||||
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(),
|
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(),
|
||||||
false,
|
false,
|
||||||
None,
|
None,
|
||||||
pos,
|
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
.map(|(v, _)| Some(v))
|
.map(|(v, _)| Some(v))
|
||||||
.or_else(|_| Ok(None))
|
.unwrap_or_else(|_| None)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Optimize a statement.
|
/// Optimize a statement.
|
||||||
@ -574,9 +570,8 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
|
|||||||
""
|
""
|
||||||
};
|
};
|
||||||
|
|
||||||
call_fn_with_constant_arguments(&state, name, arg_values.as_mut(), *pos).ok()
|
call_fn_with_constant_arguments(&state, name, arg_values.as_mut())
|
||||||
.and_then(|result|
|
.or_else(|| {
|
||||||
result.or_else(|| {
|
|
||||||
if !arg_for_type_of.is_empty() {
|
if !arg_for_type_of.is_empty() {
|
||||||
// Handle `type_of()`
|
// Handle `type_of()`
|
||||||
Some(arg_for_type_of.to_string().into())
|
Some(arg_for_type_of.to_string().into())
|
||||||
@ -584,12 +579,13 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
|
|||||||
// Otherwise use the default value, if any
|
// Otherwise use the default value, if any
|
||||||
def_value.clone()
|
def_value.clone()
|
||||||
}
|
}
|
||||||
}).and_then(|result| map_dynamic_to_expr(result, *pos))
|
})
|
||||||
|
.and_then(|result| map_dynamic_to_expr(result, *pos))
|
||||||
.map(|expr| {
|
.map(|expr| {
|
||||||
state.set_dirty();
|
state.set_dirty();
|
||||||
expr
|
expr
|
||||||
})
|
})
|
||||||
).unwrap_or_else(|| {
|
.unwrap_or_else(|| {
|
||||||
// Optimize function call arguments
|
// Optimize function call arguments
|
||||||
x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect();
|
x.3 = x.3.into_iter().map(|a| optimize_expr(a, state)).collect();
|
||||||
Expr::FnCall(x)
|
Expr::FnCall(x)
|
||||||
|
@ -2478,44 +2478,15 @@ fn parse_fn<'a>(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_global_expr<'a>(
|
|
||||||
input: &mut Peekable<TokenIterator<'a>>,
|
|
||||||
engine: &Engine,
|
|
||||||
scope: &Scope,
|
|
||||||
optimization_level: OptimizationLevel,
|
|
||||||
max_expr_depth: usize,
|
|
||||||
) -> Result<AST, ParseError> {
|
|
||||||
let mut state = ParseState::new(max_expr_depth);
|
|
||||||
let expr = parse_expr(input, &mut state, 0, false, false)?;
|
|
||||||
|
|
||||||
match input.peek().unwrap() {
|
|
||||||
(Token::EOF, _) => (),
|
|
||||||
// Return error if the expression doesn't end
|
|
||||||
(token, pos) => {
|
|
||||||
return Err(PERR::BadInput(format!("Unexpected '{}'", token.syntax())).into_err(*pos))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(
|
|
||||||
// Optimize AST
|
|
||||||
optimize_into_ast(
|
|
||||||
engine,
|
|
||||||
scope,
|
|
||||||
vec![Stmt::Expr(Box::new(expr))],
|
|
||||||
vec![],
|
|
||||||
optimization_level,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the global level statements.
|
/// Parse the global level statements.
|
||||||
fn parse_global_level<'a>(
|
fn parse_global_level<'a>(
|
||||||
input: &mut Peekable<TokenIterator<'a>>,
|
input: &mut Peekable<TokenIterator<'a>>,
|
||||||
max_expr_depth: (usize, usize),
|
max_expr_depth: usize,
|
||||||
|
max_function_expr_depth: usize,
|
||||||
) -> Result<(Vec<Stmt>, Vec<FnDef>), ParseError> {
|
) -> Result<(Vec<Stmt>, Vec<FnDef>), ParseError> {
|
||||||
let mut statements = Vec::<Stmt>::new();
|
let mut statements = Vec::<Stmt>::new();
|
||||||
let mut functions = HashMap::<u64, FnDef, _>::with_hasher(StraightHasherBuilder);
|
let mut functions = HashMap::<u64, FnDef, _>::with_hasher(StraightHasherBuilder);
|
||||||
let mut state = ParseState::new(max_expr_depth.0);
|
let mut state = ParseState::new(max_expr_depth);
|
||||||
|
|
||||||
while !input.peek().unwrap().0.is_eof() {
|
while !input.peek().unwrap().0.is_eof() {
|
||||||
// Collect all the function definitions
|
// Collect all the function definitions
|
||||||
@ -2530,7 +2501,7 @@ fn parse_global_level<'a>(
|
|||||||
match input.peek().unwrap() {
|
match input.peek().unwrap() {
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
(Token::Fn, _) => {
|
(Token::Fn, _) => {
|
||||||
let mut state = ParseState::new(max_expr_depth.1);
|
let mut state = ParseState::new(max_function_expr_depth);
|
||||||
let func = parse_fn(input, &mut state, access, 0, true, true)?;
|
let func = parse_fn(input, &mut state, access, 0, true, true)?;
|
||||||
|
|
||||||
// Qualifiers (none) + function name + number of arguments.
|
// Qualifiers (none) + function name + number of arguments.
|
||||||
@ -2586,20 +2557,49 @@ fn parse_global_level<'a>(
|
|||||||
Ok((statements, functions.into_iter().map(|(_, v)| v).collect()))
|
Ok((statements, functions.into_iter().map(|(_, v)| v).collect()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run the parser on an input stream, returning an AST.
|
impl Engine {
|
||||||
pub fn parse<'a>(
|
pub(crate) fn parse_global_expr<'a>(
|
||||||
|
&self,
|
||||||
input: &mut Peekable<TokenIterator<'a>>,
|
input: &mut Peekable<TokenIterator<'a>>,
|
||||||
engine: &Engine,
|
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
optimization_level: OptimizationLevel,
|
optimization_level: OptimizationLevel,
|
||||||
max_expr_depth: (usize, usize),
|
) -> Result<AST, ParseError> {
|
||||||
) -> Result<AST, ParseError> {
|
let mut state = ParseState::new(self.max_expr_depth);
|
||||||
let (statements, lib) = parse_global_level(input, max_expr_depth)?;
|
let expr = parse_expr(input, &mut state, 0, false, false)?;
|
||||||
|
|
||||||
|
match input.peek().unwrap() {
|
||||||
|
(Token::EOF, _) => (),
|
||||||
|
// Return error if the expression doesn't end
|
||||||
|
(token, pos) => {
|
||||||
|
return Err(
|
||||||
|
PERR::BadInput(format!("Unexpected '{}'", token.syntax())).into_err(*pos)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let expr = vec![Stmt::Expr(Box::new(expr))];
|
||||||
|
|
||||||
Ok(
|
Ok(
|
||||||
// Optimize AST
|
// Optimize AST
|
||||||
optimize_into_ast(engine, scope, statements, lib, optimization_level),
|
optimize_into_ast(self, scope, expr, Default::default(), optimization_level),
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the parser on an input stream, returning an AST.
|
||||||
|
pub(crate) fn parse<'a>(
|
||||||
|
&self,
|
||||||
|
input: &mut Peekable<TokenIterator<'a>>,
|
||||||
|
scope: &Scope,
|
||||||
|
optimization_level: OptimizationLevel,
|
||||||
|
) -> Result<AST, ParseError> {
|
||||||
|
let (statements, lib) =
|
||||||
|
parse_global_level(input, self.max_expr_depth, self.max_function_expr_depth)?;
|
||||||
|
|
||||||
|
Ok(
|
||||||
|
// Optimize AST
|
||||||
|
optimize_into_ast(self, scope, statements, lib, optimization_level),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map a `Dynamic` value to an expression.
|
/// Map a `Dynamic` value to an expression.
|
||||||
|
@ -331,10 +331,12 @@ impl EvalAltResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Consume the current `EvalAltResult` and return a new one
|
/// Consume the current `EvalAltResult` and return a new one with the specified `Position`
|
||||||
/// with the specified `Position`.
|
/// if the current position is `Position::None`.
|
||||||
pub(crate) fn new_position(mut self: Box<Self>, new_position: Position) -> Box<Self> {
|
pub(crate) fn new_position(mut self: Box<Self>, new_position: Position) -> Box<Self> {
|
||||||
|
if self.position().is_none() {
|
||||||
self.set_position(new_position);
|
self.set_position(new_position);
|
||||||
|
}
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -175,7 +175,7 @@ impl<'a> Scope<'a> {
|
|||||||
///
|
///
|
||||||
/// Modules are used for accessing member variables, functions and plugins under a namespace.
|
/// Modules are used for accessing member variables, functions and plugins under a namespace.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
pub fn push_module<K: Into<Cow<'a, str>>>(&mut self, name: K, mut value: Module) {
|
pub fn push_module<K: Into<Cow<'a, str>>>(&mut self, name: K, value: Module) {
|
||||||
self.push_module_internal(name, value);
|
self.push_module_internal(name, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -198,6 +198,7 @@ pub enum Token {
|
|||||||
XOrAssign,
|
XOrAssign,
|
||||||
ModuloAssign,
|
ModuloAssign,
|
||||||
PowerOfAssign,
|
PowerOfAssign,
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
Private,
|
Private,
|
||||||
Import,
|
Import,
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -284,6 +285,7 @@ impl Token {
|
|||||||
ModuloAssign => "%=",
|
ModuloAssign => "%=",
|
||||||
PowerOf => "~",
|
PowerOf => "~",
|
||||||
PowerOfAssign => "~=",
|
PowerOfAssign => "~=",
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
Private => "private",
|
Private => "private",
|
||||||
Import => "import",
|
Import => "import",
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
@ -757,6 +759,7 @@ impl<'a> TokenIterator<'a> {
|
|||||||
"throw" => Token::Throw,
|
"throw" => Token::Throw,
|
||||||
"for" => Token::For,
|
"for" => Token::For,
|
||||||
"in" => Token::In,
|
"in" => Token::In,
|
||||||
|
#[cfg(not(feature = "no_function"))]
|
||||||
"private" => Token::Private,
|
"private" => Token::Private,
|
||||||
"import" => Token::Import,
|
"import" => Token::Import,
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
|
@ -6,7 +6,7 @@ fn test_max_operations() -> Result<(), Box<EvalAltResult>> {
|
|||||||
let mut engine = Engine::new();
|
let mut engine = Engine::new();
|
||||||
engine.set_max_operations(500);
|
engine.set_max_operations(500);
|
||||||
|
|
||||||
engine.on_progress(|count| {
|
engine.on_progress(|&count| {
|
||||||
if count % 100 == 0 {
|
if count % 100 == 0 {
|
||||||
println!("{}", count);
|
println!("{}", count);
|
||||||
}
|
}
|
||||||
@ -34,7 +34,7 @@ fn test_max_operations_functions() -> Result<(), Box<EvalAltResult>> {
|
|||||||
let mut engine = Engine::new();
|
let mut engine = Engine::new();
|
||||||
engine.set_max_operations(500);
|
engine.set_max_operations(500);
|
||||||
|
|
||||||
engine.on_progress(|count| {
|
engine.on_progress(|&count| {
|
||||||
if count % 100 == 0 {
|
if count % 100 == 0 {
|
||||||
println!("{}", count);
|
println!("{}", count);
|
||||||
}
|
}
|
||||||
@ -90,7 +90,7 @@ fn test_max_operations_eval() -> Result<(), Box<EvalAltResult>> {
|
|||||||
let mut engine = Engine::new();
|
let mut engine = Engine::new();
|
||||||
engine.set_max_operations(500);
|
engine.set_max_operations(500);
|
||||||
|
|
||||||
engine.on_progress(|count| {
|
engine.on_progress(|&count| {
|
||||||
if count % 100 == 0 {
|
if count % 100 == 0 {
|
||||||
println!("{}", count);
|
println!("{}", count);
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user