Deprecate From<EvalAltResult> for Result<T, Box<EvalAltResult>> because it is clearer for code to explicitly wrap errors in Err.

This commit is contained in:
Stephen Chung 2021-10-19 23:52:58 +08:00
parent 6d31bb0d19
commit 3001e90775
23 changed files with 226 additions and 193 deletions

View File

@ -7,9 +7,14 @@ Version 1.2.0
Enhancements Enhancements
------------ ------------
* `NativeCallContext::call_fn_dynamic_raw` is deprecated and `NativeCallContext::call_fn_raw` is added.
* Array methods now avoid cloning as much as possible (although most predicates will involve cloning anyway if passed a closure). * Array methods now avoid cloning as much as possible (although most predicates will involve cloning anyway if passed a closure).
* Inlining is disabled for error-path functions because, most of the time, the script fails completely when an error is encountered. * Inlining is disabled for error-path functions because errors are exceptional and scripts usually fail completely when an error is encountered.
Deprecated API's
----------------
* `NativeCallContext::call_fn_dynamic_raw` is deprecated and `NativeCallContext::call_fn_raw` is added.
* `From<EvalAltResult>` for `Result<T, Box<EvalAltResult>>` is deprecated so it will no longer be possible to do `EvalAltResult::ErrorXXXXX.into()` to convert to a `Result`; instead, `Err(EvalAltResult:ErrorXXXXX.into())` must be used. Code is clearer if errors are explicitly wrapped in `Err`.
Version 1.1.0 Version 1.1.0

View File

@ -1,6 +1,6 @@
[package] [package]
name = "rhai_codegen" name = "rhai_codegen"
version = "1.1.0" version = "1.1.1"
edition = "2018" edition = "2018"
authors = ["jhwgh1968", "Stephen Chung"] authors = ["jhwgh1968", "Stephen Chung"]
description = "Procedural macros support package for Rhai, a scripting language and engine for Rust" description = "Procedural macros support package for Rhai, a scripting language and engine for Rust"
@ -16,7 +16,7 @@ default = []
metadata = [] metadata = []
[dev-dependencies] [dev-dependencies]
rhai = { path = "..", version = "1" } rhai = { path = "..", version = "1.1" }
trybuild = "1" trybuild = "1"
[dependencies] [dependencies]

View File

@ -696,7 +696,7 @@ impl ExportedFn {
unpack_statements.push( unpack_statements.push(
syn::parse2::<syn::Stmt>(quote! { syn::parse2::<syn::Stmt>(quote! {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant(#arg_lit_str.to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant(#arg_lit_str.to_string(), Position::NONE).into());
} }
}) })
.unwrap(), .unwrap(),

View File

@ -486,7 +486,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<usize>(); let arg1 = mem::take(args[1usize]).cast::<usize>();
let arg0 = &mut args[0usize].write_lock::<usize>().unwrap(); let arg0 = &mut args[0usize].write_lock::<usize>().unwrap();

View File

@ -1096,7 +1096,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap(); let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0))) Ok(Dynamic::from(increment(arg0)))
@ -1155,7 +1155,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap(); let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0))) Ok(Dynamic::from(increment(arg0)))
@ -1235,7 +1235,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap(); let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0))) Ok(Dynamic::from(increment(arg0)))
@ -1316,7 +1316,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap(); let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
Ok(Dynamic::from(int_foo(arg0))) Ok(Dynamic::from(int_foo(arg0)))
@ -1376,7 +1376,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap(); let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
Ok(Dynamic::from(int_foo(arg0))) Ok(Dynamic::from(int_foo(arg0)))
@ -1433,7 +1433,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap(); let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
@ -1494,7 +1494,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap(); let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
@ -1552,7 +1552,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap(); let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap();
@ -1613,7 +1613,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap(); let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap();
@ -1671,7 +1671,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg2 = mem::take(args[2usize]).cast::<FLOAT>(); let arg2 = mem::take(args[2usize]).cast::<FLOAT>();
@ -1733,7 +1733,7 @@ mod generate_tests {
#[inline(always)] #[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult { fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() { if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
} }
let arg1 = mem::take(args[1usize]).cast::<u64>(); let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg2 = mem::take(args[2usize]).cast::<FLOAT>(); let arg2 = mem::take(args[2usize]).cast::<FLOAT>();

View File

@ -168,3 +168,12 @@ impl NativeCallContext<'_> {
self.call_fn_raw(fn_name.as_ref(), is_method_call, is_method_call, args) self.call_fn_raw(fn_name.as_ref(), is_method_call, is_method_call, args)
} }
} }
#[allow(useless_deprecated)]
#[deprecated(since = "1.2.0", note = "explicitly wrap `EvalAltResult` in `Err`")]
impl<T> From<EvalAltResult> for Result<T, Box<EvalAltResult>> {
#[inline(always)]
fn from(err: EvalAltResult) -> Self {
Err(err.into())
}
}

