crossandra/
error.rs

1#[derive(Debug)]
2pub enum Error {
3    BadToken(char, usize),
4    DuplicatePattern(String),
5    EmptyLiteral,
6    InvalidRegex(Box<fancy_regex::Error>),
7}
8
9impl std::fmt::Display for Error {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        match self {
12            Self::BadToken(c, p) => write!(f, "invalid token {c:?} at position {p}"),
13            Self::DuplicatePattern(name) => write!(f, "duplicate pattern {name:?}"),
14            Self::EmptyLiteral => write!(f, "literals cannot be empty"),
15            Self::InvalidRegex(err) => err.fmt(f),
16        }
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use crate::error::Error;
23
24    #[test]
25    fn error_display() {
26        assert_eq!(
27            Error::BadToken('x', 7).to_string(),
28            "invalid token 'x' at position 7"
29        );
30        assert_eq!(
31            Error::DuplicatePattern("string".into()).to_string(),
32            "duplicate pattern \"string\""
33        );
34        assert_eq!(Error::EmptyLiteral.to_string(), "literals cannot be empty");
35        assert_eq!(
36            Error::InvalidRegex(Box::new(fancy_regex::Regex::new("+").unwrap_err())).to_string(),
37            "Parsing error at position 0: Target of repeat operator is invalid"
38        );
39    }
40}