Use type alias for error.

This commit is contained in:
Stephen Chung 2021-12-27 12:27:31 +08:00
parent e7ca3f41dd
commit 05d4c81e7a
29 changed files with 293 additions and 378 deletions

View File

@ -4,8 +4,7 @@
use crate::engine::{EvalState, Imports};
use crate::types::dynamic::Variant;
use crate::{
Dynamic, Engine, EvalAltResult, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec,
AST,
Dynamic, Engine, FuncArgs, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, AST, ERR,
};
use std::any::type_name;
#[cfg(feature = "no_std")]
@ -70,7 +69,7 @@ impl Engine {
let typ = self.map_type_name(result.type_name());
result.try_cast().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
self.map_type_name(type_name::<T>()).into(),
typ.into(),
Position::NONE,
@ -176,7 +175,7 @@ impl Engine {
let fn_def = ast
.shared_lib()
.get_script_fn(name, args.len())
.ok_or_else(|| EvalAltResult::ErrorFunctionNotFound(name.into(), Position::NONE))?;
.ok_or_else(|| ERR::ErrorFunctionNotFound(name.into(), Position::NONE))?;
// Check for data race.
#[cfg(not(feature = "no_closure"))]

View File

@ -366,7 +366,7 @@ impl Engine {
} else if json_text.starts_with(Token::LeftBrace.literal_syntax()) {
["#", json_text]
} else {
return Err(crate::ParseErrorType::MissingToken(
return Err(crate::PERR::MissingToken(
Token::LeftBrace.syntax().into(),
"to start a JSON object hash".into(),
)

View File

@ -3,9 +3,7 @@
use crate::engine::{EvalState, Imports};
use crate::parser::ParseState;
use crate::types::dynamic::Variant;
use crate::{
Dynamic, Engine, EvalAltResult, Module, Position, RhaiResult, RhaiResultOf, Scope, AST,
};
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, AST, ERR};
use std::any::type_name;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -193,7 +191,7 @@ impl Engine {
let typ = self.map_type_name(result.type_name());
result.try_cast::<T>().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
self.map_type_name(type_name::<T>()).into(),
typ.into(),
Position::NONE,

View File

@ -3,7 +3,7 @@
#![cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
use crate::types::dynamic::Variant;
use crate::{Engine, EvalAltResult, RhaiResultOf, Scope, AST};
use crate::{Engine, RhaiResultOf, Scope, AST, ERR};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -13,7 +13,7 @@ impl Engine {
use std::io::Read;
let mut f = std::fs::File::open(path.clone()).map_err(|err| {
EvalAltResult::ErrorSystem(
ERR::ErrorSystem(
format!("Cannot open script file '{}'", path.to_string_lossy()),
err.into(),
)
@ -22,7 +22,7 @@ impl Engine {
let mut contents = String::new();
f.read_to_string(&mut contents).map_err(|err| {
EvalAltResult::ErrorSystem(
ERR::ErrorSystem(
format!("Cannot read script file '{}'", path.to_string_lossy()),
err.into(),
)

View File

@ -13,8 +13,8 @@ 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, RhaiError, RhaiResult, RhaiResultOf, Scope, Shared, StaticVec, INT,
calc_fn_params_hash, combine_hashes, Dynamic, Identifier, ImmutableString, Module, Position,
RhaiError, RhaiResult, RhaiResultOf, Scope, Shared, StaticVec, ERR, INT,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -459,7 +459,7 @@ pub enum Target<'a> {
Dynamic,
),
),
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
/// The target is a temporary `Dynamic` value (i.e. its mutation can cause no side effects).
TempValue(Dynamic),
/// The target is a bit inside an [`INT`][crate::INT].
/// This is necessary because directly pointing to a bit inside an [`INT`][crate::INT] is impossible.
@ -557,7 +557,7 @@ impl<'a> Target<'a> {
match self {
Self::RefMut(r) => r.clone(), // Referenced value is cloned
#[cfg(not(feature = "no_closure"))]
Self::LockGuard((_, orig)) => orig, // Original value is simply taken
Self::LockGuard((_, shared)) => shared, // Original shared value is simply taken
Self::TempValue(v) => v, // Owned value is simply taken
#[cfg(not(feature = "no_index"))]
Self::Bit(_, value, _) => value, // Boolean is taken
@ -585,7 +585,7 @@ impl<'a> Target<'a> {
self.take_or_clone().into()
}
/// Propagate a changed value back to the original source.
/// This has no effect except for string indexing.
/// This has no effect for direct references.
#[inline]
pub fn propagate_changed_value(&mut self) -> RhaiResultOf<()> {
match self {
@ -596,7 +596,7 @@ impl<'a> Target<'a> {
Self::Bit(value, new_val, index) => {
// Replace the bit at the specified index position
let new_bit = new_val.as_bool().map_err(|err| {
Box::new(EvalAltResult::ErrorMismatchDataType(
Box::new(ERR::ErrorMismatchDataType(
"bool".to_string(),
err.to_string(),
Position::NONE,
@ -621,7 +621,7 @@ impl<'a> Target<'a> {
// Replace the bit at the specified index position
let new_value = new_val.as_int().map_err(|err| {
Box::new(EvalAltResult::ErrorMismatchDataType(
Box::new(ERR::ErrorMismatchDataType(
"integer".to_string(),
err.to_string(),
Position::NONE,
@ -638,7 +638,7 @@ impl<'a> Target<'a> {
Self::BlobByte(value, index, new_val) => {
// Replace the byte at the specified index position
let new_byte = new_val.as_int().map_err(|err| {
Box::new(EvalAltResult::ErrorMismatchDataType(
Box::new(ERR::ErrorMismatchDataType(
"INT".to_string(),
err.to_string(),
Position::NONE,
@ -659,7 +659,7 @@ impl<'a> Target<'a> {
Self::StringChar(s, index, new_val) => {
// Replace the character at the specified index position
let new_ch = new_val.as_char().map_err(|err| {
Box::new(EvalAltResult::ErrorMismatchDataType(
Box::new(ERR::ErrorMismatchDataType(
"char".to_string(),
err.to_string(),
Position::NONE,
@ -1189,18 +1189,16 @@ impl Engine {
Ok((target.into(), *_var_pos))
}
Err(err) => Err(match *err {
EvalAltResult::ErrorVariableNotFound(_, _) => {
EvalAltResult::ErrorVariableNotFound(
format!(
"{}{}{}",
namespace,
Token::DoubleColon.literal_syntax(),
var_name
),
namespace[0].pos,
)
.into()
}
ERR::ErrorVariableNotFound(_, _) => ERR::ErrorVariableNotFound(
format!(
"{}{}{}",
namespace,
Token::DoubleColon.literal_syntax(),
var_name
),
namespace[0].pos,
)
.into(),
_ => err.fill_position(*_var_pos),
}),
};
@ -1220,7 +1218,7 @@ impl Engine {
}
}
return Err(EvalAltResult::ErrorVariableNotFound(
return Err(ERR::ErrorVariableNotFound(
format!(
"{}{}{}",
namespace,
@ -1232,10 +1230,7 @@ impl Engine {
.into());
}
Err(
EvalAltResult::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos)
.into(),
)
Err(ERR::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos).into())
}
#[cfg(feature = "no_module")]
@ -1267,7 +1262,7 @@ impl Engine {
return if let Some(val) = this_ptr {
Ok(((*val).into(), *pos))
} else {
Err(EvalAltResult::ErrorUnboundThis(*pos).into())
Err(ERR::ErrorUnboundThis(*pos).into())
}
}
_ if state.always_search_scope => (0, expr.position()),
@ -1308,7 +1303,7 @@ impl Engine {
let var_name = expr.get_variable_name(true).expect("`Variable`");
scope
.get_index(var_name)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(var_name.to_string(), var_pos))?
.ok_or_else(|| ERR::ErrorVariableNotFound(var_name.to_string(), var_pos))?
.0
};
@ -1387,7 +1382,7 @@ impl Engine {
root_pos, None, level,
) {
// Just ignore if there is no index setter
if !matches!(*err, EvalAltResult::ErrorFunctionNotFound(_, _)) {
if !matches!(*err, ERR::ErrorFunctionNotFound(_, _)) {
return Err(err);
}
}
@ -1416,7 +1411,7 @@ impl Engine {
}
// Can't index - try to call an index setter
#[cfg(not(feature = "no_index"))]
Err(err) if matches!(*err, EvalAltResult::ErrorIndexingType(_, _)) => {
Err(err) if matches!(*err, ERR::ErrorIndexingType(_, _)) => {
Some(new_val)
}
// Any other error
@ -1510,7 +1505,7 @@ impl Engine {
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
ERR::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
mods, state, lib, target, prop, *pos, false, true,
@ -1519,7 +1514,7 @@ impl Engine {
.map(|v| (v.take_or_clone(), false))
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
ERR::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
@ -1553,7 +1548,7 @@ impl Engine {
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
ERR::ErrorDotExpr(_, _) => {
let args = &mut [target, &mut name.into(), &mut new_val];
let hash_set =
crate::ast::FnCallHashes::from_native(mods.hash_idx_set());
@ -1565,7 +1560,7 @@ impl Engine {
)
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
ERR::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
@ -1585,7 +1580,7 @@ impl Engine {
.map_or_else(
|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
ERR::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
mods, state, lib, target, prop, *pos, false, true, level,
@ -1593,7 +1588,7 @@ impl Engine {
.map(|v| (v.take_or_clone(), false))
.map_err(|idx_err| {
match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
ERR::ErrorIndexingType(_, _) => err,
_ => idx_err,
}
})
@ -1663,7 +1658,7 @@ impl Engine {
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
ERR::ErrorDotExpr(_, _) => {
let prop = name.into();
self.get_indexed_mut(
mods, state, lib, target, prop, *pos, false, true,
@ -1672,7 +1667,7 @@ impl Engine {
.map(|v| (v.take_or_clone(), false))
.map_err(
|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => err,
ERR::ErrorIndexingType(_, _) => err,
_ => idx_err,
},
)
@ -1711,7 +1706,7 @@ impl Engine {
.or_else(
|err| match *err {
// Try an indexer if property does not exist
EvalAltResult::ErrorDotExpr(_, _) => {
ERR::ErrorDotExpr(_, _) => {
let args =
&mut [target.as_mut(), &mut name.into(), val];
let hash_set =
@ -1723,7 +1718,7 @@ impl Engine {
is_ref_mut, true, *pos, None, level,
)
.or_else(|idx_err| match *idx_err {
EvalAltResult::ErrorIndexingType(_, _) => {
ERR::ErrorIndexingType(_, _) => {
// If there is no setter, no need to feed it back because
// the property is read-only
Ok((Dynamic::UNIT, false))
@ -1768,7 +1763,7 @@ impl Engine {
}
}
// Syntax error
_ => Err(EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into()),
_ => Err(ERR::ErrorDotExpr("".into(), rhs.position()).into()),
}
}
}
@ -2007,11 +2002,10 @@ impl Engine {
arr_len
- index
.checked_abs()
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos))
.and_then(|n| {
if n as usize > arr_len {
Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
.into())
Err(ERR::ErrorArrayBounds(arr_len, index, idx_pos).into())
} else {
Ok(n as usize)
}
@ -2029,7 +2023,7 @@ impl Engine {
arr.get_mut(arr_idx)
.map(Target::from)
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into())
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos).into())
}
#[cfg(not(feature = "no_index"))]
@ -2047,11 +2041,10 @@ impl Engine {
arr_len
- index
.checked_abs()
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
.ok_or_else(|| ERR::ErrorArrayBounds(arr_len, index, idx_pos))
.and_then(|n| {
if n as usize > arr_len {
Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
.into())
Err(ERR::ErrorArrayBounds(arr_len, index, idx_pos).into())
} else {
Ok(n as usize)
}
@ -2070,9 +2063,7 @@ impl Engine {
let value = arr
.get(arr_idx)
.map(|&v| (v as INT).into())
.ok_or_else(|| {
Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
})?;
.ok_or_else(|| Box::new(ERR::ErrorArrayBounds(arr_len, index, idx_pos)))?;
Ok(Target::BlobByte(target, arr_idx, value))
}
@ -2110,9 +2101,9 @@ impl Engine {
let end = range.end;
if start < 0 || start as usize >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, start, idx_pos).into());
return Err(ERR::ErrorBitFieldBounds(BITS, start, idx_pos).into());
} else if end < 0 || end as usize >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, end, idx_pos).into());
return Err(ERR::ErrorBitFieldBounds(BITS, end, idx_pos).into());
} else if end <= start {
(0, 0)
} else if end as usize == BITS && start == 0 {
@ -2130,9 +2121,9 @@ impl Engine {
let end = *range.end();
if start < 0 || start as usize >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, start, idx_pos).into());
return Err(ERR::ErrorBitFieldBounds(BITS, start, idx_pos).into());
} else if end < 0 || end as usize >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, end, idx_pos).into());
return Err(ERR::ErrorBitFieldBounds(BITS, end, idx_pos).into());
} else if end < start {
(0, 0)
} else if end as usize == BITS - 1 && start == 0 {
@ -2167,9 +2158,7 @@ impl Engine {
let offset = index as usize;
(
if offset >= BITS {
return Err(
EvalAltResult::ErrorBitFieldBounds(BITS, index, idx_pos).into()
);
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
} else {
(*value & (1 << offset)) != 0
},
@ -2180,16 +2169,14 @@ impl Engine {
(
// Count from end if negative
if offset > BITS {
return Err(
EvalAltResult::ErrorBitFieldBounds(BITS, index, idx_pos).into()
);
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
} else {
(*value & (1 << (BITS - offset))) != 0
},
offset as u8,
)
} else {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, idx_pos).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, idx_pos).into());
};
Ok(Target::Bit(target, bit_value.into(), offset))
@ -2207,7 +2194,7 @@ impl Engine {
(
s.chars().nth(offset).ok_or_else(|| {
let chars_len = s.chars().count();
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
ERR::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
@ -2217,13 +2204,13 @@ impl Engine {
// Count from end if negative
s.chars().rev().nth(offset - 1).ok_or_else(|| {
let chars_len = s.chars().count();
EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
ERR::ErrorStringBounds(chars_len, index, idx_pos)
})?,
offset,
)
} else {
let chars_len = s.chars().count();
return Err(EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into());
return Err(ERR::ErrorStringBounds(chars_len, index, idx_pos).into());
};
Ok(Target::StringChar(target, offset, ch.into()))
@ -2240,7 +2227,7 @@ impl Engine {
.map(|(v, _)| v.into())
}
_ => Err(EvalAltResult::ErrorIndexingType(
_ => Err(ERR::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(target.type_name()),
@ -2277,7 +2264,7 @@ impl Engine {
Expr::Variable(None, var_pos, x) if x.0.is_none() && x.2 == KEYWORD_THIS => this_ptr
.as_deref()
.cloned()
.ok_or_else(|| EvalAltResult::ErrorUnboundThis(*var_pos).into()),
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into()),
Expr::Variable(_, _, _) => self
.search_namespace(scope, mods, state, lib, this_ptr, expr)
.map(|(val, _)| val.take_or_clone()),
@ -2542,9 +2529,7 @@ impl Engine {
) -> RhaiResultOf<()> {
if target.is_read_only() {
// Assignment to constant variable
return Err(
EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into(),
);
return Err(ERR::ErrorAssignmentToConstant(root.0.to_string(), root.1).into());
}
let mut new_val = new_val;
@ -2575,7 +2560,7 @@ impl Engine {
let args = &mut [lhs_ptr_inner, &mut new_val];
match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) {
Err(err) if matches!(*err, EvalAltResult::ErrorFunctionNotFound(ref f, _) if f.starts_with(op)) =>
Err(err) if matches!(*err, ERR::ErrorFunctionNotFound(ref f, _) if f.starts_with(op)) =>
{
// Expand to `var = var op rhs`
let op = &op[..op.len() - 1]; // extract operator without =
@ -2638,11 +2623,7 @@ impl Engine {
let var_name = lhs_expr.get_variable_name(false).expect("`Variable`");
if !lhs_ptr.is_ref() {
return Err(EvalAltResult::ErrorAssignmentToConstant(
var_name.to_string(),
pos,
)
.into());
return Err(ERR::ErrorAssignmentToConstant(var_name.to_string(), pos).into());
}
#[cfg(not(feature = "unchecked"))]
@ -2829,8 +2810,8 @@ impl Engine {
{
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
}
@ -2856,8 +2837,8 @@ impl Engine {
{
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
}
@ -2874,8 +2855,8 @@ impl Engine {
{
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::LoopBreak(false, _) => continue,
EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
ERR::LoopBreak(false, _) => continue,
ERR::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
_ => return Err(err),
},
}
@ -2932,7 +2913,7 @@ impl Engine {
if let Some(c) = counter_index {
#[cfg(not(feature = "unchecked"))]
if x > INT::MAX as usize {
return Err(EvalAltResult::ErrorArithmetic(
return Err(ERR::ErrorArithmetic(
format!("for-loop counter overflow: {}", x),
counter.as_ref().expect("`Some`").pos,
)
@ -2975,8 +2956,8 @@ impl Engine {
match result {
Ok(_) => (),
Err(err) => match *err {
EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::LoopBreak(true, _) => break,
ERR::LoopBreak(false, _) => (),
ERR::LoopBreak(true, _) => break,
_ => return Err(err),
},
}
@ -2985,13 +2966,13 @@ impl Engine {
scope.rewind(orig_scope_len);
Ok(Dynamic::UNIT)
} else {
Err(EvalAltResult::ErrorFor(expr.position()).into())
Err(ERR::ErrorFor(expr.position()).into())
}
}
// Continue/Break statement
Stmt::BreakLoop(options, pos) => {
Err(EvalAltResult::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
Err(ERR::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
}
// Namespace-qualified function call
@ -3044,7 +3025,7 @@ impl Engine {
Err(err) if !err.is_catchable() => Err(err),
Err(mut err) => {
let err_value = match *err {
EvalAltResult::ErrorRuntime(ref x, _) => x.clone(),
ERR::ErrorRuntime(ref x, _) => x.clone(),
#[cfg(feature = "no_object")]
_ => {
@ -3096,7 +3077,7 @@ impl Engine {
Ok(_) => Ok(Dynamic::UNIT),
Err(result_err) => match *result_err {
// Re-throw exception
EvalAltResult::ErrorRuntime(Dynamic(Union::Unit(_, _, _)), pos) => {
ERR::ErrorRuntime(Dynamic(Union::Unit(_, _, _)), pos) => {
err.set_position(pos);
Err(err)
}
@ -3109,7 +3090,7 @@ impl Engine {
// Throw value
Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => {
Err(EvalAltResult::ErrorRuntime(
Err(ERR::ErrorRuntime(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
@ -3119,11 +3100,11 @@ impl Engine {
// Empty throw
Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
Err(EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into())
Err(ERR::ErrorRuntime(Dynamic::UNIT, *pos).into())
}
// Return value
Stmt::Return(_, Some(expr), pos) => Err(EvalAltResult::Return(
Stmt::Return(_, Some(expr), pos) => Err(ERR::Return(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
@ -3131,7 +3112,7 @@ impl Engine {
.into()),
// Empty return
Stmt::Return(_, None, pos) => Err(EvalAltResult::Return(Dynamic::UNIT, *pos).into()),
Stmt::Return(_, None, pos) => Err(ERR::Return(Dynamic::UNIT, *pos).into()),
// Let/const statement
Stmt::Var(expr, x, options, _) => {
@ -3178,7 +3159,7 @@ impl Engine {
// Guard against too many modules
#[cfg(not(feature = "unchecked"))]
if mods.num_modules >= self.max_modules() {
return Err(EvalAltResult::ErrorTooManyModules(*_pos).into());
return Err(ERR::ErrorTooManyModules(*_pos).into());
}
if let Some(path) = self
@ -3194,11 +3175,7 @@ impl Engine {
.embedded_module_resolver
.as_ref()
.and_then(|r| match r.resolve(self, source, &path, path_pos) {
Err(err)
if matches!(*err, EvalAltResult::ErrorModuleNotFound(_, _)) =>
{
None
}
Err(err) if matches!(*err, ERR::ErrorModuleNotFound(_, _)) => None,
result => Some(result),
})
.or_else(|| {
@ -3207,10 +3184,7 @@ impl Engine {
.map(|r| r.resolve(self, source, &path, path_pos))
})
.unwrap_or_else(|| {
Err(
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos)
.into(),
)
Err(ERR::ErrorModuleNotFound(path.to_string(), path_pos).into())
})?;
if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
@ -3245,7 +3219,7 @@ impl Engine {
);
Ok(()) as RhaiResultOf<_>
} else {
Err(EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into())
Err(ERR::ErrorVariableNotFound(name.to_string(), *pos).into())
}
},
)?;
@ -3380,11 +3354,9 @@ impl Engine {
.max_string_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return Err(EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(),
Position::NONE,
)
.into());
return Err(
ERR::ErrorDataTooLarge("Length of string".to_string(), Position::NONE).into(),
);
}
#[cfg(not(feature = "no_index"))]
@ -3394,11 +3366,7 @@ impl Engine {
.max_array_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
Position::NONE,
)
.into());
return Err(ERR::ErrorDataTooLarge("Size of array".to_string(), Position::NONE).into());
}
#[cfg(not(feature = "no_object"))]
@ -3408,11 +3376,9 @@ impl Engine {
.max_map_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of object map".to_string(),
Position::NONE,
)
.into());
return Err(
ERR::ErrorDataTooLarge("Size of object map".to_string(), Position::NONE).into(),
);
}
Ok(())
@ -3429,14 +3395,14 @@ impl Engine {
// Guard against too many operations
if self.max_operations() > 0 && *num_operations > self.max_operations() {
return Err(EvalAltResult::ErrorTooManyOperations(pos).into());
return Err(ERR::ErrorTooManyOperations(pos).into());
}
// Report progress - only in steps
if let Some(ref progress) = self.progress {
if let Some(token) = progress(*num_operations) {
// Terminate script if progress returns a termination token
return Err(EvalAltResult::ErrorTerminated(token, pos).into());
return Err(ERR::ErrorTerminated(token, pos).into());
}
}
@ -3456,15 +3422,11 @@ impl Engine {
.unwrap_or_else(|| map_std_type_name(name))
}
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][EvalAltResult::ErrorMismatchDataType]`>`.
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][ERR::ErrorMismatchDataType]`>`.
#[inline]
#[must_use]
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(),
pos,
)
.into()
ERR::ErrorMismatchDataType(self.map_type_name(type_name::<T>()).into(), typ.into(), pos)
.into()
}
}

View File

@ -12,8 +12,8 @@ use crate::engine::{
use crate::module::Namespace;
use crate::tokenizer::Token;
use crate::{
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, EvalAltResult, FnPtr,
Identifier, ImmutableString, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec,
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnPtr, Identifier,
ImmutableString, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, ERR,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -114,7 +114,7 @@ pub fn ensure_no_data_race(
.skip(if is_method_call { 1 } else { 0 })
.find(|(_, a)| a.is_locked())
{
return Err(EvalAltResult::ErrorDataRace(
return Err(ERR::ErrorDataRace(
format!("argument #{} of function '{}'", n + 1, fn_name.as_ref()),
Position::NONE,
)
@ -195,7 +195,7 @@ impl Engine {
let max_bitmask = if !allow_dynamic {
0
} else {
1usize << num_args.min(MAX_DYNAMIC_PARAMETERS)
1usize << usize::min(num_args, MAX_DYNAMIC_PARAMETERS)
};
let mut bitmask = 1usize; // Bitmask of which parameter to replace with `Dynamic`
@ -369,7 +369,7 @@ impl Engine {
KEYWORD_PRINT => {
if let Some(ref print) = self.print {
let text = result.into_immutable_string().map_err(|typ| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
pos,
@ -383,7 +383,7 @@ impl Engine {
KEYWORD_DEBUG => {
if let Some(ref debug) = self.debug {
let text = result.into_immutable_string().map_err(|typ| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
self.map_type_name(type_name::<ImmutableString>()).into(),
typ.into(),
pos,
@ -407,7 +407,7 @@ impl Engine {
crate::engine::FN_IDX_GET => {
assert!(args.len() == 2);
Err(EvalAltResult::ErrorIndexingType(
Err(ERR::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(args[0].type_name()),
@ -423,7 +423,7 @@ impl Engine {
crate::engine::FN_IDX_SET => {
assert!(args.len() == 3);
Err(EvalAltResult::ErrorIndexingType(
Err(ERR::ErrorIndexingType(
format!(
"{} [{}] = {}",
self.map_type_name(args[0].type_name()),
@ -440,7 +440,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_GET) => {
assert!(args.len() == 1);
Err(EvalAltResult::ErrorDotExpr(
Err(ERR::ErrorDotExpr(
format!(
"Unknown property '{}' - a getter is not registered for type '{}'",
&name[crate::engine::FN_GET.len()..],
@ -456,7 +456,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_SET) => {
assert!(args.len() == 2);
Err(EvalAltResult::ErrorDotExpr(
Err(ERR::ErrorDotExpr(
format!(
"No writable property '{}' - a setter is not registered for type '{}' to handle '{}'",
&name[crate::engine::FN_SET.len()..],
@ -469,11 +469,9 @@ impl Engine {
}
// Raise error
_ => Err(EvalAltResult::ErrorFunctionNotFound(
self.gen_call_signature(None, name, args),
pos,
)
.into()),
_ => Err(
ERR::ErrorFunctionNotFound(self.gen_call_signature(None, name, args), pos).into(),
),
}
}
@ -501,7 +499,7 @@ impl Engine {
) -> 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())
Err(ERR::ErrorRuntime(msg.into(), pos).into())
}
let fn_name = fn_name.as_ref();
@ -669,8 +667,8 @@ impl Engine {
scope, mods, state, lib, &mut None, statements, false, false, level,
)
.or_else(|err| match *err {
EvalAltResult::Return(out, _) => Ok(out),
EvalAltResult::LoopBreak(_, _) => {
ERR::Return(out, _) => Ok(out),
ERR::LoopBreak(_, _) => {
unreachable!("no outer loop scope to break out of")
}
_ => Err(err),
@ -707,7 +705,7 @@ impl Engine {
// If new functions are defined within the eval string, it is an error
#[cfg(not(feature = "no_function"))]
if !ast.shared_lib().is_empty() {
return Err(crate::ParseErrorType::WrongFnDefinition.into());
return Err(crate::PERR::WrongFnDefinition.into());
}
let statements = ast.statements();
@ -1071,7 +1069,7 @@ impl Engine {
}
return result.map_err(|err| {
EvalAltResult::ErrorInFunctionCall(
ERR::ErrorInFunctionCall(
KEYWORD_EVAL.to_string(),
mods.source
.as_ref()
@ -1241,9 +1239,9 @@ impl Engine {
}
}
let module = self.search_imports(mods, state, namespace).ok_or_else(|| {
EvalAltResult::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos)
})?;
let module = self
.search_imports(mods, state, namespace)
.ok_or_else(|| ERR::ErrorModuleNotFound(namespace.to_string(), namespace[0].pos))?;
// First search in script-defined functions (can override built-in)
let func = match module.get_qualified_fn(hash) {
@ -1310,7 +1308,7 @@ impl Engine {
Some(f) => unreachable!("unknown function type: {:?}", f),
None => Err(EvalAltResult::ErrorFunctionNotFound(
None => Err(ERR::ErrorFunctionNotFound(
self.gen_call_signature(Some(namespace), fn_name, &args),
pos,
)

View File

@ -7,8 +7,8 @@ use crate::plugin::PluginFunction;
use crate::tokenizer::{Token, TokenizeState};
use crate::types::dynamic::Variant;
use crate::{
calc_fn_hash, Dynamic, Engine, EvalAltResult, EvalContext, FuncArgs, Module, Position,
RhaiResult, RhaiResultOf, StaticVec,
calc_fn_hash, Dynamic, Engine, EvalContext, FuncArgs, Module, Position, RhaiResult,
RhaiResultOf, StaticVec, ERR,
};
use std::any::type_name;
#[cfg(feature = "no_std")]
@ -244,7 +244,7 @@ impl<'a> NativeCallContext<'a> {
let typ = self.engine().map_type_name(result.type_name());
result.try_cast().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
self.engine().map_type_name(type_name::<T>()).into(),
typ.into(),
Position::NONE,

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, RhaiResultOf};
use crate::{Dynamic, ERR, NativeCallContext, RhaiResultOf};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{any::TypeId, mem};
@ -124,7 +124,7 @@ macro_rules! def_register {
#[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()) {
return Err(EvalAltResult::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
return Err(ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -152,7 +152,7 @@ macro_rules! def_register {
#[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()) {
return Err(EvalAltResult::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
return Err(ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -180,7 +180,7 @@ macro_rules! def_register {
#[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()) {
return Err(EvalAltResult::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
return Err(ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -205,7 +205,7 @@ macro_rules! def_register {
#[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()) {
return Err(EvalAltResult::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
return Err(ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!

View File

@ -5,9 +5,7 @@ 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, RhaiError, RhaiResult, Scope, StaticVec,
};
use crate::{Dynamic, Engine, Module, Position, RhaiError, RhaiResult, Scope, StaticVec, ERR};
use std::mem;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -44,7 +42,7 @@ impl Engine {
err: RhaiError,
pos: Position,
) -> RhaiResult {
Err(EvalAltResult::ErrorInFunctionCall(
Err(ERR::ErrorInFunctionCall(
name,
fn_def
.lib
@ -70,7 +68,7 @@ impl Engine {
// Check for stack overflow
#[cfg(not(feature = "unchecked"))]
if level > self.max_call_levels() {
return Err(EvalAltResult::ErrorStackOverflow(pos).into());
return Err(ERR::ErrorStackOverflow(pos).into());
}
let orig_scope_len = scope.len();
@ -131,9 +129,9 @@ impl Engine {
)
.or_else(|err| match *err {
// Convert return statement to return value
EvalAltResult::Return(x, _) => Ok(x),
ERR::Return(x, _) => Ok(x),
// Error in sub function call
EvalAltResult::ErrorInFunctionCall(name, src, err, _) => {
ERR::ErrorInFunctionCall(name, src, err, _) => {
let fn_name = if src.is_empty() {
format!("{} < {}", name, fn_def.name)
} else {

View File

@ -82,8 +82,12 @@ mod tokenizer;
mod types;
mod r#unsafe;
/// Error encountered when parsing a script.
type PERR = ParseErrorType;
/// Evaluation result.
type ERR = EvalAltResult;
/// General evaluation error for Rhai scripts.
type RhaiError = Box<EvalAltResult>;
type RhaiError = Box<ERR>;
/// Generic [`Result`] type for Rhai functions.
type RhaiResultOf<T> = Result<T, RhaiError>;
/// General [`Result`] type for Rhai functions returning [`Dynamic`] values.

View File

@ -458,7 +458,7 @@ impl Module {
#[inline]
pub(crate) fn get_qualified_var(&self, hash_var: u64) -> RhaiResultOf<&Dynamic> {
self.all_variables.get(&hash_var).ok_or_else(|| {
crate::EvalAltResult::ErrorVariableNotFound(String::new(), crate::Position::NONE).into()
crate::ERR::ErrorVariableNotFound(String::new(), crate::Position::NONE).into()
})
}

View File

@ -1,4 +1,4 @@
use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, RhaiResultOf, Shared};
use crate::{Engine,ERR, Module, ModuleResolver, Position, RhaiResultOf, Shared};
use std::ops::AddAssign;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -128,14 +128,14 @@ impl ModuleResolver for ModuleResolversCollection {
match resolver.resolve(engine, source_path, path, pos) {
Ok(module) => return Ok(module),
Err(err) => match *err {
EvalAltResult::ErrorModuleNotFound(_, _) => continue,
EvalAltResult::ErrorInModule(_, err, _) => return Err(err),
ERR::ErrorModuleNotFound(_, _) => continue,
ERR::ErrorInModule(_, err, _) => return Err(err),
_ => panic!("ModuleResolver::resolve returns error that is not ErrorModuleNotFound or ErrorInModule"),
},
}
}
Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
Err(ERR::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -1,4 +1,4 @@
use crate::{Engine, EvalAltResult, Module, ModuleResolver, Position, RhaiResultOf, Shared};
use crate::{Engine,ERR, Module, ModuleResolver, Position, RhaiResultOf, Shared};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -45,6 +45,6 @@ impl ModuleResolver for DummyModuleResolver {
path: &str,
pos: Position,
) -> RhaiResultOf<Shared<Module>> {
Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
Err(ERR::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -3,7 +3,7 @@
use crate::func::native::shared_write_lock;
use crate::{
Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Scope,
Engine,ERR, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Scope,
Shared,
};
@ -288,17 +288,17 @@ impl ModuleResolver for FileModuleResolver {
let mut ast = engine
.compile_file(file_path.clone())
.map_err(|err| match *err {
EvalAltResult::ErrorSystem(_, err) if err.is::<IoError>() => {
Box::new(EvalAltResult::ErrorModuleNotFound(path.to_string(), pos))
ERR::ErrorSystem(_, err) if err.is::<IoError>() => {
Box::new(ERR::ErrorModuleNotFound(path.to_string(), pos))
}
_ => Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos)),
_ => Box::new(ERR::ErrorInModule(path.to_string(), err, pos)),
})?;
ast.set_source(path);
// Make a module from the AST
let m: Shared<Module> = Module::eval_ast_as_new(scope, &ast, engine)
.map_err(|err| Box::new(EvalAltResult::ErrorInModule(path.to_string(), err, pos)))?
.map_err(|err| Box::new(ERR::ErrorInModule(path.to_string(), err, pos)))?
.into();
// Put it into the cache
@ -331,10 +331,10 @@ impl ModuleResolver for FileModuleResolver {
ast
})
.map_err(|err| match *err {
EvalAltResult::ErrorSystem(_, err) if err.is::<IoError>() => {
EvalAltResult::ErrorModuleNotFound(path.to_string(), pos).into()
ERR::ErrorSystem(_, err) if err.is::<IoError>() => {
ERR::ErrorModuleNotFound(path.to_string(), pos).into()
}
_ => EvalAltResult::ErrorInModule(path.to_string(), err, pos).into(),
_ => ERR::ErrorInModule(path.to_string(), err, pos).into(),
}),
)
}

View File

@ -1,6 +1,5 @@
use crate::{
Engine, EvalAltResult, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Shared,
SmartString,
Engine, Identifier, Module, ModuleResolver, Position, RhaiResultOf, Shared, SmartString, ERR,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -136,7 +135,7 @@ impl ModuleResolver for StaticModuleResolver {
self.0
.get(path)
.cloned()
.ok_or_else(|| EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
.ok_or_else(|| ERR::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -1,7 +1,7 @@
#![allow(non_snake_case)]
use crate::plugin::*;
use crate::{def_package, EvalAltResult, Position, RhaiError, RhaiResultOf, INT};
use crate::{def_package, Position, RhaiError, RhaiResultOf, ERR, INT};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -11,7 +11,7 @@ use num_traits::Float;
#[inline(never)]
pub fn make_err(msg: impl Into<String>) -> RhaiError {
EvalAltResult::ErrorArithmetic(msg.into(), Position::NONE).into()
ERR::ErrorArithmetic(msg.into(), Position::NONE).into()
}
macro_rules! gen_arithmetic_functions {

View File

@ -4,8 +4,8 @@
use crate::engine::OP_EQUALS;
use crate::plugin::*;
use crate::{
def_package, Array, Dynamic, EvalAltResult, ExclusiveRange, FnPtr, InclusiveRange,
NativeCallContext, Position, RhaiResultOf, INT,
def_package, Array, Dynamic, ExclusiveRange, FnPtr, InclusiveRange, NativeCallContext,
Position, RhaiResultOf, ERR, INT,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -90,11 +90,7 @@ pub mod array_functions {
// Check if array will be over max size limit
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_array_size() > 0 && (len as usize) > _ctx.engine().max_array_size() {
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
Position::NONE,
)
.into());
return Err(ERR::ErrorDataTooLarge("Size of array".to_string(), Position::NONE).into());
}
if len as usize > array.len() {
@ -174,7 +170,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
array.extend(replace);
return;
@ -213,7 +209,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
return Array::new();
} else {
@ -275,7 +271,7 @@ pub mod array_functions {
mapper
.call_raw(&ctx, None, [item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(mapper.fn_name()) =>
{
mapper.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
@ -283,7 +279,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"map".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -316,7 +312,7 @@ pub mod array_functions {
if filter
.call_raw(&ctx, None, [item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
@ -324,7 +320,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"filter".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -362,9 +358,7 @@ pub mod array_functions {
if ctx
.call_fn_raw(OP_EQUALS, true, false, &mut [item, &mut value.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(ref fn_sig, _)
if fn_sig.starts_with(OP_EQUALS) =>
{
ERR::ErrorFunctionNotFound(ref fn_sig, _) if fn_sig.starts_with(OP_EQUALS) => {
if item.type_id() == value.type_id() {
// No default when comparing same type
Err(err)
@ -410,7 +404,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
return Ok(-1);
} else {
@ -421,9 +415,7 @@ pub mod array_functions {
if ctx
.call_fn_raw(OP_EQUALS, true, false, &mut [item, &mut value.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(ref fn_sig, _)
if fn_sig.starts_with(OP_EQUALS) =>
{
ERR::ErrorFunctionNotFound(ref fn_sig, _) if fn_sig.starts_with(OP_EQUALS) => {
if item.type_id() == value.type_id() {
// No default when comparing same type
Err(err)
@ -477,7 +469,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
return Ok(-1);
} else {
@ -488,7 +480,7 @@ pub mod array_functions {
if filter
.call_raw(&ctx, None, [item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
@ -496,7 +488,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"index_of".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -531,7 +523,7 @@ pub mod array_functions {
if filter
.call_raw(&ctx, None, [item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
@ -539,7 +531,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"some".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -573,7 +565,7 @@ pub mod array_functions {
if !filter
.call_raw(&ctx, None, [item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [item.clone(), (i as INT).into()])
@ -581,7 +573,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"all".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -668,7 +660,7 @@ pub mod array_functions {
result = reducer
.call_raw(&ctx, None, [result.clone(), item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(reducer.fn_name()) =>
{
reducer.call_raw(&ctx, None, [result, item, (i as INT).into()])
@ -676,7 +668,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"reduce".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -728,7 +720,7 @@ pub mod array_functions {
result = reducer
.call_raw(&ctx, None, [result.clone(), item.clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(reducer.fn_name()) =>
{
reducer.call_raw(&ctx, None, [result, item, ((len - 1 - i) as INT).into()])
@ -736,7 +728,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"reduce_rev".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -795,7 +787,7 @@ pub mod array_functions {
let type_id = array[0].type_id();
if array.iter().any(|a| a.type_id() != type_id) {
return Err(EvalAltResult::ErrorFunctionNotFound(
return Err(ERR::ErrorFunctionNotFound(
"sort() cannot be called with elements of different types".into(),
Position::NONE,
)
@ -873,7 +865,7 @@ pub mod array_functions {
if filter
.call_raw(&ctx, None, [array[x].clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [array[x].clone(), (i as INT).into()])
@ -881,7 +873,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"drain".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -931,7 +923,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
return Array::new();
} else {
@ -963,7 +955,7 @@ pub mod array_functions {
if !filter
.call_raw(&ctx, None, [array[x].clone()])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(fn_sig, _)
ERR::ErrorFunctionNotFound(fn_sig, _)
if fn_sig.starts_with(filter.fn_name()) =>
{
filter.call_raw(&ctx, None, [array[x].clone(), (i as INT).into()])
@ -971,7 +963,7 @@ pub mod array_functions {
_ => Err(err),
})
.map_err(|err| {
Box::new(EvalAltResult::ErrorInFunctionCall(
Box::new(ERR::ErrorInFunctionCall(
"retain".to_string(),
ctx.source().unwrap_or("").to_string(),
err,
@ -1021,7 +1013,7 @@ pub mod array_functions {
let arr_len = array.len();
start
.checked_abs()
.map_or(0, |n| arr_len - (n as usize).min(arr_len))
.map_or(0, |n| arr_len - usize::min(n as usize, arr_len))
} else if start as usize >= array.len() {
return mem::take(array);
} else {
@ -1056,9 +1048,7 @@ pub mod array_functions {
if !ctx
.call_fn_raw(OP_EQUALS, true, false, &mut [a1, a2])
.or_else(|err| match *err {
EvalAltResult::ErrorFunctionNotFound(ref fn_sig, _)
if fn_sig.starts_with(OP_EQUALS) =>
{
ERR::ErrorFunctionNotFound(ref fn_sig, _) if fn_sig.starts_with(OP_EQUALS) => {
if a1.type_id() == a2.type_id() {
// No default when comparing same type
Err(err)

View File

@ -3,8 +3,8 @@
use crate::plugin::*;
use crate::{
def_package, Blob, Dynamic, EvalAltResult, ExclusiveRange, InclusiveRange, NativeCallContext,
Position, RhaiResultOf, INT,
def_package, Blob, Dynamic, ExclusiveRange, InclusiveRange, NativeCallContext, Position,
RhaiResultOf, ERR, INT,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -46,11 +46,7 @@ pub mod blob_functions {
// Check if blob will be over max size limit
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_array_size() > 0 && len > _ctx.engine().max_array_size() {
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of BLOB".to_string(),
Position::NONE,
)
.into());
return Err(ERR::ErrorDataTooLarge("Size of BLOB".to_string(), Position::NONE).into());
}
let mut blob = Blob::new();
@ -121,11 +117,7 @@ pub mod blob_functions {
// Check if blob will be over max size limit
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_array_size() > 0 && (len as usize) > _ctx.engine().max_array_size() {
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of BLOB".to_string(),
Position::NONE,
)
.into());
return Err(ERR::ErrorDataTooLarge("Size of BLOB".to_string(), Position::NONE).into());
}
if len as usize > blob.len() {
@ -205,7 +197,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
blob.extend(replace);
return;
@ -244,7 +236,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return Blob::new();
} else {
@ -308,7 +300,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return Blob::new();
} else {
@ -344,7 +336,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return mem::take(blob);
} else {
@ -373,7 +365,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return 0;
} else {
@ -442,7 +434,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return;
} else {
@ -511,7 +503,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return 0.0;
} else {
@ -587,7 +579,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return;
} else {
@ -659,7 +651,7 @@ pub mod blob_functions {
let start = if start < 0 {
start
.checked_abs()
.map_or(0, |n| blob_len - (n as usize).min(blob_len))
.map_or(0, |n| blob_len - usize::min(n as usize, blob_len))
} else if start as usize >= blob_len {
return;
} else {

View File

@ -1,6 +1,6 @@
use crate::plugin::*;
use crate::types::dynamic::Variant;
use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, RhaiResultOf, INT};
use crate::{def_package, ExclusiveRange, InclusiveRange, RhaiResultOf, ERR, INT};
use std::iter::{ExactSizeIterator, FusedIterator};
use std::ops::{Range, RangeInclusive};
#[cfg(feature = "no_std")]
@ -26,10 +26,10 @@ where
#[cfg(not(feature = "unchecked"))]
if let Some(r) = from.checked_add(&step) {
if r == from {
return Err(EvalAltResult::ErrorInFunctionCall(
return Err(ERR::ErrorInFunctionCall(
"range".to_string(),
String::new(),
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
"step value cannot be zero".to_string(),
crate::Position::NONE,
)
@ -123,27 +123,18 @@ impl BitRange {
#[cfg(not(feature = "unchecked"))]
if offset >= BITS {
return Err(
EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into(),
);
return Err(ERR::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into());
}
offset
} else {
#[cfg(not(feature = "unchecked"))]
if let Some(abs_from) = from.checked_abs() {
if (abs_from as usize) > BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(
BITS,
from,
crate::Position::NONE,
)
.into());
return Err(ERR::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into());
}
BITS - (abs_from as usize)
} else {
return Err(
EvalAltResult::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into(),
);
return Err(ERR::ErrorBitFieldBounds(BITS, from, crate::Position::NONE).into());
}
#[cfg(feature = "unchecked")]
@ -337,8 +328,8 @@ def_package! {
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(),
EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
return Err(ERR::ErrorInFunctionCall("range".to_string(), "".to_string(),
ERR::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
crate::Position::NONE,
).into());
}
@ -399,8 +390,8 @@ def_package! {
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(),
EvalAltResult::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
return Err(ERR::ErrorInFunctionCall("range".to_string(), "".to_string(),
ERR::ErrorArithmetic("step value cannot be zero".to_string(), crate::Position::NONE).into(),
crate::Position::NONE,
).into());
}

View File

@ -1,7 +1,7 @@
use crate::def_package;
use crate::plugin::*;
use crate::types::dynamic::Tag;
use crate::{Dynamic, EvalAltResult, RhaiResultOf, INT};
use crate::{Dynamic, RhaiResultOf, ERR, INT};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -23,7 +23,7 @@ mod core_functions {
#[rhai_fn(name = "set_tag", set = "tag", return_raw)]
pub fn set_tag(value: &mut Dynamic, tag: INT) -> RhaiResultOf<()> {
if tag < Tag::MIN as INT {
Err(EvalAltResult::ErrorArithmetic(
Err(ERR::ErrorArithmetic(
format!(
"{} is too small to fit into a tag (must be between {} and {})",
tag,
@ -34,7 +34,7 @@ mod core_functions {
)
.into())
} else if tag > Tag::MAX as INT {
Err(EvalAltResult::ErrorArithmetic(
Err(ERR::ErrorArithmetic(
format!(
"{} is too large to fit into a tag (must be between {} and {})",
tag,

View File

@ -1,7 +1,7 @@
#![allow(non_snake_case)]
use crate::plugin::*;
use crate::{def_package, EvalAltResult, ExclusiveRange, InclusiveRange, RhaiResultOf, INT};
use crate::{def_package, ExclusiveRange, InclusiveRange, RhaiResultOf, ERR, INT};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -207,7 +207,7 @@ mod bit_field_functions {
let offset = index as usize;
if offset >= BITS {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else {
Ok((value & (1 << offset)) != 0)
}
@ -216,12 +216,12 @@ mod bit_field_functions {
// Count from end if negative
if offset > BITS {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else {
Ok((value & (1 << (BITS - offset))) != 0)
}
} else {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
}
}
#[rhai_fn(return_raw)]
@ -230,7 +230,7 @@ mod bit_field_functions {
let offset = index as usize;
if offset >= BITS {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else {
let mask = 1 << offset;
if new_value {
@ -245,7 +245,7 @@ mod bit_field_functions {
// Count from end if negative
if offset > BITS {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
} else {
let mask = 1 << offset;
if new_value {
@ -256,7 +256,7 @@ mod bit_field_functions {
Ok(())
}
} else {
Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into())
}
}
#[rhai_fn(name = "get_bits", return_raw)]
@ -281,7 +281,7 @@ mod bit_field_functions {
let offset = index as usize;
if offset >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}
offset
@ -290,11 +290,11 @@ mod bit_field_functions {
// Count from end if negative
if offset > BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}
BITS - offset
} else {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
};
let bits = if offset + bits as usize > BITS {
@ -343,7 +343,7 @@ mod bit_field_functions {
let offset = index as usize;
if offset >= BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}
offset
@ -352,11 +352,11 @@ mod bit_field_functions {
// Count from end if negative
if offset > BITS {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
}
BITS - offset
} else {
return Err(EvalAltResult::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
return Err(ERR::ErrorBitFieldBounds(BITS, index, Position::NONE).into());
};
let bits = if offset + bits as usize > BITS {

View File

@ -1,7 +1,7 @@
#![allow(non_snake_case)]
use crate::plugin::*;
use crate::{def_package, Position, RhaiResultOf, INT, INT_BASE};
use crate::{def_package, Position, RhaiResultOf, ERR, INT, INT_BASE};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -116,7 +116,7 @@ mod int_functions {
#[rhai_fn(name = "parse_int", return_raw)]
pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf<INT> {
if !(2..=36).contains(&radix) {
return Err(EvalAltResult::ErrorArithmetic(
return Err(ERR::ErrorArithmetic(
format!("Invalid radix: '{}'", radix),
Position::NONE,
)
@ -126,7 +126,7 @@ mod int_functions {
INT_BASE::from_str_radix(string.trim(), radix as u32)
.map(|v| v as INT)
.map_err(|err| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Error parsing integer number '{}': {}", string, err),
Position::NONE,
)
@ -265,11 +265,10 @@ mod float_functions {
#[rhai_fn(name = "to_int", return_raw)]
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),
Position::NONE,
Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
.into(),
)
.into())
} else {
Ok(x.trunc() as INT)
}
@ -277,11 +276,10 @@ mod float_functions {
#[rhai_fn(name = "to_int", return_raw)]
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),
Position::NONE,
Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
.into(),
)
.into())
} else {
Ok(x.trunc() as INT)
}
@ -289,7 +287,7 @@ mod float_functions {
#[rhai_fn(return_raw)]
pub fn parse_float(string: &str) -> RhaiResultOf<FLOAT> {
string.trim().parse::<FLOAT>().map_err(|err| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Error parsing floating-point number '{}': {}", string, err),
Position::NONE,
)
@ -475,7 +473,7 @@ mod decimal_functions {
Decimal::from_str(string)
.or_else(|_| Decimal::from_scientific(string))
.map_err(|err| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Error parsing decimal number '{}': {}", string, err),
Position::NONE,
)
@ -487,7 +485,7 @@ mod decimal_functions {
#[rhai_fn(name = "to_decimal", return_raw)]
pub fn f32_to_decimal(x: f32) -> RhaiResultOf<Decimal> {
Decimal::try_from(x).map_err(|_| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Cannot convert to Decimal: to_decimal({})", x),
Position::NONE,
)
@ -498,7 +496,7 @@ mod decimal_functions {
#[rhai_fn(name = "to_decimal", return_raw)]
pub fn f64_to_decimal(x: f64) -> RhaiResultOf<Decimal> {
Decimal::try_from(x).map_err(|_| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Cannot convert to Decimal: to_decimal({})", x),
Position::NONE,
)
@ -509,7 +507,7 @@ mod decimal_functions {
#[rhai_fn(return_raw)]
pub fn to_float(x: Decimal) -> RhaiResultOf<FLOAT> {
FLOAT::try_from(x).map_err(|_| {
EvalAltResult::ErrorArithmetic(
ERR::ErrorArithmetic(
format!("Cannot convert to floating-point: to_float({})", x),
Position::NONE,
)

View File

@ -509,7 +509,7 @@ mod string_functions {
// Check if string will be over max size limit
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
return Err(crate::EvalAltResult::ErrorDataTooLarge(
return Err(crate::ERR::ErrorDataTooLarge(
"Length of string".to_string(),
crate::Position::NONE,
)
@ -528,7 +528,7 @@ mod string_functions {
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size()
{
return Err(crate::EvalAltResult::ErrorDataTooLarge(
return Err(crate::ERR::ErrorDataTooLarge(
"Length of string".to_string(),
crate::Position::NONE,
)
@ -553,7 +553,7 @@ mod string_functions {
// Check if string will be over max size limit
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && len as usize > _ctx.engine().max_string_size() {
return Err(crate::EvalAltResult::ErrorDataTooLarge(
return Err(crate::ERR::ErrorDataTooLarge(
"Length of string".to_string(),
crate::Position::NONE,
)
@ -579,7 +579,7 @@ mod string_functions {
#[cfg(not(feature = "unchecked"))]
if _ctx.engine().max_string_size() > 0 && string.len() > _ctx.engine().max_string_size()
{
return Err(crate::EvalAltResult::ErrorDataTooLarge(
return Err(crate::ERR::ErrorDataTooLarge(
"Length of string".to_string(),
crate::Position::NONE,
)

View File

@ -16,8 +16,8 @@ use crate::tokenizer::{
use crate::types::dynamic::AccessMode;
use crate::{
calc_fn_hash, calc_qualified_fn_hash, calc_qualified_var_hash, Dynamic, Engine, ExclusiveRange,
Identifier, ImmutableString, InclusiveRange, LexError, ParseError, ParseErrorType, Position,
Scope, Shared, StaticVec, AST, INT,
Identifier, ImmutableString, InclusiveRange, LexError, ParseError, Position, Scope, Shared,
StaticVec, AST, INT, PERR,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -30,8 +30,6 @@ use std::{
pub type ParseResult<T> = Result<T, ParseError>;
type PERR = ParseErrorType;
type FnLib = BTreeMap<u64, Shared<ScriptFnDef>>;
/// Invalid variable name that acts as a search barrier in a [`Scope`].
@ -498,7 +496,7 @@ fn parse_fn_call(
let relax = false;
if !relax && settings.strict_var && index.is_none() {
return Err(ParseErrorType::ModuleUndefined(modules[0].name.to_string())
return Err(PERR::ModuleUndefined(modules[0].name.to_string())
.into_err(modules[0].pos));
}
@ -557,10 +555,8 @@ fn parse_fn_call(
let relax = false;
if !relax && settings.strict_var && index.is_none() {
return Err(ParseErrorType::ModuleUndefined(
modules[0].name.to_string(),
)
.into_err(modules[0].pos));
return Err(PERR::ModuleUndefined(modules[0].name.to_string())
.into_err(modules[0].pos));
}
modules.set_index(index);
@ -1259,8 +1255,7 @@ fn parse_primary(
if !settings.is_closure && settings.strict_var && index.is_none() {
// If the parent scope is not inside another capturing closure
Err(ParseErrorType::VariableUndefined(captured_var.to_string())
.into_err(pos))
Err(PERR::VariableUndefined(captured_var.to_string()).into_err(pos))
} else {
Ok(())
}
@ -1384,9 +1379,7 @@ fn parse_primary(
let index = state.access_var(&s, settings.pos);
if settings.strict_var && index.is_none() {
return Err(
ParseErrorType::VariableUndefined(s.to_string()).into_err(settings.pos)
);
return Err(PERR::VariableUndefined(s.to_string()).into_err(settings.pos));
}
let short_index = index.and_then(|x| {
@ -1586,8 +1579,7 @@ fn parse_postfix(
if !relax && settings.strict_var && index.is_none() {
return Err(
ParseErrorType::ModuleUndefined(namespace[0].name.to_string())
.into_err(namespace[0].pos),
PERR::ModuleUndefined(namespace[0].name.to_string()).into_err(namespace[0].pos)
);
}

View File

@ -1,7 +1,7 @@
//! Implement deserialization support of [`Dynamic`][crate::Dynamic] for [`serde`].
use crate::types::dynamic::Union;
use crate::{Dynamic, EvalAltResult, ImmutableString, LexError, Position, RhaiError, RhaiResultOf};
use crate::{Dynamic, ImmutableString, LexError, Position, RhaiError, RhaiResultOf, ERR};
use serde::de::{Error, IntoDeserializer, Visitor};
use serde::{Deserialize, Deserializer};
#[cfg(feature = "no_std")]
@ -31,7 +31,7 @@ impl<'de> DynamicDeserializer<'de> {
}
/// Shortcut for a type conversion error.
fn type_error_str<T>(&self, error: &str) -> RhaiResultOf<T> {
Err(EvalAltResult::ErrorMismatchOutputType(
Err(ERR::ErrorMismatchOutputType(
error.into(),
self.value.type_name().into(),
Position::NONE,

View File

@ -1,6 +1,6 @@
//! Implement serialization support of [`Dynamic`][crate::Dynamic] for [`serde`].
use crate::{Dynamic, EvalAltResult, Position, RhaiError, RhaiResult, RhaiResultOf};
use crate::{Dynamic, Position, RhaiError, RhaiResult, RhaiResultOf, ERR};
use serde::ser::{
Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct,
};
@ -83,7 +83,7 @@ pub fn to_dynamic<T: Serialize>(value: T) -> RhaiResult {
impl Error for RhaiError {
fn custom<T: fmt::Display>(err: T) -> Self {
EvalAltResult::ErrorRuntime(err.to_string().into(), Position::NONE).into()
ERR::ErrorRuntime(err.to_string().into(), Position::NONE).into()
}
}
@ -259,7 +259,7 @@ impl Serializer for &mut DynamicSerializer {
return Ok(Dynamic::from_blob(_v.to_vec()));
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"BLOB's are not supported with 'no_index'".into(),
Position::NONE,
@ -313,7 +313,7 @@ impl Serializer for &mut DynamicSerializer {
make_variant(_variant, content)
}
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -325,7 +325,7 @@ impl Serializer for &mut DynamicSerializer {
#[cfg(not(feature = "no_index"))]
return Ok(DynamicSerializer::new(crate::Array::new().into()));
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"arrays are not supported with 'no_index'".into(),
Position::NONE,
@ -359,7 +359,7 @@ impl Serializer for &mut DynamicSerializer {
array: crate::Array::with_capacity(_len),
});
#[cfg(any(feature = "no_object", feature = "no_index"))]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"tuples are not supported with 'no_index' or 'no_object'".into(),
Position::NONE,
@ -371,7 +371,7 @@ impl Serializer for &mut DynamicSerializer {
#[cfg(not(feature = "no_object"))]
return Ok(DynamicSerializer::new(crate::Map::new().into()));
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -400,7 +400,7 @@ impl Serializer for &mut DynamicSerializer {
map: crate::Map::new(),
});
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -422,7 +422,7 @@ impl SerializeSeq for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"arrays are not supported with 'no_index'".into(),
Position::NONE,
@ -435,7 +435,7 @@ impl SerializeSeq for DynamicSerializer {
#[cfg(not(feature = "no_index"))]
return Ok(self._value);
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"arrays are not supported with 'no_index'".into(),
Position::NONE,
@ -457,7 +457,7 @@ impl SerializeTuple for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"tuples are not supported with 'no_index'".into(),
Position::NONE,
@ -469,7 +469,7 @@ impl SerializeTuple for DynamicSerializer {
#[cfg(not(feature = "no_index"))]
return Ok(self._value);
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"tuples are not supported with 'no_index'".into(),
Position::NONE,
@ -491,7 +491,7 @@ impl SerializeTupleStruct for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"tuples are not supported with 'no_index'".into(),
Position::NONE,
@ -503,7 +503,7 @@ impl SerializeTupleStruct for DynamicSerializer {
#[cfg(not(feature = "no_index"))]
return Ok(self._value);
#[cfg(feature = "no_index")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"tuples are not supported with 'no_index'".into(),
Position::NONE,
@ -523,7 +523,7 @@ impl SerializeMap for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -537,11 +537,7 @@ impl SerializeMap for DynamicSerializer {
let key = std::mem::take(&mut self._key)
.into_immutable_string()
.map_err(|typ| {
EvalAltResult::ErrorMismatchDataType(
"string".into(),
typ.into(),
Position::NONE,
)
ERR::ErrorMismatchDataType("string".into(), typ.into(), Position::NONE)
})?;
let _value = _value.serialize(&mut *self)?;
let map = self._value.downcast_mut::<crate::Map>().unwrap();
@ -549,7 +545,7 @@ impl SerializeMap for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -566,7 +562,7 @@ impl SerializeMap for DynamicSerializer {
{
let _key: Dynamic = _key.serialize(&mut *self)?;
let _key = _key.into_immutable_string().map_err(|typ| {
EvalAltResult::ErrorMismatchDataType("string".into(), typ.into(), Position::NONE)
ERR::ErrorMismatchDataType("string".into(), typ.into(), Position::NONE)
})?;
let _value = _value.serialize(&mut *self)?;
let map = self._value.downcast_mut::<crate::Map>().unwrap();
@ -574,7 +570,7 @@ impl SerializeMap for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -586,7 +582,7 @@ impl SerializeMap for DynamicSerializer {
#[cfg(not(feature = "no_object"))]
return Ok(self._value);
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -612,7 +608,7 @@ impl SerializeStruct for DynamicSerializer {
Ok(())
}
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,
@ -624,7 +620,7 @@ impl SerializeStruct for DynamicSerializer {
#[cfg(not(feature = "no_object"))]
return Ok(self._value);
#[cfg(feature = "no_object")]
return Err(EvalAltResult::ErrorMismatchDataType(
return Err(ERR::ErrorMismatchDataType(
"".into(),
"object maps are not supported with 'no_object'".into(),
Position::NONE,

View File

@ -1,6 +1,6 @@
//! Implement deserialization support of [`ImmutableString`][crate::ImmutableString] for [`serde`].
use crate::{EvalAltResult, Position, RhaiError, RhaiResultOf};
use crate::{Position, RhaiError, RhaiResultOf, ERR};
use serde::de::{Deserializer, Visitor};
use std::any::type_name;
#[cfg(feature = "no_std")]
@ -19,12 +19,10 @@ impl<'a> StringSliceDeserializer<'a> {
}
/// Shortcut for a type conversion error.
fn type_error<T>(&self) -> RhaiResultOf<T> {
Err(EvalAltResult::ErrorMismatchOutputType(
type_name::<T>().into(),
"string".into(),
Position::NONE,
Err(
ERR::ErrorMismatchOutputType(type_name::<T>().into(), "string".into(), Position::NONE)
.into(),
)
.into())
}
}

View File

@ -3,8 +3,8 @@
use crate::tokenizer::is_valid_identifier;
use crate::types::dynamic::Variant;
use crate::{
Dynamic, Engine, EvalAltResult, FuncArgs, Identifier, Module, NativeCallContext, Position,
RhaiError, RhaiResult, RhaiResultOf, StaticVec, AST,
Dynamic, Engine, FuncArgs, Identifier, Module, NativeCallContext, Position, RhaiError,
RhaiResult, RhaiResultOf, StaticVec, AST, ERR,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -157,7 +157,7 @@ impl FnPtr {
let typ = engine.map_type_name(result.type_name());
result.try_cast().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
engine.map_type_name(type_name::<T>()).into(),
typ.into(),
Position::NONE,
@ -185,7 +185,7 @@ impl FnPtr {
let typ = context.engine().map_type_name(result.type_name());
result.try_cast().ok_or_else(|| {
EvalAltResult::ErrorMismatchOutputType(
ERR::ErrorMismatchOutputType(
context.engine().map_type_name(type_name::<T>()).into(),
typ.into(),
Position::NONE,
@ -255,7 +255,7 @@ impl TryFrom<Identifier> for FnPtr {
if is_valid_identifier(value.chars()) {
Ok(Self(value, StaticVec::new_const()))
} else {
Err(EvalAltResult::ErrorFunctionNotFound(value.to_string(), Position::NONE).into())
Err(ERR::ErrorFunctionNotFound(value.to_string(), Position::NONE).into())
}
}
}

View File

@ -1,7 +1,7 @@
//! Module containing error definitions for the parsing process.
use crate::tokenizer::is_valid_identifier;
use crate::{EvalAltResult, Position, RhaiError};
use crate::{Position, RhaiError, ERR};
#[cfg(feature = "no_std")]
use core_error::Error;
#[cfg(not(feature = "no_std"))]
@ -66,7 +66,7 @@ impl LexError {
}
}
/// Type of error encountered when parsing a script.
/// Error encountered when parsing a script.
///
/// Some errors never appear when certain features are turned on.
/// They still exist so that the application can turn features on and off without going through
@ -317,10 +317,10 @@ impl From<ParseErrorType> for RhaiError {
}
}
impl From<ParseErrorType> for EvalAltResult {
impl From<ParseErrorType> for ERR {
#[inline(always)]
fn from(err: ParseErrorType) -> Self {
EvalAltResult::ErrorParsing(err, Position::NONE)
ERR::ErrorParsing(err, Position::NONE)
}
}
@ -331,9 +331,9 @@ impl From<ParseError> for RhaiError {
}
}
impl From<ParseError> for EvalAltResult {
impl From<ParseError> for ERR {
#[inline(always)]
fn from(err: ParseError) -> Self {
EvalAltResult::ErrorParsing(*err.0, err.1)
ERR::ErrorParsing(*err.0, err.1)
}
}