View File

@ -1221,7 +1221,7 @@ impl Engine {
return if let Some(val) = this_ptr { return if let Some(val) = this_ptr {
Ok(((*val).into(), *pos)) Ok(((*val).into(), *pos))
} else { } else {
EvalAltResult::ErrorUnboundThis(*pos).into() Err(EvalAltResult::ErrorUnboundThis(*pos).into())
} }
} }
_ if state.always_search_scope => (0, expr.position()), _ if state.always_search_scope => (0, expr.position()),
@ -1723,7 +1723,7 @@ impl Engine {
} }
} }
// Syntax error // Syntax error
_ => EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into(), _ => Err(EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into()),
} }
} }
} }
@ -1958,12 +1958,11 @@ impl Engine {
arr_len arr_len
- index - index
.checked_abs() .checked_abs()
.ok_or_else(|| { .ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into()
})
.and_then(|n| { .and_then(|n| {
if n as usize > arr_len { if n as usize > arr_len {
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into() Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
.into())
} else { } else {
Ok(n as usize) Ok(n as usize)
} }
@ -2014,7 +2013,9 @@ impl Engine {
let offset = index as usize; let offset = index as usize;
( (
if offset >= bits { if offset >= bits {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); return Err(
EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into()
);
} else { } else {
(*value & (1 << offset)) != 0 (*value & (1 << offset)) != 0
}, },
@ -2025,14 +2026,16 @@ impl Engine {
( (
// Count from end if negative // Count from end if negative
if offset > bits { if offset > bits {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); return Err(
EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into()
);
} else { } else {
(*value & (1 << (bits - offset))) != 0 (*value & (1 << (bits - offset))) != 0
}, },
offset, offset,
) )
} else { } else {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into(); return Err(EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into());
}; };
Ok(Target::BitField(target, offset, bit_value.into())) Ok(Target::BitField(target, offset, bit_value.into()))
@ -2066,7 +2069,7 @@ impl Engine {
) )
} else { } else {
let chars_len = s.chars().count(); let chars_len = s.chars().count();
return EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into(); return Err(EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into());
}; };
Ok(Target::StringChar(target, offset, ch.into())) Ok(Target::StringChar(target, offset, ch.into()))
@ -2083,7 +2086,7 @@ impl Engine {
.map(|(v, _)| v.into()) .map(|(v, _)| v.into())
} }
_ => EvalAltResult::ErrorIndexingType( _ => Err(EvalAltResult::ErrorIndexingType(
format!( format!(
"{} [{}]", "{} [{}]",
self.map_type_name(target.type_name()), self.map_type_name(target.type_name()),
@ -2091,7 +2094,7 @@ impl Engine {
), ),
Position::NONE, Position::NONE,
) )
.into(), .into()),
} }
} }
@ -2386,7 +2389,9 @@ impl Engine {
) -> Result<(), Box<EvalAltResult>> { ) -> Result<(), Box<EvalAltResult>> {
if target.is_read_only() { if target.is_read_only() {
// Assignment to constant variable // Assignment to constant variable
return EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into(); return Err(
EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into(),
);
} }
let mut new_val = new_val; let mut new_val = new_val;
@ -2482,8 +2487,11 @@ impl Engine {
.expect("`lhs_ptr` is `Variable`"); .expect("`lhs_ptr` is `Variable`");
if !lhs_ptr.is_ref() { if !lhs_ptr.is_ref() {
return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos) return Err(EvalAltResult::ErrorAssignmentToConstant(
.into(); var_name.to_string(),
pos,
)
.into());
} }
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
@ -2735,11 +2743,11 @@ impl Engine {
if let Some(c) = counter_index { if let Some(c) = counter_index {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if x > INT::MAX as usize { if x > INT::MAX as usize {
return EvalAltResult::ErrorArithmetic( return Err(EvalAltResult::ErrorArithmetic(
format!("for-loop counter overflow: {}", x), format!("for-loop counter overflow: {}", x),
counter.as_ref().expect("`counter` is `Some`").pos, counter.as_ref().expect("`counter` is `Some`").pos,
) )
.into(); .into());
} }
let mut counter_var = scope let mut counter_var = scope
@ -2789,13 +2797,13 @@ impl Engine {
scope.rewind(orig_scope_len); scope.rewind(orig_scope_len);
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
} else { } else {
EvalAltResult::ErrorFor(expr.position()).into() Err(EvalAltResult::ErrorFor(expr.position()).into())
} }
} }
// Continue/Break statement // Continue/Break statement
Stmt::BreakLoop(options, pos) => { Stmt::BreakLoop(options, pos) => {
EvalAltResult::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into() Err(EvalAltResult::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
} }
// Namespace-qualified function call // Namespace-qualified function call
@ -2918,29 +2926,29 @@ impl Engine {
// Throw value // Throw value
Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => { Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => {
EvalAltResult::ErrorRuntime( Err(EvalAltResult::ErrorRuntime(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)? self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(), .flatten(),
*pos, *pos,
) )
.into() .into())
} }
// Empty throw // Empty throw
Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => { Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into() Err(EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into())
} }
// Return value // Return value
Stmt::Return(_, Some(expr), pos) => EvalAltResult::Return( Stmt::Return(_, Some(expr), pos) => Err(EvalAltResult::Return(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)? self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(), .flatten(),
*pos, *pos,
) )
.into(), .into()),
// Empty return // Empty return
Stmt::Return(_, None, pos) => EvalAltResult::Return(Dynamic::UNIT, *pos).into(), Stmt::Return(_, None, pos) => Err(EvalAltResult::Return(Dynamic::UNIT, *pos).into()),
// Let/const statement // Let/const statement
Stmt::Var(expr, x, options, _) => { Stmt::Var(expr, x, options, _) => {
@ -3003,7 +3011,7 @@ impl Engine {
// Guard against too many modules // Guard against too many modules
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if state.num_modules >= self.max_modules() { if state.num_modules >= self.max_modules() {
return EvalAltResult::ErrorTooManyModules(*_pos).into(); return Err(EvalAltResult::ErrorTooManyModules(*_pos).into());
} }
if let Some(path) = self if let Some(path) = self
@ -3032,7 +3040,10 @@ impl Engine {
.map(|r| r.resolve(self, source, &path, path_pos)) .map(|r| r.resolve(self, source, &path, path_pos))
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into() Err(
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos)
.into(),
)
})?; })?;
if let Some(name) = export.as_ref().map(|x| x.name.clone()) { if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
@ -3065,7 +3076,9 @@ impl Engine {
if rename.is_empty() { name } else { rename }.clone(), if rename.is_empty() { name } else { rename }.clone(),
); );
} else { } else {
return EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into(); return Err(
EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into()
);
} }
} }
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
@ -3182,11 +3195,11 @@ impl Engine {
.max_string_size .max_string_size
.map_or(usize::MAX, NonZeroUsize::get) .map_or(usize::MAX, NonZeroUsize::get)
{ {
return EvalAltResult::ErrorDataTooLarge( return Err(EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(), "Length of string".to_string(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -3196,8 +3209,11 @@ impl Engine {
.max_array_size .max_array_size
.map_or(usize::MAX, NonZeroUsize::get) .map_or(usize::MAX, NonZeroUsize::get)
{ {
return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), Position::NONE) return Err(EvalAltResult::ErrorDataTooLarge(
.into(); "Size of array".to_string(),
Position::NONE,
)
.into());
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
@ -3207,11 +3223,11 @@ impl Engine {
.max_map_size .max_map_size
.map_or(usize::MAX, NonZeroUsize::get) .map_or(usize::MAX, NonZeroUsize::get)
{ {
return EvalAltResult::ErrorDataTooLarge( return Err(EvalAltResult::ErrorDataTooLarge(
"Size of object map".to_string(), "Size of object map".to_string(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
Ok(()) Ok(())
@ -3228,14 +3244,14 @@ impl Engine {
// Guard against too many operations // Guard against too many operations
if self.max_operations() > 0 && state.num_operations > self.max_operations() { if self.max_operations() > 0 && state.num_operations > self.max_operations() {
return EvalAltResult::ErrorTooManyOperations(pos).into(); return Err(EvalAltResult::ErrorTooManyOperations(pos).into());
} }
// Report progress - only in steps // Report progress - only in steps
if let Some(ref progress) = self.progress { if let Some(ref progress) = self.progress {
if let Some(token) = progress(state.num_operations) { if let Some(token) = progress(state.num_operations) {
// Terminate script if progress returns a termination token // Terminate script if progress returns a termination token
return EvalAltResult::ErrorTerminated(token, pos).into(); return Err(EvalAltResult::ErrorTerminated(token, pos).into());
} }
} }

View File

@ -453,10 +453,3 @@ impl EvalAltResult {
self self
} }
} }
impl<T> From<EvalAltResult> for Result<T, Box<EvalAltResult>> {
#[inline(always)]
fn from(err: EvalAltResult) -> Self {
Err(err.into())
}
}

View File

@ -115,11 +115,11 @@ pub fn ensure_no_data_race(
.skip(if is_method_call { 1 } else { 0 }) .skip(if is_method_call { 1 } else { 0 })
.find(|(_, a)| a.is_locked()) .find(|(_, a)| a.is_locked())
{ {
return EvalAltResult::ErrorDataRace( return Err(EvalAltResult::ErrorDataRace(
format!("argument #{} of function '{}'", n + 1, fn_name), format!("argument #{} of function '{}'", n + 1, fn_name),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
Ok(()) Ok(())
@ -392,7 +392,7 @@ impl Engine {
crate::engine::FN_IDX_GET => { crate::engine::FN_IDX_GET => {
assert!(args.len() == 2); assert!(args.len() == 2);
EvalAltResult::ErrorIndexingType( Err(EvalAltResult::ErrorIndexingType(
format!( format!(
"{} [{}]", "{} [{}]",
self.map_type_name(args[0].type_name()), self.map_type_name(args[0].type_name()),
@ -400,7 +400,7 @@ impl Engine {
), ),
pos, pos,
) )
.into() .into())
} }
// index setter function not found? // index setter function not found?
@ -408,7 +408,7 @@ impl Engine {
crate::engine::FN_IDX_SET => { crate::engine::FN_IDX_SET => {
assert!(args.len() == 3); assert!(args.len() == 3);
EvalAltResult::ErrorIndexingType( Err(EvalAltResult::ErrorIndexingType(
format!( format!(
"{} [{}] = {}", "{} [{}] = {}",
self.map_type_name(args[0].type_name()), self.map_type_name(args[0].type_name()),
@ -417,7 +417,7 @@ impl Engine {
), ),
pos, pos,
) )
.into() .into())
} }
// Getter function not found? // Getter function not found?
@ -425,7 +425,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_GET) => { _ if name.starts_with(crate::engine::FN_GET) => {
assert!(args.len() == 1); assert!(args.len() == 1);
EvalAltResult::ErrorDotExpr( Err(EvalAltResult::ErrorDotExpr(
format!( format!(
"Unknown property '{}' - a getter is not registered for type '{}'", "Unknown property '{}' - a getter is not registered for type '{}'",
&name[crate::engine::FN_GET.len()..], &name[crate::engine::FN_GET.len()..],
@ -433,7 +433,7 @@ impl Engine {
), ),
pos, pos,
) )
.into() .into())
} }
// Setter function not found? // Setter function not found?
@ -441,7 +441,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_SET) => { _ if name.starts_with(crate::engine::FN_SET) => {
assert!(args.len() == 2); assert!(args.len() == 2);
EvalAltResult::ErrorDotExpr( Err(EvalAltResult::ErrorDotExpr(
format!( format!(
"No writable property '{}' - a setter is not registered for type '{}' to handle '{}'", "No writable property '{}' - a setter is not registered for type '{}' to handle '{}'",
&name[crate::engine::FN_SET.len()..], &name[crate::engine::FN_SET.len()..],
@ -450,14 +450,15 @@ impl Engine {
), ),
pos, pos,
) )
.into() .into())
} }
// Raise error // Raise error
_ => { _ => Err(EvalAltResult::ErrorFunctionNotFound(
EvalAltResult::ErrorFunctionNotFound(self.gen_call_signature(None, name, args), pos) self.gen_call_signature(None, name, args),
.into() pos,
} )
.into()),
} }
} }
@ -489,7 +490,7 @@ impl Engine {
err: Box<EvalAltResult>, err: Box<EvalAltResult>,
pos: Position, pos: Position,
) -> RhaiResult { ) -> RhaiResult {
EvalAltResult::ErrorInFunctionCall( Err(EvalAltResult::ErrorInFunctionCall(
name, name,
fn_def fn_def
.lib .lib
@ -500,7 +501,7 @@ impl Engine {
err, err,
pos, pos,
) )
.into() .into())
} }
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
@ -514,7 +515,7 @@ impl Engine {
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if level > self.max_call_levels() { if level > self.max_call_levels() {
return EvalAltResult::ErrorStackOverflow(pos).into(); return Err(EvalAltResult::ErrorStackOverflow(pos).into());
} }
let orig_scope_level = state.scope_level; let orig_scope_level = state.scope_level;
@ -578,7 +579,7 @@ impl Engine {
// System errors are passed straight-through // System errors are passed straight-through
mut err if err.is_system_exception() => { mut err if err.is_system_exception() => {
err.set_position(pos); err.set_position(pos);
err.into() Err(err.into())
} }
// Other errors are wrapped in `ErrorInFunctionCall` // Other errors are wrapped in `ErrorInFunctionCall`
_ => make_error(fn_def.name.to_string(), fn_def, state, err, pos), _ => make_error(fn_def.name.to_string(), fn_def, state, err, pos),
@ -651,7 +652,7 @@ impl Engine {
) -> Result<(Dynamic, bool), Box<EvalAltResult>> { ) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
fn no_method_err(name: &str, pos: Position) -> Result<(Dynamic, bool), Box<EvalAltResult>> { fn no_method_err(name: &str, pos: Position) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
let msg = format!("'{0}' should not be called this way. Try {0}(...);", name); let msg = format!("'{0}' should not be called this way. Try {0}(...);", name);
EvalAltResult::ErrorRuntime(msg.into(), pos).into() Err(EvalAltResult::ErrorRuntime(msg.into(), pos).into())
} }
// Check for data race. // Check for data race.
@ -1458,11 +1459,11 @@ impl Engine {
Some(f) => unreachable!("unknown function type: {:?}", f), Some(f) => unreachable!("unknown function type: {:?}", f),
None => EvalAltResult::ErrorFunctionNotFound( None => Err(EvalAltResult::ErrorFunctionNotFound(
self.gen_call_signature(Some(namespace), fn_name, &args), self.gen_call_signature(Some(namespace), fn_name, &args),
pos, pos,
) )
.into(), .into()),
} }
} }
} }

View File

@ -183,6 +183,9 @@ impl<'a> NativeCallContext<'a> {
} }
/// Call a function inside the call context. /// Call a function inside the call context.
/// ///
/// If `is_method_call` is [`true`], the first argument is assumed to be the
/// `this` pointer for a script-defined function (or the object of a method call).
///
/// # WARNING /// # WARNING
/// ///
/// All arguments may be _consumed_, meaning that they may be replaced by `()`. /// All arguments may be _consumed_, meaning that they may be replaced by `()`.
@ -193,9 +196,6 @@ impl<'a> NativeCallContext<'a> {
/// ///
/// If `is_ref_mut` is [`true`], the first argument is assumed to be passed /// If `is_ref_mut` is [`true`], the first argument is assumed to be passed
/// by reference and is not consumed. /// by reference and is not consumed.
///
/// If `is_method_call` is [`true`], the first argument is assumed to be the
/// `this` pointer for a script-defined function (or the object of a method call).
pub fn call_fn_raw( pub fn call_fn_raw(
&self, &self,
fn_name: &str, fn_name: &str,

View File

@ -148,7 +148,7 @@ impl TryFrom<Identifier> for FnPtr {
if is_valid_identifier(value.chars()) { if is_valid_identifier(value.chars()) {
Ok(Self(value, Default::default())) Ok(Self(value, Default::default()))
} else { } else {
EvalAltResult::ErrorFunctionNotFound(value.to_string(), Position::NONE).into() Err(EvalAltResult::ErrorFunctionNotFound(value.to_string(), Position::NONE).into())
} }
} }
} }

View File

@ -123,7 +123,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction { #[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
} }
// The arguments are assumed to be of the correct number and types! // The arguments are assumed to be of the correct number and types!
@ -151,7 +151,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction { #[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
} }
// The arguments are assumed to be of the correct number and types! // The arguments are assumed to be of the correct number and types!
@ -179,7 +179,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction { #[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
} }
// The arguments are assumed to be of the correct number and types! // The arguments are assumed to be of the correct number and types!
@ -204,7 +204,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction { #[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| { CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) { if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into(); return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
} }
// The arguments are assumed to be of the correct number and types! // The arguments are assumed to be of the correct number and types!

View File

@ -136,7 +136,7 @@ impl ModuleResolver for ModuleResolversCollection {
} }
} }
EvalAltResult::ErrorModuleNotFound(path.into(), pos).into() Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
} }
} }

View File

@ -45,6 +45,6 @@ impl ModuleResolver for DummyModuleResolver {
path: &str, path: &str,
pos: Position, pos: Position,
) -> Result<Shared<Module>, Box<EvalAltResult>> { ) -> Result<Shared<Module>, Box<EvalAltResult>> {
EvalAltResult::ErrorModuleNotFound(path.into(), pos).into() Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
} }
} }

