fancy_regex/
error.rs

1use alloc::string::String;
2use core::fmt;
3use regex_automata::meta::BuildError as RaBuildError;
4
5/// Result type for this crate with specific error enum.
6pub type Result<T> = ::core::result::Result<T, Error>;
7
8pub type ParseErrorPosition = usize;
9
10/// An error as the result of parsing, compiling or running a regex.
11#[derive(Clone, Debug)]
12#[non_exhaustive]
13pub enum Error {
14    /// An error as a result of parsing a regex pattern, with the position where the error occurred
15    ParseError(ParseErrorPosition, ParseError),
16    /// An error as a result of compiling a regex
17    CompileError(CompileError),
18    /// An error as a result of running a regex
19    RuntimeError(RuntimeError),
20}
21
22/// An error for the result of parsing a regex pattern.
23#[derive(Clone, Debug)]
24#[non_exhaustive]
25pub enum ParseError {
26    /// General parsing error
27    GeneralParseError(String),
28    /// Opening parenthesis without closing parenthesis, e.g. `(a|b`
29    UnclosedOpenParen,
30    /// Invalid repeat syntax
31    InvalidRepeat,
32    /// Pattern too deeply nested
33    RecursionExceeded,
34    /// Backslash without following character
35    TrailingBackslash,
36    /// Invalid escape
37    InvalidEscape(String),
38    /// Unicode escape not closed
39    UnclosedUnicodeName,
40    /// Invalid hex escape
41    InvalidHex,
42    /// Invalid codepoint for hex or unicode escape
43    InvalidCodepointValue,
44    /// Invalid character class
45    InvalidClass,
46    /// Unknown group flag
47    UnknownFlag(String),
48    /// Disabling Unicode not supported
49    NonUnicodeUnsupported,
50    /// Invalid back reference
51    InvalidBackref,
52    /// Quantifier on lookaround or other zero-width assertion
53    TargetNotRepeatable,
54    /// Couldn't parse group name
55    InvalidGroupName,
56    /// Invalid group id in escape sequence
57    InvalidGroupNameBackref(String),
58}
59
60/// An error as the result of compiling a regex.
61#[derive(Clone, Debug)]
62#[non_exhaustive]
63pub enum CompileError {
64    /// Regex crate error
65    InnerError(RaBuildError),
66    /// Look-behind assertion without constant size
67    LookBehindNotConst,
68    /// Couldn't parse group name
69    InvalidGroupName,
70    /// Invalid group id in escape sequence
71    InvalidGroupNameBackref(String),
72    /// Invalid back reference
73    InvalidBackref,
74    /// Once named groups are used you cannot refer to groups by number
75    NamedBackrefOnly,
76}
77
78/// An error as the result of executing a regex.
79#[derive(Clone, Debug)]
80#[non_exhaustive]
81pub enum RuntimeError {
82    /// Max stack size exceeded for backtracking while executing regex.
83    StackOverflow,
84    /// Max limit for backtracking count exceeded while executing the regex.
85    /// Configure using
86    /// [`RegexBuilder::backtrack_limit`](struct.RegexBuilder.html#method.backtrack_limit).
87    BacktrackLimitExceeded,
88}
89
90#[cfg(feature = "std")]
91impl ::std::error::Error for Error {}
92
93impl fmt::Display for ParseError {
94    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95        match self {
96            ParseError::GeneralParseError(s) => write!(f, "General parsing error: {}", s),
97            ParseError::UnclosedOpenParen => {
98                write!(f, "Opening parenthesis without closing parenthesis")
99            }
100            ParseError::InvalidRepeat => write!(f, "Invalid repeat syntax"),
101            ParseError::RecursionExceeded => write!(f, "Pattern too deeply nested"),
102            ParseError::TrailingBackslash => write!(f, "Backslash without following character"),
103            ParseError::InvalidEscape(s) => write!(f, "Invalid escape: {}", s),
104            ParseError::UnclosedUnicodeName => write!(f, "Unicode escape not closed"),
105            ParseError::InvalidHex => write!(f, "Invalid hex escape"),
106            ParseError::InvalidCodepointValue => {
107                write!(f, "Invalid codepoint for hex or unicode escape")
108            }
109            ParseError::InvalidClass => write!(f, "Invalid character class"),
110            ParseError::UnknownFlag(s) => write!(f, "Unknown group flag: {}", s),
111            ParseError::NonUnicodeUnsupported => write!(f, "Disabling Unicode not supported"),
112            ParseError::InvalidBackref => write!(f, "Invalid back reference"),
113            ParseError::InvalidGroupName => write!(f, "Could not parse group name"),
114            ParseError::InvalidGroupNameBackref(s) => {
115                write!(f, "Invalid group name in back reference: {}", s)
116            }
117            ParseError::TargetNotRepeatable => write!(f, "Target of repeat operator is invalid"),
118        }
119    }
120}
121
122impl fmt::Display for CompileError {
123    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124        match self {
125            CompileError::InnerError(e) => write!(f, "Regex error: {}", e),
126            CompileError::LookBehindNotConst => {
127                write!(f, "Look-behind assertion without constant size")
128            },
129            CompileError::InvalidGroupName => write!(f, "Could not parse group name"),
130            CompileError::InvalidGroupNameBackref(s) => write!(f, "Invalid group name in back reference: {}", s),
131            CompileError::InvalidBackref => write!(f, "Invalid back reference"),
132            CompileError::NamedBackrefOnly => write!(f, "Numbered backref/call not allowed because named group was used, use a named backref instead"),
133        }
134    }
135}
136
137impl fmt::Display for RuntimeError {
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        match self {
140            RuntimeError::StackOverflow => write!(f, "Max stack size exceeded for backtracking"),
141            RuntimeError::BacktrackLimitExceeded => {
142                write!(f, "Max limit for backtracking count exceeded")
143            }
144        }
145    }
146}
147
148impl fmt::Display for Error {
149    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150        match self {
151            Error::ParseError(position, parse_error) => {
152                write!(f, "Parsing error at position {}: {}", position, parse_error)
153            }
154            Error::CompileError(compile_error) => {
155                write!(f, "Error compiling regex: {}", compile_error)
156            }
157            Error::RuntimeError(runtime_error) => {
158                write!(f, "Error executing regex: {}", runtime_error)
159            }
160        }
161    }
162}
163
164impl From<CompileError> for Error {
165    fn from(compile_error: CompileError) -> Self {
166        Error::CompileError(compile_error)
167    }
168}