1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! Error types for the regex engine.
use std::fmt;
/// A specialized Result type for regex operations.
pub type Result<T> = std::result::Result<T, Error>;
/// An error that occurred during regex parsing or compilation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
pattern: String,
span: Option<Span>,
}
/// The position in the pattern where an error occurred.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
/// Start byte offset (inclusive).
pub start: usize,
/// End byte offset (exclusive).
pub end: usize,
}
impl Span {
/// Creates a new span.
pub fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
/// Creates a span for a single position.
pub fn point(pos: usize) -> Self {
Self {
start: pos,
end: pos + 1,
}
}
}
/// The kind of error that occurred.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
// Parse errors
/// Unexpected end of pattern.
UnexpectedEof,
/// Unexpected character in pattern.
UnexpectedChar(char),
/// Unmatched opening parenthesis.
UnmatchedOpenParen,
/// Unmatched closing parenthesis.
UnmatchedCloseParen,
/// Unmatched opening bracket.
UnmatchedOpenBracket,
/// Unmatched closing bracket.
UnmatchedCloseBracket,
/// Invalid escape sequence.
InvalidEscape(char),
/// An escape that is valid in a pattern but meaningless inside a character
/// class, such as the anchor `\b`. Carries the escape as written.
EscapeNotAllowedInClass(String),
/// Invalid hex escape.
InvalidHexEscape,
/// Invalid unicode escape.
InvalidUnicodeEscape,
/// Invalid control escape (e.g. `\c` at end of pattern, or `\c1`).
InvalidControlEscape,
/// `\N{NAME}` (named Unicode character escape) is not supported — it
/// needs the full Unicode character-name database, which is out of
/// scope. Bare `\N` (any code point except line feed) is unaffected.
NamedUnicodeCharacterNotSupported,
/// Invalid Unicode property (e.g., \p{InvalidName}).
InvalidUnicodeProperty,
/// Unknown Unicode property name.
UnknownUnicodeProperty(String),
/// Malformed POSIX bracket-expression class syntax (e.g. `[[:alpha]`,
/// `[[::]]`, or a non-alphabetic character in the name).
InvalidPosixClass,
/// Well-formed but unrecognized POSIX class name (e.g. `[[:bogus:]]`).
UnknownPosixClass(String),
/// Invalid repetition syntax.
InvalidRepetition,
/// The pattern expands to more elements than the engines will build.
ExpansionTooLarge {
/// Elements the pattern expands to.
size: u32,
/// The largest expansion accepted.
limit: u32,
},
/// A repetition bound past what the engines will expand.
RepetitionTooLarge {
/// The bound the pattern asked for.
bound: u32,
/// The largest bound accepted.
limit: u32,
},
/// Repetition quantifier on nothing.
RepetitionOnNothing,
/// Invalid character class range (e.g., z-a).
InvalidClassRange {
/// Start of the invalid range.
start: char,
/// End of the invalid range.
end: char,
},
/// Empty character class.
EmptyClass,
/// Malformed character-class set operation (`&&`, `--`, `~~`): the
/// operator is missing its left operand (e.g. `[&&a-z]`), missing its
/// right operand (e.g. `[a-z&&]`), or the class ends (`]` or end of
/// pattern) immediately after the operator.
InvalidClassSetOp,
/// Invalid group syntax.
InvalidGroup,
/// Invalid backreference.
InvalidBackref(usize),
/// Backreference to non-existent group.
BackrefNotFound(usize),
/// Malformed named-backreference syntax: `\k` at end of pattern, `\k`
/// followed by a delimiter other than `<`, `{`, or `'`, an empty name
/// (`\k<>`), or an unterminated form (`\k<name`).
InvalidNamedBackref,
/// A named backreference (`\k<name>`, `\k{name}`, `\k'name'`, or
/// `(?P=name)`) refers to a name that was never defined as a capture
/// group.
UnknownGroupName(String),
/// Nested quantifiers (e.g., a**).
NestedQuantifier,
/// Possessive quantifier (e.g., `a*+`, `a++`, `a?+`, `a{n,m}+`). Not
/// supported: regexr's engines are linear-time and never backtrack
/// catastrophically, so possessive quantifiers — which exist to bound
/// backtracking — have nothing to bound here.
PossessiveQuantifier,
/// Atomic group (`(?>...)`). Not supported for the same reason as
/// possessive quantifiers: regexr does not backtrack.
AtomicGroup,
// Compile errors
/// Pattern too large.
PatternTooLarge,
/// Too many capture groups.
TooManyCaptureGroups,
/// Too many states in NFA.
TooManyStates,
// Runtime errors
/// Match limit exceeded (to prevent ReDoS).
MatchLimitExceeded,
/// Stack overflow during matching.
StackOverflow,
// JIT errors
/// JIT compilation failed.
Jit(String),
}
impl Error {
/// Creates a new error.
pub fn new(kind: ErrorKind, pattern: impl Into<String>) -> Self {
Self {
kind,
pattern: pattern.into(),
span: None,
}
}
/// Creates a new error with a span.
pub fn with_span(kind: ErrorKind, pattern: impl Into<String>, span: Span) -> Self {
Self {
kind,
pattern: pattern.into(),
span: Some(span),
}
}
/// Returns the error kind.
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
/// Returns the pattern that caused the error.
pub fn pattern(&self) -> &str {
&self.pattern
}
/// Returns the span where the error occurred, if available.
pub fn span(&self) -> Option<Span> {
self.span
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "regex error: {}", self.kind)?;
if let Some(span) = self.span {
write!(f, " at position {}", span.start)?;
// Show context
if !self.pattern.is_empty() {
write!(f, "\n pattern: {}", self.pattern)?;
write!(f, "\n ")?;
for _ in 0..span.start {
write!(f, " ")?;
}
let len = (span.end - span.start).max(1);
for _ in 0..len {
write!(f, "^")?;
}
}
}
Ok(())
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorKind::UnexpectedEof => write!(f, "unexpected end of pattern"),
ErrorKind::UnexpectedChar(c) => write!(f, "unexpected character '{}'", c),
ErrorKind::UnmatchedOpenParen => write!(f, "unmatched '('"),
ErrorKind::UnmatchedCloseParen => write!(f, "unmatched ')'"),
ErrorKind::UnmatchedOpenBracket => write!(f, "unmatched '['"),
ErrorKind::UnmatchedCloseBracket => write!(f, "unmatched ']'"),
ErrorKind::InvalidEscape(c) => write!(f, "invalid escape sequence '\\{}'", c),
ErrorKind::EscapeNotAllowedInClass(esc) => {
write!(f, "escape '{}' is not allowed in a character class", esc)
}
ErrorKind::InvalidHexEscape => write!(f, "invalid hex escape sequence"),
ErrorKind::InvalidUnicodeEscape => write!(f, "invalid unicode escape sequence"),
ErrorKind::InvalidControlEscape => write!(f, "invalid control escape sequence"),
ErrorKind::NamedUnicodeCharacterNotSupported => write!(
f,
"\\N{{NAME}} named Unicode character escapes are not supported"
),
ErrorKind::InvalidUnicodeProperty => write!(f, "invalid unicode property syntax"),
ErrorKind::UnknownUnicodeProperty(name) => {
write!(f, "unknown unicode property '{}'", name)
}
ErrorKind::InvalidPosixClass => write!(f, "invalid POSIX class syntax"),
ErrorKind::UnknownPosixClass(name) => {
write!(f, "unknown POSIX class '[:{}:]'", name)
}
ErrorKind::InvalidRepetition => write!(f, "invalid repetition syntax"),
ErrorKind::ExpansionTooLarge { size, limit } => write!(
f,
"pattern expands to {size} elements, exceeding the limit of {limit}"
),
ErrorKind::RepetitionTooLarge { bound, limit } => write!(
f,
"repetition count {bound} exceeds the limit of {limit}"
),
ErrorKind::RepetitionOnNothing => write!(f, "quantifier on nothing"),
ErrorKind::InvalidClassRange { start, end } => {
write!(f, "invalid character class range '{}-{}'", start, end)
}
ErrorKind::EmptyClass => write!(f, "empty character class"),
ErrorKind::InvalidClassSetOp => {
write!(
f,
"invalid character class set operation: '&&', '--', and '~~' require both a left and a right operand"
)
}
ErrorKind::InvalidGroup => write!(f, "invalid group syntax"),
ErrorKind::InvalidBackref(n) => write!(f, "invalid backreference '\\{}'", n),
ErrorKind::BackrefNotFound(n) => {
write!(f, "backreference '\\{}' references non-existent group", n)
}
ErrorKind::InvalidNamedBackref => write!(f, "invalid named backreference syntax"),
ErrorKind::UnknownGroupName(name) => {
write!(f, "backreference to unknown group name '{}'", name)
}
ErrorKind::NestedQuantifier => write!(f, "nested quantifiers are not allowed"),
ErrorKind::PossessiveQuantifier => write!(
f,
"possessive quantifiers are not supported; regexr does not backtrack, so plain greedy is usually equivalent"
),
ErrorKind::AtomicGroup => write!(
f,
"atomic groups `(?>…)` are not supported; regexr does not backtrack, so they are usually unnecessary"
),
ErrorKind::PatternTooLarge => write!(f, "pattern too large"),
ErrorKind::TooManyCaptureGroups => write!(f, "too many capture groups"),
ErrorKind::TooManyStates => write!(f, "too many NFA states"),
ErrorKind::MatchLimitExceeded => write!(f, "match limit exceeded"),
ErrorKind::StackOverflow => write!(f, "stack overflow during matching"),
ErrorKind::Jit(msg) => write!(f, "JIT compilation failed: {}", msg),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_display() {
let err = Error::with_span(ErrorKind::UnexpectedChar('?'), "a?*b", Span::new(2, 3));
let msg = err.to_string();
assert!(msg.contains("unexpected character"));
assert!(msg.contains("position 2"));
}
#[test]
fn test_error_kind_display() {
assert_eq!(
ErrorKind::InvalidClassRange {
start: 'z',
end: 'a'
}
.to_string(),
"invalid character class range 'z-a'"
);
}
}