View File

@ -79,8 +79,11 @@ mod array_functions {
// Check if array will be over max size limit // Check if array will be over max size limit
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_array_size() > 0 && (len as usize) > _ctx.engine().max_array_size() { if _ctx.engine().max_array_size() > 0 && (len as usize) > _ctx.engine().max_array_size() {
return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), Position::NONE) return Err(EvalAltResult::ErrorDataTooLarge(
.into(); "Size of array".to_string(),
Position::NONE,
)
.into());
} }
if len as usize > array.len() { if len as usize > array.len() {
@ -267,13 +270,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "map".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
}, },
@ -309,13 +312,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "filter".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }
@ -473,13 +476,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "index_of".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }
@ -519,13 +522,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "some".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }
@ -565,13 +568,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "all".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }
@ -781,13 +784,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "drain".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }
@ -875,13 +878,13 @@ mod array_functions {
ctx.call_fn_raw(fn_name, true, false, &mut args)? ctx.call_fn_raw(fn_name, true, false, &mut args)?
} }
_ => { _ => {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"drain".to_string(), "retain".to_string(),
ctx.source().unwrap_or("").to_string(), ctx.source().unwrap_or("").to_string(),
err, err,
Position::NONE, Position::NONE,
) )
.into() .into())
} }
}, },
} }

