use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Position {
pub file: PathBuf,
pub line: usize,
}
impl Position {
pub fn new(file: impl Into<PathBuf>, line: usize) -> Self {
Self {
file: file.into(),
line,
}
}
}
#[derive(Debug)]
pub enum Error {
Io {
path: PathBuf,
source: io::Error,
},
FileNotFound(PathBuf),
MissingIndex(PathBuf),
UndefinedVariable {
name: String,
at: Option<Position>,
},
Parse {
message: String,
at: Option<Position>,
},
RecursiveInclude(PathBuf),
OutDirectoryNotFound(PathBuf),
InvalidArgument(String),
}
impl Error {
pub fn io(path: impl AsRef<Path>, source: io::Error) -> Self {
Error::Io {
path: path.as_ref().to_path_buf(),
source,
}
}
pub fn parse(at: Position, message: impl Into<String>) -> Self {
Error::Parse {
message: message.into(),
at: Some(at),
}
}
pub fn undefined_variable(name: impl Into<String>, at: Position) -> Self {
Error::UndefinedVariable {
name: name.into(),
at: Some(at),
}
}
pub fn position(&self) -> Option<&Position> {
match self {
Error::UndefinedVariable { at, .. } | Error::Parse { at, .. } => at.as_ref(),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io { path, source } => write!(f, "{}: {source}", path.display()),
Error::FileNotFound(path) => write!(f, "file not found: {}", path.display()),
Error::MissingIndex(path) => {
write!(f, "no index.sql in the directory: {}", path.display())
}
Error::UndefinedVariable { name, at } => {
write!(f, "variable '{name}' undefined")?;
write_position(f, at)
}
Error::Parse { message, at } => {
write!(f, "{message}")?;
write_position(f, at)
}
Error::RecursiveInclude(path) => {
write!(f, "recursive include: {}", path.display())
}
Error::OutDirectoryNotFound(path) => {
write!(f, "output directory not found: {}", path.display())
}
Error::InvalidArgument(message) => write!(f, "{message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io { source, .. } => Some(source),
_ => None,
}
}
}
fn write_position(f: &mut fmt::Formatter<'_>, at: &Option<Position>) -> fmt::Result {
match at {
Some(at) => write!(f, " at {}:{}", at.file.display(), at.line),
None => Ok(()),
}
}
pub type Result<T> = std::result::Result<T, Error>;