Skip to main content

tui_markup/
error.rs

1use std::fmt::{Debug, Display};
2
3use crate::parser::Error as ParseError;
4
5/// Error with a location info.
6pub trait LocatedError {
7    /// get error happened location in source input.
8    fn location(&self) -> (usize, usize);
9}
10
11/// Error for markup source compile pipeline.
12///
13/// Display this error in `{}` formatter will show a error message with detailed reason and
14/// location. So usually you don't need check variants.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Error<'a, GE> {
17    /// Parsing stage failed, usually means there is invalid syntax in source string
18    Parse(ParseError<'a>),
19
20    /// Generating stage failed, see document of generator type for detail.
21    Gen(GE),
22}
23
24impl<GE> Display for Error<'_, GE>
25where
26    GE: Display,
27{
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        match self {
30            Error::Parse(pe) => f.write_fmt(format_args!("parse failed: {}", pe)),
31            Error::Gen(ge) => f.write_fmt(format_args!("generate failed: {}", ge)),
32        }
33    }
34}
35
36impl<GE> std::error::Error for Error<'_, GE> where Self: Debug + Display {}
37
38impl<GE: LocatedError> LocatedError for Error<'_, GE> {
39    fn location(&self) -> (usize, usize) {
40        match self {
41            Self::Parse(e) => e.location(),
42            Self::Gen(e) => e.location(),
43        }
44    }
45}
46
47impl<'a, GE> From<ParseError<'a>> for Error<'a, GE> {
48    fn from(e: ParseError<'a>) -> Self {
49        Self::Parse(e)
50    }
51}
52
53#[cfg(test)]
54mod test {
55    use crate::generator::helper::GeneratorInfallible;
56
57    #[test]
58    fn error_must_impl_std_error() {
59        fn is_error<E: std::error::Error>() {}
60
61        is_error::<GeneratorInfallible>();
62        is_error::<crate::parser::Error<'_>>();
63        is_error::<super::Error<'static, GeneratorInfallible>>();
64    }
65}