rhai/src/types/error.rs

456 lines
19 KiB
Rust
Raw Normal View History

2020-03-08 12:54:02 +01:00
//! Module containing error definitions for the evaluation process.
2020-03-04 15:00:01 +01:00
2020-11-20 09:52:28 +01:00
use crate::{Dynamic, ImmutableString, ParseErrorType, Position, INT};
2021-04-17 09:15:54 +02:00
#[cfg(feature = "no_std")]
use core_error::Error;
#[cfg(not(feature = "no_std"))]
use std::error::Error;
use std::fmt;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
2020-03-17 19:26:11 +01:00
2020-03-04 15:00:01 +01:00
/// Evaluation result.
///
2020-11-20 09:52:28 +01:00
/// All wrapped [`Position`] values represent the location in the script where the error occurs.
///
2020-10-27 04:30:38 +01:00
/// # Thread Safety
///
2020-11-20 09:52:28 +01:00
/// Currently, [`EvalAltResult`] is neither [`Send`] nor [`Sync`].
/// Turn on the `sync` feature to make it [`Send`] `+` [`Sync`].
2020-03-04 15:00:01 +01:00
#[derive(Debug)]
2020-06-25 05:07:46 +02:00
#[non_exhaustive]
2020-03-04 15:00:01 +01:00
pub enum EvalAltResult {
2020-10-17 10:34:07 +02:00
/// System error. Wrapped values are the error message and the internal error.
2020-10-25 14:48:18 +01:00
#[cfg(not(feature = "sync"))]
2020-10-17 10:34:07 +02:00
ErrorSystem(String, Box<dyn Error>),
2020-10-25 14:48:18 +01:00
/// System error. Wrapped values are the error message and the internal error.
#[cfg(feature = "sync")]
ErrorSystem(String, Box<dyn Error + Send + Sync>),
2020-10-17 10:34:07 +02:00
2020-03-04 15:00:01 +01:00
/// Syntax error.
ErrorParsing(ParseErrorType, Position),
2020-03-30 16:19:37 +02:00
2020-10-05 07:45:57 +02:00
/// Usage of an unknown variable. Wrapped value is the variable name.
ErrorVariableNotFound(String, Position),
/// Call to an unknown function. Wrapped value is the function signature.
2020-03-04 15:00:01 +01:00
ErrorFunctionNotFound(String, Position),
/// An error has occurred inside a called function.
2020-12-30 14:12:51 +01:00
/// Wrapped values are the function name, function source, and the interior error.
ErrorInFunctionCall(String, String, Box<EvalAltResult>, Position),
2020-11-25 02:36:06 +01:00
/// Usage of an unknown [module][crate::Module]. Wrapped value is the [module][crate::Module] name.
2020-10-05 07:45:57 +02:00
ErrorModuleNotFound(String, Position),
2020-11-25 02:36:06 +01:00
/// An error has occurred while loading a [module][crate::Module].
/// Wrapped value are the [module][crate::Module] name and the interior error.
ErrorInModule(String, Box<EvalAltResult>, Position),
2020-07-30 17:29:11 +02:00
/// Access to `this` that is not bound.
ErrorUnboundThis(Position),
2020-10-03 17:27:30 +02:00
/// Data is not of the required type.
/// Wrapped values are the type requested and type of the actual result.
ErrorMismatchDataType(String, String, Position),
2020-10-05 07:45:57 +02:00
/// Returned type is not the same as the required output type.
/// Wrapped values are the type requested and type of the actual result.
ErrorMismatchOutputType(String, String, Position),
2020-03-04 15:00:01 +01:00
/// Array access out-of-bounds.
/// Wrapped values are the current number of elements in the array and the index number.
ErrorArrayBounds(usize, INT, Position),
2020-03-04 15:00:01 +01:00
/// String indexing out-of-bounds.
/// Wrapped values are the current number of characters in the string and the index number.
ErrorStringBounds(usize, INT, Position),
2021-06-02 08:29:18 +02:00
/// Bit-field indexing out-of-bounds.
/// Wrapped values are the current number of bits in the bit-field and the index number.
ErrorBitFieldBounds(usize, INT, Position),
/// Trying to index into a type that has no indexer function defined. Wrapped value is the type name.
ErrorIndexingType(String, Position),
2020-03-04 15:00:01 +01:00
/// The `for` statement encounters a type that is not an iterator.
ErrorFor(Position),
2020-10-05 07:45:57 +02:00
/// Data race detected when accessing a variable. Wrapped value is the variable name.
2020-08-02 07:33:51 +02:00
ErrorDataRace(String, Position),
2020-10-05 07:45:57 +02:00
/// Assignment to a constant variable. Wrapped value is the variable name.
2020-03-13 11:12:41 +01:00
ErrorAssignmentToConstant(String, Position),
2020-10-05 07:45:57 +02:00
/// Inappropriate property access. Wrapped value is the property name.
ErrorDotExpr(String, Position),
2020-03-04 15:00:01 +01:00
/// Arithmetic error encountered. Wrapped value is the error message.
ErrorArithmetic(String, Position),
/// Number of operations over maximum limit.
ErrorTooManyOperations(Position),
2020-11-25 02:36:06 +01:00
/// [Modules][crate::Module] over maximum limit.
2020-05-15 15:40:54 +02:00
ErrorTooManyModules(Position),
2020-03-27 07:34:01 +01:00
/// Call stack over maximum limit.
ErrorStackOverflow(Position),
2020-11-02 04:04:45 +01:00
/// Data value over maximum size limit. Wrapped value is the type name.
ErrorDataTooLarge(String, Position),
/// The script is prematurely terminated. Wrapped value is the termination token.
ErrorTerminated(Dynamic, Position),
/// Run-time error encountered. Wrapped value is the error token.
ErrorRuntime(Dynamic, Position),
2020-03-30 16:19:37 +02:00
2020-03-17 10:33:37 +01:00
/// Breaking out of loops - not an error if within a loop.
2020-04-01 10:22:18 +02:00
/// The wrapped value, if true, means breaking clean out of the loop (i.e. a `break` statement).
/// The wrapped value, if false, means breaking the current context (i.e. a `continue` statement).
2020-10-17 10:34:07 +02:00
LoopBreak(bool, Position),
2020-03-04 15:00:01 +01:00
/// Not an error: Value returned from a script via the `return` keyword.
/// Wrapped value is the result value.
Return(Dynamic, Position),
}
2020-03-14 16:39:45 +01:00
impl Error for EvalAltResult {}
2020-03-08 12:54:02 +01:00
impl fmt::Display for EvalAltResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020-03-04 15:00:01 +01:00
match self {
2021-07-02 05:50:24 +02:00
Self::ErrorSystem(s, err) => match s.as_str() {
"" => write!(f, "{}", err),
s => write!(f, "{}: {}", s, err),
}?,
2020-03-30 16:19:37 +02:00
Self::ErrorParsing(p, _) => write!(f, "Syntax error: {}", p)?,
2020-03-30 16:19:37 +02:00
2020-10-12 16:49:51 +02:00
#[cfg(not(feature = "no_function"))]
2020-12-30 14:12:51 +01:00
Self::ErrorInFunctionCall(s, src, err, _) if crate::engine::is_anonymous_fn(s) => {
2021-03-04 16:47:52 +01:00
write!(f, "{} in call to closure", err)?;
2020-12-30 14:12:51 +01:00
if !src.is_empty() {
write!(f, " @ '{}'", src)?;
}
2020-10-12 16:49:51 +02:00
}
2020-12-30 14:12:51 +01:00
Self::ErrorInFunctionCall(s, src, err, _) => {
2021-03-04 16:47:52 +01:00
write!(f, "{} in call to function {}", err, s)?;
2020-12-30 14:12:51 +01:00
if !src.is_empty() {
write!(f, " @ '{}'", src)?;
}
}
2020-12-30 14:12:51 +01:00
Self::ErrorInModule(s, err, _) if s.is_empty() => {
write!(f, "Error in module: {}", err)?
}
2021-10-27 17:30:25 +02:00
Self::ErrorInModule(s, err, _) => write!(f, "Error in module {}: {}", s, err)?,
2021-06-24 08:55:53 +02:00
Self::ErrorFunctionNotFound(s, _) => write!(f, "Function not found: {}", s)?,
Self::ErrorVariableNotFound(s, _) => write!(f, "Variable not found: {}", s)?,
2021-10-27 17:30:25 +02:00
Self::ErrorModuleNotFound(s, _) => write!(f, "Module not found: {}", s)?,
2021-06-24 08:55:53 +02:00
Self::ErrorDataRace(s, _) => {
write!(f, "Data race detected when accessing variable: {}", s)?
}
2021-07-02 05:50:24 +02:00
Self::ErrorDotExpr(s, _) => match s.as_str() {
"" => f.write_str("Malformed dot expression"),
s => f.write_str(s),
}?,
2021-10-27 17:30:25 +02:00
Self::ErrorIndexingType(s, _) => write!(f, "Indexer not registered for {}", s)?,
2021-06-24 08:55:53 +02:00
Self::ErrorUnboundThis(_) => f.write_str("'this' is not bound")?,
Self::ErrorFor(_) => f.write_str("For loop expects a type with an iterator defined")?,
Self::ErrorTooManyOperations(_) => f.write_str("Too many operations")?,
Self::ErrorTooManyModules(_) => f.write_str("Too many modules imported")?,
Self::ErrorStackOverflow(_) => f.write_str("Stack overflow")?,
Self::ErrorTerminated(_, _) => f.write_str("Script terminated")?,
2020-03-29 17:53:35 +02:00
2021-06-24 08:55:53 +02:00
Self::ErrorRuntime(d, _) if d.is::<()>() => f.write_str("Runtime error")?,
2021-07-02 05:50:24 +02:00
Self::ErrorRuntime(d, _)
if d.read_lock::<ImmutableString>()
.map_or(false, |v| v.is_empty()) =>
{
write!(f, "Runtime error")?
}
2021-06-24 08:55:53 +02:00
Self::ErrorRuntime(d, _) => write!(f, "Runtime error: {}", d)?,
2020-03-30 16:19:37 +02:00
Self::ErrorAssignmentToConstant(s, _) => write!(f, "Cannot modify constant {}", s)?,
2021-07-02 05:50:24 +02:00
Self::ErrorMismatchOutputType(s, r, _) => match (r.as_str(), s.as_str()) {
("", s) => write!(f, "Output type is incorrect, expecting {}", s),
(r, "") => write!(f, "Output type is incorrect: {}", r),
(r, s) => write!(f, "Output type is incorrect: {} (expecting {})", r, s),
}?,
Self::ErrorMismatchDataType(s, r, _) => match (r.as_str(), s.as_str()) {
("", s) => write!(f, "Data type is incorrect, expecting {}", s),
(r, "") => write!(f, "Data type is incorrect: {}", r),
(r, s) => write!(f, "Data type is incorrect: {} (expecting {})", r, s),
}?,
Self::ErrorArithmetic(s, _) => match s.as_str() {
"" => f.write_str("Arithmetic error"),
s => f.write_str(s),
}?,
Self::LoopBreak(true, _) => f.write_str("'break' not inside a loop")?,
Self::LoopBreak(false, _) => f.write_str("'continue' not inside a loop")?,
Self::Return(_, _) => f.write_str("NOT AN ERROR - function returns value")?,
Self::ErrorArrayBounds(max, index, _) => match max {
0 => write!(f, "Array index {} out of bounds: array is empty", index),
1 => write!(
f,
"Array index {} out of bounds: only 1 element in the array",
index
),
_ => write!(
f,
"Array index {} out of bounds: only {} elements in the array",
index, max
),
}?,
Self::ErrorStringBounds(max, index, _) => match max {
0 => write!(f, "String index {} out of bounds: string is empty", index),
1 => write!(
f,
"String index {} out of bounds: only 1 character in the string",
index
),
_ => write!(
f,
"String index {} out of bounds: only {} characters in the string",
index, max
),
}?,
2021-06-02 08:29:18 +02:00
Self::ErrorBitFieldBounds(max, index, _) => write!(
f,
"Bit-field index {} out of bounds: only {} bits in the bit-field",
index, max
)?,
2020-11-02 04:04:45 +01:00
Self::ErrorDataTooLarge(typ, _) => write!(f, "{} exceeds maximum limit", typ)?,
}
// Do not write any position if None
2021-06-24 08:55:53 +02:00
if !self.position().is_none() {
write!(f, " ({})", self.position())?;
2020-03-04 15:00:01 +01:00
}
Ok(())
2020-03-04 15:00:01 +01:00
}
}
2020-10-17 10:34:07 +02:00
impl<T: AsRef<str>> From<T> for EvalAltResult {
2021-10-19 14:16:36 +02:00
#[inline(never)]
2020-10-17 10:34:07 +02:00
fn from(err: T) -> Self {
2020-11-20 09:52:28 +01:00
Self::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE)
2020-10-17 10:34:07 +02:00
}
}
impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
2021-10-19 14:16:36 +02:00
#[inline(never)]
fn from(err: T) -> Self {
2021-10-11 09:49:51 +02:00
EvalAltResult::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE).into()
}
}
impl EvalAltResult {
/// Is this a pseudo error? A pseudo error is one that does not occur naturally.
///
2021-02-28 07:38:34 +01:00
/// [`LoopBreak`][EvalAltResult::LoopBreak] and [`Return`][EvalAltResult::Return] are pseudo errors.
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-28 12:06:05 +02:00
pub const fn is_pseudo_error(&self) -> bool {
match self {
Self::LoopBreak(_, _) | Self::Return(_, _) => true,
_ => false,
}
}
/// Can this error be caught?
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-28 12:06:05 +02:00
pub const fn is_catchable(&self) -> bool {
match self {
Self::ErrorSystem(_, _) => false,
Self::ErrorParsing(_, _) => false,
Self::ErrorFunctionNotFound(_, _)
2020-12-30 14:12:51 +01:00
| Self::ErrorInFunctionCall(_, _, _, _)
| Self::ErrorInModule(_, _, _)
| Self::ErrorUnboundThis(_)
| Self::ErrorMismatchDataType(_, _, _)
| Self::ErrorArrayBounds(_, _, _)
| Self::ErrorStringBounds(_, _, _)
2021-06-02 08:29:18 +02:00
| Self::ErrorBitFieldBounds(_, _, _)
| Self::ErrorIndexingType(_, _)
| Self::ErrorFor(_)
| Self::ErrorVariableNotFound(_, _)
| Self::ErrorModuleNotFound(_, _)
| Self::ErrorDataRace(_, _)
| Self::ErrorAssignmentToConstant(_, _)
| Self::ErrorMismatchOutputType(_, _, _)
| Self::ErrorDotExpr(_, _)
| Self::ErrorArithmetic(_, _)
| Self::ErrorRuntime(_, _) => true,
Self::ErrorTooManyOperations(_)
| Self::ErrorTooManyModules(_)
| Self::ErrorStackOverflow(_)
2020-11-02 04:04:45 +01:00
| Self::ErrorDataTooLarge(_, _)
| Self::ErrorTerminated(_, _) => false,
2021-06-28 12:06:05 +02:00
Self::LoopBreak(_, _) | Self::Return(_, _) => false,
}
}
/// Is this error a system exception?
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-28 12:06:05 +02:00
pub const fn is_system_exception(&self) -> bool {
match self {
Self::ErrorSystem(_, _) => true,
Self::ErrorParsing(_, _) => true,
Self::ErrorTooManyOperations(_)
| Self::ErrorTooManyModules(_)
| Self::ErrorStackOverflow(_)
2020-11-02 04:04:45 +01:00
| Self::ErrorDataTooLarge(_, _) => true,
2020-11-02 04:04:45 +01:00
Self::ErrorTerminated(_, _) => true,
_ => false,
}
}
2020-11-25 02:36:06 +01:00
/// Get the [position][Position] of this error.
2021-02-28 07:38:34 +01:00
#[cfg(not(feature = "no_object"))]
pub(crate) fn dump_fields(&self, map: &mut crate::Map) {
map.insert(
"error".into(),
2021-05-22 13:14:24 +02:00
format!("{:?}", self)
.split('(')
.next()
2021-08-26 17:58:41 +02:00
.expect("debug format of error is `ErrorXXX(...)`")
2021-05-22 13:14:24 +02:00
.into(),
2021-02-28 07:38:34 +01:00
);
match self {
Self::LoopBreak(_, _) | Self::Return(_, _) => (),
Self::ErrorSystem(_, _)
| Self::ErrorParsing(_, _)
| Self::ErrorUnboundThis(_)
| Self::ErrorFor(_)
| Self::ErrorArithmetic(_, _)
| Self::ErrorTooManyOperations(_)
| Self::ErrorTooManyModules(_)
| Self::ErrorStackOverflow(_)
| Self::ErrorRuntime(_, _) => (),
Self::ErrorFunctionNotFound(f, _) => {
map.insert("function".into(), f.into());
}
Self::ErrorInFunctionCall(f, s, _, _) => {
map.insert("function".into(), f.into());
map.insert("source".into(), s.into());
}
Self::ErrorInModule(m, _, _) => {
map.insert("module".into(), m.into());
}
Self::ErrorMismatchDataType(r, a, _) | Self::ErrorMismatchOutputType(r, a, _) => {
map.insert("requested".into(), r.into());
map.insert("actual".into(), a.into());
}
2021-06-02 08:29:18 +02:00
Self::ErrorArrayBounds(n, i, _)
| Self::ErrorStringBounds(n, i, _)
| Self::ErrorBitFieldBounds(n, i, _) => {
2021-02-28 07:38:34 +01:00
map.insert("length".into(), (*n as INT).into());
map.insert("index".into(), (*i as INT).into());
}
Self::ErrorIndexingType(t, _) => {
map.insert("type".into(), t.into());
}
Self::ErrorVariableNotFound(v, _)
| Self::ErrorDataRace(v, _)
| Self::ErrorAssignmentToConstant(v, _) => {
map.insert("variable".into(), v.into());
}
Self::ErrorModuleNotFound(m, _) => {
map.insert("module".into(), m.into());
}
Self::ErrorDotExpr(p, _) => {
map.insert("property".into(), p.into());
}
Self::ErrorDataTooLarge(t, _) => {
map.insert("type".into(), t.into());
}
Self::ErrorTerminated(t, _) => {
map.insert("token".into(), t.clone());
}
};
}
/// Get the [position][Position] of this error.
2021-06-12 16:47:43 +02:00
#[must_use]
2021-06-28 12:06:05 +02:00
pub const fn position(&self) -> Position {
match self {
2020-11-20 09:52:28 +01:00
Self::ErrorSystem(_, _) => Position::NONE,
Self::ErrorParsing(_, pos)
| Self::ErrorFunctionNotFound(_, pos)
2020-12-30 14:12:51 +01:00
| Self::ErrorInFunctionCall(_, _, _, pos)
| Self::ErrorInModule(_, _, pos)
2020-07-30 17:29:11 +02:00
| Self::ErrorUnboundThis(pos)
2020-10-03 17:27:30 +02:00
| Self::ErrorMismatchDataType(_, _, pos)
| Self::ErrorArrayBounds(_, _, pos)
| Self::ErrorStringBounds(_, _, pos)
2021-06-02 08:29:18 +02:00
| Self::ErrorBitFieldBounds(_, _, pos)
| Self::ErrorIndexingType(_, pos)
| Self::ErrorFor(pos)
| Self::ErrorVariableNotFound(_, pos)
2020-05-04 13:36:58 +02:00
| Self::ErrorModuleNotFound(_, pos)
2020-08-02 07:33:51 +02:00
| Self::ErrorDataRace(_, pos)
2020-03-13 11:12:41 +01:00
| Self::ErrorAssignmentToConstant(_, pos)
2020-07-03 04:45:01 +02:00
| Self::ErrorMismatchOutputType(_, _, pos)
| Self::ErrorDotExpr(_, pos)
| Self::ErrorArithmetic(_, pos)
| Self::ErrorTooManyOperations(pos)
2020-05-15 15:40:54 +02:00
| Self::ErrorTooManyModules(pos)
2020-03-27 07:34:01 +01:00
| Self::ErrorStackOverflow(pos)
2020-11-02 04:04:45 +01:00
| Self::ErrorDataTooLarge(_, pos)
| Self::ErrorTerminated(_, pos)
| Self::ErrorRuntime(_, pos)
2020-10-17 10:34:07 +02:00
| Self::LoopBreak(_, pos)
| Self::Return(_, pos) => *pos,
}
}
2021-06-12 16:47:43 +02:00
/// Remove the [position][Position] information from this error.
///
/// The [position][Position] of this error is set to [`NONE`][Position::NONE] afterwards.
pub fn clear_position(&mut self) -> &mut Self {
self.set_position(Position::NONE)
}
2021-02-28 07:38:34 +01:00
/// Remove the [position][Position] information from this error and return it.
///
/// The [position][Position] of this error is set to [`NONE`][Position::NONE] afterwards.
pub fn take_position(&mut self) -> Position {
let pos = self.position();
2021-01-08 07:29:57 +01:00
self.set_position(Position::NONE);
2021-02-28 07:38:34 +01:00
pos
2021-01-08 07:29:57 +01:00
}
2020-11-25 02:36:06 +01:00
/// Override the [position][Position] of this error.
2021-06-12 16:47:43 +02:00
pub fn set_position(&mut self, new_position: Position) -> &mut Self {
match self {
2020-10-17 10:34:07 +02:00
Self::ErrorSystem(_, _) => (),
Self::ErrorParsing(_, pos)
| Self::ErrorFunctionNotFound(_, pos)
2020-12-30 14:12:51 +01:00
| Self::ErrorInFunctionCall(_, _, _, pos)
| Self::ErrorInModule(_, _, pos)
2020-07-30 17:29:11 +02:00
| Self::ErrorUnboundThis(pos)
2020-10-03 17:27:30 +02:00
| Self::ErrorMismatchDataType(_, _, pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorArrayBounds(_, _, pos)
| Self::ErrorStringBounds(_, _, pos)
2021-06-02 08:29:18 +02:00
| Self::ErrorBitFieldBounds(_, _, pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorIndexingType(_, pos)
| Self::ErrorFor(pos)
| Self::ErrorVariableNotFound(_, pos)
2020-05-04 13:36:58 +02:00
| Self::ErrorModuleNotFound(_, pos)
2020-08-02 07:33:51 +02:00
| Self::ErrorDataRace(_, pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorAssignmentToConstant(_, pos)
2020-07-03 04:45:01 +02:00
| Self::ErrorMismatchOutputType(_, _, pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorDotExpr(_, pos)
| Self::ErrorArithmetic(_, pos)
| Self::ErrorTooManyOperations(pos)
2020-05-15 15:40:54 +02:00
| Self::ErrorTooManyModules(pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorStackOverflow(pos)
2020-11-02 04:04:45 +01:00
| Self::ErrorDataTooLarge(_, pos)
| Self::ErrorTerminated(_, pos)
2020-04-05 06:37:07 +02:00
| Self::ErrorRuntime(_, pos)
2020-10-17 10:34:07 +02:00
| Self::LoopBreak(_, pos)
2020-04-05 06:37:07 +02:00
| Self::Return(_, pos) => *pos = new_position,
}
2021-06-12 16:47:43 +02:00
self
}
2020-11-20 09:52:28 +01:00
/// Consume the current [`EvalAltResult`] and return a new one with the specified [`Position`]
/// if the current position is [`Position::None`].
2021-10-19 14:16:36 +02:00
#[inline(never)]
2021-06-12 16:47:43 +02:00
#[must_use]
2020-10-11 15:58:11 +02:00
pub(crate) fn fill_position(mut self: Box<Self>, new_position: Position) -> Box<Self> {
2020-06-01 09:25:22 +02:00
if self.position().is_none() {
self.set_position(new_position);
}
self
}
}