use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Location {
pub file: Arc<Path>,
pub line: usize,
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let here = std::env::current_dir().unwrap_or_default();
let file = self.file.strip_prefix(&here).unwrap_or(&self.file);
write!(f, "{}:{}", file.display(), self.line)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
pub message: String,
pub location: Option<Location>,
pub excerpt: Option<(String, std::ops::Range<usize>)>,
pub help: Option<String>,
}
impl Error {
pub fn new(message: impl Into<String>) -> Error {
Error { message: message.into(), location: None, excerpt: None, help: None }
}
pub fn at(mut self, location: Location) -> Error {
self.location.get_or_insert(location);
self
}
pub fn excerpt(mut self, text: &str, span: std::ops::Range<usize>) -> Error {
self.excerpt = Some((text.to_string(), span));
self
}
pub fn help(mut self, help: impl Into<String>) -> Error {
self.help = Some(help.into());
self
}
pub fn io(path: &Path, error: std::io::Error) -> Error {
Error::new(format!("{}: {error}", path.display()))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)?;
let Some(location) = &self.location else {
return match &self.help {
Some(help) => write!(f, "\n = help: {help}"),
None => Ok(()),
};
};
let number = location.line.to_string();
let gutter = " ".repeat(number.len());
write!(f, "\n{gutter}--> {location}")?;
if let Some((text, span)) = &self.excerpt {
let before = text[..span.start.min(text.len())].chars().count();
let width = text.get(span.clone()).map_or(1, |part| part.chars().count().max(1));
write!(f, "\n{gutter} |\n{number} | {text}\n{gutter} | {}{}", " ".repeat(before), "^".repeat(width))?;
}
if let Some(help) = &self.help {
write!(f, "\n{gutter} = help: {help}")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Error {
Error::new(error.to_string())
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub(crate) fn resolve(base: &Path, path: impl AsRef<Path>) -> PathBuf {
use std::path::Component;
let path = path.as_ref();
let joined = if path.is_absolute() { path.to_path_buf() } else { base.join(path) };
let mut normal = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir if normal.file_name().is_some() => {
normal.pop();
}
other => normal.push(other),
}
}
if path.as_os_str().to_string_lossy().ends_with(['/', '\\']) {
normal.push("");
}
normal
}
#[cfg(test)]
mod tests {
use super::*;
fn location() -> Location {
Location { file: Arc::from(Path::new("demo.tape")), line: 12 }
}
#[test]
fn displays_like_a_compiler() {
let error = Error::new("not a duration: 5x")
.at(location())
.excerpt("Sleep 5x", 6..8)
.help("durations are written 500ms, 2s or 1.5s");
assert_eq!(
error.to_string(),
"not a duration: 5x\n --> demo.tape:12\n |\n12 | Sleep 5x\n | ^^\n = help: durations are written 500ms, 2s or 1.5s"
);
}
#[test]
fn the_first_location_given_is_the_one_kept() {
let other = Location { file: Arc::from(Path::new("other.tape")), line: 1 };
assert_eq!(Error::new("x").at(location()).at(other).location, Some(location()));
}
#[test]
fn without_a_location_it_is_the_message_and_any_help() {
assert_eq!(Error::new("boom").to_string(), "boom");
assert_eq!(Error::new("boom").help("duck").to_string(), "boom\n = help: duck");
}
#[test]
fn resolve_works_out_dots_and_keeps_a_trailing_separator() {
assert_eq!(resolve(Path::new("/a/b"), "../c.gif"), PathBuf::from("/a/c.gif"));
assert_eq!(resolve(Path::new("/a/b"), "./c/./d.gif"), PathBuf::from("/a/b/c/d.gif"));
assert_eq!(resolve(Path::new("/a/b"), "/x/../y"), PathBuf::from("/y"));
assert!(resolve(Path::new("/a"), "frames/").to_string_lossy().ends_with('/'));
}
#[test]
fn an_empty_span_still_underlines_one_character() {
let error = Error::new("x").at(location()).excerpt("Type", 4..4);
assert!(error.to_string().ends_with("| ^"), "{error}");
}
}