Skip to main content

monster_regex/parser/
mod.rs

1use crate::flags::Flags;
2use std::collections::HashMap;
3use std::fmt;
4
5/// Represents a node in the Abstract Syntax Tree (AST) of a regular expression.
6#[derive(Debug, Clone, PartialEq)]
7pub enum AstNode {
8    /// A literal character match.
9    Literal(char),
10
11    /// A character class (e.g., `\d`, `[a-z]`, `.`).
12    CharClass(CharClass),
13
14    /// Start of string (or line in multiline mode) anchor `^`.
15    StartAnchor,
16    /// End of string (or line in multiline mode) anchor `$`.
17    EndAnchor,
18    /// Word boundary anchor `\b`.
19    WordBoundary,
20    /// Start of word anchor `\<`.
21    StartWord,
22    /// End of word anchor `\>`.
23    EndWord,
24    /// Sets the start of the match `\zs`.
25    SetMatchStart,
26    /// Sets the end of the match `\ze`.
27    SetMatchEnd,
28
29    /// Zero or more repetitions `*`.
30    ZeroOrMore {
31        /// The node being repeated.
32        node: Box<AstNode>,
33        /// Whether the quantifier is greedy (default) or lazy (`?`).
34        greedy: bool,
35    },
36    /// One or more repetitions `+`.
37    OneOrMore {
38        /// The node being repeated.
39        node: Box<AstNode>,
40        /// Whether the quantifier is greedy (default) or lazy (`?`).
41        greedy: bool,
42    },
43    /// Zero or one repetition `?`.
44    Optional {
45        /// The node being repeated.
46        node: Box<AstNode>,
47        /// Whether the quantifier is greedy (default) or lazy (`?`).
48        greedy: bool,
49    },
50    /// Exact number of repetitions `{n}`.
51    Exact {
52        /// The node being repeated.
53        node: Box<AstNode>,
54        /// The exact count.
55        count: usize,
56    },
57    /// Range of repetitions `{n,m}` or `{n,}`.
58    Range {
59        /// The node being repeated.
60        node: Box<AstNode>,
61        /// The minimum count.
62        min: usize,
63        /// The maximum count (None means infinite).
64        max: Option<usize>,
65        /// Whether the quantifier is greedy (default) or lazy (`?`).
66        greedy: bool,
67    },
68
69    /// A capturing or non-capturing group `(...)`.
70    Group {
71        /// The sequence of nodes inside the group.
72        nodes: Vec<AstNode>,
73        /// The name of the group, if it is a named capture `(?<name>...)`.
74        name: Option<String>,
75        /// Whether this group captures text.
76        capture: bool,
77        /// The index of the capture group (1-based), if capturing.
78        index: Option<usize>,
79    },
80    /// Alternation `|`.
81    Alternation(Vec<Vec<AstNode>>),
82
83    /// Backreference to a captured group `\n`.
84    Backref(usize),
85
86    /// Lookahead assertion `(?>=...)` or `(?>!...)`.
87    LookAhead {
88        /// The sequence of nodes to check ahead.
89        nodes: Vec<AstNode>,
90        /// True for positive lookahead, false for negative.
91        positive: bool,
92    },
93    /// Lookbehind assertion `(?<=...)` or `(?<!...)`.
94    LookBehind {
95        /// The sequence of nodes to check behind.
96        nodes: Vec<AstNode>,
97        /// True for positive lookbehind, false for negative.
98        positive: bool,
99    },
100
101    Subroutine(SubroutineTarget),
102}
103
104#[derive(Debug, Clone, PartialEq)]
105pub enum SubroutineTarget {
106    /// `(?R)` - recurse into the whole pattern.
107    Whole,
108    /// `(?N)`, or a `(?-N)`/`(?+N)` already resolved to an absolute number.
109    Group(usize),
110    /// `(?&name)` / `(?P>name)`, not yet resolved to a group number.
111    Name(String),
112}
113
114/// Represents a class of characters.
115#[derive(Debug, Clone, PartialEq)]
116pub enum CharClass {
117    // Standard classes
118    /// Digit `\d` (`[0-9]`).
119    Digit,
120    /// Non-digit `\D`.
121    NonDigit,
122    /// Word character `\w` (`[a-zA-Z0-9_]`).
123    Word,
124    /// Non-word character `\W`.
125    NonWord,
126    /// Whitespace `\s` (`[ \t\r\n\f\v]`).
127    Whitespace,
128    /// Non-whitespace `\S`.
129    NonWhitespace,
130
131    // Extended classes
132    /// Lowercase character `\l`.
133    Lowercase,
134    /// Non-lowercase character `\L`.
135    NonLowercase,
136    /// Uppercase character `\u`.
137    Uppercase,
138    /// Non-uppercase character `\U`.
139    NonUppercase,
140    /// Hexadecimal digit `\x`.
141    Hex,
142    /// Non-hexadecimal digit `\X`.
143    NonHex,
144    /// Octal digit `\o`.
145    Octal,
146    /// Non-octal digit `\O`.
147    NonOctal,
148    /// Start of word character `\h`.
149    WordStart,
150    /// Non-start of word character `\H`.
151    NonWordStart,
152    /// Punctuation `\p`.
153    Punctuation,
154    /// Non-punctuation `\P`.
155    NonPunctuation,
156    /// Alphanumeric `\a`.
157    Alphanumeric,
158    /// Non-alphanumeric `\A`.
159    NonAlphanumeric,
160
161    // Custom sets
162    /// Custom character set `[...]`.
163    Set {
164        /// The ranges or characters included in the set.
165        chars: Vec<CharRange>,
166        /// Whether the set is negated `[^...]`.
167        negated: bool,
168    },
169
170    /// Dot `.` (matches any character except newline, or any character with `s` flag).
171    Dot,
172}
173
174/// A range of characters in a character set.
175#[derive(Debug, Clone, PartialEq)]
176pub struct CharRange {
177    /// Start of the range.
178    pub start: char,
179    /// End of the range.
180    pub end: char,
181}
182
183const MAX_GROUP_DEPTH: usize = 200;
184
185/// The recursive descent parser for the regex pattern.
186#[derive(Debug, Clone)]
187pub struct Parser {
188    input: Vec<char>,
189    pos: usize,
190    flags: Flags,
191    group_count: usize,
192    depth: usize,
193}
194
195/// Errors that can occur during parsing.
196#[derive(Debug)]
197pub enum ParseError {
198    UnexpectedChar(char, usize),
199    UnexpectedEof,
200    InvalidQuantifier(String),
201    UnmatchedParen,
202    InvalidGroupName(String),
203    InvalidEscape(char),
204    InvalidCharClass,
205    DuplicateGroupName(String),
206    InvalidBackref(usize),
207    InvalidLineNumber(String),
208    InvalidGroup(String),
209    /// A pattern nested groups/lookarounds more than `MAX_GROUP_DEPTH` deep.
210    NestingTooDeep(usize),
211    InvalidSubroutineReference(String),
212}
213
214impl fmt::Display for ParseError {
215    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
216        match self {
217            ParseError::UnexpectedChar(c, pos) => {
218                write!(f, "Unexpected '{}' at position {}", c, pos)
219            }
220            ParseError::UnexpectedEof => write!(f, "Unexpected end of input"),
221            ParseError::InvalidQuantifier(s) => {
222                write!(f, "Invalid quantifier: {}", s)
223            }
224            ParseError::UnmatchedParen => write!(f, "Unmatched parenthesis"),
225            ParseError::InvalidGroupName(s) => {
226                write!(f, "Invalid group name: {}", s)
227            }
228            ParseError::InvalidEscape(c) => {
229                write!(f, "Invalid escape sequence: \\{}", c)
230            }
231            ParseError::InvalidCharClass => {
232                write!(f, "Invalid character class")
233            }
234            ParseError::DuplicateGroupName(s) => {
235                write!(f, "Duplicate group name: {}", s)
236            }
237            ParseError::InvalidBackref(n) => {
238                write!(f, "Invalid backreference: \\{}", n)
239            }
240            ParseError::InvalidLineNumber(s) => {
241                write!(f, "Invalid line number: {}", s)
242            }
243            ParseError::InvalidGroup(s) => {
244                write!(f, "Invalid group syntax: {}", s)
245            }
246            ParseError::NestingTooDeep(max) => {
247                write!(f, "Pattern nests groups more than {} levels deep", max)
248            }
249            ParseError::InvalidSubroutineReference(s) => {
250                write!(f, "Invalid subroutine reference: {}", s)
251            }
252        }
253    }
254}
255
256impl std::error::Error for ParseError {}
257
258impl Parser {
259    /// Creates a new parser for the given pattern.
260    pub fn new(pattern: &str, flags: Flags) -> Self {
261        Parser {
262            input: pattern.chars().collect(),
263            pos: 0,
264            flags,
265            group_count: 0,
266            depth: 0,
267        }
268    }
269
270    /// Parses the pattern into an AST.
271    pub fn parse(&mut self) -> Result<Vec<AstNode>, ParseError> {
272        let mut nodes = self.parse_alternation()?;
273        let mut names = HashMap::new();
274        collect_group_names(&nodes, &mut names);
275        resolve_subroutines(&mut nodes, &names, self.group_count)?;
276        Ok(nodes)
277    }
278
279    // Top level: handle |
280    fn parse_alternation(&mut self) -> Result<Vec<AstNode>, ParseError> {
281        let mut alternatives = vec![];
282        let mut current = self.parse_sequence()?;
283
284        while self.peek() == Some('|') {
285            self.consume()?;
286            alternatives.push(current);
287            current = self.parse_sequence()?;
288        }
289        alternatives.push(current);
290
291        if alternatives.len() == 1 {
292            Ok(alternatives.pop().unwrap())
293        } else {
294            Ok(vec![AstNode::Alternation(alternatives)])
295        }
296    }
297
298    fn skip_whitespace_and_comments(&mut self) {
299        if !self.flags.verbose {
300            return;
301        }
302        while self.pos < self.input.len() {
303            let ch = self.input[self.pos];
304            if ch.is_whitespace() {
305                self.pos += 1;
306            } else if ch == '#' {
307                self.pos += 1;
308                while self.pos < self.input.len() && self.input[self.pos] != '\n' {
309                    self.pos += 1;
310                }
311            } else {
312                break;
313            }
314        }
315    }
316
317    // Parse sequence of atoms with quantifiers
318    fn parse_sequence(&mut self) -> Result<Vec<AstNode>, ParseError> {
319        let mut nodes = vec![];
320
321        loop {
322            self.skip_whitespace_and_comments();
323            match self.current() {
324                Some(&'|') | Some(&')') | None => break,
325                _ => {
326                    let node = self.parse_atom()?;
327                    let node = self.apply_quantifier(node)?;
328                    nodes.push(node);
329                }
330            }
331        }
332
333        Ok(nodes)
334    }
335
336    // Parse a single atom (before quantifiers)
337    fn parse_atom(&mut self) -> Result<AstNode, ParseError> {
338        match self.current() {
339            None => Err(ParseError::UnexpectedEof),
340            Some(&'.') => {
341                self.consume()?;
342                Ok(AstNode::CharClass(CharClass::Dot))
343            }
344            Some(&'^') => {
345                self.consume()?;
346                Ok(AstNode::StartAnchor)
347            }
348            Some(&'$') => {
349                self.consume()?;
350                Ok(AstNode::EndAnchor)
351            }
352            Some(&'[') => self.parse_char_class(),
353            Some(&'(') => self.parse_group(),
354            Some(&'\\') => self.parse_escape(),
355            Some(&ch) => {
356                self.consume()?;
357                Ok(AstNode::Literal(ch))
358            }
359        }
360    }
361
362    // Parse \escape sequences
363    fn parse_escape(&mut self) -> Result<AstNode, ParseError> {
364        self.consume()?; // consume \
365
366        match self.current() {
367            None => Err(ParseError::UnexpectedEof),
368            Some(&'d') => {
369                self.consume()?;
370                Ok(AstNode::CharClass(CharClass::Digit))
371            }
372            Some(&'D') => {
373                self.consume()?;
374                Ok(AstNode::CharClass(CharClass::NonDigit))
375            }
376            Some(&'w') => {
377                self.consume()?;
378                Ok(AstNode::CharClass(CharClass::Word))
379            }
380            Some(&'W') => {
381                self.consume()?;
382                Ok(AstNode::CharClass(CharClass::NonWord))
383            }
384            Some(&'s') => {
385                self.consume()?;
386                Ok(AstNode::CharClass(CharClass::Whitespace))
387            }
388            Some(&'S') => {
389                self.consume()?;
390                Ok(AstNode::CharClass(CharClass::NonWhitespace))
391            }
392            Some(&'l') => {
393                self.consume()?;
394                Ok(AstNode::CharClass(CharClass::Lowercase))
395            }
396            Some(&'L') => {
397                self.consume()?;
398                Ok(AstNode::CharClass(CharClass::NonLowercase))
399            }
400            Some(&'u') => {
401                self.consume()?;
402                Ok(AstNode::CharClass(CharClass::Uppercase))
403            }
404            Some(&'U') => {
405                self.consume()?;
406                Ok(AstNode::CharClass(CharClass::NonUppercase))
407            }
408            Some(&'x') => {
409                self.consume()?;
410                Ok(AstNode::CharClass(CharClass::Hex))
411            }
412            Some(&'X') => {
413                self.consume()?;
414                Ok(AstNode::CharClass(CharClass::NonHex))
415            }
416            Some(&'o') => {
417                self.consume()?;
418                Ok(AstNode::CharClass(CharClass::Octal))
419            }
420            Some(&'O') => {
421                self.consume()?;
422                Ok(AstNode::CharClass(CharClass::NonOctal))
423            }
424            Some(&'h') => {
425                self.consume()?;
426                Ok(AstNode::CharClass(CharClass::WordStart))
427            }
428            Some(&'H') => {
429                self.consume()?;
430                Ok(AstNode::CharClass(CharClass::NonWordStart))
431            }
432            Some(&'p') => {
433                self.consume()?;
434                Ok(AstNode::CharClass(CharClass::Punctuation))
435            }
436            Some(&'P') => {
437                self.consume()?;
438                Ok(AstNode::CharClass(CharClass::NonPunctuation))
439            }
440            Some(&'a') => {
441                self.consume()?;
442                Ok(AstNode::CharClass(CharClass::Alphanumeric))
443            }
444            Some(&'A') => {
445                self.consume()?;
446                Ok(AstNode::CharClass(CharClass::NonAlphanumeric))
447            }
448            Some(&'b') => {
449                self.consume()?;
450                Ok(AstNode::WordBoundary)
451            }
452            Some(&'<') => {
453                self.consume()?;
454                Ok(AstNode::StartWord)
455            }
456            Some(&'>') => {
457                self.consume()?;
458                Ok(AstNode::EndWord)
459            }
460            Some(&'z') => {
461                self.consume()?;
462                match self.current() {
463                    Some(&'s') => {
464                        self.consume()?;
465                        Ok(AstNode::SetMatchStart)
466                    }
467                    Some(&'e') => {
468                        self.consume()?;
469                        Ok(AstNode::SetMatchEnd)
470                    }
471                    _ => Err(ParseError::InvalidEscape('z')),
472                }
473            }
474            Some(&c @ '0'..='9') => {
475                self.consume()?;
476                let digit = c.to_digit(10).unwrap() as usize;
477                Ok(AstNode::Backref(digit))
478            }
479            Some(&'n') => {
480                self.consume()?;
481                Ok(AstNode::Literal('\n'))
482            }
483            Some(&'t') => {
484                self.consume()?;
485                Ok(AstNode::Literal('\t'))
486            }
487            Some(&'r') => {
488                self.consume()?;
489                Ok(AstNode::Literal('\r'))
490            }
491            Some(&'f') => {
492                self.consume()?;
493                Ok(AstNode::Literal('\x0C'))
494            }
495            Some(&'v') => {
496                self.consume()?;
497                Ok(AstNode::Literal('\x0B'))
498            }
499            Some(&'\\') => {
500                self.consume()?;
501                Ok(AstNode::Literal('\\'))
502            }
503            Some(&ch) => {
504                self.consume()?;
505                // Literal escape (e.g. \*, \[)
506                Ok(AstNode::Literal(ch))
507            }
508        }
509    }
510
511    // Parse (group) or (?:non-capture) or (?<name>) or lookarounds
512    fn parse_group(&mut self) -> Result<AstNode, ParseError> {
513        self.consume()?; // consume (
514
515        self.depth += 1;
516        if self.depth > MAX_GROUP_DEPTH {
517            return Err(ParseError::NestingTooDeep(MAX_GROUP_DEPTH));
518        }
519
520        let result = if self.current() == Some(&'?') {
521            self.consume()?;
522            self.parse_extended_group()
523        } else {
524            // Capturing group
525            self.group_count += 1;
526            let index = self.group_count;
527            self.parse_alternation().and_then(|nodes| {
528                self.expect_close_paren()?;
529                Ok(AstNode::Group {
530                    nodes,
531                    name: None,
532                    capture: true,
533                    index: Some(index),
534                })
535            })
536        };
537
538        self.depth -= 1;
539        result
540    }
541
542    fn parse_extended_group(&mut self) -> Result<AstNode, ParseError> {
543        match self.current() {
544            Some(&':') => {
545                self.consume()?;
546                let nodes = self.parse_alternation()?;
547                self.expect_close_paren()?;
548                Ok(AstNode::Group {
549                    nodes,
550                    name: None,
551                    capture: false,
552                    index: None,
553                })
554            }
555            Some(&'<') => {
556                self.consume()?;
557                // Check for lookbehind
558                match self.current() {
559                    Some(&'=') => {
560                        self.consume()?;
561                        let nodes = self.parse_alternation()?;
562                        self.expect_close_paren()?;
563                        Ok(AstNode::LookBehind {
564                            nodes,
565                            positive: true,
566                        })
567                    }
568                    Some(&'!') => {
569                        self.consume()?;
570                        let nodes = self.parse_alternation()?;
571                        self.expect_close_paren()?;
572                        Ok(AstNode::LookBehind {
573                            nodes,
574                            positive: false,
575                        })
576                    }
577                    _ => {
578                        // Named capture (?<name>...)
579                        let name = self.parse_group_name()?;
580                        if self.current() != Some(&'>') {
581                            return Err(ParseError::InvalidGroupName("expected '>'".to_string()));
582                        }
583                        self.consume()?;
584
585                        self.group_count += 1;
586                        let index = self.group_count;
587
588                        let nodes = self.parse_alternation()?;
589                        self.expect_close_paren()?;
590                        Ok(AstNode::Group {
591                            nodes,
592                            name: Some(name),
593                            capture: true,
594                            index: Some(index),
595                        })
596                    }
597                }
598            }
599            Some(&'>') => {
600                self.consume()?;
601                match self.current() {
602                    Some(&'=') => {
603                        self.consume()?;
604                        let nodes = self.parse_alternation()?;
605                        self.expect_close_paren()?;
606                        Ok(AstNode::LookAhead {
607                            nodes,
608                            positive: true,
609                        })
610                    }
611                    Some(&'!') => {
612                        self.consume()?;
613                        let nodes = self.parse_alternation()?;
614                        self.expect_close_paren()?;
615                        Ok(AstNode::LookAhead {
616                            nodes,
617                            positive: false,
618                        })
619                    }
620                    _ => Err(ParseError::InvalidGroup(
621                        "Expected = or ! after ?>".to_string(),
622                    )),
623                }
624            }
625            // Subroutine call: recurse the whole pattern `(?R)`.
626            Some(&'R') => {
627                self.consume()?;
628                self.expect_close_paren()?;
629                Ok(AstNode::Subroutine(SubroutineTarget::Whole))
630            }
631            // Subroutine call: named group `(?&name)`. Resolved to a group
632            // number in a post-parse pass - see `resolve_subroutines`.
633            Some(&'&') => {
634                self.consume()?;
635                let name = self.parse_group_name()?;
636                self.expect_close_paren()?;
637                Ok(AstNode::Subroutine(SubroutineTarget::Name(name)))
638            }
639            // Subroutine call, alternate named syntax: `(?P>name)`.
640            Some(&'P') => {
641                self.consume()?;
642                if self.current() != Some(&'>') {
643                    return Err(ParseError::InvalidGroup(
644                        "Expected '>' after ?P".to_string(),
645                    ));
646                }
647                self.consume()?;
648                let name = self.parse_group_name()?;
649                self.expect_close_paren()?;
650                Ok(AstNode::Subroutine(SubroutineTarget::Name(name)))
651            }
652            // Subroutine call: absolute group number `(?N)`.
653            Some(&c) if c.is_ascii_digit() => {
654                let n = self.parse_number()?;
655                self.expect_close_paren()?;
656                Ok(AstNode::Subroutine(SubroutineTarget::Group(n)))
657            }
658            Some(&sign @ ('-' | '+')) => {
659                self.consume()?;
660                let n = self.parse_number()?;
661                self.expect_close_paren()?;
662                let count = self.group_count as isize;
663                let target = if sign == '-' {
664                    count - (n as isize) + 1
665                } else {
666                    count + n as isize
667                };
668                if target < 1 {
669                    return Err(ParseError::InvalidSubroutineReference(format!(
670                        "(?{sign}{n}) has no target group"
671                    )));
672                }
673                Ok(AstNode::Subroutine(SubroutineTarget::Group(
674                    target as usize,
675                )))
676            }
677            _ => Err(ParseError::InvalidGroup("Unknown extension ?".to_string())),
678        }
679    }
680
681    // Parse group name [a-zA-Z_][a-zA-Z0-9_]*
682    fn parse_group_name(&mut self) -> Result<String, ParseError> {
683        let mut name = String::new();
684
685        loop {
686            match self.current() {
687                Some(&c) if c.is_alphanumeric() || c == '_' => {
688                    name.push(c);
689                    self.consume()?;
690                }
691                _ => break,
692            }
693        }
694
695        if name.is_empty() {
696            return Err(ParseError::InvalidGroupName("empty name".to_string()));
697        }
698
699        Ok(name)
700    }
701
702    // Parse [char class]
703    fn parse_char_class(&mut self) -> Result<AstNode, ParseError> {
704        self.consume()?; // consume [
705
706        let negated = if self.current() == Some(&'^') {
707            self.consume()?;
708            true
709        } else {
710            false
711        };
712
713        let mut ranges = vec![];
714
715        loop {
716            match self.current() {
717                None => return Err(ParseError::UnexpectedEof),
718                Some(&']') => {
719                    self.consume()?;
720                    break;
721                }
722                Some(&'\\') => {
723                    // Escaped char in class
724                    self.consume()?;
725                    match self.current() {
726                        Some(&c) => {
727                            self.consume()?;
728                            ranges.push(CharRange { start: c, end: c });
729                        }
730                        None => return Err(ParseError::UnexpectedEof),
731                    }
732                }
733                Some(&c) => {
734                    self.consume()?;
735                    // Check for range
736                    if self.current() == Some(&'-')
737                        && self.peek_ahead(1).is_some()
738                        && self.peek_ahead(1) != Some(&']')
739                    {
740                        self.consume()?;
741                        match self.current() {
742                            Some(&end) => {
743                                self.consume()?;
744                                ranges.push(CharRange { start: c, end });
745                            }
746                            None => return Err(ParseError::UnexpectedEof),
747                        }
748                    } else {
749                        ranges.push(CharRange { start: c, end: c });
750                    }
751                }
752            }
753        }
754
755        Ok(AstNode::CharClass(CharClass::Set {
756            chars: ranges,
757            negated,
758        }))
759    }
760
761    // Apply quantifiers: *, +, ?, {n}, {n,m}, etc
762    fn apply_quantifier(&mut self, node: AstNode) -> Result<AstNode, ParseError> {
763        self.skip_whitespace_and_comments();
764        let quantified = match self.current() {
765            Some(&'*') => {
766                self.consume()?;
767                let greedy = self.current() != Some(&'?');
768                if !greedy {
769                    self.consume()?;
770                }
771                AstNode::ZeroOrMore {
772                    node: Box::new(node),
773                    greedy,
774                }
775            }
776            Some(&'+') => {
777                self.consume()?;
778                let greedy = self.current() != Some(&'?');
779                if !greedy {
780                    self.consume()?;
781                }
782                AstNode::OneOrMore {
783                    node: Box::new(node),
784                    greedy,
785                }
786            }
787            Some(&'?') => {
788                self.consume()?;
789                let greedy = self.current() != Some(&'?');
790                if !greedy {
791                    self.consume()?;
792                }
793                AstNode::Optional {
794                    node: Box::new(node),
795                    greedy,
796                }
797            }
798            Some(&'{') => self.parse_bounded_quantifier(node)?,
799            _ => return Ok(node),
800        };
801        self.apply_quantifier(quantified)
802    }
803
804    // Parse {n}, {n,}, {n,m}, {,m}
805    fn parse_bounded_quantifier(&mut self, node: AstNode) -> Result<AstNode, ParseError> {
806        self.consume()?; // consume {
807
808        // Parse min
809        let min = if self.current() == Some(&',') {
810            0
811        } else {
812            self.parse_number()?
813        };
814
815        match self.current() {
816            Some(&',') => {
817                self.consume()?;
818                // Parse max (optional)
819                let max = if self.current() == Some(&'}') {
820                    None
821                } else {
822                    Some(self.parse_number()?)
823                };
824
825                if self.current() != Some(&'}') {
826                    return Err(ParseError::InvalidQuantifier("expected '}'".to_string()));
827                }
828                self.consume()?;
829
830                let greedy = self.current() != Some(&'?');
831                if !greedy {
832                    self.consume()?;
833                }
834
835                Ok(AstNode::Range {
836                    node: Box::new(node),
837                    min,
838                    max,
839                    greedy,
840                })
841            }
842            Some(&'}') => {
843                self.consume()?;
844                if self.current() == Some(&'?') {
845                    self.consume()?;
846                }
847                Ok(AstNode::Exact {
848                    node: Box::new(node),
849                    count: min,
850                })
851            }
852            _ => Err(ParseError::InvalidQuantifier(
853                "expected ',' or '}'".to_string(),
854            )),
855        }
856    }
857
858    // Helper: parse a decimal number
859    fn parse_number(&mut self) -> Result<usize, ParseError> {
860        let mut num = 0;
861        let mut found = false;
862
863        while let Some(&c @ '0'..='9') = self.current() {
864            found = true;
865            num = num * 10 + (c.to_digit(10).unwrap() as usize);
866            self.consume()?;
867        }
868
869        if !found {
870            return Err(ParseError::InvalidLineNumber("expected digits".to_string()));
871        }
872
873        Ok(num)
874    }
875
876    fn expect_close_paren(&mut self) -> Result<(), ParseError> {
877        if self.current() != Some(&')') {
878            return Err(ParseError::UnmatchedParen);
879        }
880        self.consume()?;
881        Ok(())
882    }
883
884    // Helper: get current char without advancing
885    fn current(&self) -> Option<&char> {
886        self.input.get(self.pos)
887    }
888
889    // Helper: peek ahead n positions
890    fn peek_ahead(&self, n: usize) -> Option<&char> {
891        self.input.get(self.pos + n)
892    }
893
894    // Helper: peek next char
895    fn peek(&self) -> Option<char> {
896        self.input.get(self.pos).copied()
897    }
898
899    // Helper: consume current char and advance
900    fn consume(&mut self) -> Result<char, ParseError> {
901        match self.current() {
902            Some(&ch) => {
903                self.pos += 1;
904                Ok(ch)
905            }
906            None => Err(ParseError::UnexpectedEof),
907        }
908    }
909}
910
911fn collect_group_names(nodes: &[AstNode], names: &mut HashMap<String, usize>) {
912    for node in nodes {
913        match node {
914            AstNode::Group {
915                nodes, name, index, ..
916            } => {
917                if let (Some(n), Some(i)) = (name, index) {
918                    names.insert(n.clone(), *i);
919                }
920                collect_group_names(nodes, names);
921            }
922            AstNode::Alternation(alts) => {
923                for alt in alts {
924                    collect_group_names(alt, names);
925                }
926            }
927            AstNode::ZeroOrMore { node, .. }
928            | AstNode::OneOrMore { node, .. }
929            | AstNode::Optional { node, .. }
930            | AstNode::Exact { node, .. }
931            | AstNode::Range { node, .. } => {
932                collect_group_names(std::slice::from_ref(node), names);
933            }
934            AstNode::LookAhead { nodes, .. } | AstNode::LookBehind { nodes, .. } => {
935                collect_group_names(nodes, names);
936            }
937            _ => {}
938        }
939    }
940}
941
942fn resolve_subroutines(
943    nodes: &mut [AstNode],
944    names: &HashMap<String, usize>,
945    max_group: usize,
946) -> Result<(), ParseError> {
947    for node in nodes {
948        match node {
949            AstNode::Subroutine(target) => {
950                if let SubroutineTarget::Name(n) = target {
951                    let idx = names.get(n).copied().ok_or_else(|| {
952                        ParseError::InvalidSubroutineReference(format!(
953                            "no group named '{n}'"
954                        ))
955                    })?;
956                    *target = SubroutineTarget::Group(idx);
957                }
958                if let SubroutineTarget::Group(n) = target
959                    && (*n == 0 || *n > max_group)
960                {
961                    return Err(ParseError::InvalidSubroutineReference(format!(
962                        "reference to non-existent group {n}"
963                    )));
964                }
965            }
966            AstNode::Group { nodes, .. } => resolve_subroutines(nodes, names, max_group)?,
967            AstNode::Alternation(alts) => {
968                for alt in alts {
969                    resolve_subroutines(alt, names, max_group)?;
970                }
971            }
972            AstNode::ZeroOrMore { node, .. }
973            | AstNode::OneOrMore { node, .. }
974            | AstNode::Optional { node, .. }
975            | AstNode::Exact { node, .. }
976            | AstNode::Range { node, .. } => {
977                resolve_subroutines(std::slice::from_mut(node), names, max_group)?;
978            }
979            AstNode::LookAhead { nodes, .. } | AstNode::LookBehind { nodes, .. } => {
980                resolve_subroutines(nodes, names, max_group)?;
981            }
982            _ => {}
983        }
984    }
985    Ok(())
986}