Skip to main content

rustia/
error.rs

1use crate::{CompileError, SourceError, SourceSnapshot};
2use crate::{Diagnostic, DiagnosticLimits, DiagnosticSpan, SourceLocation, SourceSpan, VmError};
3use std::{fmt, sync::Arc};
4
5/// A script, conversion, or host failure with optional source diagnostics.
6///
7/// Formatting with `{error}` gives a short message. Use [`report`](Self::report)
8/// for a source excerpt and call trail, or [`kind`](Self::kind) to classify the
9/// failure in code. Retained diagnostics remain usable after the VM is reset or
10/// dropped. Errors are not logged automatically.
11#[derive(Debug)]
12pub struct Error {
13    pub(crate) kind: ErrorKind,
14    pub(crate) diagnostic: Option<Arc<Diagnostic>>,
15    contexts: Vec<String>,
16}
17
18/// The original failure category. Match this instead of parsing error text.
19///
20/// New categories can be added as the language and embedding API grow. Include
21/// a fallback arm when matching an error's [`kind`](Error::kind).
22#[derive(Debug)]
23#[non_exhaustive]
24pub enum ErrorKind {
25    /// The source could not be lexed or parsed.
26    Source(SourceError),
27    /// Parsed source could not be compiled.
28    Compile(CompileError),
29    /// Execution or VM validation failed, including resource and handle errors.
30    Vm(Box<VmError>),
31    /// An embedding or conversion failure described by a message.
32    Embed(String),
33    /// A host error whose original type and cause chain are preserved.
34    External(Arc<dyn std::error::Error + Send + Sync>),
35}
36
37impl Error {
38    pub(crate) fn from_engine(error: impl Into<EngineError>) -> Self {
39        match error.into() {
40            EngineError::Source(error) => Self::from(SourceError::from_core(error)),
41            EngineError::Compile(error) => Self::from(CompileError::from_core(error)),
42            EngineError::Vm(error) => Self::from(VmError::from_core(error)),
43        }
44    }
45
46    /// Creates a message-based error for a callback or embedding operation.
47    /// Use [`external`](Self::external) to preserve an existing error's type.
48    pub fn embed(message: impl Into<String>) -> Self {
49        Self {
50            kind: ErrorKind::Embed(message.into()),
51            diagnostic: None,
52            contexts: Vec::new(),
53        }
54    }
55
56    /// Returns this failure's original category without consuming its diagnostics.
57    ///
58    /// ```
59    /// use rustia::{Error, ErrorKind};
60    ///
61    /// let error = Error::embed("configuration is missing");
62    /// match error.kind() {
63    ///     ErrorKind::Embed(message) => assert_eq!(message, "configuration is missing"),
64    ///     _ => unreachable!("this example constructs an embedding error"),
65    /// }
66    /// ```
67    pub fn kind(&self) -> &ErrorKind {
68        &self.kind
69    }
70
71    /// Preserves a host's typed error for downcasting and standard cause traversal.
72    pub fn external(error: impl std::error::Error + Send + Sync + 'static) -> Self {
73        Self {
74            kind: ErrorKind::External(Arc::new(error)),
75            diagnostic: None,
76            contexts: Vec::new(),
77        }
78    }
79
80    /// Adds host context without changing the typed failure classification.
81    pub fn with_context(mut self, context: impl fmt::Display) -> Self {
82        self.contexts.push(context.to_string());
83        self
84    }
85
86    /// Returns added context in the order it was attached.
87    /// The most recently added context is displayed first in error messages.
88    pub fn contexts(&self) -> impl DoubleEndedIterator<Item = &str> {
89        self.contexts.iter().map(String::as_str)
90    }
91
92    pub(crate) fn with_data_path(mut self, path: String) -> Self {
93        let diagnostic = self
94            .diagnostic
95            .get_or_insert_with(|| Arc::new(Diagnostic::default()));
96        Arc::make_mut(diagnostic).data_path = Some(path);
97        self
98    }
99
100    pub(crate) fn with_result_source(mut self, name: &str, limits: DiagnosticLimits) -> Self {
101        let diagnostic = self
102            .diagnostic
103            .get_or_insert_with(|| Arc::new(Diagnostic::default()));
104        let diagnostic = Arc::make_mut(diagnostic);
105        if diagnostic.source.is_none() {
106            diagnostic.source = Some(Arc::from(name));
107        }
108        diagnostic.report_bytes = limits.report_bytes;
109        self.with_context("converting the script's returned value")
110    }
111
112    /// Consumes this error and returns its original failure category.
113    /// Attached context and diagnostics are discarded.
114    pub fn into_kind(self) -> ErrorKind {
115        self.kind
116    }
117
118    pub(crate) fn installation_rolled_back(self) -> Self {
119        self.with_context("installation failed; guest state was restored; external host effects are not rolled back")
120    }
121
122    /// Returns the VM error, if this failure came from execution or VM validation.
123    ///
124    /// Inspect its typed kind to distinguish limits, stale handles, and runtime
125    /// failures without parsing a message. Script-thrown objects remain private
126    /// to their interpreter: returning a captured guest error from a Rust
127    /// callback raises its original text as a string.
128    pub fn as_vm_error(&self) -> Option<&VmError> {
129        match &self.kind {
130            ErrorKind::Vm(error) => Some(error),
131            _ => None,
132        }
133    }
134
135    /// Returns the source byte range associated with the failure, when known.
136    /// Use [`source_location`](Self::source_location) for its source name and line.
137    pub fn source_span(&self) -> Option<SourceSpan> {
138        if let Some(diagnostic) = self.diagnostic() {
139            return diagnostic.span.map(|span| SourceSpan {
140                start: span.start,
141                end: span.end,
142            });
143        }
144        match &self.kind {
145            ErrorKind::Source(SourceError::Lex(error)) => Some(error.span),
146            ErrorKind::Source(SourceError::Parse(error)) => Some(error.span),
147            ErrorKind::Compile(error) => error.span,
148            ErrorKind::Vm(error) => error.span.map(|span| SourceSpan {
149                start: span.0 as usize,
150                end: span.1 as usize,
151            }),
152            ErrorKind::Embed(_) | ErrorKind::External(_) => None,
153        }
154    }
155
156    /// Returns the source name and line associated with the failure, when known.
157    pub fn source_location(&self) -> Option<SourceLocation<'_>> {
158        if let Some(diagnostic) = self.diagnostic() {
159            if let (Some(source), Some(line)) = (&diagnostic.source, diagnostic.line) {
160                return Some(SourceLocation { source, line });
161            }
162        }
163        self.as_vm_error()?
164            .location
165            .as_ref()
166            .map(|location| SourceLocation {
167                source: &location.source,
168                line: location.line,
169            })
170    }
171
172    pub(crate) fn with_source(
173        mut self,
174        name: &str,
175        source: &[u8],
176        limits: DiagnosticLimits,
177    ) -> Self {
178        let span = self.source_span().map(|span| DiagnosticSpan {
179            start: span.start,
180            end: span.end,
181        });
182        let line = span.and_then(|span| {
183            source.get(..span.start).and_then(|prefix| {
184                u32::try_from(prefix.iter().filter(|byte| **byte == b'\n').count() + 1).ok()
185            })
186        });
187        let unclosed_block = match &self.kind {
188            ErrorKind::Source(SourceError::Parse(error)) => {
189                error.unclosed_block.as_ref().and_then(|block| {
190                    let prefix = source.get(..block.start)?;
191                    let line =
192                        u32::try_from(prefix.iter().filter(|byte| **byte == b'\n').count() + 1)
193                            .ok()?;
194                    Some((line, block.expected))
195                })
196            }
197            _ => None,
198        };
199        self.diagnostic = Some(Arc::new(Diagnostic {
200            unclosed_block,
201            source: Some(Arc::from(name)),
202            line,
203            span,
204            snapshot: SourceSnapshot::copy_with_limit(source, limits.source_bytes),
205            report_bytes: limits.report_bytes,
206            ..Diagnostic::default()
207        }));
208        self
209    }
210
211    pub(crate) fn admit_diagnostic(mut self, vm: &rustia_vm::Vm) -> Self {
212        if let Some(diagnostic) = &mut self.diagnostic {
213            let diagnostic = Arc::make_mut(diagnostic);
214            let mut core = diagnostic.to_core();
215            vm.admit_host_diagnostic(&mut core);
216            *diagnostic = Diagnostic::from_core(&core);
217        }
218        self
219    }
220}
221
222impl From<SourceError> for Error {
223    fn from(error: SourceError) -> Self {
224        Self {
225            kind: ErrorKind::Source(error),
226            diagnostic: None,
227            contexts: Vec::new(),
228        }
229    }
230}
231
232impl From<String> for Error {
233    fn from(message: String) -> Self {
234        Self::embed(message)
235    }
236}
237
238impl From<CompileError> for Error {
239    fn from(error: CompileError) -> Self {
240        Self {
241            kind: ErrorKind::Compile(error),
242            diagnostic: None,
243            contexts: Vec::new(),
244        }
245    }
246}
247
248impl From<VmError> for Error {
249    fn from(error: VmError) -> Self {
250        let diagnostic = error.diagnostic.clone();
251        Self {
252            kind: ErrorKind::Vm(Box::new(error)),
253            diagnostic,
254            contexts: Vec::new(),
255        }
256    }
257}
258
259impl fmt::Display for Error {
260    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
261        for context in self.contexts().rev() {
262            write!(formatter, "{context}: ")?;
263        }
264        self.kind.fmt(formatter)
265    }
266}
267
268impl fmt::Display for ErrorKind {
269    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
270        match self {
271            ErrorKind::Source(error) => error.fmt(formatter),
272            ErrorKind::Compile(error) => error.fmt(formatter),
273            ErrorKind::Vm(error) => error.fmt(formatter),
274            ErrorKind::Embed(message) => formatter.write_str(message),
275            ErrorKind::External(error) => error.fmt(formatter),
276        }
277    }
278}
279
280impl std::error::Error for Error {
281    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
282        match &self.kind {
283            ErrorKind::Source(error) => Some(error),
284            ErrorKind::Compile(error) => Some(error),
285            ErrorKind::Vm(error) => Some(error.as_ref()),
286            ErrorKind::Embed(_) => None,
287            ErrorKind::External(error) => Some(error.as_ref()),
288        }
289    }
290}
291
292// Conversion machinery stays private: core packages have independently evolving
293// APIs and must not become part of the facade's public conversion contracts.
294pub(crate) enum EngineError {
295    Source(rustia_parser::SourceError),
296    Compile(rustia_compiler::CompileError),
297    Vm(rustia_vm::Error),
298}
299
300impl From<rustia_parser::SourceError> for EngineError {
301    fn from(error: rustia_parser::SourceError) -> Self {
302        Self::Source(error)
303    }
304}
305impl From<rustia_compiler::CompileError> for EngineError {
306    fn from(error: rustia_compiler::CompileError) -> Self {
307        Self::Compile(error)
308    }
309}
310impl From<rustia_vm::Error> for EngineError {
311    fn from(error: rustia_vm::Error) -> Self {
312        Self::Vm(error)
313    }
314}