fancy_regex/
error.rs

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