Skip to main content

javelin_pattern/
error.rs

1use std::fmt;
2
3/// An error compiling a regular expression.
4#[derive(Clone, Debug, Eq, PartialEq)]
5#[non_exhaustive]
6pub enum Error {
7    /// A native compilation error, identified by a `JP_RESULT_*` code.
8    Compile(i32),
9    /// A literal NUL byte in the pattern, with its byte offset.
10    /// Use an escape such as `\x00` to match NUL bytes.
11    NulByte(usize),
12}
13
14impl Error {
15    /// Returns the native error code, if compilation reached the engine.
16    pub fn code(&self) -> Option<i32> {
17        match *self {
18            Self::Compile(code) => Some(code),
19            Self::NulByte(_) => None,
20        }
21    }
22}
23
24impl std::error::Error for Error {}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match *self {
29            Self::NulByte(offset) => write!(f, "NUL byte in pattern at offset {offset}"),
30            Self::Compile(code) => {
31                let message = match code {
32                    1 => "internal error",
33                    2 => "expected closing group",
34                    3 => "invalid backreference",
35                    4 => "invalid options",
36                    5 => "lookbehind does not have constant byte length",
37                    6 => "malformed conditional",
38                    7 => "maximum repetition count exceeded",
39                    8 => "minimum repetition count exceeds maximum",
40                    9 => "too many bytecode instructions",
41                    10 => "too many captures",
42                    11 => "too many progress checks",
43                    12 => "unable to parse group type",
44                    13 => "unable to parse repetition",
45                    14 => "unable to resolve recursion target",
46                    15 => "unexpected control character",
47                    16 => "unexpected end of pattern",
48                    17 => "unexpected group options",
49                    18 => "unexpected hex character",
50                    19 => "unexpected lookbehind type",
51                    20 => "unexpected token",
52                    21 => "unknown escape",
53                    22 => "unknown POSIX character class",
54                    23 => "malformed Unicode property",
55                    24 => "unknown Unicode property",
56                    _ => "unknown error",
57                };
58                write!(f, "JavelinPattern compilation failed: {message} ({code})")
59            }
60        }
61    }
62}