rustia 0.2.0

Rustia is a pure-Rust interpreter for embedding standalone Luau in games and tools. Edit scripts without a rebuild and let players write mods. Rustia grew out of a game by Slowchop Studios that needed to script character decisions and replay them on desktop and in a browser.
Documentation
use crate::{CompileError, SourceError, SourceSnapshot};
use crate::{Diagnostic, DiagnosticLimits, DiagnosticSpan, SourceLocation, SourceSpan, VmError};
use std::{fmt, sync::Arc};

/// A script, conversion, or host failure with optional source diagnostics.
///
/// Formatting with `{error}` gives a short message. Use [`report`](Self::report)
/// for a source excerpt and call trail, or [`kind`](Self::kind) to classify the
/// failure in code. Retained diagnostics remain usable after the VM is reset or
/// dropped. Errors are not logged automatically.
#[derive(Debug)]
pub struct Error {
    pub(crate) kind: ErrorKind,
    pub(crate) diagnostic: Option<Arc<Diagnostic>>,
    contexts: Vec<String>,
}

/// The original failure category. Match this instead of parsing error text.
///
/// New categories can be added as the language and embedding API grow. Include
/// a fallback arm when matching an error's [`kind`](Error::kind).
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The source could not be lexed or parsed.
    Source(SourceError),
    /// Parsed source could not be compiled.
    Compile(CompileError),
    /// Execution or VM validation failed, including resource and handle errors.
    Vm(Box<VmError>),
    /// An embedding or conversion failure described by a message.
    Embed(String),
    /// A host error whose original type and cause chain are preserved.
    External(Arc<dyn std::error::Error + Send + Sync>),
}

impl Error {
    pub(crate) fn from_engine(error: impl Into<EngineError>) -> Self {
        match error.into() {
            EngineError::Source(error) => Self::from(SourceError::from_core(error)),
            EngineError::Compile(error) => Self::from(CompileError::from_core(error)),
            EngineError::Vm(error) => Self::from(VmError::from_core(error)),
        }
    }

    /// Creates a message-based error for a callback or embedding operation.
    /// Use [`external`](Self::external) to preserve an existing error's type.
    pub fn embed(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Embed(message.into()),
            diagnostic: None,
            contexts: Vec::new(),
        }
    }

    /// Returns this failure's original category without consuming its diagnostics.
    ///
    /// ```
    /// use rustia::{Error, ErrorKind};
    ///
    /// let error = Error::embed("configuration is missing");
    /// match error.kind() {
    ///     ErrorKind::Embed(message) => assert_eq!(message, "configuration is missing"),
    ///     _ => unreachable!("this example constructs an embedding error"),
    /// }
    /// ```
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    /// Preserves a host's typed error for downcasting and standard cause traversal.
    pub fn external(error: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            kind: ErrorKind::External(Arc::new(error)),
            diagnostic: None,
            contexts: Vec::new(),
        }
    }

    /// Adds host context without changing the typed failure classification.
    pub fn with_context(mut self, context: impl fmt::Display) -> Self {
        self.contexts.push(context.to_string());
        self
    }

    /// Returns added context in the order it was attached.
    /// The most recently added context is displayed first in error messages.
    pub fn contexts(&self) -> impl DoubleEndedIterator<Item = &str> {
        self.contexts.iter().map(String::as_str)
    }

    pub(crate) fn with_data_path(mut self, path: String) -> Self {
        let diagnostic = self
            .diagnostic
            .get_or_insert_with(|| Arc::new(Diagnostic::default()));
        Arc::make_mut(diagnostic).data_path = Some(path);
        self
    }

    pub(crate) fn with_result_source(mut self, name: &str, limits: DiagnosticLimits) -> Self {
        let diagnostic = self
            .diagnostic
            .get_or_insert_with(|| Arc::new(Diagnostic::default()));
        let diagnostic = Arc::make_mut(diagnostic);
        if diagnostic.source.is_none() {
            diagnostic.source = Some(Arc::from(name));
        }
        diagnostic.report_bytes = limits.report_bytes;
        self.with_context("converting the script's returned value")
    }

    /// Consumes this error and returns its original failure category.
    /// Attached context and diagnostics are discarded.
    pub fn into_kind(self) -> ErrorKind {
        self.kind
    }

    pub(crate) fn installation_rolled_back(self) -> Self {
        self.with_context("installation failed; guest state was restored; external host effects are not rolled back")
    }

    /// Returns the VM error, if this failure came from execution or VM validation.
    ///
    /// Inspect its typed kind to distinguish limits, stale handles, and runtime
    /// failures without parsing a message. Script-thrown objects remain private
    /// to their interpreter: returning a captured guest error from a Rust
    /// callback raises its original text as a string.
    pub fn as_vm_error(&self) -> Option<&VmError> {
        match &self.kind {
            ErrorKind::Vm(error) => Some(error),
            _ => None,
        }
    }

    /// Returns the source byte range associated with the failure, when known.
    /// Use [`source_location`](Self::source_location) for its source name and line.
    pub fn source_span(&self) -> Option<SourceSpan> {
        if let Some(diagnostic) = self.diagnostic() {
            return diagnostic.span.map(|span| SourceSpan {
                start: span.start,
                end: span.end,
            });
        }
        match &self.kind {
            ErrorKind::Source(SourceError::Lex(error)) => Some(error.span),
            ErrorKind::Source(SourceError::Parse(error)) => Some(error.span),
            ErrorKind::Compile(error) => error.span,
            ErrorKind::Vm(error) => error.span.map(|span| SourceSpan {
                start: span.0 as usize,
                end: span.1 as usize,
            }),
            ErrorKind::Embed(_) | ErrorKind::External(_) => None,
        }
    }

    /// Returns the source name and line associated with the failure, when known.
    pub fn source_location(&self) -> Option<SourceLocation<'_>> {
        if let Some(diagnostic) = self.diagnostic() {
            if let (Some(source), Some(line)) = (&diagnostic.source, diagnostic.line) {
                return Some(SourceLocation { source, line });
            }
        }
        self.as_vm_error()?
            .location
            .as_ref()
            .map(|location| SourceLocation {
                source: &location.source,
                line: location.line,
            })
    }

    pub(crate) fn with_source(
        mut self,
        name: &str,
        source: &[u8],
        limits: DiagnosticLimits,
    ) -> Self {
        let span = self.source_span().map(|span| DiagnosticSpan {
            start: span.start,
            end: span.end,
        });
        let line = span.and_then(|span| {
            source.get(..span.start).and_then(|prefix| {
                u32::try_from(prefix.iter().filter(|byte| **byte == b'\n').count() + 1).ok()
            })
        });
        let unclosed_block = match &self.kind {
            ErrorKind::Source(SourceError::Parse(error)) => {
                error.unclosed_block.as_ref().and_then(|block| {
                    let prefix = source.get(..block.start)?;
                    let line =
                        u32::try_from(prefix.iter().filter(|byte| **byte == b'\n').count() + 1)
                            .ok()?;
                    Some((line, block.expected))
                })
            }
            _ => None,
        };
        self.diagnostic = Some(Arc::new(Diagnostic {
            unclosed_block,
            source: Some(Arc::from(name)),
            line,
            span,
            snapshot: SourceSnapshot::copy_with_limit(source, limits.source_bytes),
            report_bytes: limits.report_bytes,
            ..Diagnostic::default()
        }));
        self
    }

    pub(crate) fn admit_diagnostic(mut self, vm: &rustia_vm::Vm) -> Self {
        if let Some(diagnostic) = &mut self.diagnostic {
            let diagnostic = Arc::make_mut(diagnostic);
            let mut core = diagnostic.to_core();
            vm.admit_host_diagnostic(&mut core);
            *diagnostic = Diagnostic::from_core(&core);
        }
        self
    }
}

