1
0
dust/dust-lang/src/dust_error.rs

50 lines
1.3 KiB
Rust
Raw Normal View History

2024-09-10 05:04:30 +00:00
use annotate_snippets::{Level, Renderer, Snippet};
use crate::{LexError, ParseError, Span};
2024-09-07 16:15:47 +00:00
#[derive(Debug, PartialEq)]
pub enum DustError<'src> {
2024-09-07 16:15:47 +00:00
Lex {
error: LexError,
source: &'src str,
},
2024-09-07 16:15:47 +00:00
Parse {
error: ParseError,
source: &'src str,
},
}
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 {
DustError::Parse { error, source } => {
let position = error.position();
let label = format!("Parse error: {}", error.description());
let details = error
.details()
.unwrap_or_else(|| "While parsing this code".to_string());
let message = Level::Error.title(&label).snippet(
Snippet::source(source)
.fold(true)
.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());
}
_ => todo!(),
}
report
}
}
pub trait AnnotatedError {
fn title() -> &'static str;
fn description(&self) -> &'static str;
fn details(&self) -> Option<String>;
fn position(&self) -> Span;
}