1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
//! This module contains the error handling code for the interpreter.
//! It provides the `Error` struct, which is used to represent errors
//! that occur during execution.
/// A macro to create a new error with a kind and a message.
///
/// # Arguments
///
/// * `kind` - The kind of error.
/// * `message` - The error message.
///
/// # Returns
///
/// A new error with the given kind and message.
#[macro_export]
macro_rules! err {
($kind:expr, $($arg:tt)*) => {
Err($crate::error::Error::new(&format!($($arg)*), $kind))
}
}
/// The Error struct is used to represent errors that occur during execution.
/// It contains a message and a kind, which is used to categorise the error.
#[derive(Debug, PartialEq, Clone)]
pub struct Error {
pub message: String,
pub kind: ErrorKind,
}
impl Error {
/// Creates a new error with a message and a kind.
///
/// # Arguments
///
/// * `message` - The error message.
/// * `kind` - The kind of error.
///
/// # Returns
///
/// A new error with the given message and kind.
pub fn new(message: &str, kind: ErrorKind) -> Self {
Self {
message: message.to_string(),
kind,
}
}
}
/// The ErrorKind enum is used to sort errors into different types. This allows
/// error handling code to exhibit different behavior based on the kind of error.
#[derive(Debug, PartialEq, Clone)]
pub enum ErrorKind {
TypeError,
NameError,
DivisionByZero,
OverflowError,
SyntaxError,
NotImplemented,
}
/// Implements the `Display` trait for `ErrorKind`.
/// This allows `ErrorKind` to be formatted as a string when using the `write!` macro.
impl std::fmt::Display for ErrorKind {
// Match the error kind and return the corresponding string.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
ErrorKind::TypeError => "TypeError",
ErrorKind::NameError => "NameError",
ErrorKind::DivisionByZero => "DivisionByZero",
ErrorKind::OverflowError => "OverflowError",
ErrorKind::SyntaxError => "SyntaxError",
ErrorKind::NotImplemented => "NotImplemented",
};
write!(f, "{}", s)
}
}