2024-11-06 20:40:37 +00:00
|
|
|
//! Top-level Dust errors with source code annotations.
|
2024-09-10 05:04:30 +00:00
|
|
|
use annotate_snippets::{Level, Renderer, Snippet};
|
|
|
|
|
2024-11-06 20:40:37 +00:00
|
|
|
use crate::{vm::VmError, CompileError, Span};
|
2024-09-07 08:34:03 +00:00
|
|
|
|
2024-11-06 00:38:26 +00:00
|
|
|
/// A top-level error that can occur during the execution of Dust code.
|
|
|
|
///
|
|
|
|
/// This error can display nicely formatted messages with source code annotations.
|
2024-09-07 16:15:47 +00:00
|
|
|
#[derive(Debug, PartialEq)]
|
2024-09-07 08:34:03 +00:00
|
|
|
pub enum DustError<'src> {
|
2024-11-06 20:40:37 +00:00
|
|
|
Compile {
|
|
|
|
error: CompileError,
|
2024-09-07 08:34:03 +00:00
|
|
|
source: &'src str,
|
|
|
|
},
|
2024-09-12 04:39:31 +00:00
|
|
|
Runtime {
|
|
|
|
error: VmError,
|
|
|
|
source: &'src str,
|
|
|
|
},
|
2024-09-07 08:34:03 +00:00
|
|
|
}
|
2024-09-10 05:04:30 +00:00
|
|
|
|
|
|
|
impl<'src> DustError<'src> {
|
|
|
|
pub fn report(&self) -> String {
|
|
|
|
let mut report = String::new();
|
|
|
|
let renderer = Renderer::styled();
|
|
|
|
|
|
|
|
match self {
|
2024-09-12 04:39:31 +00:00
|
|
|
DustError::Runtime { error, source } => {
|
|
|
|
let position = error.position();
|
2024-11-06 20:40:37 +00:00
|
|
|
let label = format!("{}: {}", VmError::title(), error.description());
|
2024-09-12 04:39:31 +00:00
|
|
|
let details = error
|
|
|
|
.details()
|
|
|
|
.unwrap_or_else(|| "While running this code".to_string());
|
|
|
|
let message = Level::Error.title(&label).snippet(
|
|
|
|
Snippet::source(source)
|
2024-10-13 11:14:12 +00:00
|
|
|
.fold(false)
|
2024-09-12 04:39:31 +00:00
|
|
|
.annotation(Level::Error.span(position.0..position.1).label(&details)),
|
|
|
|
);
|
|
|
|
|
|
|
|
report.push_str(&renderer.render(message).to_string());
|
|
|
|
}
|
2024-11-06 20:40:37 +00:00
|
|
|
DustError::Compile { error, source } => {
|
2024-09-10 07:42:25 +00:00
|
|
|
let position = error.position();
|
2024-11-06 20:40:37 +00:00
|
|
|
let label = format!("{}: {}", CompileError::title(), error.description());
|
2024-09-10 13:26:05 +00:00
|
|
|
let details = error
|
|
|
|
.details()
|
|
|
|
.unwrap_or_else(|| "While parsing this code".to_string());
|
|
|
|
let message = Level::Error.title(&label).snippet(
|
|
|
|
Snippet::source(source)
|
2024-10-13 11:14:12 +00:00
|
|
|
.fold(false)
|
2024-09-10 13:26:05 +00:00
|
|
|
.annotation(Level::Error.span(position.0..position.1).label(&details)),
|
2024-09-10 05:04:30 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
report.push_str(&renderer.render(message).to_string());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
report
|
|
|
|
}
|
|
|
|
}
|
2024-09-10 13:26:05 +00:00
|
|
|
|
|
|
|
pub trait AnnotatedError {
|
|
|
|
fn title() -> &'static str;
|
|
|
|
fn description(&self) -> &'static str;
|
|
|
|
fn details(&self) -> Option<String>;
|
|
|
|
fn position(&self) -> Span;
|
|
|
|
}
|