use core::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum VmError {
TypeMismatch {
op: &'static str,
},
DivideByZero,
IntegerOverflow,
BadRegister(u16),
BadConstant(u16),
BadJump(u32),
NoTerminator,
}
impl fmt::Display for VmError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TypeMismatch { op } => {
write!(
f,
"type mismatch: `{op}` received an operand of the wrong kind"
)
}
Self::DivideByZero => f.write_str("integer division or remainder by zero"),
Self::IntegerOverflow => f.write_str("integer arithmetic overflowed the 32-bit range"),
Self::BadRegister(r) => write!(f, "register index {r} is outside the register file"),
Self::BadConstant(c) => write!(f, "constant index {c} does not exist"),
Self::BadJump(t) => write!(f, "branch target {t} is outside the code"),
Self::NoTerminator => {
f.write_str("execution reached the end of the code without a return or halt")
}
}
}
}
impl core::error::Error for VmError {}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use alloc::string::ToString;
#[test]
fn test_display_type_mismatch_names_op() {
let msg = VmError::TypeMismatch { op: "add" }.to_string();
assert!(msg.contains("add"), "message should name the op: {msg}");
}
#[test]
fn test_display_all_variants_nonempty() {
let variants = [
VmError::TypeMismatch { op: "neg" },
VmError::DivideByZero,
VmError::IntegerOverflow,
VmError::BadRegister(7),
VmError::BadConstant(3),
VmError::BadJump(99),
VmError::NoTerminator,
];
for v in variants {
assert!(!v.to_string().is_empty());
}
}
#[test]
fn test_error_is_std_error() {
fn assert_error<E: core::error::Error>(_: &E) {}
assert_error(&VmError::DivideByZero);
}
}