mod compile;
mod external;
use thiserror::Error;
use crate::MiraType;
pub use self::compile::{DiagnosticCode, Diagnostics, InvalidBytecodeReason};
pub type Result<T> = std::result::Result<T, Box<MiraError>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ConversionPathSegment {
Field(String),
Index(usize),
}
#[derive(Debug, Error)]
pub enum ConversionReason {
#[error("expected Rust {expected}, got MiraScript {actual}")]
Type {
expected: &'static str,
actual: MiraType,
},
#[error("number {value} cannot be represented as Rust {expected}")]
Number {
expected: &'static str,
value: f64,
},
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RuntimeErrorKind {
#[error("uninitialized register value")]
UninitializedValue,
#[error("expected a non-nil value")]
ExpectedNonNil,
#[error("global variable {name:?} is not defined")]
UndefinedGlobal {
name: String,
},
#[error("argument {name:?} is required")]
MissingArgument {
name: &'static str,
},
#[error("expected {expected}, got {actual}")]
TypeMismatch {
expected: &'static str,
actual: MiraType,
},
#[error("value of type {actual} is not callable")]
NotCallable {
actual: MiraType,
},
#[error("index or field does not exist")]
MissingIndexOrField,
#[error("array length {requested} exceeds the configured maximum of {max}")]
ArrayLimit {
requested: usize,
max: usize,
},
#[error("value handle belongs to another runtime")]
ForeignHandle,
#[error("invalid {category} arena handle")]
InvalidHandle {
category: &'static str,
},
#[error("value behind {category} handle has a different Rust type")]
HandleTypeMismatch {
category: &'static str,
},
#[error("{category} arena exhausted its slot space")]
ArenaExhausted {
category: &'static str,
},
#[error("the runtime is already executing a script")]
ReentrantRun,
#[error("invalid {context} control flow")]
InvalidControlFlow {
context: &'static str,
},
#[error("invalid upvalue level {level}")]
InvalidUpvalueLevel {
level: usize,
},
#[error("execution exceeded the configured timeout")]
Timeout,
#[error("execution exceeded the configured call-depth limit of {max}")]
MaxCallDepth {
max: u32,
},
#[error("a script closure or script module attempted to escape its run")]
EscapingClosure,
#[error("a script-scoped value was used after its run ended")]
ExecutionEnded,
#[error("constant {index} is not a {expected} constant")]
InvalidConstantKind {
index: usize,
expected: &'static str,
},
#[error("invalid matrix size")]
InvalidMatrixSize,
#[error("matrix must be square")]
MatrixMustBeSquare,
#[error("incompatible matrix dimensions")]
IncompatibleMatrixDimensions,
#[error("argument {name:?} must be {constraint}")]
InvalidIntegerArgument {
name: &'static str,
constraint: &'static str,
},
#[error("expected an even number of update entries, got {actual}")]
InvalidUpdateEntryCount {
actual: usize,
},
#[error("argument \"datetime\" cannot be parsed as a datetime")]
InvalidDateTime,
#[error("argument \"datetime\" of type {actual} is not a valid timestamp")]
InvalidTimestamp {
actual: MiraType,
},
#[error("argument \"offset\" must be between -24 and 24")]
TimeOffsetOutOfRange,
#[error("failed to serialize JSON: {source}")]
JsonSerialization {
#[source]
source: serde_json::Error,
},
#[error("invalid JSON: {source}")]
InvalidJson {
#[source]
source: serde_json::Error,
},
#[error("{message}")]
UserMessage {
message: String,
},
}
#[derive(Debug, Clone, Default)]
pub struct RuntimeTrace {
pub function: Option<String>,
pub offset: Option<usize>,
pub stack: Vec<String>,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum MiraError {
#[error("invalid bytecode at offset {offset}: {reason}")]
InvalidBytecode {
offset: usize,
reason: InvalidBytecodeReason,
},
#[error("compilation failed with {diagnostics:?}")]
Compile {
diagnostics: Vec<Diagnostics>,
},
#[error("runtime failure: {kind}")]
Runtime {
#[source]
kind: RuntimeErrorKind,
trace: RuntimeTrace,
},
#[error("failed to convert value: {reason}")]
Conversion {
#[source]
reason: ConversionReason,
path: Vec<ConversionPathSegment>,
},
#[error(transparent)]
External(#[from] anyhow::Error),
}
impl MiraError {
#[doc(hidden)]
pub fn runtime(kind: RuntimeErrorKind) -> Box<Self> {
Box::new(Self::Runtime {
kind,
trace: RuntimeTrace::default(),
})
}
pub(crate) fn conversion_type(expected: &'static str, actual: MiraType) -> Box<Self> {
Box::new(Self::Conversion {
reason: ConversionReason::Type { expected, actual },
path: Vec::new(),
})
}
pub(crate) fn conversion_number(expected: &'static str, value: f64) -> Box<Self> {
Box::new(Self::Conversion {
reason: ConversionReason::Number { expected, value },
path: Vec::new(),
})
}
pub fn at_field(mut self: Box<Self>, field: impl Into<String>) -> Box<Self> {
if let Self::Conversion { path, .. } = self.as_mut() {
path.insert(0, ConversionPathSegment::Field(field.into()));
}
self
}
pub fn at_index(mut self: Box<Self>, index: usize) -> Box<Self> {
if let Self::Conversion { path, .. } = self.as_mut() {
path.insert(0, ConversionPathSegment::Index(index));
}
self
}
pub(crate) fn with_runtime_context(
mut self,
function: Option<String>,
offset: usize,
stack: Vec<String>,
) -> Self {
if let Self::Runtime { trace, .. } = &mut self
&& trace.offset.is_none()
{
trace.function = function;
trace.offset = Some(offset);
trace.stack = stack;
}
self
}
}