Merge branch 'master' into plugins
This commit is contained in:
commit
d7d9f42802
@ -16,6 +16,11 @@ New features
|
|||||||
* `x.call(f, ...)` allows binding `x` to `this` for the function referenced by the function pointer `f`.
|
* `x.call(f, ...)` allows binding `x` to `this` for the function referenced by the function pointer `f`.
|
||||||
* Anonymous functions in the syntax of a closure, e.g. `|x, y, z| x + y - z`.
|
* Anonymous functions in the syntax of a closure, e.g. `|x, y, z| x + y - z`.
|
||||||
|
|
||||||
|
Breaking changes
|
||||||
|
----------------
|
||||||
|
|
||||||
|
* Function signature for defining custom syntax is simplified.
|
||||||
|
|
||||||
|
|
||||||
Version 0.17.0
|
Version 0.17.0
|
||||||
==============
|
==============
|
||||||
|
@ -25,12 +25,12 @@ It doesn't attempt to be a new language. For example:
|
|||||||
* No closures - do your closure magic in Rust instead; [turn a Rhai scripted function into a Rust closure]({{rootUrl}}/engine/call-fn.md).
|
* No closures - do your closure magic in Rust instead; [turn a Rhai scripted function into a Rust closure]({{rootUrl}}/engine/call-fn.md).
|
||||||
|
|
||||||
* No byte-codes/JIT - Rhai has an AST-walking interpreter which will not win any speed races. The purpose of Rhai is not
|
* No byte-codes/JIT - Rhai has an AST-walking interpreter which will not win any speed races. The purpose of Rhai is not
|
||||||
to be extremely _fast_, but to make it as easy as possible to integrate with native Rust programs.
|
to be extremely _fast_, but to make it as easy as possible to integrate with native Rust applications.
|
||||||
|
|
||||||
Due to this intended usage, Rhai deliberately keeps the language simple and small by omitting advanced language features
|
Due to this intended usage, Rhai deliberately keeps the language simple and small by omitting advanced language features
|
||||||
such as classes, inheritance, first-class functions, closures, concurrency, byte-codes, JIT etc.
|
such as classes, inheritance, first-class functions, closures, concurrency, byte-codes, JIT etc.
|
||||||
|
|
||||||
Avoid the temptation to write full-fledge program logic entirely in Rhai - that use case is best fulfilled by
|
Avoid the temptation to write full-fledge application logic entirely in Rhai - that use case is best fulfilled by
|
||||||
more complete languages such as JavaScript or Lua.
|
more complete languages such as JavaScript or Lua.
|
||||||
|
|
||||||
Therefore, in actual practice, it is usually best to expose a Rust API into Rhai for scripts to call.
|
Therefore, in actual practice, it is usually best to expose a Rust API into Rhai for scripts to call.
|
||||||
|
@ -126,32 +126,21 @@ Any custom syntax must include an _implementation_ of it.
|
|||||||
The function signature of an implementation is:
|
The function signature of an implementation is:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
Fn(
|
Fn(engine: &Engine, context: &mut EvalContext, scope: &mut Scope, inputs: &[Expression])
|
||||||
engine: &Engine,
|
-> Result<Dynamic, Box<EvalAltResult>>
|
||||||
scope: &mut Scope,
|
|
||||||
mods: &mut Imports,
|
|
||||||
state: &mut State,
|
|
||||||
lib: &Module,
|
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
inputs: &[Expression],
|
|
||||||
level: usize
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
where:
|
where:
|
||||||
|
|
||||||
* `engine: &Engine` - reference to the current [`Engine`].
|
* `engine: &Engine` - reference to the current [`Engine`].
|
||||||
|
* `context: &mut EvalContext` - mutable reference to the current evaluation _context_; **do not touch**.
|
||||||
* `scope: &mut Scope` - mutable reference to the current [`Scope`]; variables can be added to it.
|
* `scope: &mut Scope` - mutable reference to the current [`Scope`]; variables can be added to it.
|
||||||
* `mods : &mut Imports` - mutable reference to the current collection of imported [`Module`]'s; **do not touch**.
|
|
||||||
* `state : &mut State` - mutable reference to the current evaluation state; **do not touch**.
|
|
||||||
* `lib : &Module` - reference to the current collection of script-defined functions.
|
|
||||||
* `this_ptr : &mut Option<&mut Dynamic>` - mutable reference to the current binding of the `this` pointer; **do not touch**.
|
|
||||||
* `inputs: &[Expression]` - a list of input expression trees.
|
* `inputs: &[Expression]` - a list of input expression trees.
|
||||||
* `level : usize` - the current function call level.
|
|
||||||
|
|
||||||
There are a lot of parameters, most of which should not be touched or Bad Things Happen™.
|
#### WARNING - Lark's Vomit
|
||||||
They represent the running _content_ of a script evaluation and should simply be passed
|
|
||||||
straight-through the the [`Engine`].
|
The `context` parameter contains the evaluation _context_ and should not be touched or Bad Things Happen™.
|
||||||
|
It should simply be passed straight-through the the [`Engine`].
|
||||||
|
|
||||||
### Access Arguments
|
### Access Arguments
|
||||||
|
|
||||||
@ -172,7 +161,7 @@ Use the `engine::eval_expression_tree` method to evaluate an expression tree.
|
|||||||
|
|
||||||
```rust
|
```rust
|
||||||
let expr = inputs.get(0).unwrap();
|
let expr = inputs.get(0).unwrap();
|
||||||
let result = engine.eval_expression_tree(scope, mods, state, lib, this_ptr, expr, level)?;
|
let result = engine.eval_expression_tree(context, scope, expr)?;
|
||||||
```
|
```
|
||||||
|
|
||||||
As can be seem above, most arguments are simply passed straight-through to `engine::eval_expression_tree`.
|
As can be seem above, most arguments are simply passed straight-through to `engine::eval_expression_tree`.
|
||||||
@ -210,13 +199,9 @@ The syntax is passed simply as a slice of `&str`.
|
|||||||
// Custom syntax implementation
|
// Custom syntax implementation
|
||||||
fn implementation_func(
|
fn implementation_func(
|
||||||
engine: &Engine,
|
engine: &Engine,
|
||||||
|
context: &mut EvalContext,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
mods: &mut Imports,
|
inputs: &[Expression]
|
||||||
state: &mut State,
|
|
||||||
lib: &Module,
|
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
inputs: &[Expression],
|
|
||||||
level: usize
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
||||||
let stmt = inputs.get(1).unwrap();
|
let stmt = inputs.get(1).unwrap();
|
||||||
@ -227,15 +212,12 @@ fn implementation_func(
|
|||||||
|
|
||||||
loop {
|
loop {
|
||||||
// Evaluate the statement block
|
// Evaluate the statement block
|
||||||
engine.eval_expression_tree(scope, mods, state, lib, this_ptr, stmt, level)?;
|
engine.eval_expression_tree(context, scope, stmt)?;
|
||||||
|
|
||||||
// Evaluate the condition expression
|
// Evaluate the condition expression
|
||||||
let stop = !engine
|
let stop = !engine.eval_expression_tree(context, scope, condition)?
|
||||||
.eval_expression_tree(scope, mods, state, lib, this_ptr, condition, level)?
|
.as_bool().map_err(|_| EvalAltResult::ErrorBooleanArgMismatch(
|
||||||
.as_bool()
|
"do-while".into(), expr.position()))?;
|
||||||
.map_err(|_| EvalAltResult::ErrorBooleanArgMismatch(
|
|
||||||
"do-while".into(), expr.position()
|
|
||||||
))?;
|
|
||||||
|
|
||||||
if stop {
|
if stop {
|
||||||
break;
|
break;
|
||||||
|
@ -7,7 +7,7 @@ Raw `Engine`
|
|||||||
`Engine::new` creates a scripting [`Engine`] with common functionalities (e.g. printing to the console via `print`).
|
`Engine::new` creates a scripting [`Engine`] with common functionalities (e.g. printing to the console via `print`).
|
||||||
|
|
||||||
In many controlled embedded environments, however, these may not be needed and unnecessarily occupy
|
In many controlled embedded environments, however, these may not be needed and unnecessarily occupy
|
||||||
program code storage space.
|
application code storage space.
|
||||||
|
|
||||||
Use `Engine::new_raw` to create a _raw_ `Engine`, in which only a minimal set of
|
Use `Engine::new_raw` to create a _raw_ `Engine`, in which only a minimal set of
|
||||||
basic arithmetic and logical operators are supported.
|
basic arithmetic and logical operators are supported.
|
||||||
|
@ -13,3 +13,9 @@ Nightly Required
|
|||||||
----------------
|
----------------
|
||||||
|
|
||||||
Currently, [`no_std`] requires the nightly compiler due to the crates that it uses.
|
Currently, [`no_std`] requires the nightly compiler due to the crates that it uses.
|
||||||
|
|
||||||
|
|
||||||
|
Samples
|
||||||
|
-------
|
||||||
|
|
||||||
|
Check out the [`no-std` sample applications](../examples/rust.md#no-std-samples) for different operating environments.
|
||||||
|
@ -3,7 +3,7 @@ Rust Examples
|
|||||||
|
|
||||||
{{#include ../../links.md}}
|
{{#include ../../links.md}}
|
||||||
|
|
||||||
A number of examples can be found in the `examples` folder:
|
A number of examples can be found in the `examples` directory:
|
||||||
|
|
||||||
| Example | Description |
|
| Example | Description |
|
||||||
| ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
@ -29,3 +29,22 @@ Examples can be run with the following command:
|
|||||||
```bash
|
```bash
|
||||||
cargo run --example {example_name}
|
cargo run --example {example_name}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`no-std` Samples
|
||||||
|
----------------
|
||||||
|
|
||||||
|
To illustrate `no-std` builds, a number of sample applications are available under the `no_std` directory:
|
||||||
|
|
||||||
|
| Sample | Description | Optimization | Allocator | Panics |
|
||||||
|
| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | :----------: | :-----------------------------------------------: | :----: |
|
||||||
|
| [`no_std_test`](https://github.com/jonathandturner/rhai/tree/master/no_std/no_std_test) | Bare-bones test application that evaluates a Rhai expression and sets the result as the return value. | Size | [`wee_alloc`](https://crates.io/crates/wee_alloc) | Abort |
|
||||||
|
|
||||||
|
`cargo run` cannot be used to run a `no-std` sample. It must first be built:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd no_std/no_std_test
|
||||||
|
|
||||||
|
cargo +nightly build --release
|
||||||
|
|
||||||
|
./target/release/no_std_test
|
||||||
|
```
|
||||||
|
@ -6,27 +6,27 @@ Example Scripts
|
|||||||
Language Feature Scripts
|
Language Feature Scripts
|
||||||
-----------------------
|
-----------------------
|
||||||
|
|
||||||
There are also a number of examples scripts that showcase Rhai's features, all in the `scripts` folder:
|
There are also a number of examples scripts that showcase Rhai's features, all in the `scripts` directory:
|
||||||
|
|
||||||
| Script | Description |
|
| Script | Description |
|
||||||
| -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||||
| [`array.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/array.rhai) | [Arrays] |
|
| [`array.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/array.rhai) | [Arrays] |
|
||||||
| [`assignment.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/assignment.rhai) | Variable declarations |
|
| [`assignment.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/assignment.rhai) | Variable declarations |
|
||||||
| [`comments.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/comments.rhai) | Just comments |
|
| [`comments.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/comments.rhai) | Just comments |
|
||||||
| [`for1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/for1.rhai) | [`for`](#for-loop) loops |
|
| [`for1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/for1.rhai) | [`for`]({{rootUrl}}/language/for.md) loops |
|
||||||
| [`for2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/for2.rhai) | [`for`](#for-loop) loops on [arrays] |
|
| [`for2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/for2.rhai) | [`for`]({{rootUrl}}/language/for.md) loops on [arrays] |
|
||||||
| [`function_decl1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl1.rhai) | A [function] without parameters |
|
| [`function_decl1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl1.rhai) | A [function] without parameters |
|
||||||
| [`function_decl2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl2.rhai) | A [function] with two parameters |
|
| [`function_decl2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl2.rhai) | A [function] with two parameters |
|
||||||
| [`function_decl3.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl3.rhai) | A [function] with many parameters |
|
| [`function_decl3.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/function_decl3.rhai) | A [function] with many parameters |
|
||||||
| [`if1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/if1.rhai) | [`if`](#if-statement) example |
|
| [`if1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/if1.rhai) | [`if`]({{rootUrl}}/language/if.md) example |
|
||||||
| [`loop.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/loop.rhai) | Count-down [`loop`](#infinite-loop) in Rhai, emulating a `do` .. `while` loop |
|
| [`loop.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/loop.rhai) | Count-down [`loop`]({{rootUrl}}/language/loop.md) in Rhai, emulating a `do` .. `while` loop |
|
||||||
| [`oop.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/oop.rhai) | Simulate [object-oriented programming (OOP)][OOP] |
|
| [`oop.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/oop.rhai) | Simulate [object-oriented programming (OOP)][OOP] |
|
||||||
| [`op1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op1.rhai) | Just simple addition |
|
| [`op1.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op1.rhai) | Just simple addition |
|
||||||
| [`op2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op2.rhai) | Simple addition and multiplication |
|
| [`op2.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op2.rhai) | Simple addition and multiplication |
|
||||||
| [`op3.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op3.rhai) | Change evaluation order with parenthesis |
|
| [`op3.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/op3.rhai) | Change evaluation order with parenthesis |
|
||||||
| [`string.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/string.rhai) | [String] operations |
|
| [`string.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/string.rhai) | [String] operations |
|
||||||
| [`strings_map.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/strings_map.rhai) | [String] and [object map] operations |
|
| [`strings_map.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/strings_map.rhai) | [String] and [object map] operations |
|
||||||
| [`while.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/while.rhai) | [`while`](#while-loop) loop |
|
| [`while.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/while.rhai) | [`while`]({{rootUrl}}/language/while.md) loop |
|
||||||
|
|
||||||
|
|
||||||
Benchmark Scripts
|
Benchmark Scripts
|
||||||
@ -35,8 +35,8 @@ Benchmark Scripts
|
|||||||
The following scripts are for benchmarking the speed of Rhai:
|
The following scripts are for benchmarking the speed of Rhai:
|
||||||
|
|
||||||
| Scripts | Description |
|
| Scripts | Description |
|
||||||
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
|
||||||
| [`speed_test.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/speed_test.rhai) | A simple program to measure the speed of Rhai's interpreter (1 million iterations). |
|
| [`speed_test.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/speed_test.rhai) | A simple application to measure the speed of Rhai's interpreter (1 million iterations). |
|
||||||
| [`primes.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/primes.rhai) | Use Sieve of Eratosthenes to find all primes smaller than a limit. |
|
| [`primes.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/primes.rhai) | Use Sieve of Eratosthenes to find all primes smaller than a limit. |
|
||||||
| [`fibonacci.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/fibonacci.rhai) | Calculate the n-th Fibonacci number using a really dumb algorithm. |
|
| [`fibonacci.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/fibonacci.rhai) | Calculate the n-th Fibonacci number using a really dumb algorithm. |
|
||||||
| [`mat_mul.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/mat_mul.rhai) | Matrix multiplication test to measure the speed of multi-dimensional array access. |
|
| [`mat_mul.rhai`](https://github.com/jonathandturner/rhai/tree/master/scripts/mat_mul.rhai) | Matrix multiplication test to measure the speed of multi-dimensional array access. |
|
||||||
@ -45,7 +45,7 @@ The following scripts are for benchmarking the speed of Rhai:
|
|||||||
Running Example Scripts
|
Running Example Scripts
|
||||||
----------------------
|
----------------------
|
||||||
|
|
||||||
To run the scripts, either make a tiny program or use of the `rhai_runner` example:
|
The [`rhai_runner`](../examples/rust.md) example can be used to run the scripts:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run --example rhai_runner scripts/any_script.rhai
|
cargo run --example rhai_runner scripts/any_script.rhai
|
||||||
|
24
no_std/no_std_test/Cargo.toml
Normal file
24
no_std/no_std_test/Cargo.toml
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
[package]
|
||||||
|
name = "no_std_test"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
authors = ["Stephen Chung"]
|
||||||
|
description = "no-std test application"
|
||||||
|
homepage = "https://github.com/jonathandturner/rhai/tree/master/no_std/no_std_test"
|
||||||
|
repository = "https://github.com/jonathandturner/rhai"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
rhai = { path = "../../", features = [ "no_std", "unchecked", "only_i32", "no_module" ], default_features = false }
|
||||||
|
wee_alloc = { version = "0.4.5", default_features = false }
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
panic = "abort"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
opt-level = "z" # optimize for size
|
||||||
|
debug = false
|
||||||
|
rpath = false
|
||||||
|
lto = "fat"
|
||||||
|
debug-assertions = false
|
||||||
|
codegen-units = 1
|
||||||
|
panic = "abort"
|
18
no_std/no_std_test/README.md
Normal file
18
no_std/no_std_test/README.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
`no-std` Test Sample
|
||||||
|
====================
|
||||||
|
|
||||||
|
This sample application is a bare-bones `no-std` build for testing.
|
||||||
|
|
||||||
|
[`wee_alloc`](https://crates.io/crates/wee_alloc) is used as the allocator.
|
||||||
|
|
||||||
|
|
||||||
|
To Compile
|
||||||
|
----------
|
||||||
|
|
||||||
|
The nightly compiler is required:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo +nightly build --release
|
||||||
|
```
|
||||||
|
|
||||||
|
The release build is optimized for size. It can be changed to optimize on speed instead.
|
43
no_std/no_std_test/src/main.rs
Normal file
43
no_std/no_std_test/src/main.rs
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
//! This is a bare-bones `no-std` application that evaluates
|
||||||
|
//! a simple expression and uses the result as the return value.
|
||||||
|
|
||||||
|
#![no_std]
|
||||||
|
#![feature(alloc_error_handler, start, core_intrinsics, lang_items)]
|
||||||
|
|
||||||
|
extern crate alloc;
|
||||||
|
extern crate wee_alloc;
|
||||||
|
|
||||||
|
#[global_allocator]
|
||||||
|
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||||
|
|
||||||
|
use rhai::{Engine, INT};
|
||||||
|
|
||||||
|
#[start]
|
||||||
|
fn main(_argc: isize, _argv: *const *const u8) -> isize {
|
||||||
|
// Notice that this is a _raw_ engine.
|
||||||
|
// To do anything useful, load a few packages from `rhai::packages`.
|
||||||
|
let engine = Engine::new_raw();
|
||||||
|
|
||||||
|
// Evaluate a simple expression: 40 + 2
|
||||||
|
engine.eval_expression::<INT>("40 + 2").unwrap() as isize
|
||||||
|
}
|
||||||
|
|
||||||
|
#[alloc_error_handler]
|
||||||
|
fn foo(_: core::alloc::Layout) -> ! {
|
||||||
|
core::intrinsics::abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[panic_handler]
|
||||||
|
#[lang = "panic_impl"]
|
||||||
|
extern "C" fn rust_begin_panic(_: &core::panic::PanicInfo) -> ! {
|
||||||
|
core::intrinsics::abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[lang = "eh_personality"]
|
||||||
|
extern "C" fn eh_personality() {}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
extern "C" fn rust_eh_register_frames() {}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
extern "C" fn rust_eh_unregister_frames() {}
|
320
src/any.rs
320
src/any.rs
@ -203,6 +203,7 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Map the name of a standard type into a friendly form.
|
/// Map the name of a standard type into a friendly form.
|
||||||
|
#[inline]
|
||||||
pub(crate) fn map_std_type_name(name: &str) -> &str {
|
pub(crate) fn map_std_type_name(name: &str) -> &str {
|
||||||
if name == type_name::<String>() {
|
if name == type_name::<String>() {
|
||||||
"string"
|
"string"
|
||||||
@ -340,30 +341,47 @@ impl Dynamic {
|
|||||||
/// assert_eq!(new_result.type_name(), "string");
|
/// assert_eq!(new_result.type_name(), "string");
|
||||||
/// assert_eq!(new_result.to_string(), "hello");
|
/// assert_eq!(new_result.to_string(), "hello");
|
||||||
/// ```
|
/// ```
|
||||||
|
#[inline(always)]
|
||||||
pub fn from<T: Variant + Clone>(value: T) -> Self {
|
pub fn from<T: Variant + Clone>(value: T) -> Self {
|
||||||
if let Some(result) = <dyn Any>::downcast_ref::<()>(&value) {
|
let type_id = TypeId::of::<T>();
|
||||||
return result.clone().into();
|
|
||||||
} else if let Some(result) = <dyn Any>::downcast_ref::<bool>(&value) {
|
|
||||||
return result.clone().into();
|
|
||||||
} else if let Some(result) = <dyn Any>::downcast_ref::<INT>(&value) {
|
|
||||||
return result.clone().into();
|
|
||||||
} else if let Some(result) = <dyn Any>::downcast_ref::<char>(&value) {
|
|
||||||
return result.clone().into();
|
|
||||||
} else if let Some(result) = <dyn Any>::downcast_ref::<ImmutableString>(&value) {
|
|
||||||
return result.clone().into();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if type_id == TypeId::of::<INT>() {
|
||||||
|
return <dyn Any>::downcast_ref::<INT>(&value)
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into();
|
||||||
|
}
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
if let Some(result) = <dyn Any>::downcast_ref::<FLOAT>(&value) {
|
if type_id == TypeId::of::<FLOAT>() {
|
||||||
return result.clone().into();
|
return <dyn Any>::downcast_ref::<FLOAT>(&value)
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<bool>() {
|
||||||
|
return <dyn Any>::downcast_ref::<bool>(&value)
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<char>() {
|
||||||
|
return <dyn Any>::downcast_ref::<char>(&value)
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<ImmutableString>() {
|
||||||
|
return <dyn Any>::downcast_ref::<ImmutableString>(&value)
|
||||||
|
.unwrap()
|
||||||
|
.clone()
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<()>() {
|
||||||
|
return ().into();
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut boxed = Box::new(value);
|
let mut boxed = Box::new(value);
|
||||||
|
|
||||||
boxed = match unsafe_cast_box::<_, Dynamic>(boxed) {
|
|
||||||
Ok(d) => return *d,
|
|
||||||
Err(val) => val,
|
|
||||||
};
|
|
||||||
boxed = match unsafe_cast_box::<_, String>(boxed) {
|
boxed = match unsafe_cast_box::<_, String>(boxed) {
|
||||||
Ok(s) => return (*s).into(),
|
Ok(s) => return (*s).into(),
|
||||||
Err(val) => val,
|
Err(val) => val,
|
||||||
@ -384,6 +402,11 @@ impl Dynamic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
boxed = match unsafe_cast_box::<_, Dynamic>(boxed) {
|
||||||
|
Ok(d) => return *d,
|
||||||
|
Err(val) => val,
|
||||||
|
};
|
||||||
|
|
||||||
Self(Union::Variant(Box::new(boxed)))
|
Self(Union::Variant(Box::new(boxed)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -401,30 +424,80 @@ impl Dynamic {
|
|||||||
///
|
///
|
||||||
/// assert_eq!(x.try_cast::<u32>().unwrap(), 42);
|
/// assert_eq!(x.try_cast::<u32>().unwrap(), 42);
|
||||||
/// ```
|
/// ```
|
||||||
|
#[inline(always)]
|
||||||
pub fn try_cast<T: Variant>(self) -> Option<T> {
|
pub fn try_cast<T: Variant>(self) -> Option<T> {
|
||||||
let type_id = TypeId::of::<T>();
|
let type_id = TypeId::of::<T>();
|
||||||
|
|
||||||
|
if type_id == TypeId::of::<INT>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Int(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_float"))]
|
||||||
|
if type_id == TypeId::of::<FLOAT>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Float(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<bool>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Bool(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<ImmutableString>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Str(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<String>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Str(value) => unsafe_try_cast(value.into_owned()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<char>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Char(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
if type_id == TypeId::of::<Array>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Array(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
if type_id == TypeId::of::<Map>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Map(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<FnPtr>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::FnPtr(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<()>() {
|
||||||
|
return match self.0 {
|
||||||
|
Union::Unit(value) => unsafe_try_cast(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
if type_id == TypeId::of::<Dynamic>() {
|
if type_id == TypeId::of::<Dynamic>() {
|
||||||
return unsafe_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 {
|
match self.0 {
|
||||||
Union::Unit(value) => unsafe_try_cast(value),
|
|
||||||
Union::Bool(value) => unsafe_try_cast(value),
|
|
||||||
Union::Str(value) if type_id == TypeId::of::<ImmutableString>() => {
|
|
||||||
unsafe_try_cast(value)
|
|
||||||
}
|
|
||||||
Union::Str(value) => unsafe_try_cast(value.into_owned()),
|
|
||||||
Union::Char(value) => unsafe_try_cast(value),
|
|
||||||
Union::Int(value) => unsafe_try_cast(value),
|
|
||||||
#[cfg(not(feature = "no_float"))]
|
|
||||||
Union::Float(value) => unsafe_try_cast(value),
|
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Union::Array(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
Union::Map(value) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
|
|
||||||
Union::FnPtr(value) => unsafe_try_cast(value),
|
|
||||||
Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).ok(),
|
Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).ok(),
|
||||||
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -444,81 +517,162 @@ impl Dynamic {
|
|||||||
///
|
///
|
||||||
/// assert_eq!(x.cast::<u32>(), 42);
|
/// assert_eq!(x.cast::<u32>(), 42);
|
||||||
/// ```
|
/// ```
|
||||||
|
#[inline(always)]
|
||||||
pub fn cast<T: Variant + Clone>(self) -> T {
|
pub fn cast<T: Variant + Clone>(self) -> T {
|
||||||
let type_id = TypeId::of::<T>();
|
self.try_cast::<T>().unwrap()
|
||||||
|
|
||||||
if type_id == TypeId::of::<Dynamic>() {
|
|
||||||
return *unsafe_cast_box::<_, T>(Box::new(self)).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
match self.0 {
|
|
||||||
Union::Unit(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
Union::Bool(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
Union::Str(value) if type_id == TypeId::of::<ImmutableString>() => {
|
|
||||||
unsafe_try_cast(value).unwrap()
|
|
||||||
}
|
|
||||||
Union::Str(value) => unsafe_try_cast(value.into_owned()).unwrap(),
|
|
||||||
Union::Char(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
Union::Int(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
#[cfg(not(feature = "no_float"))]
|
|
||||||
Union::Float(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Union::Array(value) => *unsafe_cast_box::<_, T>(value).unwrap(),
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
Union::Map(value) => *unsafe_cast_box::<_, T>(value).unwrap(),
|
|
||||||
Union::FnPtr(value) => unsafe_try_cast(value).unwrap(),
|
|
||||||
Union::Variant(value) => (*value).as_box_any().downcast().map(|x| *x).unwrap(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a reference of a specific type to the `Dynamic`.
|
/// Get a reference of a specific type to the `Dynamic`.
|
||||||
/// Casting to `Dynamic` just returns a reference to it.
|
/// Casting to `Dynamic` just returns a reference to it.
|
||||||
/// Returns `None` if the cast fails.
|
/// Returns `None` if the cast fails.
|
||||||
|
#[inline(always)]
|
||||||
pub fn downcast_ref<T: Variant + Clone>(&self) -> Option<&T> {
|
pub fn downcast_ref<T: Variant + Clone>(&self) -> Option<&T> {
|
||||||
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
|
let type_id = TypeId::of::<T>();
|
||||||
|
|
||||||
|
if type_id == TypeId::of::<INT>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Int(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_float"))]
|
||||||
|
if type_id == TypeId::of::<FLOAT>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Float(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<bool>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Bool(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<ImmutableString>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<String>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<char>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Char(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
if type_id == TypeId::of::<Array>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Array(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
if type_id == TypeId::of::<Map>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Map(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<FnPtr>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::FnPtr(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<()>() {
|
||||||
|
return match &self.0 {
|
||||||
|
Union::Unit(value) => <dyn Any>::downcast_ref::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<Dynamic>() {
|
||||||
return <dyn Any>::downcast_ref::<T>(self);
|
return <dyn Any>::downcast_ref::<T>(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
Union::Unit(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
Union::Bool(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
Union::Str(value) => <dyn Any>::downcast_ref::<T>(value)
|
|
||||||
.or_else(|| <dyn Any>::downcast_ref::<T>(value.as_ref())),
|
|
||||||
Union::Char(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
Union::Int(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
#[cfg(not(feature = "no_float"))]
|
|
||||||
Union::Float(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Union::Array(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
Union::Map(value) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
|
|
||||||
Union::FnPtr(value) => <dyn Any>::downcast_ref::<T>(value),
|
|
||||||
Union::Variant(value) => value.as_ref().as_ref().as_any().downcast_ref::<T>(),
|
Union::Variant(value) => value.as_ref().as_ref().as_any().downcast_ref::<T>(),
|
||||||
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a mutable reference of a specific type to the `Dynamic`.
|
/// Get a mutable reference of a specific type to the `Dynamic`.
|
||||||
/// Casting to `Dynamic` just returns a mutable reference to it.
|
/// Casting to `Dynamic` just returns a mutable reference to it.
|
||||||
/// Returns `None` if the cast fails.
|
/// Returns `None` if the cast fails.
|
||||||
|
#[inline(always)]
|
||||||
pub fn downcast_mut<T: Variant + Clone>(&mut self) -> Option<&mut T> {
|
pub fn downcast_mut<T: Variant + Clone>(&mut self) -> Option<&mut T> {
|
||||||
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
|
let type_id = TypeId::of::<T>();
|
||||||
|
|
||||||
|
if type_id == TypeId::of::<INT>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Int(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_float"))]
|
||||||
|
if type_id == TypeId::of::<FLOAT>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Float(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<bool>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Bool(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<ImmutableString>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Str(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<char>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Char(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_index"))]
|
||||||
|
if type_id == TypeId::of::<Array>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Array(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "no_object"))]
|
||||||
|
if type_id == TypeId::of::<Map>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Map(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<FnPtr>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::FnPtr(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<()>() {
|
||||||
|
return match &mut self.0 {
|
||||||
|
Union::Unit(value) => <dyn Any>::downcast_mut::<T>(value),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if type_id == TypeId::of::<Dynamic>() {
|
||||||
return <dyn Any>::downcast_mut::<T>(self);
|
return <dyn Any>::downcast_mut::<T>(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
match &mut self.0 {
|
match &mut self.0 {
|
||||||
Union::Unit(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
Union::Bool(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
Union::Str(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
Union::Char(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
Union::Int(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
#[cfg(not(feature = "no_float"))]
|
|
||||||
Union::Float(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
#[cfg(not(feature = "no_index"))]
|
|
||||||
Union::Array(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
|
|
||||||
#[cfg(not(feature = "no_object"))]
|
|
||||||
Union::Map(value) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
|
|
||||||
Union::FnPtr(value) => <dyn Any>::downcast_mut::<T>(value),
|
|
||||||
Union::Variant(value) => value.as_mut().as_mut_any().downcast_mut::<T>(),
|
Union::Variant(value) => value.as_mut().as_mut_any().downcast_mut::<T>(),
|
||||||
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ use crate::utils::StaticVec;
|
|||||||
use crate::parser::FLOAT;
|
use crate::parser::FLOAT;
|
||||||
|
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
use crate::syntax::CustomSyntax;
|
use crate::syntax::{CustomSyntax, EvalContext};
|
||||||
|
|
||||||
use crate::stdlib::{
|
use crate::stdlib::{
|
||||||
any::{type_name, TypeId},
|
any::{type_name, TypeId},
|
||||||
@ -1738,15 +1738,19 @@ impl Engine {
|
|||||||
#[deprecated(note = "this method is volatile and may change")]
|
#[deprecated(note = "this method is volatile and may change")]
|
||||||
pub fn eval_expression_tree(
|
pub fn eval_expression_tree(
|
||||||
&self,
|
&self,
|
||||||
|
context: &mut EvalContext,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
mods: &mut Imports,
|
|
||||||
state: &mut State,
|
|
||||||
lib: &Module,
|
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
expr: &Expression,
|
expr: &Expression,
|
||||||
level: usize,
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>> {
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
||||||
self.eval_expr(scope, mods, state, lib, this_ptr, expr.expr(), level)
|
self.eval_expr(
|
||||||
|
scope,
|
||||||
|
context.mods,
|
||||||
|
context.state,
|
||||||
|
context.lib,
|
||||||
|
context.this_ptr,
|
||||||
|
expr.expr(),
|
||||||
|
context.level,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate an expression
|
/// Evaluate an expression
|
||||||
@ -1773,8 +1777,8 @@ impl Engine {
|
|||||||
Expr::CharConstant(x) => Ok(x.0.into()),
|
Expr::CharConstant(x) => Ok(x.0.into()),
|
||||||
Expr::FnPointer(x) => Ok(FnPtr::new_unchecked(x.0.clone()).into()),
|
Expr::FnPointer(x) => Ok(FnPtr::new_unchecked(x.0.clone()).into()),
|
||||||
Expr::Variable(x) if (x.0).0 == KEYWORD_THIS => {
|
Expr::Variable(x) if (x.0).0 == KEYWORD_THIS => {
|
||||||
if let Some(ref val) = this_ptr {
|
if let Some(val) = this_ptr {
|
||||||
Ok((*val).clone())
|
Ok(val.clone())
|
||||||
} else {
|
} else {
|
||||||
Err(Box::new(EvalAltResult::ErrorUnboundedThis((x.0).1)))
|
Err(Box::new(EvalAltResult::ErrorUnboundedThis((x.0).1)))
|
||||||
}
|
}
|
||||||
@ -1829,15 +1833,16 @@ impl Engine {
|
|||||||
// Not built in, map to `var = var op rhs`
|
// Not built in, map to `var = var op rhs`
|
||||||
let op = &op[..op.len() - 1]; // extract operator without =
|
let op = &op[..op.len() - 1]; // extract operator without =
|
||||||
let hash = calc_fn_hash(empty(), op, 2, empty());
|
let hash = calc_fn_hash(empty(), op, 2, empty());
|
||||||
|
// Clone the LHS value
|
||||||
let args = &mut [&mut lhs_ptr.clone(), &mut rhs_val];
|
let args = &mut [&mut lhs_ptr.clone(), &mut rhs_val];
|
||||||
|
// Run function
|
||||||
// Set variable value
|
let (value, _) = self
|
||||||
*lhs_ptr = self
|
|
||||||
.exec_fn_call(
|
.exec_fn_call(
|
||||||
state, lib, op, true, hash, args, false, false, None, level,
|
state, lib, op, true, hash, args, false, false, None, level,
|
||||||
)
|
)
|
||||||
.map(|(v, _)| v)
|
|
||||||
.map_err(|err| err.new_position(*op_pos))?;
|
.map_err(|err| err.new_position(*op_pos))?;
|
||||||
|
// Set value to LHS
|
||||||
|
*lhs_ptr = value;
|
||||||
}
|
}
|
||||||
Ok(Default::default())
|
Ok(Default::default())
|
||||||
}
|
}
|
||||||
@ -2215,7 +2220,14 @@ impl Engine {
|
|||||||
Expr::Custom(x) => {
|
Expr::Custom(x) => {
|
||||||
let func = (x.0).1.as_ref();
|
let func = (x.0).1.as_ref();
|
||||||
let ep: StaticVec<_> = (x.0).0.iter().map(|e| e.into()).collect();
|
let ep: StaticVec<_> = (x.0).0.iter().map(|e| e.into()).collect();
|
||||||
func(self, scope, mods, state, lib, this_ptr, ep.as_ref(), level)
|
let mut context = EvalContext {
|
||||||
|
mods,
|
||||||
|
state,
|
||||||
|
lib,
|
||||||
|
this_ptr,
|
||||||
|
level,
|
||||||
|
};
|
||||||
|
func(self, &mut context, scope, ep.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
@ -2492,12 +2504,8 @@ impl Engine {
|
|||||||
for ((id, id_pos), rename) in list.iter() {
|
for ((id, id_pos), rename) in list.iter() {
|
||||||
// Mark scope variables as public
|
// Mark scope variables as public
|
||||||
if let Some(index) = scope.get_index(id).map(|(i, _)| i) {
|
if let Some(index) = scope.get_index(id).map(|(i, _)| i) {
|
||||||
let alias = rename
|
let alias = rename.as_ref().map(|(n, _)| n).unwrap_or_else(|| id);
|
||||||
.as_ref()
|
scope.set_entry_alias(index, alias.clone());
|
||||||
.map(|(n, _)| n.clone())
|
|
||||||
.unwrap_or_else(|| id.clone());
|
|
||||||
|
|
||||||
scope.set_entry_alias(index, alias);
|
|
||||||
} else {
|
} else {
|
||||||
return Err(Box::new(EvalAltResult::ErrorVariableNotFound(
|
return Err(Box::new(EvalAltResult::ErrorVariableNotFound(
|
||||||
id.into(),
|
id.into(),
|
||||||
|
@ -175,6 +175,10 @@ pub use parser::{CustomExpr, Expr, ReturnType, ScriptFnDef, Stmt};
|
|||||||
#[deprecated(note = "this type is volatile and may change")]
|
#[deprecated(note = "this type is volatile and may change")]
|
||||||
pub use engine::{Expression, Imports, State as EvalState};
|
pub use engine::{Expression, Imports, State as EvalState};
|
||||||
|
|
||||||
|
#[cfg(feature = "internals")]
|
||||||
|
#[deprecated(note = "this type is volatile and may change")]
|
||||||
|
pub use syntax::EvalContext;
|
||||||
|
|
||||||
#[cfg(feature = "internals")]
|
#[cfg(feature = "internals")]
|
||||||
#[deprecated(note = "this type is volatile and may change")]
|
#[deprecated(note = "this type is volatile and may change")]
|
||||||
pub use module::ModuleRef;
|
pub use module::ModuleRef;
|
||||||
|
@ -434,7 +434,7 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
|
|||||||
(Expr::StringConstant(s), Expr::IntegerConstant(i)) if i.0 >= 0 && (i.0 as usize) < s.0.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
|
// String literal indexing - get the character
|
||||||
state.set_dirty();
|
state.set_dirty();
|
||||||
Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).expect("should get char"), s.1)))
|
Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).unwrap(), s.1)))
|
||||||
}
|
}
|
||||||
// lhs[rhs]
|
// lhs[rhs]
|
||||||
(lhs, rhs) => Expr::Index(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
|
(lhs, rhs) => Expr::Index(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
|
||||||
@ -614,7 +614,7 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
|
|||||||
state.set_dirty();
|
state.set_dirty();
|
||||||
|
|
||||||
// Replace constant with value
|
// Replace constant with value
|
||||||
state.find_constant(&name).expect("should find constant in scope!").clone().set_position(pos)
|
state.find_constant(&name).unwrap().clone().set_position(pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Custom syntax
|
// Custom syntax
|
||||||
@ -655,10 +655,7 @@ fn optimize(
|
|||||||
&& expr.as_ref().map(|v| v.is_constant()).unwrap_or(false)
|
&& expr.as_ref().map(|v| v.is_constant()).unwrap_or(false)
|
||||||
})
|
})
|
||||||
.for_each(|ScopeEntry { name, expr, .. }| {
|
.for_each(|ScopeEntry { name, expr, .. }| {
|
||||||
state.push_constant(
|
state.push_constant(name.as_ref(), expr.as_ref().unwrap().as_ref().clone())
|
||||||
name.as_ref(),
|
|
||||||
(**expr.as_ref().expect("should be Some(expr)")).clone(),
|
|
||||||
)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let orig_constants_len = state.constants.len();
|
let orig_constants_len = state.constants.len();
|
||||||
|
@ -22,26 +22,13 @@ use crate::stdlib::{
|
|||||||
#[cfg(not(feature = "sync"))]
|
#[cfg(not(feature = "sync"))]
|
||||||
pub type FnCustomSyntaxEval = dyn Fn(
|
pub type FnCustomSyntaxEval = dyn Fn(
|
||||||
&Engine,
|
&Engine,
|
||||||
|
&mut EvalContext,
|
||||||
&mut Scope,
|
&mut Scope,
|
||||||
&mut Imports,
|
|
||||||
&mut State,
|
|
||||||
&Module,
|
|
||||||
&mut Option<&mut Dynamic>,
|
|
||||||
&[Expression],
|
&[Expression],
|
||||||
usize,
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>>;
|
) -> Result<Dynamic, Box<EvalAltResult>>;
|
||||||
/// A general function trail object.
|
/// A general function trail object.
|
||||||
#[cfg(feature = "sync")]
|
#[cfg(feature = "sync")]
|
||||||
pub type FnCustomSyntaxEval = dyn Fn(
|
pub type FnCustomSyntaxEval = dyn Fn(&Engine, &mut EvalContext, &mut Scope, &[Expression]) -> Result<Dynamic, Box<EvalAltResult>>
|
||||||
&Engine,
|
|
||||||
&mut Scope,
|
|
||||||
&mut Imports,
|
|
||||||
&mut State,
|
|
||||||
&Module,
|
|
||||||
&mut Option<&mut Dynamic>,
|
|
||||||
&[Expression],
|
|
||||||
usize,
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>>
|
|
||||||
+ Send
|
+ Send
|
||||||
+ Sync;
|
+ Sync;
|
||||||
|
|
||||||
@ -58,6 +45,14 @@ impl fmt::Debug for CustomSyntax {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct EvalContext<'a, 'b: 'a, 's, 'm, 't, 'd: 't> {
|
||||||
|
pub(crate) mods: &'a mut Imports<'b>,
|
||||||
|
pub(crate) state: &'s mut State,
|
||||||
|
pub(crate) lib: &'m Module,
|
||||||
|
pub(crate) this_ptr: &'t mut Option<&'d mut Dynamic>,
|
||||||
|
pub(crate) level: usize,
|
||||||
|
}
|
||||||
|
|
||||||
impl Engine {
|
impl Engine {
|
||||||
pub fn register_custom_syntax<S: AsRef<str> + ToString>(
|
pub fn register_custom_syntax<S: AsRef<str> + ToString>(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -65,13 +60,9 @@ impl Engine {
|
|||||||
scope_delta: isize,
|
scope_delta: isize,
|
||||||
func: impl Fn(
|
func: impl Fn(
|
||||||
&Engine,
|
&Engine,
|
||||||
|
&mut EvalContext,
|
||||||
&mut Scope,
|
&mut Scope,
|
||||||
&mut Imports,
|
|
||||||
&mut State,
|
|
||||||
&Module,
|
|
||||||
&mut Option<&mut Dynamic>,
|
|
||||||
&[Expression],
|
&[Expression],
|
||||||
usize,
|
|
||||||
) -> Result<Dynamic, Box<EvalAltResult>>
|
) -> Result<Dynamic, Box<EvalAltResult>>
|
||||||
+ SendSync
|
+ SendSync
|
||||||
+ 'static,
|
+ 'static,
|
||||||
|
@ -12,6 +12,7 @@ use crate::stdlib::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// Cast a type into another type.
|
/// Cast a type into another type.
|
||||||
|
#[inline(always)]
|
||||||
pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Option<B> {
|
pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Option<B> {
|
||||||
if TypeId::of::<B>() == a.type_id() {
|
if TypeId::of::<B>() == a.type_id() {
|
||||||
// SAFETY: Just checked we have the right type. We explicitly forget the
|
// SAFETY: Just checked we have the right type. We explicitly forget the
|
||||||
@ -28,6 +29,7 @@ pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Option<B> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Cast a Boxed type into another type.
|
/// Cast a Boxed type into another type.
|
||||||
|
#[inline(always)]
|
||||||
pub fn unsafe_cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<Box<T>, Box<X>> {
|
pub fn unsafe_cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<Box<T>, Box<X>> {
|
||||||
// Only allow casting to the exact same type
|
// Only allow casting to the exact same type
|
||||||
if TypeId::of::<X>() == TypeId::of::<T>() {
|
if TypeId::of::<X>() == TypeId::of::<T>() {
|
||||||
@ -51,6 +53,7 @@ pub fn unsafe_cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<Box<T>, B
|
|||||||
///
|
///
|
||||||
/// Force-casting a local variable's lifetime to the current `Scope`'s larger lifetime saves
|
/// Force-casting a local variable's 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.
|
/// on allocations and string cloning, thus avoids us having to maintain a chain of `Scope`'s.
|
||||||
|
#[inline]
|
||||||
pub fn unsafe_cast_var_name_to_lifetime<'s>(name: &str, state: &State) -> Cow<'s, str> {
|
pub fn unsafe_cast_var_name_to_lifetime<'s>(name: &str, state: &State) -> Cow<'s, str> {
|
||||||
// If not at global level, we can force-cast
|
// If not at global level, we can force-cast
|
||||||
if state.scope_level > 0 {
|
if state.scope_level > 0 {
|
||||||
|
26
src/utils.rs
26
src/utils.rs
@ -36,11 +36,9 @@ use ahash::AHasher;
|
|||||||
pub struct StraightHasher(u64);
|
pub struct StraightHasher(u64);
|
||||||
|
|
||||||
impl Hasher for StraightHasher {
|
impl Hasher for StraightHasher {
|
||||||
#[inline(always)]
|
|
||||||
fn finish(&self) -> u64 {
|
fn finish(&self) -> u64 {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
#[inline]
|
|
||||||
fn write(&mut self, bytes: &[u8]) {
|
fn write(&mut self, bytes: &[u8]) {
|
||||||
let mut key = [0_u8; 8];
|
let mut key = [0_u8; 8];
|
||||||
key.copy_from_slice(&bytes[..8]); // Panics if fewer than 8 bytes
|
key.copy_from_slice(&bytes[..8]); // Panics if fewer than 8 bytes
|
||||||
@ -50,7 +48,6 @@ impl Hasher for StraightHasher {
|
|||||||
|
|
||||||
impl StraightHasher {
|
impl StraightHasher {
|
||||||
/// Create a `StraightHasher`.
|
/// Create a `StraightHasher`.
|
||||||
#[inline(always)]
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self(0)
|
Self(0)
|
||||||
}
|
}
|
||||||
@ -63,7 +60,6 @@ pub struct StraightHasherBuilder;
|
|||||||
impl BuildHasher for StraightHasherBuilder {
|
impl BuildHasher for StraightHasherBuilder {
|
||||||
type Hasher = StraightHasher;
|
type Hasher = StraightHasher;
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
fn build_hasher(&self) -> Self::Hasher {
|
fn build_hasher(&self) -> Self::Hasher {
|
||||||
StraightHasher::new()
|
StraightHasher::new()
|
||||||
}
|
}
|
||||||
@ -150,7 +146,6 @@ pub struct StaticVec<T> {
|
|||||||
const MAX_STATIC_VEC: usize = 4;
|
const MAX_STATIC_VEC: usize = 4;
|
||||||
|
|
||||||
impl<T> Drop for StaticVec<T> {
|
impl<T> Drop for StaticVec<T> {
|
||||||
#[inline(always)]
|
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.clear();
|
self.clear();
|
||||||
}
|
}
|
||||||
@ -233,7 +228,6 @@ impl<T: 'static> IntoIterator for StaticVec<T> {
|
|||||||
|
|
||||||
impl<T> StaticVec<T> {
|
impl<T> StaticVec<T> {
|
||||||
/// Create a new `StaticVec`.
|
/// Create a new `StaticVec`.
|
||||||
#[inline(always)]
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Default::default()
|
Default::default()
|
||||||
}
|
}
|
||||||
@ -249,7 +243,6 @@ impl<T> StaticVec<T> {
|
|||||||
self.len = 0;
|
self.len = 0;
|
||||||
}
|
}
|
||||||
/// Extract a `MaybeUninit` into a concrete initialized type.
|
/// Extract a `MaybeUninit` into a concrete initialized type.
|
||||||
#[inline(always)]
|
|
||||||
fn extract(value: MaybeUninit<T>) -> T {
|
fn extract(value: MaybeUninit<T>) -> T {
|
||||||
unsafe { value.assume_init() }
|
unsafe { value.assume_init() }
|
||||||
}
|
}
|
||||||
@ -311,7 +304,6 @@ impl<T> StaticVec<T> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
/// Is data stored in fixed-size storage?
|
/// Is data stored in fixed-size storage?
|
||||||
#[inline(always)]
|
|
||||||
fn is_fixed_storage(&self) -> bool {
|
fn is_fixed_storage(&self) -> bool {
|
||||||
self.len <= MAX_STATIC_VEC
|
self.len <= MAX_STATIC_VEC
|
||||||
}
|
}
|
||||||
@ -418,12 +410,10 @@ impl<T> StaticVec<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Get the number of items in this `StaticVec`.
|
/// Get the number of items in this `StaticVec`.
|
||||||
#[inline(always)]
|
|
||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
self.len
|
self.len
|
||||||
}
|
}
|
||||||
/// Is this `StaticVec` empty?
|
/// Is this `StaticVec` empty?
|
||||||
#[inline(always)]
|
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.len == 0
|
self.len == 0
|
||||||
}
|
}
|
||||||
@ -664,48 +654,41 @@ pub struct ImmutableString(Shared<String>);
|
|||||||
impl Deref for ImmutableString {
|
impl Deref for ImmutableString {
|
||||||
type Target = String;
|
type Target = String;
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRef<String> for ImmutableString {
|
impl AsRef<String> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn as_ref(&self) -> &String {
|
fn as_ref(&self) -> &String {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Borrow<str> for ImmutableString {
|
impl Borrow<str> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn borrow(&self) -> &str {
|
fn borrow(&self) -> &str {
|
||||||
self.0.as_str()
|
self.0.as_str()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&str> for ImmutableString {
|
impl From<&str> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from(value: &str) -> Self {
|
fn from(value: &str) -> Self {
|
||||||
Self(value.to_string().into())
|
Self(value.to_string().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<String> for ImmutableString {
|
impl From<String> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from(value: String) -> Self {
|
fn from(value: String) -> Self {
|
||||||
Self(value.into())
|
Self(value.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Box<String>> for ImmutableString {
|
impl From<Box<String>> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from(value: Box<String>) -> Self {
|
fn from(value: Box<String>) -> Self {
|
||||||
Self(value.into())
|
Self(value.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ImmutableString> for String {
|
impl From<ImmutableString> for String {
|
||||||
#[inline(always)]
|
|
||||||
fn from(value: ImmutableString) -> Self {
|
fn from(value: ImmutableString) -> Self {
|
||||||
value.into_owned()
|
value.into_owned()
|
||||||
}
|
}
|
||||||
@ -714,49 +697,42 @@ impl From<ImmutableString> for String {
|
|||||||
impl FromStr for ImmutableString {
|
impl FromStr for ImmutableString {
|
||||||
type Err = ();
|
type Err = ();
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
Ok(Self(s.to_string().into()))
|
Ok(Self(s.to_string().into()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromIterator<char> for ImmutableString {
|
impl FromIterator<char> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
|
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
|
||||||
Self(iter.into_iter().collect::<String>().into())
|
Self(iter.into_iter().collect::<String>().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> FromIterator<&'a char> for ImmutableString {
|
impl<'a> FromIterator<&'a char> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
|
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
|
||||||
Self(iter.into_iter().cloned().collect::<String>().into())
|
Self(iter.into_iter().cloned().collect::<String>().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> FromIterator<&'a str> for ImmutableString {
|
impl<'a> FromIterator<&'a str> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
|
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
|
||||||
Self(iter.into_iter().collect::<String>().into())
|
Self(iter.into_iter().collect::<String>().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> FromIterator<String> for ImmutableString {
|
impl<'a> FromIterator<String> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
|
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
|
||||||
Self(iter.into_iter().collect::<String>().into())
|
Self(iter.into_iter().collect::<String>().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for ImmutableString {
|
impl fmt::Display for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
fmt::Display::fmt(self.0.as_str(), f)
|
fmt::Display::fmt(self.0.as_str(), f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for ImmutableString {
|
impl fmt::Debug for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
fmt::Debug::fmt(self.0.as_str(), f)
|
fmt::Debug::fmt(self.0.as_str(), f)
|
||||||
}
|
}
|
||||||
@ -891,7 +867,6 @@ impl Add<char> for &ImmutableString {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AddAssign<char> for ImmutableString {
|
impl AddAssign<char> for ImmutableString {
|
||||||
#[inline(always)]
|
|
||||||
fn add_assign(&mut self, rhs: char) {
|
fn add_assign(&mut self, rhs: char) {
|
||||||
self.make_mut().push(rhs);
|
self.make_mut().push(rhs);
|
||||||
}
|
}
|
||||||
@ -906,7 +881,6 @@ impl ImmutableString {
|
|||||||
}
|
}
|
||||||
/// Make sure that the `ImmutableString` is unique (i.e. no other outstanding references).
|
/// Make sure that the `ImmutableString` is unique (i.e. no other outstanding references).
|
||||||
/// Then return a mutable reference to the `String`.
|
/// Then return a mutable reference to the `String`.
|
||||||
#[inline(always)]
|
|
||||||
pub fn make_mut(&mut self) -> &mut String {
|
pub fn make_mut(&mut self) -> &mut String {
|
||||||
shared_make_mut(&mut self.0)
|
shared_make_mut(&mut self.0)
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,5 @@
|
|||||||
#![cfg(feature = "internals")]
|
#![cfg(feature = "internals")]
|
||||||
use rhai::{
|
use rhai::{Engine, EvalAltResult, EvalContext, Expression, LexError, ParseErrorType, Scope, INT};
|
||||||
Dynamic, Engine, EvalAltResult, EvalState, Expression, Imports, LexError, Module, ParseError,
|
|
||||||
ParseErrorType, Scope, INT,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||||
@ -28,13 +25,9 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
|||||||
],
|
],
|
||||||
1,
|
1,
|
||||||
|engine: &Engine,
|
|engine: &Engine,
|
||||||
|
context: &mut EvalContext,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
mods: &mut Imports,
|
inputs: &[Expression]| {
|
||||||
state: &mut EvalState,
|
|
||||||
lib: &Module,
|
|
||||||
this_ptr: &mut Option<&mut Dynamic>,
|
|
||||||
inputs: &[Expression],
|
|
||||||
level: usize| {
|
|
||||||
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
||||||
let stmt = inputs.get(1).unwrap();
|
let stmt = inputs.get(1).unwrap();
|
||||||
let expr = inputs.get(2).unwrap();
|
let expr = inputs.get(2).unwrap();
|
||||||
@ -42,10 +35,10 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
|||||||
scope.push(var_name, 0 as INT);
|
scope.push(var_name, 0 as INT);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
engine.eval_expression_tree(scope, mods, state, lib, this_ptr, stmt, level)?;
|
engine.eval_expression_tree(context, scope, stmt)?;
|
||||||
|
|
||||||
if !engine
|
if !engine
|
||||||
.eval_expression_tree(scope, mods, state, lib, this_ptr, expr, level)?
|
.eval_expression_tree(context, scope, expr)?
|
||||||
.as_bool()
|
.as_bool()
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
EvalAltResult::ErrorBooleanArgMismatch(
|
EvalAltResult::ErrorBooleanArgMismatch(
|
||||||
@ -78,7 +71,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
|||||||
|
|
||||||
// The first symbol must be an identifier
|
// The first symbol must be an identifier
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
*engine.register_custom_syntax(&["!"], 0, |_, _, _, _, _, _, _, _| Ok(().into())).expect_err("should error"),
|
*engine.register_custom_syntax(&["!"], 0, |_, _, _, _| Ok(().into())).expect_err("should error"),
|
||||||
LexError::ImproperSymbol(s) if s == "!"
|
LexError::ImproperSymbol(s) if s == "!"
|
||||||
));
|
));
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user