stak_vm/
error.rs

1use crate::exception::Exception;
2use core::{
3    error,
4    fmt::{self, Debug, Display, Formatter},
5};
6
7/// An error of a virtual machine.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub enum Error {
10    /// Mismatched numbers of call arguments and procedure parameters.
11    ArgumentCount,
12    /// A cons expected.
13    ConsExpected,
14    /// An unexpected end of bytecode.
15    BytecodeEnd,
16    /// A format error.
17    Format(fmt::Error),
18    /// Invalid memory access.
19    InvalidMemoryAccess,
20    /// An illegal instruction detected.
21    IllegalInstruction,
22    /// An illegal primitive detected.
23    IllegalPrimitive,
24    /// A number expected.
25    NumberExpected,
26    /// Out of memory.
27    OutOfMemory,
28    /// A procedure expected.
29    ProcedureExpected,
30}
31
32impl Exception for Error {
33    fn is_critical(&self) -> bool {
34        match self {
35            Self::ArgumentCount
36            | Self::InvalidMemoryAccess
37            | Self::IllegalPrimitive
38            | Self::NumberExpected
39            | Self::ConsExpected
40            | Self::ProcedureExpected => false,
41            Self::BytecodeEnd | Self::Format(_) | Self::IllegalInstruction | Self::OutOfMemory => {
42                true
43            }
44        }
45    }
46}
47
48impl error::Error for Error {}
49
50impl Display for Error {
51    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
52        match self {
53            Self::ArgumentCount => write!(formatter, "invalid argument count"),
54            Self::BytecodeEnd => write!(formatter, "unexpected end of bytecode"),
55            Self::ConsExpected => write!(formatter, "cons expected"),
56            Self::Format(error) => write!(formatter, "{error}"),
57            Self::InvalidMemoryAccess => write!(formatter, "invalid memory access"),
58            Self::IllegalInstruction => write!(formatter, "illegal instruction"),
59            Self::IllegalPrimitive => write!(formatter, "illegal primitive"),
60            Self::NumberExpected => write!(formatter, "number expected"),
61            Self::OutOfMemory => write!(formatter, "out of memory"),
62            Self::ProcedureExpected => write!(formatter, "procedure expected"),
63        }
64    }
65}
66
67impl From<fmt::Error> for Error {
68    fn from(error: fmt::Error) -> Self {
69        Self::Format(error)
70    }
71}