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 bytecodes.
15    BytecodeEnd,
16    /// A format error.
17    Format(fmt::Error),
18    /// An illegal instruction detected.
19    IllegalInstruction,
20    /// An illegal primitive detected.
21    IllegalPrimitive,
22    /// A number expected.
23    NumberExpected,
24    /// Out of memory.
25    OutOfMemory,
26    /// A procedure expected.
27    ProcedureExpected,
28}
29
30impl Exception for Error {
31    fn is_critical(&self) -> bool {
32        match self {
33            Self::ArgumentCount
34            | Self::IllegalPrimitive
35            | Self::NumberExpected
36            | Self::ConsExpected
37            | Self::ProcedureExpected => false,
38            Self::BytecodeEnd | Self::Format(_) | Self::IllegalInstruction | Self::OutOfMemory => {
39                true
40            }
41        }
42    }
43}
44
45impl error::Error for Error {}
46
47impl Display for Error {
48    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
49        match self {
50            Self::ArgumentCount => write!(formatter, "invalid argument count"),
51            Self::BytecodeEnd => write!(formatter, "unexpected end of bytecodes"),
52            Self::ConsExpected => write!(formatter, "cons expected"),
53            Self::Format(error) => write!(formatter, "{error}"),
54            Self::IllegalInstruction => write!(formatter, "illegal instruction"),
55            Self::IllegalPrimitive => write!(formatter, "illegal primitive"),
56            Self::NumberExpected => write!(formatter, "number expected"),
57            Self::OutOfMemory => write!(formatter, "out of memory"),
58            Self::ProcedureExpected => write!(formatter, "procedure expected"),
59        }
60    }
61}
62
63impl From<fmt::Error> for Error {
64    fn from(error: fmt::Error) -> Self {
65        Self::Format(error)
66    }
67}