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

81 lines
2.6 KiB
Rust
Raw Normal View History

2024-08-09 01:59:09 +00:00
//! Top-level error handling for the Dust language.
2024-08-09 01:47:49 +00:00
use annotate_snippets::{Level, Renderer, Snippet};
2024-08-11 21:59:52 +00:00
use std::fmt::Display;
2024-08-09 00:58:56 +00:00
use crate::{AnalysisError, LexError, ParseError, RuntimeError};
2024-08-09 00:58:56 +00:00
2024-08-09 01:59:09 +00:00
/// An error that occurred during the execution of the Dust language and its
/// corresponding source code.
2024-08-09 00:58:56 +00:00
#[derive(Debug, Clone, PartialEq)]
2024-08-11 21:59:52 +00:00
pub enum DustError<'src> {
VmError {
runtime_error: RuntimeError,
2024-08-11 21:59:52 +00:00
source: &'src str,
},
AnalysisError {
analysis_error: AnalysisError,
2024-08-11 21:59:52 +00:00
source: &'src str,
},
ParseError {
parse_error: ParseError,
source: &'src str,
},
LexError {
lex_error: LexError,
source: &'src str,
},
2024-08-09 00:58:56 +00:00
}
2024-08-09 01:47:49 +00:00
impl<'src> DustError<'src> {
2024-08-11 21:59:52 +00:00
pub fn title(&self) -> &'static str {
match self {
DustError::VmError { .. } => "Runtime error",
DustError::AnalysisError { .. } => "Analysis error",
2024-08-11 21:59:52 +00:00
DustError::ParseError { .. } => "Parse error",
DustError::LexError { .. } => "Lex error",
}
}
pub fn position(&self) -> (usize, usize) {
match self {
DustError::VmError { runtime_error, .. } => runtime_error.position(),
DustError::AnalysisError { analysis_error, .. } => analysis_error.position(),
2024-08-11 21:59:52 +00:00
DustError::ParseError { parse_error, .. } => parse_error.position(),
DustError::LexError { lex_error, .. } => lex_error.position(),
}
}
pub fn source(&self) -> &'src str {
match self {
DustError::VmError { source, .. } => source,
DustError::AnalysisError { source, .. } => source,
2024-08-11 21:59:52 +00:00
DustError::ParseError { source, .. } => source,
DustError::LexError { source, .. } => source,
}
2024-08-09 01:47:49 +00:00
}
pub fn report(&self) -> String {
2024-08-11 21:59:52 +00:00
let title = self.title();
let span = self.position();
let label = self.to_string();
2024-08-09 01:47:49 +00:00
let message = Level::Error.title(title).snippet(
2024-08-11 21:59:52 +00:00
Snippet::source(self.source())
.annotation(Level::Info.span(span.0..span.1).label(&label)),
2024-08-09 01:47:49 +00:00
);
let renderer = Renderer::styled();
format!("{}", renderer.render(message))
}
}
2024-08-09 00:58:56 +00:00
impl Display for DustError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2024-08-11 21:59:52 +00:00
match self {
DustError::VmError { runtime_error, .. } => write!(f, "{runtime_error}"),
DustError::AnalysisError { analysis_error, .. } => write!(f, "{analysis_error}"),
2024-08-11 21:59:52 +00:00
DustError::ParseError { parse_error, .. } => write!(f, "{parse_error}"),
DustError::LexError { lex_error, .. } => write!(f, "{lex_error}"),
}
2024-08-09 00:58:56 +00:00
}
}