From 01c35808cb46d2c11b4611220c85ca2cfd8ec8d2 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 25 Dec 2021 23:49:14 +0800 Subject: [PATCH] Use type alias --- src/api/call_fn.rs | 5 +- src/api/compile.rs | 30 +++--- src/api/deprecated.rs | 24 ++--- src/api/eval.rs | 19 ++-- src/api/events.rs | 4 +- src/api/files.rs | 19 ++-- src/api/register.rs | 20 ++-- src/api/run.rs | 18 +--- src/ast/expr.rs | 12 +-- src/engine.rs | 38 ++++---- src/func/builtin.rs | 17 +--- src/func/call.rs | 25 +++-- src/func/func.rs | 15 ++- src/func/native.rs | 16 ++-- src/func/plugin.rs | 2 +- src/func/register.rs | 18 ++-- src/func/script.rs | 6 +- src/lib.rs | 18 ++-- src/module/mod.rs | 56 ++++++----- src/module/resolvers/collection.rs | 4 +- src/module/resolvers/dummy.rs | 4 +- src/module/resolvers/file.rs | 9 +- src/module/resolvers/mod.rs | 6 +- src/module/resolvers/stat.rs | 5 +- src/packages/arithmetic.rs | 44 +++++---- src/packages/array_basic.rs | 98 ++++++++----------- src/packages/blob_basic.rs | 11 +-- src/packages/iter_basic.rs | 10 +- src/packages/lang_core.rs | 4 +- src/packages/logic.rs | 26 ++--- src/packages/map_basic.rs | 14 +-- src/packages/math_basic.rs | 40 ++++---- src/packages/string_more.rs | 6 +- src/packages/time_basic.rs | 45 +++------ src/parser.rs | 146 ++++++++++++++--------------- src/serde/de.rs | 140 +++++++++++---------------- src/serde/metadata.rs | 16 +--- src/serde/ser.rs | 134 ++++++++++++-------------- src/serde/str.rs | 74 +++++++-------- src/types/error.rs | 8 +- src/types/fn_ptr.rs | 28 +++--- src/types/parse_error.rs | 6 +- 42 files changed, 538 insertions(+), 702 deletions(-) diff --git a/src/api/call_fn.rs b/src/api/call_fn.rs index 6ac100b0..a78943ed 100644 --- a/src/api/call_fn.rs +++ b/src/api/call_fn.rs @@ -4,7 +4,8 @@ use crate::engine::{EvalState, Imports}; use crate::types::dynamic::Variant; use crate::{ - Dynamic, Engine, EvalAltResult, FuncArgs, Position, RhaiResult, Scope, StaticVec, AST, + Dynamic, Engine, EvalAltResult, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, + AST, }; use std::any::type_name; #[cfg(feature = "no_std")] @@ -60,7 +61,7 @@ impl Engine { ast: &AST, name: impl AsRef, args: impl FuncArgs, - ) -> Result> { + ) -> RhaiResultOf { let mut arg_values = StaticVec::new_const(); args.parse(&mut arg_values); diff --git a/src/api/compile.rs b/src/api/compile.rs index 9ca748cd..172e5db8 100644 --- a/src/api/compile.rs +++ b/src/api/compile.rs @@ -1,7 +1,7 @@ //! Module that defines the public compilation API of [`Engine`]. -use crate::parser::ParseState; -use crate::{Engine, ParseError, Scope, AST}; +use crate::parser::{ParseResult, ParseState}; +use crate::{Engine, RhaiResultOf, Scope, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -26,7 +26,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn compile(&self, script: impl AsRef) -> Result { + pub fn compile(&self, script: impl AsRef) -> ParseResult { self.compile_with_scope(&Scope::new(), script) } /// Compile a string into an [`AST`] using own scope, which can be used later for evaluation. @@ -67,11 +67,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn compile_with_scope( - &self, - scope: &Scope, - script: impl AsRef, - ) -> Result { + pub fn compile_with_scope(&self, scope: &Scope, script: impl AsRef) -> ParseResult { self.compile_scripts_with_scope(scope, &[script]) } /// Compile a string into an [`AST`] using own scope, which can be used later for evaluation, @@ -88,7 +84,7 @@ impl Engine { &self, scope: &Scope, script: impl AsRef, - ) -> Result> { + ) -> RhaiResultOf { use crate::{ ast::{ASTNode, Expr, Stmt}, func::native::shared_take_or_clone, @@ -201,7 +197,7 @@ impl Engine { &self, scope: &Scope, scripts: &[impl AsRef], - ) -> Result { + ) -> ParseResult { self.compile_with_scope_and_optimization_level( scope, scripts, @@ -222,7 +218,7 @@ impl Engine { scope: &Scope, scripts: &[impl AsRef], #[cfg(not(feature = "no_optimize"))] optimization_level: crate::OptimizationLevel, - ) -> Result { + ) -> ParseResult { let (stream, tokenizer_control) = self.lex_raw(scripts, self.token_mapper.as_ref().map(Box::as_ref)); let mut state = ParseState::new(self, tokenizer_control); @@ -255,7 +251,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn compile_expression(&self, script: impl AsRef) -> Result { + pub fn compile_expression(&self, script: impl AsRef) -> ParseResult { self.compile_expression_with_scope(&Scope::new(), script) } /// Compile a string containing an expression into an [`AST`] using own scope, @@ -295,7 +291,7 @@ impl Engine { &self, scope: &Scope, script: impl AsRef, - ) -> Result { + ) -> ParseResult { let scripts = [script]; let (stream, tokenizer_control) = self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); @@ -355,18 +351,14 @@ impl Engine { /// ``` #[cfg(not(feature = "no_object"))] #[inline(always)] - pub fn parse_json( - &self, - json: impl AsRef, - has_null: bool, - ) -> Result> { + pub fn parse_json(&self, json: impl AsRef, has_null: bool) -> RhaiResultOf { use crate::tokenizer::Token; fn parse_json_inner( engine: &Engine, json: &str, has_null: bool, - ) -> Result> { + ) -> RhaiResultOf { let mut scope = Scope::new(); let json_text = json.trim_start(); let scripts = if json_text.starts_with(Token::MapStart.literal_syntax()) { diff --git a/src/api/deprecated.rs b/src/api/deprecated.rs index 9dbc3b5f..6ef2573b 100644 --- a/src/api/deprecated.rs +++ b/src/api/deprecated.rs @@ -2,7 +2,7 @@ use crate::{ Dynamic, Engine, EvalAltResult, Expression, FnPtr, ImmutableString, NativeCallContext, - RhaiResult, Scope, AST, + RhaiResult, RhaiResultOf, Scope, AST, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -22,7 +22,7 @@ impl Engine { #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] #[inline(always)] - pub fn consume_file(&self, path: std::path::PathBuf) -> Result<(), Box> { + pub fn consume_file(&self, path: std::path::PathBuf) -> RhaiResultOf<()> { self.run_file(path) } @@ -44,7 +44,7 @@ impl Engine { &self, scope: &mut Scope, path: std::path::PathBuf, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { self.run_file_with_scope(scope, path) } @@ -58,7 +58,7 @@ impl Engine { /// This method will be removed in the next major version. #[deprecated(since = "1.1.0", note = "use `run` instead")] #[inline(always)] - pub fn consume(&self, script: &str) -> Result<(), Box> { + pub fn consume(&self, script: &str) -> RhaiResultOf<()> { self.run(script) } @@ -72,11 +72,7 @@ impl Engine { /// This method will be removed in the next major version. #[deprecated(since = "1.1.0", note = "use `run_with_scope` instead")] #[inline(always)] - pub fn consume_with_scope( - &self, - scope: &mut Scope, - script: &str, - ) -> Result<(), Box> { + pub fn consume_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> { self.run_with_scope(scope, script) } @@ -90,7 +86,7 @@ impl Engine { /// This method will be removed in the next major version. #[deprecated(since = "1.1.0", note = "use `run_ast` instead")] #[inline(always)] - pub fn consume_ast(&self, ast: &AST) -> Result<(), Box> { + pub fn consume_ast(&self, ast: &AST) -> RhaiResultOf<()> { self.run_ast(ast) } @@ -104,11 +100,7 @@ impl Engine { /// This method will be removed in the next major version. #[deprecated(since = "1.1.0", note = "use `run_ast_with_scope` instead")] #[inline(always)] - pub fn consume_ast_with_scope( - &self, - scope: &mut Scope, - ast: &AST, - ) -> Result<(), Box> { + pub fn consume_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> { self.run_ast_with_scope(scope, ast) } /// Call a script function defined in an [`AST`] with multiple [`Dynamic`] arguments @@ -258,7 +250,7 @@ impl NativeCallContext<'_> { #[allow(useless_deprecated)] #[deprecated(since = "1.2.0", note = "explicitly wrap `EvalAltResult` in `Err`")] -impl From for Result> { +impl From for RhaiResultOf { #[inline(always)] fn from(err: EvalAltResult) -> Self { Err(err.into()) diff --git a/src/api/eval.rs b/src/api/eval.rs index 6356c1e8..674e4da9 100644 --- a/src/api/eval.rs +++ b/src/api/eval.rs @@ -3,7 +3,9 @@ use crate::engine::{EvalState, Imports}; use crate::parser::ParseState; use crate::types::dynamic::Variant; -use crate::{Dynamic, Engine, EvalAltResult, Module, Position, RhaiResult, Scope, AST}; +use crate::{ + Dynamic, Engine, EvalAltResult, Module, Position, RhaiResult, RhaiResultOf, Scope, AST, +}; use std::any::type_name; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -24,7 +26,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn eval(&self, script: &str) -> Result> { + pub fn eval(&self, script: &str) -> RhaiResultOf { self.eval_with_scope(&mut Scope::new(), script) } /// Evaluate a string with own scope. @@ -60,7 +62,7 @@ impl Engine { &self, scope: &mut Scope, script: &str, - ) -> Result> { + ) -> RhaiResultOf { let ast = self.compile_with_scope_and_optimization_level( scope, &[script], @@ -84,10 +86,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn eval_expression( - &self, - script: &str, - ) -> Result> { + pub fn eval_expression(&self, script: &str) -> RhaiResultOf { self.eval_expression_with_scope(&mut Scope::new(), script) } /// Evaluate a string containing an expression with own scope. @@ -113,7 +112,7 @@ impl Engine { &self, scope: &mut Scope, script: &str, - ) -> Result> { + ) -> RhaiResultOf { let scripts = [script]; let (stream, tokenizer_control) = self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); @@ -149,7 +148,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn eval_ast(&self, ast: &AST) -> Result> { + pub fn eval_ast(&self, ast: &AST) -> RhaiResultOf { self.eval_ast_with_scope(&mut Scope::new(), ast) } /// Evaluate an [`AST`] with own scope. @@ -186,7 +185,7 @@ impl Engine { &self, scope: &mut Scope, ast: &AST, - ) -> Result> { + ) -> RhaiResultOf { let mods = &mut Imports::new(); let result = self.eval_ast_with_scope_raw(scope, mods, ast, 0)?; diff --git a/src/api/events.rs b/src/api/events.rs index 9f981836..e43d4e4a 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -2,7 +2,7 @@ use crate::engine::EvalContext; use crate::func::SendSync; -use crate::{Dynamic, Engine, EvalAltResult, Position}; +use crate::{Dynamic, Engine, Position, RhaiResultOf}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -58,7 +58,7 @@ impl Engine { #[inline(always)] pub fn on_var( &mut self, - callback: impl Fn(&str, usize, &EvalContext) -> Result, Box> + callback: impl Fn(&str, usize, &EvalContext) -> RhaiResultOf> + SendSync + 'static, ) -> &mut Self { diff --git a/src/api/files.rs b/src/api/files.rs index 785bffbc..1adea263 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -3,13 +3,13 @@ #![cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] use crate::types::dynamic::Variant; -use crate::{Engine, EvalAltResult, Scope, AST}; +use crate::{Engine, EvalAltResult, RhaiResultOf, Scope, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; impl Engine { /// Read the contents of a file into a string. - fn read_file(path: std::path::PathBuf) -> Result> { + fn read_file(path: std::path::PathBuf) -> RhaiResultOf { use std::io::Read; let mut f = std::fs::File::open(path.clone()).map_err(|err| { @@ -62,7 +62,7 @@ impl Engine { /// # } /// ``` #[inline(always)] - pub fn compile_file(&self, path: std::path::PathBuf) -> Result> { + pub fn compile_file(&self, path: std::path::PathBuf) -> RhaiResultOf { self.compile_file_with_scope(&Scope::new(), path) } /// Compile a script file into an [`AST`] using own scope, which can be used later for evaluation. @@ -103,7 +103,7 @@ impl Engine { &self, scope: &Scope, path: std::path::PathBuf, - ) -> Result> { + ) -> RhaiResultOf { Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?)) } /// Evaluate a script file. @@ -124,10 +124,7 @@ impl Engine { /// # } /// ``` #[inline] - pub fn eval_file( - &self, - path: std::path::PathBuf, - ) -> Result> { + pub fn eval_file(&self, path: std::path::PathBuf) -> RhaiResultOf { Self::read_file(path).and_then(|contents| self.eval::(&contents)) } /// Evaluate a script file with own scope. @@ -162,7 +159,7 @@ impl Engine { &self, scope: &mut Scope, path: std::path::PathBuf, - ) -> Result> { + ) -> RhaiResultOf { Self::read_file(path).and_then(|contents| self.eval_with_scope(scope, &contents)) } /// Evaluate a file, returning any error (if any). @@ -171,7 +168,7 @@ impl Engine { #[cfg(not(feature = "no_std"))] #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] #[inline] - pub fn run_file(&self, path: std::path::PathBuf) -> Result<(), Box> { + pub fn run_file(&self, path: std::path::PathBuf) -> RhaiResultOf<()> { Self::read_file(path).and_then(|contents| self.run(&contents)) } /// Evaluate a file with own scope, returning any error (if any). @@ -190,7 +187,7 @@ impl Engine { &self, scope: &mut Scope, path: std::path::PathBuf, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { Self::read_file(path).and_then(|contents| self.run_with_scope(scope, &contents)) } } diff --git a/src/api/register.rs b/src/api/register.rs index 32c929d7..66a85220 100644 --- a/src/api/register.rs +++ b/src/api/register.rs @@ -3,7 +3,7 @@ use crate::func::{FnCallArgs, RegisterNativeFunction, SendSync}; use crate::types::dynamic::Variant; use crate::{ - Engine, EvalAltResult, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, Shared, + Engine, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, RhaiResultOf, Shared, SmartString, }; use std::any::{type_name, TypeId}; @@ -113,7 +113,7 @@ impl Engine { pub fn register_result_fn(&mut self, name: N, func: F) -> &mut Self where N: AsRef + Into, - F: RegisterNativeFunction>>, + F: RegisterNativeFunction>, { let param_types = F::param_types(); @@ -166,9 +166,7 @@ impl Engine { &mut self, name: N, arg_types: &[TypeId], - func: impl Fn(NativeCallContext, &mut FnCallArgs) -> Result> - + SendSync - + 'static, + func: impl Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResultOf + SendSync + 'static, ) -> &mut Self where N: AsRef + Into, @@ -383,7 +381,7 @@ impl Engine { pub fn register_get_result( &mut self, name: impl AsRef, - get_fn: impl Fn(&mut T) -> Result> + SendSync + 'static, + get_fn: impl Fn(&mut T) -> RhaiResultOf + SendSync + 'static, ) -> &mut Self { self.register_result_fn(&crate::engine::make_getter(name), get_fn) } @@ -449,7 +447,7 @@ impl Engine { /// /// impl TestStruct { /// fn new() -> Self { Self { field: 1 } } - /// fn set_field(&mut self, new_val: i64) -> Result<(), Box> { + /// fn set_field(&mut self, new_val: i64) -> Result<(), Box> { /// self.field = new_val; /// Ok(()) /// } @@ -478,7 +476,7 @@ impl Engine { pub fn register_set_result( &mut self, name: impl AsRef, - set_fn: impl Fn(&mut T, V) -> Result<(), Box> + SendSync + 'static, + set_fn: impl Fn(&mut T, V) -> RhaiResultOf<()> + SendSync + 'static, ) -> &mut Self { self.register_result_fn(&crate::engine::make_setter(name), set_fn) } @@ -657,7 +655,7 @@ impl Engine { V: Variant + Clone, >( &mut self, - get_fn: impl Fn(&mut T, X) -> Result> + SendSync + 'static, + get_fn: impl Fn(&mut T, X) -> RhaiResultOf + SendSync + 'static, ) -> &mut Self { #[cfg(not(feature = "no_index"))] if TypeId::of::() == TypeId::of::() { @@ -772,7 +770,7 @@ impl Engine { /// /// impl TestStruct { /// fn new() -> Self { Self { fields: vec![1, 2, 3, 4, 5] } } - /// fn set_field(&mut self, index: i64, value: i64) -> Result<(), Box> { + /// fn set_field(&mut self, index: i64, value: i64) -> Result<(), Box> { /// self.fields[index as usize] = value; /// Ok(()) /// } @@ -806,7 +804,7 @@ impl Engine { V: Variant + Clone, >( &mut self, - set_fn: impl Fn(&mut T, X, V) -> Result<(), Box> + SendSync + 'static, + set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + SendSync + 'static, ) -> &mut Self { #[cfg(not(feature = "no_index"))] if TypeId::of::() == TypeId::of::() { diff --git a/src/api/run.rs b/src/api/run.rs index 84e2222d..08805846 100644 --- a/src/api/run.rs +++ b/src/api/run.rs @@ -2,14 +2,14 @@ use crate::engine::{EvalState, Imports}; use crate::parser::ParseState; -use crate::{Engine, EvalAltResult, Module, Scope, AST}; +use crate::{Engine, Module, RhaiResultOf, Scope, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; impl Engine { /// Evaluate a script, returning any error (if any). #[inline(always)] - pub fn run(&self, script: &str) -> Result<(), Box> { + pub fn run(&self, script: &str) -> RhaiResultOf<()> { self.run_with_scope(&mut Scope::new(), script) } /// Evaluate a script with own scope, returning any error (if any). @@ -20,11 +20,7 @@ impl Engine { /// the scope are propagated throughout the script _including_ functions. This allows functions /// to be optimized based on dynamic global constants. #[inline] - pub fn run_with_scope( - &self, - scope: &mut Scope, - script: &str, - ) -> Result<(), Box> { + pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> { let scripts = [script]; let (stream, tokenizer_control) = self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); @@ -42,16 +38,12 @@ impl Engine { } /// Evaluate an [`AST`], returning any error (if any). #[inline(always)] - pub fn run_ast(&self, ast: &AST) -> Result<(), Box> { + pub fn run_ast(&self, ast: &AST) -> RhaiResultOf<()> { self.run_ast_with_scope(&mut Scope::new(), ast) } /// Evaluate an [`AST`] with own scope, returning any error (if any). #[inline] - pub fn run_ast_with_scope( - &self, - scope: &mut Scope, - ast: &AST, - ) -> Result<(), Box> { + pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> { let mods = &mut Imports::new(); let mut state = EvalState::new(); if ast.source_raw().is_some() { diff --git a/src/ast/expr.rs b/src/ast/expr.rs index 66aba2f7..e50e5086 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -3,7 +3,7 @@ use super::{ASTNode, Ident, Stmt, StmtBlock}; use crate::engine::{OP_EXCLUSIVE_RANGE, OP_INCLUSIVE_RANGE}; use crate::func::hashing::ALT_ZERO_HASH; -use crate::module::NamespaceRef; +use crate::module::Namespace; use crate::tokenizer::Token; use crate::types::dynamic::Union; use crate::{Dynamic, Identifier, ImmutableString, Position, StaticVec, INT}; @@ -62,7 +62,7 @@ impl CustomExpr { /// /// Two separate hashes are pre-calculated because of the following patterns: /// -/// ```ignore +/// ```js /// func(a, b, c); // Native: func(a, b, c) - 3 parameters /// // Script: func(a, b, c) - 3 parameters /// @@ -158,7 +158,7 @@ impl FnCallHashes { #[derive(Debug, Clone, Default, Hash)] pub struct FnCallExpr { /// Namespace of the function, if any. - pub namespace: Option, + pub namespace: Option, /// Function name. pub name: Identifier, /// Pre-calculated hashes. @@ -357,11 +357,7 @@ pub enum Expr { Variable( Option, Position, - Box<( - Option, - Option<(NamespaceRef, u64)>, - Identifier, - )>, + Box<(Option, Option<(Namespace, u64)>, Identifier)>, ), /// Property access - ((getter, hash), (setter, hash), prop) Property( diff --git a/src/engine.rs b/src/engine.rs index e88e76e3..aa25bc20 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -7,14 +7,14 @@ use crate::func::{ native::{OnDebugCallback, OnParseTokenCallback, OnPrintCallback, OnVarCallback}, CallableFunction, IteratorFn, }; -use crate::module::NamespaceRef; +use crate::module::Namespace; use crate::packages::{Package, StandardPackage}; use crate::r#unsafe::unsafe_cast_var_name_to_lifetime; use crate::tokenizer::Token; use crate::types::dynamic::{map_std_type_name, AccessMode, Union, Variant}; use crate::{ calc_fn_params_hash, combine_hashes, Dynamic, EvalAltResult, Identifier, ImmutableString, - Module, Position, RhaiResult, Scope, Shared, StaticVec, INT, + Module, Position, RhaiError, RhaiResult, RhaiResultOf, Scope, Shared, StaticVec, INT, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -587,7 +587,7 @@ impl<'a> Target<'a> { /// Propagate a changed value back to the original source. /// This has no effect except for string indexing. #[inline] - pub fn propagate_changed_value(&mut self) -> Result<(), Box> { + pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> { match self { Self::RefMut(_) | Self::TempValue(_) => (), #[cfg(not(feature = "no_closure"))] @@ -1136,7 +1136,7 @@ impl Engine { &self, mods: &Imports, state: &mut EvalState, - namespace: &NamespaceRef, + namespace: &Namespace, ) -> Option> { let root = &namespace[0].name; @@ -1167,7 +1167,7 @@ impl Engine { lib: &[&Module], this_ptr: &'s mut Option<&mut Dynamic>, expr: &Expr, - ) -> Result<(Target<'s>, Position), Box> { + ) -> RhaiResultOf<(Target<'s>, Position)> { match expr { Expr::Variable(Some(_), _, _) => { self.search_scope_only(scope, mods, state, lib, this_ptr, expr) @@ -1258,7 +1258,7 @@ impl Engine { lib: &[&Module], this_ptr: &'s mut Option<&mut Dynamic>, expr: &Expr, - ) -> Result<(Target<'s>, Position), Box> { + ) -> RhaiResultOf<(Target<'s>, Position)> { // Make sure that the pointer indirection is taken only when absolutely necessary. let (index, var_pos) = match expr { @@ -1334,7 +1334,7 @@ impl Engine { chain_type: ChainType, level: usize, new_val: Option<((Dynamic, Position), (Option, Position))>, - ) -> Result<(Dynamic, bool), Box> { + ) -> RhaiResultOf<(Dynamic, bool)> { let is_ref_mut = target.is_ref(); let _terminate_chaining = terminate_chaining; @@ -1854,7 +1854,7 @@ impl Engine { idx_values: &mut StaticVec, size: usize, level: usize, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { #[cfg(not(feature = "unchecked"))] self.inc_operations(&mut mods.num_operations, expr.position())?; @@ -1869,7 +1869,7 @@ impl Engine { let (values, pos) = args.iter().try_fold( (StaticVec::with_capacity(args.len()), Position::NONE), - |(mut values, mut pos), expr| -> Result<_, Box> { + |(mut values, mut pos), expr| -> RhaiResultOf<_> { let (value, arg_pos) = self.get_arg_value( scope, mods, state, lib, this_ptr, level, expr, constants, )?; @@ -1916,7 +1916,7 @@ impl Engine { args.iter() .try_fold( (StaticVec::with_capacity(args.len()), Position::NONE), - |(mut values, mut pos), expr| -> Result<_, Box> { + |(mut values, mut pos), expr| -> RhaiResultOf<_> { let (value, arg_pos) = self.get_arg_value( scope, mods, state, lib, this_ptr, level, expr, constants, )?; @@ -1984,7 +1984,7 @@ impl Engine { add_if_not_found: bool, use_indexers: bool, level: usize, - ) -> Result, Box> { + ) -> RhaiResultOf> { #[cfg(not(feature = "unchecked"))] self.inc_operations(&mut mods.num_operations, Position::NONE)?; @@ -2339,7 +2339,7 @@ impl Engine { .iter() .try_fold( crate::Array::with_capacity(x.len()), - |mut arr, item| -> Result<_, Box> { + |mut arr, item| -> RhaiResultOf<_> { arr.push( self.eval_expr(scope, mods, state, lib, this_ptr, item, level)? .flatten(), @@ -2355,7 +2355,7 @@ impl Engine { .iter() .try_fold( x.1.clone(), - |mut map, (Ident { name: key, .. }, expr)| -> Result<_, Box> { + |mut map, (Ident { name: key, .. }, expr)| -> RhaiResultOf<_> { let value_ref = map.get_mut(key.as_str()).expect("contains all keys"); *value_ref = self .eval_expr(scope, mods, state, lib, this_ptr, expr, level)? @@ -2539,7 +2539,7 @@ impl Engine { target: &mut Target, root: (&str, Position), new_val: Dynamic, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if target.is_read_only() { // Assignment to constant variable return Err( @@ -3243,7 +3243,7 @@ impl Engine { index, if rename.is_empty() { name } else { rename }.clone(), ); - Ok(()) as Result<_, Box> + Ok(()) as RhaiResultOf<_> } else { Err(EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into()) } @@ -3305,12 +3305,12 @@ impl Engine { #[cfg(feature = "unchecked")] #[inline(always)] - fn check_data_size(&self, _value: &Dynamic) -> Result<(), Box> { + fn check_data_size(&self, _value: &Dynamic) -> RhaiResultOf<()> { Ok(()) } #[cfg(not(feature = "unchecked"))] - fn check_data_size(&self, value: &Dynamic) -> Result<(), Box> { + fn check_data_size(&self, value: &Dynamic) -> RhaiResultOf<()> { // Recursively calculate the size of a value (especially `Array` and `Map`) fn calc_size(value: &Dynamic) -> (usize, usize, usize) { match value.0 { @@ -3424,7 +3424,7 @@ impl Engine { &self, num_operations: &mut u64, pos: Position, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { *num_operations += 1; // Guard against too many operations @@ -3459,7 +3459,7 @@ impl Engine { /// Make a `Box<`[`EvalAltResult`][EvalAltResult::ErrorMismatchDataType]`>`. #[inline] #[must_use] - pub(crate) fn make_type_mismatch_err(&self, typ: &str, pos: Position) -> Box { + pub(crate) fn make_type_mismatch_err(&self, typ: &str, pos: Position) -> RhaiError { EvalAltResult::ErrorMismatchDataType( self.map_type_name(type_name::()).into(), typ.into(), diff --git a/src/func/builtin.rs b/src/func/builtin.rs index 2da123d4..3375f243 100644 --- a/src/func/builtin.rs +++ b/src/func/builtin.rs @@ -1,10 +1,9 @@ //! Built-in implementations for common operators. use super::call::FnCallArgs; +use super::native::FnBuiltin; use crate::engine::OP_CONTAINS; -use crate::{ - Dynamic, ExclusiveRange, ImmutableString, InclusiveRange, NativeCallContext, RhaiResult, INT, -}; +use crate::{Dynamic, ExclusiveRange, ImmutableString, InclusiveRange, INT}; use std::any::TypeId; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -51,11 +50,7 @@ fn is_numeric(type_id: TypeId) -> bool { /// /// The return function will be registered as a _method_, so the first parameter cannot be consumed. #[must_use] -pub fn get_builtin_binary_op_fn( - op: &str, - x: &Dynamic, - y: &Dynamic, -) -> Option RhaiResult> { +pub fn get_builtin_binary_op_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option { let type1 = x.type_id(); let type2 = y.type_id(); @@ -516,11 +511,7 @@ pub fn get_builtin_binary_op_fn( /// /// The return function is registered as a _method_, so the first parameter cannot be consumed. #[must_use] -pub fn get_builtin_op_assignment_fn( - op: &str, - x: &Dynamic, - y: &Dynamic, -) -> Option RhaiResult> { +pub fn get_builtin_op_assignment_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option { let type1 = x.type_id(); let type2 = y.type_id(); diff --git a/src/func/call.rs b/src/func/call.rs index 7e6b1c38..958a6ec1 100644 --- a/src/func/call.rs +++ b/src/func/call.rs @@ -4,17 +4,16 @@ use super::callable_function::CallableFunction; use super::native::FnAny; use super::{get_builtin_binary_op_fn, get_builtin_op_assignment_fn}; use crate::api::default_limits::MAX_DYNAMIC_PARAMETERS; -use crate::ast::FnCallHashes; +use crate::ast::{Expr, FnCallHashes, Stmt}; use crate::engine::{ EvalState, FnResolutionCacheEntry, Imports, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_TYPE_OF, }; -use crate::module::NamespaceRef; +use crate::module::Namespace; use crate::tokenizer::Token; use crate::{ - ast::{Expr, Stmt}, calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, EvalAltResult, FnPtr, - Identifier, ImmutableString, Module, Position, RhaiResult, Scope, StaticVec, + Identifier, ImmutableString, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -108,7 +107,7 @@ pub fn ensure_no_data_race( fn_name: impl AsRef, args: &FnCallArgs, is_method_call: bool, -) -> Result<(), Box> { +) -> RhaiResultOf<()> { if let Some((n, _)) = args .iter() .enumerate() @@ -131,7 +130,7 @@ impl Engine { #[must_use] fn gen_call_signature( &self, - namespace: Option<&NamespaceRef>, + namespace: Option<&Namespace>, fn_name: impl AsRef, args: &[&mut Dynamic], ) -> String { @@ -318,7 +317,7 @@ impl Engine { is_ref_mut: bool, is_op_assign: bool, pos: Position, - ) -> Result<(Dynamic, bool), Box> { + ) -> RhaiResultOf<(Dynamic, bool)> { #[cfg(not(feature = "unchecked"))] self.inc_operations(&mut mods.num_operations, pos)?; @@ -499,8 +498,8 @@ impl Engine { pos: Position, scope: Option<&mut Scope>, level: usize, - ) -> Result<(Dynamic, bool), Box> { - fn no_method_err(name: &str, pos: Position) -> Result<(Dynamic, bool), Box> { + ) -> RhaiResultOf<(Dynamic, bool)> { + fn no_method_err(name: &str, pos: Position) -> RhaiResultOf<(Dynamic, bool)> { let msg = format!("'{0}' should not be called this way. Try {0}(...);", name); Err(EvalAltResult::ErrorRuntime(msg.into(), pos).into()) } @@ -733,7 +732,7 @@ impl Engine { (call_args, call_arg_pos): &mut (StaticVec, Position), pos: Position, level: usize, - ) -> Result<(Dynamic, bool), Box> { + ) -> RhaiResultOf<(Dynamic, bool)> { let fn_name = fn_name.as_ref(); let is_ref_mut = target.is_ref(); @@ -893,7 +892,7 @@ impl Engine { level: usize, arg_expr: &Expr, constants: &[Dynamic], - ) -> Result<(Dynamic, Position), Box> { + ) -> RhaiResultOf<(Dynamic, Position)> { match arg_expr { Expr::Stack(slot, pos) => Ok((constants[*slot].clone(), *pos)), ref arg => self @@ -992,7 +991,7 @@ impl Engine { // Append the new curried arguments to the existing list. let fn_curry = a_expr.iter().skip(1).try_fold( fn_curry, - |mut curried, expr| -> Result<_, Box> { + |mut curried, expr| -> RhaiResultOf<_> { let (value, _) = self.get_arg_value( scope, mods, state, lib, this_ptr, level, expr, constants, )?; @@ -1181,7 +1180,7 @@ impl Engine { state: &mut EvalState, lib: &[&Module], this_ptr: &mut Option<&mut Dynamic>, - namespace: &NamespaceRef, + namespace: &Namespace, fn_name: impl AsRef, args_expr: &[Expr], constants: &[Dynamic], diff --git a/src/func/func.rs b/src/func/func.rs index f442b6fb..65636fbd 100644 --- a/src/func/func.rs +++ b/src/func/func.rs @@ -3,8 +3,9 @@ #![cfg(not(feature = "no_function"))] #![allow(non_snake_case)] +use crate::parser::ParseResult; use crate::types::dynamic::Variant; -use crate::{Engine, EvalAltResult, ParseError, Scope, SmartString, AST}; +use crate::{Engine, RhaiResultOf, Scope, SmartString, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -77,11 +78,7 @@ pub trait Func { /// # Ok(()) /// # } /// ``` - fn create_from_script( - self, - script: &str, - entry_point: &str, - ) -> Result; + fn create_from_script(self, script: &str, entry_point: &str) -> ParseResult; } macro_rules! def_anonymous_fn { @@ -92,9 +89,9 @@ macro_rules! def_anonymous_fn { impl<$($par: Variant + Clone,)* RET: Variant + Clone> Func<($($par,)*), RET> for Engine { #[cfg(feature = "sync")] - type Output = Box Result> + Send + Sync>; + type Output = Box RhaiResultOf + Send + Sync>; #[cfg(not(feature = "sync"))] - type Output = Box Result>>; + type Output = Box RhaiResultOf>; #[inline] fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output { @@ -103,7 +100,7 @@ macro_rules! def_anonymous_fn { } #[inline] - fn create_from_script(self, script: &str, entry_point: &str) -> Result { + fn create_from_script(self, script: &str, entry_point: &str) -> ParseResult { let ast = self.compile(script)?; Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point)) } diff --git a/src/func/native.rs b/src/func/native.rs index 56a8edfc..bbf989bb 100644 --- a/src/func/native.rs +++ b/src/func/native.rs @@ -8,7 +8,7 @@ use crate::tokenizer::{Token, TokenizeState}; use crate::types::dynamic::Variant; use crate::{ calc_fn_hash, Dynamic, Engine, EvalAltResult, EvalContext, FuncArgs, Module, Position, - RhaiResult, StaticVec, + RhaiResult, RhaiResultOf, StaticVec, }; use std::any::type_name; #[cfg(feature = "no_std")] @@ -233,7 +233,7 @@ impl<'a> NativeCallContext<'a> { &self, fn_name: impl AsRef, args: impl FuncArgs, - ) -> Result> { + ) -> RhaiResultOf { let mut arg_values = StaticVec::new_const(); args.parse(&mut arg_values); @@ -277,7 +277,7 @@ impl<'a> NativeCallContext<'a> { is_ref_mut: bool, is_method_call: bool, args: &mut [&mut Dynamic], - ) -> Result> { + ) -> RhaiResult { let fn_name = fn_name.as_ref(); let hash = if is_method_call { @@ -363,6 +363,9 @@ pub type FnAny = dyn Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResult; #[cfg(feature = "sync")] pub type FnAny = dyn Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResult + Send + Sync; +/// A trail object for built-in functions. +pub type FnBuiltin = fn(NativeCallContext, &mut FnCallArgs) -> RhaiResult; + /// A standard function that gets an iterator from a type. pub type IteratorFn = fn(Dynamic) -> Box>; @@ -405,12 +408,9 @@ pub type OnParseTokenCallback = /// A standard callback function for variable access. #[cfg(not(feature = "sync"))] pub type OnVarCallback = - Box Result, Box> + 'static>; + Box RhaiResultOf> + 'static>; /// A standard callback function for variable access. #[cfg(feature = "sync")] pub type OnVarCallback = Box< - dyn Fn(&str, usize, &EvalContext) -> Result, Box> - + Send - + Sync - + 'static, + dyn Fn(&str, usize, &EvalContext) -> RhaiResultOf> + Send + Sync + 'static, >; diff --git a/src/func/plugin.rs b/src/func/plugin.rs index 3faf408b..dc20e6f3 100644 --- a/src/func/plugin.rs +++ b/src/func/plugin.rs @@ -10,7 +10,7 @@ pub use crate::{ use std::prelude::v1::*; pub use std::{any::TypeId, mem}; -pub type RhaiResult = Result>; +pub type RhaiResult = crate::RhaiResult; #[cfg(not(features = "no_module"))] pub use rhai_codegen::*; diff --git a/src/func/register.rs b/src/func/register.rs index 7230ab02..2a8a212c 100644 --- a/src/func/register.rs +++ b/src/func/register.rs @@ -8,7 +8,7 @@ use super::native::{FnAny, SendSync}; use crate::r#unsafe::unsafe_try_cast; use crate::tokenizer::Position; use crate::types::dynamic::{DynamicWriteLock, Variant}; -use crate::{Dynamic, EvalAltResult, NativeCallContext}; +use crate::{Dynamic, EvalAltResult, NativeCallContext, RhaiResultOf}; #[cfg(feature = "no_std")] use std::prelude::v1::*; use std::{any::TypeId, mem}; @@ -169,14 +169,14 @@ macro_rules! def_register { } impl< - FN: Fn($($param),*) -> Result> + SendSync + 'static, + FN: Fn($($param),*) -> RhaiResultOf + SendSync + 'static, $($par: Variant + Clone,)* RET: Variant + Clone - > RegisterNativeFunction<($($mark,)*), Result>> for FN { + > RegisterNativeFunction<($($mark,)*), RhaiResultOf> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>>() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { @@ -194,14 +194,14 @@ macro_rules! def_register { } impl< - FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> Result> + SendSync + 'static, + FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> RhaiResultOf + SendSync + 'static, $($par: Variant + Clone,)* RET: Variant + Clone - > RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), Result>> for FN { + > RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), RhaiResultOf> for FN { #[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() } #[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>>() } - #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::>() } + #[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::>() } #[inline(always)] fn into_callable_function(self) -> CallableFunction { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { diff --git a/src/func/script.rs b/src/func/script.rs index 1bb56e3f..56326e64 100644 --- a/src/func/script.rs +++ b/src/func/script.rs @@ -5,7 +5,9 @@ use super::call::FnCallArgs; use crate::ast::ScriptFnDef; use crate::engine::{EvalState, Imports}; use crate::r#unsafe::unsafe_cast_var_name_to_lifetime; -use crate::{Dynamic, Engine, EvalAltResult, Module, Position, RhaiResult, Scope, StaticVec}; +use crate::{ + Dynamic, Engine, EvalAltResult, Module, Position, RhaiError, RhaiResult, Scope, StaticVec, +}; use std::mem; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -39,7 +41,7 @@ impl Engine { name: String, fn_def: &ScriptFnDef, mods: &Imports, - err: Box, + err: RhaiError, pos: Position, ) -> RhaiResult { Err(EvalAltResult::ErrorInFunctionCall( diff --git a/src/lib.rs b/src/lib.rs index 04232dec..ee86a923 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,11 +42,10 @@ //! //! # #[cfg(not(feature = "no_std"))] //! # #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] -//! assert_eq!( -//! // Evaluate the script, expects a 'bool' return -//! engine.eval_file::("my_script.rhai".into())?, -//! true -//! ); +//! // Evaluate the script, expects a 'bool' return +//! let result = engine.eval_file::("my_script.rhai".into())?, +//! +//! assert_eq!(result, true); //! //! Ok(()) //! } @@ -83,7 +82,12 @@ mod tokenizer; mod types; mod r#unsafe; -type RhaiResult = Result>; +/// General evaluation error for Rhai scripts. +type RhaiError = Box; +/// Generic [`Result`] type for Rhai functions. +type RhaiResultOf = Result; +/// General [`Result`] type for Rhai functions returning [`Dynamic`] values. +type RhaiResult = RhaiResultOf; /// The system integer type. It is defined as [`i64`]. /// @@ -234,7 +238,7 @@ pub use ast::FloatWrapper; pub use engine::{EvalState, FnResolutionCache, FnResolutionCacheEntry, Imports}; #[cfg(feature = "internals")] -pub use module::NamespaceRef; +pub use module::Namespace; /// Alias to [`smallvec::SmallVec<[T; 3]>`](https://crates.io/crates/smallvec), which is a /// specialized [`Vec`] backed by a small, inline, fixed-size array when there are ≤ 3 items stored. diff --git a/src/module/mod.rs b/src/module/mod.rs index 1c252317..e7e9b745 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -9,8 +9,8 @@ use crate::parser::IdentifierBuilder; use crate::tokenizer::Token; use crate::types::dynamic::Variant; use crate::{ - calc_fn_params_hash, calc_qualified_fn_hash, combine_hashes, Dynamic, EvalAltResult, - Identifier, ImmutableString, NativeCallContext, Shared, StaticVec, + calc_fn_params_hash, calc_qualified_fn_hash, combine_hashes, Dynamic, Identifier, + ImmutableString, NativeCallContext, RhaiResultOf, Shared, StaticVec, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -456,9 +456,9 @@ impl Module { /// Name and Position in [`EvalAltResult`] are [`None`] and [`NONE`][Position::NONE] and must be set afterwards. #[cfg(not(feature = "no_module"))] #[inline] - pub(crate) fn get_qualified_var(&self, hash_var: u64) -> Result<&Dynamic, Box> { + pub(crate) fn get_qualified_var(&self, hash_var: u64) -> RhaiResultOf<&Dynamic> { self.all_variables.get(&hash_var).ok_or_else(|| { - EvalAltResult::ErrorVariableNotFound(String::new(), crate::Position::NONE).into() + crate::EvalAltResult::ErrorVariableNotFound(String::new(), crate::Position::NONE).into() }) } @@ -918,7 +918,7 @@ impl Module { /// *x *= 2; // the first argument can be mutated /// } /// - /// Ok(orig) // return Result> + /// Ok(orig) // return RhaiResult /// }); /// /// assert!(module.contains_fn(hash)); @@ -935,9 +935,7 @@ impl Module { where N: AsRef + Into, T: Variant + Clone, - F: Fn(NativeCallContext, &mut FnCallArgs) -> Result> - + SendSync - + 'static, + F: Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResultOf + SendSync + 'static, { let f = move |ctx: NativeCallContext, args: &mut FnCallArgs| func(ctx, args).map(Dynamic::from); @@ -979,7 +977,7 @@ impl Module { where N: AsRef + Into, T: Variant + Clone, - F: RegisterNativeFunction>>, + F: RegisterNativeFunction>, { self.set_fn( name, @@ -1015,8 +1013,8 @@ impl Module { where A: Variant + Clone, T: Variant + Clone, - F: RegisterNativeFunction>>, - F: Fn(&mut A) -> Result> + SendSync + 'static, + F: RegisterNativeFunction>, + F: Fn(&mut A) -> RhaiResultOf + SendSync + 'static, { self.set_fn( &crate::engine::make_getter(name), @@ -1057,8 +1055,8 @@ impl Module { where A: Variant + Clone, B: Variant + Clone, - F: RegisterNativeFunction>>, - F: Fn(&mut A, B) -> Result<(), Box> + SendSync + 'static, + F: RegisterNativeFunction>, + F: Fn(&mut A, B) -> RhaiResultOf<()> + SendSync + 'static, { self.set_fn( &crate::engine::make_setter(name), @@ -1104,8 +1102,8 @@ impl Module { A: Variant + Clone, B: Variant + Clone, T: Variant + Clone, - F: RegisterNativeFunction>>, - F: Fn(&mut A, B) -> Result> + SendSync + 'static, + F: RegisterNativeFunction>, + F: Fn(&mut A, B) -> RhaiResultOf + SendSync + 'static, { #[cfg(not(feature = "no_index"))] if TypeId::of::() == TypeId::of::() { @@ -1166,8 +1164,8 @@ impl Module { A: Variant + Clone, B: Variant + Clone, C: Variant + Clone, - F: RegisterNativeFunction>>, - F: Fn(&mut A, B, C) -> Result<(), Box> + SendSync + 'static, + F: RegisterNativeFunction>, + F: Fn(&mut A, B, C) -> RhaiResultOf<()> + SendSync + 'static, { #[cfg(not(feature = "no_index"))] if TypeId::of::() == TypeId::of::() { @@ -1231,8 +1229,8 @@ impl Module { #[inline(always)] pub fn set_indexer_get_set_fn( &mut self, - get_fn: impl Fn(&mut A, B) -> Result> + SendSync + 'static, - set_fn: impl Fn(&mut A, B, T) -> Result<(), Box> + SendSync + 'static, + get_fn: impl Fn(&mut A, B) -> RhaiResultOf + SendSync + 'static, + set_fn: impl Fn(&mut A, B, T) -> RhaiResultOf<()> + SendSync + 'static, ) -> (u64, u64) where A: Variant + Clone, @@ -1549,7 +1547,7 @@ impl Module { scope: crate::Scope, ast: &crate::AST, engine: &crate::Engine, - ) -> Result> { + ) -> RhaiResultOf { let mut scope = scope; let mut mods = crate::engine::Imports::new(); let orig_mods_len = mods.len(); @@ -1800,12 +1798,12 @@ impl Module { /// A [`StaticVec`] is used because most namespace-qualified access contains only one level, /// and it is wasteful to always allocate a [`Vec`] with one element. #[derive(Clone, Eq, PartialEq, Default, Hash)] -pub struct NamespaceRef { +pub struct Namespace { index: Option, path: StaticVec, } -impl fmt::Debug for NamespaceRef { +impl fmt::Debug for Namespace { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(index) = self.index { write!(f, "{} -> ", index)?; @@ -1822,7 +1820,7 @@ impl fmt::Debug for NamespaceRef { } } -impl fmt::Display for NamespaceRef { +impl fmt::Display for Namespace { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str( &self @@ -1835,7 +1833,7 @@ impl fmt::Display for NamespaceRef { } } -impl Deref for NamespaceRef { +impl Deref for Namespace { type Target = StaticVec; #[inline(always)] @@ -1844,14 +1842,14 @@ impl Deref for NamespaceRef { } } -impl DerefMut for NamespaceRef { +impl DerefMut for Namespace { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.path } } -impl From> for NamespaceRef { +impl From> for Namespace { #[inline(always)] fn from(mut path: Vec) -> Self { path.shrink_to_fit(); @@ -1862,7 +1860,7 @@ impl From> for NamespaceRef { } } -impl From> for NamespaceRef { +impl From> for Namespace { #[inline(always)] fn from(mut path: StaticVec) -> Self { path.shrink_to_fit(); @@ -1870,8 +1868,8 @@ impl From> for NamespaceRef { } } -impl NamespaceRef { - /// Create a new [`NamespaceRef`]. +impl Namespace { + /// Create a new [`Namespace`]. #[inline(always)] #[must_use] pub const fn new() -> Self { diff --git a/src/module/resolvers/collection.rs b/src/module/resolvers/collection.rs index a3581a99..14b4da57 100644 --- a/src/module/resolvers/collection.rs +++ b/src/module/resolvers/collection.rs @@ -1,4 +1,4 @@ -use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, Shared}; +use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, RhaiResultOf, Shared}; use std::ops::AddAssign; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -123,7 +123,7 @@ impl ModuleResolver for ModuleResolversCollection { source_path: Option<&str>, path: &str, pos: Position, - ) -> Result, Box> { + ) -> RhaiResultOf> { for resolver in self.0.iter() { match resolver.resolve(engine, source_path, path, pos) { Ok(module) => return Ok(module), diff --git a/src/module/resolvers/dummy.rs b/src/module/resolvers/dummy.rs index 904f48ce..c183e1a6 100644 --- a/src/module/resolvers/dummy.rs +++ b/src/module/resolvers/dummy.rs @@ -1,4 +1,4 @@ -use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, Shared}; +use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, RhaiResultOf, Shared}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -44,7 +44,7 @@ impl ModuleResolver for DummyModuleResolver { _: Option<&str>, path: &str, pos: Position, - ) -> Result, Box> { + ) -> RhaiResultOf> { Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into()) } } diff --git a/src/module/resolvers/file.rs b/src/module/resolvers/file.rs index d9d567e7..27269157 100644 --- a/src/module/resolvers/file.rs +++ b/src/module/resolvers/file.rs @@ -2,7 +2,10 @@ #![cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))] use crate::func::native::shared_write_lock; -use crate::{Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, Scope, Shared}; +use crate::{ + Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Scope, + Shared, +}; use std::{ collections::BTreeMap, @@ -259,7 +262,7 @@ impl ModuleResolver for FileModuleResolver { source_path: Option<&str>, path: &str, pos: Position, - ) -> Result, Box> { + ) -> RhaiResultOf> { // Load relative paths from source if there is no base path specified let source_path = source_path.and_then(|p| Path::new(p).parent().map(|p| p.to_string_lossy())); @@ -315,7 +318,7 @@ impl ModuleResolver for FileModuleResolver { source_path: Option<&str>, path: &str, pos: Position, - ) -> Option>> { + ) -> Option> { // Construct the script file path let file_path = self.get_file_path(path, source_path); diff --git a/src/module/resolvers/mod.rs b/src/module/resolvers/mod.rs index 47911c34..33f3d6e8 100644 --- a/src/module/resolvers/mod.rs +++ b/src/module/resolvers/mod.rs @@ -1,5 +1,5 @@ use crate::func::native::SendSync; -use crate::{Engine, EvalAltResult, Module, Position, Shared, AST}; +use crate::{Engine, Module, Position, RhaiResultOf, Shared, AST}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -24,7 +24,7 @@ pub trait ModuleResolver: SendSync { source_path: Option<&str>, path: &str, pos: Position, - ) -> Result, Box>; + ) -> RhaiResultOf>; /// Resolve an `AST` based on a path string. /// @@ -43,7 +43,7 @@ pub trait ModuleResolver: SendSync { source_path: Option<&str>, path: &str, pos: Position, - ) -> Option>> { + ) -> Option> { None } } diff --git a/src/module/resolvers/stat.rs b/src/module/resolvers/stat.rs index 90b33ed7..278a7c00 100644 --- a/src/module/resolvers/stat.rs +++ b/src/module/resolvers/stat.rs @@ -1,5 +1,6 @@ use crate::{ - Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, Shared, SmartString, + Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Shared, + SmartString, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -131,7 +132,7 @@ impl ModuleResolver for StaticModuleResolver { _: Option<&str>, path: &str, pos: Position, - ) -> Result, Box> { + ) -> RhaiResultOf> { self.0 .get(path) .cloned() diff --git a/src/packages/arithmetic.rs b/src/packages/arithmetic.rs index 452d0c22..58338391 100644 --- a/src/packages/arithmetic.rs +++ b/src/packages/arithmetic.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::{def_package, EvalAltResult, Position, INT}; +use crate::{def_package, EvalAltResult, Position, RhaiError, RhaiResultOf, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -10,7 +10,7 @@ use std::prelude::v1::*; use num_traits::Float; #[inline(never)] -pub fn make_err(msg: impl Into) -> Box { +pub fn make_err(msg: impl Into) -> RhaiError { EvalAltResult::ErrorArithmetic(msg.into(), Position::NONE).into() } @@ -22,7 +22,7 @@ macro_rules! gen_arithmetic_functions { #[export_module] pub mod functions { #[rhai_fn(name = "+", return_raw)] - pub fn add(x: $arg_type, y: $arg_type) -> Result<$arg_type, Box> { + pub fn add(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_add(y).ok_or_else(|| make_err(format!("Addition overflow: {} + {}", x, y))) } else { @@ -30,7 +30,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = "-", return_raw)] - pub fn subtract(x: $arg_type, y: $arg_type) -> Result<$arg_type, Box> { + pub fn subtract(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_sub(y).ok_or_else(|| make_err(format!("Subtraction overflow: {} - {}", x, y))) } else { @@ -38,7 +38,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = "*", return_raw)] - pub fn multiply(x: $arg_type, y: $arg_type) -> Result<$arg_type, Box> { + pub fn multiply(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_mul(y).ok_or_else(|| make_err(format!("Multiplication overflow: {} * {}", x, y))) } else { @@ -46,7 +46,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = "/", return_raw)] - pub fn divide(x: $arg_type, y: $arg_type) -> Result<$arg_type, Box> { + pub fn divide(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { // Detect division by zero if y == 0 { @@ -59,7 +59,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = "%", return_raw)] - pub fn modulo(x: $arg_type, y: $arg_type) -> Result<$arg_type, Box> { + pub fn modulo(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_rem(y).ok_or_else(|| make_err(format!("Modulo division by zero or overflow: {} % {}", x, y))) } else { @@ -67,7 +67,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = "**", return_raw)] - pub fn power(x: $arg_type, y: INT) -> Result<$arg_type, Box> { + pub fn power(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { Err(make_err(format!("Integer raised to too large an index: {} ~ {}", x, y))) @@ -82,7 +82,7 @@ macro_rules! gen_arithmetic_functions { } #[rhai_fn(name = "<<", return_raw)] - pub fn shift_left(x: $arg_type, y: INT) -> Result<$arg_type, Box> { + pub fn shift_left(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { Err(make_err(format!("Left-shift by too many bits: {} << {}", x, y))) @@ -96,7 +96,7 @@ macro_rules! gen_arithmetic_functions { } } #[rhai_fn(name = ">>", return_raw)] - pub fn shift_right(x: $arg_type, y: INT) -> Result<$arg_type, Box> { + pub fn shift_right(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { Err(make_err(format!("Right-shift by too many bits: {} >> {}", x, y))) @@ -146,7 +146,7 @@ macro_rules! gen_signed_functions { #[export_module] pub mod functions { #[rhai_fn(name = "-", return_raw)] - pub fn neg(x: $arg_type) -> Result<$arg_type, Box> { + pub fn neg(x: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_neg().ok_or_else(|| make_err(format!("Negation overflow: -{}", x))) } else { @@ -158,7 +158,7 @@ macro_rules! gen_signed_functions { x } #[rhai_fn(return_raw)] - pub fn abs(x: $arg_type) -> Result<$arg_type, Box> { + pub fn abs(x: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { x.checked_abs().ok_or_else(|| make_err(format!("Negation overflow: -{}", x))) } else { @@ -254,8 +254,6 @@ gen_signed_functions!(signed_num_128 => i128); #[cfg(not(feature = "no_float"))] #[export_module] mod f32_functions { - use crate::EvalAltResult; - #[cfg(not(feature = "f32_float"))] pub mod basic_arithmetic { #[rhai_fn(name = "+")] @@ -337,7 +335,7 @@ mod f32_functions { x.abs() } #[rhai_fn(return_raw)] - pub fn sign(x: f32) -> Result> { + pub fn sign(x: f32) -> RhaiResultOf { match x.signum() { _ if x == 0.0 => Ok(0), x if x.is_nan() => Err(make_err("Sign of NaN is undefined")), @@ -349,7 +347,7 @@ mod f32_functions { x == 0.0 } #[rhai_fn(name = "**", return_raw)] - pub fn pow_f_i(x: f32, y: INT) -> Result> { + pub fn pow_f_i(x: f32, y: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && y > (i32::MAX as INT) { Err(make_err(format!( "Number raised to too large an index: {} ~ {}", @@ -445,7 +443,7 @@ mod f64_functions { x.abs() } #[rhai_fn(return_raw)] - pub fn sign(x: f64) -> Result> { + pub fn sign(x: f64) -> RhaiResultOf { match x.signum() { _ if x == 0.0 => Ok(0), x if x.is_nan() => Err(make_err("Sign of NaN is undefined")), @@ -465,7 +463,7 @@ pub mod decimal_functions { use rust_decimal::{prelude::Zero, Decimal, MathematicalOps}; #[rhai_fn(skip, return_raw)] - pub fn add(x: Decimal, y: Decimal) -> Result> { + pub fn add(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_add(y) .ok_or_else(|| make_err(format!("Addition overflow: {} + {}", x, y))) @@ -474,7 +472,7 @@ pub mod decimal_functions { } } #[rhai_fn(skip, return_raw)] - pub fn subtract(x: Decimal, y: Decimal) -> Result> { + pub fn subtract(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_sub(y) .ok_or_else(|| make_err(format!("Subtraction overflow: {} - {}", x, y))) @@ -483,7 +481,7 @@ pub mod decimal_functions { } } #[rhai_fn(skip, return_raw)] - pub fn multiply(x: Decimal, y: Decimal) -> Result> { + pub fn multiply(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_mul(y) .ok_or_else(|| make_err(format!("Multiplication overflow: {} * {}", x, y))) @@ -492,7 +490,7 @@ pub mod decimal_functions { } } #[rhai_fn(skip, return_raw)] - pub fn divide(x: Decimal, y: Decimal) -> Result> { + pub fn divide(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { // Detect division by zero if y == Decimal::zero() { @@ -506,7 +504,7 @@ pub mod decimal_functions { } } #[rhai_fn(skip, return_raw)] - pub fn modulo(x: Decimal, y: Decimal) -> Result> { + pub fn modulo(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_rem(y).ok_or_else(|| { make_err(format!( @@ -519,7 +517,7 @@ pub mod decimal_functions { } } #[rhai_fn(skip, return_raw)] - pub fn power(x: Decimal, y: Decimal) -> Result> { + pub fn power(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_powd(y) .ok_or_else(|| make_err(format!("Exponential overflow: {} + {}", x, y))) diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index b26a4ace..3e2903a1 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -5,7 +5,7 @@ use crate::engine::OP_EQUALS; use crate::plugin::*; use crate::{ def_package, Array, Dynamic, EvalAltResult, ExclusiveRange, FnPtr, InclusiveRange, - NativeCallContext, Position, INT, + NativeCallContext, Position, RhaiResultOf, INT, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -80,7 +80,7 @@ pub mod array_functions { array: &mut Array, len: INT, item: Dynamic, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if len <= 0 { return Ok(()); } @@ -263,11 +263,7 @@ pub mod array_functions { } } #[rhai_fn(return_raw, pure)] - pub fn map( - ctx: NativeCallContext, - array: &mut Array, - mapper: FnPtr, - ) -> Result> { + pub fn map(ctx: NativeCallContext, array: &mut Array, mapper: FnPtr) -> RhaiResultOf { if array.is_empty() { return Ok(array.clone()); } @@ -304,7 +300,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, mapper: &str, - ) -> Result> { + ) -> RhaiResultOf { map(ctx, array, FnPtr::new(mapper)?) } @@ -313,7 +309,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: FnPtr, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(array.clone()); } @@ -353,7 +349,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter_func: &str, - ) -> Result> { + ) -> RhaiResultOf { filter(ctx, array, FnPtr::new(filter_func)?) } #[rhai_fn(return_raw, pure)] @@ -361,7 +357,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, value: Dynamic, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(false); } @@ -396,7 +392,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, value: Dynamic, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { Ok(-1) } else { @@ -409,7 +405,7 @@ pub mod array_functions { array: &mut Array, value: Dynamic, start: INT, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(-1); } @@ -455,7 +451,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: &str, - ) -> Result> { + ) -> RhaiResultOf { index_of_filter(ctx, array, FnPtr::new(filter)?) } #[rhai_fn(name = "index_of", return_raw, pure)] @@ -463,7 +459,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: FnPtr, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { Ok(-1) } else { @@ -476,7 +472,7 @@ pub mod array_functions { array: &mut Array, filter: FnPtr, start: INT, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(-1); } @@ -526,15 +522,11 @@ pub mod array_functions { array: &mut Array, filter: &str, start: INT, - ) -> Result> { + ) -> RhaiResultOf { index_of_filter_starting_from(ctx, array, FnPtr::new(filter)?, start) } #[rhai_fn(return_raw, pure)] - pub fn some( - ctx: NativeCallContext, - array: &mut Array, - filter: FnPtr, - ) -> Result> { + pub fn some(ctx: NativeCallContext, array: &mut Array, filter: FnPtr) -> RhaiResultOf { if array.is_empty() { return Ok(false); } @@ -572,15 +564,11 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: &str, - ) -> Result> { + ) -> RhaiResultOf { some(ctx, array, FnPtr::new(filter)?) } #[rhai_fn(return_raw, pure)] - pub fn all( - ctx: NativeCallContext, - array: &mut Array, - filter: FnPtr, - ) -> Result> { + pub fn all(ctx: NativeCallContext, array: &mut Array, filter: FnPtr) -> RhaiResultOf { if array.is_empty() { return Ok(true); } @@ -618,11 +606,11 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: &str, - ) -> Result> { + ) -> RhaiResultOf { all(ctx, array, FnPtr::new(filter)?) } #[rhai_fn(return_raw)] - pub fn dedup(ctx: NativeCallContext, array: &mut Array) -> Result<(), Box> { + pub fn dedup(ctx: NativeCallContext, array: &mut Array) -> RhaiResultOf<()> { dedup_with_fn_name(ctx, array, OP_EQUALS) } #[rhai_fn(name = "dedup", return_raw)] @@ -630,7 +618,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, comparer: FnPtr, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if array.is_empty() { return Ok(()); } @@ -650,15 +638,11 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, comparer: &str, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { dedup_by_comparer(ctx, array, FnPtr::new(comparer)?) } #[rhai_fn(return_raw, pure)] - pub fn reduce( - ctx: NativeCallContext, - array: &mut Array, - reducer: FnPtr, - ) -> Result> { + pub fn reduce(ctx: NativeCallContext, array: &mut Array, reducer: FnPtr) -> RhaiResult { reduce_with_initial(ctx, array, reducer, Dynamic::UNIT) } #[rhai_fn(name = "reduce", return_raw, pure)] @@ -666,7 +650,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, reducer: &str, - ) -> Result> { + ) -> RhaiResult { reduce(ctx, array, FnPtr::new(reducer)?) } #[rhai_fn(name = "reduce", return_raw, pure)] @@ -675,7 +659,7 @@ pub mod array_functions { array: &mut Array, reducer: FnPtr, initial: Dynamic, - ) -> Result> { + ) -> RhaiResult { if array.is_empty() { return Ok(initial); } @@ -713,15 +697,11 @@ pub mod array_functions { array: &mut Array, reducer: &str, initial: Dynamic, - ) -> Result> { + ) -> RhaiResult { reduce_with_initial(ctx, array, FnPtr::new(reducer)?, initial) } #[rhai_fn(return_raw, pure)] - pub fn reduce_rev( - ctx: NativeCallContext, - array: &mut Array, - reducer: FnPtr, - ) -> Result> { + pub fn reduce_rev(ctx: NativeCallContext, array: &mut Array, reducer: FnPtr) -> RhaiResult { reduce_rev_with_initial(ctx, array, reducer, Dynamic::UNIT) } #[rhai_fn(name = "reduce_rev", return_raw, pure)] @@ -729,7 +709,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, reducer: &str, - ) -> Result> { + ) -> RhaiResult { reduce_rev(ctx, array, FnPtr::new(reducer)?) } #[rhai_fn(name = "reduce_rev", return_raw, pure)] @@ -738,7 +718,7 @@ pub mod array_functions { array: &mut Array, reducer: FnPtr, initial: Dynamic, - ) -> Result> { + ) -> RhaiResult { if array.is_empty() { return Ok(initial); } @@ -777,7 +757,7 @@ pub mod array_functions { array: &mut Array, reducer: &str, initial: Dynamic, - ) -> Result> { + ) -> RhaiResult { reduce_rev_with_initial(ctx, array, FnPtr::new(reducer)?, initial) } #[rhai_fn(name = "sort", return_raw)] @@ -785,15 +765,11 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, comparer: &str, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { sort(ctx, array, FnPtr::new(comparer)?) } #[rhai_fn(return_raw)] - pub fn sort( - ctx: NativeCallContext, - array: &mut Array, - comparer: FnPtr, - ) -> Result<(), Box> { + pub fn sort(ctx: NativeCallContext, array: &mut Array, comparer: FnPtr) -> RhaiResultOf<()> { if array.len() <= 1 { return Ok(()); } @@ -815,7 +791,7 @@ pub mod array_functions { Ok(()) } #[rhai_fn(name = "sort", return_raw)] - pub fn sort_with_builtin(array: &mut Array) -> Result<(), Box> { + pub fn sort_with_builtin(array: &mut Array) -> RhaiResultOf<()> { if array.len() <= 1 { return Ok(()); } @@ -891,7 +867,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: FnPtr, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(Array::new()); } @@ -938,7 +914,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: &str, - ) -> Result> { + ) -> RhaiResultOf { drain(ctx, array, FnPtr::new(filter)?) } #[rhai_fn(name = "drain")] @@ -985,7 +961,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: FnPtr, - ) -> Result> { + ) -> RhaiResultOf { if array.is_empty() { return Ok(Array::new()); } @@ -1032,7 +1008,7 @@ pub mod array_functions { ctx: NativeCallContext, array: &mut Array, filter: &str, - ) -> Result> { + ) -> RhaiResultOf { retain(ctx, array, FnPtr::new(filter)?) } #[rhai_fn(name = "retain")] @@ -1082,7 +1058,7 @@ pub mod array_functions { ctx: NativeCallContext, array1: &mut Array, array2: Array, - ) -> Result> { + ) -> RhaiResultOf { if array1.len() != array2.len() { return Ok(false); } @@ -1122,7 +1098,7 @@ pub mod array_functions { ctx: NativeCallContext, array1: &mut Array, array2: Array, - ) -> Result> { + ) -> RhaiResultOf { equals(ctx, array1, array2).map(|r| !r) } } diff --git a/src/packages/blob_basic.rs b/src/packages/blob_basic.rs index 048b1226..342a97fc 100644 --- a/src/packages/blob_basic.rs +++ b/src/packages/blob_basic.rs @@ -4,7 +4,7 @@ use crate::plugin::*; use crate::{ def_package, Blob, Dynamic, EvalAltResult, ExclusiveRange, InclusiveRange, NativeCallContext, - Position, INT, + Position, RhaiResultOf, INT, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -31,10 +31,7 @@ pub mod blob_functions { Blob::new() } #[rhai_fn(name = "blob", return_raw)] - pub fn blob_with_capacity( - ctx: NativeCallContext, - len: INT, - ) -> Result> { + pub fn blob_with_capacity(ctx: NativeCallContext, len: INT) -> RhaiResultOf { blob_with_capacity_and_value(ctx, len, 0) } #[rhai_fn(name = "blob", return_raw)] @@ -42,7 +39,7 @@ pub mod blob_functions { ctx: NativeCallContext, len: INT, value: INT, - ) -> Result> { + ) -> RhaiResultOf { let len = if len < 0 { 0 } else { len as usize }; let _ctx = ctx; @@ -118,7 +115,7 @@ pub mod blob_functions { blob: &mut Blob, len: INT, item: INT, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if len <= 0 { return Ok(()); } diff --git a/src/packages/iter_basic.rs b/src/packages/iter_basic.rs index bdbcfaf9..d6be661f 100644 --- a/src/packages/iter_basic.rs +++ b/src/packages/iter_basic.rs @@ -1,6 +1,6 @@ use crate::plugin::*; use crate::types::dynamic::Variant; -use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, INT}; +use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, RhaiResultOf, INT}; use std::iter::{ExactSizeIterator, FusedIterator}; use std::ops::{Range, RangeInclusive}; #[cfg(feature = "no_std")] @@ -22,7 +22,7 @@ impl StepRange where T: Variant + Copy + PartialOrd + Add + Sub, { - pub fn new(from: T, to: T, step: T) -> Result> { + pub fn new(from: T, to: T, step: T) -> RhaiResultOf { #[cfg(not(feature = "unchecked"))] if let Some(r) = from.checked_add(&step) { if r == from { @@ -117,7 +117,7 @@ struct BitRange(INT, INT, usize); const BITS: usize = std::mem::size_of::() * 8; impl BitRange { - pub fn new(value: INT, from: INT, len: INT) -> Result> { + pub fn new(value: INT, from: INT, len: INT) -> RhaiResultOf { let from = if from >= 0 { let offset = from as usize; @@ -334,7 +334,7 @@ def_package! { struct StepFloatRange(FLOAT, FLOAT, FLOAT); impl StepFloatRange { - pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> Result> { + pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> RhaiResultOf { #[cfg(not(feature = "unchecked"))] if step == 0.0 { return Err(EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), @@ -396,7 +396,7 @@ def_package! { struct StepDecimalRange(Decimal, Decimal, Decimal); impl StepDecimalRange { - pub fn new(from: Decimal, to: Decimal, step: Decimal) -> Result> { + pub fn new(from: Decimal, to: Decimal, step: Decimal) -> RhaiResultOf { #[cfg(not(feature = "unchecked"))] if step.is_zero() { return Err(EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), diff --git a/src/packages/lang_core.rs b/src/packages/lang_core.rs index 75ac1d8e..ff9c7d87 100644 --- a/src/packages/lang_core.rs +++ b/src/packages/lang_core.rs @@ -1,7 +1,7 @@ use crate::def_package; use crate::plugin::*; use crate::types::dynamic::Tag; -use crate::{Dynamic, EvalAltResult, INT}; +use crate::{Dynamic, EvalAltResult, RhaiResultOf, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -21,7 +21,7 @@ mod core_functions { value.tag() as INT } #[rhai_fn(name = "set_tag", set = "tag", return_raw)] - pub fn set_tag(value: &mut Dynamic, tag: INT) -> Result<(), Box> { + pub fn set_tag(value: &mut Dynamic, tag: INT) -> RhaiResultOf<()> { if tag < Tag::MIN as INT { Err(EvalAltResult::ErrorArithmetic( format!( diff --git a/src/packages/logic.rs b/src/packages/logic.rs index a800425c..2aad954e 100644 --- a/src/packages/logic.rs +++ b/src/packages/logic.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, INT}; +use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, RhaiResultOf, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -202,7 +202,7 @@ mod bit_field_functions { const BITS: usize = std::mem::size_of::() * 8; #[rhai_fn(return_raw)] - pub fn get_bit(value: INT, index: INT) -> Result> { + pub fn get_bit(value: INT, index: INT) -> RhaiResultOf { if index >= 0 { let offset = index as usize; @@ -225,7 +225,7 @@ mod bit_field_functions { } } #[rhai_fn(return_raw)] - pub fn set_bit(value: &mut INT, index: INT, new_value: bool) -> Result<(), Box> { + pub fn set_bit(value: &mut INT, index: INT, new_value: bool) -> RhaiResultOf<()> { if index >= 0 { let offset = index as usize; @@ -260,22 +260,19 @@ mod bit_field_functions { } } #[rhai_fn(name = "get_bits", return_raw)] - pub fn get_bits_range(value: INT, range: ExclusiveRange) -> Result> { + pub fn get_bits_range(value: INT, range: ExclusiveRange) -> RhaiResultOf { let from = INT::max(range.start, 0); let to = INT::max(range.end, from); get_bits(value, from, to - from) } #[rhai_fn(name = "get_bits", return_raw)] - pub fn get_bits_range_inclusive( - value: INT, - range: InclusiveRange, - ) -> Result> { + pub fn get_bits_range_inclusive(value: INT, range: InclusiveRange) -> RhaiResultOf { let from = INT::max(*range.start(), 0); let to = INT::max(*range.end(), from - 1); get_bits(value, from, to - from + 1) } #[rhai_fn(return_raw)] - pub fn get_bits(value: INT, index: INT, bits: INT) -> Result> { + pub fn get_bits(value: INT, index: INT, bits: INT) -> RhaiResultOf { if bits < 1 { return Ok(0); } @@ -321,7 +318,7 @@ mod bit_field_functions { value: &mut INT, range: ExclusiveRange, new_value: INT, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { let from = INT::max(range.start, 0); let to = INT::max(range.end, from); set_bits(value, from, to - from, new_value) @@ -331,18 +328,13 @@ mod bit_field_functions { value: &mut INT, range: InclusiveRange, new_value: INT, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { let from = INT::max(*range.start(), 0); let to = INT::max(*range.end(), from - 1); set_bits(value, from, to - from + 1, new_value) } #[rhai_fn(return_raw)] - pub fn set_bits( - value: &mut INT, - index: INT, - bits: INT, - new_value: INT, - ) -> Result<(), Box> { + pub fn set_bits(value: &mut INT, index: INT, bits: INT, new_value: INT) -> RhaiResultOf<()> { if bits < 1 { return Ok(()); } diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs index 7f6c8e2f..a1f2fa5d 100644 --- a/src/packages/map_basic.rs +++ b/src/packages/map_basic.rs @@ -2,7 +2,7 @@ use crate::engine::OP_EQUALS; use crate::plugin::*; -use crate::{def_package, Dynamic, ImmutableString, Map, INT}; +use crate::{def_package, Dynamic, ImmutableString, Map, RhaiResultOf, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -66,11 +66,7 @@ mod map_functions { } } #[rhai_fn(name = "==", return_raw, pure)] - pub fn equals( - ctx: NativeCallContext, - map1: &mut Map, - map2: Map, - ) -> Result> { + pub fn equals(ctx: NativeCallContext, map1: &mut Map, map2: Map) -> RhaiResultOf { if map1.len() != map2.len() { return Ok(false); } @@ -96,11 +92,7 @@ mod map_functions { Ok(true) } #[rhai_fn(name = "!=", return_raw, pure)] - pub fn not_equals( - ctx: NativeCallContext, - map1: &mut Map, - map2: Map, - ) -> Result> { + pub fn not_equals(ctx: NativeCallContext, map1: &mut Map, map2: Map) -> RhaiResultOf { equals(ctx, map1, map2).map(|r| !r) } diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs index c596cc62..5f81f19d 100644 --- a/src/packages/math_basic.rs +++ b/src/packages/math_basic.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::{def_package, Position, INT, INT_BASE}; +use crate::{def_package, Position, RhaiResultOf, INT, INT_BASE}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -114,7 +114,7 @@ def_package! { #[export_module] mod int_functions { #[rhai_fn(name = "parse_int", return_raw)] - pub fn parse_int_radix(string: &str, radix: INT) -> Result> { + pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf { if !(2..=36).contains(&radix) { return Err(EvalAltResult::ErrorArithmetic( format!("Invalid radix: '{}'", radix), @@ -134,7 +134,7 @@ mod int_functions { }) } #[rhai_fn(name = "parse_int", return_raw)] - pub fn parse_int(string: &str) -> Result> { + pub fn parse_int(string: &str) -> RhaiResultOf { parse_int_radix(string, 10) } } @@ -263,7 +263,7 @@ mod float_functions { x.is_infinite() } #[rhai_fn(name = "to_int", return_raw)] - pub fn f32_to_int(x: f32) -> Result> { + pub fn f32_to_int(x: f32) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f32) { Err(EvalAltResult::ErrorArithmetic( format!("Integer overflow: to_int({})", x), @@ -275,7 +275,7 @@ mod float_functions { } } #[rhai_fn(name = "to_int", return_raw)] - pub fn f64_to_int(x: f64) -> Result> { + pub fn f64_to_int(x: f64) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f64) { Err(EvalAltResult::ErrorArithmetic( format!("Integer overflow: to_int({})", x), @@ -287,7 +287,7 @@ mod float_functions { } } #[rhai_fn(return_raw)] - pub fn parse_float(string: &str) -> Result> { + pub fn parse_float(string: &str) -> RhaiResultOf { string.trim().parse::().map_err(|err| { EvalAltResult::ErrorArithmetic( format!("Error parsing floating-point number '{}': {}", string, err), @@ -325,7 +325,7 @@ mod decimal_functions { } #[cfg(feature = "no_float")] #[rhai_fn(return_raw)] - pub fn parse_float(s: &str) -> Result> { + pub fn parse_float(s: &str) -> RhaiResultOf { parse_decimal(s) } @@ -339,12 +339,12 @@ mod decimal_functions { x.tan() } #[rhai_fn(return_raw)] - pub fn sqrt(x: Decimal) -> Result> { + pub fn sqrt(x: Decimal) -> RhaiResultOf { x.sqrt() .ok_or_else(|| make_err(format!("Error taking the square root of {}", x,))) } #[rhai_fn(return_raw)] - pub fn exp(x: Decimal) -> Result> { + pub fn exp(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_exp() .ok_or_else(|| make_err(format!("Exponential overflow: e ** {}", x,))) @@ -353,7 +353,7 @@ mod decimal_functions { } } #[rhai_fn(return_raw)] - pub fn ln(x: Decimal) -> Result> { + pub fn ln(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_ln() .ok_or_else(|| make_err(format!("Error taking the natural log of {}", x))) @@ -362,7 +362,7 @@ mod decimal_functions { } } #[rhai_fn(name = "log", return_raw)] - pub fn log10(x: Decimal) -> Result> { + pub fn log10(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_log10() .ok_or_else(|| make_err(format!("Error taking the log of {}", x))) @@ -383,7 +383,7 @@ mod decimal_functions { x.round() } #[rhai_fn(name = "round", return_raw)] - pub fn round_dp(x: Decimal, dp: INT) -> Result> { + pub fn round_dp(x: Decimal, dp: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { if dp < 0 { return Err(make_err(format!( @@ -399,7 +399,7 @@ mod decimal_functions { Ok(x.round_dp(dp as u32)) } #[rhai_fn(return_raw)] - pub fn round_up(x: Decimal, dp: INT) -> Result> { + pub fn round_up(x: Decimal, dp: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { if dp < 0 { return Err(make_err(format!( @@ -415,7 +415,7 @@ mod decimal_functions { Ok(x.round_dp_with_strategy(dp as u32, RoundingStrategy::AwayFromZero)) } #[rhai_fn(return_raw)] - pub fn round_down(x: Decimal, dp: INT) -> Result> { + pub fn round_down(x: Decimal, dp: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { if dp < 0 { return Err(make_err(format!( @@ -431,7 +431,7 @@ mod decimal_functions { Ok(x.round_dp_with_strategy(dp as u32, RoundingStrategy::ToZero)) } #[rhai_fn(return_raw)] - pub fn round_half_up(x: Decimal, dp: INT) -> Result> { + pub fn round_half_up(x: Decimal, dp: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { if dp < 0 { return Err(make_err(format!( @@ -447,7 +447,7 @@ mod decimal_functions { Ok(x.round_dp_with_strategy(dp as u32, RoundingStrategy::MidpointAwayFromZero)) } #[rhai_fn(return_raw)] - pub fn round_half_down(x: Decimal, dp: INT) -> Result> { + pub fn round_half_down(x: Decimal, dp: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { if dp < 0 { return Err(make_err(format!( @@ -471,7 +471,7 @@ mod decimal_functions { x.fract() } #[rhai_fn(return_raw)] - pub fn parse_decimal(string: &str) -> Result> { + pub fn parse_decimal(string: &str) -> RhaiResultOf { Decimal::from_str(string) .or_else(|_| Decimal::from_scientific(string)) .map_err(|err| { @@ -485,7 +485,7 @@ mod decimal_functions { #[cfg(not(feature = "no_float"))] #[rhai_fn(name = "to_decimal", return_raw)] - pub fn f32_to_decimal(x: f32) -> Result> { + pub fn f32_to_decimal(x: f32) -> RhaiResultOf { Decimal::try_from(x).map_err(|_| { EvalAltResult::ErrorArithmetic( format!("Cannot convert to Decimal: to_decimal({})", x), @@ -496,7 +496,7 @@ mod decimal_functions { } #[cfg(not(feature = "no_float"))] #[rhai_fn(name = "to_decimal", return_raw)] - pub fn f64_to_decimal(x: f64) -> Result> { + pub fn f64_to_decimal(x: f64) -> RhaiResultOf { Decimal::try_from(x).map_err(|_| { EvalAltResult::ErrorArithmetic( format!("Cannot convert to Decimal: to_decimal({})", x), @@ -507,7 +507,7 @@ mod decimal_functions { } #[cfg(not(feature = "no_float"))] #[rhai_fn(return_raw)] - pub fn to_float(x: Decimal) -> Result> { + pub fn to_float(x: Decimal) -> RhaiResultOf { FLOAT::try_from(x).map_err(|_| { EvalAltResult::ErrorArithmetic( format!("Cannot convert to floating-point: to_float({})", x), diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index c29b4af0..ec1fc793 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use crate::plugin::*; -use crate::{def_package, Dynamic, ExclusiveRange, InclusiveRange, StaticVec, INT}; +use crate::{def_package, Dynamic, ExclusiveRange, InclusiveRange, RhaiResultOf, StaticVec, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; use std::{any::TypeId, mem}; @@ -500,7 +500,7 @@ mod string_functions { string: &mut ImmutableString, len: INT, character: char, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if len <= 0 { return Ok(()); } @@ -544,7 +544,7 @@ mod string_functions { string: &mut ImmutableString, len: INT, padding: &str, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { if len <= 0 { return Ok(()); } diff --git a/src/packages/time_basic.rs b/src/packages/time_basic.rs index bf6a0d50..f4a6e7df 100644 --- a/src/packages/time_basic.rs +++ b/src/packages/time_basic.rs @@ -2,7 +2,7 @@ use super::{arithmetic::make_err as make_arithmetic_err, math_basic::MAX_INT}; use crate::plugin::*; -use crate::{def_package, Dynamic, EvalAltResult, INT}; +use crate::{def_package, Dynamic, EvalAltResult, RhaiResult, RhaiResultOf, INT}; #[cfg(not(feature = "no_float"))] use crate::FLOAT; @@ -30,7 +30,7 @@ mod time_functions { } #[rhai_fn(name = "elapsed", get = "elapsed", return_raw)] - pub fn elapsed(timestamp: Instant) -> Result> { + pub fn elapsed(timestamp: Instant) -> RhaiResult { #[cfg(not(feature = "no_float"))] if timestamp > Instant::now() { Err(make_arithmetic_err("Time-stamp is later than now")) @@ -56,10 +56,7 @@ mod time_functions { } #[rhai_fn(return_raw, name = "-")] - pub fn time_diff( - timestamp1: Instant, - timestamp2: Instant, - ) -> Result> { + pub fn time_diff(timestamp1: Instant, timestamp2: Instant) -> RhaiResult { #[cfg(not(feature = "no_float"))] return Ok(if timestamp2 > timestamp1 { -(timestamp2 - timestamp1).as_secs_f64() as FLOAT @@ -96,7 +93,7 @@ mod time_functions { #[cfg(not(feature = "no_float"))] pub mod float_functions { - fn add_impl(timestamp: Instant, seconds: FLOAT) -> Result> { + fn add_impl(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf { if seconds < 0.0 { subtract_impl(timestamp, -seconds) } else if cfg!(not(feature = "unchecked")) { @@ -119,10 +116,7 @@ mod time_functions { Ok(timestamp + Duration::from_millis((seconds * 1000.0) as u64)) } } - fn subtract_impl( - timestamp: Instant, - seconds: FLOAT, - ) -> Result> { + fn subtract_impl(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf { if seconds < 0.0 { add_impl(timestamp, -seconds) } else if cfg!(not(feature = "unchecked")) { @@ -147,32 +141,26 @@ mod time_functions { } #[rhai_fn(return_raw, name = "+")] - pub fn add(timestamp: Instant, seconds: FLOAT) -> Result> { + pub fn add(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf { add_impl(timestamp, seconds) } #[rhai_fn(return_raw, name = "+=")] - pub fn add_assign( - timestamp: &mut Instant, - seconds: FLOAT, - ) -> Result<(), Box> { + pub fn add_assign(timestamp: &mut Instant, seconds: FLOAT) -> RhaiResultOf<()> { *timestamp = add_impl(*timestamp, seconds)?; Ok(()) } #[rhai_fn(return_raw, name = "-")] - pub fn subtract(timestamp: Instant, seconds: FLOAT) -> Result> { + pub fn subtract(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf { subtract_impl(timestamp, seconds) } #[rhai_fn(return_raw, name = "-=")] - pub fn subtract_assign( - timestamp: &mut Instant, - seconds: FLOAT, - ) -> Result<(), Box> { + pub fn subtract_assign(timestamp: &mut Instant, seconds: FLOAT) -> RhaiResultOf<()> { *timestamp = subtract_impl(*timestamp, seconds)?; Ok(()) } } - fn add_impl(timestamp: Instant, seconds: INT) -> Result> { + fn add_impl(timestamp: Instant, seconds: INT) -> RhaiResultOf { if seconds < 0 { subtract_impl(timestamp, -seconds) } else if cfg!(not(feature = "unchecked")) { @@ -188,7 +176,7 @@ mod time_functions { Ok(timestamp + Duration::from_secs(seconds as u64)) } } - fn subtract_impl(timestamp: Instant, seconds: INT) -> Result> { + fn subtract_impl(timestamp: Instant, seconds: INT) -> RhaiResultOf { if seconds < 0 { add_impl(timestamp, -seconds) } else if cfg!(not(feature = "unchecked")) { @@ -206,23 +194,20 @@ mod time_functions { } #[rhai_fn(return_raw, name = "+")] - pub fn add(timestamp: Instant, seconds: INT) -> Result> { + pub fn add(timestamp: Instant, seconds: INT) -> RhaiResultOf { add_impl(timestamp, seconds) } #[rhai_fn(return_raw, name = "+=")] - pub fn add_assign(timestamp: &mut Instant, seconds: INT) -> Result<(), Box> { + pub fn add_assign(timestamp: &mut Instant, seconds: INT) -> RhaiResultOf<()> { *timestamp = add_impl(*timestamp, seconds)?; Ok(()) } #[rhai_fn(return_raw, name = "-")] - pub fn subtract(timestamp: Instant, seconds: INT) -> Result> { + pub fn subtract(timestamp: Instant, seconds: INT) -> RhaiResultOf { subtract_impl(timestamp, seconds) } #[rhai_fn(return_raw, name = "-=")] - pub fn subtract_assign( - timestamp: &mut Instant, - seconds: INT, - ) -> Result<(), Box> { + pub fn subtract_assign(timestamp: &mut Instant, seconds: INT) -> RhaiResultOf<()> { *timestamp = subtract_impl(*timestamp, seconds)?; Ok(()) } diff --git a/src/parser.rs b/src/parser.rs index e2dd2162..6190de72 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -8,7 +8,7 @@ use crate::ast::{ use crate::custom_syntax::{markers::*, CustomSyntax}; use crate::engine::{Precedence, KEYWORD_THIS, OP_CONTAINS}; use crate::func::hashing::get_hasher; -use crate::module::NamespaceRef; +use crate::module::Namespace; use crate::tokenizer::{ is_keyword_function, is_valid_function_name, is_valid_identifier, Token, TokenStream, TokenizerControl, @@ -28,9 +28,11 @@ use std::{ ops::AddAssign, }; +pub type ParseResult = Result; + type PERR = ParseErrorType; -type FunctionsLib = BTreeMap>; +type FnLib = BTreeMap>; /// Invalid variable name that acts as a search barrier in a [`Scope`]. const SCOPE_SEARCH_BARRIER_MARKER: &str = "$BARRIER$"; @@ -258,10 +260,7 @@ impl ParseSettings { /// Make sure that the current level of expression nesting is within the maximum limit. #[cfg(not(feature = "unchecked"))] #[inline] - pub fn ensure_level_within_max_limit( - &self, - limit: Option, - ) -> Result<(), ParseError> { + pub fn ensure_level_within_max_limit(&self, limit: Option) -> ParseResult<()> { if let Some(limit) = limit { if self.level > limit.get() { return Err(PERR::ExprTooDeep.into_err(self.pos)); @@ -296,7 +295,7 @@ impl Expr { } } /// Raise an error if the expression can never yield a boolean value. - fn ensure_bool_expr(self) -> Result { + fn ensure_bool_expr(self) -> ParseResult { let type_name = match self { Expr::Unit(_) => "()", Expr::DynamicConstant(ref v, _) if !v.is::() => v.type_name(), @@ -317,7 +316,7 @@ impl Expr { ) } /// Raise an error if the expression can never yield an iterable value. - fn ensure_iterable(self) -> Result { + fn ensure_iterable(self) -> ParseResult { let type_name = match self { Expr::Unit(_) => "()", Expr::BoolConstant(_, _) => "a boolean", @@ -340,10 +339,7 @@ impl Expr { /// Make sure that the next expression is not a statement expression (i.e. wrapped in `{}`). #[inline] -fn ensure_not_statement_expr( - input: &mut TokenStream, - type_name: impl ToString, -) -> Result<(), ParseError> { +fn ensure_not_statement_expr(input: &mut TokenStream, type_name: impl ToString) -> ParseResult<()> { match input.peek().expect(NEVER_ENDS) { (Token::LeftBrace, pos) => Err(PERR::ExprExpected(type_name.to_string()).into_err(*pos)), _ => Ok(()), @@ -352,7 +348,7 @@ fn ensure_not_statement_expr( /// Make sure that the next expression is not a mis-typed assignment (i.e. `a = b` instead of `a == b`). #[inline] -fn ensure_not_assignment(input: &mut TokenStream) -> Result<(), ParseError> { +fn ensure_not_assignment(input: &mut TokenStream) -> ParseResult<()> { match input.peek().expect(NEVER_ENDS) { (Token::Equals, pos) => Err(LexError::ImproperSymbol( "=".to_string(), @@ -395,7 +391,7 @@ fn match_token(input: &mut TokenStream, token: Token) -> (bool, Position) { } /// Parse a variable name. -fn parse_var_name(input: &mut TokenStream) -> Result<(Box, Position), ParseError> { +fn parse_var_name(input: &mut TokenStream) -> ParseResult<(Box, Position)> { match input.next().expect(NEVER_ENDS) { // Variable name (Token::Identifier(s), pos) => Ok((s, pos)), @@ -411,7 +407,7 @@ fn parse_var_name(input: &mut TokenStream) -> Result<(Box, Position), Parse } /// Parse a symbol. -fn parse_symbol(input: &mut TokenStream) -> Result<(Box, Position), ParseError> { +fn parse_symbol(input: &mut TokenStream) -> ParseResult<(Box, Position)> { match input.next().expect(NEVER_ENDS) { // Symbol (token, pos) if token.is_standard_symbol() => Ok((token.literal_syntax().into(), pos)), @@ -428,9 +424,9 @@ fn parse_symbol(input: &mut TokenStream) -> Result<(Box, Position), ParseEr fn parse_paren_expr( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -462,12 +458,12 @@ fn parse_paren_expr( fn parse_fn_call( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, id: Identifier, capture_parent_scope: bool, - namespace: Option, + namespace: Option, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -625,10 +621,10 @@ fn parse_fn_call( fn parse_index_chain( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, lhs: Expr, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -789,9 +785,9 @@ fn parse_index_chain( fn parse_array_literal( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -862,9 +858,9 @@ fn parse_array_literal( fn parse_map_literal( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -979,9 +975,9 @@ fn parse_map_literal( fn parse_switch( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -1164,9 +1160,9 @@ fn parse_switch( fn parse_primary( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -1258,7 +1254,7 @@ fn parse_primary( #[cfg(not(feature = "no_closure"))] new_state.external_vars.iter().try_for_each( - |(captured_var, &pos)| -> Result<_, ParseError> { + |(captured_var, &pos)| -> ParseResult<_> { let index = state.access_var(captured_var, pos); if !settings.is_closure && settings.strict_var && index.is_none() { @@ -1456,10 +1452,10 @@ fn parse_primary( fn parse_postfix( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, mut lhs: Expr, settings: ParseSettings, -) -> Result { +) -> ParseResult { let mut settings = settings; // Tail processing all possible postfix operators @@ -1522,7 +1518,7 @@ fn parse_postfix( if let Some((ref mut namespace, _)) = namespace { namespace.push(var_name_def); } else { - let mut ns = NamespaceRef::new(); + let mut ns = Namespace::new(); ns.push(var_name_def); namespace = Some((ns, 42)); } @@ -1607,9 +1603,9 @@ fn parse_postfix( fn parse_unary( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -1712,7 +1708,7 @@ fn make_assignment_stmt( lhs: Expr, rhs: Expr, op_pos: Position, -) -> Result { +) -> ParseResult { #[must_use] fn check_lvalue(expr: &Expr, parent_is_dot: bool) -> Option { match expr { @@ -1808,10 +1804,10 @@ fn make_assignment_stmt( fn parse_op_assignment_stmt( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, lhs: Expr, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -1842,7 +1838,7 @@ fn make_dot_expr( terminate_chaining: bool, rhs: Expr, op_pos: Position, -) -> Result { +) -> ParseResult { match (lhs, rhs) { // lhs[idx_expr].rhs (Expr::Index(mut x, term, pos), rhs) => { @@ -1956,11 +1952,11 @@ fn make_dot_expr( fn parse_binary_op( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, parent_precedence: Option, lhs: Expr, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2119,12 +2115,12 @@ fn parse_binary_op( fn parse_custom_syntax( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, key: impl Into, syntax: &CustomSyntax, pos: Position, -) -> Result { +) -> ParseResult { let mut settings = settings; let mut inputs = StaticVec::::new(); let mut segments = StaticVec::new_const(); @@ -2294,9 +2290,9 @@ fn parse_custom_syntax( fn parse_expr( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2313,9 +2309,9 @@ fn parse_expr( fn parse_if( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2353,9 +2349,9 @@ fn parse_if( fn parse_while_loop( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2384,9 +2380,9 @@ fn parse_while_loop( fn parse_do( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2427,9 +2423,9 @@ fn parse_do( fn parse_for( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2518,11 +2514,11 @@ fn parse_for( fn parse_let( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, var_type: AccessMode, is_export: bool, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2573,9 +2569,9 @@ fn parse_let( fn parse_import( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2608,9 +2604,9 @@ fn parse_import( fn parse_export( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2681,9 +2677,9 @@ fn parse_export( fn parse_block( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2783,9 +2779,9 @@ fn parse_block( fn parse_expr_stmt( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -2801,9 +2797,9 @@ fn parse_expr_stmt( fn parse_stmt( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { use AccessMode::{ReadOnly, ReadWrite}; let mut settings = settings; @@ -3015,9 +3011,9 @@ fn parse_stmt( fn parse_try_catch( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -3077,13 +3073,13 @@ fn parse_try_catch( fn parse_fn( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, access: crate::FnAccess, settings: ParseSettings, #[cfg(not(feature = "no_function"))] #[cfg(feature = "metadata")] comments: Vec>, -) -> Result { +) -> ParseResult { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -3222,9 +3218,9 @@ fn make_curry_from_externals( fn parse_anon_fn( input: &mut TokenStream, state: &mut ParseState, - lib: &mut FunctionsLib, + lib: &mut FnLib, settings: ParseSettings, -) -> Result<(Expr, ScriptFnDef), ParseError> { +) -> ParseResult<(Expr, ScriptFnDef)> { #[cfg(not(feature = "unchecked"))] settings.ensure_level_within_max_limit(state.max_expr_depth)?; @@ -3332,7 +3328,7 @@ impl Engine { state: &mut ParseState, scope: &Scope, #[cfg(not(feature = "no_optimize"))] optimization_level: crate::OptimizationLevel, - ) -> Result { + ) -> ParseResult { let _scope = scope; let mut functions = BTreeMap::new(); @@ -3392,7 +3388,7 @@ impl Engine { &self, input: &mut TokenStream, state: &mut ParseState, - ) -> Result<(StaticVec, StaticVec>), ParseError> { + ) -> ParseResult<(StaticVec, StaticVec>)> { let mut statements = StaticVec::new_const(); let mut functions = BTreeMap::new(); @@ -3462,7 +3458,7 @@ impl Engine { state: &mut ParseState, scope: &Scope, #[cfg(not(feature = "no_optimize"))] optimization_level: crate::OptimizationLevel, - ) -> Result { + ) -> ParseResult { let _scope = scope; let (statements, _lib) = self.parse_global_level(input, state)?; diff --git a/src/serde/de.rs b/src/serde/de.rs index bd055ce0..04ac5681 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -1,8 +1,8 @@ //! Implement deserialization support of [`Dynamic`][crate::Dynamic] for [`serde`]. use crate::types::dynamic::Union; -use crate::{Dynamic, EvalAltResult, ImmutableString, LexError, Position}; -use serde::de::{DeserializeSeed, Error, IntoDeserializer, Visitor}; +use crate::{Dynamic, EvalAltResult, ImmutableString, LexError, Position, RhaiError, RhaiResultOf}; +use serde::de::{Error, IntoDeserializer, Visitor}; use serde::{Deserialize, Deserializer}; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -26,11 +26,11 @@ impl<'de> DynamicDeserializer<'de> { Self { value } } /// Shortcut for a type conversion error. - fn type_error(&self) -> Result> { + fn type_error(&self) -> RhaiResultOf { self.type_error_str(type_name::()) } /// Shortcut for a type conversion error. - fn type_error_str(&self, error: &str) -> Result> { + fn type_error_str(&self, error: &str) -> RhaiResultOf { Err(EvalAltResult::ErrorMismatchOutputType( error.into(), self.value.type_name().into(), @@ -42,7 +42,7 @@ impl<'de> DynamicDeserializer<'de> { &mut self, v: crate::INT, visitor: V, - ) -> Result> { + ) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return visitor.visit_i64(v); #[cfg(feature = "only_i32")] @@ -101,13 +101,11 @@ impl<'de> DynamicDeserializer<'de> { /// # Ok(()) /// # } /// ``` -pub fn from_dynamic<'de, T: Deserialize<'de>>( - value: &'de Dynamic, -) -> Result> { +pub fn from_dynamic<'de, T: Deserialize<'de>>(value: &'de Dynamic) -> RhaiResultOf { T::deserialize(&mut DynamicDeserializer::from_dynamic(value)) } -impl Error for Box { +impl Error for RhaiError { fn custom(err: T) -> Self { LexError::ImproperSymbol(String::new(), err.to_string()) .into_err(Position::NONE) @@ -116,9 +114,9 @@ impl Error for Box { } impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { - type Error = Box; + type Error = RhaiError; - fn deserialize_any>(self, visitor: V) -> Result> { + fn deserialize_any>(self, visitor: V) -> RhaiResultOf { match self.value.0 { Union::Unit(_, _, _) => self.deserialize_unit(visitor), Union::Bool(_, _, _) => self.deserialize_bool(visitor), @@ -172,11 +170,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_bool>(self, visitor: V) -> Result> { + fn deserialize_bool>(self, visitor: V) -> RhaiResultOf { visitor.visit_bool(self.value.as_bool().or_else(|_| self.type_error())?) } - fn deserialize_i8>(self, visitor: V) -> Result> { + fn deserialize_i8>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -186,7 +184,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_i16>(self, visitor: V) -> Result> { + fn deserialize_i16>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -196,7 +194,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_i32>(self, visitor: V) -> Result> { + fn deserialize_i32>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else if cfg!(feature = "only_i32") { @@ -208,7 +206,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_i64>(self, visitor: V) -> Result> { + fn deserialize_i64>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else if cfg!(not(feature = "only_i32")) { @@ -220,7 +218,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_i128>(self, visitor: V) -> Result> { + fn deserialize_i128>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else if cfg!(not(feature = "only_i32")) { @@ -232,7 +230,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_u8>(self, visitor: V) -> Result> { + fn deserialize_u8>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -242,7 +240,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_u16>(self, visitor: V) -> Result> { + fn deserialize_u16>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -252,7 +250,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_u32>(self, visitor: V) -> Result> { + fn deserialize_u32>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -262,7 +260,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_u64>(self, visitor: V) -> Result> { + fn deserialize_u64>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -272,7 +270,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_u128>(self, visitor: V) -> Result> { + fn deserialize_u128>(self, visitor: V) -> RhaiResultOf { if let Ok(v) = self.value.as_int() { self.deserialize_int(v, visitor) } else { @@ -282,7 +280,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_f32>(self, _visitor: V) -> Result> { + fn deserialize_f32>(self, _visitor: V) -> RhaiResultOf { #[cfg(not(feature = "no_float"))] return self .value @@ -306,7 +304,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { return self.type_error_str("f32"); } - fn deserialize_f64>(self, _visitor: V) -> Result> { + fn deserialize_f64>(self, _visitor: V) -> RhaiResultOf { #[cfg(not(feature = "no_float"))] return self .value @@ -330,30 +328,24 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { return self.type_error_str("f64"); } - fn deserialize_char>(self, visitor: V) -> Result> { + fn deserialize_char>(self, visitor: V) -> RhaiResultOf { self.value .downcast_ref::() .map_or_else(|| self.type_error(), |&x| visitor.visit_char(x)) } - fn deserialize_str>(self, visitor: V) -> Result> { + fn deserialize_str>(self, visitor: V) -> RhaiResultOf { self.value.downcast_ref::().map_or_else( || self.type_error(), |x| visitor.visit_borrowed_str(x.as_str()), ) } - fn deserialize_string>( - self, - visitor: V, - ) -> Result> { + fn deserialize_string>(self, visitor: V) -> RhaiResultOf { self.deserialize_str(visitor) } - fn deserialize_bytes>( - self, - _visitor: V, - ) -> Result> { + fn deserialize_bytes>(self, _visitor: V) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return self .value @@ -364,17 +356,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { return self.type_error(); } - fn deserialize_byte_buf>( - self, - visitor: V, - ) -> Result> { + fn deserialize_byte_buf>(self, visitor: V) -> RhaiResultOf { self.deserialize_bytes(visitor) } - fn deserialize_option>( - self, - visitor: V, - ) -> Result> { + fn deserialize_option>(self, visitor: V) -> RhaiResultOf { if self.value.is::<()>() { visitor.visit_none() } else { @@ -382,7 +368,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_unit>(self, visitor: V) -> Result> { + fn deserialize_unit>(self, visitor: V) -> RhaiResultOf { self.value .downcast_ref::<()>() .map_or_else(|| self.type_error(), |_| visitor.visit_unit()) @@ -392,7 +378,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { self, _name: &'static str, visitor: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_unit(visitor) } @@ -400,11 +386,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { self, _name: &'static str, visitor: V, - ) -> Result> { + ) -> RhaiResultOf { visitor.visit_newtype_struct(self) } - fn deserialize_seq>(self, _visitor: V) -> Result> { + fn deserialize_seq>(self, _visitor: V) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return self.value.downcast_ref::().map_or_else( || self.type_error(), @@ -415,11 +401,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { return self.type_error(); } - fn deserialize_tuple>( - self, - _len: usize, - visitor: V, - ) -> Result> { + fn deserialize_tuple>(self, _len: usize, visitor: V) -> RhaiResultOf { self.deserialize_seq(visitor) } @@ -428,11 +410,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { _name: &'static str, _len: usize, visitor: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_seq(visitor) } - fn deserialize_map>(self, _visitor: V) -> Result> { + fn deserialize_map>(self, _visitor: V) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] return self.value.downcast_ref::().map_or_else( || self.type_error(), @@ -453,7 +435,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { _name: &'static str, _fields: &'static [&'static str], visitor: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_map(visitor) } @@ -462,7 +444,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { _name: &'static str, _variants: &'static [&'static str], visitor: V, - ) -> Result> { + ) -> RhaiResultOf { if let Some(s) = self.value.read_lock::() { visitor.visit_enum(s.as_str().into_deserializer()) } else { @@ -487,17 +469,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { } } - fn deserialize_identifier>( - self, - visitor: V, - ) -> Result> { + fn deserialize_identifier>(self, visitor: V) -> RhaiResultOf { self.deserialize_str(visitor) } - fn deserialize_ignored_any>( - self, - visitor: V, - ) -> Result> { + fn deserialize_ignored_any>(self, visitor: V) -> RhaiResultOf { self.deserialize_any(visitor) } } @@ -521,12 +497,12 @@ impl<'a, ITER: Iterator> IterateDynamicArray<'a, ITER> { impl<'a: 'de, 'de, ITER: Iterator> serde::de::SeqAccess<'de> for IterateDynamicArray<'a, ITER> { - type Error = Box; + type Error = RhaiError; - fn next_element_seed>( + fn next_element_seed>( &mut self, seed: T, - ) -> Result, Box> { + ) -> RhaiResultOf> { // Deserialize each item coming out of the iterator. match self.iter.next() { None => Ok(None), @@ -568,12 +544,12 @@ where KEYS: Iterator, VALUES: Iterator, { - type Error = Box; + type Error = RhaiError; - fn next_key_seed>( + fn next_key_seed>( &mut self, seed: K, - ) -> Result, Box> { + ) -> RhaiResultOf> { // Deserialize each `Identifier` key coming out of the keys iterator. match self.keys.next() { None => Ok(None), @@ -583,10 +559,10 @@ where } } - fn next_value_seed>( + fn next_value_seed>( &mut self, seed: V, - ) -> Result> { + ) -> RhaiResultOf { // Deserialize each value item coming out of the iterator. seed.deserialize(&mut DynamicDeserializer::from_dynamic( self.values.next().expect("exists"), @@ -602,13 +578,13 @@ struct EnumDeserializer<'t, 'de: 't> { #[cfg(not(feature = "no_object"))] impl<'t, 'de> serde::de::EnumAccess<'de> for EnumDeserializer<'t, 'de> { - type Error = Box; + type Error = RhaiError; type Variant = Self; - fn variant_seed>( + fn variant_seed>( self, seed: V, - ) -> Result<(V::Value, Self::Variant), Self::Error> { + ) -> RhaiResultOf<(V::Value, Self::Variant)> { seed.deserialize(self.tag.into_deserializer()) .map(|v| (v, self)) } @@ -616,24 +592,20 @@ impl<'t, 'de> serde::de::EnumAccess<'de> for EnumDeserializer<'t, 'de> { #[cfg(not(feature = "no_object"))] impl<'t, 'de> serde::de::VariantAccess<'de> for EnumDeserializer<'t, 'de> { - type Error = Box; + type Error = RhaiError; - fn unit_variant(mut self) -> Result<(), Self::Error> { + fn unit_variant(mut self) -> RhaiResultOf<()> { Deserialize::deserialize(&mut self.content) } - fn newtype_variant_seed>( + fn newtype_variant_seed>( mut self, seed: T, - ) -> Result { + ) -> RhaiResultOf { seed.deserialize(&mut self.content) } - fn tuple_variant>( - mut self, - len: usize, - visitor: V, - ) -> Result { + fn tuple_variant>(mut self, len: usize, visitor: V) -> RhaiResultOf { self.content.deserialize_tuple(len, visitor) } @@ -641,7 +613,7 @@ impl<'t, 'de> serde::de::VariantAccess<'de> for EnumDeserializer<'t, 'de> { mut self, fields: &'static [&'static str], visitor: V, - ) -> Result { + ) -> RhaiResultOf { self.content.deserialize_struct("", fields, visitor) } } diff --git a/src/serde/metadata.rs b/src/serde/metadata.rs index f5c5a8dc..ce5f3f3d 100644 --- a/src/serde/metadata.rs +++ b/src/serde/metadata.rs @@ -1,3 +1,5 @@ +//! Serialization of functions metadata. + #![cfg(feature = "metadata")] use crate::module::calc_native_fn_hash; @@ -162,16 +164,9 @@ impl<'a> From<&'a crate::module::FuncInfo> for FnMetadata<'a> { .as_ref() .map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect()) } else { - #[cfg(not(feature = "metadata"))] - { - Vec::new() - } - #[cfg(feature = "metadata")] - { - info.comments - .as_ref() - .map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect()) - } + info.comments + .as_ref() + .map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect()) }, } } @@ -211,7 +206,6 @@ impl<'a> From<&'a crate::Module> for ModuleMetadata<'a> { } } -#[cfg(feature = "metadata")] impl Engine { /// _(metadata)_ Generate a list of all functions (including those defined in an /// [`AST`][crate::AST]) in JSON format. diff --git a/src/serde/ser.rs b/src/serde/ser.rs index b415d8fc..ede8db11 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -1,6 +1,6 @@ //! Implement serialization support of [`Dynamic`][crate::Dynamic] for [`serde`]. -use crate::{Dynamic, EvalAltResult, Position, RhaiResult}; +use crate::{Dynamic, EvalAltResult, Position, RhaiError, RhaiResult, RhaiResultOf}; use serde::ser::{ Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct, }; @@ -81,7 +81,7 @@ pub fn to_dynamic(value: T) -> RhaiResult { value.serialize(&mut s) } -impl Error for Box { +impl Error for RhaiError { fn custom(err: T) -> Self { EvalAltResult::ErrorRuntime(err.to_string().into(), Position::NONE).into() } @@ -89,47 +89,47 @@ impl Error for Box { impl Serializer for &mut DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; type SerializeSeq = DynamicSerializer; type SerializeTuple = DynamicSerializer; type SerializeTupleStruct = DynamicSerializer; #[cfg(not(any(feature = "no_object", feature = "no_index")))] type SerializeTupleVariant = TupleVariantSerializer; #[cfg(any(feature = "no_object", feature = "no_index"))] - type SerializeTupleVariant = serde::ser::Impossible>; + type SerializeTupleVariant = serde::ser::Impossible; type SerializeMap = DynamicSerializer; type SerializeStruct = DynamicSerializer; #[cfg(not(feature = "no_object"))] type SerializeStructVariant = StructVariantSerializer; #[cfg(feature = "no_object")] - type SerializeStructVariant = serde::ser::Impossible>; + type SerializeStructVariant = serde::ser::Impossible; - fn serialize_bool(self, v: bool) -> Result> { + fn serialize_bool(self, v: bool) -> RhaiResultOf { Ok(v.into()) } - fn serialize_i8(self, v: i8) -> Result> { + fn serialize_i8(self, v: i8) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return self.serialize_i64(i64::from(v)); #[cfg(feature = "only_i32")] return self.serialize_i32(i32::from(v)); } - fn serialize_i16(self, v: i16) -> Result> { + fn serialize_i16(self, v: i16) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return self.serialize_i64(i64::from(v)); #[cfg(feature = "only_i32")] return self.serialize_i32(i32::from(v)); } - fn serialize_i32(self, v: i32) -> Result> { + fn serialize_i32(self, v: i32) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return self.serialize_i64(i64::from(v)); #[cfg(feature = "only_i32")] return Ok(v.into()); } - fn serialize_i64(self, v: i64) -> Result> { + fn serialize_i64(self, v: i64) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] { Ok(v.into()) @@ -142,7 +142,7 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_i128(self, v: i128) -> Result> { + fn serialize_i128(self, v: i128) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] if v > i64::MAX as i128 { Ok(Dynamic::from(v)) @@ -157,21 +157,21 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_u8(self, v: u8) -> Result> { + fn serialize_u8(self, v: u8) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return self.serialize_i64(i64::from(v)); #[cfg(feature = "only_i32")] return self.serialize_i32(i32::from(v)); } - fn serialize_u16(self, v: u16) -> Result> { + fn serialize_u16(self, v: u16) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] return self.serialize_i64(i64::from(v)); #[cfg(feature = "only_i32")] return self.serialize_i32(i32::from(v)); } - fn serialize_u32(self, v: u32) -> Result> { + fn serialize_u32(self, v: u32) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] { self.serialize_i64(i64::from(v)) @@ -184,7 +184,7 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_u64(self, v: u64) -> Result> { + fn serialize_u64(self, v: u64) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] if v > i64::MAX as u64 { Ok(Dynamic::from(v)) @@ -199,7 +199,7 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_u128(self, v: u128) -> Result> { + fn serialize_u128(self, v: u128) -> RhaiResultOf { #[cfg(not(feature = "only_i32"))] if v > i64::MAX as u128 { Ok(Dynamic::from(v)) @@ -214,7 +214,7 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_f32(self, v: f32) -> Result> { + fn serialize_f32(self, v: f32) -> RhaiResultOf { #[cfg(any(not(feature = "no_float"), not(feature = "decimal")))] return Ok(Dynamic::from(v)); @@ -230,7 +230,7 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_f64(self, v: f64) -> Result> { + fn serialize_f64(self, v: f64) -> RhaiResultOf { #[cfg(any(not(feature = "no_float"), not(feature = "decimal")))] return Ok(Dynamic::from(v)); @@ -246,15 +246,15 @@ impl Serializer for &mut DynamicSerializer { } } - fn serialize_char(self, v: char) -> Result> { + fn serialize_char(self, v: char) -> RhaiResultOf { Ok(v.into()) } - fn serialize_str(self, v: &str) -> Result> { + fn serialize_str(self, v: &str) -> RhaiResultOf { Ok(v.into()) } - fn serialize_bytes(self, _v: &[u8]) -> Result> { + fn serialize_bytes(self, _v: &[u8]) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return Ok(Dynamic::from_blob(_v.to_vec())); @@ -267,22 +267,19 @@ impl Serializer for &mut DynamicSerializer { .into()); } - fn serialize_none(self) -> Result> { + fn serialize_none(self) -> RhaiResultOf { Ok(Dynamic::UNIT) } - fn serialize_some( - self, - value: &T, - ) -> Result> { + fn serialize_some(self, value: &T) -> RhaiResultOf { value.serialize(&mut *self) } - fn serialize_unit(self) -> Result> { + fn serialize_unit(self) -> RhaiResultOf { Ok(Dynamic::UNIT) } - fn serialize_unit_struct(self, _name: &'static str) -> Result> { + fn serialize_unit_struct(self, _name: &'static str) -> RhaiResultOf { self.serialize_unit() } @@ -291,7 +288,7 @@ impl Serializer for &mut DynamicSerializer { _name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result> { + ) -> RhaiResultOf { self.serialize_str(variant) } @@ -299,7 +296,7 @@ impl Serializer for &mut DynamicSerializer { self, _name: &'static str, value: &T, - ) -> Result> { + ) -> RhaiResultOf { value.serialize(&mut *self) } @@ -309,7 +306,7 @@ impl Serializer for &mut DynamicSerializer { _variant_index: u32, _variant: &'static str, _value: &T, - ) -> Result> { + ) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] { let content = to_dynamic(_value)?; @@ -324,7 +321,7 @@ impl Serializer for &mut DynamicSerializer { .into()); } - fn serialize_seq(self, _len: Option) -> Result> { + fn serialize_seq(self, _len: Option) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return Ok(DynamicSerializer::new(crate::Array::new().into())); #[cfg(feature = "no_index")] @@ -336,7 +333,7 @@ impl Serializer for &mut DynamicSerializer { .into()); } - fn serialize_tuple(self, len: usize) -> Result> { + fn serialize_tuple(self, len: usize) -> RhaiResultOf { self.serialize_seq(Some(len)) } @@ -344,7 +341,7 @@ impl Serializer for &mut DynamicSerializer { self, _name: &'static str, len: usize, - ) -> Result> { + ) -> RhaiResultOf { self.serialize_seq(Some(len)) } @@ -354,7 +351,7 @@ impl Serializer for &mut DynamicSerializer { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result> { + ) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_index"))] return Ok(TupleVariantSerializer { @@ -370,7 +367,7 @@ impl Serializer for &mut DynamicSerializer { .into()); } - fn serialize_map(self, _len: Option) -> Result> { + fn serialize_map(self, _len: Option) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] return Ok(DynamicSerializer::new(crate::Map::new().into())); #[cfg(feature = "no_object")] @@ -386,7 +383,7 @@ impl Serializer for &mut DynamicSerializer { self, _name: &'static str, len: usize, - ) -> Result> { + ) -> RhaiResultOf { self.serialize_map(Some(len)) } @@ -396,7 +393,7 @@ impl Serializer for &mut DynamicSerializer { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result> { + ) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] return Ok(StructVariantSerializer { variant: _variant, @@ -414,12 +411,9 @@ impl Serializer for &mut DynamicSerializer { impl SerializeSeq for DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; - fn serialize_element( - &mut self, - _value: &T, - ) -> Result<(), Box> { + fn serialize_element(&mut self, _value: &T) -> RhaiResultOf<()> { #[cfg(not(feature = "no_index"))] { let _value = _value.serialize(&mut *self)?; @@ -437,7 +431,7 @@ impl SerializeSeq for DynamicSerializer { } // Close the sequence. - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return Ok(self._value); #[cfg(feature = "no_index")] @@ -452,12 +446,9 @@ impl SerializeSeq for DynamicSerializer { impl SerializeTuple for DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; - fn serialize_element( - &mut self, - _value: &T, - ) -> Result<(), Box> { + fn serialize_element(&mut self, _value: &T) -> RhaiResultOf<()> { #[cfg(not(feature = "no_index"))] { let _value = _value.serialize(&mut *self)?; @@ -474,7 +465,7 @@ impl SerializeTuple for DynamicSerializer { .into()); } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return Ok(self._value); #[cfg(feature = "no_index")] @@ -489,12 +480,9 @@ impl SerializeTuple for DynamicSerializer { impl SerializeTupleStruct for DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; - fn serialize_field( - &mut self, - _value: &T, - ) -> Result<(), Box> { + fn serialize_field(&mut self, _value: &T) -> RhaiResultOf<()> { #[cfg(not(feature = "no_index"))] { let _value = _value.serialize(&mut *self)?; @@ -511,7 +499,7 @@ impl SerializeTupleStruct for DynamicSerializer { .into()); } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { #[cfg(not(feature = "no_index"))] return Ok(self._value); #[cfg(feature = "no_index")] @@ -526,9 +514,9 @@ impl SerializeTupleStruct for DynamicSerializer { impl SerializeMap for DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; - fn serialize_key(&mut self, _key: &T) -> Result<(), Box> { + fn serialize_key(&mut self, _key: &T) -> RhaiResultOf<()> { #[cfg(not(feature = "no_object"))] { self._key = _key.serialize(&mut *self)?; @@ -543,10 +531,7 @@ impl SerializeMap for DynamicSerializer { .into()); } - fn serialize_value( - &mut self, - _value: &T, - ) -> Result<(), Box> { + fn serialize_value(&mut self, _value: &T) -> RhaiResultOf<()> { #[cfg(not(feature = "no_object"))] { let key = std::mem::take(&mut self._key) @@ -576,7 +561,7 @@ impl SerializeMap for DynamicSerializer { &mut self, _key: &K, _value: &T, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { #[cfg(not(feature = "no_object"))] { let _key: Dynamic = _key.serialize(&mut *self)?; @@ -597,7 +582,7 @@ impl SerializeMap for DynamicSerializer { .into()); } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] return Ok(self._value); #[cfg(feature = "no_object")] @@ -612,13 +597,13 @@ impl SerializeMap for DynamicSerializer { impl SerializeStruct for DynamicSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; fn serialize_field( &mut self, _key: &'static str, _value: &T, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { #[cfg(not(feature = "no_object"))] { let _value = _value.serialize(&mut *self)?; @@ -635,7 +620,7 @@ impl SerializeStruct for DynamicSerializer { .into()); } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { #[cfg(not(feature = "no_object"))] return Ok(self._value); #[cfg(feature = "no_object")] @@ -657,18 +642,15 @@ struct TupleVariantSerializer { #[cfg(not(any(feature = "no_object", feature = "no_index")))] impl serde::ser::SerializeTupleVariant for TupleVariantSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; - fn serialize_field( - &mut self, - value: &T, - ) -> Result<(), Box> { + fn serialize_field(&mut self, value: &T) -> RhaiResultOf<()> { let value = to_dynamic(value)?; self.array.push(value); Ok(()) } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { make_variant(self.variant, self.array.into()) } } @@ -682,19 +664,19 @@ struct StructVariantSerializer { #[cfg(not(feature = "no_object"))] impl serde::ser::SerializeStructVariant for StructVariantSerializer { type Ok = Dynamic; - type Error = Box; + type Error = RhaiError; fn serialize_field( &mut self, key: &'static str, value: &T, - ) -> Result<(), Box> { + ) -> RhaiResultOf<()> { let value = to_dynamic(value)?; self.map.insert(key.into(), value); Ok(()) } - fn end(self) -> Result> { + fn end(self) -> RhaiResultOf { make_variant(self.variant, self.map.into()) } } diff --git a/src/serde/str.rs b/src/serde/str.rs index 1ad17537..95e26dcc 100644 --- a/src/serde/str.rs +++ b/src/serde/str.rs @@ -1,6 +1,6 @@ //! Implement deserialization support of [`ImmutableString`][crate::ImmutableString] for [`serde`]. -use crate::{EvalAltResult, Position}; +use crate::{EvalAltResult, Position, RhaiError, RhaiResultOf}; use serde::de::{Deserializer, Visitor}; use std::any::type_name; #[cfg(feature = "no_std")] @@ -18,7 +18,7 @@ impl<'a> StringSliceDeserializer<'a> { Self { value } } /// Shortcut for a type conversion error. - fn type_error(&self) -> Result> { + fn type_error(&self) -> RhaiResultOf { Err(EvalAltResult::ErrorMismatchOutputType( type_name::().into(), "string".into(), @@ -29,91 +29,84 @@ impl<'a> StringSliceDeserializer<'a> { } impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> { - type Error = Box; + type Error = RhaiError; - fn deserialize_any>(self, v: V) -> Result> { + fn deserialize_any>(self, v: V) -> RhaiResultOf { self.deserialize_str(v) } - fn deserialize_bool>(self, _: V) -> Result> { + fn deserialize_bool>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_i8>(self, _: V) -> Result> { + fn deserialize_i8>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_i16>(self, _: V) -> Result> { + fn deserialize_i16>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_i32>(self, _: V) -> Result> { + fn deserialize_i32>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_i64>(self, _: V) -> Result> { + fn deserialize_i64>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_u8>(self, _: V) -> Result> { + fn deserialize_u8>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_u16>(self, _: V) -> Result> { + fn deserialize_u16>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_u32>(self, _: V) -> Result> { + fn deserialize_u32>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_u64>(self, _: V) -> Result> { + fn deserialize_u64>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_f32>(self, _: V) -> Result> { + fn deserialize_f32>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_f64>(self, _: V) -> Result> { + fn deserialize_f64>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_char>(self, _: V) -> Result> { + fn deserialize_char>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_str>(self, v: V) -> Result> { + fn deserialize_str>(self, v: V) -> RhaiResultOf { // Only allow deserialization into a string. v.visit_borrowed_str(self.value) } - fn deserialize_string>( - self, - visitor: V, - ) -> Result> { + fn deserialize_string>(self, visitor: V) -> RhaiResultOf { self.deserialize_str(visitor) } - fn deserialize_bytes>(self, _: V) -> Result> { + fn deserialize_bytes>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_byte_buf>(self, _: V) -> Result> { + fn deserialize_byte_buf>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_option>(self, _: V) -> Result> { + fn deserialize_option>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_unit>(self, _: V) -> Result> { + fn deserialize_unit>(self, _: V) -> RhaiResultOf { self.type_error() } fn deserialize_unit_struct>( self, _name: &'static str, v: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_unit(v) } fn deserialize_newtype_struct>( self, _name: &'static str, v: V, - ) -> Result> { + ) -> RhaiResultOf { v.visit_newtype_struct(self) } - fn deserialize_seq>(self, _: V) -> Result> { + fn deserialize_seq>(self, _: V) -> RhaiResultOf { self.type_error() } - fn deserialize_tuple>( - self, - _len: usize, - v: V, - ) -> Result> { + fn deserialize_tuple>(self, _len: usize, v: V) -> RhaiResultOf { self.deserialize_seq(v) } fn deserialize_tuple_struct>( @@ -121,10 +114,10 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> { _name: &'static str, _len: usize, v: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_seq(v) } - fn deserialize_map>(self, _: V) -> Result> { + fn deserialize_map>(self, _: V) -> RhaiResultOf { self.type_error() } fn deserialize_struct>( @@ -132,7 +125,7 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> { _name: &'static str, _fields: &'static [&'static str], v: V, - ) -> Result> { + ) -> RhaiResultOf { self.deserialize_map(v) } fn deserialize_enum>( @@ -140,16 +133,13 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> { _name: &'static str, _variants: &'static [&'static str], _: V, - ) -> Result> { + ) -> RhaiResultOf { self.type_error() } - fn deserialize_identifier>(self, v: V) -> Result> { + fn deserialize_identifier>(self, v: V) -> RhaiResultOf { self.deserialize_str(v) } - fn deserialize_ignored_any>( - self, - v: V, - ) -> Result> { + fn deserialize_ignored_any>(self, v: V) -> RhaiResultOf { self.deserialize_any(v) } } diff --git a/src/types/error.rs b/src/types/error.rs index f38a971c..da636525 100644 --- a/src/types/error.rs +++ b/src/types/error.rs @@ -1,6 +1,6 @@ //! Module containing error definitions for the evaluation process. -use crate::{Dynamic, ImmutableString, ParseErrorType, Position, INT}; +use crate::{Dynamic, ImmutableString, ParseErrorType, Position, INT, RhaiError}; #[cfg(feature = "no_std")] use core_error::Error; #[cfg(not(feature = "no_std"))] @@ -36,12 +36,12 @@ pub enum EvalAltResult { ErrorFunctionNotFound(String, Position), /// An error has occurred inside a called function. /// Wrapped values are the function name, function source, and the interior error. - ErrorInFunctionCall(String, String, Box, Position), + ErrorInFunctionCall(String, String, RhaiError, Position), /// Usage of an unknown [module][crate::Module]. Wrapped value is the [module][crate::Module] name. ErrorModuleNotFound(String, Position), /// An error has occurred while loading a [module][crate::Module]. /// Wrapped value are the [module][crate::Module] name and the interior error. - ErrorInModule(String, Box, Position), + ErrorInModule(String, RhaiError, Position), /// Access to `this` that is not bound. ErrorUnboundThis(Position), /// Data is not of the required type. @@ -222,7 +222,7 @@ impl> From for EvalAltResult { } } -impl> From for Box { +impl> From for RhaiError { #[inline(never)] fn from(err: T) -> Self { EvalAltResult::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE).into() diff --git a/src/types/fn_ptr.rs b/src/types/fn_ptr.rs index 7475b7ef..205c6631 100644 --- a/src/types/fn_ptr.rs +++ b/src/types/fn_ptr.rs @@ -4,7 +4,7 @@ use crate::tokenizer::is_valid_identifier; use crate::types::dynamic::Variant; use crate::{ Dynamic, Engine, EvalAltResult, FuncArgs, Identifier, Module, NativeCallContext, Position, - RhaiResult, StaticVec, AST, + RhaiError, RhaiResult, RhaiResultOf, StaticVec, AST, }; #[cfg(feature = "no_std")] use std::prelude::v1::*; @@ -32,7 +32,7 @@ impl fmt::Debug for FnPtr { impl FnPtr { /// Create a new function pointer. #[inline(always)] - pub fn new(name: impl Into) -> Result> { + pub fn new(name: impl Into) -> RhaiResultOf { name.into().try_into() } /// Create a new function pointer without checking its parameters. @@ -135,7 +135,7 @@ impl FnPtr { engine: &Engine, ast: &AST, args: impl FuncArgs, - ) -> Result> { + ) -> RhaiResultOf { let _ast = ast; let mut arg_values = crate::StaticVec::new_const(); args.parse(&mut arg_values); @@ -176,7 +176,7 @@ impl FnPtr { &self, context: &NativeCallContext, args: impl FuncArgs, - ) -> Result> { + ) -> RhaiResultOf { let mut arg_values = crate::StaticVec::new_const(); args.parse(&mut arg_values); @@ -247,10 +247,10 @@ impl fmt::Display for FnPtr { } impl TryFrom for FnPtr { - type Error = Box; + type Error = RhaiError; #[inline] - fn try_from(value: Identifier) -> Result { + fn try_from(value: Identifier) -> RhaiResultOf { if is_valid_identifier(value.chars()) { Ok(Self(value, StaticVec::new_const())) } else { @@ -260,40 +260,40 @@ impl TryFrom for FnPtr { } impl TryFrom for FnPtr { - type Error = Box; + type Error = RhaiError; #[inline(always)] - fn try_from(value: crate::ImmutableString) -> Result { + fn try_from(value: crate::ImmutableString) -> RhaiResultOf { let s: Identifier = value.into(); Self::try_from(s) } } impl TryFrom for FnPtr { - type Error = Box; + type Error = RhaiError; #[inline(always)] - fn try_from(value: String) -> Result { + fn try_from(value: String) -> RhaiResultOf { let s: Identifier = value.into(); Self::try_from(s) } } impl TryFrom> for FnPtr { - type Error = Box; + type Error = RhaiError; #[inline(always)] - fn try_from(value: Box) -> Result { + fn try_from(value: Box) -> RhaiResultOf { let s: Identifier = value.into(); Self::try_from(s) } } impl TryFrom<&str> for FnPtr { - type Error = Box; + type Error = RhaiError; #[inline(always)] - fn try_from(value: &str) -> Result { + fn try_from(value: &str) -> RhaiResultOf { let s: Identifier = value.into(); Self::try_from(s) } diff --git a/src/types/parse_error.rs b/src/types/parse_error.rs index b1c839f9..3c0870c9 100644 --- a/src/types/parse_error.rs +++ b/src/types/parse_error.rs @@ -1,7 +1,7 @@ //! Module containing error definitions for the parsing process. use crate::tokenizer::is_valid_identifier; -use crate::{EvalAltResult, Position}; +use crate::{EvalAltResult, Position, RhaiError}; #[cfg(feature = "no_std")] use core_error::Error; #[cfg(not(feature = "no_std"))] @@ -310,7 +310,7 @@ impl fmt::Display for ParseError { } } -impl From for Box { +impl From for RhaiError { #[inline(always)] fn from(err: ParseErrorType) -> Self { Box::new(err.into()) @@ -324,7 +324,7 @@ impl From for EvalAltResult { } } -impl From for Box { +impl From for RhaiError { #[inline(always)] fn from(err: ParseError) -> Self { Box::new(err.into())