use std::fmt;
use xur_errors::Diag;
use xur_span::Span;
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeError(Box<RuntimeErrorData>);
#[derive(Debug, Clone, PartialEq)]
struct RuntimeErrorData {
message: String,
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(),
}))
}
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
}
pub fn message(&self) -> &str {
&self.0.message
}
pub fn into_message(self) -> String {
self.0.message
}
pub fn span(&self) -> Option<Span> {
self.0.span
}
pub fn notes(&self) -> &[String] {
&self.0.notes
}
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 {}