impl From<SourceError> for Error {
    fn from(error: SourceError) -> Self {
        Self {
            kind: ErrorKind::Source(error),
            diagnostic: None,
            contexts: Vec::new(),
        }
    }
}

impl From<String> for Error {
    fn from(message: String) -> Self {
        Self::embed(message)
    }
}

impl From<CompileError> for Error {
    fn from(error: CompileError) -> Self {
        Self {
            kind: ErrorKind::Compile(error),
            diagnostic: None,
            contexts: Vec::new(),
        }
    }
}

impl From<VmError> for Error {
    fn from(error: VmError) -> Self {
        let diagnostic = error.diagnostic.clone();
        Self {
            kind: ErrorKind::Vm(Box::new(error)),
            diagnostic,
            contexts: Vec::new(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for context in self.contexts().rev() {
            write!(formatter, "{context}: ")?;
        }
        self.kind.fmt(formatter)
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ErrorKind::Source(error) => error.fmt(formatter),
            ErrorKind::Compile(error) => error.fmt(formatter),
            ErrorKind::Vm(error) => error.fmt(formatter),
            ErrorKind::Embed(message) => formatter.write_str(message),
            ErrorKind::External(error) => error.fmt(formatter),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.kind {
            ErrorKind::Source(error) => Some(error),
            ErrorKind::Compile(error) => Some(error),
            ErrorKind::Vm(error) => Some(error.as_ref()),
            ErrorKind::Embed(_) => None,
            ErrorKind::External(error) => Some(error.as_ref()),
        }
    }
}

// Conversion machinery stays private: core packages have independently evolving
// APIs and must not become part of the facade's public conversion contracts.
pub(crate) enum EngineError {
    Source(rustia_parser::SourceError),
    Compile(rustia_compiler::CompileError),
    Vm(rustia_vm::Error),
}

impl From<rustia_parser::SourceError> for EngineError {
    fn from(error: rustia_parser::SourceError) -> Self {
        Self::Source(error)
    }
}
impl From<rustia_compiler::CompileError> for EngineError {
    fn from(error: rustia_compiler::CompileError) -> Self {
        Self::Compile(error)
    }
}
impl From<rustia_vm::Error> for EngineError {
    fn from(error: rustia_vm::Error) -> Self {
        Self::Vm(error)
    }
}