View File

@ -25,7 +25,7 @@ where
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if let Some(r) = from.checked_add(&step) { if let Some(r) = from.checked_add(&step) {
if r == from { if r == from {
return EvalAltResult::ErrorInFunctionCall( return Err(EvalAltResult::ErrorInFunctionCall(
"range".to_string(), "range".to_string(),
Default::default(), Default::default(),
EvalAltResult::ErrorArithmetic( EvalAltResult::ErrorArithmetic(
@ -35,7 +35,7 @@ where
.into(), .into(),
crate::Position::NONE, crate::Position::NONE,
) )
.into(); .into());
} }
} }
@ -122,21 +122,27 @@ impl BitRange {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if offset >= BITS { if offset >= BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) return Err(
.into(); EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into(),
);
} }
offset offset
} else { } else {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if let Some(abs_from) = from.checked_abs() { if let Some(abs_from) = from.checked_abs() {
if (abs_from as usize) > BITS { if (abs_from as usize) > BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) return Err(EvalAltResult::ErrorBitFieldBounds(
.into(); BITS,
from,
crate::Position::NONE,
)
.into());
} }
BITS - (abs_from as usize) BITS - (abs_from as usize)
} else { } else {
return EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE) return Err(
.into(); EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into(),
);
} }
#[cfg(feature = "unchecked")] #[cfg(feature = "unchecked")]
@ -325,10 +331,10 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> Result<Self, Box<EvalAltResult>> { pub fn new(from: FLOAT, to: FLOAT, step: FLOAT) -> Result<Self, Box<EvalAltResult>> {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if step == 0.0 { if step == 0.0 {
return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), return Err(EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(),
EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(), EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
crate::Position::NONE, crate::Position::NONE,
).into(); ).into());
} }
Ok(Self(from, to, step)) Ok(Self(from, to, step))
@ -387,10 +393,10 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
pub fn new(from: Decimal, to: Decimal, step: Decimal) -> Result<Self, Box<EvalAltResult>> { pub fn new(from: Decimal, to: Decimal, step: Decimal) -> Result<Self, Box<EvalAltResult>> {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if step.is_zero() { if step.is_zero() {
return EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(), return Err(EvalAltResult::ErrorInFunctionCall("range".to_string(), "".to_string(),
EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(), EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
crate::Position::NONE, crate::Position::NONE,
).into(); ).into());
} }
Ok(Self(from, to, step)) Ok(Self(from, to, step))

View File

@ -14,7 +14,7 @@ mod core_functions {
#[rhai_fn(name = "set_tag", set = "tag", return_raw)] #[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) -> Result<(), Box<EvalAltResult>> {
if tag < Tag::MIN as INT { if tag < Tag::MIN as INT {
EvalAltResult::ErrorArithmetic( Err(EvalAltResult::ErrorArithmetic(
format!( format!(
"{} is too small to fit into a tag (must be between {} and {})", "{} is too small to fit into a tag (must be between {} and {})",
tag, tag,
@ -23,9 +23,9 @@ mod core_functions {
), ),
Position::NONE, Position::NONE,
) )
.into() .into())
} else if tag > Tag::MAX as INT { } else if tag > Tag::MAX as INT {
EvalAltResult::ErrorArithmetic( Err(EvalAltResult::ErrorArithmetic(
format!( format!(
"{} is too large to fit into a tag (must be between {} and {})", "{} is too large to fit into a tag (must be between {} and {})",
tag, tag,
@ -34,7 +34,7 @@ mod core_functions {
), ),
Position::NONE, Position::NONE,
) )
.into() .into())
} else { } else {
value.set_tag(tag as Tag); value.set_tag(tag as Tag);
Ok(()) Ok(())

View File

@ -202,7 +202,7 @@ mod bit_field_functions {
let offset = index as usize; let offset = index as usize;
if offset >= BITS { if offset >= BITS {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else { } else {
Ok((value & (1 << offset)) != 0) Ok((value & (1 << offset)) != 0)
} }
@ -211,12 +211,12 @@ mod bit_field_functions {
// Count from end if negative // Count from end if negative
if offset > BITS { if offset > BITS {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else { } else {
Ok((value & (1 << (BITS - offset))) != 0) Ok((value & (1 << (BITS - offset))) != 0)
} }
} else { } else {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} }
} }
#[rhai_fn(return_raw)] #[rhai_fn(return_raw)]
@ -225,7 +225,7 @@ mod bit_field_functions {
let offset = index as usize; let offset = index as usize;
if offset >= BITS { if offset >= BITS {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else { } else {
let mask = 1 << offset; let mask = 1 << offset;
if new_value { if new_value {
@ -240,7 +240,7 @@ mod bit_field_functions {
// Count from end if negative // Count from end if negative
if offset > BITS { if offset > BITS {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else { } else {
let mask = 1 << offset; let mask = 1 << offset;
if new_value { if new_value {
@ -251,7 +251,7 @@ mod bit_field_functions {
Ok(()) Ok(())
} }
} else { } else {
EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into() Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} }
} }
#[rhai_fn(return_raw)] #[rhai_fn(return_raw)]
@ -264,7 +264,7 @@ mod bit_field_functions {
let offset = index as usize; let offset = index as usize;
if offset >= BITS { if offset >= BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
} }
offset offset
@ -273,11 +273,11 @@ mod bit_field_functions {
// Count from end if negative // Count from end if negative
if offset > BITS { if offset > BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
} }
BITS - offset BITS - offset
} else { } else {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}; };
let bits = if offset + bits as usize > BITS { let bits = if offset + bits as usize > BITS {
@ -311,7 +311,7 @@ mod bit_field_functions {
let offset = index as usize; let offset = index as usize;
if offset >= BITS { if offset >= BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
} }
offset offset
@ -320,11 +320,11 @@ mod bit_field_functions {
// Count from end if negative // Count from end if negative
if offset > BITS { if offset > BITS {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
} }
BITS - offset BITS - offset
} else { } else {
return EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into(); return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}; };
let bits = if offset + bits as usize > BITS { let bits = if offset + bits as usize > BITS {

View File

@ -114,11 +114,11 @@ mod int_functions {
#[rhai_fn(name = "parse_int", return_raw)] #[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) -> Result<INT, Box<EvalAltResult>> {
if !(2..=36).contains(&radix) { if !(2..=36).contains(&radix) {
return EvalAltResult::ErrorArithmetic( return Err(EvalAltResult::ErrorArithmetic(
format!("Invalid radix: '{}'", radix), format!("Invalid radix: '{}'", radix),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
INT::from_str_radix(string.trim(), radix as u32).map_err(|err| { INT::from_str_radix(string.trim(), radix as u32).map_err(|err| {
@ -261,11 +261,11 @@ mod float_functions {
#[rhai_fn(name = "to_int", return_raw)] #[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) -> Result<INT, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f32) { if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f32) {
EvalAltResult::ErrorArithmetic( Err(EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x), format!("Integer overflow: to_int({})", x),
Position::NONE, Position::NONE,
) )
.into() .into())
} else { } else {
Ok(x.trunc() as INT) Ok(x.trunc() as INT)
} }
@ -273,11 +273,11 @@ mod float_functions {
#[rhai_fn(name = "to_int", return_raw)] #[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) -> Result<INT, Box<EvalAltResult>> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f64) { if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f64) {
EvalAltResult::ErrorArithmetic( Err(EvalAltResult::ErrorArithmetic(
format!("Integer overflow: to_int({})", x), format!("Integer overflow: to_int({})", x),
Position::NONE, Position::NONE,
) )
.into() .into())
} else { } else {
Ok(x.trunc() as INT) Ok(x.trunc() as INT)
} }

View File

@ -471,11 +471,11 @@ mod string_functions {
// Check if string will be over max size limit // Check if string will be over max size limit
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() { if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
return crate::EvalAltResult::ErrorDataTooLarge( return Err(crate::EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(), "Length of string".to_string(),
crate::Position::NONE, crate::Position::NONE,
) )
.into(); .into());
} }
let orig_len = string.chars().count(); let orig_len = string.chars().count();
@ -490,11 +490,11 @@ mod string_functions {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size() if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size()
{ {
return crate::EvalAltResult::ErrorDataTooLarge( return Err(crate::EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(), "Length of string".to_string(),
crate::Position::NONE, crate::Position::NONE,
) )
.into(); .into());
} }
} }
@ -516,11 +516,11 @@ mod string_functions {
// Check if string will be over max size limit // Check if string will be over max size limit
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() { if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
return crate::EvalAltResult::ErrorDataTooLarge( return Err(crate::EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(), "Length of string".to_string(),
crate::Position::NONE, crate::Position::NONE,
) )
.into(); .into());
} }
let mut str_len = string.chars().count(); let mut str_len = string.chars().count();
@ -542,11 +542,11 @@ mod string_functions {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size() if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size()
{ {
return crate::EvalAltResult::ErrorDataTooLarge( return Err(crate::EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(), "Length of string".to_string(),
crate::Position::NONE, crate::Position::NONE,
) )
.into(); .into());
} }
} }

View File

@ -38,12 +38,12 @@ impl<'de> DynamicDeserializer<'de> {
} }
/// Shortcut for a type conversion error. /// 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) -> Result<T, Box<EvalAltResult>> {
EvalAltResult::ErrorMismatchOutputType( Err(EvalAltResult::ErrorMismatchOutputType(
error.into(), error.into(),
self.value.type_name().into(), self.value.type_name().into(),
Position::NONE, Position::NONE,
) )
.into() .into())
} }
fn deserialize_int<V: Visitor<'de>>( fn deserialize_int<V: Visitor<'de>>(
&mut self, &mut self,

View File

@ -313,24 +313,24 @@ impl Serializer for &mut DynamicSerializer {
make_variant(_variant, content) make_variant(_variant, content)
} }
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Box<EvalAltResult>> { fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Box<EvalAltResult>> {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
return Ok(DynamicSerializer::new(Array::new().into())); return Ok(DynamicSerializer::new(Array::new().into()));
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"arrays are not supported with 'no_index'".into(), "arrays are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Box<EvalAltResult>> { fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Box<EvalAltResult>> {
@ -359,24 +359,24 @@ impl Serializer for &mut DynamicSerializer {
array: Array::with_capacity(_len), array: Array::with_capacity(_len),
}); });
#[cfg(any(feature = "no_object", feature = "no_index"))] #[cfg(any(feature = "no_object", feature = "no_index"))]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"tuples are not supported with 'no_index' or 'no_object'".into(), "tuples are not supported with 'no_index' or 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Box<EvalAltResult>> { fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
return Ok(DynamicSerializer::new(Map::new().into())); return Ok(DynamicSerializer::new(Map::new().into()));
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_struct( fn serialize_struct(
@ -400,12 +400,12 @@ impl Serializer for &mut DynamicSerializer {
map: Default::default(), map: Default::default(),
}); });
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }
@ -425,12 +425,12 @@ impl SerializeSeq for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"arrays are not supported with 'no_index'".into(), "arrays are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
// Close the sequence. // Close the sequence.
@ -438,12 +438,12 @@ impl SerializeSeq for DynamicSerializer {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
return Ok(self._value); return Ok(self._value);
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"arrays are not supported with 'no_index'".into(), "arrays are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }
@ -463,24 +463,24 @@ impl SerializeTuple for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"tuples are not supported with 'no_index'".into(), "tuples are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> { fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
return Ok(self._value); return Ok(self._value);
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"tuples are not supported with 'no_index'".into(), "tuples are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }
@ -500,24 +500,24 @@ impl SerializeTupleStruct for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"tuples are not supported with 'no_index'".into(), "tuples are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> { fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
return Ok(self._value); return Ok(self._value);
#[cfg(feature = "no_index")] #[cfg(feature = "no_index")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"tuples are not supported with 'no_index'".into(), "tuples are not supported with 'no_index'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }
@ -532,12 +532,12 @@ impl SerializeMap for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_value<T: ?Sized + Serialize>( fn serialize_value<T: ?Sized + Serialize>(
@ -561,12 +561,12 @@ impl SerializeMap for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn serialize_entry<K: ?Sized + Serialize, T: ?Sized + Serialize>( fn serialize_entry<K: ?Sized + Serialize, T: ?Sized + Serialize>(
@ -586,24 +586,24 @@ impl SerializeMap for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> { fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
return Ok(self._value); return Ok(self._value);
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }
@ -624,24 +624,24 @@ impl SerializeStruct for DynamicSerializer {
Ok(()) Ok(())
} }
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> { fn end(self) -> Result<Self::Ok, Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
return Ok(self._value); return Ok(self._value);
#[cfg(feature = "no_object")] #[cfg(feature = "no_object")]
return EvalAltResult::ErrorMismatchDataType( return Err(EvalAltResult::ErrorMismatchDataType(
"".into(), "".into(),
"object maps are not supported with 'no_object'".into(), "object maps are not supported with 'no_object'".into(),
Position::NONE, Position::NONE,
) )
.into(); .into());
} }
} }

View File

@ -19,12 +19,12 @@ impl<'a> StringSliceDeserializer<'a> {
} }
/// Shortcut for a type conversion error. /// Shortcut for a type conversion error.
fn type_error<T>(&self) -> Result<T, Box<EvalAltResult>> { fn type_error<T>(&self) -> Result<T, Box<EvalAltResult>> {
EvalAltResult::ErrorMismatchOutputType( Err(EvalAltResult::ErrorMismatchOutputType(
type_name::<T>().into(), type_name::<T>().into(),
"string".into(), "string".into(),
Position::NONE, Position::NONE,
) )
.into() .into())
} }
} }