use std::fmt;
#[derive(Debug)]
pub struct GwError {
pub line: usize,
pub context: Option<String>,
pub kind: GwErrorKind,
}
impl GwError {
pub fn at(line: usize, context: impl Into<String>, kind: GwErrorKind) -> Self {
Self {
line,
context: Some(context.into()),
kind,
}
}
#[must_use]
pub fn at_line(line: usize, kind: GwErrorKind) -> Self {
Self {
line,
context: None,
kind,
}
}
}
impl fmt::Display for GwError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.line > 0 {
write!(f, "line {}: {}", self.line, self.kind)?;
} else {
write!(f, "{}", self.kind)?;
}
if let Some(context) = &self.context {
write!(f, "\n in: {context}")?;
}
Ok(())
}
}
impl std::error::Error for GwError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GwErrorKind::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for GwError {
fn from(e: std::io::Error) -> Self {
Self::at_line(0, GwErrorKind::Io(e))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum GwErrorKind {
Io(std::io::Error),
Syntax(String),
UnexpectedEof {
expected: &'static str,
},
InvalidDate(String),
InvalidTitle(String),
UnknownTag(String),
TrailingTokens(Vec<String>),
UnknownBlock(String),
}
impl fmt::Display for GwErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "I/O error: {e}"),
Self::Syntax(what) => write!(f, "syntax error: {what}"),
Self::UnexpectedEof { expected } => {
write!(f, "unexpected end of file, expected `{expected}`")
}
Self::InvalidDate(s) => write!(f, "invalid date: `{s}`"),
Self::InvalidTitle(s) => write!(f, "invalid title: `{s}`"),
Self::UnknownTag(s) => write!(f, "unknown tag: `{s}`"),
Self::TrailingTokens(toks) => {
write!(f, "unexpected trailing tokens: {}", toks.join(" "))
}
Self::UnknownBlock(s) => write!(f, "unknown block keyword: `{s}`"),
}
}
}
pub type Result<T> = std::result::Result<T, GwError>;