use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Span {
pub file: PathBuf,
pub line: usize,
pub col: usize,
pub width: usize,
}
impl Span {
#[must_use]
pub fn head(file: &Path) -> Self {
Self { file: file.to_path_buf(), line: 1, col: 1, width: 1 }
}
}
#[derive(Clone, Debug)]
pub struct Fault {
pub message: String,
pub span: Span,
pub source: String,
}
impl Fault {
pub fn at(message: impl Into<String>, span: Span, source: &str) -> Self {
Self { message: message.into(), span, source: source.to_owned() }
}
}
impl fmt::Display for Fault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Span { file, line, col, width } = &self.span;
write!(f, "{}:{line}:{col}: {}", file.display(), self.message)?;
let mut line = *line;
let mut col = *col;
let text = self.source.lines().nth(line.saturating_sub(1)).unwrap_or_else(|| {
let last = self.source.lines().next_back().unwrap_or_default();
line = self.source.lines().count().max(1);
col = last.chars().count() + 1;
last
});
let gutter = format!("{line:>5} | ");
write!(f, "\n{gutter}{text}\n")?;
for _ in 0..gutter.chars().count() + col - 1 {
f.write_str(" ")?;
}
for _ in 0..(*width).max(1) {
f.write_str("^")?;
}
Ok(())
}
}
impl std::error::Error for Fault {}