1use crate::flags::Flags;
2use std::collections::HashMap;
3use std::fmt;
4
5#[derive(Debug, Clone, PartialEq)]
7pub enum AstNode {
8 Literal(char),
10
11 CharClass(CharClass),
13
14 StartAnchor,
16 EndAnchor,
18 WordBoundary,
20 StartWord,
22 EndWord,
24 SetMatchStart,
26 SetMatchEnd,
28
29 ZeroOrMore {
31 node: Box<AstNode>,
33 greedy: bool,
35 },
36 OneOrMore {
38 node: Box<AstNode>,
40 greedy: bool,
42 },
43 Optional {
45 node: Box<AstNode>,
47 greedy: bool,
49 },
50 Exact {
52 node: Box<AstNode>,
54 count: usize,
56 },
57 Range {
59 node: Box<AstNode>,
61 min: usize,
63 max: Option<usize>,
65 greedy: bool,
67 },
68
69 Group {
71 nodes: Vec<AstNode>,
73 name: Option<String>,
75 capture: bool,
77 index: Option<usize>,
79 },
80 Alternation(Vec<Vec<AstNode>>),
82
83 Backref(usize),
85
86 LookAhead {
88 nodes: Vec<AstNode>,
90 positive: bool,
92 },
93 LookBehind {
95 nodes: Vec<AstNode>,
97 positive: bool,
99 },
100
101 Subroutine(SubroutineTarget),
102}
103
104#[derive(Debug, Clone, PartialEq)]
105pub enum SubroutineTarget {
106 Whole,
108 Group(usize),
110 Name(String),
112}
113
114#[derive(Debug, Clone, PartialEq)]
116pub enum CharClass {
117 Digit,
120 NonDigit,
122 Word,
124 NonWord,
126 Whitespace,
128 NonWhitespace,
130
131 Lowercase,
134 NonLowercase,
136 Uppercase,
138 NonUppercase,
140 Hex,
142 NonHex,
144 Octal,
146 NonOctal,
148 WordStart,
150 NonWordStart,
152 Punctuation,
154 NonPunctuation,
156 Alphanumeric,
158 NonAlphanumeric,
160
161 Set {
164 chars: Vec<CharRange>,
166 negated: bool,
168 },
169
170 Dot,
172}
173
174#[derive(Debug, Clone, PartialEq)]
176pub struct CharRange {
177 pub start: char,
179 pub end: char,
181}
182
183const MAX_GROUP_DEPTH: usize = 200;
184
185#[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#[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 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 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 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 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 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 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 fn parse_escape(&mut self) -> Result<AstNode, ParseError> {
364 self.consume()?; 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 Ok(AstNode::Literal(ch))
507 }
508 }
509 }
510
511 fn parse_group(&mut self) -> Result<AstNode, ParseError> {
513 self.consume()?; 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 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 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 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 Some(&'R') => {
627 self.consume()?;
628 self.expect_close_paren()?;
629 Ok(AstNode::Subroutine(SubroutineTarget::Whole))
630 }
631 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 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 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 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 fn parse_char_class(&mut self) -> Result<AstNode, ParseError> {
704 self.consume()?; 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 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 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 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 fn parse_bounded_quantifier(&mut self, node: AstNode) -> Result<AstNode, ParseError> {
806 self.consume()?; 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 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 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 fn current(&self) -> Option<&char> {
886 self.input.get(self.pos)
887 }
888
889 fn peek_ahead(&self, n: usize) -> Option<&char> {
891 self.input.get(self.pos + n)
892 }
893
894 fn peek(&self) -> Option<char> {
896 self.input.get(self.pos).copied()
897 }
898
899 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}