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