Use type alias

This commit is contained in:
Stephen Chung 2021-12-25 23:49:14 +08:00
parent 43363e0660
commit 01c35808cb
42 changed files with 538 additions and 702 deletions

View File

@ -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<str>,
args: impl FuncArgs,
) -> Result<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
let mut arg_values = StaticVec::new_const();
args.parse(&mut arg_values);

View File

@ -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<str>) -> Result<AST, ParseError> {
pub fn compile(&self, script: impl AsRef<str>) -> ParseResult<AST> {
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<str>,
) -> Result<AST, ParseError> {
pub fn compile_with_scope(&self, scope: &Scope, script: impl AsRef<str>) -> ParseResult<AST> {
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<str>,
) -> Result<AST, Box<crate::EvalAltResult>> {
) -> RhaiResultOf<AST> {
use crate::{
ast::{ASTNode, Expr, Stmt},
func::native::shared_take_or_clone,
@ -201,7 +197,7 @@ impl Engine {
&self,
scope: &Scope,
scripts: &[impl AsRef<str>],
) -> Result<AST, ParseError> {
) -> ParseResult<AST> {
self.compile_with_scope_and_optimization_level(
scope,
scripts,
@ -222,7 +218,7 @@ impl Engine {
scope: &Scope,
scripts: &[impl AsRef<str>],
#[cfg(not(feature = "no_optimize"))] optimization_level: crate::OptimizationLevel,
) -> Result<AST, ParseError> {
) -> ParseResult<AST> {
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<str>) -> Result<AST, ParseError> {
pub fn compile_expression(&self, script: impl AsRef<str>) -> ParseResult<AST> {
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<str>,
) -> Result<AST, ParseError> {
) -> ParseResult<AST> {
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<str>,
has_null: bool,
) -> Result<crate::Map, Box<crate::EvalAltResult>> {
pub fn parse_json(&self, json: impl AsRef<str>, has_null: bool) -> RhaiResultOf<crate::Map> {
use crate::tokenizer::Token;
fn parse_json_inner(
engine: &Engine,
json: &str,
has_null: bool,
) -> Result<crate::Map, Box<crate::EvalAltResult>> {
) -> RhaiResultOf<crate::Map> {
let mut scope = Scope::new();
let json_text = json.trim_start();
let scripts = if json_text.starts_with(Token::MapStart.literal_syntax()) {

View File

@ -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<EvalAltResult>> {
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<EvalAltResult>> {
) -> 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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<T> From<EvalAltResult> for Result<T, Box<EvalAltResult>> {
impl<T> From<EvalAltResult> for RhaiResultOf<T> {
#[inline(always)]
fn from(err: EvalAltResult) -> Self {
Err(err.into())

View File

@ -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<T: Variant + Clone>(&self, script: &str) -> Result<T, Box<EvalAltResult>> {
pub fn eval<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
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<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
let ast = self.compile_with_scope_and_optimization_level(
scope,
&[script],
@ -84,10 +86,7 @@ impl Engine {
/// # }
/// ```
#[inline(always)]
pub fn eval_expression<T: Variant + Clone>(
&self,
script: &str,
) -> Result<T, Box<EvalAltResult>> {
pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
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<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
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<T: Variant + Clone>(&self, ast: &AST) -> Result<T, Box<EvalAltResult>> {
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> RhaiResultOf<T> {
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<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
let mods = &mut Imports::new();
let result = self.eval_ast_with_scope_raw(scope, mods, ast, 0)?;

View File

@ -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<Option<Dynamic>, Box<EvalAltResult>>
callback: impl Fn(&str, usize, &EvalContext) -> RhaiResultOf<Option<Dynamic>>
+ SendSync
+ 'static,
) -> &mut Self {

View File

@ -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<String, Box<EvalAltResult>> {
fn read_file(path: std::path::PathBuf) -> RhaiResultOf<String> {
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<AST, Box<EvalAltResult>> {
pub fn compile_file(&self, path: std::path::PathBuf) -> RhaiResultOf<AST> {
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<AST, Box<EvalAltResult>> {
) -> RhaiResultOf<AST> {
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<T: Variant + Clone>(
&self,
path: std::path::PathBuf,
) -> Result<T, Box<EvalAltResult>> {
pub fn eval_file<T: Variant + Clone>(&self, path: std::path::PathBuf) -> RhaiResultOf<T> {
Self::read_file(path).and_then(|contents| self.eval::<T>(&contents))
}
/// Evaluate a script file with own scope.
@ -162,7 +159,7 @@ impl Engine {
&self,
scope: &mut Scope,
path: std::path::PathBuf,
) -> Result<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
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<EvalAltResult>> {
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<EvalAltResult>> {
) -> RhaiResultOf<()> {
Self::read_file(path).and_then(|contents| self.run_with_scope(scope, &contents))
}
}

View File

@ -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<N, A, F, R>(&mut self, name: N, func: F) -> &mut Self
where
N: AsRef<str> + Into<Identifier>,
F: RegisterNativeFunction<A, Result<R, Box<EvalAltResult>>>,
F: RegisterNativeFunction<A, RhaiResultOf<R>>,
{
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<T, Box<EvalAltResult>>
+ SendSync
+ 'static,
func: impl Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResultOf<T> + SendSync + 'static,
) -> &mut Self
where
N: AsRef<str> + Into<Identifier>,
@ -383,7 +381,7 @@ impl Engine {
pub fn register_get_result<T: Variant + Clone, V: Variant + Clone>(
&mut self,
name: impl AsRef<str>,
get_fn: impl Fn(&mut T) -> Result<V, Box<EvalAltResult>> + SendSync + 'static,
get_fn: impl Fn(&mut T) -> RhaiResultOf<V> + 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<EvalAltResult>> {
/// fn set_field(&mut self, new_val: i64) -> Result<(), Box<rhai::EvalAltResult>> {
/// self.field = new_val;
/// Ok(())
/// }
@ -478,7 +476,7 @@ impl Engine {
pub fn register_set_result<T: Variant + Clone, V: Variant + Clone>(
&mut self,
name: impl AsRef<str>,
set_fn: impl Fn(&mut T, V) -> Result<(), Box<EvalAltResult>> + 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<V, Box<EvalAltResult>> + SendSync + 'static,
get_fn: impl Fn(&mut T, X) -> RhaiResultOf<V> + SendSync + 'static,
) -> &mut Self {
#[cfg(not(feature = "no_index"))]
if TypeId::of::<T>() == TypeId::of::<crate::Array>() {
@ -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<EvalAltResult>> {
/// fn set_field(&mut self, index: i64, value: i64) -> Result<(), Box<rhai::EvalAltResult>> {
/// 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<EvalAltResult>> + SendSync + 'static,
set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + SendSync + 'static,
) -> &mut Self {
#[cfg(not(feature = "no_index"))]
if TypeId::of::<T>() == TypeId::of::<crate::Array>() {

View File

@ -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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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() {

View File

@ -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<NamespaceRef>,
pub namespace: Option<Namespace>,
/// Function name.
pub name: Identifier,
/// Pre-calculated hashes.
@ -357,11 +357,7 @@ pub enum Expr {
Variable(
Option<NonZeroU8>,
Position,
Box<(
Option<NonZeroUsize>,
Option<(NamespaceRef, u64)>,
Identifier,
)>,
Box<(Option<NonZeroUsize>, Option<(Namespace, u64)>, Identifier)>,
),
/// Property access - ((getter, hash), (setter, hash), prop)
Property(

View File

@ -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<EvalAltResult>> {
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<Shared<Module>> {
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<EvalAltResult>> {
) -> 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<EvalAltResult>> {
) -> 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<OpAssignment>, Position))>,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
) -> 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<ChainArgument>,
size: usize,
level: usize,
) -> Result<(), Box<EvalAltResult>> {
) -> 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<EvalAltResult>> {
|(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<EvalAltResult>> {
|(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<Target<'t>, Box<EvalAltResult>> {
) -> RhaiResultOf<Target<'t>> {
#[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<EvalAltResult>> {
|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<EvalAltResult>> {
|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<EvalAltResult>> {
) -> 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<EvalAltResult>>
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<EvalAltResult>> {
fn check_data_size(&self, _value: &Dynamic) -> RhaiResultOf<()> {
Ok(())
}
#[cfg(not(feature = "unchecked"))]
fn check_data_size(&self, value: &Dynamic) -> Result<(), Box<EvalAltResult>> {
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<EvalAltResult>> {
) -> RhaiResultOf<()> {
*num_operations += 1;
// Guard against too many operations
@ -3459,7 +3459,7 @@ impl Engine {
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][EvalAltResult::ErrorMismatchDataType]`>`.
#[inline]
#[must_use]
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> Box<EvalAltResult> {
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> RhaiError {
EvalAltResult::ErrorMismatchDataType(
self.map_type_name(type_name::<T>()).into(),
typ.into(),

View File

@ -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<fn(NativeCallContext, &mut FnCallArgs) -> RhaiResult> {
pub fn get_builtin_binary_op_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option<FnBuiltin> {
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<fn(NativeCallContext, &mut FnCallArgs) -> RhaiResult> {
pub fn get_builtin_op_assignment_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option<FnBuiltin> {
let type1 = x.type_id();
let type2 = y.type_id();

View File

@ -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<str>,
args: &FnCallArgs,
is_method_call: bool,
) -> Result<(), Box<EvalAltResult>> {
) -> 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<str>,
args: &[&mut Dynamic],
) -> String {
@ -318,7 +317,7 @@ impl Engine {
is_ref_mut: bool,
is_op_assign: bool,
pos: Position,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
) -> 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<EvalAltResult>> {
fn no_method_err(name: &str, pos: Position) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
) -> 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<Dynamic>, Position),
pos: Position,
level: usize,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
) -> 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<EvalAltResult>> {
) -> 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<EvalAltResult>> {
|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<str>,
args_expr: &[Expr],
constants: &[Dynamic],

View File

@ -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<ARGS, RET> {
/// # Ok(())
/// # }
/// ```
fn create_from_script(
self,
script: &str,
entry_point: &str,
) -> Result<Self::Output, ParseError>;
fn create_from_script(self, script: &str, entry_point: &str) -> ParseResult<Self::Output>;
}
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<dyn Fn($($par),*) -> Result<RET, Box<EvalAltResult>> + Send + Sync>;
type Output = Box<dyn Fn($($par),*) -> RhaiResultOf<RET> + Send + Sync>;
#[cfg(not(feature = "sync"))]
type Output = Box<dyn Fn($($par),*) -> Result<RET, Box<EvalAltResult>>>;
type Output = Box<dyn Fn($($par),*) -> RhaiResultOf<RET>>;
#[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<Self::Output, ParseError> {
fn create_from_script(self, script: &str, entry_point: &str) -> ParseResult<Self::Output> {
let ast = self.compile(script)?;
Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point))
}

View File

@ -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<str>,
args: impl FuncArgs,
) -> Result<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
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<Dynamic, Box<EvalAltResult>> {
) -> 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<dyn Iterator<Item = Dynamic>>;
@ -405,12 +408,9 @@ pub type OnParseTokenCallback =
/// A standard callback function for variable access.
#[cfg(not(feature = "sync"))]
pub type OnVarCallback =
Box<dyn Fn(&str, usize, &EvalContext) -> Result<Option<Dynamic>, Box<EvalAltResult>> + 'static>;
Box<dyn Fn(&str, usize, &EvalContext) -> RhaiResultOf<Option<Dynamic>> + 'static>;
/// A standard callback function for variable access.
#[cfg(feature = "sync")]
pub type OnVarCallback = Box<
dyn Fn(&str, usize, &EvalContext) -> Result<Option<Dynamic>, Box<EvalAltResult>>
+ Send
+ Sync
+ 'static,
dyn Fn(&str, usize, &EvalContext) -> RhaiResultOf<Option<Dynamic>> + Send + Sync + 'static,
>;

View File

@ -10,7 +10,7 @@ pub use crate::{
use std::prelude::v1::*;
pub use std::{any::TypeId, mem};
pub type RhaiResult = Result<Dynamic, Box<EvalAltResult>>;
pub type RhaiResult = crate::RhaiResult;
#[cfg(not(features = "no_module"))]
pub use rhai_codegen::*;

View File

@ -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<RET, Box<EvalAltResult>> + SendSync + 'static,
FN: Fn($($param),*) -> RhaiResultOf<RET> + SendSync + 'static,
$($par: Variant + Clone,)*
RET: Variant + Clone
> RegisterNativeFunction<($($mark,)*), Result<RET, Box<EvalAltResult>>> for FN {
> RegisterNativeFunction<($($mark,)*), RhaiResultOf<RET>> 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::<Result<RET, Box<EvalAltResult>>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<Result<RET, Box<EvalAltResult>>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RhaiResultOf<RET>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RhaiResultOf<RET>>() }
#[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<RET, Box<EvalAltResult>> + SendSync + 'static,
FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> RhaiResultOf<RET> + SendSync + 'static,
$($par: Variant + Clone,)*
RET: Variant + Clone
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), Result<RET, Box<EvalAltResult>>> for FN {
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), RhaiResultOf<RET>> 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::<Result<RET, Box<EvalAltResult>>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<Result<RET, Box<EvalAltResult>>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RhaiResultOf<RET>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RhaiResultOf<RET>>() }
#[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()) {

View File

@ -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<EvalAltResult>,
err: RhaiError,
pos: Position,
) -> RhaiResult {
Err(EvalAltResult::ErrorInFunctionCall(

View File

@ -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::<bool>("my_script.rhai".into())?,
//! true
//! );
//! // Evaluate the script, expects a 'bool' return
//! let result = engine.eval_file::<bool>("my_script.rhai".into())?,
//!
//! assert_eq!(result, true);
//!
//! Ok(())
//! }
@ -83,7 +82,12 @@ mod tokenizer;
mod types;
mod r#unsafe;
type RhaiResult = Result<Dynamic, Box<EvalAltResult>>;
/// General evaluation error for Rhai scripts.
type RhaiError = Box<EvalAltResult>;
/// Generic [`Result`] type for Rhai functions.
type RhaiResultOf<T> = Result<T, RhaiError>;
/// General [`Result`] type for Rhai functions returning [`Dynamic`] values.
type RhaiResult = RhaiResultOf<Dynamic>;
/// 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.

View File

@ -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<EvalAltResult>> {
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<T, Box<EvalAltResult>>
/// Ok(orig) // return RhaiResult<T>
/// });
///
/// assert!(module.contains_fn(hash));
@ -935,9 +935,7 @@ impl Module {
where
N: AsRef<str> + Into<Identifier>,
T: Variant + Clone,
F: Fn(NativeCallContext, &mut FnCallArgs) -> Result<T, Box<EvalAltResult>>
+ SendSync
+ 'static,
F: Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResultOf<T> + 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<str> + Into<Identifier>,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: RegisterNativeFunction<ARGS, RhaiResultOf<T>>,
{
self.set_fn(
name,
@ -1015,8 +1013,8 @@ impl Module {
where
A: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
F: RegisterNativeFunction<ARGS, RhaiResultOf<T>>,
F: Fn(&mut A) -> RhaiResultOf<T> + 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<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
F: RegisterNativeFunction<ARGS, RhaiResultOf<()>>,
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<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
F: RegisterNativeFunction<ARGS, RhaiResultOf<T>>,
F: Fn(&mut A, B) -> RhaiResultOf<T> + SendSync + 'static,
{
#[cfg(not(feature = "no_index"))]
if TypeId::of::<A>() == TypeId::of::<crate::Array>() {
@ -1166,8 +1164,8 @@ impl Module {
A: Variant + Clone,
B: Variant + Clone,
C: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B, C) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
F: RegisterNativeFunction<ARGS, RhaiResultOf<()>>,
F: Fn(&mut A, B, C) -> RhaiResultOf<()> + SendSync + 'static,
{
#[cfg(not(feature = "no_index"))]
if TypeId::of::<A>() == TypeId::of::<crate::Array>() {
@ -1231,8 +1229,8 @@ impl Module {
#[inline(always)]
pub fn set_indexer_get_set_fn<A, B, T>(
&mut self,
get_fn: impl Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
set_fn: impl Fn(&mut A, B, T) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
get_fn: impl Fn(&mut A, B) -> RhaiResultOf<T> + 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<Self, Box<EvalAltResult>> {
) -> RhaiResultOf<Self> {
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<NonZeroUsize>,
path: StaticVec<Ident>,
}
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<Ident>;
#[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<Vec<Ident>> for NamespaceRef {
impl From<Vec<Ident>> for Namespace {
#[inline(always)]
fn from(mut path: Vec<Ident>) -> Self {
path.shrink_to_fit();
@ -1862,7 +1860,7 @@ impl From<Vec<Ident>> for NamespaceRef {
}
}
impl From<StaticVec<Ident>> for NamespaceRef {
impl From<StaticVec<Ident>> for Namespace {
#[inline(always)]
fn from(mut path: StaticVec<Ident>) -> Self {
path.shrink_to_fit();
@ -1870,8 +1868,8 @@ impl From<StaticVec<Ident>> for NamespaceRef {
}
}
impl NamespaceRef {
/// Create a new [`NamespaceRef`].
impl Namespace {
/// Create a new [`Namespace`].
#[inline(always)]
#[must_use]
pub const fn new() -> Self {

View File

@ -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<Shared<Module>, Box<EvalAltResult>> {
) -> RhaiResultOf<Shared<Module>> {
for resolver in self.0.iter() {
match resolver.resolve(engine, source_path, path, pos) {
Ok(module) => return Ok(module),

View File

@ -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<Shared<Module>, Box<EvalAltResult>> {
) -> RhaiResultOf<Shared<Module>> {
Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -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<Shared<Module>, Box<EvalAltResult>> {
) -> RhaiResultOf<Shared<Module>> {
// 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<Result<crate::AST, Box<EvalAltResult>>> {
) -> Option<RhaiResultOf<crate::AST>> {
// Construct the script file path
let file_path = self.get_file_path(path, source_path);

View File

@ -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<Shared<Module>, Box<EvalAltResult>>;
) -> RhaiResultOf<Shared<Module>>;
/// 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<Result<AST, Box<EvalAltResult>>> {
) -> Option<RhaiResultOf<AST>> {
None
}
}

View File

@ -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<Shared<Module>, Box<EvalAltResult>> {
) -> RhaiResultOf<Shared<Module>> {
self.0
.get(path)
.cloned()

View File

@ -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<String>) -> Box<EvalAltResult> {
pub fn make_err(msg: impl Into<String>) -> 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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<EvalAltResult>> {
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<INT, Box<EvalAltResult>> {
pub fn sign(x: f32) -> RhaiResultOf<INT> {
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<f32, Box<EvalAltResult>> {
pub fn pow_f_i(x: f32, y: INT) -> RhaiResultOf<f32> {
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<INT, Box<EvalAltResult>> {
pub fn sign(x: f64) -> RhaiResultOf<INT> {
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<Decimal, Box<EvalAltResult>> {
pub fn add(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn subtract(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn multiply(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn divide(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn modulo(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn power(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) {
x.checked_powd(y)
.ok_or_else(|| make_err(format!("Exponential overflow: {} + {}", x, y)))

View File

@ -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<EvalAltResult>> {
) -> 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<Array, Box<EvalAltResult>> {
pub fn map(ctx: NativeCallContext, array: &mut Array, mapper: FnPtr) -> RhaiResultOf<Array> {
if array.is_empty() {
return Ok(array.clone());
}
@ -304,7 +300,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
mapper: &str,
) -> Result<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
map(ctx, array, FnPtr::new(mapper)?)
}
@ -313,7 +309,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: FnPtr,
) -> Result<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
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<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
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<bool, Box<EvalAltResult>> {
) -> RhaiResultOf<bool> {
if array.is_empty() {
return Ok(false);
}
@ -396,7 +392,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
value: Dynamic,
) -> Result<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
if array.is_empty() {
Ok(-1)
} else {
@ -409,7 +405,7 @@ pub mod array_functions {
array: &mut Array,
value: Dynamic,
start: INT,
) -> Result<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
if array.is_empty() {
return Ok(-1);
}
@ -455,7 +451,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: &str,
) -> Result<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
if array.is_empty() {
Ok(-1)
} else {
@ -476,7 +472,7 @@ pub mod array_functions {
array: &mut Array,
filter: FnPtr,
start: INT,
) -> Result<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
if array.is_empty() {
return Ok(-1);
}
@ -526,15 +522,11 @@ pub mod array_functions {
array: &mut Array,
filter: &str,
start: INT,
) -> Result<INT, Box<EvalAltResult>> {
) -> RhaiResultOf<INT> {
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<bool, Box<EvalAltResult>> {
pub fn some(ctx: NativeCallContext, array: &mut Array, filter: FnPtr) -> RhaiResultOf<bool> {
if array.is_empty() {
return Ok(false);
}
@ -572,15 +564,11 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: &str,
) -> Result<bool, Box<EvalAltResult>> {
) -> RhaiResultOf<bool> {
some(ctx, array, FnPtr::new(filter)?)
}
#[rhai_fn(return_raw, pure)]
pub fn all(
ctx: NativeCallContext,
array: &mut Array,
filter: FnPtr,
) -> Result<bool, Box<EvalAltResult>> {
pub fn all(ctx: NativeCallContext, array: &mut Array, filter: FnPtr) -> RhaiResultOf<bool> {
if array.is_empty() {
return Ok(true);
}
@ -618,11 +606,11 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: &str,
) -> Result<bool, Box<EvalAltResult>> {
) -> RhaiResultOf<bool> {
all(ctx, array, FnPtr::new(filter)?)
}
#[rhai_fn(return_raw)]
pub fn dedup(ctx: NativeCallContext, array: &mut Array) -> Result<(), Box<EvalAltResult>> {
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<EvalAltResult>> {
) -> RhaiResultOf<()> {
if array.is_empty() {
return Ok(());
}
@ -650,15 +638,11 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
comparer: &str,
) -> Result<(), Box<EvalAltResult>> {
) -> 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<Dynamic, Box<EvalAltResult>> {
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<Dynamic, Box<EvalAltResult>> {
) -> 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<Dynamic, Box<EvalAltResult>> {
) -> RhaiResult {
if array.is_empty() {
return Ok(initial);
}
@ -713,15 +697,11 @@ pub mod array_functions {
array: &mut Array,
reducer: &str,
initial: Dynamic,
) -> Result<Dynamic, Box<EvalAltResult>> {
) -> 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<Dynamic, Box<EvalAltResult>> {
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<Dynamic, Box<EvalAltResult>> {
) -> 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<Dynamic, Box<EvalAltResult>> {
) -> RhaiResult {
if array.is_empty() {
return Ok(initial);
}
@ -777,7 +757,7 @@ pub mod array_functions {
array: &mut Array,
reducer: &str,
initial: Dynamic,
) -> Result<Dynamic, Box<EvalAltResult>> {
) -> 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<EvalAltResult>> {
) -> RhaiResultOf<()> {
sort(ctx, array, FnPtr::new(comparer)?)
}
#[rhai_fn(return_raw)]
pub fn sort(
ctx: NativeCallContext,
array: &mut Array,
comparer: FnPtr,
) -> Result<(), Box<EvalAltResult>> {
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<EvalAltResult>> {
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<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
if array.is_empty() {
return Ok(Array::new());
}
@ -938,7 +914,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: &str,
) -> Result<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
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<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
if array.is_empty() {
return Ok(Array::new());
}
@ -1032,7 +1008,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array: &mut Array,
filter: &str,
) -> Result<Array, Box<EvalAltResult>> {
) -> RhaiResultOf<Array> {
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<bool, Box<EvalAltResult>> {
) -> RhaiResultOf<bool> {
if array1.len() != array2.len() {
return Ok(false);
}
@ -1122,7 +1098,7 @@ pub mod array_functions {
ctx: NativeCallContext,
array1: &mut Array,
array2: Array,
) -> Result<bool, Box<EvalAltResult>> {
) -> RhaiResultOf<bool> {
equals(ctx, array1, array2).map(|r| !r)
}
}

View File

@ -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<Blob, Box<EvalAltResult>> {
pub fn blob_with_capacity(ctx: NativeCallContext, len: INT) -> RhaiResultOf<Blob> {
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<Blob, Box<EvalAltResult>> {
) -> RhaiResultOf<Blob> {
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<EvalAltResult>> {
) -> RhaiResultOf<()> {
if len <= 0 {
return Ok(());
}

View File

@ -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<T> StepRange<T>
where
T: Variant + Copy + PartialOrd + Add<Output = T> + Sub<Output = T>,
{
pub fn new(from: T, to: T, step: T) -> Result<Self, Box<EvalAltResult>> {
pub fn new(from: T, to: T, step: T) -> RhaiResultOf<Self> {
#[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::<INT>() * 8;
impl BitRange {
pub fn new(value: INT, from: INT, len: INT) -> Result<Self, Box<EvalAltResult>> {
pub fn new(value: INT, from: INT, len: INT) -> RhaiResultOf<Self> {
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<Self, Box<EvalAltResult>> {
pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> RhaiResultOf<Self> {
#[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<Self, Box<EvalAltResult>> {
pub fn new(from: Decimal, to: Decimal, step: Decimal) -> RhaiResultOf<Self> {
#[cfg(not(feature = "unchecked"))]
if step.is_zero() {
return Err(EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(),

View File

@ -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<EvalAltResult>> {
pub fn set_tag(value: &mut Dynamic, tag: INT) -> RhaiResultOf<()> {
if tag < Tag::MIN as INT {
Err(EvalAltResult::ErrorArithmetic(
format!(

View File

@ -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::<INT>() * 8;
#[rhai_fn(return_raw)]
pub fn get_bit(value: INT, index: INT) -> Result<bool, Box<EvalAltResult>> {
pub fn get_bit(value: INT, index: INT) -> RhaiResultOf<bool> {
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<EvalAltResult>> {
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<INT, Box<EvalAltResult>> {
pub fn get_bits_range(value: INT, range: ExclusiveRange) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
pub fn get_bits_range_inclusive(value: INT, range: InclusiveRange) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
pub fn get_bits(value: INT, index: INT, bits: INT) -> RhaiResultOf<INT> {
if bits < 1 {
return Ok(0);
}
@ -321,7 +318,7 @@ mod bit_field_functions {
value: &mut INT,
range: ExclusiveRange,
new_value: INT,
) -> Result<(), Box<EvalAltResult>> {
) -> 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<EvalAltResult>> {
) -> 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<EvalAltResult>> {
pub fn set_bits(value: &mut INT, index: INT, bits: INT, new_value: INT) -> RhaiResultOf<()> {
if bits < 1 {
return Ok(());
}

View File

@ -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<bool, Box<EvalAltResult>> {
pub fn equals(ctx: NativeCallContext, map1: &mut Map, map2: Map) -> RhaiResultOf<bool> {
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<bool, Box<EvalAltResult>> {
pub fn not_equals(ctx: NativeCallContext, map1: &mut Map, map2: Map) -> RhaiResultOf<bool> {
equals(ctx, map1, map2).map(|r| !r)
}

View File

@ -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<INT, Box<EvalAltResult>> {
pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
pub fn parse_int(string: &str) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> {
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<INT, Box<EvalAltResult>> {
pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> {
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<FLOAT, Box<EvalAltResult>> {
pub fn parse_float(string: &str) -> RhaiResultOf<FLOAT> {
string.trim().parse::<FLOAT>().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<Decimal, Box<EvalAltResult>> {
pub fn parse_float(s: &str) -> RhaiResultOf<Decimal> {
parse_decimal(s)
}
@ -339,12 +339,12 @@ mod decimal_functions {
x.tan()
}
#[rhai_fn(return_raw)]
pub fn sqrt(x: Decimal) -> Result<Decimal, Box<EvalAltResult>> {
pub fn sqrt(x: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn exp(x: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn ln(x: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn log10(x: Decimal) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn round_dp(x: Decimal, dp: INT) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn round_up(x: Decimal, dp: INT) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn round_down(x: Decimal, dp: INT) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn round_half_up(x: Decimal, dp: INT) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn round_half_down(x: Decimal, dp: INT) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn parse_decimal(string: &str) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn f32_to_decimal(x: f32) -> RhaiResultOf<Decimal> {
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<Decimal, Box<EvalAltResult>> {
pub fn f64_to_decimal(x: f64) -> RhaiResultOf<Decimal> {
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<FLOAT, Box<EvalAltResult>> {
pub fn to_float(x: Decimal) -> RhaiResultOf<FLOAT> {
FLOAT::try_from(x).map_err(|_| {
EvalAltResult::ErrorArithmetic(
format!("Cannot convert to floating-point: to_float({})", x),

View File

@ -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<crate::EvalAltResult>> {
) -> RhaiResultOf<()> {
if len <= 0 {
return Ok(());
}
@ -544,7 +544,7 @@ mod string_functions {
string: &mut ImmutableString,
len: INT,
padding: &str,
) -> Result<(), Box<crate::EvalAltResult>> {
) -> RhaiResultOf<()> {
if len <= 0 {
return Ok(());
}

View File

@ -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<Dynamic, Box<EvalAltResult>> {
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<Dynamic, Box<EvalAltResult>> {
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<Instant, Box<EvalAltResult>> {
fn add_impl(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf<Instant> {
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<Instant, Box<EvalAltResult>> {
fn subtract_impl(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf<Instant> {
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<Instant, Box<EvalAltResult>> {
pub fn add(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf<Instant> {
add_impl(timestamp, seconds)
}
#[rhai_fn(return_raw, name = "+=")]
pub fn add_assign(
timestamp: &mut Instant,
seconds: FLOAT,
) -> Result<(), Box<EvalAltResult>> {
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<Instant, Box<EvalAltResult>> {
pub fn subtract(timestamp: Instant, seconds: FLOAT) -> RhaiResultOf<Instant> {
subtract_impl(timestamp, seconds)
}
#[rhai_fn(return_raw, name = "-=")]
pub fn subtract_assign(
timestamp: &mut Instant,
seconds: FLOAT,
) -> Result<(), Box<EvalAltResult>> {
pub fn subtract_assign(timestamp: &mut Instant, seconds: FLOAT) -> RhaiResultOf<()> {
*timestamp = subtract_impl(*timestamp, seconds)?;
Ok(())
}
}
fn add_impl(timestamp: Instant, seconds: INT) -> Result<Instant, Box<EvalAltResult>> {
fn add_impl(timestamp: Instant, seconds: INT) -> RhaiResultOf<Instant> {
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<Instant, Box<EvalAltResult>> {
fn subtract_impl(timestamp: Instant, seconds: INT) -> RhaiResultOf<Instant> {
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<Instant, Box<EvalAltResult>> {
pub fn add(timestamp: Instant, seconds: INT) -> RhaiResultOf<Instant> {
add_impl(timestamp, seconds)
}
#[rhai_fn(return_raw, name = "+=")]
pub fn add_assign(timestamp: &mut Instant, seconds: INT) -> Result<(), Box<EvalAltResult>> {
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<Instant, Box<EvalAltResult>> {
pub fn subtract(timestamp: Instant, seconds: INT) -> RhaiResultOf<Instant> {
subtract_impl(timestamp, seconds)
}
#[rhai_fn(return_raw, name = "-=")]
pub fn subtract_assign(
timestamp: &mut Instant,
seconds: INT,
) -> Result<(), Box<EvalAltResult>> {
pub fn subtract_assign(timestamp: &mut Instant, seconds: INT) -> RhaiResultOf<()> {
*timestamp = subtract_impl(*timestamp, seconds)?;
Ok(())
}

View File

@ -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<T> = Result<T, ParseError>;
type PERR = ParseErrorType;
type FunctionsLib = BTreeMap<u64, Shared<ScriptFnDef>>;
type FnLib = BTreeMap<u64, Shared<ScriptFnDef>>;
/// 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<NonZeroUsize>,
) -> Result<(), ParseError> {
pub fn ensure_level_within_max_limit(&self, limit: Option<NonZeroUsize>) -> 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<Expr, ParseError> {
fn ensure_bool_expr(self) -> ParseResult<Expr> {
let type_name = match self {
Expr::Unit(_) => "()",
Expr::DynamicConstant(ref v, _) if !v.is::<bool>() => 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<Expr, ParseError> {
fn ensure_iterable(self) -> ParseResult<Expr> {
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<str>, Position), ParseError> {
fn parse_var_name(input: &mut TokenStream) -> ParseResult<(Box<str>, 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<str>, Position), Parse
}
/// Parse a symbol.
fn parse_symbol(input: &mut TokenStream) -> Result<(Box<str>, Position), ParseError> {
fn parse_symbol(input: &mut TokenStream) -> ParseResult<(Box<str>, 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<str>, Position), ParseEr
fn parse_paren_expr(
input: &mut TokenStream,
state: &mut ParseState,
lib: &mut FunctionsLib,
lib: &mut FnLib,
settings: ParseSettings,
) -> Result<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<NamespaceRef>,
namespace: Option<Namespace>,
settings: ParseSettings,
) -> Result<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[must_use]
fn check_lvalue(expr: &Expr, parent_is_dot: bool) -> Option<Position> {
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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Expr, ParseError> {
) -> ParseResult<Expr> {
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<Precedence>,
lhs: Expr,
settings: ParseSettings,
) -> Result<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<ImmutableString>,
syntax: &CustomSyntax,
pos: Position,
) -> Result<Expr, ParseError> {
) -> ParseResult<Expr> {
let mut settings = settings;
let mut inputs = StaticVec::<Expr>::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<Expr, ParseError> {
) -> ParseResult<Expr> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
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<Stmt, ParseError> {
) -> ParseResult<Stmt> {
#[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<Box<str>>,
) -> Result<ScriptFnDef, ParseError> {
) -> ParseResult<ScriptFnDef> {
#[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<AST, ParseError> {
) -> ParseResult<AST> {
let _scope = scope;
let mut functions = BTreeMap::new();
@ -3392,7 +3388,7 @@ impl Engine {
&self,
input: &mut TokenStream,
state: &mut ParseState,
) -> Result<(StaticVec<Stmt>, StaticVec<Shared<ScriptFnDef>>), ParseError> {
) -> ParseResult<(StaticVec<Stmt>, StaticVec<Shared<ScriptFnDef>>)> {
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<AST, ParseError> {
) -> ParseResult<AST> {
let _scope = scope;
let (statements, _lib) = self.parse_global_level(input, state)?;

View File

@ -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<T>(&self) -> Result<T, Box<EvalAltResult>> {
fn type_error<T>(&self) -> RhaiResultOf<T> {
self.type_error_str(type_name::<T>())
}
/// Shortcut for a type conversion error.
fn type_error_str<T>(&self, error: &str) -> Result<T, Box<EvalAltResult>> {
fn type_error_str<T>(&self, error: &str) -> RhaiResultOf<T> {
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<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
#[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<T, Box<EvalAltResult>> {
pub fn from_dynamic<'de, T: Deserialize<'de>>(value: &'de Dynamic) -> RhaiResultOf<T> {
T::deserialize(&mut DynamicDeserializer::from_dynamic(value))
}
impl Error for Box<EvalAltResult> {
impl Error for RhaiError {
fn custom<T: fmt::Display>(err: T) -> Self {
LexError::ImproperSymbol(String::new(), err.to_string())
.into_err(Position::NONE)
@ -116,9 +114,9 @@ impl Error for Box<EvalAltResult> {
}
impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
visitor.visit_bool(self.value.as_bool().or_else(|_| self.type_error())?)
}
fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_f32<V: Visitor<'de>>(self, _visitor: V) -> RhaiResultOf<V::Value> {
#[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<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_f64<V: Visitor<'de>>(self, _visitor: V) -> RhaiResultOf<V::Value> {
#[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<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.value
.downcast_ref::<char>()
.map_or_else(|| self.type_error(), |&x| visitor.visit_char(x))
}
fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.value.downcast_ref::<ImmutableString>().map_or_else(
|| self.type_error(),
|x| visitor.visit_borrowed_str(x.as_str()),
)
}
fn deserialize_string<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_str(visitor)
}
fn deserialize_bytes<V: Visitor<'de>>(
self,
_visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_bytes<V: Visitor<'de>>(self, _visitor: V) -> RhaiResultOf<V::Value> {
#[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<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_bytes(visitor)
}
fn deserialize_option<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
if self.value.is::<()>() {
visitor.visit_none()
} else {
@ -382,7 +368,7 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
}
}
fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
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<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.deserialize_unit(visitor)
}
@ -400,11 +386,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
visitor.visit_newtype_struct(self)
}
fn deserialize_seq<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_seq<V: Visitor<'de>>(self, _visitor: V) -> RhaiResultOf<V::Value> {
#[cfg(not(feature = "no_index"))]
return self.value.downcast_ref::<crate::Array>().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<V: Visitor<'de>>(
self,
_len: usize,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_seq(visitor)
}
@ -428,11 +410,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.deserialize_seq(visitor)
}
fn deserialize_map<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_map<V: Visitor<'de>>(self, _visitor: V) -> RhaiResultOf<V::Value> {
#[cfg(not(feature = "no_object"))]
return self.value.downcast_ref::<crate::Map>().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<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
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<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
if let Some(s) = self.value.read_lock::<ImmutableString>() {
visitor.visit_enum(s.as_str().into_deserializer())
} else {
@ -487,17 +469,11 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
}
}
fn deserialize_identifier<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_str(visitor)
}
fn deserialize_ignored_any<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_any(visitor)
}
}
@ -521,12 +497,12 @@ impl<'a, ITER: Iterator<Item = &'a Dynamic>> IterateDynamicArray<'a, ITER> {
impl<'a: 'de, 'de, ITER: Iterator<Item = &'a Dynamic>> serde::de::SeqAccess<'de>
for IterateDynamicArray<'a, ITER>
{
type Error = Box<EvalAltResult>;
type Error = RhaiError;
fn next_element_seed<T: DeserializeSeed<'de>>(
fn next_element_seed<T: serde::de::DeserializeSeed<'de>>(
&mut self,
seed: T,
) -> Result<Option<T::Value>, Box<EvalAltResult>> {
) -> RhaiResultOf<Option<T::Value>> {
// Deserialize each item coming out of the iterator.
match self.iter.next() {
None => Ok(None),
@ -568,12 +544,12 @@ where
KEYS: Iterator<Item = &'a str>,
VALUES: Iterator<Item = &'a Dynamic>,
{
type Error = Box<EvalAltResult>;
type Error = RhaiError;
fn next_key_seed<K: DeserializeSeed<'de>>(
fn next_key_seed<K: serde::de::DeserializeSeed<'de>>(
&mut self,
seed: K,
) -> Result<Option<K::Value>, Box<EvalAltResult>> {
) -> RhaiResultOf<Option<K::Value>> {
// 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<V: DeserializeSeed<'de>>(
fn next_value_seed<V: serde::de::DeserializeSeed<'de>>(
&mut self,
seed: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
// 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<EvalAltResult>;
type Error = RhaiError;
type Variant = Self;
fn variant_seed<V: DeserializeSeed<'de>>(
fn variant_seed<V: serde::de::DeserializeSeed<'de>>(
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<EvalAltResult>;
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<T: DeserializeSeed<'de>>(
fn newtype_variant_seed<T: serde::de::DeserializeSeed<'de>>(
mut self,
seed: T,
) -> Result<T::Value, Self::Error> {
) -> RhaiResultOf<T::Value> {
seed.deserialize(&mut self.content)
}
fn tuple_variant<V: Visitor<'de>>(
mut self,
len: usize,
visitor: V,
) -> Result<V::Value, Self::Error> {
fn tuple_variant<V: Visitor<'de>>(mut self, len: usize, visitor: V) -> RhaiResultOf<V::Value> {
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<V::Value, Self::Error> {
) -> RhaiResultOf<V::Value> {
self.content.deserialize_struct("", fields, visitor)
}
}

View File

@ -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.

View File

@ -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<T: Serialize>(value: T) -> RhaiResult {
value.serialize(&mut s)
}
impl Error for Box<EvalAltResult> {
impl Error for RhaiError {
fn custom<T: fmt::Display>(err: T) -> Self {
EvalAltResult::ErrorRuntime(err.to_string().into(), Position::NONE).into()
}
@ -89,47 +89,47 @@ impl Error for Box<EvalAltResult> {
impl Serializer for &mut DynamicSerializer {
type Ok = Dynamic;
type Error = Box<EvalAltResult>;
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<Dynamic, Box<EvalAltResult>>;
type SerializeTupleVariant = serde::ser::Impossible<Dynamic, RhaiError>;
type SerializeMap = DynamicSerializer;
type SerializeStruct = DynamicSerializer;
#[cfg(not(feature = "no_object"))]
type SerializeStructVariant = StructVariantSerializer;
#[cfg(feature = "no_object")]
type SerializeStructVariant = serde::ser::Impossible<Dynamic, Box<EvalAltResult>>;
type SerializeStructVariant = serde::ser::Impossible<Dynamic, RhaiError>;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_bool(self, v: bool) -> RhaiResultOf<Self::Ok> {
Ok(v.into())
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_i8(self, v: i8) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_i16(self, v: i16) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_i32(self, v: i32) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_i64(self, v: i64) -> RhaiResultOf<Self::Ok> {
#[cfg(not(feature = "only_i32"))]
{
Ok(v.into())
@ -142,7 +142,7 @@ impl Serializer for &mut DynamicSerializer {
}
}
fn serialize_i128(self, v: i128) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_i128(self, v: i128) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_u8(self, v: u8) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_u16(self, v: u16) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_u32(self, v: u32) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_u64(self, v: u64) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_u128(self, v: u128) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_f32(self, v: f32) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_f64(self, v: f64) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_char(self, v: char) -> RhaiResultOf<Self::Ok> {
Ok(v.into())
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_str(self, v: &str) -> RhaiResultOf<Self::Ok> {
Ok(v.into())
}
fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_bytes(self, _v: &[u8]) -> RhaiResultOf<Self::Ok> {
#[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<Self::Ok, Box<EvalAltResult>> {
fn serialize_none(self) -> RhaiResultOf<Self::Ok> {
Ok(Dynamic::UNIT)
}
fn serialize_some<T: ?Sized + Serialize>(
self,
value: &T,
) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> RhaiResultOf<Self::Ok> {
value.serialize(&mut *self)
}
fn serialize_unit(self) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_unit(self) -> RhaiResultOf<Self::Ok> {
Ok(Dynamic::UNIT)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Box<EvalAltResult>> {
fn serialize_unit_struct(self, _name: &'static str) -> RhaiResultOf<Self::Ok> {
self.serialize_unit()
}
@ -291,7 +288,7 @@ impl Serializer for &mut DynamicSerializer {
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::Ok> {
self.serialize_str(variant)
}
@ -299,7 +296,7 @@ impl Serializer for &mut DynamicSerializer {
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::Ok> {
value.serialize(&mut *self)
}
@ -309,7 +306,7 @@ impl Serializer for &mut DynamicSerializer {
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<Self::Ok, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::Ok> {
#[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<usize>) -> Result<Self::SerializeSeq, Box<EvalAltResult>> {
fn serialize_seq(self, _len: Option<usize>) -> RhaiResultOf<Self::SerializeSeq> {
#[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<Self::SerializeTuple, Box<EvalAltResult>> {
fn serialize_tuple(self, len: usize) -> RhaiResultOf<Self::SerializeTuple> {
self.serialize_seq(Some(len))
}
@ -344,7 +341,7 @@ impl Serializer for &mut DynamicSerializer {
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::SerializeTupleStruct> {
self.serialize_seq(Some(len))
}
@ -354,7 +351,7 @@ impl Serializer for &mut DynamicSerializer {
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::SerializeTupleVariant> {
#[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<usize>) -> Result<Self::SerializeMap, Box<EvalAltResult>> {
fn serialize_map(self, _len: Option<usize>) -> RhaiResultOf<Self::SerializeMap> {
#[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<Self::SerializeStruct, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::SerializeStruct> {
self.serialize_map(Some(len))
}
@ -396,7 +393,7 @@ impl Serializer for &mut DynamicSerializer {
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Box<EvalAltResult>> {
) -> RhaiResultOf<Self::SerializeStructVariant> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_element<T: ?Sized + Serialize>(
&mut self,
_value: &T,
) -> Result<(), Box<EvalAltResult>> {
fn serialize_element<T: ?Sized + Serialize>(&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<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_element<T: ?Sized + Serialize>(
&mut self,
_value: &T,
) -> Result<(), Box<EvalAltResult>> {
fn serialize_element<T: ?Sized + Serialize>(&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<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
_value: &T,
) -> Result<(), Box<EvalAltResult>> {
fn serialize_field<T: ?Sized + Serialize>(&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<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<(), Box<EvalAltResult>> {
fn serialize_key<T: ?Sized + Serialize>(&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<T: ?Sized + Serialize>(
&mut self,
_value: &T,
) -> Result<(), Box<EvalAltResult>> {
fn serialize_value<T: ?Sized + Serialize>(&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<EvalAltResult>> {
) -> 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<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
_key: &'static str,
_value: &T,
) -> Result<(), Box<EvalAltResult>> {
) -> 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<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
#[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<EvalAltResult>;
type Error = RhaiError;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
value: &T,
) -> Result<(), Box<EvalAltResult>> {
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> RhaiResultOf<()> {
let value = to_dynamic(value)?;
self.array.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
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<EvalAltResult>;
type Error = RhaiError;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Box<EvalAltResult>> {
) -> RhaiResultOf<()> {
let value = to_dynamic(value)?;
self.map.insert(key.into(), value);
Ok(())
}
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
fn end(self) -> RhaiResultOf<Self::Ok> {
make_variant(self.variant, self.map.into())
}
}

View File

@ -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<T>(&self) -> Result<T, Box<EvalAltResult>> {
fn type_error<T>(&self) -> RhaiResultOf<T> {
Err(EvalAltResult::ErrorMismatchOutputType(
type_name::<T>().into(),
"string".into(),
@ -29,91 +29,84 @@ impl<'a> StringSliceDeserializer<'a> {
}
impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
fn deserialize_any<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_any<V: Visitor<'de>>(self, v: V) -> RhaiResultOf<V::Value> {
self.deserialize_str(v)
}
fn deserialize_bool<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_bool<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_i8<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i8<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_i16<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i16<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_i32<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i32<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_i64<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_i64<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_u8<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u8<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_u16<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u16<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_u32<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u32<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_u64<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_u64<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_f32<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_f32<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_f64<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_f64<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_char<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_char<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_str<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_str<V: Visitor<'de>>(self, v: V) -> RhaiResultOf<V::Value> {
// Only allow deserialization into a string.
v.visit_borrowed_str(self.value)
}
fn deserialize_string<V: Visitor<'de>>(
self,
visitor: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> RhaiResultOf<V::Value> {
self.deserialize_str(visitor)
}
fn deserialize_bytes<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_bytes<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_byte_buf<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_byte_buf<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_option<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_option<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_unit<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_unit<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_unit_struct<V: Visitor<'de>>(
self,
_name: &'static str,
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.deserialize_unit(v)
}
fn deserialize_newtype_struct<V: Visitor<'de>>(
self,
_name: &'static str,
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
v.visit_newtype_struct(self)
}
fn deserialize_seq<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_seq<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_tuple<V: Visitor<'de>>(
self,
_len: usize,
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, v: V) -> RhaiResultOf<V::Value> {
self.deserialize_seq(v)
}
fn deserialize_tuple_struct<V: Visitor<'de>>(
@ -121,10 +114,10 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> {
_name: &'static str,
_len: usize,
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.deserialize_seq(v)
}
fn deserialize_map<V: Visitor<'de>>(self, _: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_map<V: Visitor<'de>>(self, _: V) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_struct<V: Visitor<'de>>(
@ -132,7 +125,7 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> {
_name: &'static str,
_fields: &'static [&'static str],
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.deserialize_map(v)
}
fn deserialize_enum<V: Visitor<'de>>(
@ -140,16 +133,13 @@ impl<'de> Deserializer<'de> for &mut StringSliceDeserializer<'de> {
_name: &'static str,
_variants: &'static [&'static str],
_: V,
) -> Result<V::Value, Box<EvalAltResult>> {
) -> RhaiResultOf<V::Value> {
self.type_error()
}
fn deserialize_identifier<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_identifier<V: Visitor<'de>>(self, v: V) -> RhaiResultOf<V::Value> {
self.deserialize_str(v)
}
fn deserialize_ignored_any<V: Visitor<'de>>(
self,
v: V,
) -> Result<V::Value, Box<EvalAltResult>> {
fn deserialize_ignored_any<V: Visitor<'de>>(self, v: V) -> RhaiResultOf<V::Value> {
self.deserialize_any(v)
}
}

View File

@ -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<EvalAltResult>, 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<EvalAltResult>, 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<T: AsRef<str>> From<T> for EvalAltResult {
}
}
impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
impl<T: AsRef<str>> From<T> for RhaiError {
#[inline(never)]
fn from(err: T) -> Self {
EvalAltResult::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE).into()

View File

@ -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<Identifier>) -> Result<Self, Box<EvalAltResult>> {
pub fn new(name: impl Into<Identifier>) -> RhaiResultOf<Self> {
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<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
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<T, Box<EvalAltResult>> {
) -> RhaiResultOf<T> {
let mut arg_values = crate::StaticVec::new_const();
args.parse(&mut arg_values);
@ -247,10 +247,10 @@ impl fmt::Display for FnPtr {
}
impl TryFrom<Identifier> for FnPtr {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
#[inline]
fn try_from(value: Identifier) -> Result<Self, Self::Error> {
fn try_from(value: Identifier) -> RhaiResultOf<Self> {
if is_valid_identifier(value.chars()) {
Ok(Self(value, StaticVec::new_const()))
} else {
@ -260,40 +260,40 @@ impl TryFrom<Identifier> for FnPtr {
}
impl TryFrom<crate::ImmutableString> for FnPtr {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
#[inline(always)]
fn try_from(value: crate::ImmutableString) -> Result<Self, Self::Error> {
fn try_from(value: crate::ImmutableString) -> RhaiResultOf<Self> {
let s: Identifier = value.into();
Self::try_from(s)
}
}
impl TryFrom<String> for FnPtr {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
#[inline(always)]
fn try_from(value: String) -> Result<Self, Self::Error> {
fn try_from(value: String) -> RhaiResultOf<Self> {
let s: Identifier = value.into();
Self::try_from(s)
}
}
impl TryFrom<Box<str>> for FnPtr {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
#[inline(always)]
fn try_from(value: Box<str>) -> Result<Self, Self::Error> {
fn try_from(value: Box<str>) -> RhaiResultOf<Self> {
let s: Identifier = value.into();
Self::try_from(s)
}
}
impl TryFrom<&str> for FnPtr {
type Error = Box<EvalAltResult>;
type Error = RhaiError;
#[inline(always)]
fn try_from(value: &str) -> Result<Self, Self::Error> {
fn try_from(value: &str) -> RhaiResultOf<Self> {
let s: Identifier = value.into();
Self::try_from(s)
}

View File

@ -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<ParseErrorType> for Box<EvalAltResult> {
impl From<ParseErrorType> for RhaiError {
#[inline(always)]
fn from(err: ParseErrorType) -> Self {
Box::new(err.into())
@ -324,7 +324,7 @@ impl From<ParseErrorType> for EvalAltResult {
}
}
impl From<ParseError> for Box<EvalAltResult> {
impl From<ParseError> for RhaiError {
#[inline(always)]
fn from(err: ParseError) -> Self {
Box::new(err.into())