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
7/// could only be detected at runtime.
8#[derive(Debug, Clone, PartialEq)]
9pub struct RuntimeError {
10    pub message: String,
11    /// Where the error happened, once known. Errors raised inside native
12    /// functions get the span of the call that reached them.
13    pub span: Option<Span>,
14    pub notes: Vec<String>,
15}
16
17pub type RunResult<T> = Result<T, RuntimeError>;
18
19impl RuntimeError {
20    pub fn new(message: impl Into<String>) -> Self {
21        Self {
22            message: message.into(),
23            span: None,
24            notes: Vec::new(),
25        }
26    }
27
28    /// Records `span` as where the error happened, unless a more precise
29    /// location is already known.
30    pub fn at(mut self, span: Span) -> Self {
31        self.span.get_or_insert(span);
32        self
33    }
34
35    pub fn with_note(mut self, note: impl Into<String>) -> Self {
36        self.notes.push(note.into());
37        self
38    }
39
40    /// The error as a diagnostic, located at its span or else `fallback`.
41    pub fn into_diag(self, fallback: Span) -> Diag {
42        let span = self.span.unwrap_or(fallback);
43        let mut diag = Diag::error(self.message, span).with_label(span, "error happened here");
44        for note in self.notes {
45            diag = diag.with_note(note);
46        }
47        diag
48    }
49}
50
51impl fmt::Display for RuntimeError {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.write_str(&self.message)
54    }
55}
56
57impl std::error::Error for RuntimeError {}