Skip to main content

yomi_core/vm/
error.rs

1//! Runtime errors of the VM.
2
3use super::*;
4
5/// The kind of runtime error.
6#[non_exhaustive]
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum VmErrorKind {
9    /// Exceeded the limit on the number of instructions.
10    StepLimitExceeded,
11    /// An interrupt was requested through the token ([`crate::vm::InterruptHandle`]).
12    Interrupted,
13    /// The depth of calls (nesting of `call`) exceeded the limit.
14    CallDepthExceeded,
15    /// A value (a string, `list`, `struct`, and so on) exceeded the size limit.
16    ValueTooLarge,
17    /// The total size of values held in variables exceeded the limit (`VmConfig::max_total_bytes`).
18    MemoryLimitExceeded,
19    /// An index into a `list` is out of range.
20    IndexOutOfRange {
21        /// The index given.
22        index: i64,
23        /// The length of the `list`.
24        len: i64,
25    },
26    /// Read a key missing from a `map` by index (`m[k]`), or tried to update it (`m[k] += 1`, `m[k].x = 1`).
27    /// `m[k] = v` adds the key if missing, so it does not cause this.
28    KeyNotFound {
29        /// The key given (as the string written for `${}` interpolation).
30        key: String,
31    },
32    /// Integer overflow.
33    IntegerOverflow,
34    /// Divided by 0 (for both `int` and `float`).
35    DivisionByZero,
36    /// The result of a `float` operation became `NaN` or `±∞` (which never appear as values).
37    NonFiniteFloat,
38    /// The result of `to_int` does not fit in the range of `int`.
39    FloatOutOfRange,
40    /// Called `resume` or `save` while not stopped.
41    NotStopped,
42    /// Called `run` while stopped.
43    AlreadyStopped,
44    /// Called `run` after the end.
45    Ended,
46    /// None of the options of a `choice` are in the list (`if` was false, or already chosen with `once`).
47    NoChoiceAvailable,
48    /// The number of the choice passed to `resume` is out of the range of the given list.
49    ChoiceOutOfRange {
50        /// The number given.
51        index: i64,
52        /// The length of the list.
53        count: i64,
54    },
55    /// Tried to continue after a runtime error.
56    Poisoned,
57    /// The persistent data in `VmConfig::persistent` could not be read (`Vm::new`).
58    PersistentData(LoadErrorKind),
59    /// `min > max` in `random(min, max)`.
60    InvalidRandomRange {
61        /// The value given as the minimum.
62        min: i64,
63        /// The value given as the maximum.
64        max: i64,
65    },
66    /// A snapshot made with another program was passed to `restore`.
67    SnapshotMismatch,
68    /// The type of the input to `resume` does not match.
69    BadInput {
70        /// The expected type.
71        expected: Ty,
72        /// The type given.
73        found: Ty,
74    },
75    /// There is no start label.
76    StartLabelNotFound(String),
77    /// A command or variable used by the program is not in the registry.
78    CommandMissing(String),
79    /// A command function returned `Err`. Has a code decided by the package (`package.error_name`) and named arguments.
80    /// No message text (displaying it is the host's job).
81    CommandFailed {
82        /// The error code of the package (those returned by the core are `core.…`).
83        code: String,
84        /// Named arguments determined by each code.
85        args: Vec<(&'static str, DiagArg)>,
86    },
87    /// The variable named in `get_var` / `set_var` is not registered.
88    UnknownVariable(String),
89    /// A package's state slice could not be serialized (a bug in the implementation of `Package::State`).
90    SliceSerialize(String),
91    /// Tried to create a VM with a registry made from a declaration file (it has no functions to run commands).
92    DeclOnlyRegistry,
93}
94
95impl VmErrorKind {
96    /// The stable English name.
97    pub fn code(&self) -> &'static str {
98        match self {
99            VmErrorKind::StepLimitExceeded => "step_limit_exceeded",
100            VmErrorKind::Interrupted => "interrupted",
101            VmErrorKind::CallDepthExceeded => "call_depth_exceeded",
102            VmErrorKind::ValueTooLarge => "value_too_large",
103            VmErrorKind::MemoryLimitExceeded => "memory_limit_exceeded",
104            VmErrorKind::IndexOutOfRange { .. } => "index_out_of_range",
105            VmErrorKind::KeyNotFound { .. } => "key_not_found",
106            VmErrorKind::IntegerOverflow => "integer_overflow",
107            VmErrorKind::DivisionByZero => "division_by_zero",
108            VmErrorKind::NonFiniteFloat => "non_finite_float",
109            VmErrorKind::FloatOutOfRange => "float_out_of_range",
110            VmErrorKind::NotStopped => "not_stopped",
111            VmErrorKind::AlreadyStopped => "already_stopped",
112            VmErrorKind::Ended => "ended",
113            VmErrorKind::NoChoiceAvailable => "no_choice_available",
114            VmErrorKind::ChoiceOutOfRange { .. } => "choice_out_of_range",
115            VmErrorKind::Poisoned => "poisoned",
116            VmErrorKind::PersistentData(_) => "persistent_data",
117            VmErrorKind::InvalidRandomRange { .. } => "invalid_random_range",
118            VmErrorKind::SnapshotMismatch => "snapshot_mismatch",
119            VmErrorKind::BadInput { .. } => "bad_input",
120            VmErrorKind::StartLabelNotFound(_) => "start_label_not_found",
121            VmErrorKind::CommandMissing(_) => "command_missing",
122            VmErrorKind::CommandFailed { .. } => "command_failed",
123            VmErrorKind::UnknownVariable(_) => "unknown_variable",
124            VmErrorKind::SliceSerialize(_) => "slice_serialize",
125            VmErrorKind::DeclOnlyRegistry => "decl_only_registry",
126        }
127    }
128
129    /// For a command failure ([`VmErrorKind::CommandFailed`]), the package's error code and named arguments.
130    pub fn command_error(&self) -> Option<(&str, &[(&'static str, DiagArg)])> {
131        match self {
132            VmErrorKind::CommandFailed { code, args } => Some((code, args)),
133            _ => None,
134        }
135    }
136}
137
138/// A runtime error.
139#[non_exhaustive]
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct VmError {
142    /// Kind.
143    pub kind: VmErrorKind,
144    /// The name of the module (when known).
145    pub module: Option<String>,
146    /// The label (when known).
147    pub label: Option<String>,
148    /// The line (when known).
149    pub line: Option<u32>,
150}
151
152impl std::fmt::Display for VmError {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        write!(f, "{}", self.kind.code())?;
155        if let Some(l) = &self.label {
156            write!(f, " (label ")?;
157            if let Some(m) = &self.module {
158                write!(f, "{m}.")?;
159            }
160            write!(f, "{l}")?;
161            if let Some(n) = self.line {
162                write!(f, ", line {n}")?;
163            }
164            write!(f, ")")?;
165        }
166        Ok(())
167    }
168}
169
170impl std::error::Error for VmError {}