use std::fmt;
use std::path::Path;
use crate::source::SourceSpan;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Diagnostic {
pub code: &'static str,
pub message: String,
pub span: SourceSpan,
pub notes: Vec<String>,
}
impl Diagnostic {
#[must_use]
pub fn new(code: &'static str, message: impl Into<String>, span: SourceSpan) -> Self {
Self {
code,
message: message.into(),
span,
notes: Vec::new(),
}
}
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
#[must_use]
pub fn io(code: &'static str, path: &Path, error: &std::io::Error) -> Self {
Self::new(
code,
format!("could not access `{}`: {error}", path.display()),
SourceSpan::file_start(path),
)
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}:{} [{}]\n\n{}",
self.span.file().display(),
self.span.line,
self.span.column,
self.code,
self.message
)?;
if let Some(line) = self
.span
.source()
.text()
.lines()
.nth(self.span.line.saturating_sub(1))
{
write!(
f,
"\n\n{line}\n{}^",
" ".repeat(self.span.column.saturating_sub(1))
)?;
}
for note in &self.notes {
write!(f, "\n\nnote: {note}")?;
}
Ok(())
}
}
impl std::error::Error for Diagnostic {}
pub type Result<T> = std::result::Result<T, Diagnostic>;