Make all public API's return Box<EvalAltResult> to reduce footprint.

This commit is contained in:
Stephen Chung 2020-04-21 23:25:12 +08:00
parent 0a75479637
commit 69733688bf
63 changed files with 337 additions and 303 deletions

View File

@ -203,7 +203,7 @@ To get going with Rhai, create an instance of the scripting engine via `Engine::
```rust ```rust
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
fn main() -> Result<(), EvalAltResult> fn main() -> Result<(), Box<EvalAltResult>>
{ {
let engine = Engine::new(); let engine = Engine::new();
@ -324,7 +324,7 @@ let script = "fn calc(x, y) { x + y.len() < 42 }";
// 1) a tuple made up of the types of the script function's parameters // 1) a tuple made up of the types of the script function's parameters
// 2) the return type of the script function // 2) the return type of the script function
// //
// 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, EvalAltResult>> and is callable! // 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, Box<EvalAltResult>>> and is callable!
let func = Func::<(i64, String), bool>::create_from_script( let func = Func::<(i64, String), bool>::create_from_script(
// ^^^^^^^^^^^^^ function parameter types in tuple // ^^^^^^^^^^^^^ function parameter types in tuple
@ -340,7 +340,7 @@ schedule_callback(func); // pass it as a callback to anot
// Although there is nothing you can't do by manually writing out the closure yourself... // Although there is nothing you can't do by manually writing out the closure yourself...
let engine = Engine::new(); let engine = Engine::new();
let ast = engine.compile(script)?; let ast = engine.compile(script)?;
schedule_callback(Box::new(move |x: i64, y: String| -> Result<bool, EvalAltResult> { schedule_callback(Box::new(move |x: i64, y: String| -> Result<bool, Box<EvalAltResult>> {
engine.call_fn(&mut Scope::new(), &ast, "calc", (x, y)) engine.call_fn(&mut Scope::new(), &ast, "calc", (x, y))
})); }));
``` ```
@ -560,12 +560,12 @@ Traits
A number of traits, under the `rhai::` module namespace, provide additional functionalities. A number of traits, under the `rhai::` module namespace, provide additional functionalities.
| Trait | Description | Methods | | Trait | Description | Methods |
| ------------------- | --------------------------------------------------------------------------------- | --------------------------------------- | | ------------------- | -------------------------------------------------------------------------------------- | --------------------------------------- |
| `RegisterFn` | Trait for registering functions | `register_fn` | | `RegisterFn` | Trait for registering functions | `register_fn` |
| `RegisterDynamicFn` | Trait for registering functions returning [`Dynamic`] | `register_dynamic_fn` | | `RegisterDynamicFn` | Trait for registering functions returning [`Dynamic`] | `register_dynamic_fn` |
| `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, EvalAltResult>` | `register_result_fn` | | `RegisterResultFn` | Trait for registering fallible functions returning `Result<`_T_`, Box<EvalAltResult>>` | `register_result_fn` |
| `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` | | `Func` | Trait for creating anonymous functions from script | `create_from_ast`, `create_from_script` |
Working with functions Working with functions
---------------------- ----------------------
@ -588,7 +588,7 @@ fn get_an_any() -> Dynamic {
Dynamic::from(42_i64) Dynamic::from(42_i64)
} }
fn main() -> Result<(), EvalAltResult> fn main() -> Result<(), Box<EvalAltResult>>
{ {
let engine = Engine::new(); let engine = Engine::new();
@ -657,18 +657,20 @@ Fallible functions
If a function is _fallible_ (i.e. it returns a `Result<_, Error>`), it can be registered with `register_result_fn` If a function is _fallible_ (i.e. it returns a `Result<_, Error>`), it can be registered with `register_result_fn`
(using the `RegisterResultFn` trait). (using the `RegisterResultFn` trait).
The function must return `Result<_, EvalAltResult>`. `EvalAltResult` implements `From<&str>` and `From<String>` etc. The function must return `Result<_, Box<EvalAltResult>>`. `Box<EvalAltResult>` implements `From<&str>` and `From<String>` etc.
and the error text gets converted into `EvalAltResult::ErrorRuntime`. and the error text gets converted into `Box<EvalAltResult::ErrorRuntime>`.
The error values are `Box`-ed in order to reduce memory footprint of the error path, which should be hit rarely.
```rust ```rust
use rhai::{Engine, EvalAltResult, Position}; use rhai::{Engine, EvalAltResult, Position};
use rhai::RegisterResultFn; // use 'RegisterResultFn' trait for 'register_result_fn' use rhai::RegisterResultFn; // use 'RegisterResultFn' trait for 'register_result_fn'
// Function that may fail // Function that may fail
fn safe_divide(x: i64, y: i64) -> Result<i64, EvalAltResult> { fn safe_divide(x: i64, y: i64) -> Result<i64, Box<EvalAltResult>> {
if y == 0 { if y == 0 {
// Return an error if y is zero // Return an error if y is zero
Err("Division by zero!".into()) // short-cut to create EvalAltResult Err("Division by zero!".into()) // short-cut to create Box<EvalAltResult::ErrorRuntime>
} else { } else {
Ok(x / y) Ok(x / y)
} }
@ -682,7 +684,7 @@ fn main()
engine.register_result_fn("divide", safe_divide); engine.register_result_fn("divide", safe_divide);
if let Err(error) = engine.eval::<i64>("divide(40, 0)") { if let Err(error) = engine.eval::<i64>("divide(40, 0)") {
println!("Error: {:?}", error); // prints ErrorRuntime("Division by zero detected!", (1, 1)") println!("Error: {:?}", *error); // prints ErrorRuntime("Division by zero detected!", (1, 1)")
} }
} }
``` ```
@ -769,7 +771,7 @@ impl TestStruct {
} }
} }
fn main() -> Result<(), EvalAltResult> fn main() -> Result<(), Box<EvalAltResult>>
{ {
let engine = Engine::new(); let engine = Engine::new();
@ -933,7 +935,7 @@ threaded through multiple invocations:
```rust ```rust
use rhai::{Engine, Scope, EvalAltResult}; use rhai::{Engine, Scope, EvalAltResult};
fn main() -> Result<(), EvalAltResult> fn main() -> Result<(), Box<EvalAltResult>>
{ {
let engine = Engine::new(); let engine = Engine::new();
@ -1794,7 +1796,7 @@ return 123 + 456; // returns 579
Errors and `throw`-ing exceptions Errors and `throw`-ing exceptions
-------------------------------- --------------------------------
All of [`Engine`]'s evaluation/consuming methods return `Result<T, rhai::EvalAltResult>` with `EvalAltResult` All of [`Engine`]'s evaluation/consuming methods return `Result<T, Box<rhai::EvalAltResult>>` with `EvalAltResult`
holding error information. To deliberately return an error during an evaluation, use the `throw` keyword. holding error information. To deliberately return an error during an evaluation, use the `throw` keyword.
```rust ```rust

View File

@ -16,7 +16,7 @@ impl TestStruct {
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
fn main() -> Result<(), EvalAltResult> { fn main() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
engine.register_type::<TestStruct>(); engine.register_type::<TestStruct>();

View File

@ -1,7 +1,7 @@
use rhai::{packages::*, Engine, EvalAltResult, INT}; use rhai::{packages::*, Engine, EvalAltResult, INT};
use std::rc::Rc; use std::rc::Rc;
fn main() -> Result<(), EvalAltResult> { fn main() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new_raw(); let mut engine = Engine::new_raw();
engine.load_package(ArithmeticPackage::new().get()); engine.load_package(ArithmeticPackage::new().get());

View File

@ -2,7 +2,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
fn main() -> Result<(), EvalAltResult> { fn main() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let result = engine.eval::<INT>("40 + 2")?; let result = engine.eval::<INT>("40 + 2")?;

View File

@ -157,7 +157,7 @@ fn main() {
Ok(_) => (), Ok(_) => (),
Err(err) => { Err(err) => {
println!(); println!();
print_error(&input, err); print_error(&input, *err);
println!(); println!();
} }
} }

View File

@ -1,6 +1,6 @@
use rhai::{Engine, EvalAltResult, Scope, INT}; use rhai::{Engine, EvalAltResult, Scope, INT};
fn main() -> Result<(), EvalAltResult> { fn main() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();

View File

@ -72,7 +72,7 @@ fn main() {
eprintln!("{:=<1$}", "", filename.len()); eprintln!("{:=<1$}", "", filename.len());
eprintln!(""); eprintln!("");
eprint_error(&contents, err); eprint_error(&contents, *err);
} }
} }
} }

View File

@ -1,6 +1,6 @@
use rhai::{Engine, EvalAltResult, RegisterFn, INT}; use rhai::{Engine, EvalAltResult, RegisterFn, INT};
fn main() -> Result<(), EvalAltResult> { fn main() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
fn add(x: INT, y: INT) -> INT { fn add(x: INT, y: INT) -> INT {

View File

@ -450,7 +450,7 @@ impl Dynamic {
/// Cast the `Dynamic` as the system integer type `INT` and return it. /// Cast the `Dynamic` as the system integer type `INT` and return it.
/// Returns the name of the actual type if the cast fails. /// Returns the name of the actual type if the cast fails.
pub(crate) fn as_int(&self) -> Result<INT, &'static str> { pub fn as_int(&self) -> Result<INT, &'static str> {
match self.0 { match self.0 {
Union::Int(n) => Ok(n), Union::Int(n) => Ok(n),
_ => Err(self.type_name()), _ => Err(self.type_name()),
@ -459,7 +459,7 @@ impl Dynamic {
/// Cast the `Dynamic` as a `bool` and return it. /// Cast the `Dynamic` as a `bool` and return it.
/// Returns the name of the actual type if the cast fails. /// Returns the name of the actual type if the cast fails.
pub(crate) fn as_bool(&self) -> Result<bool, &'static str> { pub fn as_bool(&self) -> Result<bool, &'static str> {
match self.0 { match self.0 {
Union::Bool(b) => Ok(b), Union::Bool(b) => Ok(b),
_ => Err(self.type_name()), _ => Err(self.type_name()),
@ -468,7 +468,7 @@ impl Dynamic {
/// Cast the `Dynamic` as a `char` and return it. /// Cast the `Dynamic` as a `char` and return it.
/// Returns the name of the actual type if the cast fails. /// Returns the name of the actual type if the cast fails.
pub(crate) fn as_char(&self) -> Result<char, &'static str> { pub fn as_char(&self) -> Result<char, &'static str> {
match self.0 { match self.0 {
Union::Char(n) => Ok(n), Union::Char(n) => Ok(n),
_ => Err(self.type_name()), _ => Err(self.type_name()),
@ -477,7 +477,7 @@ impl Dynamic {
/// Cast the `Dynamic` as a string and return the string slice. /// Cast the `Dynamic` as a string and return the string slice.
/// Returns the name of the actual type if the cast fails. /// Returns the name of the actual type if the cast fails.
pub(crate) fn as_str(&self) -> Result<&str, &'static str> { pub fn as_str(&self) -> Result<&str, &'static str> {
match &self.0 { match &self.0 {
Union::Str(s) => Ok(s), Union::Str(s) => Ok(s),
_ => Err(self.type_name()), _ => Err(self.type_name()),
@ -486,30 +486,36 @@ impl Dynamic {
/// Convert the `Dynamic` into `String` and return it. /// Convert the `Dynamic` into `String` and return it.
/// Returns the name of the actual type if the cast fails. /// Returns the name of the actual type if the cast fails.
pub(crate) fn take_string(self) -> Result<String, &'static str> { pub fn take_string(self) -> Result<String, &'static str> {
match self.0 { match self.0 {
Union::Str(s) => Ok(*s), Union::Str(s) => Ok(*s),
_ => Err(self.type_name()), _ => Err(self.type_name()),
} }
} }
pub(crate) fn from_unit() -> Self { /// Create a `Dynamic` from `()`.
pub fn from_unit() -> Self {
Self(Union::Unit(())) Self(Union::Unit(()))
} }
pub(crate) fn from_bool(value: bool) -> Self { /// Create a `Dynamic` from a `bool`.
pub fn from_bool(value: bool) -> Self {
Self(Union::Bool(value)) Self(Union::Bool(value))
} }
pub(crate) fn from_int(value: INT) -> Self { /// Create a `Dynamic` from an `INT`.
pub fn from_int(value: INT) -> Self {
Self(Union::Int(value)) Self(Union::Int(value))
} }
/// Create a `Dynamic` from a `FLOAT`. Not available under `no_float`.
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
pub(crate) fn from_float(value: FLOAT) -> Self { pub(crate) fn from_float(value: FLOAT) -> Self {
Self(Union::Float(value)) Self(Union::Float(value))
} }
pub(crate) fn from_char(value: char) -> Self { /// Create a `Dynamic` from a `char`.
pub fn from_char(value: char) -> Self {
Self(Union::Char(value)) Self(Union::Char(value))
} }
pub(crate) fn from_string(value: String) -> Self { /// Create a `Dynamic` from a `String`.
pub fn from_string(value: String) -> Self {
Self(Union::Str(Box::new(value))) Self(Union::Str(Box::new(value)))
} }
} }

View File

@ -76,7 +76,7 @@ impl Engine {
/// fn update(&mut self, offset: i64) { self.field += offset; } /// fn update(&mut self, offset: i64) { self.field += offset; }
/// } /// }
/// ///
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// let mut engine = Engine::new(); /// let mut engine = Engine::new();
@ -116,7 +116,7 @@ impl Engine {
/// fn new() -> Self { TestStruct { field: 1 } } /// fn new() -> Self { TestStruct { field: 1 } }
/// } /// }
/// ///
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// let mut engine = Engine::new(); /// let mut engine = Engine::new();
@ -182,7 +182,7 @@ impl Engine {
/// fn get_field(&mut self) -> i64 { self.field } /// fn get_field(&mut self) -> i64 { self.field }
/// } /// }
/// ///
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// let mut engine = Engine::new(); /// let mut engine = Engine::new();
@ -224,7 +224,7 @@ impl Engine {
/// fn set_field(&mut self, new_val: i64) { self.field = new_val; } /// fn set_field(&mut self, new_val: i64) { self.field = new_val; }
/// } /// }
/// ///
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// let mut engine = Engine::new(); /// let mut engine = Engine::new();
@ -275,7 +275,7 @@ impl Engine {
/// fn set_field(&mut self, new_val: i64) { self.field = new_val; } /// fn set_field(&mut self, new_val: i64) { self.field = new_val; }
/// } /// }
/// ///
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// let mut engine = Engine::new(); /// let mut engine = Engine::new();
@ -310,7 +310,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -324,7 +324,7 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn compile(&self, script: &str) -> Result<AST, ParseError> { pub fn compile(&self, script: &str) -> Result<AST, Box<ParseError>> {
self.compile_with_scope(&Scope::new(), script) self.compile_with_scope(&Scope::new(), script)
} }
@ -335,7 +335,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_optimize"))] /// # #[cfg(not(feature = "no_optimize"))]
/// # { /// # {
/// use rhai::{Engine, Scope, OptimizationLevel}; /// use rhai::{Engine, Scope, OptimizationLevel};
@ -365,7 +365,7 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result<AST, ParseError> { pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result<AST, Box<ParseError>> {
self.compile_with_scope_and_optimization_level(scope, script, self.optimization_level) self.compile_with_scope_and_optimization_level(scope, script, self.optimization_level)
} }
@ -375,22 +375,22 @@ impl Engine {
scope: &Scope, scope: &Scope,
script: &str, script: &str,
optimization_level: OptimizationLevel, optimization_level: OptimizationLevel,
) -> Result<AST, ParseError> { ) -> Result<AST, Box<ParseError>> {
let scripts = [script]; let scripts = [script];
let stream = lex(&scripts); let stream = lex(&scripts);
parse(&mut stream.peekable(), self, scope, optimization_level).map_err(|err| *err) parse(&mut stream.peekable(), self, scope, optimization_level)
} }
/// Read the contents of a file into a string. /// Read the contents of a file into a string.
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
fn read_file(path: PathBuf) -> Result<String, EvalAltResult> { fn read_file(path: PathBuf) -> Result<String, Box<EvalAltResult>> {
let mut f = File::open(path.clone()) let mut f = File::open(path.clone())
.map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?; .map_err(|err| Box::new(EvalAltResult::ErrorReadingScriptFile(path.clone(), err)))?;
let mut contents = String::new(); let mut contents = String::new();
f.read_to_string(&mut contents) f.read_to_string(&mut contents)
.map_err(|err| EvalAltResult::ErrorReadingScriptFile(path.clone(), err))?; .map_err(|err| Box::new(EvalAltResult::ErrorReadingScriptFile(path.clone(), err)))?;
Ok(contents) Ok(contents)
} }
@ -400,7 +400,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ```no_run /// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -416,7 +416,7 @@ impl Engine {
/// # } /// # }
/// ``` /// ```
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
pub fn compile_file(&self, path: PathBuf) -> Result<AST, EvalAltResult> { pub fn compile_file(&self, path: PathBuf) -> Result<AST, Box<EvalAltResult>> {
self.compile_file_with_scope(&Scope::new(), path) self.compile_file_with_scope(&Scope::new(), path)
} }
@ -427,7 +427,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ```no_run /// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_optimize"))] /// # #[cfg(not(feature = "no_optimize"))]
/// # { /// # {
/// use rhai::{Engine, Scope, OptimizationLevel}; /// use rhai::{Engine, Scope, OptimizationLevel};
@ -455,7 +455,7 @@ impl Engine {
&self, &self,
scope: &Scope, scope: &Scope,
path: PathBuf, path: PathBuf,
) -> Result<AST, EvalAltResult> { ) -> Result<AST, Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?)) Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?))
} }
@ -467,7 +467,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -483,7 +483,7 @@ impl Engine {
/// # } /// # }
/// ``` /// ```
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub fn parse_json(&self, json: &str, has_null: bool) -> Result<Map, EvalAltResult> { pub fn parse_json(&self, json: &str, has_null: bool) -> Result<Map, Box<EvalAltResult>> {
let mut scope = Scope::new(); let mut scope = Scope::new();
// Trims the JSON string and add a '#' in front // Trims the JSON string and add a '#' in front
@ -510,7 +510,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -524,7 +524,7 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn compile_expression(&self, script: &str) -> Result<AST, ParseError> { pub fn compile_expression(&self, script: &str) -> Result<AST, Box<ParseError>> {
self.compile_expression_with_scope(&Scope::new(), script) self.compile_expression_with_scope(&Scope::new(), script)
} }
@ -537,7 +537,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_optimize"))] /// # #[cfg(not(feature = "no_optimize"))]
/// # { /// # {
/// use rhai::{Engine, Scope, OptimizationLevel}; /// use rhai::{Engine, Scope, OptimizationLevel};
@ -571,12 +571,11 @@ impl Engine {
&self, &self,
scope: &Scope, scope: &Scope,
script: &str, script: &str,
) -> Result<AST, ParseError> { ) -> Result<AST, Box<ParseError>> {
let scripts = [script]; let scripts = [script];
let stream = lex(&scripts); let stream = lex(&scripts);
parse_global_expr(&mut stream.peekable(), self, scope, self.optimization_level) parse_global_expr(&mut stream.peekable(), self, scope, self.optimization_level)
.map_err(|err| *err)
} }
/// Evaluate a script file. /// Evaluate a script file.
@ -584,7 +583,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ```no_run /// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -595,7 +594,7 @@ impl Engine {
/// # } /// # }
/// ``` /// ```
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> Result<T, EvalAltResult> { pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> Result<T, Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| self.eval::<T>(&contents)) Self::read_file(path).and_then(|contents| self.eval::<T>(&contents))
} }
@ -604,7 +603,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ```no_run /// ```no_run
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -623,7 +622,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
path: PathBuf, path: PathBuf,
) -> Result<T, EvalAltResult> { ) -> Result<T, Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| self.eval_with_scope::<T>(scope, &contents)) Self::read_file(path).and_then(|contents| self.eval_with_scope::<T>(scope, &contents))
} }
@ -632,7 +631,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -641,7 +640,7 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn eval<T: Variant + Clone>(&self, script: &str) -> Result<T, EvalAltResult> { pub fn eval<T: Variant + Clone>(&self, script: &str) -> Result<T, Box<EvalAltResult>> {
self.eval_with_scope(&mut Scope::new(), script) self.eval_with_scope(&mut Scope::new(), script)
} }
@ -650,7 +649,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -671,7 +670,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
script: &str, script: &str,
) -> Result<T, EvalAltResult> { ) -> Result<T, Box<EvalAltResult>> {
// Since the AST will be thrown away afterwards, don't bother to optimize it // Since the AST will be thrown away afterwards, don't bother to optimize it
let ast = let ast =
self.compile_with_scope_and_optimization_level(scope, script, OptimizationLevel::None)?; self.compile_with_scope_and_optimization_level(scope, script, OptimizationLevel::None)?;
@ -683,7 +682,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -692,7 +691,10 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> Result<T, EvalAltResult> { pub fn eval_expression<T: Variant + Clone>(
&self,
script: &str,
) -> Result<T, Box<EvalAltResult>> {
self.eval_expression_with_scope(&mut Scope::new(), script) self.eval_expression_with_scope(&mut Scope::new(), script)
} }
@ -701,7 +703,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -718,7 +720,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
script: &str, script: &str,
) -> Result<T, EvalAltResult> { ) -> Result<T, Box<EvalAltResult>> {
let scripts = [script]; let scripts = [script];
let stream = lex(&scripts); let stream = lex(&scripts);
// Since the AST will be thrown away afterwards, don't bother to optimize it // Since the AST will be thrown away afterwards, don't bother to optimize it
@ -731,7 +733,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -744,7 +746,7 @@ impl Engine {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> Result<T, EvalAltResult> { pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> Result<T, Box<EvalAltResult>> {
self.eval_ast_with_scope(&mut Scope::new(), ast) self.eval_ast_with_scope(&mut Scope::new(), ast)
} }
@ -753,7 +755,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -781,15 +783,16 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
ast: &AST, ast: &AST,
) -> Result<T, EvalAltResult> { ) -> Result<T, Box<EvalAltResult>> {
let result = self let result = self.eval_ast_with_scope_raw(scope, ast)?;
.eval_ast_with_scope_raw(scope, ast)
.map_err(|err| *err)?;
let return_type = self.map_type_name(result.type_name()); let return_type = self.map_type_name(result.type_name());
return result.try_cast::<T>().ok_or_else(|| { return result.try_cast::<T>().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(return_type.to_string(), Position::none()) Box::new(EvalAltResult::ErrorMismatchOutputType(
return_type.to_string(),
Position::none(),
))
}); });
} }
@ -812,7 +815,7 @@ impl Engine {
/// Evaluate a file, but throw away the result and only return error (if any). /// Evaluate a file, but throw away the result and only return error (if any).
/// Useful for when you don't need the result, but still need to keep track of possible errors. /// Useful for when you don't need the result, but still need to keep track of possible errors.
#[cfg(not(feature = "no_std"))] #[cfg(not(feature = "no_std"))]
pub fn consume_file(&self, path: PathBuf) -> Result<(), EvalAltResult> { pub fn consume_file(&self, path: PathBuf) -> Result<(), Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| self.consume(&contents)) Self::read_file(path).and_then(|contents| self.consume(&contents))
} }
@ -823,19 +826,23 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
path: PathBuf, path: PathBuf,
) -> Result<(), EvalAltResult> { ) -> Result<(), Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| self.consume_with_scope(scope, &contents)) Self::read_file(path).and_then(|contents| self.consume_with_scope(scope, &contents))
} }
/// Evaluate a string, but throw away the result and only return error (if any). /// Evaluate a string, but throw away the result and only return error (if any).
/// Useful for when you don't need the result, but still need to keep track of possible errors. /// Useful for when you don't need the result, but still need to keep track of possible errors.
pub fn consume(&self, script: &str) -> Result<(), EvalAltResult> { pub fn consume(&self, script: &str) -> Result<(), Box<EvalAltResult>> {
self.consume_with_scope(&mut Scope::new(), script) self.consume_with_scope(&mut Scope::new(), script)
} }
/// Evaluate a string with own scope, but throw away the result and only return error (if any). /// Evaluate a string with own scope, but throw away the result and only return error (if any).
/// Useful for when you don't need the result, but still need to keep track of possible errors. /// Useful for when you don't need the result, but still need to keep track of possible errors.
pub fn consume_with_scope(&self, scope: &mut Scope, script: &str) -> Result<(), EvalAltResult> { pub fn consume_with_scope(
&self,
scope: &mut Scope,
script: &str,
) -> Result<(), Box<EvalAltResult>> {
let scripts = [script]; let scripts = [script];
let stream = lex(&scripts); let stream = lex(&scripts);
@ -846,7 +853,7 @@ impl Engine {
/// Evaluate an AST, but throw away the result and only return error (if any). /// Evaluate an AST, but throw away the result and only return error (if any).
/// Useful for when you don't need the result, but still need to keep track of possible errors. /// Useful for when you don't need the result, but still need to keep track of possible errors.
pub fn consume_ast(&self, ast: &AST) -> Result<(), EvalAltResult> { pub fn consume_ast(&self, ast: &AST) -> Result<(), Box<EvalAltResult>> {
self.consume_ast_with_scope(&mut Scope::new(), ast) self.consume_ast_with_scope(&mut Scope::new(), ast)
} }
@ -856,7 +863,7 @@ impl Engine {
&self, &self,
scope: &mut Scope, scope: &mut Scope,
ast: &AST, ast: &AST,
) -> Result<(), EvalAltResult> { ) -> Result<(), Box<EvalAltResult>> {
ast.0 ast.0
.iter() .iter()
.try_fold(Dynamic::from_unit(), |_, stmt| { .try_fold(Dynamic::from_unit(), |_, stmt| {
@ -865,7 +872,7 @@ impl Engine {
.map_or_else( .map_or_else(
|err| match *err { |err| match *err {
EvalAltResult::Return(_, _) => Ok(()), EvalAltResult::Return(_, _) => Ok(()),
err => Err(err), err => Err(Box::new(err)),
}, },
|_| Ok(()), |_| Ok(()),
) )
@ -876,7 +883,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_function"))] /// # #[cfg(not(feature = "no_function"))]
/// # { /// # {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
@ -913,21 +920,22 @@ impl Engine {
ast: &AST, ast: &AST,
name: &str, name: &str,
args: A, args: A,
) -> Result<T, EvalAltResult> { ) -> Result<T, Box<EvalAltResult>> {
let mut arg_values = args.into_vec(); let mut arg_values = args.into_vec();
let mut args: Vec<_> = arg_values.iter_mut().collect(); let mut args: Vec<_> = arg_values.iter_mut().collect();
let fn_lib = Some(ast.1.as_ref()); let fn_lib = Some(ast.1.as_ref());
let pos = Position::none(); let pos = Position::none();
let result = self let result = self.call_fn_raw(Some(scope), fn_lib, name, &mut args, None, pos, 0)?;
.call_fn_raw(Some(scope), fn_lib, name, &mut args, None, pos, 0)
.map_err(|err| *err)?;
let return_type = self.map_type_name(result.type_name()); let return_type = self.map_type_name(result.type_name());
return result return result.try_cast().ok_or_else(|| {
.try_cast() Box::new(EvalAltResult::ErrorMismatchOutputType(
.ok_or_else(|| EvalAltResult::ErrorMismatchOutputType(return_type.into(), pos)); return_type.into(),
pos,
))
});
} }
/// Optimize the `AST` with constants defined in an external Scope. /// Optimize the `AST` with constants defined in an external Scope.
@ -961,7 +969,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::sync::RwLock; /// # use std::sync::RwLock;
/// # use std::sync::Arc; /// # use std::sync::Arc;
/// use rhai::Engine; /// use rhai::Engine;
@ -989,7 +997,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::sync::RwLock; /// # use std::sync::RwLock;
/// # use std::sync::Arc; /// # use std::sync::Arc;
/// use rhai::Engine; /// use rhai::Engine;
@ -1046,7 +1054,7 @@ impl Engine {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::sync::RwLock; /// # use std::sync::RwLock;
/// # use std::sync::Arc; /// # use std::sync::Arc;
/// use rhai::Engine; /// use rhai::Engine;

View File

@ -205,7 +205,7 @@ impl DerefMut for FunctionsLib {
/// Rhai main scripting engine. /// Rhai main scripting engine.
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine; /// use rhai::Engine;
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
@ -1383,13 +1383,11 @@ impl Engine {
// Compile the script text // Compile the script text
// No optimizations because we only run it once // No optimizations because we only run it once
let mut ast = self let mut ast = self.compile_with_scope_and_optimization_level(
.compile_with_scope_and_optimization_level( &Scope::new(),
&Scope::new(), script,
script, OptimizationLevel::None,
OptimizationLevel::None, )?;
)
.map_err(|err| EvalAltResult::ErrorParsing(Box::new(err)))?;
// 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.1.len() > 0 { if ast.1.len() > 0 {

View File

@ -21,18 +21,18 @@ pub trait Func<ARGS, RET> {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Func}; // use 'Func' for 'create_from_ast' /// use rhai::{Engine, Func}; // use 'Func' for 'create_from_ast'
/// ///
/// let engine = Engine::new(); // create a new 'Engine' just for this /// let engine = Engine::new(); // create a new 'Engine' just for this
/// ///
/// let ast = engine.compile("fn calc(x, y) { x + y.len() < 42 }")?; /// let ast = engine.compile("fn calc(x, y) { x + len(y) < 42 }")?;
/// ///
/// // Func takes two type parameters: /// // Func takes two type parameters:
/// // 1) a tuple made up of the types of the script function's parameters /// // 1) a tuple made up of the types of the script function's parameters
/// // 2) the return type of the script function /// // 2) the return type of the script function
/// // /// //
/// // 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, EvalAltResult>> and is callable! /// // 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, Box<EvalAltResult>>> and is callable!
/// let func = Func::<(i64, String), bool>::create_from_ast( /// let func = Func::<(i64, String), bool>::create_from_ast(
/// // ^^^^^^^^^^^^^ function parameter types in tuple /// // ^^^^^^^^^^^^^ function parameter types in tuple
/// ///
@ -52,18 +52,18 @@ pub trait Func<ARGS, RET> {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Func}; // use 'Func' for 'create_from_script' /// use rhai::{Engine, Func}; // use 'Func' for 'create_from_script'
/// ///
/// let engine = Engine::new(); // create a new 'Engine' just for this /// let engine = Engine::new(); // create a new 'Engine' just for this
/// ///
/// let script = "fn calc(x, y) { x + y.len() < 42 }"; /// let script = "fn calc(x, y) { x + len(y) < 42 }";
/// ///
/// // Func takes two type parameters: /// // Func takes two type parameters:
/// // 1) a tuple made up of the types of the script function's parameters /// // 1) a tuple made up of the types of the script function's parameters
/// // 2) the return type of the script function /// // 2) the return type of the script function
/// // /// //
/// // 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, EvalAltResult>> and is callable! /// // 'func' will have type Box<dyn Fn(i64, String) -> Result<bool, Box<EvalAltResult>>> and is callable!
/// let func = Func::<(i64, String), bool>::create_from_script( /// let func = Func::<(i64, String), bool>::create_from_script(
/// // ^^^^^^^^^^^^^ function parameter types in tuple /// // ^^^^^^^^^^^^^ function parameter types in tuple
/// ///
@ -80,7 +80,7 @@ pub trait Func<ARGS, RET> {
self, self,
script: &str, script: &str,
entry_point: &str, entry_point: &str,
) -> Result<Self::Output, ParseError>; ) -> Result<Self::Output, Box<ParseError>>;
} }
macro_rules! def_anonymous_fn { macro_rules! def_anonymous_fn {
@ -91,10 +91,10 @@ macro_rules! def_anonymous_fn {
impl<$($par: Variant + Clone,)* RET: Variant + Clone> Func<($($par,)*), RET> for Engine impl<$($par: Variant + Clone,)* RET: Variant + Clone> Func<($($par,)*), RET> for Engine
{ {
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
type Output = Box<dyn Fn($($par),*) -> Result<RET, EvalAltResult> + Send + Sync>; type Output = Box<dyn Fn($($par),*) -> Result<RET, Box<EvalAltResult>> + Send + Sync>;
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
type Output = Box<dyn Fn($($par),*) -> Result<RET, EvalAltResult>>; type Output = Box<dyn Fn($($par),*) -> Result<RET, Box<EvalAltResult>>>;
fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output { fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output {
let name = entry_point.to_string(); let name = entry_point.to_string();
@ -104,7 +104,7 @@ macro_rules! def_anonymous_fn {
}) })
} }
fn create_from_script(self, script: &str, entry_point: &str) -> Result<Self::Output, ParseError> { fn create_from_script(self, script: &str, entry_point: &str) -> Result<Self::Output, Box<ParseError>> {
let ast = self.compile(script)?; let ast = self.compile(script)?;
Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point)) Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point))
} }

View File

@ -16,7 +16,7 @@ pub trait RegisterFn<FN, ARGS, RET> {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, RegisterFn}; /// use rhai::{Engine, RegisterFn};
/// ///
/// // Normal function /// // Normal function
@ -48,7 +48,7 @@ pub trait RegisterDynamicFn<FN, ARGS> {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Dynamic, RegisterDynamicFn}; /// use rhai::{Engine, Dynamic, RegisterDynamicFn};
/// ///
/// // Function that returns a Dynamic value /// // Function that returns a Dynamic value
@ -68,7 +68,7 @@ pub trait RegisterDynamicFn<FN, ARGS> {
fn register_dynamic_fn(&mut self, name: &str, f: FN); fn register_dynamic_fn(&mut self, name: &str, f: FN);
} }
/// A trait to register fallible custom functions returning Result<_, EvalAltResult> with the `Engine`. /// A trait to register fallible custom functions returning `Result<_, Box<EvalAltResult>>` with the `Engine`.
pub trait RegisterResultFn<FN, ARGS, RET> { pub trait RegisterResultFn<FN, ARGS, RET> {
/// Register a custom fallible function with the `Engine`. /// Register a custom fallible function with the `Engine`.
/// ///
@ -78,9 +78,9 @@ pub trait RegisterResultFn<FN, ARGS, RET> {
/// use rhai::{Engine, RegisterResultFn, EvalAltResult}; /// use rhai::{Engine, RegisterResultFn, EvalAltResult};
/// ///
/// // Normal function /// // Normal function
/// fn div(x: i64, y: i64) -> Result<i64, EvalAltResult> { /// fn div(x: i64, y: i64) -> Result<i64, Box<EvalAltResult>> {
/// if y == 0 { /// if y == 0 {
/// // '.into()' automatically converts to 'EvalAltResult::ErrorRuntime' /// // '.into()' automatically converts to 'Box<EvalAltResult::ErrorRuntime>'
/// Err("division by zero!".into()) /// Err("division by zero!".into())
/// } else { /// } else {
/// Ok(x / y) /// Ok(x / y)
@ -180,10 +180,10 @@ pub fn map_identity(data: Dynamic, _pos: Position) -> Result<Dynamic, Box<EvalAl
Ok(data) Ok(data)
} }
/// To Result<Dynamic, EvalAltResult> mapping function. /// To `Result<Dynamic, Box<EvalAltResult>>` mapping function.
#[inline] #[inline]
pub fn map_result<T: Variant + Clone>( pub fn map_result<T: Variant + Clone>(
data: Result<T, EvalAltResult>, data: Result<T, Box<EvalAltResult>>,
pos: Position, pos: Position,
) -> Result<Dynamic, Box<EvalAltResult>> { ) -> Result<Dynamic, Box<EvalAltResult>> {
data.map(|v| v.into_dynamic()) data.map(|v| v.into_dynamic())
@ -241,9 +241,9 @@ macro_rules! def_register {
$($par: Variant + Clone,)* $($par: Variant + Clone,)*
#[cfg(feature = "sync")] #[cfg(feature = "sync")]
FN: Fn($($param),*) -> Result<RET, EvalAltResult> + Send + Sync + 'static, FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + Send + Sync + 'static,
#[cfg(not(feature = "sync"))] #[cfg(not(feature = "sync"))]
FN: Fn($($param),*) -> Result<RET, EvalAltResult> + 'static, FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + 'static,
RET: Variant + Clone RET: Variant + Clone
> RegisterResultFn<FN, ($($mark,)*), RET> for Engine > RegisterResultFn<FN, ($($mark,)*), RET> for Engine

View File

@ -23,7 +23,7 @@
//! ```,no_run //! ```,no_run
//! use rhai::{Engine, EvalAltResult, RegisterFn}; //! use rhai::{Engine, EvalAltResult, RegisterFn};
//! //!
//! fn main() -> Result<(), EvalAltResult> //! fn main() -> Result<(), Box<EvalAltResult>>
//! { //! {
//! // Define external function //! // Define external function
//! fn compute_something(x: i64) -> bool { //! fn compute_something(x: i64) -> bool {
@ -71,7 +71,7 @@ extern crate alloc;
mod any; mod any;
mod api; mod api;
mod builtin; //mod builtin;
mod engine; mod engine;
mod error; mod error;
mod fn_call; mod fn_call;

View File

@ -22,67 +22,73 @@ use crate::stdlib::{
}; };
// Checked add // Checked add
fn add<T: Display + CheckedAdd>(x: T, y: T) -> Result<T, EvalAltResult> { fn add<T: Display + CheckedAdd>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
x.checked_add(&y).ok_or_else(|| { x.checked_add(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Addition overflow: {} + {}", x, y), format!("Addition overflow: {} + {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Checked subtract // Checked subtract
fn sub<T: Display + CheckedSub>(x: T, y: T) -> Result<T, EvalAltResult> { fn sub<T: Display + CheckedSub>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
x.checked_sub(&y).ok_or_else(|| { x.checked_sub(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Subtraction underflow: {} - {}", x, y), format!("Subtraction underflow: {} - {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Checked multiply // Checked multiply
fn mul<T: Display + CheckedMul>(x: T, y: T) -> Result<T, EvalAltResult> { fn mul<T: Display + CheckedMul>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
x.checked_mul(&y).ok_or_else(|| { x.checked_mul(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Multiplication overflow: {} * {}", x, y), format!("Multiplication overflow: {} * {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Checked divide // Checked divide
fn div<T>(x: T, y: T) -> Result<T, EvalAltResult> fn div<T>(x: T, y: T) -> Result<T, Box<EvalAltResult>>
where where
T: Display + CheckedDiv + PartialEq + Zero, T: Display + CheckedDiv + PartialEq + Zero,
{ {
// Detect division by zero // Detect division by zero
if y == T::zero() { if y == T::zero() {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Division by zero: {} / {}", x, y), format!("Division by zero: {} / {}", x, y),
Position::none(), Position::none(),
)); )));
} }
x.checked_div(&y).ok_or_else(|| { x.checked_div(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Division overflow: {} / {}", x, y), format!("Division overflow: {} / {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Checked negative - e.g. -(i32::MIN) will overflow i32::MAX // Checked negative - e.g. -(i32::MIN) will overflow i32::MAX
fn neg<T: Display + CheckedNeg>(x: T) -> Result<T, EvalAltResult> { fn neg<T: Display + CheckedNeg>(x: T) -> Result<T, Box<EvalAltResult>> {
x.checked_neg().ok_or_else(|| { x.checked_neg().ok_or_else(|| {
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none()) Box::new(EvalAltResult::ErrorArithmetic(
format!("Negation overflow: -{}", x),
Position::none(),
))
}) })
} }
// Checked absolute // Checked absolute
fn abs<T: Display + CheckedNeg + PartialOrd + Zero>(x: T) -> Result<T, EvalAltResult> { fn abs<T: Display + CheckedNeg + PartialOrd + Zero>(x: T) -> Result<T, Box<EvalAltResult>> {
// FIX - We don't use Signed::abs() here because, contrary to documentation, it panics // FIX - We don't use Signed::abs() here because, contrary to documentation, it panics
// when the number is ::MIN instead of returning ::MIN itself. // when the number is ::MIN instead of returning ::MIN itself.
if x >= <T as Zero>::zero() { if x >= <T as Zero>::zero() {
Ok(x) Ok(x)
} else { } else {
x.checked_neg().ok_or_else(|| { x.checked_neg().ok_or_else(|| {
EvalAltResult::ErrorArithmetic(format!("Negation overflow: -{}", x), Position::none()) Box::new(EvalAltResult::ErrorArithmetic(
format!("Negation overflow: -{}", x),
Position::none(),
))
}) })
} }
} }
@ -129,37 +135,37 @@ fn binary_xor<T: BitXor>(x: T, y: T) -> <T as BitXor>::Output {
x ^ y x ^ y
} }
// Checked left-shift // Checked left-shift
fn shl<T: Display + CheckedShl>(x: T, y: INT) -> Result<T, EvalAltResult> { fn shl<T: Display + CheckedShl>(x: T, y: INT) -> Result<T, Box<EvalAltResult>> {
// Cannot shift by a negative number of bits // Cannot shift by a negative number of bits
if y < 0 { if y < 0 {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Left-shift by a negative number: {} << {}", x, y), format!("Left-shift by a negative number: {} << {}", x, y),
Position::none(), Position::none(),
)); )));
} }
CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| { CheckedShl::checked_shl(&x, y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Left-shift by too many bits: {} << {}", x, y), format!("Left-shift by too many bits: {} << {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Checked right-shift // Checked right-shift
fn shr<T: Display + CheckedShr>(x: T, y: INT) -> Result<T, EvalAltResult> { fn shr<T: Display + CheckedShr>(x: T, y: INT) -> Result<T, Box<EvalAltResult>> {
// Cannot shift by a negative number of bits // Cannot shift by a negative number of bits
if y < 0 { if y < 0 {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Right-shift by a negative number: {} >> {}", x, y), format!("Right-shift by a negative number: {} >> {}", x, y),
Position::none(), Position::none(),
)); )));
} }
CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| { CheckedShr::checked_shr(&x, y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Right-shift by too many bits: {} % {}", x, y), format!("Right-shift by too many bits: {} % {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Unchecked left-shift - may panic if shifting by a negative number of bits // Unchecked left-shift - may panic if shifting by a negative number of bits
@ -171,12 +177,12 @@ fn shr_u<T: Shr<T>>(x: T, y: T) -> <T as Shr<T>>::Output {
x.shr(y) x.shr(y)
} }
// Checked modulo // Checked modulo
fn modulo<T: Display + CheckedRem>(x: T, y: T) -> Result<T, EvalAltResult> { fn modulo<T: Display + CheckedRem>(x: T, y: T) -> Result<T, Box<EvalAltResult>> {
x.checked_rem(&y).ok_or_else(|| { x.checked_rem(&y).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Modulo division by zero or overflow: {} % {}", x, y), format!("Modulo division by zero or overflow: {} % {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
// Unchecked modulo - may panic if dividing by zero // Unchecked modulo - may panic if dividing by zero
@ -184,25 +190,25 @@ fn modulo_u<T: Rem>(x: T, y: T) -> <T as Rem>::Output {
x % y x % y
} }
// Checked power // Checked power
fn pow_i_i(x: INT, y: INT) -> Result<INT, EvalAltResult> { fn pow_i_i(x: INT, y: INT) -> Result<INT, Box<EvalAltResult>> {
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
{ {
if y > (u32::MAX as INT) { if y > (u32::MAX as INT) {
Err(EvalAltResult::ErrorArithmetic( Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer raised to too large an index: {} ~ {}", x, y), format!("Integer raised to too large an index: {} ~ {}", x, y),
Position::none(), Position::none(),
)) )))
} else if y < 0 { } else if y < 0 {
Err(EvalAltResult::ErrorArithmetic( Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y), format!("Integer raised to a negative index: {} ~ {}", x, y),
Position::none(), Position::none(),
)) )))
} else { } else {
x.checked_pow(y as u32).ok_or_else(|| { x.checked_pow(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Power overflow: {} ~ {}", x, y), format!("Power overflow: {} ~ {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
} }
@ -210,16 +216,16 @@ fn pow_i_i(x: INT, y: INT) -> Result<INT, EvalAltResult> {
#[cfg(feature = "only_i32")] #[cfg(feature = "only_i32")]
{ {
if y < 0 { if y < 0 {
Err(EvalAltResult::ErrorArithmetic( Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y), format!("Integer raised to a negative index: {} ~ {}", x, y),
Position::none(), Position::none(),
)) )))
} else { } else {
x.checked_pow(y as u32).ok_or_else(|| { x.checked_pow(y as u32).ok_or_else(|| {
EvalAltResult::ErrorArithmetic( Box::new(EvalAltResult::ErrorArithmetic(
format!("Power overflow: {} ~ {}", x, y), format!("Power overflow: {} ~ {}", x, y),
Position::none(), Position::none(),
) ))
}) })
} }
} }
@ -235,13 +241,13 @@ fn pow_f_f(x: FLOAT, y: FLOAT) -> FLOAT {
} }
// Checked power // Checked power
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
fn pow_f_i(x: FLOAT, y: INT) -> Result<FLOAT, EvalAltResult> { fn pow_f_i(x: FLOAT, y: INT) -> Result<FLOAT, Box<EvalAltResult>> {
// Raise to power that is larger than an i32 // Raise to power that is larger than an i32
if y > (i32::MAX as INT) { if y > (i32::MAX as INT) {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Number raised to too large an index: {} ~ {}", x, y), format!("Number raised to too large an index: {} ~ {}", x, y),
Position::none(), Position::none(),
)); )));
} }
Ok(x.powi(y as i32)) Ok(x.powi(y as i32))

View File

@ -1,7 +1,7 @@
use super::{reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut}; use super::{reg_binary, reg_binary_mut, reg_trinary_mut, reg_unary_mut};
use crate::def_package;
use crate::any::{Dynamic, Variant}; use crate::any::{Dynamic, Variant};
use crate::def_package;
use crate::engine::Array; use crate::engine::Array;
use crate::fn_register::{map_dynamic as map, map_identity as pass}; use crate::fn_register::{map_dynamic as map, map_identity as pass};
use crate::parser::INT; use crate::parser::INT;

View File

@ -1,7 +1,7 @@
use super::{reg_binary, reg_trinary, reg_unary_mut, PackageStore}; use super::{reg_binary, reg_trinary, reg_unary_mut, PackageStore};
use crate::def_package;
use crate::any::{Dynamic, Union, Variant}; use crate::any::{Dynamic, Union, Variant};
use crate::def_package;
use crate::engine::{Array, Map}; use crate::engine::{Array, Map};
use crate::fn_register::map_dynamic as map; use crate::fn_register::map_dynamic as map;
use crate::parser::INT; use crate::parser::INT;

View File

@ -1,7 +1,7 @@
use super::{reg_binary, reg_binary_mut, reg_unary_mut}; use super::{reg_binary, reg_binary_mut, reg_unary_mut};
use crate::def_package;
use crate::any::Dynamic; use crate::any::Dynamic;
use crate::def_package;
use crate::engine::Map; use crate::engine::Map;
use crate::fn_register::map_dynamic as map; use crate::fn_register::map_dynamic as map;
use crate::parser::INT; use crate::parser::INT;

View File

@ -95,10 +95,10 @@ def_package!(BasicMathPackage:"Basic mathematic functions.", lib, {
"to_int", "to_int",
|x: f32| { |x: f32| {
if x > (MAX_INT as f32) { if x > (MAX_INT as f32) {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x), format!("Integer overflow: to_int({})", x),
Position::none(), Position::none(),
)); )));
} }
Ok(x.trunc() as INT) Ok(x.trunc() as INT)
@ -110,10 +110,10 @@ def_package!(BasicMathPackage:"Basic mathematic functions.", lib, {
"to_int", "to_int",
|x: FLOAT| { |x: FLOAT| {
if x > (MAX_INT as FLOAT) { if x > (MAX_INT as FLOAT) {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x), format!("Integer overflow: to_int({})", x),
Position::none(), Position::none(),
)); )));
} }
Ok(x.trunc() as INT) Ok(x.trunc() as INT)

View File

@ -18,9 +18,11 @@ mod time_basic;
mod utils; mod utils;
pub use arithmetic::ArithmeticPackage; pub use arithmetic::ArithmeticPackage;
#[cfg(not(feature = "no_index"))]
pub use array_basic::BasicArrayPackage; pub use array_basic::BasicArrayPackage;
pub use iter_basic::BasicIteratorPackage; pub use iter_basic::BasicIteratorPackage;
pub use logic::LogicPackage; pub use logic::LogicPackage;
#[cfg(not(feature = "no_object"))]
pub use map_basic::BasicMapPackage; pub use map_basic::BasicMapPackage;
pub use math_basic::BasicMathPackage; pub use math_basic::BasicMathPackage;
pub use pkg_core::CorePackage; pub use pkg_core::CorePackage;

View File

@ -1,4 +1,6 @@
#[cfg(not(feature = "no_index"))]
use super::array_basic::BasicArrayPackage; use super::array_basic::BasicArrayPackage;
#[cfg(not(feature = "no_object"))]
use super::map_basic::BasicMapPackage; use super::map_basic::BasicMapPackage;
use super::math_basic::BasicMathPackage; use super::math_basic::BasicMathPackage;
use super::pkg_core::CorePackage; use super::pkg_core::CorePackage;

View File

@ -31,13 +31,13 @@ def_package!(BasicTimePackage:"Basic timing utilities.", lib, {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
{ {
if seconds > (MAX_INT as u64) { if seconds > (MAX_INT as u64) {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!( format!(
"Integer overflow for timestamp duration: {}", "Integer overflow for timestamp duration: {}",
-(seconds as i64) -(seconds as i64)
), ),
Position::none(), Position::none(),
)); )));
} }
} }
return Ok(-(seconds as INT)); return Ok(-(seconds as INT));
@ -53,10 +53,10 @@ def_package!(BasicTimePackage:"Basic timing utilities.", lib, {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
{ {
if seconds > (MAX_INT as u64) { if seconds > (MAX_INT as u64) {
return Err(EvalAltResult::ErrorArithmetic( return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer overflow for timestamp duration: {}", seconds), format!("Integer overflow for timestamp duration: {}", seconds),
Position::none(), Position::none(),
)); )));
} }
} }
return Ok(seconds as INT); return Ok(seconds as INT);

View File

@ -72,7 +72,7 @@ impl AST {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_function"))] /// # #[cfg(not(feature = "no_function"))]
/// # { /// # {
/// use rhai::Engine; /// use rhai::Engine;

View File

@ -228,20 +228,23 @@ impl fmt::Display for EvalAltResult {
} }
} }
impl From<ParseError> for EvalAltResult { impl From<ParseError> for Box<EvalAltResult> {
fn from(err: ParseError) -> Self { fn from(err: ParseError) -> Self {
Self::ErrorParsing(Box::new(err)) Box::new(EvalAltResult::ErrorParsing(Box::new(err)))
} }
} }
impl From<Box<ParseError>> for EvalAltResult { impl From<Box<ParseError>> for Box<EvalAltResult> {
fn from(err: Box<ParseError>) -> Self { fn from(err: Box<ParseError>) -> Self {
Self::ErrorParsing(err) Box::new(EvalAltResult::ErrorParsing(err))
} }
} }
impl<T: AsRef<str>> From<T> for EvalAltResult { impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
fn from(err: T) -> Self { fn from(err: T) -> Self {
Self::ErrorRuntime(err.as_ref().to_string(), Position::none()) Box::new(EvalAltResult::ErrorRuntime(
err.as_ref().to_string(),
Position::none(),
))
} }
} }

View File

@ -42,7 +42,7 @@ pub(crate) struct EntryRef<'a> {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> { /// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope}; /// use rhai::{Engine, Scope};
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();

View File

@ -2,7 +2,7 @@
use rhai::{Array, Engine, EvalAltResult, RegisterFn, INT}; use rhai::{Array, Engine, EvalAltResult, RegisterFn, INT};
#[test] #[test]
fn test_arrays() -> Result<(), EvalAltResult> { fn test_arrays() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = [1, 2, 3]; x[1]")?, 2); assert_eq!(engine.eval::<INT>("let x = [1, 2, 3]; x[1]")?, 2);
@ -58,7 +58,7 @@ fn test_arrays() -> Result<(), EvalAltResult> {
#[test] #[test]
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
fn test_array_with_structs() -> Result<(), EvalAltResult> { fn test_array_with_structs() -> Result<(), Box<EvalAltResult>> {
#[derive(Clone)] #[derive(Clone)]
struct TestStruct { struct TestStruct {
x: INT, x: INT,

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_binary_ops() -> Result<(), EvalAltResult> { fn test_binary_ops() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("10 % 4")?, 2); assert_eq!(engine.eval::<INT>("10 % 4")?, 2);

View File

@ -1,14 +1,14 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_left_shift() -> Result<(), EvalAltResult> { fn test_left_shift() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("4 << 2")?, 16); assert_eq!(engine.eval::<INT>("4 << 2")?, 16);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_right_shift() -> Result<(), EvalAltResult> { fn test_right_shift() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("9 >> 1")?, 4); assert_eq!(engine.eval::<INT>("9 >> 1")?, 4);
Ok(()) Ok(())

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
#[test] #[test]
fn test_bool_op1() -> Result<(), EvalAltResult> { fn test_bool_op1() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<bool>("true && (false || true)")?, true); assert_eq!(engine.eval::<bool>("true && (false || true)")?, true);
@ -11,7 +11,7 @@ fn test_bool_op1() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_bool_op2() -> Result<(), EvalAltResult> { fn test_bool_op2() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<bool>("false && (false || true)")?, false); assert_eq!(engine.eval::<bool>("false && (false || true)")?, false);
@ -21,7 +21,7 @@ fn test_bool_op2() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_bool_op3() -> Result<(), EvalAltResult> { fn test_bool_op3() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert!(engine.eval::<bool>("true && (false || 123)").is_err()); assert!(engine.eval::<bool>("true && (false || 123)").is_err());
@ -33,7 +33,7 @@ fn test_bool_op3() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_bool_op_short_circuit() -> Result<(), EvalAltResult> { fn test_bool_op_short_circuit() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -2,7 +2,7 @@
use rhai::{Engine, EvalAltResult, Func, ParseErrorType, Scope, INT}; use rhai::{Engine, EvalAltResult, Func, ParseErrorType, Scope, INT};
#[test] #[test]
fn test_fn() -> Result<(), EvalAltResult> { fn test_fn() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
// Expect duplicated parameters error // Expect duplicated parameters error
@ -19,7 +19,7 @@ fn test_fn() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_call_fn() -> Result<(), EvalAltResult> { fn test_call_fn() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();
@ -61,7 +61,7 @@ fn test_call_fn() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_anonymous_fn() -> Result<(), EvalAltResult> { fn test_anonymous_fn() -> Result<(), Box<EvalAltResult>> {
let calc_func = Func::<(INT, INT, INT), INT>::create_from_script( let calc_func = Func::<(INT, INT, INT), INT>::create_from_script(
Engine::new(), Engine::new(),
"fn calc(x, y, z) { (x + y) * z }", "fn calc(x, y, z) { (x + y) * z }",

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
#[test] #[test]
fn test_chars() -> Result<(), EvalAltResult> { fn test_chars() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<char>("'y'")?, 'y'); assert_eq!(engine.eval::<char>("'y'")?, 'y');

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_or_equals() -> Result<(), EvalAltResult> { fn test_or_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 16; x |= 74; x")?, 90); assert_eq!(engine.eval::<INT>("let x = 16; x |= 74; x")?, 90);
@ -12,7 +12,7 @@ fn test_or_equals() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_and_equals() -> Result<(), EvalAltResult> { fn test_and_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 16; x &= 31; x")?, 16); assert_eq!(engine.eval::<INT>("let x = 16; x &= 31; x")?, 16);
@ -24,42 +24,42 @@ fn test_and_equals() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_xor_equals() -> Result<(), EvalAltResult> { fn test_xor_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 90; x ^= 12; x")?, 86); assert_eq!(engine.eval::<INT>("let x = 90; x ^= 12; x")?, 86);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_multiply_equals() -> Result<(), EvalAltResult> { fn test_multiply_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 2; x *= 3; x")?, 6); assert_eq!(engine.eval::<INT>("let x = 2; x *= 3; x")?, 6);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_divide_equals() -> Result<(), EvalAltResult> { fn test_divide_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 6; x /= 2; x")?, 3); assert_eq!(engine.eval::<INT>("let x = 6; x /= 2; x")?, 3);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_left_shift_equals() -> Result<(), EvalAltResult> { fn test_left_shift_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 9; x >>=1; x")?, 4); assert_eq!(engine.eval::<INT>("let x = 9; x >>=1; x")?, 4);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_right_shift_equals() -> Result<(), EvalAltResult> { fn test_right_shift_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 4; x<<= 2; x")?, 16); assert_eq!(engine.eval::<INT>("let x = 4; x<<= 2; x")?, 16);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_modulo_equals() -> Result<(), EvalAltResult> { fn test_modulo_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 10; x %= 4; x")?, 2); assert_eq!(engine.eval::<INT>("let x = 10; x %= 4; x")?, 2);
Ok(()) Ok(())

View File

@ -1,21 +1,21 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_constant() -> Result<(), EvalAltResult> { fn test_constant() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("const x = 123; x")?, 123); assert_eq!(engine.eval::<INT>("const x = 123; x")?, 123);
assert!( assert!(matches!(
matches!(engine.eval::<INT>("const x = 123; x = 42;").expect_err("expects error"), *engine.eval::<INT>("const x = 123; x = 42;").expect_err("expects error"),
EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x") EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x"
); ));
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
assert!( assert!(matches!(
matches!(engine.eval::<INT>("const x = [1, 2, 3, 4, 5]; x[2] = 42;").expect_err("expects error"), *engine.eval::<INT>("const x = [1, 2, 3, 4, 5]; x[2] = 42;").expect_err("expects error"),
EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x") EvalAltResult::ErrorAssignmentToConstant(var, _) if var == "x"
); ));
Ok(()) Ok(())
} }

View File

@ -1,14 +1,15 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_decrement() -> Result<(), EvalAltResult> { fn test_decrement() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 10; x -= 7; x")?, 3); assert_eq!(engine.eval::<INT>("let x = 10; x -= 7; x")?, 3);
assert!(matches!(engine assert!(matches!(
.eval::<String>(r#"let s = "test"; s -= "ing"; s"#) *engine.eval::<String>(r#"let s = "test"; s -= "ing"; s"#).expect_err("expects error"),
.expect_err("expects error"), EvalAltResult::ErrorFunctionNotFound(err, _) if err == "- (string, string)")); EvalAltResult::ErrorFunctionNotFound(err, _) if err == "- (string, string)"
));
Ok(()) Ok(())
} }

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, Scope, INT}; use rhai::{Engine, EvalAltResult, Scope, INT};
#[test] #[test]
fn test_eval() -> Result<(), EvalAltResult> { fn test_eval() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -18,7 +18,7 @@ fn test_eval() -> Result<(), EvalAltResult> {
#[test] #[test]
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
fn test_eval_function() -> Result<(), EvalAltResult> { fn test_eval_function() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();
@ -61,7 +61,7 @@ fn test_eval_function() -> Result<(), EvalAltResult> {
#[test] #[test]
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
fn test_eval_override() -> Result<(), EvalAltResult> { fn test_eval_override() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, Scope, INT}; use rhai::{Engine, EvalAltResult, Scope, INT};
#[test] #[test]
fn test_expressions() -> Result<(), EvalAltResult> { fn test_expressions() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();
@ -28,7 +28,7 @@ fn test_expressions() -> Result<(), EvalAltResult> {
/// This example taken from https://github.com/jonathandturner/rhai/issues/115 /// This example taken from https://github.com/jonathandturner/rhai/issues/115
#[test] #[test]
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
fn test_expressions_eval() -> Result<(), EvalAltResult> { fn test_expressions_eval() -> Result<(), Box<EvalAltResult>> {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct AGENT { struct AGENT {
pub gender: String, pub gender: String,

View File

@ -4,7 +4,7 @@ use rhai::{Engine, EvalAltResult, RegisterFn, FLOAT};
const EPSILON: FLOAT = 0.000_000_000_1; const EPSILON: FLOAT = 0.000_000_000_1;
#[test] #[test]
fn test_float() -> Result<(), EvalAltResult> { fn test_float() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -22,7 +22,7 @@ fn test_float() -> Result<(), EvalAltResult> {
#[test] #[test]
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
fn struct_with_float() -> Result<(), EvalAltResult> { fn struct_with_float() -> Result<(), Box<EvalAltResult>> {
#[derive(Clone)] #[derive(Clone)]
struct TestStruct { struct TestStruct {
x: f64, x: f64,

View File

@ -2,7 +2,7 @@ use rhai::{Engine, EvalAltResult, INT};
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
#[test] #[test]
fn test_for_array() -> Result<(), EvalAltResult> { fn test_for_array() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let script = r" let script = r"
@ -32,7 +32,7 @@ fn test_for_array() -> Result<(), EvalAltResult> {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
#[test] #[test]
fn test_for_object() -> Result<(), EvalAltResult> { fn test_for_object() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let script = r#" let script = r#"

View File

@ -3,7 +3,7 @@
use rhai::{Engine, EvalAltResult, RegisterFn, INT}; use rhai::{Engine, EvalAltResult, RegisterFn, INT};
#[test] #[test]
fn test_get_set() -> Result<(), EvalAltResult> { fn test_get_set() -> Result<(), Box<EvalAltResult>> {
#[derive(Clone)] #[derive(Clone)]
struct TestStruct { struct TestStruct {
x: INT, x: INT,
@ -36,7 +36,7 @@ fn test_get_set() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_big_get_set() -> Result<(), EvalAltResult> { fn test_big_get_set() -> Result<(), Box<EvalAltResult>> {
#[derive(Clone)] #[derive(Clone)]
struct TestChild { struct TestChild {
x: INT, x: INT,

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_if() -> Result<(), EvalAltResult> { fn test_if() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("if true { 55 }")?, 55); assert_eq!(engine.eval::<INT>("if true { 55 }")?, 55);
@ -29,7 +29,7 @@ fn test_if() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_if_expr() -> Result<(), EvalAltResult> { fn test_if_expr() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_increment() -> Result<(), EvalAltResult> { fn test_increment() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 1; x += 2; x")?, 3); assert_eq!(engine.eval::<INT>("let x = 1; x += 2; x")?, 3);

View File

@ -3,7 +3,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_internal_fn() -> Result<(), EvalAltResult> { fn test_internal_fn() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -16,7 +16,7 @@ fn test_internal_fn() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_big_internal_fn() -> Result<(), EvalAltResult> { fn test_big_internal_fn() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -35,7 +35,7 @@ fn test_big_internal_fn() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_internal_fn_overloading() -> Result<(), EvalAltResult> { fn test_internal_fn_overloading() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_loop() -> Result<(), EvalAltResult> { fn test_loop() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -3,7 +3,7 @@
use rhai::{Engine, EvalAltResult, Map, Scope, INT}; use rhai::{Engine, EvalAltResult, Map, Scope, INT};
#[test] #[test]
fn test_map_indexing() -> Result<(), EvalAltResult> { fn test_map_indexing() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -81,7 +81,7 @@ fn test_map_indexing() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_map_assign() -> Result<(), EvalAltResult> { fn test_map_assign() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let x = engine.eval::<Map>(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?; let x = engine.eval::<Map>(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?;
@ -112,7 +112,7 @@ fn test_map_assign() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_map_return() -> Result<(), EvalAltResult> { fn test_map_return() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?; let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?;
@ -143,7 +143,7 @@ fn test_map_return() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_map_for() -> Result<(), EvalAltResult> { fn test_map_for() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -170,7 +170,7 @@ fn test_map_for() -> Result<(), EvalAltResult> {
#[test] #[test]
/// Because a Rhai object map literal is almost the same as JSON, /// Because a Rhai object map literal is almost the same as JSON,
/// it is possible to convert from JSON into a Rhai object map. /// it is possible to convert from JSON into a Rhai object map.
fn test_map_json() -> Result<(), EvalAltResult> { fn test_map_json() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let json = r#"{"a":1, "b":true, "c":42, "$d e f!":"hello", "z":null}"#; let json = r#"{"a":1, "b":true, "c":42, "$d e f!":"hello", "z":null}"#;

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_math() -> Result<(), EvalAltResult> { fn test_math() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("1 + 2")?, 3); assert_eq!(engine.eval::<INT>("1 + 2")?, 3);
@ -25,37 +25,37 @@ fn test_math() -> Result<(), EvalAltResult> {
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
{ {
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("abs(-9223372036854775808)") .eval::<INT>("abs(-9223372036854775808)")
.expect_err("expects negation overflow"), .expect_err("expects negation overflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("9223372036854775807 + 1") .eval::<INT>("9223372036854775807 + 1")
.expect_err("expects overflow"), .expect_err("expects overflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("-9223372036854775808 - 1") .eval::<INT>("-9223372036854775808 - 1")
.expect_err("expects underflow"), .expect_err("expects underflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("9223372036854775807 * 9223372036854775807") .eval::<INT>("9223372036854775807 * 9223372036854775807")
.expect_err("expects overflow"), .expect_err("expects overflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("9223372036854775807 / 0") .eval::<INT>("9223372036854775807 / 0")
.expect_err("expects division by zero"), .expect_err("expects division by zero"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("9223372036854775807 % 0") .eval::<INT>("9223372036854775807 % 0")
.expect_err("expects division by zero"), .expect_err("expects division by zero"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
@ -65,31 +65,31 @@ fn test_math() -> Result<(), EvalAltResult> {
#[cfg(feature = "only_i32")] #[cfg(feature = "only_i32")]
{ {
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("2147483647 + 1") .eval::<INT>("2147483647 + 1")
.expect_err("expects overflow"), .expect_err("expects overflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("-2147483648 - 1") .eval::<INT>("-2147483648 - 1")
.expect_err("expects underflow"), .expect_err("expects underflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("2147483647 * 2147483647") .eval::<INT>("2147483647 * 2147483647")
.expect_err("expects overflow"), .expect_err("expects overflow"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("2147483647 / 0") .eval::<INT>("2147483647 / 0")
.expect_err("expects division by zero"), .expect_err("expects division by zero"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)
)); ));
assert!(matches!( assert!(matches!(
engine *engine
.eval::<INT>("2147483647 % 0") .eval::<INT>("2147483647 % 0")
.expect_err("expects division by zero"), .expect_err("expects division by zero"),
EvalAltResult::ErrorArithmetic(_, _) EvalAltResult::ErrorArithmetic(_, _)

View File

@ -3,7 +3,7 @@
use rhai::{Engine, EvalAltResult, RegisterFn, INT}; use rhai::{Engine, EvalAltResult, RegisterFn, INT};
#[test] #[test]
fn test_method_call() -> Result<(), EvalAltResult> { fn test_method_call() -> Result<(), Box<EvalAltResult>> {
#[derive(Debug, Clone, Eq, PartialEq)] #[derive(Debug, Clone, Eq, PartialEq)]
struct TestStruct { struct TestStruct {
x: INT, x: INT,

View File

@ -4,10 +4,10 @@ use rhai::{Engine, EvalAltResult, RegisterFn, INT};
fn test_mismatched_op() { fn test_mismatched_op() {
let engine = Engine::new(); let engine = Engine::new();
assert!( assert!(matches!(
matches!(engine.eval::<INT>(r#""hello, " + "world!""#).expect_err("expects error"), *engine.eval::<INT>(r#""hello, " + "world!""#).expect_err("expects error"),
EvalAltResult::ErrorMismatchOutputType(err, _) if err == "string") EvalAltResult::ErrorMismatchOutputType(err, _) if err == "string"
); ));
} }
#[test] #[test]
@ -33,12 +33,14 @@ fn test_mismatched_op_custom_type() {
.expect_err("expects error"); .expect_err("expects error");
#[cfg(feature = "only_i32")] #[cfg(feature = "only_i32")]
assert!( assert!(matches!(
matches!(r, EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i32, TestStruct)") *r,
); EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i32, TestStruct)"
));
#[cfg(not(feature = "only_i32"))] #[cfg(not(feature = "only_i32"))]
assert!( assert!(matches!(
matches!(r, EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i64, TestStruct)") *r,
); EvalAltResult::ErrorFunctionNotFound(err, _) if err == "+ (i64, TestStruct)"
));
} }

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
#[test] #[test]
fn test_not() -> Result<(), EvalAltResult> { fn test_not() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_number_literal() -> Result<(), EvalAltResult> { fn test_number_literal() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("65")?, 65); assert_eq!(engine.eval::<INT>("65")?, 65);
@ -10,7 +10,7 @@ fn test_number_literal() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_hex_literal() -> Result<(), EvalAltResult> { fn test_hex_literal() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 0xf; x")?, 15); assert_eq!(engine.eval::<INT>("let x = 0xf; x")?, 15);
@ -20,7 +20,7 @@ fn test_hex_literal() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_octal_literal() -> Result<(), EvalAltResult> { fn test_octal_literal() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 0o77; x")?, 63); assert_eq!(engine.eval::<INT>("let x = 0o77; x")?, 63);
@ -30,7 +30,7 @@ fn test_octal_literal() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_binary_literal() -> Result<(), EvalAltResult> { fn test_binary_literal() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 0b1111; x")?, 15); assert_eq!(engine.eval::<INT>("let x = 0b1111; x")?, 15);

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_ops() -> Result<(), EvalAltResult> { fn test_ops() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("60 + 5")?, 65); assert_eq!(engine.eval::<INT>("60 + 5")?, 65);
@ -11,7 +11,7 @@ fn test_ops() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_op_precedence() -> Result<(), EvalAltResult> { fn test_op_precedence() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -3,8 +3,8 @@
use rhai::{Engine, EvalAltResult, OptimizationLevel, INT}; use rhai::{Engine, EvalAltResult, OptimizationLevel, INT};
#[test] #[test]
fn test_optimizer() -> Result<(), EvalAltResult> { fn test_optimizer() -> Result<(), Box<EvalAltResult>> {
fn run_test(engine: &mut Engine) -> Result<(), EvalAltResult> { fn run_test(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
assert_eq!(engine.eval::<INT>(r"if true { 42 } else { 123 }")?, 42); assert_eq!(engine.eval::<INT>(r"if true { 42 } else { 123 }")?, 42);
assert_eq!( assert_eq!(
engine.eval::<INT>(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?, engine.eval::<INT>(r"if 1 == 1 || 2 > 3 { 42 } else { 123 }")?,

View File

@ -7,7 +7,7 @@ use rhai::FLOAT;
const EPSILON: FLOAT = 0.000_000_000_1; const EPSILON: FLOAT = 0.000_000_000_1;
#[test] #[test]
fn test_power_of() -> Result<(), EvalAltResult> { fn test_power_of() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("2 ~ 3")?, 8); assert_eq!(engine.eval::<INT>("2 ~ 3")?, 8);
@ -28,7 +28,7 @@ fn test_power_of() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_power_of_equals() -> Result<(), EvalAltResult> { fn test_power_of_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 2; x ~= 3; x")?, 8); assert_eq!(engine.eval::<INT>("let x = 2; x ~= 3; x")?, 8);

View File

@ -40,7 +40,7 @@ impl CommandWrapper {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
#[test] #[test]
fn test_side_effects_command() -> Result<(), EvalAltResult> { fn test_side_effects_command() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();
@ -80,7 +80,7 @@ fn test_side_effects_command() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_side_effects_print() -> Result<(), EvalAltResult> { fn test_side_effects_print() -> Result<(), Box<EvalAltResult>> {
use std::sync::Arc; use std::sync::Arc;
use std::sync::RwLock; use std::sync::RwLock;

View File

@ -2,7 +2,7 @@
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
#[test] #[test]
fn test_stack_overflow() -> Result<(), EvalAltResult> { fn test_stack_overflow() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -22,8 +22,10 @@ fn test_stack_overflow() -> Result<(), EvalAltResult> {
", ",
) { ) {
Ok(_) => panic!("should be stack overflow"), Ok(_) => panic!("should be stack overflow"),
Err(EvalAltResult::ErrorStackOverflow(_)) => (), Err(err) => match *err {
Err(_) => panic!("should be stack overflow"), EvalAltResult::ErrorStackOverflow(_) => (),
_ => panic!("should be stack overflow"),
},
} }
Ok(()) Ok(())

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_string() -> Result<(), EvalAltResult> { fn test_string() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(
@ -37,7 +37,7 @@ fn test_string() -> Result<(), EvalAltResult> {
#[cfg(not(feature = "no_stdlib"))] #[cfg(not(feature = "no_stdlib"))]
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
#[test] #[test]
fn test_string_substring() -> Result<(), EvalAltResult> { fn test_string_substring() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(

View File

@ -5,10 +5,12 @@ fn test_throw() {
let engine = Engine::new(); let engine = Engine::new();
assert!(matches!( assert!(matches!(
engine.eval::<()>(r#"if true { throw "hello" }"#).expect_err("expects error"), *engine.eval::<()>(r#"if true { throw "hello" }"#).expect_err("expects error"),
EvalAltResult::ErrorRuntime(s, _) if s == "hello")); EvalAltResult::ErrorRuntime(s, _) if s == "hello"
));
assert!(matches!( assert!(matches!(
engine.eval::<()>(r#"throw"#).expect_err("expects error"), *engine.eval::<()>(r#"throw"#).expect_err("expects error"),
EvalAltResult::ErrorRuntime(s, _) if s == "")); EvalAltResult::ErrorRuntime(s, _) if s == ""
));
} }

View File

@ -7,7 +7,7 @@ use rhai::{Engine, EvalAltResult, INT};
use rhai::FLOAT; use rhai::FLOAT;
#[test] #[test]
fn test_timestamp() -> Result<(), EvalAltResult> { fn test_timestamp() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<String>("type_of(timestamp())")?, "timestamp"); assert_eq!(engine.eval::<String>("type_of(timestamp())")?, "timestamp");

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, RegisterFn, INT}; use rhai::{Engine, EvalAltResult, RegisterFn, INT};
#[test] #[test]
fn test_type_of() -> Result<(), EvalAltResult> { fn test_type_of() -> Result<(), Box<EvalAltResult>> {
#[derive(Clone)] #[derive(Clone)]
struct TestStruct { struct TestStruct {
x: INT, x: INT,

View File

@ -3,7 +3,7 @@ use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
// TODO also add test case for unary after compound // TODO also add test case for unary after compound
// Hah, turns out unary + has a good use after all! // Hah, turns out unary + has a good use after all!
fn test_unary_after_binary() -> Result<(), EvalAltResult> { fn test_unary_after_binary() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("10 % +4")?, 2); assert_eq!(engine.eval::<INT>("10 % +4")?, 2);

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_unary_minus() -> Result<(), EvalAltResult> { fn test_unary_minus() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = -5; x")?, -5); assert_eq!(engine.eval::<INT>("let x = -5; x")?, -5);

View File

@ -1,21 +1,21 @@
use rhai::{Engine, EvalAltResult}; use rhai::{Engine, EvalAltResult};
#[test] #[test]
fn test_unit() -> Result<(), EvalAltResult> { fn test_unit() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
engine.eval::<()>("let x = (); x")?; engine.eval::<()>("let x = (); x")?;
Ok(()) Ok(())
} }
#[test] #[test]
fn test_unit_eq() -> Result<(), EvalAltResult> { fn test_unit_eq() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!(engine.eval::<bool>("let x = (); let y = (); x == y")?, true); assert_eq!(engine.eval::<bool>("let x = (); let y = (); x == y")?, true);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_unit_with_spaces() -> Result<(), EvalAltResult> { fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
engine.eval::<()>("let x = ( ); x")?; engine.eval::<()>("let x = ( ); x")?;
Ok(()) Ok(())

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, Scope, INT}; use rhai::{Engine, EvalAltResult, Scope, INT};
#[test] #[test]
fn test_var_scope() -> Result<(), EvalAltResult> { fn test_var_scope() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
let mut scope = Scope::new(); let mut scope = Scope::new();
@ -20,7 +20,7 @@ fn test_var_scope() -> Result<(), EvalAltResult> {
} }
#[test] #[test]
fn test_scope_eval() -> Result<(), EvalAltResult> { fn test_scope_eval() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
// First create the state // First create the state

View File

@ -1,7 +1,7 @@
use rhai::{Engine, EvalAltResult, INT}; use rhai::{Engine, EvalAltResult, INT};
#[test] #[test]
fn test_while() -> Result<(), EvalAltResult> { fn test_while() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert_eq!(