Skip to main content

mirascript_vm/
error.rs

1use std::fmt;
2
3/// Result type returned by the MiraScript VM.
4pub type Result<T> = std::result::Result<T, MiraError>;
5
6/// An error produced while compiling, decoding, executing, or bridging values.
7#[derive(Debug, Clone, PartialEq)]
8#[non_exhaustive]
9pub enum MiraError {
10    /// Source compilation failed.
11    Compile {
12        /// Compiler diagnostics encoded by `mirascript-core`.
13        diagnostics: Vec<u32>,
14    },
15    /// The compiled bytecode chunk failed structural validation.
16    InvalidBytecode {
17        /// Byte offset at which validation failed.
18        offset: usize,
19        /// Human-readable validation failure.
20        reason: String,
21    },
22    /// Script execution failed.
23    Runtime {
24        /// Human-readable runtime failure.
25        message: String,
26        /// Function active at the failure site, when known.
27        function: Option<String>,
28        /// Bytecode offset of the failure site, when known.
29        offset: Option<usize>,
30        /// Names of active callers, ordered from root to leaf.
31        stack: Vec<String>,
32    },
33    /// A MiraScript value could not be converted to the requested Rust type.
34    Conversion {
35        /// Requested Rust-side value description.
36        expected: String,
37        /// MiraScript value type that was encountered.
38        actual: String,
39        /// Nested field or index path, when conversion added one.
40        path: Option<String>,
41    },
42    /// A host extern reported an error.
43    Extern {
44        /// Error message supplied by the extern.
45        message: String,
46    },
47    /// A live Rust value was already borrowed incompatibly.
48    BorrowConflict {
49        /// Operation that required the conflicting borrow.
50        operation: &'static str,
51        /// Type tag of the bridged Rust value.
52        tag: String,
53    },
54    /// Execution exceeded [`crate::RunOptions::timeout`].
55    Timeout,
56    /// Execution exceeded the configured call-depth limit.
57    MaxCallDepth {
58        /// Configured maximum call depth.
59        max: u32,
60    },
61    /// A script closure or script module attempted to outlive its execution.
62    EscapingClosure,
63    /// A previously captured script value was used after execution ended.
64    ExecutionEnded,
65}
66
67impl MiraError {
68    pub(crate) fn runtime(message: impl Into<String>) -> Self {
69        Self::Runtime {
70            message: message.into(),
71            function: None,
72            offset: None,
73            stack: Vec::new(),
74        }
75    }
76
77    pub(crate) fn conversion(expected: impl Into<String>, value: &crate::MiraAny) -> Self {
78        Self::Conversion {
79            expected: expected.into(),
80            actual: value.type_name().into(),
81            path: None,
82        }
83    }
84
85    /// Attach a nested field or index path to a [`MiraError::Conversion`].
86    ///
87    /// Other error variants are returned unchanged.
88    pub fn at_path(mut self, path: impl Into<String>) -> Self {
89        if let Self::Conversion { path: slot, .. } = &mut self {
90            *slot = Some(path.into());
91        }
92        self
93    }
94
95    pub(crate) fn with_runtime_context(
96        mut self,
97        function: Option<String>,
98        offset: usize,
99        stack: Vec<String>,
100    ) -> Self {
101        if let Self::Runtime {
102            function: error_function,
103            offset: error_offset,
104            stack: error_stack,
105            ..
106        } = &mut self
107            && error_function.is_none()
108        {
109            *error_function = function;
110            *error_offset = Some(offset);
111            *error_stack = stack;
112        }
113        self
114    }
115}
116
117impl fmt::Display for MiraError {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        match self {
120            Self::Compile { diagnostics } => {
121                write!(
122                    f,
123                    "failed to compile MiraScript ({} diagnostic words)",
124                    diagnostics.len()
125                )
126            }
127            Self::InvalidBytecode { offset, reason } => {
128                write!(f, "invalid bytecode at offset {offset}: {reason}")
129            }
130            Self::Runtime {
131                message,
132                function,
133                offset,
134                ..
135            } => {
136                write!(f, "{message}")?;
137                if let Some(function) = function {
138                    write!(f, " in {function}")?;
139                }
140                if let Some(offset) = offset {
141                    write!(f, " at bytecode offset {offset}")?;
142                }
143                Ok(())
144            }
145            Self::Conversion {
146                expected,
147                actual,
148                path,
149            } => {
150                write!(f, "failed to convert {actual} to {expected}")?;
151                if let Some(path) = path {
152                    write!(f, " at {path}")?;
153                }
154                Ok(())
155            }
156            Self::Extern { message } => write!(f, "extern error: {message}"),
157            Self::BorrowConflict { operation, tag } => {
158                write!(f, "borrow conflict while attempting to {operation} {tag}")
159            }
160            Self::Timeout => write!(f, "MiraScript execution timed out"),
161            Self::MaxCallDepth { max } => write!(f, "maximum call depth of {max} exceeded"),
162            Self::EscapingClosure => {
163                write!(f, "a MiraScript closure or module cannot escape run()")
164            }
165            Self::ExecutionEnded => write!(f, "MiraScript execution has ended"),
166        }
167    }
168}
169
170impl std::error::Error for MiraError {}