1mod compile;
2mod external;
3
4use thiserror::Error;
5
6use crate::MiraType;
7
8pub use self::compile::{DiagnosticCode, Diagnostics, InvalidBytecodeReason};
9
10pub type Result<T> = std::result::Result<T, Box<MiraError>>;
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
15pub enum ConversionPathSegment {
16 Field(String),
18 Index(usize),
20}
21
22#[derive(Debug, Error)]
24pub enum ConversionReason {
25 #[error("expected Rust {expected}, got MiraScript {actual}")]
27 Type {
28 expected: &'static str,
30 actual: MiraType,
32 },
33 #[error("number {value} cannot be represented as Rust {expected}")]
35 Number {
36 expected: &'static str,
38 value: f64,
40 },
41}
42
43#[derive(Debug, Error)]
45#[non_exhaustive]
46pub enum RuntimeErrorKind {
47 #[error("uninitialized register value")]
49 UninitializedValue,
50 #[error("expected a non-nil value")]
52 ExpectedNonNil,
53 #[error("global variable {name:?} is not defined")]
55 UndefinedGlobal {
56 name: String,
58 },
59 #[error("argument {name:?} is required")]
61 MissingArgument {
62 name: &'static str,
64 },
65 #[error("expected {expected}, got {actual}")]
67 TypeMismatch {
68 expected: &'static str,
70 actual: MiraType,
72 },
73 #[error("value of type {actual} is not callable")]
75 NotCallable {
76 actual: MiraType,
78 },
79 #[error("index or field does not exist")]
81 MissingIndexOrField,
82 #[error("array length {requested} exceeds the configured maximum of {max}")]
84 ArrayLimit {
85 requested: usize,
87 max: usize,
89 },
90 #[error("value handle belongs to another runtime")]
92 ForeignHandle,
93 #[error("invalid {category} arena handle")]
95 InvalidHandle {
96 category: &'static str,
98 },
99 #[error("value behind {category} handle has a different Rust type")]
101 HandleTypeMismatch {
102 category: &'static str,
104 },
105 #[error("{category} arena exhausted its slot space")]
107 ArenaExhausted {
108 category: &'static str,
110 },
111 #[error("the runtime is already executing a script")]
113 ReentrantRun,
114 #[error("invalid {context} control flow")]
116 InvalidControlFlow {
117 context: &'static str,
119 },
120 #[error("invalid upvalue level {level}")]
122 InvalidUpvalueLevel {
123 level: usize,
125 },
126 #[error("execution exceeded the configured timeout")]
128 Timeout,
129 #[error("execution exceeded the configured call-depth limit of {max}")]
131 MaxCallDepth {
132 max: u32,
134 },
135 #[error("a script closure or script module attempted to escape its run")]
137 EscapingClosure,
138 #[error("a script-scoped value was used after its run ended")]
140 ExecutionEnded,
141 #[error("constant {index} is not a {expected} constant")]
143 InvalidConstantKind {
144 index: usize,
146 expected: &'static str,
148 },
149 #[error("invalid matrix size")]
151 InvalidMatrixSize,
152 #[error("matrix must be square")]
154 MatrixMustBeSquare,
155 #[error("incompatible matrix dimensions")]
157 IncompatibleMatrixDimensions,
158 #[error("argument {name:?} must be {constraint}")]
160 InvalidIntegerArgument {
161 name: &'static str,
163 constraint: &'static str,
165 },
166 #[error("expected an even number of update entries, got {actual}")]
168 InvalidUpdateEntryCount {
169 actual: usize,
171 },
172 #[error("argument \"datetime\" cannot be parsed as a datetime")]
174 InvalidDateTime,
175 #[error("argument \"datetime\" of type {actual} is not a valid timestamp")]
177 InvalidTimestamp {
178 actual: MiraType,
180 },
181 #[error("argument \"offset\" must be between -24 and 24")]
183 TimeOffsetOutOfRange,
184 #[error("failed to serialize JSON: {source}")]
186 JsonSerialization {
187 #[source]
189 source: serde_json::Error,
190 },
191 #[error("invalid JSON: {source}")]
193 InvalidJson {
194 #[source]
196 source: serde_json::Error,
197 },
198 #[error("{message}")]
200 UserMessage {
201 message: String,
203 },
204}
205
206#[derive(Debug, Clone, Default)]
208pub struct RuntimeTrace {
209 pub function: Option<String>,
211 pub offset: Option<usize>,
213 pub stack: Vec<String>,
215}
216
217#[derive(Debug, Error)]
219#[non_exhaustive]
220pub enum MiraError {
221 #[error("invalid bytecode at offset {offset}: {reason}")]
223 InvalidBytecode {
224 offset: usize,
226 reason: InvalidBytecodeReason,
228 },
229 #[error("compilation failed with {diagnostics:?}")]
231 Compile {
232 diagnostics: Vec<Diagnostics>,
234 },
235 #[error("runtime failure: {kind}")]
237 Runtime {
238 #[source]
240 kind: RuntimeErrorKind,
241 trace: RuntimeTrace,
243 },
244 #[error("failed to convert value: {reason}")]
246 Conversion {
247 #[source]
249 reason: ConversionReason,
250 path: Vec<ConversionPathSegment>,
252 },
253 #[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 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 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}