Debian Codegraph @

third_party/rust/regex-syntax/src/ast/mod.rs

raw
1 /*!
2 Defines an abstract syntax for regular expressions.
3 */
4
5 use core::cmp::Ordering;
6
7 use alloc::{boxed::Box, string::String, vec, vec::Vec};
8
9 pub use crate::ast::visitor::{visit, Visitor};
10
11 pub mod parse;
12 pub mod print;
13 mod visitor;
14
15 /// An error that occurred while parsing a regular expression into an abstract
16 /// syntax tree.
17 ///
18 /// Note that not all ASTs represents a valid regular expression. For example,
19 /// an AST is constructed without error for `\p{Quux}`, but `Quux` is not a
20 /// valid Unicode property name. That particular error is reported when
21 /// translating an AST to the high-level intermediate representation (`HIR`).
22 #[derive(Clone, Debug, Eq, PartialEq)]
23 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
24 pub struct Error {
25 /// The kind of error.
26 kind: ErrorKind,
27 /// The original pattern that the parser generated the error from. Every
28 /// span in an error is a valid range into this string.
29 pattern: String,
30 /// The span of this error.
31 span: Span,
32 }
33
34 impl Error {
35 /// Return the type of this error.
36 pub fn kind(&self) -> &ErrorKind {
37 &self.kind
38 }
39
40 /// The original pattern string in which this error occurred.
41 ///
42 /// Every span reported by this error is reported in terms of this string.
43 pub fn pattern(&self) -> &str {
44 &self.pattern
45 }
46
47 /// Return the span at which this error occurred.
48 pub fn span(&self) -> &Span {
49 &self.span
50 }
51
52 /// Return an auxiliary span. This span exists only for some errors that
53 /// benefit from being able to point to two locations in the original
54 /// regular expression. For example, "duplicate" errors will have the
55 /// main error position set to the duplicate occurrence while its
56 /// auxiliary span will be set to the initial occurrence.
57 pub fn auxiliary_span(&self) -> Option<&Span> {
58 use self::ErrorKind::*;
59 match self.kind {
60 FlagDuplicate { ref original } => Some(original),
61 FlagRepeatedNegation { ref original, .. } => Some(original),
62 GroupNameDuplicate { ref original, .. } => Some(original),
63 _ => None,
64 }
65 }
66 }
67
68 /// The type of an error that occurred while building an AST.
69 ///
70 /// This error type is marked as `non_exhaustive`. This means that adding a
71 /// new variant is not considered a breaking change.
72 #[non_exhaustive]
73 #[derive(Clone, Debug, Eq, PartialEq)]
74 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
75 pub enum ErrorKind {
76 /// The capturing group limit was exceeded.
77 ///
78 /// Note that this represents a limit on the total number of capturing
79 /// groups in a regex and not necessarily the number of nested capturing
80 /// groups. That is, the nest limit can be low and it is still possible for
81 /// this error to occur.
82 CaptureLimitExceeded,
83 /// An invalid escape sequence was found in a character class set.
84 ClassEscapeInvalid,
85 /// An invalid character class range was found. An invalid range is any
86 /// range where the start is greater than the end.
87 ClassRangeInvalid,
88 /// An invalid range boundary was found in a character class. Range
89 /// boundaries must be a single literal codepoint, but this error indicates
90 /// that something else was found, such as a nested class.
91 ClassRangeLiteral,
92 /// An opening `[` was found with no corresponding closing `]`.
93 ClassUnclosed,
94 /// Note that this error variant is no longer used. Namely, a decimal
95 /// number can only appear as a repetition quantifier. When the number
96 /// in a repetition quantifier is empty, then it gets its own specialized
97 /// error, `RepetitionCountDecimalEmpty`.
98 DecimalEmpty,
99 /// An invalid decimal number was given where one was expected.
100 DecimalInvalid,
101 /// A bracketed hex literal was empty.
102 EscapeHexEmpty,
103 /// A bracketed hex literal did not correspond to a Unicode scalar value.
104 EscapeHexInvalid,
105 /// An invalid hexadecimal digit was found.
106 EscapeHexInvalidDigit,
107 /// EOF was found before an escape sequence was completed.
108 EscapeUnexpectedEof,
109 /// An unrecognized escape sequence.
110 EscapeUnrecognized,
111 /// A dangling negation was used when setting flags, e.g., `i-`.
112 FlagDanglingNegation,
113 /// A flag was used twice, e.g., `i-i`.
114 FlagDuplicate {
115 /// The position of the original flag. The error position
116 /// points to the duplicate flag.
117 original: Span,
118 },
119 /// The negation operator was used twice, e.g., `-i-s`.
120 FlagRepeatedNegation {
121 /// The position of the original negation operator. The error position
122 /// points to the duplicate negation operator.
123 original: Span,
124 },
125 /// Expected a flag but got EOF, e.g., `(?`.
126 FlagUnexpectedEof,
127 /// Unrecognized flag, e.g., `a`.
128 FlagUnrecognized,
129 /// A duplicate capture name was found.
130 GroupNameDuplicate {
131 /// The position of the initial occurrence of the capture name. The
132 /// error position itself points to the duplicate occurrence.
133 original: Span,
134 },
135 /// A capture group name is empty, e.g., `(?P<>abc)`.
136 GroupNameEmpty,
137 /// An invalid character was seen for a capture group name. This includes
138 /// errors where the first character is a digit (even though subsequent
139 /// characters are allowed to be digits).
140 GroupNameInvalid,
141 /// A closing `>` could not be found for a capture group name.
142 GroupNameUnexpectedEof,
143 /// An unclosed group, e.g., `(ab`.
144 ///
145 /// The span of this error corresponds to the unclosed parenthesis.
146 GroupUnclosed,
147 /// An unopened group, e.g., `ab)`.
148 GroupUnopened,
149 /// The nest limit was exceeded. The limit stored here is the limit
150 /// configured in the parser.
151 NestLimitExceeded(u32),
152 /// The range provided in a counted repetition operator is invalid. The
153 /// range is invalid if the start is greater than the end.
154 RepetitionCountInvalid,
155 /// An opening `{` was not followed by a valid decimal value.
156 /// For example, `x{}` or `x{]}` would fail.
157 RepetitionCountDecimalEmpty,
158 /// An opening `{` was found with no corresponding closing `}`.
159 RepetitionCountUnclosed,
160 /// A repetition operator was applied to a missing sub-expression. This
161 /// occurs, for example, in the regex consisting of just a `*` or even
162 /// `(?i)*`. It is, however, possible to create a repetition operating on
163 /// an empty sub-expression. For example, `()*` is still considered valid.
164 RepetitionMissing,
165 /// The Unicode class is not valid. This typically occurs when a `\p` is
166 /// followed by something other than a `{`.
167 UnicodeClassInvalid,
168 /// When octal support is disabled, this error is produced when an octal
169 /// escape is used. The octal escape is assumed to be an invocation of
170 /// a backreference, which is the common case.
171 UnsupportedBackreference,
172 /// When syntax similar to PCRE's look-around is used, this error is
173 /// returned. Some example syntaxes that are rejected include, but are
174 /// not necessarily limited to, `(?=re)`, `(?!re)`, `(?<=re)` and
175 /// `(?<!re)`. Note that all of these syntaxes are otherwise invalid; this
176 /// error is used to improve the user experience.
177 UnsupportedLookAround,
178 }
179
180 #[cfg(feature = "std")]
181 impl std::error::Error for Error {}
182
183 impl core::fmt::Display for Error {
184 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
185 crate::error::Formatter::from(self).fmt(f)
186 }
187 }
188
189 impl core::fmt::Display for ErrorKind {
190 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
191 use self::ErrorKind::*;
192 match *self {
193 CaptureLimitExceeded => write!(
194 f,
195 "exceeded the maximum number of \
196 capturing groups ({})",
197 u32::MAX
198 ),
199 ClassEscapeInvalid => {
200 write!(f, "invalid escape sequence found in character class")
201 }
202 ClassRangeInvalid => write!(
203 f,
204 "invalid character class range, \
205 the start must be <= the end"
206 ),
207 ClassRangeLiteral => {
208 write!(f, "invalid range boundary, must be a literal")
209 }
210 ClassUnclosed => write!(f, "unclosed character class"),
211 DecimalEmpty => write!(f, "decimal literal empty"),
212 DecimalInvalid => write!(f, "decimal literal invalid"),
213 EscapeHexEmpty => write!(f, "hexadecimal literal empty"),
214 EscapeHexInvalid => {
215 write!(f, "hexadecimal literal is not a Unicode scalar value")
216 }
217 EscapeHexInvalidDigit => write!(f, "invalid hexadecimal digit"),
218 EscapeUnexpectedEof => write!(
219 f,
220 "incomplete escape sequence, \
221 reached end of pattern prematurely"
222 ),
223 EscapeUnrecognized => write!(f, "unrecognized escape sequence"),
224 FlagDanglingNegation => {
225 write!(f, "dangling flag negation operator")
226 }
227 FlagDuplicate { .. } => write!(f, "duplicate flag"),
228 FlagRepeatedNegation { .. } => {
229 write!(f, "flag negation operator repeated")
230 }
231 FlagUnexpectedEof => {
232 write!(f, "expected flag but got end of regex")
233 }
234 FlagUnrecognized => write!(f, "unrecognized flag"),
235 GroupNameDuplicate { .. } => {
236 write!(f, "duplicate capture group name")
237 }
238 GroupNameEmpty => write!(f, "empty capture group name"),
239 GroupNameInvalid => write!(f, "invalid capture group character"),
240 GroupNameUnexpectedEof => write!(f, "unclosed capture group name"),
241 GroupUnclosed => write!(f, "unclosed group"),
242 GroupUnopened => write!(f, "unopened group"),
243 NestLimitExceeded(limit) => write!(
244 f,
245 "exceed the maximum number of \
246 nested parentheses/brackets ({})",
247 limit
248 ),
249 RepetitionCountInvalid => write!(
250 f,
251 "invalid repetition count range, \
252 the start must be <= the end"
253 ),
254 RepetitionCountDecimalEmpty => {
255 write!(f, "repetition quantifier expects a valid decimal")
256 }
257 RepetitionCountUnclosed => {
258 write!(f, "unclosed counted repetition")
259 }
260 RepetitionMissing => {
261 write!(f, "repetition operator missing expression")
262 }
263 UnicodeClassInvalid => {
264 write!(f, "invalid Unicode character class")
265 }
266 UnsupportedBackreference => {
267 write!(f, "backreferences are not supported")
268 }
269 UnsupportedLookAround => write!(
270 f,
271 "look-around, including look-ahead and look-behind, \
272 is not supported"
273 ),
274 }
275 }
276 }
277
278 /// Span represents the position information of a single AST item.
279 ///
280 /// All span positions are absolute byte offsets that can be used on the
281 /// original regular expression that was parsed.
282 #[derive(Clone, Copy, Eq, PartialEq)]
283 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
284 pub struct Span {
285 /// The start byte offset.
286 pub start: Position,
287 /// The end byte offset.
288 pub end: Position,
289 }
290
291 impl core::fmt::Debug for Span {
292 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
293 write!(f, "Span({:?}, {:?})", self.start, self.end)
294 }
295 }
296
297 impl Ord for Span {
298 fn cmp(&self, other: &Span) -> Ordering {
299 (&self.start, &self.end).cmp(&(&other.start, &other.end))
300 }
301 }
302
303 impl PartialOrd for Span {
304 fn partial_cmp(&self, other: &Span) -> Option<Ordering> {
305 Some(self.cmp(other))
306 }
307 }
308
309 /// A single position in a regular expression.
310 ///
311 /// A position encodes one half of a span, and include the byte offset, line
312 /// number and column number.
313 #[derive(Clone, Copy, Eq, PartialEq)]
314 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
315 pub struct Position {
316 /// The absolute offset of this position, starting at `0` from the
317 /// beginning of the regular expression pattern string.
318 pub offset: usize,
319 /// The line number, starting at `1`.
320 pub line: usize,
321 /// The approximate column number, starting at `1`.
322 pub column: usize,
323 }
324
325 impl core::fmt::Debug for Position {
326 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
327 write!(
328 f,
329 "Position(o: {:?}, l: {:?}, c: {:?})",
330 self.offset, self.line, self.column
331 )
332 }
333 }
334
335 impl Ord for Position {
336 fn cmp(&self, other: &Position) -> Ordering {
337 self.offset.cmp(&other.offset)
338 }
339 }
340
341 impl PartialOrd for Position {
342 fn partial_cmp(&self, other: &Position) -> Option<Ordering> {
343 Some(self.cmp(other))
344 }
345 }
346
347 impl Span {
348 /// Create a new span with the given positions.
349 pub fn new(start: Position, end: Position) -> Span {
350 Span { start, end }
351 }
352
353 /// Create a new span using the given position as the start and end.
354 pub fn splat(pos: Position) -> Span {
355 Span::new(pos, pos)
356 }
357
358 /// Create a new span by replacing the starting the position with the one
359 /// given.
360 pub fn with_start(self, pos: Position) -> Span {
361 Span { start: pos, ..self }
362 }
363
364 /// Create a new span by replacing the ending the position with the one
365 /// given.
366 pub fn with_end(self, pos: Position) -> Span {
367 Span { end: pos, ..self }
368 }
369
370 /// Returns true if and only if this span occurs on a single line.
371 pub fn is_one_line(&self) -> bool {
372 self.start.line == self.end.line
373 }
374
375 /// Returns true if and only if this span is empty. That is, it points to
376 /// a single position in the concrete syntax of a regular expression.
377 pub fn is_empty(&self) -> bool {
378 self.start.offset == self.end.offset
379 }
380 }
381
382 impl Position {
383 /// Create a new position with the given information.
384 ///
385 /// `offset` is the absolute offset of the position, starting at `0` from
386 /// the beginning of the regular expression pattern string.
387 ///
388 /// `line` is the line number, starting at `1`.
389 ///
390 /// `column` is the approximate column number, starting at `1`.
391 pub fn new(offset: usize, line: usize, column: usize) -> Position {
392 Position { offset, line, column }
393 }
394 }
395
396 /// An abstract syntax tree for a singular expression along with comments
397 /// found.
398 ///
399 /// Comments are not stored in the tree itself to avoid complexity. Each
400 /// comment contains a span of precisely where it occurred in the original
401 /// regular expression.
402 #[derive(Clone, Debug, Eq, PartialEq)]
403 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
404 pub struct WithComments {
405 /// The actual ast.
406 pub ast: Ast,
407 /// All comments found in the original regular expression.
408 pub comments: Vec<Comment>,
409 }
410
411 /// A comment from a regular expression with an associated span.
412 ///
413 /// A regular expression can only contain comments when the `x` flag is
414 /// enabled.
415 #[derive(Clone, Debug, Eq, PartialEq)]
416 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
417 pub struct Comment {
418 /// The span of this comment, including the beginning `#` and ending `\n`.
419 pub span: Span,
420 /// The comment text, starting with the first character following the `#`
421 /// and ending with the last character preceding the `\n`.
422 pub comment: String,
423 }
424
425 /// An abstract syntax tree for a single regular expression.
426 ///
427 /// An `Ast`'s `fmt::Display` implementation uses constant stack space and heap
428 /// space proportional to the size of the `Ast`.
429 ///
430 /// This type defines its own destructor that uses constant stack space and
431 /// heap space proportional to the size of the `Ast`.
432 #[derive(Clone, Debug, Eq, PartialEq)]
433 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
434 pub enum Ast {
435 /// An empty regex that matches everything.
436 Empty(Span),
437 /// A set of flags, e.g., `(?is)`.
438 Flags(SetFlags),
439 /// A single character literal, which includes escape sequences.
440 Literal(Literal),
441 /// The "any character" class.
442 Dot(Span),
443 /// A single zero-width assertion.
444 Assertion(Assertion),
445 /// A single character class. This includes all forms of character classes
446 /// except for `.`. e.g., `\d`, `\pN`, `[a-z]` and `[[:alpha:]]`.
447 Class(Class),
448 /// A repetition operator applied to an arbitrary regular expression.
449 Repetition(Repetition),
450 /// A grouped regular expression.
451 Group(Group),
452 /// An alternation of regular expressions.
453 Alternation(Alternation),
454 /// A concatenation of regular expressions.
455 Concat(Concat),
456 }
457
458 impl Ast {
459 /// Return the span of this abstract syntax tree.
460 pub fn span(&self) -> &Span {
461 match *self {
462 Ast::Empty(ref span) => span,
463 Ast::Flags(ref x) => &x.span,
464 Ast::Literal(ref x) => &x.span,
465 Ast::Dot(ref span) => span,
466 Ast::Assertion(ref x) => &x.span,
467 Ast::Class(ref x) => x.span(),
468 Ast::Repetition(ref x) => &x.span,
469 Ast::Group(ref x) => &x.span,
470 Ast::Alternation(ref x) => &x.span,
471 Ast::Concat(ref x) => &x.span,
472 }
473 }
474
475 /// Return true if and only if this Ast is empty.
476 pub fn is_empty(&self) -> bool {
477 match *self {
478 Ast::Empty(_) => true,
479 _ => false,
480 }
481 }
482
483 /// Returns true if and only if this AST has any (including possibly empty)
484 /// subexpressions.
485 fn has_subexprs(&self) -> bool {
486 match *self {
487 Ast::Empty(_)
488 | Ast::Flags(_)
489 | Ast::Literal(_)
490 | Ast::Dot(_)
491 | Ast::Assertion(_) => false,
492 Ast::Class(_)
493 | Ast::Repetition(_)
494 | Ast::Group(_)
495 | Ast::Alternation(_)
496 | Ast::Concat(_) => true,
497 }
498 }
499 }
500
501 /// Print a display representation of this Ast.
502 ///
503 /// This does not preserve any of the original whitespace formatting that may
504 /// have originally been present in the concrete syntax from which this Ast
505 /// was generated.
506 ///
507 /// This implementation uses constant stack space and heap space proportional
508 /// to the size of the `Ast`.
509 impl core::fmt::Display for Ast {
510 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
511 use crate::ast::print::Printer;
512 Printer::new().print(self, f)
513 }
514 }
515
516 /// An alternation of regular expressions.
517 #[derive(Clone, Debug, Eq, PartialEq)]
518 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
519 pub struct Alternation {
520 /// The span of this alternation.
521 pub span: Span,
522 /// The alternate regular expressions.
523 pub asts: Vec<Ast>,
524 }
525
526 impl Alternation {
527 /// Return this alternation as an AST.
528 ///
529 /// If this alternation contains zero ASTs, then Ast::Empty is
530 /// returned. If this alternation contains exactly 1 AST, then the
531 /// corresponding AST is returned. Otherwise, Ast::Alternation is returned.
532 pub fn into_ast(mut self) -> Ast {
533 match self.asts.len() {
534 0 => Ast::Empty(self.span),
535 1 => self.asts.pop().unwrap(),
536 _ => Ast::Alternation(self),
537 }
538 }
539 }
540
541 /// A concatenation of regular expressions.
542 #[derive(Clone, Debug, Eq, PartialEq)]
543 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
544 pub struct Concat {
545 /// The span of this concatenation.
546 pub span: Span,
547 /// The concatenation regular expressions.
548 pub asts: Vec<Ast>,
549 }
550
551 impl Concat {
552 /// Return this concatenation as an AST.
553 ///
554 /// If this concatenation contains zero ASTs, then Ast::Empty is
555 /// returned. If this concatenation contains exactly 1 AST, then the
556 /// corresponding AST is returned. Otherwise, Ast::Concat is returned.
557 pub fn into_ast(mut self) -> Ast {
558 match self.asts.len() {
559 0 => Ast::Empty(self.span),
560 1 => self.asts.pop().unwrap(),
561 _ => Ast::Concat(self),
562 }
563 }
564 }
565
566 /// A single literal expression.
567 ///
568 /// A literal corresponds to a single Unicode scalar value. Literals may be
569 /// represented in their literal form, e.g., `a` or in their escaped form,
570 /// e.g., `\x61`.
571 #[derive(Clone, Debug, Eq, PartialEq)]
572 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
573 pub struct Literal {
574 /// The span of this literal.
575 pub span: Span,
576 /// The kind of this literal.
577 pub kind: LiteralKind,
578 /// The Unicode scalar value corresponding to this literal.
579 pub c: char,
580 }
581
582 impl Literal {
583 /// If this literal was written as a `\x` hex escape, then this returns
584 /// the corresponding byte value. Otherwise, this returns `None`.
585 pub fn byte(&self) -> Option<u8> {
586 match self.kind {
587 LiteralKind::HexFixed(HexLiteralKind::X) => {
588 u8::try_from(self.c).ok()
589 }
590 _ => None,
591 }
592 }
593 }
594
595 /// The kind of a single literal expression.
596 #[derive(Clone, Debug, Eq, PartialEq)]
597 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
598 pub enum LiteralKind {
599 /// The literal is written verbatim, e.g., `a` or `☃`.
600 Verbatim,
601 /// The literal is written as an escape because it is otherwise a special
602 /// regex meta character, e.g., `\*` or `\[`.
603 Meta,
604 /// The literal is written as an escape despite the fact that the escape is
605 /// unnecessary, e.g., `\%` or `\/`.
606 Superfluous,
607 /// The literal is written as an octal escape, e.g., `\141`.
608 Octal,
609 /// The literal is written as a hex code with a fixed number of digits
610 /// depending on the type of the escape, e.g., `\x61` or or `\u0061` or
611 /// `\U00000061`.
612 HexFixed(HexLiteralKind),
613 /// The literal is written as a hex code with a bracketed number of
614 /// digits. The only restriction is that the bracketed hex code must refer
615 /// to a valid Unicode scalar value.
616 HexBrace(HexLiteralKind),
617 /// The literal is written as a specially recognized escape, e.g., `\f`
618 /// or `\n`.
619 Special(SpecialLiteralKind),
620 }
621
622 /// The type of a special literal.
623 ///
624 /// A special literal is a special escape sequence recognized by the regex
625 /// parser, e.g., `\f` or `\n`.
626 #[derive(Clone, Debug, Eq, PartialEq)]
627 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
628 pub enum SpecialLiteralKind {
629 /// Bell, spelled `\a` (`\x07`).
630 Bell,
631 /// Form feed, spelled `\f` (`\x0C`).
632 FormFeed,
633 /// Tab, spelled `\t` (`\x09`).
634 Tab,
635 /// Line feed, spelled `\n` (`\x0A`).
636 LineFeed,
637 /// Carriage return, spelled `\r` (`\x0D`).
638 CarriageReturn,
639 /// Vertical tab, spelled `\v` (`\x0B`).
640 VerticalTab,
641 /// Space, spelled `\ ` (`\x20`). Note that this can only appear when
642 /// parsing in verbose mode.
643 Space,
644 }
645
646 /// The type of a Unicode hex literal.
647 ///
648 /// Note that all variants behave the same when used with brackets. They only
649 /// differ when used without brackets in the number of hex digits that must
650 /// follow.
651 #[derive(Clone, Debug, Eq, PartialEq)]
652 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
653 pub enum HexLiteralKind {
654 /// A `\x` prefix. When used without brackets, this form is limited to
655 /// two digits.
656 X,
657 /// A `\u` prefix. When used without brackets, this form is limited to
658 /// four digits.
659 UnicodeShort,
660 /// A `\U` prefix. When used without brackets, this form is limited to
661 /// eight digits.
662 UnicodeLong,
663 }
664
665 impl HexLiteralKind {
666 /// The number of digits that must be used with this literal form when
667 /// used without brackets. When used with brackets, there is no
668 /// restriction on the number of digits.
669 pub fn digits(&self) -> u32 {
670 match *self {
671 HexLiteralKind::X => 2,
672 HexLiteralKind::UnicodeShort => 4,
673 HexLiteralKind::UnicodeLong => 8,
674 }
675 }
676 }
677
678 /// A single character class expression.
679 #[derive(Clone, Debug, Eq, PartialEq)]
680 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
681 pub enum Class {
682 /// A Unicode character class, e.g., `\pL` or `\p{Greek}`.
683 Unicode(ClassUnicode),
684 /// A perl character class, e.g., `\d` or `\W`.
685 Perl(ClassPerl),
686 /// A bracketed character class set, which may contain zero or more
687 /// character ranges and/or zero or more nested classes. e.g.,
688 /// `[a-zA-Z\pL]`.
689 Bracketed(ClassBracketed),
690 }
691
692 impl Class {
693 /// Return the span of this character class.
694 pub fn span(&self) -> &Span {
695 match *self {
696 Class::Perl(ref x) => &x.span,
697 Class::Unicode(ref x) => &x.span,
698 Class::Bracketed(ref x) => &x.span,
699 }
700 }
701 }
702
703 /// A Perl character class.
704 #[derive(Clone, Debug, Eq, PartialEq)]
705 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
706 pub struct ClassPerl {
707 /// The span of this class.
708 pub span: Span,
709 /// The kind of Perl class.
710 pub kind: ClassPerlKind,
711 /// Whether the class is negated or not. e.g., `\d` is not negated but
712 /// `\D` is.
713 pub negated: bool,
714 }
715
716 /// The available Perl character classes.
717 #[derive(Clone, Debug, Eq, PartialEq)]
718 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
719 pub enum ClassPerlKind {
720 /// Decimal numbers.
721 Digit,
722 /// Whitespace.
723 Space,
724 /// Word characters.
725 Word,
726 }
727
728 /// An ASCII character class.
729 #[derive(Clone, Debug, Eq, PartialEq)]
730 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
731 pub struct ClassAscii {
732 /// The span of this class.
733 pub span: Span,
734 /// The kind of ASCII class.
735 pub kind: ClassAsciiKind,
736 /// Whether the class is negated or not. e.g., `[[:alpha:]]` is not negated
737 /// but `[[:^alpha:]]` is.
738 pub negated: bool,
739 }
740
741 /// The available ASCII character classes.
742 #[derive(Clone, Debug, Eq, PartialEq)]
743 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
744 pub enum ClassAsciiKind {
745 /// `[0-9A-Za-z]`
746 Alnum,
747 /// `[A-Za-z]`
748 Alpha,
749 /// `[\x00-\x7F]`
750 Ascii,
751 /// `[ \t]`
752 Blank,
753 /// `[\x00-\x1F\x7F]`
754 Cntrl,
755 /// `[0-9]`
756 Digit,
757 /// `[!-~]`
758 Graph,
759 /// `[a-z]`
760 Lower,
761 /// `[ -~]`
762 Print,
763 /// `[!-/:-@\[-`{-~]`
764 Punct,
765 /// `[\t\n\v\f\r ]`
766 Space,
767 /// `[A-Z]`
768 Upper,
769 /// `[0-9A-Za-z_]`
770 Word,
771 /// `[0-9A-Fa-f]`
772 Xdigit,
773 }
774
775 impl ClassAsciiKind {
776 /// Return the corresponding ClassAsciiKind variant for the given name.
777 ///
778 /// The name given should correspond to the lowercase version of the
779 /// variant name. e.g., `cntrl` is the name for `ClassAsciiKind::Cntrl`.
780 ///
781 /// If no variant with the corresponding name exists, then `None` is
782 /// returned.
783 pub fn from_name(name: &str) -> Option<ClassAsciiKind> {
784 use self::ClassAsciiKind::*;
785 match name {
786 "alnum" => Some(Alnum),
787 "alpha" => Some(Alpha),
788 "ascii" => Some(Ascii),
789 "blank" => Some(Blank),
790 "cntrl" => Some(Cntrl),
791 "digit" => Some(Digit),
792 "graph" => Some(Graph),
793 "lower" => Some(Lower),
794 "print" => Some(Print),
795 "punct" => Some(Punct),
796 "space" => Some(Space),
797 "upper" => Some(Upper),
798 "word" => Some(Word),
799 "xdigit" => Some(Xdigit),
800 _ => None,
801 }
802 }
803 }
804
805 /// A Unicode character class.
806 #[derive(Clone, Debug, Eq, PartialEq)]
807 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
808 pub struct ClassUnicode {
809 /// The span of this class.
810 pub span: Span,
811 /// Whether this class is negated or not.
812 ///
813 /// Note: be careful when using this attribute. This specifically refers
814 /// to whether the class is written as `\p` or `\P`, where the latter
815 /// is `negated = true`. However, it also possible to write something like
816 /// `\P{scx!=Katakana}` which is actually equivalent to
817 /// `\p{scx=Katakana}` and is therefore not actually negated even though
818 /// `negated = true` here. To test whether this class is truly negated
819 /// or not, use the `is_negated` method.
820 pub negated: bool,
821 /// The kind of Unicode class.
822 pub kind: ClassUnicodeKind,
823 }
824
825 impl ClassUnicode {
826 /// Returns true if this class has been negated.
827 ///
828 /// Note that this takes the Unicode op into account, if it's present.
829 /// e.g., `is_negated` for `\P{scx!=Katakana}` will return `false`.
830 pub fn is_negated(&self) -> bool {
831 match self.kind {
832 ClassUnicodeKind::NamedValue {
833 op: ClassUnicodeOpKind::NotEqual,
834 ..
835 } => !self.negated,
836 _ => self.negated,
837 }
838 }
839 }
840
841 /// The available forms of Unicode character classes.
842 #[derive(Clone, Debug, Eq, PartialEq)]
843 pub enum ClassUnicodeKind {
844 /// A one letter abbreviated class, e.g., `\pN`.
845 OneLetter(char),
846 /// A binary property, general category or script. The string may be
847 /// empty.
848 Named(String),
849 /// A property name and an associated value.
850 NamedValue {
851 /// The type of Unicode op used to associate `name` with `value`.
852 op: ClassUnicodeOpKind,
853 /// The property name (which may be empty).
854 name: String,
855 /// The property value (which may be empty).
856 value: String,
857 },
858 }
859
860 #[cfg(feature = "arbitrary")]
861 impl arbitrary::Arbitrary<'_> for ClassUnicodeKind {
862 fn arbitrary(
863 u: &mut arbitrary::Unstructured,
864 ) -> arbitrary::Result<ClassUnicodeKind> {
865 #[cfg(any(
866 feature = "unicode-age",
867 feature = "unicode-bool",
868 feature = "unicode-gencat",
869 feature = "unicode-perl",
870 feature = "unicode-script",
871 feature = "unicode-segment",
872 ))]
873 {
874 use alloc::string::ToString;
875
876 use super::unicode_tables::{
877 property_names::PROPERTY_NAMES,
878 property_values::PROPERTY_VALUES,
879 };
880
881 match u.choose_index(3)? {
882 0 => {
883 let all = PROPERTY_VALUES
884 .iter()
885 .flat_map(|e| e.1.iter())
886 .filter(|(name, _)| name.len() == 1)
887 .count();
888 let idx = u.choose_index(all)?;
889 let value = PROPERTY_VALUES
890 .iter()
891 .flat_map(|e| e.1.iter())
892 .take(idx + 1)
893 .last()
894 .unwrap()
895 .0
896 .chars()
897 .next()
898 .unwrap();
899 Ok(ClassUnicodeKind::OneLetter(value))
900 }
901 1 => {
902 let all = PROPERTY_VALUES
903 .iter()
904 .map(|e| e.1.len())
905 .sum::<usize>()
906 + PROPERTY_NAMES.len();
907 let idx = u.choose_index(all)?;
908 let name = PROPERTY_VALUES
909 .iter()
910 .flat_map(|e| e.1.iter())
911 .chain(PROPERTY_NAMES)
912 .map(|(_, e)| e)
913 .take(idx + 1)
914 .last()
915 .unwrap();
916 Ok(ClassUnicodeKind::Named(name.to_string()))
917 }
918 2 => {
919 let all = PROPERTY_VALUES
920 .iter()
921 .map(|e| e.1.len())
922 .sum::<usize>();
923 let idx = u.choose_index(all)?;
924 let (prop, value) = PROPERTY_VALUES
925 .iter()
926 .flat_map(|e| {
927 e.1.iter().map(|(_, value)| (e.0, value))
928 })
929 .take(idx + 1)
930 .last()
931 .unwrap();
932 Ok(ClassUnicodeKind::NamedValue {
933 op: u.arbitrary()?,
934 name: prop.to_string(),
935 value: value.to_string(),
936 })
937 }
938 _ => unreachable!("index chosen is impossible"),
939 }
940 }
941 #[cfg(not(any(
942 feature = "unicode-age",
943 feature = "unicode-bool",
944 feature = "unicode-gencat",
945 feature = "unicode-perl",
946 feature = "unicode-script",
947 feature = "unicode-segment",
948 )))]
949 {
950 match u.choose_index(3)? {
951 0 => Ok(ClassUnicodeKind::OneLetter(u.arbitrary()?)),
952 1 => Ok(ClassUnicodeKind::Named(u.arbitrary()?)),
953 2 => Ok(ClassUnicodeKind::NamedValue {
954 op: u.arbitrary()?,
955 name: u.arbitrary()?,
956 value: u.arbitrary()?,
957 }),
958 _ => unreachable!("index chosen is impossible"),
959 }
960 }
961 }
962
963 fn size_hint(depth: usize) -> (usize, Option<usize>) {
964 #[cfg(any(
965 feature = "unicode-age",
966 feature = "unicode-bool",
967 feature = "unicode-gencat",
968 feature = "unicode-perl",
969 feature = "unicode-script",
970 feature = "unicode-segment",
971 ))]
972 {
973 arbitrary::size_hint::and_all(&[
974 usize::size_hint(depth),
975 usize::size_hint(depth),
976 arbitrary::size_hint::or(
977 (0, Some(0)),
978 ClassUnicodeOpKind::size_hint(depth),
979 ),
980 ])
981 }
982 #[cfg(not(any(
983 feature = "unicode-age",
984 feature = "unicode-bool",
985 feature = "unicode-gencat",
986 feature = "unicode-perl",
987 feature = "unicode-script",
988 feature = "unicode-segment",
989 )))]
990 {
991 arbitrary::size_hint::and(
992 usize::size_hint(depth),
993 arbitrary::size_hint::or_all(&[
994 char::size_hint(depth),
995 String::size_hint(depth),
996 arbitrary::size_hint::and_all(&[
997 String::size_hint(depth),
998 String::size_hint(depth),
999 ClassUnicodeOpKind::size_hint(depth),
1000 ]),
1001 ]),
1002 )
1003 }
1004 }
1005 }
1006
1007 /// The type of op used in a Unicode character class.
1008 #[derive(Clone, Debug, Eq, PartialEq)]
1009 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1010 pub enum ClassUnicodeOpKind {
1011 /// A property set to a specific value, e.g., `\p{scx=Katakana}`.
1012 Equal,
1013 /// A property set to a specific value using a colon, e.g.,
1014 /// `\p{scx:Katakana}`.
1015 Colon,
1016 /// A property that isn't a particular value, e.g., `\p{scx!=Katakana}`.
1017 NotEqual,
1018 }
1019
1020 impl ClassUnicodeOpKind {
1021 /// Whether the op is an equality op or not.
1022 pub fn is_equal(&self) -> bool {
1023 match *self {
1024 ClassUnicodeOpKind::Equal | ClassUnicodeOpKind::Colon => true,
1025 _ => false,
1026 }
1027 }
1028 }
1029
1030 /// A bracketed character class, e.g., `[a-z0-9]`.
1031 #[derive(Clone, Debug, Eq, PartialEq)]
1032 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1033 pub struct ClassBracketed {
1034 /// The span of this class.
1035 pub span: Span,
1036 /// Whether this class is negated or not. e.g., `[a]` is not negated but
1037 /// `[^a]` is.
1038 pub negated: bool,
1039 /// The type of this set. A set is either a normal union of things, e.g.,
1040 /// `[abc]` or a result of applying set operations, e.g., `[\pL--c]`.
1041 pub kind: ClassSet,
1042 }
1043
1044 /// A character class set.
1045 ///
1046 /// This type corresponds to the internal structure of a bracketed character
1047 /// class. That is, every bracketed character is one of two types: a union of
1048 /// items (literals, ranges, other bracketed classes) or a tree of binary set
1049 /// operations.
1050 #[derive(Clone, Debug, Eq, PartialEq)]
1051 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1052 pub enum ClassSet {
1053 /// An item, which can be a single literal, range, nested character class
1054 /// or a union of items.
1055 Item(ClassSetItem),
1056 /// A single binary operation (i.e., &&, -- or ~~).
1057 BinaryOp(ClassSetBinaryOp),
1058 }
1059
1060 impl ClassSet {
1061 /// Build a set from a union.
1062 pub fn union(ast: ClassSetUnion) -> ClassSet {
1063 ClassSet::Item(ClassSetItem::Union(ast))
1064 }
1065
1066 /// Return the span of this character class set.
1067 pub fn span(&self) -> &Span {
1068 match *self {
1069 ClassSet::Item(ref x) => x.span(),
1070 ClassSet::BinaryOp(ref x) => &x.span,
1071 }
1072 }
1073
1074 /// Return true if and only if this class set is empty.
1075 fn is_empty(&self) -> bool {
1076 match *self {
1077 ClassSet::Item(ClassSetItem::Empty(_)) => true,
1078 _ => false,
1079 }
1080 }
1081 }
1082
1083 /// A single component of a character class set.
1084 #[derive(Clone, Debug, Eq, PartialEq)]
1085 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1086 pub enum ClassSetItem {
1087 /// An empty item.
1088 ///
1089 /// Note that a bracketed character class cannot contain a single empty
1090 /// item. Empty items can appear when using one of the binary operators.
1091 /// For example, `[&&]` is the intersection of two empty classes.
1092 Empty(Span),
1093 /// A single literal.
1094 Literal(Literal),
1095 /// A range between two literals.
1096 Range(ClassSetRange),
1097 /// An ASCII character class, e.g., `[:alnum:]` or `[:punct:]`.
1098 Ascii(ClassAscii),
1099 /// A Unicode character class, e.g., `\pL` or `\p{Greek}`.
1100 Unicode(ClassUnicode),
1101 /// A perl character class, e.g., `\d` or `\W`.
1102 Perl(ClassPerl),
1103 /// A bracketed character class set, which may contain zero or more
1104 /// character ranges and/or zero or more nested classes. e.g.,
1105 /// `[a-zA-Z\pL]`.
1106 Bracketed(Box<ClassBracketed>),
1107 /// A union of items.
1108 Union(ClassSetUnion),
1109 }
1110
1111 impl ClassSetItem {
1112 /// Return the span of this character class set item.
1113 pub fn span(&self) -> &Span {
1114 match *self {
1115 ClassSetItem::Empty(ref span) => span,
1116 ClassSetItem::Literal(ref x) => &x.span,
1117 ClassSetItem::Range(ref x) => &x.span,
1118 ClassSetItem::Ascii(ref x) => &x.span,
1119 ClassSetItem::Perl(ref x) => &x.span,
1120 ClassSetItem::Unicode(ref x) => &x.span,
1121 ClassSetItem::Bracketed(ref x) => &x.span,
1122 ClassSetItem::Union(ref x) => &x.span,
1123 }
1124 }
1125 }
1126
1127 /// A single character class range in a set.
1128 #[derive(Clone, Debug, Eq, PartialEq)]
1129 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1130 pub struct ClassSetRange {
1131 /// The span of this range.
1132 pub span: Span,
1133 /// The start of this range.
1134 pub start: Literal,
1135 /// The end of this range.
1136 pub end: Literal,
1137 }
1138
1139 impl ClassSetRange {
1140 /// Returns true if and only if this character class range is valid.
1141 ///
1142 /// The only case where a range is invalid is if its start is greater than
1143 /// its end.
1144 pub fn is_valid(&self) -> bool {
1145 self.start.c <= self.end.c
1146 }
1147 }
1148
1149 /// A union of items inside a character class set.
1150 #[derive(Clone, Debug, Eq, PartialEq)]
1151 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1152 pub struct ClassSetUnion {
1153 /// The span of the items in this operation. e.g., the `a-z0-9` in
1154 /// `[^a-z0-9]`
1155 pub span: Span,
1156 /// The sequence of items that make up this union.
1157 pub items: Vec<ClassSetItem>,
1158 }
1159
1160 impl ClassSetUnion {
1161 /// Push a new item in this union.
1162 ///
1163 /// The ending position of this union's span is updated to the ending
1164 /// position of the span of the item given. If the union is empty, then
1165 /// the starting position of this union is set to the starting position
1166 /// of this item.
1167 ///
1168 /// In other words, if you only use this method to add items to a union
1169 /// and you set the spans on each item correctly, then you should never
1170 /// need to adjust the span of the union directly.
1171 pub fn push(&mut self, item: ClassSetItem) {
1172 if self.items.is_empty() {
1173 self.span.start = item.span().start;
1174 }
1175 self.span.end = item.span().end;
1176 self.items.push(item);
1177 }
1178
1179 /// Return this union as a character class set item.
1180 ///
1181 /// If this union contains zero items, then an empty union is
1182 /// returned. If this concatenation contains exactly 1 item, then the
1183 /// corresponding item is returned. Otherwise, ClassSetItem::Union is
1184 /// returned.
1185 pub fn into_item(mut self) -> ClassSetItem {
1186 match self.items.len() {
1187 0 => ClassSetItem::Empty(self.span),
1188 1 => self.items.pop().unwrap(),
1189 _ => ClassSetItem::Union(self),
1190 }
1191 }
1192 }
1193
1194 /// A Unicode character class set operation.
1195 #[derive(Clone, Debug, Eq, PartialEq)]
1196 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1197 pub struct ClassSetBinaryOp {
1198 /// The span of this operation. e.g., the `a-z--[h-p]` in `[a-z--h-p]`.
1199 pub span: Span,
1200 /// The type of this set operation.
1201 pub kind: ClassSetBinaryOpKind,
1202 /// The left hand side of the operation.
1203 pub lhs: Box<ClassSet>,
1204 /// The right hand side of the operation.
1205 pub rhs: Box<ClassSet>,
1206 }
1207
1208 /// The type of a Unicode character class set operation.
1209 ///
1210 /// Note that this doesn't explicitly represent union since there is no
1211 /// explicit union operator. Concatenation inside a character class corresponds
1212 /// to the union operation.
1213 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1214 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1215 pub enum ClassSetBinaryOpKind {
1216 /// The intersection of two sets, e.g., `\pN&&[a-z]`.
1217 Intersection,
1218 /// The difference of two sets, e.g., `\pN--[0-9]`.
1219 Difference,
1220 /// The symmetric difference of two sets. The symmetric difference is the
1221 /// set of elements belonging to one but not both sets.
1222 /// e.g., `[\pL~~[:ascii:]]`.
1223 SymmetricDifference,
1224 }
1225
1226 /// A single zero-width assertion.
1227 #[derive(Clone, Debug, Eq, PartialEq)]
1228 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1229 pub struct Assertion {
1230 /// The span of this assertion.
1231 pub span: Span,
1232 /// The assertion kind, e.g., `\b` or `^`.
1233 pub kind: AssertionKind,
1234 }
1235
1236 /// An assertion kind.
1237 #[derive(Clone, Debug, Eq, PartialEq)]
1238 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1239 pub enum AssertionKind {
1240 /// `^`
1241 StartLine,
1242 /// `$`
1243 EndLine,
1244 /// `\A`
1245 StartText,
1246 /// `\z`
1247 EndText,
1248 /// `\b`
1249 WordBoundary,
1250 /// `\B`
1251 NotWordBoundary,
1252 }
1253
1254 /// A repetition operation applied to a regular expression.
1255 #[derive(Clone, Debug, Eq, PartialEq)]
1256 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1257 pub struct Repetition {
1258 /// The span of this operation.
1259 pub span: Span,
1260 /// The actual operation.
1261 pub op: RepetitionOp,
1262 /// Whether this operation was applied greedily or not.
1263 pub greedy: bool,
1264 /// The regular expression under repetition.
1265 pub ast: Box<Ast>,
1266 }
1267
1268 /// The repetition operator itself.
1269 #[derive(Clone, Debug, Eq, PartialEq)]
1270 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1271 pub struct RepetitionOp {
1272 /// The span of this operator. This includes things like `+`, `*?` and
1273 /// `{m,n}`.
1274 pub span: Span,
1275 /// The type of operation.
1276 pub kind: RepetitionKind,
1277 }
1278
1279 /// The kind of a repetition operator.
1280 #[derive(Clone, Debug, Eq, PartialEq)]
1281 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1282 pub enum RepetitionKind {
1283 /// `?`
1284 ZeroOrOne,
1285 /// `*`
1286 ZeroOrMore,
1287 /// `+`
1288 OneOrMore,
1289 /// `{m,n}`
1290 Range(RepetitionRange),
1291 }
1292
1293 /// A range repetition operator.
1294 #[derive(Clone, Debug, Eq, PartialEq)]
1295 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1296 pub enum RepetitionRange {
1297 /// `{m}`
1298 Exactly(u32),
1299 /// `{m,}`
1300 AtLeast(u32),
1301 /// `{m,n}`
1302 Bounded(u32, u32),
1303 }
1304
1305 impl RepetitionRange {
1306 /// Returns true if and only if this repetition range is valid.
1307 ///
1308 /// The only case where a repetition range is invalid is if it is bounded
1309 /// and its start is greater than its end.
1310 pub fn is_valid(&self) -> bool {
1311 match *self {
1312 RepetitionRange::Bounded(s, e) if s > e => false,
1313 _ => true,
1314 }
1315 }
1316 }
1317
1318 /// A grouped regular expression.
1319 ///
1320 /// This includes both capturing and non-capturing groups. This does **not**
1321 /// include flag-only groups like `(?is)`, but does contain any group that
1322 /// contains a sub-expression, e.g., `(a)`, `(?P<name>a)`, `(?:a)` and
1323 /// `(?is:a)`.
1324 #[derive(Clone, Debug, Eq, PartialEq)]
1325 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1326 pub struct Group {
1327 /// The span of this group.
1328 pub span: Span,
1329 /// The kind of this group.
1330 pub kind: GroupKind,
1331 /// The regular expression in this group.
1332 pub ast: Box<Ast>,
1333 }
1334
1335 impl Group {
1336 /// If this group is non-capturing, then this returns the (possibly empty)
1337 /// set of flags. Otherwise, `None` is returned.
1338 pub fn flags(&self) -> Option<&Flags> {
1339 match self.kind {
1340 GroupKind::NonCapturing(ref flags) => Some(flags),
1341 _ => None,
1342 }
1343 }
1344
1345 /// Returns true if and only if this group is capturing.
1346 pub fn is_capturing(&self) -> bool {
1347 match self.kind {
1348 GroupKind::CaptureIndex(_) | GroupKind::CaptureName { .. } => true,
1349 GroupKind::NonCapturing(_) => false,
1350 }
1351 }
1352
1353 /// Returns the capture index of this group, if this is a capturing group.
1354 ///
1355 /// This returns a capture index precisely when `is_capturing` is `true`.
1356 pub fn capture_index(&self) -> Option<u32> {
1357 match self.kind {
1358 GroupKind::CaptureIndex(i) => Some(i),
1359 GroupKind::CaptureName { ref name, .. } => Some(name.index),
1360 GroupKind::NonCapturing(_) => None,
1361 }
1362 }
1363 }
1364
1365 /// The kind of a group.
1366 #[derive(Clone, Debug, Eq, PartialEq)]
1367 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1368 pub enum GroupKind {
1369 /// `(a)`
1370 CaptureIndex(u32),
1371 /// `(?<name>a)` or `(?P<name>a)`
1372 CaptureName {
1373 /// True if the `?P<` syntax is used and false if the `?<` syntax is used.
1374 starts_with_p: bool,
1375 /// The capture name.
1376 name: CaptureName,
1377 },
1378 /// `(?:a)` and `(?i:a)`
1379 NonCapturing(Flags),
1380 }
1381
1382 /// A capture name.
1383 ///
1384 /// This corresponds to the name itself between the angle brackets in, e.g.,
1385 /// `(?P<foo>expr)`.
1386 #[derive(Clone, Debug, Eq, PartialEq)]
1387 pub struct CaptureName {
1388 /// The span of this capture name.
1389 pub span: Span,
1390 /// The capture name.
1391 pub name: String,
1392 /// The capture index.
1393 pub index: u32,
1394 }
1395
1396 #[cfg(feature = "arbitrary")]
1397 impl arbitrary::Arbitrary<'_> for CaptureName {
1398 fn arbitrary(
1399 u: &mut arbitrary::Unstructured,
1400 ) -> arbitrary::Result<CaptureName> {
1401 let len = u.arbitrary_len::<char>()?;
1402 if len == 0 {
1403 return Err(arbitrary::Error::NotEnoughData);
1404 }
1405 let mut name: String = String::new();
1406 for _ in 0..len {
1407 let ch: char = u.arbitrary()?;
1408 let cp = u32::from(ch);
1409 let ascii_letter_offset = u8::try_from(cp % 26).unwrap();
1410 let ascii_letter = b'a' + ascii_letter_offset;
1411 name.push(char::from(ascii_letter));
1412 }
1413 Ok(CaptureName { span: u.arbitrary()?, name, index: u.arbitrary()? })
1414 }
1415
1416 fn size_hint(depth: usize) -> (usize, Option<usize>) {
1417 arbitrary::size_hint::and_all(&[
1418 Span::size_hint(depth),
1419 usize::size_hint(depth),
1420 u32::size_hint(depth),
1421 ])
1422 }
1423 }
1424
1425 /// A group of flags that is not applied to a particular regular expression.
1426 #[derive(Clone, Debug, Eq, PartialEq)]
1427 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1428 pub struct SetFlags {
1429 /// The span of these flags, including the grouping parentheses.
1430 pub span: Span,
1431 /// The actual sequence of flags.
1432 pub flags: Flags,
1433 }
1434
1435 /// A group of flags.
1436 ///
1437 /// This corresponds only to the sequence of flags themselves, e.g., `is-u`.
1438 #[derive(Clone, Debug, Eq, PartialEq)]
1439 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1440 pub struct Flags {
1441 /// The span of this group of flags.
1442 pub span: Span,
1443 /// A sequence of flag items. Each item is either a flag or a negation
1444 /// operator.
1445 pub items: Vec<FlagsItem>,
1446 }
1447
1448 impl Flags {
1449 /// Add the given item to this sequence of flags.
1450 ///
1451 /// If the item was added successfully, then `None` is returned. If the
1452 /// given item is a duplicate, then `Some(i)` is returned, where
1453 /// `items[i].kind == item.kind`.
1454 pub fn add_item(&mut self, item: FlagsItem) -> Option<usize> {
1455 for (i, x) in self.items.iter().enumerate() {
1456 if x.kind == item.kind {
1457 return Some(i);
1458 }
1459 }
1460 self.items.push(item);
1461 None
1462 }
1463
1464 /// Returns the state of the given flag in this set.
1465 ///
1466 /// If the given flag is in the set but is negated, then `Some(false)` is
1467 /// returned.
1468 ///
1469 /// If the given flag is in the set and is not negated, then `Some(true)`
1470 /// is returned.
1471 ///
1472 /// Otherwise, `None` is returned.
1473 pub fn flag_state(&self, flag: Flag) -> Option<bool> {
1474 let mut negated = false;
1475 for x in &self.items {
1476 match x.kind {
1477 FlagsItemKind::Negation => {
1478 negated = true;
1479 }
1480 FlagsItemKind::Flag(ref xflag) if xflag == &flag => {
1481 return Some(!negated);
1482 }
1483 _ => {}
1484 }
1485 }
1486 None
1487 }
1488 }
1489
1490 /// A single item in a group of flags.
1491 #[derive(Clone, Debug, Eq, PartialEq)]
1492 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1493 pub struct FlagsItem {
1494 /// The span of this item.
1495 pub span: Span,
1496 /// The kind of this item.
1497 pub kind: FlagsItemKind,
1498 }
1499
1500 /// The kind of an item in a group of flags.
1501 #[derive(Clone, Debug, Eq, PartialEq)]
1502 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1503 pub enum FlagsItemKind {
1504 /// A negation operator applied to all subsequent flags in the enclosing
1505 /// group.
1506 Negation,
1507 /// A single flag in a group.
1508 Flag(Flag),
1509 }
1510
1511 impl FlagsItemKind {
1512 /// Returns true if and only if this item is a negation operator.
1513 pub fn is_negation(&self) -> bool {
1514 match *self {
1515 FlagsItemKind::Negation => true,
1516 _ => false,
1517 }
1518 }
1519 }
1520
1521 /// A single flag.
1522 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1523 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1524 pub enum Flag {
1525 /// `i`
1526 CaseInsensitive,
1527 /// `m`
1528 MultiLine,
1529 /// `s`
1530 DotMatchesNewLine,
1531 /// `U`
1532 SwapGreed,
1533 /// `u`
1534 Unicode,
1535 /// `R`
1536 CRLF,
1537 /// `x`
1538 IgnoreWhitespace,
1539 }
1540
1541 /// A custom `Drop` impl is used for `Ast` such that it uses constant stack
1542 /// space but heap space proportional to the depth of the `Ast`.
1543 impl Drop for Ast {
1544 fn drop(&mut self) {
1545 use core::mem;
1546
1547 match *self {
1548 Ast::Empty(_)
1549 | Ast::Flags(_)
1550 | Ast::Literal(_)
1551 | Ast::Dot(_)
1552 | Ast::Assertion(_)
1553 // Classes are recursive, so they get their own Drop impl.
1554 | Ast::Class(_) => return,
1555 Ast::Repetition(ref x) if !x.ast.has_subexprs() => return,
1556 Ast::Group(ref x) if !x.ast.has_subexprs() => return,
1557 Ast::Alternation(ref x) if x.asts.is_empty() => return,
1558 Ast::Concat(ref x) if x.asts.is_empty() => return,
1559 _ => {}
1560 }
1561
1562 let empty_span = || Span::splat(Position::new(0, 0, 0));
1563 let empty_ast = || Ast::Empty(empty_span());
1564 let mut stack = vec![mem::replace(self, empty_ast())];
1565 while let Some(mut ast) = stack.pop() {
1566 match ast {
1567 Ast::Empty(_)
1568 | Ast::Flags(_)
1569 | Ast::Literal(_)
1570 | Ast::Dot(_)
1571 | Ast::Assertion(_)
1572 // Classes are recursive, so they get their own Drop impl.
1573 | Ast::Class(_) => {}
1574 Ast::Repetition(ref mut x) => {
1575 stack.push(mem::replace(&mut x.ast, empty_ast()));
1576 }
1577 Ast::Group(ref mut x) => {
1578 stack.push(mem::replace(&mut x.ast, empty_ast()));
1579 }
1580 Ast::Alternation(ref mut x) => {
1581 stack.extend(x.asts.drain(..));
1582 }
1583 Ast::Concat(ref mut x) => {
1584 stack.extend(x.asts.drain(..));
1585 }
1586 }
1587 }
1588 }
1589 }
1590
1591 /// A custom `Drop` impl is used for `ClassSet` such that it uses constant
1592 /// stack space but heap space proportional to the depth of the `ClassSet`.
1593 impl Drop for ClassSet {
1594 fn drop(&mut self) {
1595 use core::mem;
1596
1597 match *self {
1598 ClassSet::Item(ref item) => match *item {
1599 ClassSetItem::Empty(_)
1600 | ClassSetItem::Literal(_)
1601 | ClassSetItem::Range(_)
1602 | ClassSetItem::Ascii(_)
1603 | ClassSetItem::Unicode(_)
1604 | ClassSetItem::Perl(_) => return,
1605 ClassSetItem::Bracketed(ref x) => {
1606 if x.kind.is_empty() {
1607 return;
1608 }
1609 }
1610 ClassSetItem::Union(ref x) => {
1611 if x.items.is_empty() {
1612 return;
1613 }
1614 }
1615 },
1616 ClassSet::BinaryOp(ref op) => {
1617 if op.lhs.is_empty() && op.rhs.is_empty() {
1618 return;
1619 }
1620 }
1621 }
1622
1623 let empty_span = || Span::splat(Position::new(0, 0, 0));
1624 let empty_set = || ClassSet::Item(ClassSetItem::Empty(empty_span()));
1625 let mut stack = vec![mem::replace(self, empty_set())];
1626 while let Some(mut set) = stack.pop() {
1627 match set {
1628 ClassSet::Item(ref mut item) => match *item {
1629 ClassSetItem::Empty(_)
1630 | ClassSetItem::Literal(_)
1631 | ClassSetItem::Range(_)
1632 | ClassSetItem::Ascii(_)
1633 | ClassSetItem::Unicode(_)
1634 | ClassSetItem::Perl(_) => {}
1635 ClassSetItem::Bracketed(ref mut x) => {
1636 stack.push(mem::replace(&mut x.kind, empty_set()));
1637 }
1638 ClassSetItem::Union(ref mut x) => {
1639 stack.extend(x.items.drain(..).map(ClassSet::Item));
1640 }
1641 },
1642 ClassSet::BinaryOp(ref mut op) => {
1643 stack.push(mem::replace(&mut op.lhs, empty_set()));
1644 stack.push(mem::replace(&mut op.rhs, empty_set()));
1645 }
1646 }
1647 }
1648 }
1649 }
1650
1651 #[cfg(test)]
1652 mod tests {
1653 use super::*;
1654
1655 // We use a thread with an explicit stack size to test that our destructor
1656 // for Ast can handle arbitrarily sized expressions in constant stack
1657 // space. In case we run on a platform without threads (WASM?), we limit
1658 // this test to Windows/Unix.
1659 #[test]
1660 #[cfg(any(unix, windows))]
1661 fn no_stack_overflow_on_drop() {
1662 use std::thread;
1663
1664 let run = || {
1665 let span = || Span::splat(Position::new(0, 0, 0));
1666 let mut ast = Ast::Empty(span());
1667 for i in 0..200 {
1668 ast = Ast::Group(Group {
1669 span: span(),
1670 kind: GroupKind::CaptureIndex(i),
1671 ast: Box::new(ast),
1672 });
1673 }
1674 assert!(!ast.is_empty());
1675 };
1676
1677 // We run our test on a thread with a small stack size so we can
1678 // force the issue more easily.
1679 //
1680 // NOTE(2023-03-21): It turns out that some platforms (like FreeBSD)
1681 // will just barf with very small stack sizes. So we bump this up a bit
1682 // to give more room to breath. When I did this, I confirmed that if
1683 // I remove the custom `Drop` impl for `Ast`, then this test does
1684 // indeed still fail with a stack overflow. (At the time of writing, I
1685 // had to bump it all the way up to 32K before the test would pass even
1686 // without the custom `Drop` impl. So 16K seems like a safe number
1687 // here.)
1688 //
1689 // See: https://github.com/rust-lang/regex/issues/967
1690 thread::Builder::new()
1691 .stack_size(16 << 10)
1692 .spawn(run)
1693 .unwrap()
1694 .join()
1695 .unwrap();
1696 }
1697 }