Skip to main content

xur_runtime/
error.rs

1use std::fmt;
2
3use xur_errors::Diag;
4use xur_span::Span;
5
6/// An error raised while running a program, such as a type mismatch that could
7/// only be detected at runtime.
8///
9/// The payload is boxed so `RuntimeError` is one pointer wide. That keeps
10/// `RunResult<T>` — returned and `?`-propagated on essentially every fallible
11/// VM operation — small; the unboxed form made it ~72 bytes, and moving that
12/// Result around showed up prominently in profiles.
13#[derive(Debug, Clone, PartialEq)]
14pub struct RuntimeError(Box<RuntimeErrorData>);
15
16#[derive(Debug, Clone, PartialEq)]
17struct RuntimeErrorData {
18    message: String,
19    /// Where the error happened, once known. Errors raised inside native
20    /// functions get the span of the call that reached them.
21    span: Option<Span>,
22    notes: Vec<String>,
23}
24
25pub type RunResult<T> = Result<T, RuntimeError>;
26
27impl RuntimeError {
28    pub fn new(message: impl Into<String>) -> Self {
29        Self(Box::new(RuntimeErrorData {
30            message: message.into(),
31            span: None,
32            notes: Vec::new(),
33        }))
34    }
35
36    /// Records `span` as where the error happened, unless a more precise
37    /// location is already known.
38    pub fn at(mut self, span: Span) -> Self {
39        self.0.span.get_or_insert(span);
40        self
41    }
42
43    pub fn with_note(mut self, note: impl Into<String>) -> Self {
44        self.0.notes.push(note.into());
45        self
46    }
47
48    /// The error message.
49    pub fn message(&self) -> &str {
50        &self.0.message
51    }
52
53    /// The error message, consuming the error.
54    pub fn into_message(self) -> String {
55        self.0.message
56    }
57
58    /// Where the error happened, if known.
59    pub fn span(&self) -> Option<Span> {
60        self.0.span
61    }
62
63    /// The `?`-propagation notes attached to the error.
64    pub fn notes(&self) -> &[String] {
65        &self.0.notes
66    }
67
68    /// The error as a diagnostic, located at its span or else `fallback`.
69    pub fn into_diag(self, fallback: Span) -> Diag {
70        let data = *self.0;
71        let span = data.span.unwrap_or(fallback);
72        let mut diag = Diag::error(data.message, span).with_label(span, "error happened here");
73        for note in data.notes {
74            diag = diag.with_note(note);
75        }
76        diag
77    }
78}
79
80impl fmt::Display for RuntimeError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(&self.0.message)
83    }
84}
85
86impl std::error::Error for RuntimeError {}