Skip to main content

bvm_lang/
error.rs

1//! Execution failures raised by the interpreter loop.
2//!
3//! Bytecode handed to [`Vm::run`](crate::Vm::run) is treated as untrusted: a
4//! malformed program (an out-of-range register, a jump past the end of the code,
5//! a constant index that does not exist) is reported as a [`VmError`] rather than
6//! panicking. Runtime faults from otherwise well-formed code — a type mismatch, a
7//! division by zero, integer overflow — surface the same way. Every variant
8//! carries enough context to point at the specific fault.
9
10use core::fmt;
11
12/// An error raised while executing a [`Chunk`](crate::Chunk).
13///
14/// Errors fall into two groups. *Structural* faults (`BadRegister`,
15/// `BadConstant`, `BadJump`, `NoTerminator`) mean the bytecode itself is
16/// malformed and would never be produced by a correct compiler; they are
17/// reported instead of trusted so that hand-written or corrupted programs cannot
18/// drive the VM into a panic. *Runtime* faults (`TypeMismatch`, `DivideByZero`,
19/// `IntegerOverflow`) come from executing well-formed instructions against
20/// operands that do not satisfy their contract.
21#[derive(Debug, Clone, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum VmError {
24    /// An operation received an operand of the wrong kind — for example, adding a
25    /// boolean to an integer, or branching on a value that is not a boolean.
26    ///
27    /// The field names the operation that rejected its operand (`"add"`,
28    /// `"jump-if-true"`, …) so a caller can report which instruction faulted.
29    TypeMismatch {
30        /// The operation that rejected its operand(s).
31        op: &'static str,
32    },
33
34    /// Integer division or remainder with a zero divisor.
35    ///
36    /// Only integer operands raise this. Floating-point division by zero follows
37    /// IEEE-754 and yields an infinity or NaN rather than an error.
38    DivideByZero,
39
40    /// A checked integer operation overflowed its 32-bit range.
41    ///
42    /// Raised by addition, subtraction, multiplication, negation, and the
43    /// `i32::MIN / -1` division/remainder edge case. Integer arithmetic never
44    /// wraps silently.
45    IntegerOverflow,
46
47    /// A register index addressed a slot outside the chunk's register file.
48    ///
49    /// Indicates malformed bytecode: a correct compiler only emits register
50    /// indices below [`Chunk::registers`](crate::Chunk::registers).
51    BadRegister(u16),
52
53    /// A `LoadConst` referenced a constant-pool slot that does not exist.
54    BadConstant(u16),
55
56    /// Control flow reached an instruction index outside the code array — either
57    /// a branch target past the end, or a `pc` that walked off the end.
58    BadJump(u32),
59
60    /// Execution reached the end of the code without a `Return` or `Halt`.
61    ///
62    /// Every well-formed program terminates explicitly; falling off the end is
63    /// treated as a structural fault rather than an implicit return.
64    NoTerminator,
65}
66
67impl fmt::Display for VmError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            Self::TypeMismatch { op } => {
71                write!(
72                    f,
73                    "type mismatch: `{op}` received an operand of the wrong kind"
74                )
75            }
76            Self::DivideByZero => f.write_str("integer division or remainder by zero"),
77            Self::IntegerOverflow => f.write_str("integer arithmetic overflowed the 32-bit range"),
78            Self::BadRegister(r) => write!(f, "register index {r} is outside the register file"),
79            Self::BadConstant(c) => write!(f, "constant index {c} does not exist"),
80            Self::BadJump(t) => write!(f, "branch target {t} is outside the code"),
81            Self::NoTerminator => {
82                f.write_str("execution reached the end of the code without a return or halt")
83            }
84        }
85    }
86}
87
88impl core::error::Error for VmError {}
89
90#[cfg(test)]
91mod tests {
92    #![allow(clippy::unwrap_used, clippy::expect_used)]
93    use super::*;
94    use alloc::string::ToString;
95
96    #[test]
97    fn test_display_type_mismatch_names_op() {
98        let msg = VmError::TypeMismatch { op: "add" }.to_string();
99        assert!(msg.contains("add"), "message should name the op: {msg}");
100    }
101
102    #[test]
103    fn test_display_all_variants_nonempty() {
104        let variants = [
105            VmError::TypeMismatch { op: "neg" },
106            VmError::DivideByZero,
107            VmError::IntegerOverflow,
108            VmError::BadRegister(7),
109            VmError::BadConstant(3),
110            VmError::BadJump(99),
111            VmError::NoTerminator,
112        ];
113        for v in variants {
114            assert!(!v.to_string().is_empty());
115        }
116    }
117
118    #[test]
119    fn test_error_is_std_error() {
120        fn assert_error<E: core::error::Error>(_: &E) {}
121        assert_error(&VmError::DivideByZero);
122    }
123}