Skip to main content

mirascript_vm/error/
mod.rs

1mod compile;
2mod external;
3
4use thiserror::Error;
5
6use crate::MiraType;
7
8pub use self::compile::{DiagnosticCode, Diagnostics, InvalidBytecodeReason};
9
10/// Result type returned by the MiraScript VM.
11pub type Result<T> = std::result::Result<T, Box<MiraError>>;
12
13/// One segment in a failed Rust value conversion path.
14#[derive(Debug, Clone, PartialEq, Eq, Hash)]
15pub enum ConversionPathSegment {
16    /// A record field.
17    Field(String),
18    /// An array index.
19    Index(usize),
20}
21
22/// The reason a MiraScript value could not be converted to a Rust type.
23#[derive(Debug, Error)]
24pub enum ConversionReason {
25    /// The MiraScript value has the wrong category.
26    #[error("expected Rust {expected}, got MiraScript {actual}")]
27    Type {
28        /// Requested Rust type.
29        expected: &'static str,
30        /// Actual MiraScript type.
31        actual: MiraType,
32    },
33    /// A number cannot be represented by the requested Rust type.
34    #[error("number {value} cannot be represented as Rust {expected}")]
35    Number {
36        /// Requested Rust type.
37        expected: &'static str,
38        /// Numeric value that failed validation.
39        value: f64,
40    },
41}
42
43/// A VM or standard-library execution failure.
44#[derive(Debug, Error)]
45#[non_exhaustive]
46pub enum RuntimeErrorKind {
47    /// A register was read before initialization.
48    #[error("uninitialized register value")]
49    UninitializedValue,
50    /// A non-nil value was required.
51    #[error("expected a non-nil value")]
52    ExpectedNonNil,
53    /// A global variable is not defined.
54    #[error("global variable {name:?} is not defined")]
55    UndefinedGlobal {
56        /// Missing name.
57        name: String,
58    },
59    /// An argument is required.
60    #[error("argument {name:?} is required")]
61    MissingArgument {
62        /// Argument name.
63        name: &'static str,
64    },
65    /// A value has the wrong type for an operation.
66    #[error("expected {expected}, got {actual}")]
67    TypeMismatch {
68        /// Human-readable expected type set.
69        expected: &'static str,
70        /// Actual value category.
71        actual: MiraType,
72    },
73    /// A value is not callable.
74    #[error("value of type {actual} is not callable")]
75    NotCallable {
76        /// Actual value category.
77        actual: MiraType,
78    },
79    /// An index or field does not exist.
80    #[error("index or field does not exist")]
81    MissingIndexOrField,
82    /// An array allocation would exceed the configured limit.
83    #[error("array length {requested} exceeds the configured maximum of {max}")]
84    ArrayLimit {
85        /// Requested length.
86        requested: usize,
87        /// Configured maximum.
88        max: usize,
89    },
90    /// An arena handle belongs to another runtime.
91    #[error("value handle belongs to another runtime")]
92    ForeignHandle,
93    /// An arena handle is invalid for its value category.
94    #[error("invalid {category} arena handle")]
95    InvalidHandle {
96        /// Arena category.
97        category: &'static str,
98    },
99    /// The value behind a typed handle has a different concrete Rust type.
100    #[error("value behind {category} handle has a different Rust type")]
101    HandleTypeMismatch {
102        /// Arena category.
103        category: &'static str,
104    },
105    /// One arena category exhausted its 32-bit slot space.
106    #[error("{category} arena exhausted its slot space")]
107    ArenaExhausted {
108        /// Arena category.
109        category: &'static str,
110    },
111    /// Runtime execution was entered recursively.
112    #[error("the runtime is already executing a script")]
113    ReentrantRun,
114    /// Internal bytecode control flow reached an invalid boundary.
115    #[error("invalid {context} control flow")]
116    InvalidControlFlow {
117        /// Boundary being exited.
118        context: &'static str,
119    },
120    /// An upvalue level is invalid for the current frame.
121    #[error("invalid upvalue level {level}")]
122    InvalidUpvalueLevel {
123        /// Requested lexical level.
124        level: usize,
125    },
126    /// Execution exceeded its time limit.
127    #[error("execution exceeded the configured timeout")]
128    Timeout,
129    /// Execution exceeded its call-depth limit.
130    #[error("execution exceeded the configured call-depth limit of {max}")]
131    MaxCallDepth {
132        /// Configured maximum call depth.
133        max: u32,
134    },
135    /// A script closure or script module attempted to escape a run.
136    #[error("a script closure or script module attempted to escape its run")]
137    EscapingClosure,
138    /// A script-scoped callable was used after its run ended.
139    #[error("a script-scoped value was used after its run ended")]
140    ExecutionEnded,
141    /// Bytecode referenced a constant with an incompatible kind.
142    #[error("constant {index} is not a {expected} constant")]
143    InvalidConstantKind {
144        /// Constant-table index.
145        index: usize,
146        /// Required constant kind.
147        expected: &'static str,
148    },
149    /// Matrix dimensions are invalid or exceed the configured limit.
150    #[error("invalid matrix size")]
151    InvalidMatrixSize,
152    /// A matrix operation requires a square matrix.
153    #[error("matrix must be square")]
154    MatrixMustBeSquare,
155    /// Matrix operands have incompatible dimensions.
156    #[error("incompatible matrix dimensions")]
157    IncompatibleMatrixDimensions,
158    /// An integer-valued argument failed its domain constraint.
159    #[error("argument {name:?} must be {constraint}")]
160    InvalidIntegerArgument {
161        /// Argument name.
162        name: &'static str,
163        /// Required integer constraint.
164        constraint: &'static str,
165    },
166    /// The number of update entries is not valid.
167    #[error("expected an even number of update entries, got {actual}")]
168    InvalidUpdateEntryCount {
169        /// Actual number of entries.
170        actual: usize,
171    },
172    /// A datetime string could not be parsed.
173    #[error("argument \"datetime\" cannot be parsed as a datetime")]
174    InvalidDateTime,
175    /// A value cannot be interpreted as a timestamp.
176    #[error("argument \"datetime\" of type {actual} is not a valid timestamp")]
177    InvalidTimestamp {
178        /// Actual value category.
179        actual: MiraType,
180    },
181    /// A timezone offset is outside the supported range.
182    #[error("argument \"offset\" must be between -24 and 24")]
183    TimeOffsetOutOfRange,
184    /// JSON serialization failed.
185    #[error("failed to serialize JSON: {source}")]
186    JsonSerialization {
187        /// Serializer error.
188        #[source]
189        source: serde_json::Error,
190    },
191    /// JSON input is invalid.
192    #[error("invalid JSON: {source}")]
193    InvalidJson {
194        /// Parser error.
195        #[source]
196        source: serde_json::Error,
197    },
198    /// A script assertion or panic supplied a message.
199    #[error("{message}")]
200    UserMessage {
201        /// Script-provided message.
202        message: String,
203    },
204}
205
206/// Runtime source location and call stack attached to an execution error.
207#[derive(Debug, Clone, Default)]
208pub struct RuntimeTrace {
209    /// Function active at the failure site, when known.
210    pub function: Option<String>,
211    /// Bytecode offset of the failure site, when known.
212    pub offset: Option<usize>,
213    /// Active callers ordered from root to leaf.
214    pub stack: Vec<String>,
215}
216
217/// An error produced while compiling, decoding, executing, or bridging values.
218#[derive(Debug, Error)]
219#[non_exhaustive]
220pub enum MiraError {
221    /// The compiled bytecode chunk failed structural validation.
222    #[error("invalid bytecode at offset {offset}: {reason}")]
223    InvalidBytecode {
224        /// Byte offset at which validation failed.
225        offset: usize,
226        /// Structural validation failure.
227        reason: InvalidBytecodeReason,
228    },
229    /// Source compilation failed.
230    #[error("compilation failed with {diagnostics:?}")]
231    Compile {
232        /// Compiler diagnostics encoded by `mirascript-core`.
233        diagnostics: Vec<Diagnostics>,
234    },
235    /// Script execution failed.
236    #[error("runtime failure: {kind}")]
237    Runtime {
238        /// Structured runtime failure.
239        #[source]
240        kind: RuntimeErrorKind,
241        /// Execution location and stack.
242        trace: RuntimeTrace,
243    },
244    /// A MiraScript value could not be converted to a Rust type.
245    #[error("failed to convert value: {reason}")]
246    Conversion {
247        /// Structured conversion failure.
248        #[source]
249        reason: ConversionReason,
250        /// Nested field and index path.
251        path: Vec<ConversionPathSegment>,
252    },
253    /// A host callback returned an arbitrary error.
254    #[error(transparent)]
255    External(#[from] anyhow::Error),
256}
257
258impl MiraError {
259    #[doc(hidden)]
260    pub fn runtime(kind: RuntimeErrorKind) -> Box<Self> {
261        Box::new(Self::Runtime {
262            kind,
263            trace: RuntimeTrace::default(),
264        })
265    }
266
267    pub(crate) fn conversion_type(expected: &'static str, actual: MiraType) -> Box<Self> {
268        Box::new(Self::Conversion {
269            reason: ConversionReason::Type { expected, actual },
270            path: Vec::new(),
271        })
272    }
273
274    pub(crate) fn conversion_number(expected: &'static str, value: f64) -> Box<Self> {
275        Box::new(Self::Conversion {
276            reason: ConversionReason::Number { expected, value },
277            path: Vec::new(),
278        })
279    }
280
281    /// Attach a record field to a conversion path.
282    pub fn at_field(mut self: Box<Self>, field: impl Into<String>) -> Box<Self> {
283        if let Self::Conversion { path, .. } = self.as_mut() {
284            path.insert(0, ConversionPathSegment::Field(field.into()));
285        }
286        self
287    }
288
289    /// Attach an array index to a conversion path.
290    pub fn at_index(mut self: Box<Self>, index: usize) -> Box<Self> {
291        if let Self::Conversion { path, .. } = self.as_mut() {
292            path.insert(0, ConversionPathSegment::Index(index));
293        }
294        self
295    }
296
297    pub(crate) fn with_runtime_context(
298        mut self,
299        function: Option<String>,
300        offset: usize,
301        stack: Vec<String>,
302    ) -> Self {
303        if let Self::Runtime { trace, .. } = &mut self
304            && trace.offset.is_none()
305        {
306            trace.function = function;
307            trace.offset = Some(offset);
308            trace.stack = stack;
309        }
310        self
311    }
312}