1use std::fmt;
2
3use xur_errors::Diag;
4use xur_span::Span;
5
6#[derive(Debug, Clone, PartialEq)]
14pub struct RuntimeError(Box<RuntimeErrorData>);
15
16#[derive(Debug, Clone, PartialEq)]
17struct RuntimeErrorData {
18 message: String,
19 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 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 pub fn message(&self) -> &str {
50 &self.0.message
51 }
52
53 pub fn into_message(self) -> String {
55 self.0.message
56 }
57
58 pub fn span(&self) -> Option<Span> {
60 self.0.span
61 }
62
63 pub fn notes(&self) -> &[String] {
65 &self.0.notes
66 }
67
68 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 {}