Skip to main content

resharp_parser/
lib.rs

1//! Parser for resharp regex patterns.
2//!
3//! Converts regex pattern strings into the node representation used by resharp-algebra.
4
5#![warn(dead_code)]
6pub mod ast;
7use std::cell::{Cell, RefCell};
8
9use ast::{Ast, Concat, ErrorKind, GroupKind, LookaroundKind};
10use regex_syntax::{
11    ast::{
12        ClassAscii, ClassBracketed, ClassPerl, ClassSet, ClassSetBinaryOpKind, ClassSetItem,
13        ClassSetRange, ClassSetUnion, ClassUnicode, ClassUnicodeKind, ClassUnicodeOpKind,
14        HexLiteralKind, Literal, LiteralKind, Position, Span, SpecialLiteralKind,
15    },
16    hir::{
17        self,
18        translate::{Translator, TranslatorBuilder},
19    },
20    utf8::Utf8Sequences,
21};
22use resharp_algebra::NodeId;
23
24type TB<'s> = resharp_algebra::RegexBuilder;
25
26/// global pattern-level flags, set from `EngineOptions`.
27pub struct PatternFlags {
28    /// `\w`/`\d`/`\s` match full Unicode (true) or ASCII only (false).
29    pub unicode: bool,
30    /// `\w` covers all Unicode word chars including 3- and 4-byte sequences.
31    pub full_unicode: bool,
32    /// global case-insensitive matching.
33    pub case_insensitive: bool,
34    /// `.` matches `\n` (behaves like `_`).
35    pub dot_matches_new_line: bool,
36    /// allow whitespace and `#` comments in the pattern.
37    pub ignore_whitespace: bool,
38}
39
40impl Default for PatternFlags {
41    fn default() -> Self {
42        Self {
43            unicode: true,
44            full_unicode: false,
45            case_insensitive: false,
46            dot_matches_new_line: false,
47            ignore_whitespace: false,
48        }
49    }
50}
51
52#[derive(Clone, Copy, PartialEq)]
53enum WordCharKind {
54    Word,
55    NonWord,
56    MaybeWord,
57    MaybeNonWord,
58    Unknown,
59    Edge,
60}
61
62fn is_word_byte(b: u8) -> bool {
63    b.is_ascii_alphanumeric() || b == b'_'
64}
65
66#[derive(Clone, Debug, Eq, PartialEq)]
67enum Primitive {
68    Literal(Literal),
69    Assertion(ast::Assertion),
70    Dot(Span),
71    Top(Span),
72    Perl(ClassPerl),
73    Unicode(ClassUnicode),
74}
75
76impl Primitive {
77    fn span(&self) -> &Span {
78        match *self {
79            Primitive::Literal(ref x) => &x.span,
80            Primitive::Assertion(ref x) => &x.span,
81            Primitive::Dot(ref span) => span,
82            Primitive::Top(ref span) => span,
83            Primitive::Perl(ref x) => &x.span,
84            Primitive::Unicode(ref x) => &x.span,
85        }
86    }
87
88    fn into_ast(self) -> Ast {
89        match self {
90            Primitive::Literal(lit) => Ast::literal(lit),
91            Primitive::Assertion(assert) => Ast::assertion(assert),
92            Primitive::Dot(span) => Ast::dot(span),
93            Primitive::Top(span) => Ast::top(span),
94            Primitive::Perl(cls) => Ast::class_perl(cls),
95            Primitive::Unicode(cls) => Ast::class_unicode(cls),
96        }
97    }
98
99    fn into_class_set_item(self, p: &ResharpParser) -> Result<regex_syntax::ast::ClassSetItem> {
100        use self::Primitive::*;
101        use regex_syntax::ast::ClassSetItem;
102
103        match self {
104            Literal(lit) => Ok(ClassSetItem::Literal(lit)),
105            Perl(cls) => Ok(ClassSetItem::Perl(cls)),
106            Unicode(cls) => Ok(ClassSetItem::Unicode(cls)),
107            x => Err(p.error(*x.span(), ast::ErrorKind::ClassEscapeInvalid)),
108        }
109    }
110
111    fn into_class_literal(self, p: &ResharpParser) -> Result<Literal> {
112        use self::Primitive::*;
113
114        match self {
115            Literal(lit) => Ok(lit),
116            x => Err(p.error(*x.span(), ast::ErrorKind::ClassRangeLiteral)),
117        }
118    }
119}
120
121#[derive(Clone, Debug, Eq, PartialEq)]
122pub enum Either<Left, Right> {
123    Left(Left),
124    Right(Right),
125}
126
127#[derive(Clone, Debug, Eq, PartialEq)]
128pub struct ResharpError {
129    /// The kind of error.
130    pub kind: ErrorKind,
131    /// The original pattern that the parser generated the error from. Every
132    /// span in an error is a valid range into this string.
133    pattern: String,
134    /// The span of this error.
135    pub span: Span,
136}
137
138impl std::fmt::Display for ResharpError {
139    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
140        write!(f, "{:?}: {:?}", self.kind, self.span)
141    }
142}
143impl std::error::Error for ResharpError {}
144
145type Result<T> = core::result::Result<T, ResharpError>;
146
147#[derive(Clone, Debug)]
148enum GroupState {
149    /// This state is pushed whenever an opening group is found.
150    Group {
151        /// The concatenation immediately preceding the opening group.
152        concat: Concat,
153        /// The group that has been opened. Its sub-AST is always empty.
154        group: ast::Group,
155        /// Whether this group has the `x` flag enabled or not.
156        ignore_whitespace: bool,
157    },
158    /// This state is pushed whenever a new alternation branch is found. If
159    /// an alternation branch is found and this state is at the top of the
160    /// stack, then this state should be modified to include the new
161    /// alternation.
162    Alternation(ast::Alternation),
163    Intersection(ast::Intersection),
164}
165
166#[derive(Clone, Debug)]
167enum ClassState {
168    /// This state is pushed whenever an opening bracket is found.
169    Open {
170        /// The union of class items immediately preceding this class.
171        union: regex_syntax::ast::ClassSetUnion,
172        /// The class that has been opened. Typically this just corresponds
173        /// to the `[`, but it can also include `[^` since `^` indicates
174        /// negation of the class.
175        set: regex_syntax::ast::ClassBracketed,
176    },
177    /// This state is pushed when a operator is seen. When popped, the stored
178    /// set becomes the left hand side of the operator.
179    Op {
180        /// The type of the operation, i.e., &&, -- or ~~.
181        kind: regex_syntax::ast::ClassSetBinaryOpKind,
182        /// The left-hand side of the operator.
183        lhs: regex_syntax::ast::ClassSet,
184    },
185}
186
187/// RE# syntax parser based on the regex-syntax crate.
188pub struct ResharpParser<'s> {
189    perl_classes: Vec<(bool, regex_syntax::ast::ClassPerlKind, NodeId)>,
190    unicode_classes: resharp_algebra::UnicodeClassCache,
191    pub translator: regex_syntax::hir::translate::Translator,
192    pub pattern: &'s str,
193    pos: Cell<Position>,
194    capture_index: Cell<u32>,
195    octal: bool,
196    empty_min_range: bool,
197    ignore_whitespace: Cell<bool>,
198    dot_all: Cell<bool>,
199    global_unicode: bool,
200    global_full_unicode: bool,
201    global_case_insensitive: bool,
202    comments: RefCell<Vec<ast::Comment>>,
203    stack_group: RefCell<Vec<GroupState>>,
204    stack_class: RefCell<Vec<ClassState>>,
205    capture_names: RefCell<Vec<ast::CaptureName>>,
206    scratch: RefCell<String>,
207}
208
209fn specialize_err<T>(result: Result<T>, from: ast::ErrorKind, to: ast::ErrorKind) -> Result<T> {
210    result.map_err(|e| {
211        if e.kind == from {
212            ResharpError {
213                kind: to,
214                pattern: e.pattern,
215                span: e.span,
216            }
217        } else {
218            e
219        }
220    })
221}
222
223fn is_capture_char(c: char, first: bool) -> bool {
224    if first {
225        c == '_' || c.is_alphabetic()
226    } else {
227        c == '_' || c == '.' || c == '[' || c == ']' || c.is_alphanumeric()
228    }
229}
230
231pub fn is_meta_character(c: char) -> bool {
232    matches!(
233        c,
234        '\\' | '.'
235            | '+'
236            | '*'
237            | '?'
238            | '('
239            | ')'
240            | '|'
241            | '['
242            | ']'
243            | '{'
244            | '}'
245            | '^'
246            | '$'
247            | '#'
248            | '&'
249            | '-'
250            | '~'
251            | '_'
252    )
253}
254
255/// escapes all resharp meta characters in `text`.
256pub fn escape(text: &str) -> String {
257    let mut buf = String::new();
258    escape_into(text, &mut buf);
259    buf
260}
261
262/// escapes all resharp meta characters in `text` and appends to `buf`.
263pub fn escape_into(text: &str, buf: &mut String) {
264    buf.reserve(text.len());
265    for c in text.chars() {
266        if is_meta_character(c) {
267            buf.push('\\');
268        }
269        buf.push(c);
270    }
271}
272
273pub fn is_escapeable_character(c: char) -> bool {
274    // Certainly escapeable if it's a meta character.
275    if is_meta_character(c) {
276        return true;
277    }
278    // Any character that isn't ASCII is definitely not escapeable. There's
279    // no real need to allow things like \☃ right?
280    if !c.is_ascii() {
281        return false;
282    }
283    // Otherwise, we basically say that everything is escapeable unless it's a
284    // letter or digit. Things like \3 are either octal (when enabled) or an
285    // error, and we should keep it that way. Otherwise, letters are reserved
286    // for adding new syntax in a backwards compatible way.
287    match c {
288        '0'..='9' | 'A'..='Z' | 'a'..='z' => false,
289        // While not currently supported, we keep these as not escapeable to
290        // give us some flexibility with respect to supporting the \< and
291        // \> word boundary assertions in the future. By rejecting them as
292        // escapeable, \< and \> will result in a parse error. Thus, we can
293        // turn them into something else in the future without it being a
294        // backwards incompatible change.
295        //
296        // OK, now we support \< and \>, and we need to retain them as *not*
297        // escapeable here since the escape sequence is significant.
298        '<' | '>' => false,
299        _ => true,
300    }
301}
302
303fn is_hex(c: char) -> bool {
304    c.is_ascii_digit() || ('a'..='f').contains(&c) || ('A'..='F').contains(&c)
305}
306
307impl<'s> ResharpParser<'s> {
308    fn default_translator_builder(&self) -> TranslatorBuilder {
309        let mut trb = TranslatorBuilder::new();
310        trb.unicode(self.global_unicode);
311        trb.utf8(false);
312        trb.case_insensitive(self.global_case_insensitive);
313        trb
314    }
315
316    pub fn new(pattern: &'s str) -> Self {
317        Self::with_flags(pattern, &PatternFlags::default())
318    }
319
320    pub fn with_flags(pattern: &'s str, flags: &PatternFlags) -> Self {
321        let mut trb = TranslatorBuilder::new();
322        trb.unicode(flags.unicode);
323        trb.utf8(false);
324        trb.case_insensitive(flags.case_insensitive);
325        Self {
326            translator: trb.build(),
327            pattern,
328            perl_classes: vec![],
329            unicode_classes: resharp_algebra::UnicodeClassCache::default(),
330            pos: Cell::new(Position::new(0, 0, 0)),
331            capture_index: Cell::new(0),
332            octal: false,
333            empty_min_range: false,
334            ignore_whitespace: Cell::new(flags.ignore_whitespace),
335            dot_all: Cell::new(flags.dot_matches_new_line),
336            global_unicode: flags.unicode || flags.full_unicode,
337            global_full_unicode: flags.full_unicode,
338            global_case_insensitive: flags.case_insensitive,
339            comments: RefCell::new(vec![]),
340            stack_group: RefCell::new(vec![]),
341            stack_class: RefCell::new(vec![]),
342            capture_names: RefCell::new(vec![]),
343            scratch: RefCell::new(String::new()),
344        }
345    }
346
347    /// Return a reference to the parser state.
348    fn parser(&'_ self) -> &'_ ResharpParser<'_> {
349        self
350    }
351
352    /// Return a reference to the pattern being parsed.
353    fn pattern(&self) -> &str {
354        self.pattern
355    }
356
357    /// Create a new error with the given span and error type.
358    fn error(&self, span: Span, kind: ast::ErrorKind) -> ResharpError {
359        ResharpError {
360            kind,
361            pattern: self.pattern().to_string(),
362            span,
363        }
364    }
365
366    fn unsupported_error(&self, _: regex_syntax::hir::Error) -> ResharpError {
367        self.error(
368            Span::splat(self.pos()),
369            ast::ErrorKind::UnsupportedResharpRegex,
370        )
371    }
372
373    /// Return the current offset of the parser.
374    ///
375    /// The offset starts at `0` from the beginning of the regular expression
376    /// pattern string.
377    fn offset(&self) -> usize {
378        self.parser().pos.get().offset
379    }
380
381    /// Return the current line number of the parser.
382    ///
383    /// The line number starts at `1`.
384    fn line(&self) -> usize {
385        self.parser().pos.get().line
386    }
387
388    /// Return the current column of the parser.
389    ///
390    /// The column number starts at `1` and is reset whenever a `\n` is seen.
391    fn column(&self) -> usize {
392        self.parser().pos.get().column
393    }
394
395    /// Return the next capturing index. Each subsequent call increments the
396    /// internal index.
397    ///
398    /// The span given should correspond to the location of the opening
399    /// parenthesis.
400    ///
401    /// If the capture limit is exceeded, then an error is returned.
402    fn next_capture_index(&self, span: Span) -> Result<u32> {
403        let current = self.parser().capture_index.get();
404        let i = current
405            .checked_add(1)
406            .ok_or_else(|| self.error(span, ast::ErrorKind::CaptureLimitExceeded))?;
407        self.parser().capture_index.set(i);
408        Ok(i)
409    }
410
411    fn add_capture_name(&self, cap: &ast::CaptureName) -> Result<()> {
412        let mut names = self.parser().capture_names.borrow_mut();
413        match names.binary_search_by_key(&cap.name.as_str(), |c| c.name.as_str()) {
414            Err(i) => {
415                names.insert(i, cap.clone());
416                Ok(())
417            }
418            Ok(i) => Err(self.error(
419                cap.span,
420                ast::ErrorKind::GroupNameDuplicate {
421                    original: names[i].span,
422                },
423            )),
424        }
425    }
426
427    fn ignore_whitespace(&self) -> bool {
428        self.parser().ignore_whitespace.get()
429    }
430
431    fn char(&self) -> char {
432        self.char_at(self.offset())
433    }
434
435    fn char_at(&self, i: usize) -> char {
436        self.pattern()[i..]
437            .chars()
438            .next()
439            .unwrap_or_else(|| panic!("expected char at offset {}", i))
440    }
441
442    fn bump(&self) -> bool {
443        if self.is_eof() {
444            return false;
445        }
446        let Position {
447            mut offset,
448            mut line,
449            mut column,
450        } = self.pos();
451        if self.char() == '\n' {
452            line = line.checked_add(1).unwrap();
453            column = 1;
454        } else {
455            column = column.checked_add(1).unwrap();
456        }
457        offset += self.char().len_utf8();
458        self.parser().pos.set(Position {
459            offset,
460            line,
461            column,
462        });
463        self.pattern()[self.offset()..].chars().next().is_some()
464    }
465
466    fn bump_if(&self, prefix: &str) -> bool {
467        if self.pattern()[self.offset()..].starts_with(prefix) {
468            for _ in 0..prefix.chars().count() {
469                self.bump();
470            }
471            true
472        } else {
473            false
474        }
475    }
476
477    fn is_lookaround_prefix(&self) -> Option<(bool, bool)> {
478        if self.bump_if("?=") {
479            return Some((true, true));
480        }
481        if self.bump_if("?!") {
482            return Some((true, false));
483        }
484        if self.bump_if("?<=") {
485            return Some((false, true));
486        }
487        if self.bump_if("?<!") {
488            return Some((false, false));
489        }
490        None
491    }
492
493    fn bump_and_bump_space(&self) -> bool {
494        if !self.bump() {
495            return false;
496        }
497        self.bump_space();
498        !self.is_eof()
499    }
500
501    fn bump_space(&self) {
502        if !self.ignore_whitespace() {
503            return;
504        }
505        while !self.is_eof() {
506            if self.char().is_whitespace() {
507                self.bump();
508            } else if self.char() == '#' {
509                let start = self.pos();
510                let mut comment_text = String::new();
511                self.bump();
512                while !self.is_eof() {
513                    let c = self.char();
514                    self.bump();
515                    if c == '\n' {
516                        break;
517                    }
518                    comment_text.push(c);
519                }
520                let comment = ast::Comment {
521                    span: Span::new(start, self.pos()),
522                    comment: comment_text,
523                };
524                self.parser().comments.borrow_mut().push(comment);
525            } else {
526                break;
527            }
528        }
529    }
530
531    /// Peek at the next character in the input without advancing the parser.
532    ///
533    /// If the input has been exhausted, then this returns `None`.
534    fn peek(&self) -> Option<char> {
535        if self.is_eof() {
536            return None;
537        }
538        self.pattern()[self.offset() + self.char().len_utf8()..]
539            .chars()
540            .next()
541    }
542
543    /// Like peek, but will ignore spaces when the parser is in whitespace
544    /// insensitive mode.
545    fn peek_space(&self) -> Option<char> {
546        if !self.ignore_whitespace() {
547            return self.peek();
548        }
549        if self.is_eof() {
550            return None;
551        }
552        let mut start = self.offset() + self.char().len_utf8();
553        let mut in_comment = false;
554        for (i, c) in self.pattern()[start..].char_indices() {
555            if c.is_whitespace() {
556                continue;
557            } else if !in_comment && c == '#' {
558                in_comment = true;
559            } else if in_comment && c == '\n' {
560                in_comment = false;
561            } else {
562                start += i;
563                break;
564            }
565        }
566        self.pattern()[start..].chars().next()
567    }
568
569    /// Returns true if the next call to `bump` would return false.
570    fn is_eof(&self) -> bool {
571        self.offset() == self.pattern().len()
572    }
573
574    /// Return the current position of the parser, which includes the offset,
575    /// line and column.
576    fn pos(&self) -> Position {
577        self.parser().pos.get()
578    }
579
580    /// Create a span at the current position of the parser. Both the start
581    /// and end of the span are set.
582    fn span(&self) -> Span {
583        Span::splat(self.pos())
584    }
585
586    /// Create a span that covers the current character.
587    fn span_char(&self) -> Span {
588        let mut next = Position {
589            offset: self.offset().checked_add(self.char().len_utf8()).unwrap(),
590            line: self.line(),
591            column: self.column().checked_add(1).unwrap(),
592        };
593        if self.char() == '\n' {
594            next.line += 1;
595            next.column = 1;
596        }
597        Span::new(self.pos(), next)
598    }
599
600    /// Parse and push a single alternation on to the parser's internal stack.
601    /// If the top of the stack already has an alternation, then add to that
602    /// instead of pushing a new one.
603    ///
604    /// The concatenation given corresponds to a single alternation branch.
605    /// The concatenation returned starts the next branch and is empty.
606    ///
607    /// This assumes the parser is currently positioned at `|` and will advance
608    /// the parser to the character following `|`.
609    #[inline(never)]
610    fn push_alternate(&self, mut concat: ast::Concat) -> Result<ast::Concat> {
611        assert_eq!(self.char(), '|');
612        concat.span.end = self.pos();
613        self.push_or_add_alternation(concat);
614        self.bump();
615        Ok(ast::Concat {
616            span: self.span(),
617            asts: vec![],
618        })
619    }
620
621    /// Pushes or adds the given branch of an alternation to the parser's
622    /// internal stack of state.
623    fn push_or_add_alternation(&self, concat: Concat) {
624        use self::GroupState::*;
625
626        let mut stack = self.parser().stack_group.borrow_mut();
627        if let Some(&mut Alternation(ref mut alts)) = stack.last_mut() {
628            alts.asts.push(concat.into_ast());
629            return;
630        }
631        stack.push(Alternation(ast::Alternation {
632            span: Span::new(concat.span.start, self.pos()),
633            asts: vec![concat.into_ast()],
634        }));
635    }
636
637    #[inline(never)]
638    fn push_intersect(&self, mut concat: Concat) -> Result<Concat> {
639        assert_eq!(self.char(), '&');
640        concat.span.end = self.pos();
641        self.push_or_add_intersect(concat);
642        self.bump();
643        Ok(Concat {
644            span: self.span(),
645            asts: vec![],
646        })
647    }
648
649    /// Pushes or adds the given branch of an alternation to the parser's
650    /// internal stack of state.
651    fn push_or_add_intersect(&self, concat: Concat) {
652        use self::GroupState::*;
653
654        let mut stack = self.parser().stack_group.borrow_mut();
655        if let Some(&mut Intersection(ref mut alts)) = stack.last_mut() {
656            alts.asts.push(concat.into_ast());
657            return;
658        }
659        stack.push(Intersection(ast::Intersection {
660            span: Span::new(concat.span.start, self.pos()),
661            asts: vec![concat.into_ast()],
662        }));
663    }
664
665    /// Parse and push a group AST (and its parent concatenation) on to the
666    /// parser's internal stack. Return a fresh concatenation corresponding
667    /// to the group's sub-AST.
668    ///
669    /// If a set of flags was found (with no group), then the concatenation
670    /// is returned with that set of flags added.
671    ///
672    /// This assumes that the parser is currently positioned on the opening
673    /// parenthesis. It advances the parser to the character at the start
674    /// of the sub-expression (or adjoining expression).
675    ///
676    /// If there was a problem parsing the start of the group, then an error
677    /// is returned.
678    #[inline(never)]
679    fn push_group(&self, mut concat: Concat) -> Result<Concat> {
680        assert_eq!(self.char(), '(');
681        match self.parse_group()? {
682            Either::Left(set) => {
683                let ignore = set.flags.flag_state(ast::Flag::IgnoreWhitespace);
684                if let Some(v) = ignore {
685                    self.parser().ignore_whitespace.set(v);
686                }
687
688                concat.asts.push(Ast::flags(set));
689                Ok(concat)
690            }
691            Either::Right(group) => {
692                let old_ignore_whitespace = self.ignore_whitespace();
693                let new_ignore_whitespace = group
694                    .flags()
695                    .and_then(|f| f.flag_state(ast::Flag::IgnoreWhitespace))
696                    .unwrap_or(old_ignore_whitespace);
697                self.parser()
698                    .stack_group
699                    .borrow_mut()
700                    .push(GroupState::Group {
701                        concat,
702                        group,
703                        ignore_whitespace: old_ignore_whitespace,
704                    });
705                self.parser().ignore_whitespace.set(new_ignore_whitespace);
706                Ok(Concat {
707                    span: self.span(),
708                    asts: vec![],
709                })
710            }
711        }
712    }
713
714    #[inline(never)]
715    fn push_compl_group(&self, concat: Concat) -> Result<Concat> {
716        assert_eq!(self.char(), '~');
717        self.bump();
718        if self.is_eof() || self.char() != '(' {
719            return Err(self.error(self.span(), ast::ErrorKind::ComplementGroupExpected));
720        }
721        let open_span = self.span_char();
722        self.bump();
723        let group = ast::Group {
724            span: open_span,
725            kind: ast::GroupKind::Complement,
726            ast: Box::new(Ast::empty(self.span())),
727        };
728
729        let old_ignore_whitespace = self.ignore_whitespace();
730        let new_ignore_whitespace = group
731            .flags()
732            .and_then(|f| f.flag_state(ast::Flag::IgnoreWhitespace))
733            .unwrap_or(old_ignore_whitespace);
734        self.parser()
735            .stack_group
736            .borrow_mut()
737            .push(GroupState::Group {
738                concat,
739                group,
740                ignore_whitespace: old_ignore_whitespace,
741            });
742        self.parser().ignore_whitespace.set(new_ignore_whitespace);
743        Ok(Concat {
744            span: self.span(),
745            asts: vec![],
746        })
747    }
748
749    /// Pop a group AST from the parser's internal stack and set the group's
750    /// AST to the given concatenation. Return the concatenation containing
751    /// the group.
752    ///
753    /// This assumes that the parser is currently positioned on the closing
754    /// parenthesis and advances the parser to the character following the `)`.
755    ///
756    /// If no such group could be popped, then an unopened group error is
757    /// returned.
758    #[inline(never)]
759    fn pop_group(&self, mut group_concat: Concat) -> Result<Concat> {
760        use self::GroupState::*;
761        assert_eq!(self.char(), ')');
762        let mut stack = self.parser().stack_group.borrow_mut();
763        let topstack = stack.pop();
764
765        let (mut prior_concat, mut group, ignore_whitespace, alt) = match topstack {
766            Some(Group {
767                concat,
768                group,
769                ignore_whitespace,
770            }) => (concat, group, ignore_whitespace, None),
771            Some(Alternation(alt)) => match stack.pop() {
772                Some(Group {
773                    concat,
774                    group,
775                    ignore_whitespace,
776                }) => (
777                    concat,
778                    group,
779                    ignore_whitespace,
780                    Some(Either::Left::<ast::Alternation, ast::Intersection>(alt)),
781                ),
782                None | Some(Alternation(_)) | Some(Intersection(_)) => {
783                    return Err(self.error(self.span_char(), ast::ErrorKind::GroupUnopened));
784                }
785            },
786            Some(Intersection(int)) => match stack.pop() {
787                Some(Group {
788                    concat,
789                    group,
790                    ignore_whitespace,
791                }) => (
792                    concat,
793                    group,
794                    ignore_whitespace,
795                    Some(Either::Right::<ast::Alternation, ast::Intersection>(int)),
796                ),
797                None | Some(Alternation(_)) | Some(Intersection(_)) => {
798                    return Err(self.error(self.span_char(), ast::ErrorKind::GroupUnopened));
799                }
800            },
801
802            None => {
803                return Err(self.error(self.span_char(), ast::ErrorKind::GroupUnopened));
804            }
805        };
806        self.parser().ignore_whitespace.set(ignore_whitespace);
807        group_concat.span.end = self.pos();
808        self.bump();
809        group.span.end = self.pos();
810        match alt {
811            Some(Either::Left(mut alt)) => {
812                alt.span.end = group_concat.span.end;
813                alt.asts.push(group_concat.into_ast());
814                group.ast = Box::new(alt.into_ast());
815            }
816            Some(Either::Right(mut int)) => {
817                int.span.end = group_concat.span.end;
818                int.asts.push(group_concat.into_ast());
819                group.ast = Box::new(int.into_ast());
820            }
821            None => {
822                group.ast = Box::new(group_concat.into_ast());
823            }
824        }
825
826        if group.kind == GroupKind::Complement {
827            let complement = ast::Complement {
828                span: self.span(),
829                ast: group.ast,
830            };
831            prior_concat.asts.push(Ast::complement(complement));
832        }
833        // ignore groups for now
834        else {
835            prior_concat.asts.push(Ast::group(group));
836        }
837        Ok(prior_concat)
838    }
839
840    /// Pop the last state from the parser's internal stack, if it exists, and
841    /// add the given concatenation to it. There either must be no state or a
842    /// single alternation item on the stack. Any other scenario produces an
843    /// error.
844    ///
845    /// This assumes that the parser has advanced to the end.
846    #[inline(never)]
847    fn pop_group_end(&self, mut concat: ast::Concat) -> Result<Ast> {
848        concat.span.end = self.pos();
849        let mut stack = self.parser().stack_group.borrow_mut();
850        let ast = match stack.pop() {
851            None => Ok(concat.into_ast()),
852            Some(GroupState::Alternation(mut alt)) => {
853                alt.span.end = self.pos();
854                alt.asts.push(concat.into_ast());
855                Ok(Ast::alternation(alt))
856            }
857            Some(GroupState::Intersection(mut int)) => {
858                int.span.end = self.pos();
859                int.asts.push(concat.into_ast());
860
861                Ok(Ast::intersection(int))
862            }
863            Some(GroupState::Group { group, .. }) => {
864                return Err(self.error(group.span, ast::ErrorKind::GroupUnclosed));
865            }
866        };
867        // If we try to pop again, there should be nothing.
868        match stack.pop() {
869            None => ast,
870            Some(GroupState::Alternation(_)) => {
871                // This unreachable is unfortunate. This case can't happen
872                // because the only way we can be here is if there were two
873                // `GroupState::Alternation`s adjacent in the parser's stack,
874                // which we guarantee to never happen because we never push a
875                // `GroupState::Alternation` if one is already at the top of
876                // the stack.
877                unreachable!()
878            }
879            Some(GroupState::Intersection(_)) => {
880                unreachable!()
881            }
882            Some(GroupState::Group { group, .. }) => {
883                Err(self.error(group.span, ast::ErrorKind::GroupUnclosed))
884            }
885        }
886    }
887
888    /// Parse the opening of a character class and push the current class
889    /// parsing context onto the parser's stack. This assumes that the parser
890    /// is positioned at an opening `[`. The given union should correspond to
891    /// the union of set items built up before seeing the `[`.
892    ///
893    /// If there was a problem parsing the opening of the class, then an error
894    /// is returned. Otherwise, a new union of set items for the class is
895    /// returned (which may be populated with either a `]` or a `-`).
896    #[inline(never)]
897    fn push_class_open(
898        &self,
899        parent_union: regex_syntax::ast::ClassSetUnion,
900    ) -> Result<regex_syntax::ast::ClassSetUnion> {
901        assert_eq!(self.char(), '[');
902
903        let (nested_set, nested_union) = self.parse_set_class_open()?;
904        self.parser()
905            .stack_class
906            .borrow_mut()
907            .push(ClassState::Open {
908                union: parent_union,
909                set: nested_set,
910            });
911        Ok(nested_union)
912    }
913
914    /// Parse the end of a character class set and pop the character class
915    /// parser stack. The union given corresponds to the last union built
916    /// before seeing the closing `]`. The union returned corresponds to the
917    /// parent character class set with the nested class added to it.
918    ///
919    /// This assumes that the parser is positioned at a `]` and will advance
920    /// the parser to the byte immediately following the `]`.
921    ///
922    /// If the stack is empty after popping, then this returns the final
923    /// "top-level" character class AST (where a "top-level" character class
924    /// is one that is not nested inside any other character class).
925    ///
926    /// If there is no corresponding opening bracket on the parser's stack,
927    /// then an error is returned.
928    #[inline(never)]
929    fn pop_class(
930        &self,
931        nested_union: regex_syntax::ast::ClassSetUnion,
932    ) -> Result<Either<regex_syntax::ast::ClassSetUnion, regex_syntax::ast::ClassBracketed>> {
933        assert_eq!(self.char(), ']');
934
935        let item = regex_syntax::ast::ClassSet::Item(nested_union.into_item());
936        let prevset = self.pop_class_op(item);
937        let mut stack = self.parser().stack_class.borrow_mut();
938        match stack.pop() {
939            None => {
940                // We can never observe an empty stack:
941                //
942                // 1) We are guaranteed to start with a non-empty stack since
943                //    the character class parser is only initiated when it sees
944                //    a `[`.
945                // 2) If we ever observe an empty stack while popping after
946                //    seeing a `]`, then we signal the character class parser
947                //    to terminate.
948                panic!("unexpected empty character class stack")
949            }
950            Some(ClassState::Op { .. }) => {
951                // This panic is unfortunate, but this case is impossible
952                // since we already popped the Op state if one exists above.
953                // Namely, every push to the class parser stack is guarded by
954                // whether an existing Op is already on the top of the stack.
955                // If it is, the existing Op is modified. That is, the stack
956                // can never have consecutive Op states.
957                panic!("unexpected ClassState::Op")
958            }
959            Some(ClassState::Open { mut union, mut set }) => {
960                self.bump();
961                set.span.end = self.pos();
962                set.kind = prevset;
963                if stack.is_empty() {
964                    Ok(Either::Right(set))
965                } else {
966                    union.push(regex_syntax::ast::ClassSetItem::Bracketed(Box::new(set)));
967                    Ok(Either::Left(union))
968                }
969            }
970        }
971    }
972
973    /// Return an "unclosed class" error whose span points to the most
974    /// recently opened class.
975    ///
976    /// This should only be called while parsing a character class.
977    #[inline(never)]
978    fn unclosed_class_error(&self) -> ResharpError {
979        for state in self.parser().stack_class.borrow().iter().rev() {
980            if let ClassState::Open { ref set, .. } = *state {
981                return self.error(set.span, ast::ErrorKind::ClassUnclosed);
982            }
983        }
984        // We are guaranteed to have a non-empty stack with at least
985        // one open bracket, so we should never get here.
986        panic!("no open character class found")
987    }
988
989    /// Push the current set of class items on to the class parser's stack as
990    /// the left hand side of the given operator.
991    ///
992    /// A fresh set union is returned, which should be used to build the right
993    /// hand side of this operator.
994    #[inline(never)]
995    fn push_class_op(
996        &self,
997        next_kind: regex_syntax::ast::ClassSetBinaryOpKind,
998        next_union: regex_syntax::ast::ClassSetUnion,
999    ) -> regex_syntax::ast::ClassSetUnion {
1000        let item = regex_syntax::ast::ClassSet::Item(next_union.into_item());
1001        let new_lhs = self.pop_class_op(item);
1002        self.parser().stack_class.borrow_mut().push(ClassState::Op {
1003            kind: next_kind,
1004            lhs: new_lhs,
1005        });
1006        regex_syntax::ast::ClassSetUnion {
1007            span: self.span(),
1008            items: vec![],
1009        }
1010    }
1011
1012    /// Pop a character class set from the character class parser stack. If the
1013    /// top of the stack is just an item (not an operation), then return the
1014    /// given set unchanged. If the top of the stack is an operation, then the
1015    /// given set will be used as the rhs of the operation on the top of the
1016    /// stack. In that case, the binary operation is returned as a set.
1017    #[inline(never)]
1018    fn pop_class_op(&self, rhs: regex_syntax::ast::ClassSet) -> regex_syntax::ast::ClassSet {
1019        let mut stack = self.parser().stack_class.borrow_mut();
1020        let (kind, lhs) = match stack.pop() {
1021            Some(ClassState::Op { kind, lhs }) => (kind, lhs),
1022            Some(state @ ClassState::Open { .. }) => {
1023                stack.push(state);
1024                return rhs;
1025            }
1026            None => unreachable!(),
1027        };
1028        let span = Span::new(lhs.span().start, rhs.span().end);
1029        regex_syntax::ast::ClassSet::BinaryOp(regex_syntax::ast::ClassSetBinaryOp {
1030            span,
1031            kind,
1032            lhs: Box::new(lhs),
1033            rhs: Box::new(rhs),
1034        })
1035    }
1036
1037    fn hir_to_node_id(&self, hir: &hir::Hir, tb: &mut TB<'s>) -> Result<NodeId> {
1038        match hir.kind() {
1039            hir::HirKind::Empty => Ok(NodeId::EPS),
1040            hir::HirKind::Literal(l) => {
1041                if l.0.len() == 1 {
1042                    let node = tb.mk_u8(l.0[0]);
1043                    Ok(node)
1044                } else {
1045                    let ws: Vec<_> = l.0.iter().map(|l| tb.mk_u8(*l)).collect();
1046                    let conc = tb.mk_concats(ws.iter().copied());
1047                    Ok(conc)
1048                }
1049            }
1050            hir::HirKind::Class(class) => match class {
1051                hir::Class::Unicode(class_unicode) => {
1052                    let ranges = class_unicode.ranges();
1053                    let mut nodes = Vec::new();
1054                    for range in ranges {
1055                        for seq in Utf8Sequences::new(range.start(), range.end()) {
1056                            let sl = seq.as_slice();
1057                            let bytes: Vec<_> = sl.iter().map(|s| (s.start, s.end)).collect();
1058                            let node = match bytes.len() {
1059                                1 => tb.mk_range_u8(bytes[0].0, bytes[0].1),
1060                                n => {
1061                                    let last = tb.mk_range_u8(bytes[n - 1].0, bytes[n - 1].1);
1062                                    let mut conc = last;
1063                                    for i in (0..n - 1).rev() {
1064                                        let b = tb.mk_range_u8(bytes[i].0, bytes[i].1);
1065                                        conc = tb.mk_concat(b, conc);
1066                                    }
1067                                    conc
1068                                }
1069                            };
1070                            nodes.push(node);
1071                        }
1072                    }
1073                    let merged = tb.mk_unions(nodes.into_iter());
1074                    Ok(merged)
1075                }
1076                hir::Class::Bytes(class_bytes) => {
1077                    let ranges = class_bytes.ranges();
1078                    let mut result = NodeId::BOT;
1079                    for range in ranges {
1080                        let start = range.start();
1081                        let end = range.end();
1082                        let node = tb.mk_range_u8(start, end);
1083                        result = tb.mk_union(result, node);
1084                    }
1085                    Ok(result)
1086                }
1087            },
1088            hir::HirKind::Look(_) => Err(self.error(
1089                Span::splat(self.pos()),
1090                ast::ErrorKind::UnsupportedResharpRegex,
1091            )),
1092            hir::HirKind::Repetition(_) => Err(self.error(
1093                Span::splat(self.pos()),
1094                ast::ErrorKind::UnsupportedResharpRegex,
1095            )),
1096            hir::HirKind::Capture(_) => Err(self.error(
1097                Span::splat(self.pos()),
1098                ast::ErrorKind::UnsupportedResharpRegex,
1099            )),
1100            hir::HirKind::Concat(body) => {
1101                let mut result = NodeId::EPS;
1102                for child in body {
1103                    let node = self.hir_to_node_id(child, tb)?;
1104                    result = tb.mk_concat(result, node);
1105                }
1106                Ok(result)
1107            }
1108            hir::HirKind::Alternation(_) => Err(self.error(
1109                Span::splat(self.pos()),
1110                ast::ErrorKind::UnsupportedResharpRegex,
1111            )),
1112        }
1113    }
1114
1115    fn translate_ast_to_hir(
1116        &mut self,
1117        orig_ast: &regex_syntax::ast::Ast,
1118        tb: &mut TB<'s>,
1119    ) -> Result<NodeId> {
1120        match self.translator.translate("", orig_ast) {
1121            Err(_) => Err(self.error(self.span(), ast::ErrorKind::UnicodeClassInvalid)),
1122            Ok(hir) => self.hir_to_node_id(&hir, tb),
1123        }
1124    }
1125
1126    fn translator_to_node_id(
1127        &mut self,
1128        orig_ast: &regex_syntax::ast::Ast,
1129        translator: &mut Option<Translator>,
1130        tb: &mut TB<'s>,
1131    ) -> Result<NodeId> {
1132        match translator {
1133            Some(tr) => {
1134                let hir = tr
1135                    .translate("", orig_ast)
1136                    .map_err(|e| self.unsupported_error(e))?;
1137                self.hir_to_node_id(&hir, tb)
1138            }
1139            None => self.translate_ast_to_hir(orig_ast, tb),
1140        }
1141    }
1142
1143    fn get_class(
1144        &mut self,
1145        negated: bool,
1146        kind: regex_syntax::ast::ClassPerlKind,
1147        tb: &mut TB<'s>,
1148    ) -> Result<NodeId> {
1149        let w = self
1150            .perl_classes
1151            .iter()
1152            .find(|(c_neg, c_kind, _)| *c_kind == kind && *c_neg == negated);
1153        match w {
1154            Some((_, _, value)) => Ok(*value),
1155            None => {
1156                let translated = if self.global_unicode {
1157                    match kind {
1158                        regex_syntax::ast::ClassPerlKind::Word => {
1159                            if self.global_full_unicode {
1160                                self.unicode_classes.ensure_word_full(tb);
1161                            } else {
1162                                self.unicode_classes.ensure_word(tb);
1163                            }
1164                            if negated {
1165                                self.unicode_classes.non_word
1166                            } else {
1167                                self.unicode_classes.word
1168                            }
1169                        }
1170                        regex_syntax::ast::ClassPerlKind::Digit => {
1171                            if self.global_full_unicode {
1172                                self.unicode_classes.ensure_digit_full(tb);
1173                            } else {
1174                                self.unicode_classes.ensure_digit(tb);
1175                            }
1176                            if negated {
1177                                self.unicode_classes.non_digit
1178                            } else {
1179                                self.unicode_classes.digit
1180                            }
1181                        }
1182                        regex_syntax::ast::ClassPerlKind::Space => {
1183                            self.unicode_classes.ensure_space(tb);
1184                            if negated {
1185                                self.unicode_classes.non_space
1186                            } else {
1187                                self.unicode_classes.space
1188                            }
1189                        }
1190                    }
1191                } else {
1192                    let pos = match kind {
1193                        regex_syntax::ast::ClassPerlKind::Word => {
1194                            let az = tb.mk_range_u8(b'a', b'z');
1195                            let big = tb.mk_range_u8(b'A', b'Z');
1196                            let dig = tb.mk_range_u8(b'0', b'9');
1197                            let us = tb.mk_u8(b'_');
1198                            tb.mk_unions([az, big, dig, us].into_iter())
1199                        }
1200                        regex_syntax::ast::ClassPerlKind::Digit => tb.mk_range_u8(b'0', b'9'),
1201                        regex_syntax::ast::ClassPerlKind::Space => {
1202                            let sp = tb.mk_u8(b' ');
1203                            let tab = tb.mk_u8(b'\t');
1204                            let nl = tb.mk_u8(b'\n');
1205                            let cr = tb.mk_u8(b'\r');
1206                            let ff = tb.mk_u8(0x0C);
1207                            let vt = tb.mk_u8(0x0B);
1208                            tb.mk_unions([sp, tab, nl, cr, ff, vt].into_iter())
1209                        }
1210                    };
1211                    if negated {
1212                        tb.mk_compl(pos)
1213                    } else {
1214                        pos
1215                    }
1216                };
1217                self.perl_classes.push((negated, kind, translated));
1218                Ok(translated)
1219            }
1220        }
1221    }
1222
1223    fn word_char_kind(ast: &Ast, left: bool) -> WordCharKind {
1224        use WordCharKind::*;
1225        match ast {
1226            Ast::Literal(lit) => {
1227                if is_word_byte(lit.c as u8) {
1228                    Word
1229                } else {
1230                    NonWord
1231                }
1232            }
1233            Ast::ClassPerl(c) => match (&c.kind, c.negated) {
1234                (&regex_syntax::ast::ClassPerlKind::Word, false) => Word,
1235                (&regex_syntax::ast::ClassPerlKind::Word, true) => NonWord,
1236                (&regex_syntax::ast::ClassPerlKind::Space, false) => NonWord,
1237                (&regex_syntax::ast::ClassPerlKind::Space, true) => Unknown,
1238                (&regex_syntax::ast::ClassPerlKind::Digit, false) => Word,
1239                (&regex_syntax::ast::ClassPerlKind::Digit, true) => Unknown,
1240            },
1241            Ast::Dot(_) | Ast::Top(_) => Unknown,
1242            Ast::Group(g) => Self::word_char_kind(&g.ast, left),
1243            Ast::Concat(c) if !c.asts.is_empty() => {
1244                let edge = if left { c.asts.len() - 1 } else { 0 };
1245                let kind = Self::word_char_kind(&c.asts[edge], left);
1246                match kind {
1247                    MaybeWord => {
1248                        let dir: isize = if left { -1 } else { 1 };
1249                        match Self::concat_neighbor_kind(&c.asts, edge, dir) {
1250                            Word => Word,
1251                            _ => MaybeWord,
1252                        }
1253                    }
1254                    MaybeNonWord => {
1255                        let dir: isize = if left { -1 } else { 1 };
1256                        match Self::concat_neighbor_kind(&c.asts, edge, dir) {
1257                            NonWord => NonWord,
1258                            _ => MaybeNonWord,
1259                        }
1260                    }
1261                    other => other,
1262                }
1263            }
1264            Ast::Alternation(alt) if !alt.asts.is_empty() => {
1265                let first = Self::word_char_kind(&alt.asts[0], left);
1266                if alt.asts[1..]
1267                    .iter()
1268                    .all(|a| Self::word_char_kind(a, left) == first)
1269                {
1270                    first
1271                } else {
1272                    Unknown
1273                }
1274            }
1275            Ast::Repetition(r) => {
1276                let inner = Self::word_char_kind(&r.ast, left);
1277                let nullable = matches!(
1278                    &r.op.kind,
1279                    ast::RepetitionKind::ZeroOrMore
1280                        | ast::RepetitionKind::ZeroOrOne
1281                        | ast::RepetitionKind::Range(ast::RepetitionRange::Bounded(0, _))
1282                );
1283                if nullable {
1284                    match inner {
1285                        Word => MaybeWord,
1286                        NonWord => MaybeNonWord,
1287                        _ => Unknown,
1288                    }
1289                } else {
1290                    inner
1291                }
1292            }
1293            Ast::Lookaround(la) => Self::word_char_kind(&la.ast, left),
1294            _ => Unknown,
1295        }
1296    }
1297
1298    fn edge_class_ast(ast: &Ast, left: bool) -> Option<&Ast> {
1299        match ast {
1300            Ast::Literal(_)
1301            | Ast::ClassPerl(_)
1302            | Ast::ClassBracketed(_)
1303            | Ast::ClassUnicode(_)
1304            | Ast::Dot(_)
1305            | Ast::Top(_) => Some(ast),
1306            Ast::Group(g) => Self::edge_class_ast(&g.ast, left),
1307            Ast::Concat(c) if !c.asts.is_empty() => {
1308                Self::edge_class_ast(&c.asts[if left { c.asts.len() - 1 } else { 0 }], left)
1309            }
1310            Ast::Repetition(r) => Self::edge_class_ast(&r.ast, left),
1311            Ast::Lookaround(la) => Self::edge_class_ast(&la.ast, left),
1312            _ => None,
1313        }
1314    }
1315
1316    fn resolve_word_kind(
1317        &mut self,
1318        asts: &[Ast],
1319        idx: usize,
1320        dir: isize,
1321        translator: &mut Option<Translator>,
1322        tb: &mut TB<'s>,
1323        word_id: NodeId,
1324        not_word_id: NodeId,
1325    ) -> Result<WordCharKind> {
1326        use WordCharKind::*;
1327        let fast = Self::concat_neighbor_kind(asts, idx, dir);
1328        if fast != Unknown {
1329            return Ok(fast);
1330        }
1331        let neighbor_idx = (idx as isize + dir) as usize;
1332        let node = if let Some(edge) = Self::edge_class_ast(&asts[neighbor_idx], dir < 0) {
1333            self.ast_to_node_id(edge, translator, tb)?
1334        } else {
1335            // check if \w_* (starts-with-word) or \W_* (starts-with-non-word) subsumes it.
1336            let neighbor_node = self.ast_to_node_id(&asts[neighbor_idx], translator, tb)?;
1337            let word_prefix = if dir > 0 {
1338                tb.mk_concat(word_id, NodeId::TS)
1339            } else {
1340                tb.mk_concat(NodeId::TS, word_id)
1341            };
1342            let non_word_prefix = if dir > 0 {
1343                tb.mk_concat(not_word_id, NodeId::TS)
1344            } else {
1345                tb.mk_concat(NodeId::TS, not_word_id)
1346            };
1347            return if tb.subsumes(word_prefix, neighbor_node) == Some(true) {
1348                Ok(Word)
1349            } else if tb.subsumes(non_word_prefix, neighbor_node) == Some(true) {
1350                Ok(NonWord)
1351            } else {
1352                Ok(Unknown)
1353            };
1354        };
1355        if tb.subsumes(word_id, node) == Some(true) {
1356            Ok(Word)
1357        } else if tb.subsumes(not_word_id, node) == Some(true) {
1358            Ok(NonWord)
1359        } else {
1360            Ok(Unknown)
1361        }
1362    }
1363
1364    fn concat_neighbor_kind(asts: &[Ast], idx: usize, dir: isize) -> WordCharKind {
1365        use WordCharKind::*;
1366        let next = idx as isize + dir;
1367        if next < 0 || next >= asts.len() as isize {
1368            return Edge;
1369        }
1370        let kind = Self::word_char_kind(&asts[next as usize], dir < 0);
1371        match kind {
1372            MaybeWord => match Self::concat_neighbor_kind(asts, next as usize, dir) {
1373                Word => Word,
1374                _ => Unknown,
1375            },
1376            MaybeNonWord => match Self::concat_neighbor_kind(asts, next as usize, dir) {
1377                NonWord => NonWord,
1378                _ => Unknown,
1379            },
1380            other => other,
1381        }
1382    }
1383
1384    fn rewrite_word_boundary_in_concat(
1385        &mut self,
1386        asts: &[Ast],
1387        idx: usize,
1388        translator: &mut Option<Translator>,
1389        tb: &mut TB<'s>,
1390    ) -> Result<(NodeId, usize)> {
1391        use WordCharKind::*;
1392        let (word_id, not_word_id) = if self.global_full_unicode {
1393            self.unicode_classes.ensure_word_full(tb);
1394            (self.unicode_classes.word, self.unicode_classes.non_word)
1395        } else if self.global_unicode {
1396            self.unicode_classes.ensure_word(tb);
1397            (self.unicode_classes.word, self.unicode_classes.non_word)
1398        } else {
1399            let az = tb.mk_range_u8(b'a', b'z');
1400            let big = tb.mk_range_u8(b'A', b'Z');
1401            let dig = tb.mk_range_u8(b'0', b'9');
1402            let us = tb.mk_u8(b'_');
1403            let w = tb.mk_unions([az, big, dig, us].into_iter());
1404            (w, tb.mk_compl(w))
1405        };
1406        let left = self.resolve_word_kind(asts, idx, -1, translator, tb, word_id, not_word_id)?;
1407        let right = self.resolve_word_kind(asts, idx, 1, translator, tb, word_id, not_word_id)?;
1408
1409        match (left, right) {
1410            (NonWord, Word) | (Word, NonWord) => Ok((NodeId::EPS, idx + 1)),
1411            (Word, _) => {
1412                let neg = tb.mk_neg_lookahead(word_id, 0);
1413                Ok((neg, idx + 1))
1414            }
1415            (NonWord, _) => {
1416                let set = tb.mk_union(NodeId::END, word_id);
1417                let tail = tb.mk_concat(set, NodeId::TS);
1418                self.merge_boundary_with_following_lookaheads(asts, idx, tail, translator, tb)
1419            }
1420            (_, Word) => Ok((tb.mk_neg_lookbehind(word_id), idx + 1)),
1421            (_, NonWord) => {
1422                let body = tb.mk_union(NodeId::BEGIN, word_id);
1423                Ok((tb.mk_lookbehind(body, NodeId::MISSING), idx + 1))
1424            }
1425            // TODO: (Unknown, Unknown) is possible via make_full_word_boundary but
1426            // the full expansion (lb(\w)·la(\W) | lb(\W)·la(\w)) is too expensive
1427            // reimplement once/if the builder is more optimized
1428            _ => Err(self.error(self.span(), ast::ErrorKind::UnsupportedResharpRegex)),
1429        }
1430    }
1431
1432    fn merge_boundary_with_following_lookaheads(
1433        &mut self,
1434        asts: &[Ast],
1435        wb_idx: usize,
1436        boundary_tail: NodeId,
1437        translator: &mut Option<Translator>,
1438        tb: &mut TB<'s>,
1439    ) -> Result<(NodeId, usize)> {
1440        let mut next = wb_idx + 1;
1441        let mut la_bodies = vec![boundary_tail];
1442        while next < asts.len() {
1443            match &asts[next] {
1444                Ast::Lookaround(la) if la.kind == ast::LookaroundKind::PositiveLookahead => {
1445                    let body = self.ast_to_node_id(&la.ast, translator, tb)?;
1446                    la_bodies.push(tb.mk_concat(body, NodeId::TS));
1447                    next += 1;
1448                }
1449                _ => break,
1450            }
1451        }
1452        let merged = tb.mk_inters(la_bodies.into_iter());
1453        Ok((tb.mk_lookahead(merged, NodeId::MISSING, 0), next))
1454    }
1455
1456    fn ast_to_node_id(
1457        &mut self,
1458        ast: &Ast,
1459        translator: &mut Option<Translator>,
1460        tb: &mut TB<'s>,
1461    ) -> Result<NodeId> {
1462        match ast {
1463            Ast::Empty(_) => Ok(NodeId::EPS),
1464            Ast::Flags(f) => {
1465                let mut translator_builder = self.default_translator_builder();
1466                if let Some(state) = f.flags.flag_state(ast::Flag::CaseInsensitive) {
1467                    translator_builder.case_insensitive(state);
1468                }
1469                if let Some(state) = f.flags.flag_state(ast::Flag::Unicode) {
1470                    translator_builder.unicode(state);
1471                }
1472                if let Some(state) = f.flags.flag_state(ast::Flag::DotMatchesNewLine) {
1473                    self.dot_all.set(state);
1474                }
1475                let concat_translator = Some(translator_builder.build());
1476                *translator = concat_translator;
1477                Ok(NodeId::EPS)
1478            }
1479            Ast::Literal(l) => {
1480                let ast_lit = regex_syntax::ast::Ast::literal(*l.to_owned());
1481                self.translator_to_node_id(&ast_lit, translator, tb)
1482            }
1483            Ast::Top(_) => Ok(NodeId::TOP),
1484            Ast::Dot(_) => {
1485                if self.dot_all.get() {
1486                    Ok(NodeId::TOP)
1487                } else {
1488                    let hirv = hir::Hir::dot(hir::Dot::AnyByteExceptLF);
1489                    self.hir_to_node_id(&hirv, tb)
1490                }
1491            }
1492            Ast::Assertion(a) => match &a.kind {
1493                ast::AssertionKind::StartText => Ok(NodeId::BEGIN),
1494                ast::AssertionKind::EndText => Ok(NodeId::END),
1495                ast::AssertionKind::WordBoundary => {
1496                    Err(self.error(self.span(), ast::ErrorKind::UnsupportedResharpRegex))
1497                }
1498                ast::AssertionKind::NotWordBoundary => {
1499                    Err(self.error(self.span(), ast::ErrorKind::UnsupportedResharpRegex))
1500                }
1501                ast::AssertionKind::StartLine => {
1502                    let left = NodeId::BEGIN;
1503                    let right = tb.mk_u8(b'\n');
1504                    let union = tb.mk_union(left, right);
1505                    Ok(tb.mk_lookbehind(union, NodeId::MISSING))
1506                }
1507                ast::AssertionKind::EndLine => {
1508                    let left = NodeId::END;
1509                    let right = tb.mk_u8(b'\n');
1510                    let union = tb.mk_union(left, right);
1511                    Ok(tb.mk_lookahead(union, NodeId::MISSING, 0))
1512                }
1513                ast::AssertionKind::WordBoundaryStart => {
1514                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1515                }
1516                ast::AssertionKind::WordBoundaryEnd => {
1517                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1518                }
1519                ast::AssertionKind::WordBoundaryStartAngle => {
1520                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1521                }
1522                ast::AssertionKind::WordBoundaryEndAngle => {
1523                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1524                }
1525                ast::AssertionKind::WordBoundaryStartHalf => {
1526                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1527                }
1528                ast::AssertionKind::WordBoundaryEndHalf => {
1529                    Err(self.error(a.span, ast::ErrorKind::UnsupportedResharpRegex))
1530                }
1531            },
1532            Ast::ClassUnicode(c) => {
1533                let tmp = regex_syntax::ast::ClassUnicode {
1534                    span: c.span,
1535                    negated: c.negated,
1536                    kind: c.kind.clone(),
1537                };
1538                if !c.negated {
1539                    if let regex_syntax::ast::ClassUnicodeKind::Named(s) = &c.kind {
1540                        match s.as_str() {
1541                            // \p{ascii} for ascii, \p{ascii}&\p{Letter} => [A-Za-z]
1542                            "ascii" => return Ok(tb.mk_range_u8(0, 127)),
1543                            // restricts matches to valid utf8, \p{utf8}*&~(a) => non a, but valid utf8
1544                            "utf8" => {
1545                                let ascii = tb.mk_range_u8(0, 127);
1546                                let beta = tb.mk_range_u8(128, 0xBF);
1547                                let c0 = tb.mk_range_u8(0xC0, 0xDF);
1548                                let c0s = tb.mk_concats([c0, beta].into_iter());
1549                                let e0 = tb.mk_range_u8(0xE0, 0xEF);
1550                                let e0s = tb.mk_concats([e0, beta, beta].into_iter());
1551                                let f0 = tb.mk_range_u8(0xF0, 0xF7);
1552                                let f0s = tb.mk_concats([f0, beta, beta, beta].into_iter());
1553                                let merged = tb.mk_unions([ascii, c0s, e0s, f0s].into_iter());
1554                                return Ok(tb.mk_star(merged));
1555                            }
1556                            "hex" => {
1557                                let nums = tb.mk_range_u8(b'0', b'9');
1558                                let lets = tb.mk_range_u8(b'a', b'f');
1559                                let lets2 = tb.mk_range_u8(b'A', b'F');
1560                                let merged = tb.mk_unions([nums, lets, lets2].into_iter());
1561                                return Ok(merged);
1562                            }
1563                            _ => {}
1564                        }
1565                    };
1566                }
1567
1568                let orig_ast = regex_syntax::ast::Ast::class_unicode(tmp);
1569                self.translator_to_node_id(&orig_ast, translator, tb)
1570            }
1571            Ast::ClassPerl(c) => self.get_class(c.negated, c.kind.clone(), tb),
1572            Ast::ClassBracketed(c) => match &c.kind {
1573                regex_syntax::ast::ClassSet::Item(_) => {
1574                    let tmp = regex_syntax::ast::ClassBracketed {
1575                        span: c.span,
1576                        negated: c.negated,
1577                        kind: c.kind.clone(),
1578                    };
1579                    let orig_ast = regex_syntax::ast::Ast::class_bracketed(tmp);
1580                    self.translator_to_node_id(&orig_ast, translator, tb)
1581                }
1582                regex_syntax::ast::ClassSet::BinaryOp(_) => {
1583                    Err(self.error(c.span, ast::ErrorKind::UnsupportedResharpRegex))
1584                }
1585            },
1586            Ast::Repetition(r) => {
1587                let body = self.ast_to_node_id(&r.ast, translator, tb);
1588                match body {
1589                    Ok(body) => match &r.op.kind {
1590                        ast::RepetitionKind::ZeroOrOne => Ok(tb.mk_opt(body)),
1591                        ast::RepetitionKind::ZeroOrMore => Ok(tb.mk_star(body)),
1592                        ast::RepetitionKind::OneOrMore => Ok(tb.mk_plus(body)),
1593                        ast::RepetitionKind::Range(r) => match r {
1594                            ast::RepetitionRange::Exactly(n) => Ok(tb.mk_repeat(body, *n, *n)),
1595                            ast::RepetitionRange::AtLeast(n) => {
1596                                let rep = tb.mk_repeat(body, *n, *n);
1597                                let st = tb.mk_star(body);
1598                                Ok(tb.mk_concat(rep, st))
1599                            }
1600
1601                            ast::RepetitionRange::Bounded(n, m) => Ok(tb.mk_repeat(body, *n, *m)),
1602                        },
1603                    },
1604                    Err(_) => body,
1605                }
1606            }
1607            Ast::Lookaround(g) => {
1608                let body = self.ast_to_node_id(&g.ast, translator, tb)?;
1609                match g.kind {
1610                    ast::LookaroundKind::PositiveLookahead => {
1611                        Ok(tb.mk_lookahead(body, NodeId::MISSING, 0))
1612                    }
1613                    ast::LookaroundKind::PositiveLookbehind => {
1614                        Ok(tb.mk_lookbehind(body, NodeId::MISSING))
1615                    }
1616                    ast::LookaroundKind::NegativeLookahead => Ok(tb.mk_neg_lookahead(body, 0)),
1617                    ast::LookaroundKind::NegativeLookbehind => Ok(tb.mk_neg_lookbehind(body)),
1618                }
1619            }
1620            Ast::Group(g) => {
1621                if let ast::GroupKind::NonCapturing(ref flags) = g.kind {
1622                    if !flags.items.is_empty() {
1623                        let mut translator_builder = self.default_translator_builder();
1624                        if let Some(state) = flags.flag_state(ast::Flag::CaseInsensitive) {
1625                            translator_builder.case_insensitive(state);
1626                        }
1627                        if let Some(state) = flags.flag_state(ast::Flag::Unicode) {
1628                            translator_builder.unicode(state);
1629                        }
1630                        let saved_dot_all = self.dot_all.get();
1631                        if let Some(state) = flags.flag_state(ast::Flag::DotMatchesNewLine) {
1632                            self.dot_all.set(state);
1633                        }
1634                        let mut scoped = Some(translator_builder.build());
1635                        let result = self.ast_to_node_id(&g.ast, &mut scoped, tb);
1636                        self.dot_all.set(saved_dot_all);
1637                        return result;
1638                    }
1639                }
1640                self.ast_to_node_id(&g.ast, translator, tb)
1641            }
1642            Ast::Alternation(a) => {
1643                let mut children = vec![];
1644                for ast in &a.asts {
1645                    match self.ast_to_node_id(ast, translator, tb) {
1646                        Ok(node_id) => children.push(node_id),
1647                        Err(err) => return Err(err),
1648                    }
1649                }
1650                Ok(tb.mk_unions(children.iter().copied()))
1651            }
1652            Ast::Concat(c) => {
1653                let mut concat_translator: Option<Translator> = None;
1654                let mut children = vec![];
1655                let mut i = 0;
1656                while i < c.asts.len() {
1657                    let ast = &c.asts[i];
1658                    match ast {
1659                        Ast::Flags(f) => {
1660                            let mut translator_builder = self.default_translator_builder();
1661                            if let Some(state) = f.flags.flag_state(ast::Flag::CaseInsensitive) {
1662                                translator_builder.case_insensitive(state);
1663                            }
1664                            if let Some(state) = f.flags.flag_state(ast::Flag::Unicode) {
1665                                translator_builder.unicode(state);
1666                            }
1667                            if let Some(state) = f.flags.flag_state(ast::Flag::DotMatchesNewLine) {
1668                                self.dot_all.set(state);
1669                            }
1670                            concat_translator = Some(translator_builder.build());
1671                            *translator = concat_translator.clone();
1672                            i += 1;
1673                            continue;
1674                        }
1675                        Ast::Assertion(a) if a.kind == ast::AssertionKind::WordBoundary => {
1676                            let node =
1677                                self.rewrite_word_boundary_in_concat(&c.asts, i, translator, tb)?;
1678                            children.push(node.0);
1679                            i = node.1; // skip consumed lookaheads
1680                            continue;
1681                        }
1682                        _ => {}
1683                    }
1684                    match concat_translator {
1685                        Some(_) => match self.ast_to_node_id(ast, &mut concat_translator, tb) {
1686                            Ok(node_id) => children.push(node_id),
1687                            Err(err) => return Err(err),
1688                        },
1689                        None => match self.ast_to_node_id(ast, translator, tb) {
1690                            Ok(node_id) => children.push(node_id),
1691                            Err(err) => return Err(err),
1692                        },
1693                    }
1694                    i += 1;
1695                }
1696                Ok(tb.mk_concats(children.iter().cloned()))
1697            }
1698            Ast::Intersection(intersection) => {
1699                let mut children = vec![];
1700                for ast in &intersection.asts {
1701                    match self.ast_to_node_id(ast, translator, tb) {
1702                        Ok(node_id) => children.push(node_id),
1703                        Err(err) => return Err(err),
1704                    }
1705                }
1706                Ok(tb.mk_inters(children.into_iter()))
1707            }
1708            Ast::Complement(complement) => {
1709                let body = self.ast_to_node_id(&complement.ast, translator, tb);
1710                body.map(|x| tb.mk_compl(x))
1711            }
1712        }
1713    }
1714
1715    fn parse_inner(&mut self) -> Result<Ast> {
1716        let mut concat = Concat {
1717            span: self.span(),
1718            asts: vec![],
1719        };
1720        loop {
1721            self.bump_space();
1722            if self.is_eof() {
1723                break;
1724            }
1725            match self.char() {
1726                '(' => concat = self.push_group(concat)?,
1727                ')' => concat = self.pop_group(concat)?,
1728                '|' => concat = self.push_alternate(concat)?,
1729                '&' => concat = self.push_intersect(concat)?,
1730                '~' => concat = self.push_compl_group(concat)?,
1731                '[' => {
1732                    let class = self.parse_set_class()?;
1733                    concat.asts.push(Ast::class_bracketed(class));
1734                }
1735                '?' => {
1736                    concat =
1737                        self.parse_uncounted_repetition(concat, ast::RepetitionKind::ZeroOrOne)?;
1738                }
1739                '*' => {
1740                    concat =
1741                        self.parse_uncounted_repetition(concat, ast::RepetitionKind::ZeroOrMore)?;
1742                }
1743                '+' => {
1744                    concat =
1745                        self.parse_uncounted_repetition(concat, ast::RepetitionKind::OneOrMore)?;
1746                }
1747                '{' => {
1748                    concat = self.parse_counted_repetition(concat)?;
1749                }
1750                _ => concat.asts.push(self.parse_primitive()?.into_ast()),
1751            }
1752        }
1753        self.pop_group_end(concat)
1754    }
1755
1756    /// Parse the regular expression and return an abstract syntax tree with
1757    /// all of the comments found in the pattern.
1758    fn parse(&mut self, tb: &mut TB<'s>) -> Result<NodeId> {
1759        let ast = self.parse_inner()?;
1760        self.ast_to_node_id(&ast, &mut None, tb)
1761    }
1762
1763    #[inline(never)]
1764    fn parse_uncounted_repetition(
1765        &self,
1766        mut concat: ast::Concat,
1767        kind: ast::RepetitionKind,
1768    ) -> Result<ast::Concat> {
1769        // assert!(self.char() == '?' || self.char() == '*' || self.char() == '+');
1770        let op_start = self.pos();
1771        let ast = match concat.asts.pop() {
1772            Some(ast) => ast,
1773            None => return Err(self.error(self.span(), ast::ErrorKind::RepetitionMissing)),
1774        };
1775        match ast {
1776            Ast::Empty(_) | Ast::Flags(_) => {
1777                return Err(self.error(self.span(), ast::ErrorKind::RepetitionMissing))
1778            }
1779            _ => {}
1780        }
1781        if self.bump() && self.char() == '?' {
1782            return Err(self.error(
1783                Span::new(op_start, self.pos()),
1784                ast::ErrorKind::UnsupportedLazyQuantifier,
1785            ));
1786        }
1787        concat.asts.push(Ast::repetition(ast::Repetition {
1788            span: ast.span().with_end(self.pos()),
1789            op: ast::RepetitionOp {
1790                span: Span::new(op_start, self.pos()),
1791                kind,
1792            },
1793            greedy: true,
1794            ast: Box::new(ast),
1795        }));
1796        Ok(concat)
1797    }
1798
1799    #[inline(never)]
1800    fn parse_counted_repetition(&self, mut concat: ast::Concat) -> Result<ast::Concat> {
1801        assert!(self.char() == '{');
1802        let start = self.pos();
1803        let ast = match concat.asts.pop() {
1804            Some(ast) => ast,
1805            None => return Err(self.error(self.span(), ast::ErrorKind::RepetitionMissing)),
1806        };
1807        match ast {
1808            Ast::Empty(_) | Ast::Flags(_) => {
1809                return Err(self.error(self.span(), ast::ErrorKind::RepetitionMissing))
1810            }
1811            _ => {}
1812        }
1813        if !self.bump_and_bump_space() {
1814            return Err(self.error(
1815                Span::new(start, self.pos()),
1816                ast::ErrorKind::RepetitionCountUnclosed,
1817            ));
1818        }
1819        let count_start = specialize_err(
1820            self.parse_decimal(),
1821            ast::ErrorKind::DecimalEmpty,
1822            ast::ErrorKind::RepetitionCountDecimalEmpty,
1823        );
1824        if self.is_eof() {
1825            return Err(self.error(
1826                Span::new(start, self.pos()),
1827                ast::ErrorKind::RepetitionCountUnclosed,
1828            ));
1829        }
1830        let range = if self.char() == ',' {
1831            if !self.bump_and_bump_space() {
1832                return Err(self.error(
1833                    Span::new(start, self.pos()),
1834                    ast::ErrorKind::RepetitionCountUnclosed,
1835                ));
1836            }
1837            if self.char() != '}' {
1838                let count_start = match count_start {
1839                    Ok(c) => c,
1840                    Err(err) if err.kind == ast::ErrorKind::RepetitionCountDecimalEmpty => {
1841                        if self.parser().empty_min_range {
1842                            0
1843                        } else {
1844                            return Err(err);
1845                        }
1846                    }
1847                    err => err?,
1848                };
1849                let count_end = specialize_err(
1850                    self.parse_decimal(),
1851                    ast::ErrorKind::DecimalEmpty,
1852                    ast::ErrorKind::RepetitionCountDecimalEmpty,
1853                )?;
1854                ast::RepetitionRange::Bounded(count_start, count_end)
1855            } else {
1856                ast::RepetitionRange::AtLeast(count_start?)
1857            }
1858        } else {
1859            ast::RepetitionRange::Exactly(count_start?)
1860        };
1861
1862        if self.is_eof() || self.char() != '}' {
1863            return Err(self.error(
1864                Span::new(start, self.pos()),
1865                ast::ErrorKind::RepetitionCountUnclosed,
1866            ));
1867        }
1868
1869        if self.bump_and_bump_space() && self.char() == '?' {
1870            return Err(self.error(
1871                Span::new(start, self.pos()),
1872                ast::ErrorKind::UnsupportedLazyQuantifier,
1873            ));
1874        }
1875
1876        let op_span = Span::new(start, self.pos());
1877        if !range.is_valid() {
1878            return Err(self.error(op_span, ast::ErrorKind::RepetitionCountInvalid));
1879        }
1880        concat.asts.push(Ast::repetition(ast::Repetition {
1881            span: ast.span().with_end(self.pos()),
1882            op: ast::RepetitionOp {
1883                span: op_span,
1884                kind: ast::RepetitionKind::Range(range),
1885            },
1886            greedy: true,
1887            ast: Box::new(ast),
1888        }));
1889        Ok(concat)
1890    }
1891
1892    #[inline(never)]
1893    fn parse_group(&self) -> Result<Either<ast::SetFlags, ast::Group>> {
1894        assert_eq!(self.char(), '(');
1895        let open_span = self.span_char();
1896        self.bump();
1897        self.bump_space();
1898        if let Some((ahead, pos)) = self.is_lookaround_prefix() {
1899            let kind = match (pos, ahead) {
1900                (true, true) => LookaroundKind::PositiveLookahead,
1901                (true, false) => LookaroundKind::PositiveLookbehind,
1902                (false, true) => LookaroundKind::NegativeLookahead,
1903                (false, false) => LookaroundKind::NegativeLookbehind,
1904            };
1905            return Ok(Either::Right(ast::Group {
1906                span: open_span,
1907                kind: ast::GroupKind::Lookaround(kind),
1908                ast: Box::new(Ast::empty(self.span())),
1909            }));
1910        }
1911        let inner_span = self.span();
1912        let mut starts_with_p = true;
1913        if self.bump_if("?P<") || {
1914            starts_with_p = false;
1915            self.bump_if("?<")
1916        } {
1917            let capture_index = self.next_capture_index(open_span)?;
1918            let name = self.parse_capture_name(capture_index)?;
1919            Ok(Either::Right(ast::Group {
1920                span: open_span,
1921                kind: ast::GroupKind::CaptureName {
1922                    starts_with_p,
1923                    name,
1924                },
1925                ast: Box::new(Ast::empty(self.span())),
1926            }))
1927        } else if self.bump_if("?") {
1928            if self.is_eof() {
1929                return Err(self.error(open_span, ast::ErrorKind::GroupUnclosed));
1930            }
1931            let flags = self.parse_flags()?;
1932            let char_end = self.char();
1933            self.bump();
1934            if char_end == ')' {
1935                // We don't allow empty flags, e.g., `(?)`. We instead
1936                // interpret it as a repetition operator missing its argument.
1937                if flags.items.is_empty() {
1938                    return Err(self.error(inner_span, ast::ErrorKind::RepetitionMissing));
1939                }
1940                Ok(Either::Left(ast::SetFlags {
1941                    span: Span {
1942                        end: self.pos(),
1943                        ..open_span
1944                    },
1945                    flags,
1946                }))
1947            } else {
1948                assert_eq!(char_end, ':');
1949                Ok(Either::Right(ast::Group {
1950                    span: open_span,
1951                    kind: ast::GroupKind::NonCapturing(flags),
1952                    ast: Box::new(Ast::empty(self.span())),
1953                }))
1954            }
1955        } else {
1956            let capture_index = self.next_capture_index(open_span)?;
1957            Ok(Either::Right(ast::Group {
1958                span: open_span,
1959                kind: ast::GroupKind::CaptureIndex(capture_index),
1960                ast: Box::new(Ast::empty(self.span())),
1961            }))
1962        }
1963    }
1964
1965    #[inline(never)]
1966    fn parse_capture_name(&self, capture_index: u32) -> Result<ast::CaptureName> {
1967        if self.is_eof() {
1968            return Err(self.error(self.span(), ast::ErrorKind::GroupNameUnexpectedEof));
1969        }
1970        let start = self.pos();
1971        loop {
1972            if self.char() == '>' {
1973                break;
1974            }
1975            if !is_capture_char(self.char(), self.pos() == start) {
1976                return Err(self.error(self.span_char(), ast::ErrorKind::GroupNameInvalid));
1977            }
1978            if !self.bump() {
1979                break;
1980            }
1981        }
1982        let end = self.pos();
1983        if self.is_eof() {
1984            return Err(self.error(self.span(), ast::ErrorKind::GroupNameUnexpectedEof));
1985        }
1986        assert_eq!(self.char(), '>');
1987        self.bump();
1988        let name = &self.pattern()[start.offset..end.offset];
1989        if name.is_empty() {
1990            return Err(self.error(Span::new(start, start), ast::ErrorKind::GroupNameEmpty));
1991        }
1992        let capname = ast::CaptureName {
1993            span: Span::new(start, end),
1994            name: name.to_string(),
1995            index: capture_index,
1996        };
1997        self.add_capture_name(&capname)?;
1998        Ok(capname)
1999    }
2000
2001    #[inline(never)]
2002    fn parse_flags(&self) -> Result<ast::Flags> {
2003        let mut flags = ast::Flags {
2004            span: self.span(),
2005            items: vec![],
2006        };
2007        let mut last_was_negation = None;
2008        while self.char() != ':' && self.char() != ')' {
2009            if self.char() == '-' {
2010                last_was_negation = Some(self.span_char());
2011                let item = ast::FlagsItem {
2012                    span: self.span_char(),
2013                    kind: ast::FlagsItemKind::Negation,
2014                };
2015                if let Some(i) = flags.add_item(item) {
2016                    return Err(self.error(
2017                        self.span_char(),
2018                        ast::ErrorKind::FlagRepeatedNegation {
2019                            original: flags.items[i].span,
2020                        },
2021                    ));
2022                }
2023            } else {
2024                last_was_negation = None;
2025                let item = ast::FlagsItem {
2026                    span: self.span_char(),
2027                    kind: ast::FlagsItemKind::Flag(self.parse_flag()?),
2028                };
2029                if let Some(i) = flags.add_item(item) {
2030                    return Err(self.error(
2031                        self.span_char(),
2032                        ast::ErrorKind::FlagDuplicate {
2033                            original: flags.items[i].span,
2034                        },
2035                    ));
2036                }
2037            }
2038            if !self.bump() {
2039                return Err(self.error(self.span(), ast::ErrorKind::FlagUnexpectedEof));
2040            }
2041        }
2042        if let Some(span) = last_was_negation {
2043            return Err(self.error(span, ast::ErrorKind::FlagDanglingNegation));
2044        }
2045        flags.span.end = self.pos();
2046        Ok(flags)
2047    }
2048
2049    #[inline(never)]
2050    fn parse_flag(&self) -> Result<ast::Flag> {
2051        match self.char() {
2052            'i' => Ok(ast::Flag::CaseInsensitive),
2053            'm' => Ok(ast::Flag::MultiLine),
2054            's' => Ok(ast::Flag::DotMatchesNewLine),
2055            'U' => Ok(ast::Flag::SwapGreed),
2056            'u' => Ok(ast::Flag::Unicode),
2057            'R' => Ok(ast::Flag::CRLF),
2058            'x' => Ok(ast::Flag::IgnoreWhitespace),
2059            _ => Err(self.error(self.span_char(), ast::ErrorKind::FlagUnrecognized)),
2060        }
2061    }
2062
2063    fn parse_primitive(&self) -> Result<Primitive> {
2064        match self.char() {
2065            '\\' => self.parse_escape(),
2066            '_' => {
2067                let ast = Primitive::Top(self.span_char());
2068                self.bump();
2069                Ok(ast)
2070            }
2071            '.' => {
2072                let ast = Primitive::Dot(self.span_char());
2073                self.bump();
2074                Ok(ast)
2075            }
2076            '^' => {
2077                let ast = Primitive::Assertion(ast::Assertion {
2078                    span: self.span_char(),
2079                    kind: ast::AssertionKind::StartLine,
2080                });
2081                self.bump();
2082                Ok(ast)
2083            }
2084            '$' => {
2085                let ast = Primitive::Assertion(ast::Assertion {
2086                    span: self.span_char(),
2087                    kind: ast::AssertionKind::EndLine,
2088                });
2089                self.bump();
2090                Ok(ast)
2091            }
2092            c => {
2093                let ast = Primitive::Literal(Literal {
2094                    span: self.span_char(),
2095                    kind: LiteralKind::Verbatim,
2096                    c,
2097                });
2098                self.bump();
2099                Ok(ast)
2100            }
2101        }
2102    }
2103
2104    #[inline(never)]
2105    fn parse_escape(&self) -> Result<Primitive> {
2106        assert_eq!(self.char(), '\\');
2107        let start = self.pos();
2108        if !self.bump() {
2109            return Err(self.error(
2110                Span::new(start, self.pos()),
2111                ast::ErrorKind::EscapeUnexpectedEof,
2112            ));
2113        }
2114        let c = self.char();
2115        // Put some of the more complicated routines into helpers.
2116        match c {
2117            '0'..='9' => {
2118                if !self.parser().octal {
2119                    return Err(self.error(
2120                        Span::new(start, self.span_char().end),
2121                        ast::ErrorKind::UnsupportedBackreference,
2122                    ));
2123                }
2124                let mut lit = self.parse_octal();
2125                lit.span.start = start;
2126                return Ok(Primitive::Literal(lit));
2127            }
2128            // '8'..='9' if !self.parser().octal => {
2129            //     return Err(self.error(
2130            //         Span::new(start, self.span_char().end),
2131            //         ast::ErrorKind::UnsupportedBackreference,
2132            //     ));
2133            // }
2134            'x' | 'u' | 'U' => {
2135                let mut lit = self.parse_hex()?;
2136                lit.span.start = start;
2137                return Ok(Primitive::Literal(lit));
2138            }
2139            'p' | 'P' => {
2140                let mut cls = self.parse_unicode_class()?;
2141                cls.span.start = start;
2142                return Ok(Primitive::Unicode(cls));
2143            }
2144            'd' | 's' | 'w' | 'D' | 'S' | 'W' => {
2145                let mut cls = self.parse_perl_class();
2146                cls.span.start = start;
2147                return Ok(Primitive::Perl(cls));
2148            }
2149            _ => {}
2150        }
2151
2152        // Handle all of the one letter sequences inline.
2153        self.bump();
2154        let span = Span::new(start, self.pos());
2155        if is_meta_character(c) {
2156            return Ok(Primitive::Literal(Literal {
2157                span,
2158                kind: LiteralKind::Meta,
2159                c,
2160            }));
2161        }
2162        if is_escapeable_character(c) {
2163            return Ok(Primitive::Literal(Literal {
2164                span,
2165                kind: LiteralKind::Superfluous,
2166                c,
2167            }));
2168        }
2169        let special = |kind, c| {
2170            Ok(Primitive::Literal(Literal {
2171                span,
2172                kind: LiteralKind::Special(kind),
2173                c,
2174            }))
2175        };
2176        match c {
2177            'a' => special(SpecialLiteralKind::Bell, '\x07'),
2178            'f' => special(SpecialLiteralKind::FormFeed, '\x0C'),
2179            't' => special(SpecialLiteralKind::Tab, '\t'),
2180            'n' => special(SpecialLiteralKind::LineFeed, '\n'),
2181            'r' => special(SpecialLiteralKind::CarriageReturn, '\r'),
2182            'v' => special(SpecialLiteralKind::VerticalTab, '\x0B'),
2183            'A' => Ok(Primitive::Assertion(ast::Assertion {
2184                span,
2185                kind: ast::AssertionKind::StartText,
2186            })),
2187            'z' => Ok(Primitive::Assertion(ast::Assertion {
2188                span,
2189                kind: ast::AssertionKind::EndText,
2190            })),
2191            'b' => {
2192                let mut wb = ast::Assertion {
2193                    span,
2194                    kind: ast::AssertionKind::WordBoundary,
2195                };
2196                // After a \b, we "try" to parse things like \b{start} for
2197                // special word boundary assertions.
2198                if !self.is_eof() && self.char() == '{' {
2199                    if let Some(kind) = self.maybe_parse_special_word_boundary(start)? {
2200                        wb.kind = kind;
2201                        wb.span.end = self.pos();
2202                    }
2203                }
2204                Ok(Primitive::Assertion(wb))
2205            }
2206            'B' => Ok(Primitive::Assertion(ast::Assertion {
2207                span,
2208                kind: ast::AssertionKind::NotWordBoundary,
2209            })),
2210            '<' => Ok(Primitive::Assertion(ast::Assertion {
2211                span,
2212                kind: ast::AssertionKind::WordBoundaryStartAngle,
2213            })),
2214            '>' => Ok(Primitive::Assertion(ast::Assertion {
2215                span,
2216                kind: ast::AssertionKind::WordBoundaryEndAngle,
2217            })),
2218            _ => Err(self.error(span, ast::ErrorKind::EscapeUnrecognized)),
2219        }
2220    }
2221
2222    fn maybe_parse_special_word_boundary(
2223        &self,
2224        wb_start: Position,
2225    ) -> Result<Option<ast::AssertionKind>> {
2226        assert_eq!(self.char(), '{');
2227
2228        let is_valid_char = |c| matches!(c, 'A'..='Z' | 'a'..='z' | '-');
2229        let start = self.pos();
2230        if !self.bump_and_bump_space() {
2231            return Err(self.error(
2232                Span::new(wb_start, self.pos()),
2233                ast::ErrorKind::SpecialWordOrRepetitionUnexpectedEof,
2234            ));
2235        }
2236        let start_contents = self.pos();
2237        // This is one of the critical bits: if the first non-whitespace
2238        // character isn't in [-A-Za-z] (i.e., this can't be a special word
2239        // boundary), then we bail and let the counted repetition parser deal
2240        // with this.
2241        if !is_valid_char(self.char()) {
2242            self.parser().pos.set(start);
2243            return Ok(None);
2244        }
2245
2246        // Now collect up our chars until we see a '}'.
2247        let mut scratch = self.parser().scratch.borrow_mut();
2248        scratch.clear();
2249        while !self.is_eof() && is_valid_char(self.char()) {
2250            scratch.push(self.char());
2251            self.bump_and_bump_space();
2252        }
2253        if self.is_eof() || self.char() != '}' {
2254            return Err(self.error(
2255                Span::new(start, self.pos()),
2256                ast::ErrorKind::SpecialWordBoundaryUnclosed,
2257            ));
2258        }
2259        let end = self.pos();
2260        self.bump();
2261        let kind = match scratch.as_str() {
2262            "start" => ast::AssertionKind::WordBoundaryStart,
2263            "end" => ast::AssertionKind::WordBoundaryEnd,
2264            "start-half" => ast::AssertionKind::WordBoundaryStartHalf,
2265            "end-half" => ast::AssertionKind::WordBoundaryEndHalf,
2266            _ => {
2267                return Err(self.error(
2268                    Span::new(start_contents, end),
2269                    ast::ErrorKind::SpecialWordBoundaryUnrecognized,
2270                ))
2271            }
2272        };
2273        Ok(Some(kind))
2274    }
2275
2276    #[inline(never)]
2277    fn parse_octal(&self) -> Literal {
2278        assert!(self.parser().octal);
2279        assert!('0' <= self.char() && self.char() <= '7');
2280        let start = self.pos();
2281        // Parse up to two more digits.
2282        while self.bump()
2283            && '0' <= self.char()
2284            && self.char() <= '7'
2285            && self.pos().offset - start.offset <= 2
2286        {}
2287        let end = self.pos();
2288        let octal = &self.pattern()[start.offset..end.offset];
2289        // Parsing the octal should never fail since the above guarantees a
2290        // valid number.
2291        let codepoint = u32::from_str_radix(octal, 8).expect("valid octal number");
2292        // The max value for 3 digit octal is 0777 = 511 and [0, 511] has no
2293        // invalid Unicode scalar values.
2294        let c = char::from_u32(codepoint).expect("Unicode scalar value");
2295        Literal {
2296            span: Span::new(start, end),
2297            kind: LiteralKind::Octal,
2298            c,
2299        }
2300    }
2301
2302    #[inline(never)]
2303    fn parse_hex(&self) -> Result<Literal> {
2304        assert!(self.char() == 'x' || self.char() == 'u' || self.char() == 'U');
2305
2306        let hex_kind = match self.char() {
2307            'x' => HexLiteralKind::X,
2308            'u' => HexLiteralKind::UnicodeShort,
2309            _ => HexLiteralKind::UnicodeLong,
2310        };
2311        if !self.bump_and_bump_space() {
2312            return Err(self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
2313        }
2314        if self.char() == '{' {
2315            self.parse_hex_brace(hex_kind)
2316        } else {
2317            self.parse_hex_digits(hex_kind)
2318        }
2319    }
2320
2321    #[inline(never)]
2322    fn parse_hex_digits(&self, kind: HexLiteralKind) -> Result<Literal> {
2323        let mut scratch = self.parser().scratch.borrow_mut();
2324        scratch.clear();
2325
2326        let start = self.pos();
2327        for i in 0..kind.digits() {
2328            if i > 0 && !self.bump_and_bump_space() {
2329                return Err(self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
2330            }
2331            if !is_hex(self.char()) {
2332                return Err(self.error(self.span_char(), ast::ErrorKind::EscapeHexInvalidDigit));
2333            }
2334            scratch.push(self.char());
2335        }
2336        // The final bump just moves the parser past the literal, which may
2337        // be EOF.
2338        self.bump_and_bump_space();
2339        let end = self.pos();
2340        let hex = scratch.as_str();
2341        match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) {
2342            None => Err(self.error(Span::new(start, end), ast::ErrorKind::EscapeHexInvalid)),
2343            Some(c) => Ok(Literal {
2344                span: Span::new(start, end),
2345                kind: LiteralKind::HexFixed(kind),
2346                c,
2347            }),
2348        }
2349    }
2350
2351    #[inline(never)]
2352    fn parse_hex_brace(&self, kind: HexLiteralKind) -> Result<Literal> {
2353        let mut scratch = self.parser().scratch.borrow_mut();
2354        scratch.clear();
2355
2356        let brace_pos = self.pos();
2357        let start = self.span_char().end;
2358        while self.bump_and_bump_space() && self.char() != '}' {
2359            if !is_hex(self.char()) {
2360                return Err(self.error(self.span_char(), ast::ErrorKind::EscapeHexInvalidDigit));
2361            }
2362            scratch.push(self.char());
2363        }
2364        if self.is_eof() {
2365            return Err(self.error(
2366                Span::new(brace_pos, self.pos()),
2367                ast::ErrorKind::EscapeUnexpectedEof,
2368            ));
2369        }
2370        let end = self.pos();
2371        let hex = scratch.as_str();
2372        assert_eq!(self.char(), '}');
2373        self.bump_and_bump_space();
2374
2375        if hex.is_empty() {
2376            return Err(self.error(
2377                Span::new(brace_pos, self.pos()),
2378                ast::ErrorKind::EscapeHexEmpty,
2379            ));
2380        }
2381        match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) {
2382            None => Err(self.error(Span::new(start, end), ast::ErrorKind::EscapeHexInvalid)),
2383            Some(c) => Ok(Literal {
2384                span: Span::new(start, self.pos()),
2385                kind: LiteralKind::HexBrace(kind),
2386                c,
2387            }),
2388        }
2389    }
2390
2391    fn parse_decimal(&self) -> Result<u32> {
2392        let mut scratch = self.parser().scratch.borrow_mut();
2393        scratch.clear();
2394
2395        while !self.is_eof() && self.char().is_whitespace() {
2396            self.bump();
2397        }
2398        let start = self.pos();
2399        while !self.is_eof() && '0' <= self.char() && self.char() <= '9' {
2400            scratch.push(self.char());
2401            self.bump_and_bump_space();
2402        }
2403        let span = Span::new(start, self.pos());
2404        while !self.is_eof() && self.char().is_whitespace() {
2405            self.bump_and_bump_space();
2406        }
2407        let digits = scratch.as_str();
2408        if digits.is_empty() {
2409            return Err(self.error(span, ast::ErrorKind::DecimalEmpty));
2410        }
2411        match digits.parse::<u32>().ok() {
2412            Some(n) => Ok(n),
2413            None => Err(self.error(span, ast::ErrorKind::DecimalInvalid)),
2414        }
2415    }
2416
2417    #[inline(never)]
2418    fn parse_set_class(&self) -> Result<ClassBracketed> {
2419        assert_eq!(self.char(), '[');
2420
2421        let mut union = ClassSetUnion {
2422            span: self.span(),
2423            items: vec![],
2424        };
2425        loop {
2426            self.bump_space();
2427            if self.is_eof() {
2428                return Err(self.unclosed_class_error());
2429            }
2430            match self.char() {
2431                '[' => {
2432                    // If we've already parsed the opening bracket, then
2433                    // attempt to treat this as the beginning of an ASCII
2434                    // class. If ASCII class parsing fails, then the parser
2435                    // backs up to `[`.
2436                    if !self.parser().stack_class.borrow().is_empty() {
2437                        if let Some(cls) = self.maybe_parse_ascii_class() {
2438                            union.push(ClassSetItem::Ascii(cls));
2439                            continue;
2440                        }
2441                    }
2442                    union = self.push_class_open(union)?;
2443                }
2444                ']' => match self.pop_class(union)? {
2445                    Either::Left(nested_union) => {
2446                        union = nested_union;
2447                    }
2448                    Either::Right(class) => return Ok(class),
2449                },
2450                '&' if self.peek() == Some('&') => {
2451                    assert!(self.bump_if("&&"));
2452                    union = self.push_class_op(ClassSetBinaryOpKind::Intersection, union);
2453                }
2454                '-' if self.peek() == Some('-') => {
2455                    assert!(self.bump_if("--"));
2456                    union = self.push_class_op(ClassSetBinaryOpKind::Difference, union);
2457                }
2458                '~' if self.peek() == Some('~') => {
2459                    assert!(self.bump_if("~~"));
2460                    union = self.push_class_op(ClassSetBinaryOpKind::SymmetricDifference, union);
2461                }
2462                _ => {
2463                    union.push(self.parse_set_class_range()?);
2464                }
2465            }
2466        }
2467    }
2468
2469    #[inline(never)]
2470    fn parse_set_class_range(&self) -> Result<ClassSetItem> {
2471        let prim1 = self.parse_set_class_item()?;
2472        self.bump_space();
2473        if self.is_eof() {
2474            return Err(self.unclosed_class_error());
2475        }
2476        if self.char() != '-' || self.peek_space() == Some(']') || self.peek_space() == Some('-') {
2477            return prim1.into_class_set_item(self);
2478        }
2479        if !self.bump_and_bump_space() {
2480            return Err(self.unclosed_class_error());
2481        }
2482        let prim2 = self.parse_set_class_item()?;
2483        let range = ClassSetRange {
2484            span: Span::new(prim1.span().start, prim2.span().end),
2485            start: prim1.into_class_literal(self)?,
2486            end: prim2.into_class_literal(self)?,
2487        };
2488        if !range.is_valid() {
2489            return Err(self.error(range.span, ast::ErrorKind::ClassRangeInvalid));
2490        }
2491        Ok(ClassSetItem::Range(range))
2492    }
2493
2494    #[inline(never)]
2495    fn parse_set_class_item(&self) -> Result<Primitive> {
2496        if self.char() == '\\' {
2497            self.parse_escape()
2498        } else {
2499            let x = Primitive::Literal(Literal {
2500                span: self.span_char(),
2501                kind: LiteralKind::Verbatim,
2502                c: self.char(),
2503            });
2504            self.bump();
2505            Ok(x)
2506        }
2507    }
2508
2509    #[inline(never)]
2510    fn parse_set_class_open(&self) -> Result<(ClassBracketed, ClassSetUnion)> {
2511        assert_eq!(self.char(), '[');
2512        let start = self.pos();
2513        if !self.bump_and_bump_space() {
2514            return Err(self.error(Span::new(start, self.pos()), ast::ErrorKind::ClassUnclosed));
2515        }
2516
2517        let negated = if self.char() != '^' {
2518            false
2519        } else {
2520            if !self.bump_and_bump_space() {
2521                return Err(self.error(Span::new(start, self.pos()), ast::ErrorKind::ClassUnclosed));
2522            }
2523            true
2524        };
2525        // Accept any number of `-` as literal `-`.
2526        let mut union = ClassSetUnion {
2527            span: self.span(),
2528            items: vec![],
2529        };
2530        while self.char() == '-' {
2531            union.push(ClassSetItem::Literal(Literal {
2532                span: self.span_char(),
2533                kind: LiteralKind::Verbatim,
2534                c: '-',
2535            }));
2536            if !self.bump_and_bump_space() {
2537                return Err(self.error(Span::new(start, start), ast::ErrorKind::ClassUnclosed));
2538            }
2539        }
2540        // If `]` is the *first* char in a set, then interpret it as a literal
2541        // `]`. That is, an empty class is impossible to write.
2542        if union.items.is_empty() && self.char() == ']' {
2543            union.push(ClassSetItem::Literal(Literal {
2544                span: self.span_char(),
2545                kind: LiteralKind::Verbatim,
2546                c: ']',
2547            }));
2548            if !self.bump_and_bump_space() {
2549                return Err(self.error(Span::new(start, self.pos()), ast::ErrorKind::ClassUnclosed));
2550            }
2551        }
2552        let set = ClassBracketed {
2553            span: Span::new(start, self.pos()),
2554            negated,
2555            kind: ClassSet::union(ClassSetUnion {
2556                span: Span::new(union.span.start, union.span.start),
2557                items: vec![],
2558            }),
2559        };
2560        Ok((set, union))
2561    }
2562
2563    #[inline(never)]
2564    fn maybe_parse_ascii_class(&self) -> Option<ClassAscii> {
2565        assert_eq!(self.char(), '[');
2566        // If parsing fails, then we back up the parser to this starting point.
2567        let start = self.pos();
2568        let mut negated = false;
2569        if !self.bump() || self.char() != ':' {
2570            self.parser().pos.set(start);
2571            return None;
2572        }
2573        if !self.bump() {
2574            self.parser().pos.set(start);
2575            return None;
2576        }
2577        if self.char() == '^' {
2578            negated = true;
2579            if !self.bump() {
2580                self.parser().pos.set(start);
2581                return None;
2582            }
2583        }
2584        let name_start = self.offset();
2585        while self.char() != ':' && self.bump() {}
2586        if self.is_eof() {
2587            self.parser().pos.set(start);
2588            return None;
2589        }
2590        let name = &self.pattern()[name_start..self.offset()];
2591        if !self.bump_if(":]") {
2592            self.parser().pos.set(start);
2593            return None;
2594        }
2595        let kind = match regex_syntax::ast::ClassAsciiKind::from_name(name) {
2596            Some(kind) => kind,
2597            None => {
2598                self.parser().pos.set(start);
2599                return None;
2600            }
2601        };
2602        Some(ClassAscii {
2603            span: Span::new(start, self.pos()),
2604            kind,
2605            negated,
2606        })
2607    }
2608
2609    #[inline(never)]
2610    fn parse_unicode_class(&self) -> Result<ClassUnicode> {
2611        assert!(self.char() == 'p' || self.char() == 'P');
2612
2613        let mut scratch = self.parser().scratch.borrow_mut();
2614        scratch.clear();
2615
2616        let negated = self.char() == 'P';
2617        if !self.bump_and_bump_space() {
2618            return Err(self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
2619        }
2620        let (start, kind) = if self.char() == '{' {
2621            let start = self.span_char().end;
2622            while self.bump_and_bump_space() && self.char() != '}' {
2623                scratch.push(self.char());
2624            }
2625            if self.is_eof() {
2626                return Err(self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
2627            }
2628            assert_eq!(self.char(), '}');
2629            self.bump();
2630
2631            let name = scratch.as_str();
2632            if let Some(i) = name.find("!=") {
2633                (
2634                    start,
2635                    ClassUnicodeKind::NamedValue {
2636                        op: ClassUnicodeOpKind::NotEqual,
2637                        name: name[..i].to_string(),
2638                        value: name[i + 2..].to_string(),
2639                    },
2640                )
2641            } else if let Some(i) = name.find(':') {
2642                (
2643                    start,
2644                    ClassUnicodeKind::NamedValue {
2645                        op: ClassUnicodeOpKind::Colon,
2646                        name: name[..i].to_string(),
2647                        value: name[i + 1..].to_string(),
2648                    },
2649                )
2650            } else if let Some(i) = name.find('=') {
2651                (
2652                    start,
2653                    ClassUnicodeKind::NamedValue {
2654                        op: ClassUnicodeOpKind::Equal,
2655                        name: name[..i].to_string(),
2656                        value: name[i + 1..].to_string(),
2657                    },
2658                )
2659            } else {
2660                (start, ClassUnicodeKind::Named(name.to_string()))
2661            }
2662        } else {
2663            let start = self.pos();
2664            let c = self.char();
2665            if c == '\\' {
2666                return Err(self.error(self.span_char(), ast::ErrorKind::UnicodeClassInvalid));
2667            }
2668            self.bump_and_bump_space();
2669            let kind = ClassUnicodeKind::OneLetter(c);
2670            (start, kind)
2671        };
2672        Ok(ClassUnicode {
2673            span: Span::new(start, self.pos()),
2674            negated,
2675            kind,
2676        })
2677    }
2678
2679    #[inline(never)]
2680    fn parse_perl_class(&self) -> ClassPerl {
2681        let c = self.char();
2682        let span = self.span_char();
2683        self.bump();
2684        let (negated, kind) = match c {
2685            'd' => (false, regex_syntax::ast::ClassPerlKind::Digit),
2686            'D' => (true, regex_syntax::ast::ClassPerlKind::Digit),
2687            's' => (false, regex_syntax::ast::ClassPerlKind::Space),
2688            'S' => (true, regex_syntax::ast::ClassPerlKind::Space),
2689            'w' => (false, regex_syntax::ast::ClassPerlKind::Word),
2690            'W' => (true, regex_syntax::ast::ClassPerlKind::Word),
2691            c => panic!("expected valid Perl class but got '{}'", c),
2692        };
2693        ClassPerl {
2694            span,
2695            kind,
2696            negated,
2697        }
2698    }
2699}
2700
2701pub fn parse_ast<'s>(
2702    tb: &mut TB<'s>,
2703    pattern: &'s str,
2704) -> std::result::Result<NodeId, ResharpError> {
2705    let mut p: ResharpParser<'s> = ResharpParser::new(pattern);
2706    p.parse(tb)
2707}
2708
2709pub fn parse_ast_with<'s>(
2710    tb: &mut TB<'s>,
2711    pattern: &'s str,
2712    flags: &PatternFlags,
2713) -> std::result::Result<NodeId, ResharpError> {
2714    let mut p: ResharpParser<'s> = ResharpParser::with_flags(pattern, flags);
2715    p.parse(tb)
2716}
2717
2718/// Parse a pattern into the raw AST without converting to algebra nodes.
2719pub fn parse_to_ast(pattern: &str) -> std::result::Result<ast::Ast, ResharpError> {
2720    let mut p: ResharpParser = ResharpParser::new(pattern);
2721    p.parse_inner()
2722}