xur-runtime 0.1.10

Values, native-function registry and facet conversions for the Xur language
Documentation
use std::fmt;

use xur_errors::Diag;
use xur_span::Span;

/// An error raised while running a program, such as a type mismatch that could
/// only be detected at runtime.
///
/// The payload is boxed so `RuntimeError` is one pointer wide. That keeps
/// `RunResult<T>` — returned and `?`-propagated on essentially every fallible
/// VM operation — small; the unboxed form made it ~72 bytes, and moving that
/// Result around showed up prominently in profiles.
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeError(Box<RuntimeErrorData>);

#[derive(Debug, Clone, PartialEq)]
struct RuntimeErrorData {
    message: String,
    /// Where the error happened, once known. Errors raised inside native
    /// functions get the span of the call that reached them.
    span: Option<Span>,
    notes: Vec<String>,
}

pub type RunResult<T> = Result<T, RuntimeError>;

impl RuntimeError {
    pub fn new(message: impl Into<String>) -> Self {
        Self(Box::new(RuntimeErrorData {
            message: message.into(),
            span: None,
            notes: Vec::new(),
        }))
    }

    /// Records `span` as where the error happened, unless a more precise
    /// location is already known.
    pub fn at(mut self, span: Span) -> Self {
        self.0.span.get_or_insert(span);
        self
    }

    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.0.notes.push(note.into());
        self
    }

    /// The error message.
    pub fn message(&self) -> &str {
        &self.0.message
    }

    /// The error message, consuming the error.
    pub fn into_message(self) -> String {
        self.0.message
    }

    /// Where the error happened, if known.
    pub fn span(&self) -> Option<Span> {
        self.0.span
    }

    /// The `?`-propagation notes attached to the error.
    pub fn notes(&self) -> &[String] {
        &self.0.notes
    }

    /// The error as a diagnostic, located at its span or else `fallback`.
    pub fn into_diag(self, fallback: Span) -> Diag {
        let data = *self.0;
        let span = data.span.unwrap_or(fallback);
        let mut diag = Diag::error(data.message, span).with_label(span, "error happened here");
        for note in data.notes {
            diag = diag.with_note(note);
        }
        diag
    }
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0.message)
    }
}

impl std::error::Error for RuntimeError {}