Introduce EvalAltResult::ErrorSystem.

This commit is contained in:
Stephen Chung 2020-10-17 16:34:07 +08:00
parent 8eb6c821d4
commit 7a4905209c
4 changed files with 44 additions and 44 deletions

View File

@ -5,6 +5,12 @@ Rhai Release Notes
Version 0.19.3 Version 0.19.3
============== ==============
Breaking changes
----------------
* `EvalAltResult::ErrorReadingScriptFile` is removed in favor of the new `EvalAltResult::ErrorSystem`.
* `EvalAltResult::ErrorLoopBreak` is renamed to `EvalAltResult::LoopBreak`.
Version 0.19.2 Version 0.19.2
============== ==============

View File

@ -924,13 +924,19 @@ impl Engine {
#[inline] #[inline]
fn read_file(path: PathBuf) -> Result<String, Box<EvalAltResult>> { fn read_file(path: PathBuf) -> Result<String, Box<EvalAltResult>> {
let mut f = File::open(path.clone()).map_err(|err| { let mut f = File::open(path.clone()).map_err(|err| {
EvalAltResult::ErrorReadingScriptFile(path.clone(), Position::none(), err) EvalAltResult::ErrorSystem(
format!("Cannot open script file '{}'", path.to_string_lossy()),
err.into(),
)
})?; })?;
let mut contents = String::new(); let mut contents = String::new();
f.read_to_string(&mut contents).map_err(|err| { f.read_to_string(&mut contents).map_err(|err| {
EvalAltResult::ErrorReadingScriptFile(path.clone(), Position::none(), err) EvalAltResult::ErrorSystem(
format!("Cannot read script file '{}'", path.to_string_lossy()),
err.into(),
)
})?; })?;
Ok(contents) Ok(contents)

View File

@ -1814,10 +1814,8 @@ impl Engine {
match self.eval_stmt(scope, mods, state, lib, this_ptr, body, level) { match self.eval_stmt(scope, mods, state, lib, this_ptr, body, level) {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (), EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => { EvalAltResult::LoopBreak(true, _) => return Ok(Default::default()),
return Ok(Default::default())
}
_ => return Err(err), _ => return Err(err),
}, },
} }
@ -1834,8 +1832,8 @@ impl Engine {
match self.eval_stmt(scope, mods, state, lib, this_ptr, &x.0, level) { match self.eval_stmt(scope, mods, state, lib, this_ptr, &x.0, level) {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (), EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()), EvalAltResult::LoopBreak(true, _) => return Ok(Default::default()),
_ => return Err(err), _ => return Err(err),
}, },
} }
@ -1875,8 +1873,8 @@ impl Engine {
match self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level) { match self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level) {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (), EvalAltResult::LoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => break, EvalAltResult::LoopBreak(true, _) => break,
_ => return Err(err), _ => return Err(err),
}, },
} }
@ -1891,10 +1889,10 @@ impl Engine {
} }
// Continue statement // Continue statement
Stmt::Continue(pos) => EvalAltResult::ErrorLoopBreak(false, *pos).into(), Stmt::Continue(pos) => EvalAltResult::LoopBreak(false, *pos).into(),
// Break statement // Break statement
Stmt::Break(pos) => EvalAltResult::ErrorLoopBreak(true, *pos).into(), Stmt::Break(pos) => EvalAltResult::LoopBreak(true, *pos).into(),
// Return value // Return value
Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => { Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => {

View File

@ -15,10 +15,6 @@ use crate::stdlib::{
string::{String, ToString}, string::{String, ToString},
}; };
#[cfg(not(feature = "no_std"))]
#[cfg(not(target_arch = "wasm32"))]
use crate::stdlib::path::PathBuf;
/// Evaluation result. /// Evaluation result.
/// ///
/// All wrapped `Position` values represent the location in the script where the error occurs. /// All wrapped `Position` values represent the location in the script where the error occurs.
@ -27,16 +23,12 @@ use crate::stdlib::path::PathBuf;
#[derive(Debug)] #[derive(Debug)]
#[non_exhaustive] #[non_exhaustive]
pub enum EvalAltResult { pub enum EvalAltResult {
/// System error. Wrapped values are the error message and the internal error.
ErrorSystem(String, Box<dyn Error>),
/// Syntax error. /// Syntax error.
ErrorParsing(ParseErrorType, Position), ErrorParsing(ParseErrorType, Position),
/// Error reading from a script file. Wrapped value is the path of the script file.
///
/// Never appears under the `no_std` feature.
#[cfg(not(feature = "no_std"))]
#[cfg(not(target_arch = "wasm32"))]
ErrorReadingScriptFile(PathBuf, Position, std::io::Error),
/// Usage of an unknown variable. Wrapped value is the variable name. /// Usage of an unknown variable. Wrapped value is the variable name.
ErrorVariableNotFound(String, Position), ErrorVariableNotFound(String, Position),
/// Call to an unknown function. Wrapped value is the function signature. /// Call to an unknown function. Wrapped value is the function signature.
@ -96,7 +88,7 @@ pub enum EvalAltResult {
/// Breaking out of loops - not an error if within a loop. /// Breaking out of loops - not an error if within a loop.
/// The wrapped value, if true, means breaking clean out of the loop (i.e. a `break` statement). /// 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). /// The wrapped value, if false, means breaking the current context (i.e. a `continue` statement).
ErrorLoopBreak(bool, Position), LoopBreak(bool, Position),
/// Not an error: Value returned from a script via the `return` keyword. /// Not an error: Value returned from a script via the `return` keyword.
/// Wrapped value is the result value. /// Wrapped value is the result value.
Return(Dynamic, Position), Return(Dynamic, Position),
@ -105,10 +97,8 @@ pub enum EvalAltResult {
impl EvalAltResult { impl EvalAltResult {
pub(crate) fn desc(&self) -> &str { pub(crate) fn desc(&self) -> &str {
match self { match self {
#[cfg(not(feature = "no_std"))] #[allow(deprecated)]
#[cfg(not(target_arch = "wasm32"))] Self::ErrorSystem(_, s) => s.description(),
Self::ErrorReadingScriptFile(_, _, _) => "Cannot read from script file",
Self::ErrorParsing(p, _) => p.desc(), Self::ErrorParsing(p, _) => p.desc(),
Self::ErrorInFunctionCall(_, _, _) => "Error in called function", Self::ErrorInFunctionCall(_, _, _) => "Error in called function",
Self::ErrorInModule(_, _, _) => "Error in module", Self::ErrorInModule(_, _, _) => "Error in module",
@ -146,8 +136,8 @@ impl EvalAltResult {
Self::ErrorDataTooLarge(_, _, _, _) => "Data size exceeds maximum limit", Self::ErrorDataTooLarge(_, _, _, _) => "Data size exceeds maximum limit",
Self::ErrorTerminated(_) => "Script terminated.", Self::ErrorTerminated(_) => "Script terminated.",
Self::ErrorRuntime(_, _) => "Runtime error", Self::ErrorRuntime(_, _) => "Runtime error",
Self::ErrorLoopBreak(true, _) => "Break statement not inside a loop", Self::LoopBreak(true, _) => "Break statement not inside a loop",
Self::ErrorLoopBreak(false, _) => "Continue statement not inside a loop", Self::LoopBreak(false, _) => "Continue statement not inside a loop",
Self::Return(_, _) => "[Not Error] Function returns value", Self::Return(_, _) => "[Not Error] Function returns value",
} }
} }
@ -161,11 +151,8 @@ impl fmt::Display for EvalAltResult {
let pos = self.position(); let pos = self.position();
match self { match self {
#[cfg(not(feature = "no_std"))] Self::ErrorSystem(s, _) if s.is_empty() => f.write_str(desc)?,
#[cfg(not(target_arch = "wasm32"))] Self::ErrorSystem(s, _) => write!(f, "{}: {}", s, desc)?,
Self::ErrorReadingScriptFile(path, _, err) => {
write!(f, "{} '{}': {}", desc, path.display(), err)?
}
Self::ErrorParsing(p, _) => write!(f, "Syntax error: {}", p)?, Self::ErrorParsing(p, _) => write!(f, "Syntax error: {}", p)?,
@ -213,7 +200,7 @@ impl fmt::Display for EvalAltResult {
} }
Self::ErrorArithmetic(s, _) => f.write_str(s)?, Self::ErrorArithmetic(s, _) => f.write_str(s)?,
Self::ErrorLoopBreak(_, _) => f.write_str(desc)?, Self::LoopBreak(_, _) => f.write_str(desc)?,
Self::Return(_, _) => f.write_str(desc)?, Self::Return(_, _) => f.write_str(desc)?,
Self::ErrorArrayBounds(_, index, _) if *index < 0 => { Self::ErrorArrayBounds(_, index, _) if *index < 0 => {
@ -258,6 +245,13 @@ impl fmt::Display for EvalAltResult {
} }
} }
impl<T: AsRef<str>> From<T> for EvalAltResult {
#[inline(always)]
fn from(err: T) -> Self {
Self::ErrorRuntime(err.as_ref().to_string(), Position::none())
}
}
impl<T: AsRef<str>> From<T> for Box<EvalAltResult> { impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
#[inline(always)] #[inline(always)]
fn from(err: T) -> Self { fn from(err: T) -> Self {
@ -272,9 +266,7 @@ impl EvalAltResult {
/// Get the `Position` of this error. /// Get the `Position` of this error.
pub fn position(&self) -> Position { pub fn position(&self) -> Position {
match self { match self {
#[cfg(not(feature = "no_std"))] Self::ErrorSystem(_, _) => Position::none(),
#[cfg(not(target_arch = "wasm32"))]
Self::ErrorReadingScriptFile(_, pos, _) => *pos,
Self::ErrorParsing(_, pos) Self::ErrorParsing(_, pos)
| Self::ErrorFunctionNotFound(_, pos) | Self::ErrorFunctionNotFound(_, pos)
@ -301,7 +293,7 @@ impl EvalAltResult {
| Self::ErrorDataTooLarge(_, _, _, pos) | Self::ErrorDataTooLarge(_, _, _, pos)
| Self::ErrorTerminated(pos) | Self::ErrorTerminated(pos)
| Self::ErrorRuntime(_, pos) | Self::ErrorRuntime(_, pos)
| Self::ErrorLoopBreak(_, pos) | Self::LoopBreak(_, pos)
| Self::Return(_, pos) => *pos, | Self::Return(_, pos) => *pos,
} }
} }
@ -309,9 +301,7 @@ impl EvalAltResult {
/// Override the `Position` of this error. /// Override the `Position` of this error.
pub fn set_position(&mut self, new_position: Position) { pub fn set_position(&mut self, new_position: Position) {
match self { match self {
#[cfg(not(feature = "no_std"))] Self::ErrorSystem(_, _) => (),
#[cfg(not(target_arch = "wasm32"))]
Self::ErrorReadingScriptFile(_, pos, _) => *pos = new_position,
Self::ErrorParsing(_, pos) Self::ErrorParsing(_, pos)
| Self::ErrorFunctionNotFound(_, pos) | Self::ErrorFunctionNotFound(_, pos)
@ -338,7 +328,7 @@ impl EvalAltResult {
| Self::ErrorDataTooLarge(_, _, _, pos) | Self::ErrorDataTooLarge(_, _, _, pos)
| Self::ErrorTerminated(pos) | Self::ErrorTerminated(pos)
| Self::ErrorRuntime(_, pos) | Self::ErrorRuntime(_, pos)
| Self::ErrorLoopBreak(_, pos) | Self::LoopBreak(_, pos)
| Self::Return(_, pos) => *pos = new_position, | Self::Return(_, pos) => *pos = new_position,
} }
} }