Skip to main content

rustia/
runtime_error.rs

1//! Runtime errors independent of interpreter implementation types.
2
3use crate::{Diagnostic, Profile, SourceLocation, SourceSpan};
4use std::{fmt, sync::Arc};
5
6/// A script execution, resource-limit, or live-handle failure.
7///
8/// Use [`kind`](Self::kind) for application decisions and
9/// [`message`](Self::message) for the original message without a location prefix.
10#[derive(Clone)]
11pub struct VmError {
12    pub(crate) kind: VmErrorKind,
13    pub(crate) location: Option<RuntimeLocation>,
14    pub(crate) location_suppressed: bool,
15    pub(crate) diagnostic: Option<Arc<Diagnostic>>,
16    pub(crate) span: Option<(u32, u32)>,
17    core: rustia_vm::Error,
18}
19
20#[derive(Clone, Debug)]
21pub(crate) struct RuntimeLocation {
22    pub(crate) source: Arc<str>,
23    pub(crate) line: u32,
24}
25
26/// The category of a runtime failure.
27///
28/// Include a fallback arm: future versions may add categories. Script-thrown
29/// objects are represented by their message here; their VM storage is private.
30/// Match a kind instead of parsing the displayed message.
31///
32/// ```
33/// use rustia::{Rustia, VmErrorKind};
34///
35/// let mut vm = Rustia::builder().fuel(1_000).build()?;
36/// let error = vm.exec("while true do end").expect_err("the budget is finite");
37/// assert!(matches!(
38///     error.as_vm_error().map(|error| error.kind()),
39///     Some(VmErrorKind::FuelExhausted { .. })
40/// ));
41/// // Start a fresh decision, discarding the failed script's guest state.
42/// vm.reset_decision()?;
43/// assert_eq!(vm.eval::<i32>("return 42")?, 42);
44/// # Ok::<(), rustia::Error>(())
45/// ```
46#[derive(Clone, Debug)]
47#[non_exhaustive]
48pub enum VmErrorKind {
49    /// The instruction fuel budget was exhausted. Script `pcall` cannot catch it.
50    FuelExhausted {
51        /// The exhausted budget, in instruction-fuel units rather than time.
52        limit: u64,
53    },
54    /// Nested script calls reached the configured depth. Script `pcall` cannot catch it.
55    RecursionLimit {
56        /// The configured maximum script call depth.
57        limit: usize,
58    },
59    /// Bytecode referred to a register outside its register file.
60    RegisterOutOfBounds {
61        /// The zero-based register index that was requested.
62        register: usize,
63        /// The number of available registers; valid indices are less than this value.
64        max: usize,
65    },
66    /// Bytecode referred to a constant outside its constant pool.
67    ConstantOutOfBounds {
68        /// The zero-based constant index that was requested.
69        index: usize,
70        /// The number of available constants.
71        len: usize,
72    },
73    /// An operation received a value of an incompatible type.
74    TypeError {
75        /// A description of the value type the operation expected.
76        expected: &'static str,
77    },
78    /// A guest allocation failed or exceeded the VM's logical memory quota.
79    /// This does not identify an operating-system memory limit.
80    OutOfMemory,
81    /// A typed callback was called without an invocation for its host schema.
82    HostDispatcherUnavailable,
83    /// A bounded host-invocation resource was exhausted.
84    HostResourceExhausted {
85        /// The resource name, such as a record-count or record-byte budget.
86        resource: &'static str,
87        /// The configured ceiling, in the units identified by `resource`.
88        limit: u64,
89    },
90    /// A host callback's unwinding panic was contained and the VM was poisoned.
91    /// Reset the decision before executing more guest code.
92    HostPanicked {
93        /// The callback name reported at the host boundary.
94        function: String,
95    },
96    /// Execution was rejected after an earlier host panic.
97    /// [`crate::Rustia::reset_decision`] clears the poisoned state.
98    VmPoisoned,
99    /// A coroutine attempted to yield across a boundary that cannot suspend.
100    YieldAcrossBoundary,
101    /// Decision reset was requested while the interpreter was executing.
102    DecisionResetWhileRunning,
103    /// A persistent host configuration change was requested during execution or a guest savepoint.
104    HostConfigurationWhileRunning,
105    /// Decision reset could not advance the finite epoch counter.
106    DecisionEpochExhausted,
107    /// A retained guest handle was used after its decision epoch ended.
108    StaleRetainedValue {
109        /// The epoch in which the handle was created.
110        retained_epoch: u64,
111        /// The interpreter's current epoch.
112        current_epoch: u64,
113    },
114    /// A retained guest handle was used with a different interpreter.
115    RetainedValueFromDifferentVm,
116    /// A table write used `nil` as its key.
117    TableIndexNil,
118    /// A table write used NaN as its key.
119    TableIndexNaN,
120    /// `next` received a key that is not valid for the supplied table.
121    InvalidKeyToNext,
122    /// A script assertion failed.
123    AssertionFailed {
124        /// The assertion's message.
125        message: String,
126    },
127    /// An ordinary script operation failed with a textual message.
128    RuntimeError {
129        /// The message without an added source-location prefix.
130        message: String,
131    },
132    /// A script raised an error value, represented here by its original text.
133    /// The original guest object's identity does not cross the facade boundary.
134    GuestError {
135        /// The textual representation of the script's error value.
136        message: String,
137    },
138    /// Execution requested a feature that the engine does not implement.
139    Unsupported {
140        /// The unsupported feature's name.
141        feature: &'static str,
142    },
143    /// The selected profile does not permit a requested capability.
144    CapabilityRemoved {
145        /// The unavailable capability or service.
146        feature: &'static str,
147        /// The specific operation, when the failure identifies one.
148        operation: Option<String>,
149        /// The profile that rejected the request.
150        profile: Profile,
151    },
152    /// The hardened-leaf environment does not permit a requested operation or setting.
153    HardenedLeafViolation {
154        /// The rejected operation or setting.
155        feature: &'static str,
156    },
157    /// An operation tried to change the sealed hardened-leaf guest environment.
158    GuestEnvironmentSealed,
159    /// A bytecode or program-state invariant was invalid.
160    InvalidProgram {
161        /// A description of the violated bytecode invariant.
162        reason: &'static str,
163    },
164}
165
166impl VmError {
167    /// Creates a typed runtime error, for example from a Rust callback.
168    ///
169    /// A script-thrown object has no transferable identity in Rust. Returning a
170    /// captured [`GuestError`](VmErrorKind::GuestError) from a callback raises
171    /// its original message as a string, including after reset or in another VM.
172    pub fn new(kind: VmErrorKind) -> Self {
173        let mut error = Self::from_core(rustia_vm::Error::new(kind.to_core()));
174        error.kind = kind;
175        error
176    }
177
178    /// Returns the failure category without parsing its message.
179    pub fn kind(&self) -> &VmErrorKind {
180        &self.kind
181    }
182
183    /// Returns the original message without a source-location prefix.
184    pub fn message(&self) -> VmErrorMessage<'_> {
185        VmErrorMessage(self)
186    }
187
188    /// Returns the source label and one-based line, when available.
189    pub fn source_location(&self) -> Option<SourceLocation<'_>> {
190        if self.location_suppressed {
191            return None;
192        }
193        self.location.as_ref().map(|location| SourceLocation {
194            source: &location.source,
195            line: location.line,
196        })
197    }
198
199    /// Returns the source byte range, when available.
200    pub fn source_span(&self) -> Option<SourceSpan> {
201        self.span.map(|(start, end)| SourceSpan {
202            start: start as usize,
203            end: end as usize,
204        })
205    }
206
207    /// Omits a source prefix from this failure's short message.
208    ///
209    /// Host-side reports may still identify the script that called a callback.
210    pub fn without_source_location(self) -> Self {
211        let mut error = Self::from_core(self.core.without_source_location());
212        error.kind = self.kind;
213        error
214    }
215
216    pub(crate) fn from_core(core: rustia_vm::Error) -> Self {
217        Self {
218            kind: VmErrorKind::from_core(&core.kind),
219            location: core.location.as_ref().map(|location| RuntimeLocation {
220                source: location.source.clone(),
221                line: location.line,
222            }),
223            location_suppressed: core.location_suppressed,
224            diagnostic: core
225                .diagnostic
226                .as_ref()
227                .map(|diagnostic| Arc::new(Diagnostic::from_core(diagnostic))),
228            span: core.span,
229            core,
230        }
231    }
232
233    pub(crate) fn into_core(mut self) -> rustia_vm::Error {
234        if let rustia_vm::ErrorKind::GuestError { message, .. } = &self.core.kind {
235            // Facade errors can outlive their VM or epoch. A raw guest object
236            // cannot safely cross back into a VM without ownership and a root.
237            self.core.kind = rustia_vm::ErrorKind::RuntimeError {
238                message: message.clone(),
239            };
240        }
241        self.core
242    }
243
244    pub(crate) fn is_transaction_abort(&self) -> bool {
245        self.core.is_transaction_abort()
246    }
247}
248
249/// A runtime error's original message, without a source-location prefix.
250pub struct VmErrorMessage<'a>(&'a VmError);
251
252impl fmt::Display for VmErrorMessage<'_> {
253    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254        self.0.core.message().fmt(formatter)
255    }
256}
257
258impl fmt::Debug for VmError {
259    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
260        formatter
261            .debug_struct("VmError")
262            .field("kind", &self.kind)
263            .field("location", &self.source_location())
264            .field("span", &self.source_span())
265            .field("diagnostic", &self.diagnostic)
266            .finish()
267    }
268}
269
270impl fmt::Display for VmError {
271    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
272        self.core.fmt(formatter)
273    }
274}
275
276impl std::error::Error for VmError {
277    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
278        self.diagnostic
279            .as_ref()
280            .and_then(|diagnostic| diagnostic.host_cause.as_deref())
281            .map(|cause| cause as &(dyn std::error::Error + 'static))
282    }
283}
284
285impl VmErrorKind {
286    fn from_core(kind: &rustia_vm::ErrorKind) -> Self {
287        use rustia_vm::ErrorKind as Core;
288        match kind {
289            Core::FuelExhausted { limit } => Self::FuelExhausted { limit: *limit },
290            Core::RecursionLimit { limit } => Self::RecursionLimit { limit: *limit },
291            Core::RegisterOutOfBounds { register, max } => Self::RegisterOutOfBounds {
292                register: *register,
293                max: *max,
294            },
295            Core::ConstantOutOfBounds { index, len } => Self::ConstantOutOfBounds {
296                index: *index,
297                len: *len,
298            },
299            Core::TypeError { expected } => Self::TypeError { expected },
300            Core::OutOfMemory => Self::OutOfMemory,
301            Core::HostDispatcherUnavailable => Self::HostDispatcherUnavailable,
302            Core::HostResourceExhausted { resource, limit } => Self::HostResourceExhausted {
303                resource,
304                limit: *limit,
305            },
306            Core::HostPanicked { function } => Self::HostPanicked {
307                function: function.clone(),
308            },
309            Core::VmPoisoned => Self::VmPoisoned,
310            Core::YieldAcrossBoundary => Self::YieldAcrossBoundary,
311            Core::DecisionResetWhileRunning => Self::DecisionResetWhileRunning,
312            Core::HostConfigurationWhileRunning => Self::HostConfigurationWhileRunning,
313            Core::DecisionEpochExhausted => Self::DecisionEpochExhausted,
314            Core::StaleRetainedValue {
315                retained_epoch,
316                current_epoch,
317            } => Self::StaleRetainedValue {
318                retained_epoch: *retained_epoch,
319                current_epoch: *current_epoch,
320            },
321            Core::RetainedValueFromDifferentVm => Self::RetainedValueFromDifferentVm,
322            Core::TableIndexNil => Self::TableIndexNil,
323            Core::TableIndexNaN => Self::TableIndexNaN,
324            Core::InvalidKeyToNext => Self::InvalidKeyToNext,
325            Core::AssertionFailed { message } => Self::AssertionFailed {
326                message: message.clone(),
327            },
328            Core::RuntimeError { message } => Self::RuntimeError {
329                message: message.clone(),
330            },
331            Core::GuestError { message, .. } => Self::GuestError {
332                message: message.clone(),
333            },
334            Core::Unsupported { feature } => Self::Unsupported { feature },
335            Core::CapabilityRemoved {
336                feature,
337                operation,
338                profile,
339            } => Self::CapabilityRemoved {
340                feature,
341                operation: operation.clone(),
342                profile: Profile::from_core(*profile),
343            },
344            Core::HardenedLeafViolation { feature } => Self::HardenedLeafViolation { feature },
345            Core::GuestEnvironmentSealed => Self::GuestEnvironmentSealed,
346            Core::InvalidProgram { reason } => Self::InvalidProgram { reason },
347        }
348    }
349
350    fn to_core(&self) -> rustia_vm::ErrorKind {
351        use rustia_vm::ErrorKind as Core;
352        match self {
353            Self::FuelExhausted { limit } => Core::FuelExhausted { limit: *limit },
354            Self::RecursionLimit { limit } => Core::RecursionLimit { limit: *limit },
355            Self::RegisterOutOfBounds { register, max } => Core::RegisterOutOfBounds {
356                register: *register,
357                max: *max,
358            },
359            Self::ConstantOutOfBounds { index, len } => Core::ConstantOutOfBounds {
360                index: *index,
361                len: *len,
362            },
363            Self::TypeError { expected } => Core::TypeError { expected },
364            Self::OutOfMemory => Core::OutOfMemory,
365            Self::HostDispatcherUnavailable => Core::HostDispatcherUnavailable,
366            Self::HostResourceExhausted { resource, limit } => Core::HostResourceExhausted {
367                resource,
368                limit: *limit,
369            },
370            Self::HostPanicked { function } => Core::HostPanicked {
371                function: function.clone(),
372            },
373            Self::VmPoisoned => Core::VmPoisoned,
374            Self::YieldAcrossBoundary => Core::YieldAcrossBoundary,
375            Self::DecisionResetWhileRunning => Core::DecisionResetWhileRunning,
376            Self::HostConfigurationWhileRunning => Core::HostConfigurationWhileRunning,
377            Self::DecisionEpochExhausted => Core::DecisionEpochExhausted,
378            Self::StaleRetainedValue {
379                retained_epoch,
380                current_epoch,
381            } => Core::StaleRetainedValue {
382                retained_epoch: *retained_epoch,
383                current_epoch: *current_epoch,
384            },
385            Self::RetainedValueFromDifferentVm => Core::RetainedValueFromDifferentVm,
386            Self::TableIndexNil => Core::TableIndexNil,
387            Self::TableIndexNaN => Core::TableIndexNaN,
388            Self::InvalidKeyToNext => Core::InvalidKeyToNext,
389            Self::AssertionFailed { message } => Core::AssertionFailed {
390                message: message.clone(),
391            },
392            Self::RuntimeError { message } => Core::RuntimeError {
393                message: message.clone(),
394            },
395            // A host-created error has no guest object to rethrow. Errors that
396            // came from execution retain that object in VmError's private core.
397            Self::GuestError { message } => Core::RuntimeError {
398                message: message.clone(),
399            },
400            Self::Unsupported { feature } => Core::Unsupported { feature },
401            Self::CapabilityRemoved {
402                feature,
403                operation,
404                profile,
405            } => Core::CapabilityRemoved {
406                feature,
407                operation: operation.clone(),
408                profile: profile.to_core(),
409            },
410            Self::HardenedLeafViolation { feature } => Core::HardenedLeafViolation { feature },
411            Self::GuestEnvironmentSealed => Core::GuestEnvironmentSealed,
412            Self::InvalidProgram { reason } => Core::InvalidProgram { reason },
413        }
414    }
415}