Debian Codegraph @

debian/rust-vendor/fancy-regex/src/analyze.rs

raw
1 // Copyright 2016 The Fancy Regex Authors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 //! Analysis of regex expressions.
22
23 use alloc::boxed::Box;
24 use alloc::format;
25 use alloc::string::String;
26 use alloc::vec::Vec;
27 use core::cmp::{max, min};
28
29 use bit_set::BitSet;
30
31 use crate::alloc::string::ToString;
32 use crate::parse::ExprTree;
33 use crate::vm::CaptureGroupRange;
34 use crate::{Assertion, AstNode, CaptureGroupTarget, CompileError, Error, Expr, Result};
35
36 #[cfg(not(feature = "std"))]
37 use alloc::collections::BTreeMap as Map;
38 #[cfg(feature = "std")]
39 use std::collections::HashMap as Map;
40
41 /// Analysis information for a regex expression.
42 ///
43 /// This structure contains the results of analyzing a regex expression,
44 /// including size information, whether it requires backtracking features,
45 /// and references to child expressions in the tree.
46 #[derive(Debug)]
47 pub struct Info<'a> {
48 pub(crate) capture_groups: CaptureGroupRange,
49 /// The minimum number of characters this expression will match
50 pub min_size: usize,
51 /// The maximum number of characters this expression can match
52 pub max_size: usize,
53 /// Whether this expression always matches the same number of characters
54 pub const_size: bool,
55 /// Tracks the minimum number of characters that would be consumed in the innermost capture group
56 /// before this expression is matched.
57 pub(crate) min_pos_in_group: usize,
58 /// Whether this expression requires backtracking features (lookaround, backrefs, etc.)
59 pub hard: bool,
60 /// The expression being analyzed
61 pub expr: &'a Expr,
62 /// Analysis information for child expressions
63 pub children: Vec<Info<'a>>,
64 }
65
66 impl<'a> Info<'a> {
67 /// Returns the start (first) group number for this expression.
68 pub fn start_group(&self) -> usize {
69 self.capture_groups.start()
70 }
71
72 /// Returns the end (last) group number for this expression.
73 pub fn end_group(&self) -> usize {
74 self.capture_groups.end()
75 }
76
77 pub(crate) fn push_literal(&self, buf: &mut String) {
78 match *self.expr {
79 // could be more paranoid about checking casei
80 Expr::Literal { ref val, .. } => buf.push_str(val),
81 Expr::Concat(_) => {
82 for child in &self.children {
83 child.push_literal(buf);
84 }
85 }
86 _ => panic!("push_literal called on non-literal"),
87 }
88 }
89
90 /// `None` if this is not a literal; `Some(casei)` if it is, where `casei`
91 /// says whether any character is case-insensitive.
92 pub(crate) fn is_literal_get_casei(&self) -> Option<bool> {
93 match *self.expr {
94 Expr::Literal { casei, .. } => Some(casei),
95 Expr::Concat(_) => self.children.iter().try_fold(false, |any, child| {
96 child.is_literal_get_casei().map(|c| any || c)
97 }),
98 _ => None,
99 }
100 }
101
102 /// Pushes each character of the literal along with its case-insensitivity.
103 pub(crate) fn push_literal_chars(&self, buf: &mut Vec<(char, bool)>) {
104 match *self.expr {
105 Expr::Literal { ref val, casei } => buf.extend(val.chars().map(|c| (c, casei))),
106 Expr::Concat(_) => {
107 for child in &self.children {
108 child.push_literal_chars(buf);
109 }
110 }
111 _ => panic!("push_literal_chars called on non-literal"),
112 }
113 }
114 }
115
116 struct SizeInfo {
117 min_size: usize,
118 const_size: bool,
119 max_size: usize,
120 }
121
122 /// Represents a subroutine call and its minimum position within a group
123 #[derive(Debug, Clone)]
124 struct SubroutineCallInfo {
125 /// The group being called
126 target_group: usize,
127 /// The minimum number of characters consumed in the haystack by the capture group in which this call occurs
128 min_pos: usize,
129 }
130
131 struct Analyzer<'a> {
132 backrefs: &'a BitSet,
133 /// The next group number to assign when a new capture group is encountered.
134 /// Starts at 0 or 1 depending on whether explicit capture group 0 is enabled,
135 /// and increments for each capture group found during traversal.
136 next_group_number: usize,
137 /// Stores the analysis info for each group by group number
138 // NOTE: uses a Map instead of a Vec because sometimes we start from capture group 1, other times 0
139 group_info: Map<usize, SizeInfo>,
140 /// Tracks subroutine calls: maps from a group to the subroutines it calls
141 subroutine_calls: Map<usize, Vec<SubroutineCallInfo>>,
142 /// Groups that are directly executed from root (not inside {0})
143 root_groups: BitSet,
144 /// Pre-populated map of capture group index to the inner expression of that group.
145 /// Only pre-populated/used when there are subroutine calls, to enable correct resolution
146 /// of forward references, to detect whether they are const-size etc.
147 group_exprs: Map<usize, &'a Expr>,
148 /// Track groups currently being analyzed to prevent infinite recursion
149 analyzing_groups: BitSet,
150 /// When true, nodes that could produce empty matches (min size 0 and not const size)
151 /// are promoted to hard so the VM can backtrack past them to find a non-empty match.
152 find_not_empty: bool,
153 /// When true, nodes that could produce empty matches (min size 0 and not const size)
154 /// are promoted to hard so the VM can ensure the whole match at EOF isn't empty.
155 disallow_empty_match_at_eof_after_newline: bool,
156 /// When true, assertions with runtime input suppression overrides are promoted to hard
157 /// so they run on the VM.
158 allow_input_assertion_overrides: bool,
159 /// When true, leftmost-longest match semantics are enabled.
160 #[cfg(feature = "leftmost_longest")]
161 leftmost_longest: bool,
162 /// Oniguruma's `^` rejects the empty match at the absolute end of the haystack after a trailing
163 /// newline when it anchors the match itself. When used as a sub-assertion inside a lookaround,
164 /// it behaves as a plain line start. So we need to track when we are analyzing inside a lookaround.
165 in_lookaround: bool,
166 }
167
168 impl<'a> Analyzer<'a> {
169 // enclosing_group: The group that currently contains the expression being analyzed.
170 // This is used to track which group "owns" any subroutine calls found,
171 // and to determine if we're at the root level (group 0).
172 fn visit(
173 &mut self,
174 expr: &'a Expr,
175 min_pos_in_group: usize,
176 inside_zero_rep: bool,
177 enclosing_group: usize,
178 ) -> Result<Info<'a>> {
179 let start_group = self.next_group_number;
180 let mut children = match *expr {
181 Expr::Concat(ref v) | Expr::Alt(ref v) => Vec::with_capacity(v.len()),
182 _ => Vec::new(),
183 };
184 let mut min_size: usize = 0;
185 let mut const_size = false;
186 let mut max_size: usize = 0;
187 let mut hard = false;
188 match *expr {
189 Expr::Assertion(assertion) if assertion.is_always_hard() => {
190 const_size = true;
191 hard = true;
192 }
193 Expr::Assertion(Assertion::StartLineOniguruma { .. }) if !self.in_lookaround => {
194 const_size = true;
195 hard = true;
196 }
197 Expr::Assertion(Assertion::StartText | Assertion::EndText)
198 if self.allow_input_assertion_overrides =>
199 {
200 const_size = true;
201 hard = true;
202 }
203 Expr::Assertion(Assertion::EndText)
204 if self.disallow_empty_match_at_eof_after_newline =>
205 {
206 const_size = true;
207 hard = true; // NOTE: \Z is already considered hard and covered in the branch above
208 }
209 Expr::Assertion(Assertion::EndText) if self.find_not_empty && !self.in_lookaround => {
210 const_size = true;
211 hard = true;
212 }
213 Expr::Empty | Expr::Assertion(_) => {
214 const_size = true;
215 }
216 Expr::Any { .. } => {
217 min_size = 1;
218 const_size = true;
219 max_size = 1;
220 }
221 Expr::GeneralNewline { .. } => {
222 // \R matches either \r\n (2 chars) or single newline chars (1 char)
223 // So it has min_size = 1, but is not const_size
224 min_size = 1;
225 const_size = false;
226 hard = true; // requires backtracking to handle \r\n without backtracking to \r
227 max_size = 2;
228 }
229 Expr::Literal { ref val, casei } => {
230 // right now each character in a literal gets its own node, that might change
231 min_size = 1;
232 const_size = literal_const_size(val, casei);
233 max_size = 1;
234 }
235 Expr::Concat(ref v) => {
236 const_size = true;
237 let mut pos_in_group = min_pos_in_group;
238 for child in v {
239 let child_info =
240 self.visit(child, pos_in_group, inside_zero_rep, enclosing_group)?;
241 min_size = min_size.saturating_add(child_info.min_size);
242 max_size = if max_size == usize::MAX || child_info.max_size == usize::MAX {
243 usize::MAX
244 } else {
245 max_size.saturating_add(child_info.max_size)
246 };
247 const_size &= child_info.const_size;
248 hard |= child_info.hard;
249 pos_in_group = pos_in_group.saturating_add(child_info.min_size);
250 children.push(child_info);
251 }
252 }
253 Expr::Alt(ref v) => {
254 let child_info =
255 self.visit(&v[0], min_pos_in_group, inside_zero_rep, enclosing_group)?;
256 min_size = child_info.min_size;
257 max_size = child_info.max_size;
258 const_size = child_info.const_size;
259 hard = child_info.hard;
260 children.push(child_info);
261 for child in &v[1..] {
262 let child_info =
263 self.visit(child, min_pos_in_group, inside_zero_rep, enclosing_group)?;
264 const_size &= child_info.const_size && min_size == child_info.min_size;
265 min_size = min(min_size, child_info.min_size);
266 max_size = max(max_size, child_info.max_size);
267 hard |= child_info.hard;
268 children.push(child_info);
269 }
270 }
271 Expr::Group(ref child) => {
272 let group = self.next_group_number;
273 self.next_group_number += 1;
274 self.analyzing_groups.insert(group);
275
276 // Track if this group is executed from root (not inside {0})
277 if enclosing_group == 0 && !inside_zero_rep {
278 self.root_groups.insert(group);
279 }
280
281 let child_info = self.visit(child, 0, inside_zero_rep, group)?;
282 self.analyzing_groups.remove(group);
283 min_size = child_info.min_size;
284 max_size = child_info.max_size;
285 const_size = child_info.const_size;
286 // Store the group info for use by backrefs
287 self.group_info.insert(
288 group,
289 SizeInfo {
290 min_size,
291 const_size,
292 max_size,
293 },
294 );
295 // If there's a backref to this group, we potentially have to backtrack within the
296 // group. E.g. with `(x|xy)\1` and input `xyxy`, `x` matches but then the backref
297 // doesn't, so we have to backtrack and try `xy`.
298 hard = child_info.hard | self.backrefs.contains(group);
299 children.push(child_info);
300 }
301 Expr::LookAround(ref child, _) => {
302 let was_in_lookaround = self.in_lookaround;
303 self.in_lookaround = true;
304 // NOTE: min_pos_in_group might seem weird for lookbehinds
305 let child_info =
306 self.visit(child, min_pos_in_group, inside_zero_rep, enclosing_group)?;
307 self.in_lookaround = was_in_lookaround;
308 // min_size = 0
309 const_size = true;
310 hard = true;
311 children.push(child_info);
312 }
313 Expr::Repeat {
314 ref child,
315 lo,
316 hi,
317 #[cfg(feature = "leftmost_longest")]
318 greedy,
319 ..
320 } => {
321 #[cfg(feature = "leftmost_longest")]
322 if !greedy && self.leftmost_longest {
323 return Err(Error::CompileError(Box::new(
324 CompileError::FeatureNotYetSupported(
325 "non-greedy quantifiers are not supported in leftmost-longest mode"
326 .to_string(),
327 ),
328 )));
329 }
330 // If lo and hi are both 0, we're in a zero-repetition (unreachable)
331 let child_inside_zero_rep = if lo == 0 && hi == 0 {
332 true
333 } else {
334 inside_zero_rep
335 };
336 let child_info = self.visit(
337 child,
338 min_pos_in_group,
339 child_inside_zero_rep,
340 enclosing_group,
341 )?;
342 min_size = child_info.min_size * lo;
343 max_size = if hi == usize::MAX || child_info.max_size == usize::MAX {
344 usize::MAX
345 } else {
346 child_info.max_size.saturating_mul(hi)
347 };
348 const_size = child_info.const_size && lo == hi;
349 hard = child_info.hard;
350 children.push(child_info);
351 }
352 Expr::Delegate { .. } => {
353 // Delegate expressions always match exactly 1 character.
354 // This constraint ensures consistency in the AST representation.
355 min_size = 1;
356 const_size = true;
357 max_size = 1;
358 }
359 Expr::Backref { group, .. } => {
360 if group == 0 {
361 return Err(Error::CompileError(Box::new(CompileError::InvalidBackref(
362 group,
363 ))));
364 }
365
366 // Check if this backref is inside a recursed group that it refers to
367 // This happens when:
368 // 1. The backref refers to a group we're currently analyzing
369 // 2. That group has a subroutine call to itself
370 if self.analyzing_groups.contains(group) {
371 // Check if the group has a recursive subroutine call to itself
372 if let Some(calls) = self.subroutine_calls.get(&group) {
373 if calls.iter().any(|call| call.target_group == group) {
374 return Err(Error::CompileError(Box::new(
375 CompileError::FeatureNotYetSupported(
376 "Backreference to a capture group from within the same group when it's being recursed".to_string()
377 )
378 )));
379 }
380 }
381 }
382
383 // Look up the referenced group's size information
384 if let Some(&SizeInfo {
385 min_size: group_min_size,
386 max_size: group_max_size,
387 const_size: group_const_size,
388 ..
389 }) = self.group_info.get(&group)
390 {
391 min_size = group_min_size;
392 max_size = group_max_size;
393 const_size = group_const_size;
394 }
395 hard = true;
396 }
397 Expr::AtomicGroup(ref child) => {
398 let child_info =
399 self.visit(child, min_pos_in_group, inside_zero_rep, enclosing_group)?;
400 min_size = child_info.min_size;
401 max_size = child_info.max_size;
402 const_size = child_info.const_size;
403 hard = true; // TODO: possibly could weaken
404 children.push(child_info);
405 }
406 Expr::KeepOut => {
407 hard = true;
408 const_size = true;
409 }
410 Expr::ContinueFromPreviousMatchEnd => {
411 hard = true;
412 const_size = true;
413 }
414 Expr::BackrefExistsCondition { .. } => {
415 hard = true;
416 const_size = true;
417 }
418 Expr::BacktrackingControlVerb(_) => {
419 hard = true;
420 const_size = true;
421 }
422 Expr::Conditional {
423 ref condition,
424 ref true_branch,
425 ref false_branch,
426 } => {
427 hard = true;
428
429 let child_info_condition = self.visit(
430 condition,
431 min_pos_in_group,
432 inside_zero_rep,
433 enclosing_group,
434 )?;
435 let child_info_truth = self.visit(
436 true_branch,
437 min_pos_in_group + child_info_condition.min_size,
438 inside_zero_rep,
439 enclosing_group,
440 )?;
441 let child_info_false = self.visit(
442 false_branch,
443 min_pos_in_group,
444 inside_zero_rep,
445 enclosing_group,
446 )?;
447
448 min_size = child_info_condition.min_size
449 + min(child_info_truth.min_size, child_info_false.min_size);
450 max_size = max(child_info_truth.max_size, child_info_false.max_size);
451 const_size = child_info_condition.const_size
452 && child_info_truth.const_size
453 && child_info_false.const_size
454 // if the condition's size plus the truth branch's size is equal to the false branch's size then it's const size
455 && child_info_condition.min_size + child_info_truth.min_size == child_info_false.min_size;
456
457 children.push(child_info_condition);
458 children.push(child_info_truth);
459 children.push(child_info_false);
460 }
461 Expr::SubroutineCall(target_group) => {
462 // Track this subroutine call
463 // Only skip tracking if we're in unreachable code at the root level
464 // Calls inside groups should always be tracked, even if the group is inside {0} at root,
465 // because the group can be called as a subroutine from elsewhere
466 if !inside_zero_rep || enclosing_group != 0 {
467 self.subroutine_calls
468 .entry(enclosing_group)
469 .or_default()
470 .push(SubroutineCallInfo {
471 target_group,
472 min_pos: min_pos_in_group,
473 });
474 }
475
476 // Look up the target group's min_size if available (similar to backrefs)
477 // This is important for accurate left recursion detection
478 if let Some(&SizeInfo {
479 min_size: group_min_size,
480 const_size: group_const_size,
481 max_size: group_max_size,
482 }) = self.group_info.get(&target_group)
483 {
484 min_size = group_min_size;
485 max_size = group_max_size;
486 const_size = group_const_size;
487 } else if self.analyzing_groups.contains(target_group) {
488 // Currently analyzing this group - circular reference
489 // Use conservative defaults to avoid infinite recursion
490 min_size = 0;
491 max_size = usize::MAX;
492 const_size = false;
493 } else if let Some(&group_expr) = self.group_exprs.get(&target_group) {
494 // If the group hasn't been seen yet (forward reference),
495 // directly analyze it now
496 self.analyzing_groups.insert(target_group);
497
498 // Save and restore next_group_number around the recursive call
499 let prev_next_group_number = self.next_group_number;
500 self.next_group_number = target_group + 1;
501 let group_info = self.visit(group_expr, 0, inside_zero_rep, target_group)?;
502 self.next_group_number = prev_next_group_number;
503
504 self.analyzing_groups.remove(target_group);
505
506 min_size = group_info.min_size;
507 max_size = group_info.max_size;
508 const_size = group_info.const_size;
509 // Store the analysis result for future lookups
510 self.group_info.insert(
511 target_group,
512 SizeInfo {
513 min_size,
514 const_size,
515 max_size,
516 },
517 );
518 } else {
519 // Group doesn't exist - this shouldn't happen as the parser would have caught it
520 min_size = 0;
521 max_size = usize::MAX;
522 const_size = false;
523 }
524 hard = true;
525 }
526 Expr::AstNode(ref astnode, ix) => {
527 // An unresolved AstNode means the resolver couldn't find the target (e.g. a
528 // subroutine call to an unknown name). Match each SubroutineCall variant to
529 // produce an accurate error message; any other AstNode variant is an internal
530 // error and gets a distinct UnresolvedAstNode error.
531 match astnode {
532 AstNode::SubroutineCall(CaptureGroupTarget::ByName(name)) => {
533 return Err(Error::CompileError(Box::new(
534 CompileError::SubroutineCallTargetNotFound(
535 format!("named group '{}'", name),
536 ix,
537 ),
538 )));
539 }
540 AstNode::SubroutineCall(CaptureGroupTarget::ByNumber(n)) => {
541 return Err(Error::CompileError(Box::new(
542 CompileError::SubroutineCallTargetNotFound(
543 format!("group number {}", n),
544 ix,
545 ),
546 )));
547 }
548 AstNode::SubroutineCall(CaptureGroupTarget::Relative(n)) => {
549 return Err(Error::CompileError(Box::new(
550 CompileError::SubroutineCallTargetNotFound(
551 format!("relative group {}{}", if *n >= 0 { "+" } else { "" }, n),
552 ix,
553 ),
554 )));
555 }
556 AstNode::AstGroup { .. }
557 | AstNode::Backref { .. }
558 | AstNode::BackrefExistsCondition { .. } => {
559 return Err(Error::CompileError(Box::new(
560 CompileError::UnresolvedAstNode(ix, format!("{:?}", astnode)),
561 )));
562 }
563 }
564 }
565 Expr::BackrefWithRelativeRecursionLevel { .. } => {
566 return Err(Error::CompileError(Box::new(
567 CompileError::FeatureNotYetSupported("Backref at recursion level".to_string()),
568 )));
569 }
570 Expr::Absent(ref absent) => {
571 use crate::Absent::*;
572 match absent {
573 Repeater(ref child) => {
574 let child_info =
575 self.visit(child, min_pos_in_group, inside_zero_rep, enclosing_group)?;
576 min_size = 0;
577 max_size = usize::MAX;
578 const_size = false;
579 hard = true;
580 children.push(child_info);
581 }
582 Expression {
583 ref absent,
584 ref exp,
585 } => {
586 let absent_info =
587 self.visit(absent, min_pos_in_group, inside_zero_rep, enclosing_group)?;
588 let exp_info =
589 self.visit(exp, min_pos_in_group, inside_zero_rep, enclosing_group)?;
590 min_size = exp_info.min_size;
591 max_size = exp_info.max_size;
592 const_size = false;
593 hard = true;
594 children.push(absent_info);
595 children.push(exp_info);
596 }
597 Stopper(ref child) => {
598 let child_info =
599 self.visit(child, min_pos_in_group, inside_zero_rep, enclosing_group)?;
600 // Absent stopper doesn't consume any characters itself
601 min_size = 0;
602 max_size = 0;
603 const_size = true;
604 hard = true;
605 children.push(child_info);
606 }
607 Clear => {
608 // Range clear doesn't consume any characters
609 min_size = 0;
610 max_size = 0;
611 const_size = true;
612 hard = true;
613 }
614 }
615 }
616 Expr::DefineGroup { ref definitions } => {
617 // DEFINE groups don't match anything themselves, but we still need to
618 // visit the definitions to assign group numbers and analyze any nested content.
619 // The DEFINE block itself is not hard - it matches nothing, so it can be
620 // delegated (as an empty string) to the underlying engine.
621 let def_info = self.visit(definitions, 0, inside_zero_rep, enclosing_group)?;
622 min_size = 0;
623 max_size = 0;
624 const_size = true;
625 children.push(def_info);
626 }
627 };
628
629 // When find_not_empty is active, any node that could produce an empty match
630 // must be handled by the VM so it can backtrack past it to find a non-empty match.
631 if self.find_not_empty && min_size == 0 && !const_size {
632 hard = true;
633 }
634 #[cfg(feature = "leftmost_longest")]
635 if self.leftmost_longest && !const_size {
636 hard = true;
637 }
638
639 Ok(Info {
640 expr,
641 children,
642 capture_groups: CaptureGroupRange(start_group, self.next_group_number),
643 min_size,
644 max_size,
645 const_size,
646 hard,
647 min_pos_in_group,
648 })
649 }
650
651 /// Check for left-recursive subroutine calls using depth-first search
652 fn check_left_recursion(&self, named_groups: &Map<String, usize>) -> Result<()> {
653 // Compute which groups are reachable from the root (group 0)
654 let reachable_groups = self.compute_reachable_groups();
655
656 // Check each reachable group for left recursion
657 for &start_group in self.subroutine_calls.keys() {
658 if !reachable_groups.contains(start_group) {
659 // Skip unreachable groups
660 continue;
661 }
662
663 let mut visited = BitSet::new();
664 let mut recursion_stack = BitSet::new();
665 if self.dfs_check_left_recursion(start_group, &mut visited, &mut recursion_stack)? {
666 // Found left recursion
667 // Build reverse mapping from group number to group name (if any)
668 // so we can give friendly error messages
669 let mut group_names: Map<usize, String> = Map::new();
670 for (name, &group_num) in named_groups.iter() {
671 group_names.insert(group_num, name.clone());
672 }
673
674 let group_desc = if let Some(name) = group_names.get(&start_group) {
675 format!("group '{}' ({})", name, start_group)
676 } else {
677 format!("group {}", start_group)
678 };
679 return Err(Error::CompileError(Box::new(
680 CompileError::LeftRecursiveSubroutineCall(group_desc),
681 )));
682 }
683 }
684 Ok(())
685 }
686
687 /// Check for recursive subroutine calls that can never terminate
688 fn check_unbounded_recursion(&self, root_expr: &'a Expr) -> Result<()> {
689 let mut memo = Map::new();
690 if self.group_can_terminate(0, root_expr, &mut BitSet::new(), &mut memo) {
691 return Ok(());
692 }
693
694 Err(Error::CompileError(Box::new(
695 CompileError::NeverEndingRecursion,
696 )))
697 }
698
699 fn group_can_terminate(
700 &self,
701 group: usize,
702 root_expr: &'a Expr,
703 recursion_stack: &mut BitSet,
704 memo: &mut Map<usize, bool>,
705 ) -> bool {
706 if let Some(&can_terminate) = memo.get(&group) {
707 return can_terminate;
708 }
709
710 if recursion_stack.contains(group) {
711 return false;
712 }
713
714 let expr = if group == 0 {
715 root_expr
716 } else if let Some(&group_expr) = self.group_exprs.get(&group) {
717 group_expr
718 } else {
719 return true;
720 };
721
722 recursion_stack.insert(group);
723 let can_terminate = self.expr_can_terminate(expr, root_expr, recursion_stack, memo);
724 recursion_stack.remove(group);
725 memo.insert(group, can_terminate);
726 can_terminate
727 }
728
729 fn expr_can_terminate(
730 &self,
731 expr: &'a Expr,
732 root_expr: &'a Expr,
733 recursion_stack: &mut BitSet,
734 memo: &mut Map<usize, bool>,
735 ) -> bool {
736 match expr {
737 Expr::Concat(children) => children
738 .iter()
739 .all(|child| self.expr_can_terminate(child, root_expr, recursion_stack, memo)),
740 Expr::Alt(children) => children
741 .iter()
742 .any(|child| self.expr_can_terminate(child, root_expr, recursion_stack, memo)),
743 Expr::Group(child) => self.expr_can_terminate(child, root_expr, recursion_stack, memo),
744 Expr::LookAround(child, _) => {
745 self.expr_can_terminate(child, root_expr, recursion_stack, memo)
746 }
747 Expr::AtomicGroup(child) => {
748 self.expr_can_terminate(child, root_expr, recursion_stack, memo)
749 }
750 Expr::Repeat { child, lo, .. } => {
751 *lo == 0 || self.expr_can_terminate(child, root_expr, recursion_stack, memo)
752 }
753 Expr::Conditional {
754 condition,
755 true_branch,
756 false_branch,
757 } => {
758 self.expr_can_terminate(false_branch, root_expr, recursion_stack, memo)
759 || (self.expr_can_terminate(condition, root_expr, recursion_stack, memo)
760 && self.expr_can_terminate(true_branch, root_expr, recursion_stack, memo))
761 }
762 Expr::SubroutineCall(target_group) => {
763 self.group_can_terminate(*target_group, root_expr, recursion_stack, memo)
764 }
765 Expr::Absent(absent) => {
766 use crate::Absent::*;
767 match absent {
768 Repeater(child) | Stopper(child) => {
769 self.expr_can_terminate(child, root_expr, recursion_stack, memo)
770 }
771 Expression { absent, exp } => {
772 self.expr_can_terminate(absent, root_expr, recursion_stack, memo)
773 && self.expr_can_terminate(exp, root_expr, recursion_stack, memo)
774 }
775 Clear => true,
776 }
777 }
778 Expr::BackrefWithRelativeRecursionLevel { .. } => true,
779 Expr::DefineGroup { definitions } => {
780 self.expr_can_terminate(definitions, root_expr, recursion_stack, memo)
781 }
782 _ => true,
783 }
784 }
785
786 /// A group is reachable if it's executed from root (not inside {0}) or called from a reachable group
787 fn compute_reachable_groups(&self) -> BitSet {
788 let mut reachable = BitSet::new();
789 let mut to_visit = Vec::new();
790
791 // Start from root (group 0)
792 // Group 0 is always reachable
793 reachable.insert(0);
794 to_visit.push(0);
795
796 // Also mark groups that are directly executed from root (not inside {0})
797 for group in self.root_groups.iter() {
798 if !reachable.contains(group) {
799 reachable.insert(group);
800 to_visit.push(group);
801 }
802 }
803
804 // Propagate reachability through subroutine calls
805 while let Some(group) = to_visit.pop() {
806 if let Some(calls) = self.subroutine_calls.get(&group) {
807 for call_info in calls {
808 if !reachable.contains(call_info.target_group) {
809 reachable.insert(call_info.target_group);
810 to_visit.push(call_info.target_group);
811 }
812 }
813 }
814 }
815
816 reachable
817 }
818
819 /// Depth-first search to detect left recursion
820 /// Returns true if left recursion is detected
821 fn dfs_check_left_recursion(
822 &self,
823 group: usize,
824 visited: &mut BitSet,
825 recursion_stack: &mut BitSet,
826 ) -> Result<bool> {
827 if recursion_stack.contains(group) {
828 // We found a cycle. Since we only follow calls at position 0 (see below),
829 // reaching a group already in the recursion stack means we have a left-recursive cycle.
830 return Ok(true);
831 }
832
833 if visited.contains(group) {
834 return Ok(false);
835 }
836
837 visited.insert(group);
838 recursion_stack.insert(group);
839
840 // Check all subroutine calls from this group
841 if let Some(calls) = self.subroutine_calls.get(&group) {
842 for call_info in calls {
843 // Only consider calls at position 0 (potential left recursion)
844 if call_info.min_pos == 0
845 && self.dfs_check_left_recursion(
846 call_info.target_group,
847 visited,
848 recursion_stack,
849 )?
850 {
851 return Ok(true);
852 }
853 }
854 }
855
856 recursion_stack.remove(group);
857 Ok(false)
858 }
859 }
860
861 fn literal_const_size(_: &str, _: bool) -> bool {
862 // Right now, regex doesn't do sophisticated case folding,
863 // test below will fail when that changes, then we need to
864 // do something fancier here.
865 true
866 }
867
868 /// Recursively collect all Group expressions and their capture group indices
869 fn collect_groups<'a>(
870 expr: &'a Expr,
871 next_group_number: &mut usize,
872 groups: &mut Map<usize, &'a Expr>,
873 ) {
874 match expr {
875 Expr::Group(inner) => {
876 let current_group = *next_group_number;
877 *next_group_number += 1;
878 groups.insert(current_group, inner.as_ref());
879 // Continue recursing to find nested groups
880 collect_groups(inner.as_ref(), next_group_number, groups);
881 }
882 _ => {
883 // Recurse into all children
884 for child in expr.children_iter() {
885 collect_groups(child, next_group_number, groups);
886 }
887 }
888 }
889 }
890
891 /// Context options for [`analyze`].
892 #[derive(Debug, Clone, Default)]
893 pub struct AnalyzeContext {
894 /// When `true`, capture group numbering starts at 0 rather than 1 (i.e. there is an explicit
895 /// outer capture group 0 in the pattern rather than an implicit one added by the compiler).
896 pub explicit_capture_group_0: bool,
897 /// When `true`, sub-expressions that could produce an empty match (`min_size == 0` and not
898 /// `const_size`) are promoted to `hard` so that the VM can backtrack past them to find a
899 /// non-empty match.
900 pub find_not_empty: bool,
901 /// To match Oniguruma behavior where only \z can match at EOF if preceeded by a newline character
902 pub disallow_empty_match_at_eof_after_newline: bool,
903 /// When true, treat assertions that support runtime input suppression overrides (`\A`, `\z`)
904 /// as hard so that they execute on the VM.
905 pub allow_input_assertion_overrides: bool,
906 /// When true, leftmost-longest match semantics are enabled.
907 #[cfg(feature = "leftmost_longest")]
908 pub leftmost_longest: bool,
909 }
910
911 /// Analyze the parsed expression to determine whether it requires fancy features.
912 pub fn analyze<'a>(tree: &'a ExprTree, ctx: AnalyzeContext) -> Result<Info<'a>> {
913 let explicit_capture_group_0 = ctx.explicit_capture_group_0;
914 let find_not_empty = ctx.find_not_empty;
915 let disallow_empty_match_at_eof_after_newline = ctx.disallow_empty_match_at_eof_after_newline;
916 let allow_input_assertion_overrides = ctx.allow_input_assertion_overrides;
917 #[cfg(feature = "leftmost_longest")]
918 let leftmost_longest = ctx.leftmost_longest;
919
920 // Check that numeric capture group references (backrefs and subroutine calls) and named groups are not mixed
921 if tree.numbered_groups_ignored
922 && tree.numeric_capture_group_references
923 && !tree.named_groups.is_empty()
924 {
925 return Err(Error::CompileError(Box::new(
926 CompileError::NamedBackrefOnly,
927 )));
928 }
929
930 let start_group = if explicit_capture_group_0 { 0 } else { 1 };
931
932 // pre-populate groups if subroutines are present to handle forward references
933 let group_exprs = if tree.contains_subroutines {
934 let mut groups = Map::new();
935 let mut next_group_number = start_group;
936 collect_groups(&tree.expr, &mut next_group_number, &mut groups);
937 groups
938 } else {
939 Map::new()
940 };
941
942 let mut analyzer = Analyzer {
943 backrefs: &tree.backrefs,
944 next_group_number: start_group,
945 group_info: Map::new(),
946 subroutine_calls: Map::new(),
947 root_groups: BitSet::new(),
948 group_exprs,
949 analyzing_groups: BitSet::new(),
950 find_not_empty,
951 disallow_empty_match_at_eof_after_newline,
952 allow_input_assertion_overrides,
953 #[cfg(feature = "leftmost_longest")]
954 leftmost_longest,
955 in_lookaround: false,
956 };
957
958 let mut analyzed = analyzer.visit(&tree.expr, 0, false, 0)?;
959 // With start_group == 1 (no explicit group 0) the valid backref range is 1..=total_groups.
960 // With start_group == 0 (explicit group 0) group 0 is the whole match and inner groups are
961 // numbered 1..=total_groups-1, so the valid range is 0..=total_groups-1.
962 let max_valid_group = if explicit_capture_group_0 {
963 tree.total_groups.saturating_sub(1)
964 } else {
965 tree.total_groups
966 };
967 // Out-of-range group numbers are not in the BitSet (to avoid huge allocations), so check the
968 // dedicated field first.
969 if let Some(group) = tree.out_of_range_backref {
970 return Err(Error::CompileError(Box::new(CompileError::InvalidBackref(
971 group,
972 ))));
973 }
974 for group in tree.backrefs.iter() {
975 if group < start_group || group > max_valid_group {
976 return Err(Error::CompileError(Box::new(CompileError::InvalidBackref(
977 group,
978 ))));
979 }
980 }
981
982 // Check for left-recursive and unterminating subroutine calls (only if subroutines are present)
983 if tree.contains_subroutines {
984 analyzer.check_left_recursion(&tree.named_groups)?;
985 analyzer.check_unbounded_recursion(&tree.expr)?;
986 }
987
988 if analyzed.min_size == 0 && disallow_empty_match_at_eof_after_newline {
989 analyzed.hard = true;
990 }
991
992 Ok(analyzed)
993 }
994
995 /// Determine if the expression will always only ever match at position 0.
996 /// Note that false negatives are possible - it can return false even if it could be anchored.
997 /// This should therefore only be treated as an optimization.
998 pub fn can_compile_as_anchored(root_expr: &Expr) -> bool {
999 match root_expr {
1000 Expr::Concat(children) => match children[0] {
1001 Expr::Assertion(assertion) => assertion == Assertion::StartText,
1002 Expr::ContinueFromPreviousMatchEnd => true,
1003 _ => false,
1004 },
1005 Expr::Assertion(assertion) => *assertion == Assertion::StartText,
1006 _ => false,
1007 }
1008 }
1009
1010 #[cfg(test)]
1011 mod tests {
1012 use super::{analyze, AnalyzeContext};
1013 // use super::literal_const_size;
1014 use crate::parse::ExprTree;
1015 use crate::{can_compile_as_anchored, CompileError, Error, Expr};
1016 use matches::assert_matches;
1017
1018 #[cfg_attr(feature = "track_caller", track_caller)]
1019 fn assert_analyze_ok(tree: &ExprTree, ctx: AnalyzeContext) {
1020 match analyze(tree, ctx) {
1021 Ok(_) => {}
1022 Err(e) => panic!("expected analyze to succeed, but got error: {:?}", e),
1023 }
1024 }
1025
1026 #[cfg_attr(feature = "track_caller", track_caller)]
1027 fn assert_compile_error<T, F>(result: crate::Result<T>, check: F)
1028 where
1029 F: FnOnce(&CompileError) -> bool,
1030 {
1031 match result {
1032 Err(Error::CompileError(ref e)) if check(e) => {}
1033 other => panic!(
1034 "expected a matching CompileError, but got: {:?}",
1035 other.err()
1036 ),
1037 }
1038 }
1039
1040 #[cfg_attr(feature = "track_caller", track_caller)]
1041 fn assert_invalid_backref(
1042 pattern: &str,
1043 explicit_capture_group_0: bool,
1044 expected_group: usize,
1045 ) {
1046 let tree = Expr::parse_tree(pattern).unwrap();
1047 assert_compile_error(
1048 analyze(
1049 &tree,
1050 AnalyzeContext {
1051 explicit_capture_group_0,
1052 ..Default::default()
1053 },
1054 ),
1055 |e| matches!(e, CompileError::InvalidBackref(g) if *g == expected_group),
1056 );
1057 }
1058
1059 // #[test]
1060 // fn case_folding_safe() {
1061 // let re = regex::Regex::new("(?i:ß)").unwrap();
1062 // if re.is_match("SS") {
1063 // assert!(!literal_const_size("ß", true));
1064 // }
1065
1066 // // Another tricky example, Armenian ECH YIWN
1067 // let re = regex::Regex::new("(?i:\\x{0587})").unwrap();
1068 // if re.is_match("\u{0565}\u{0582}") {
1069 // assert!(!literal_const_size("\u{0587}", true));
1070 // }
1071 // }
1072
1073 #[test]
1074 fn invalid_backref_zero() {
1075 assert_invalid_backref(r".\0", false, 0);
1076 assert_invalid_backref(r".\0", true, 0);
1077 assert_invalid_backref(r"(.)\0", false, 0);
1078 assert_invalid_backref(r"(.)\0", true, 0);
1079 assert_invalid_backref(r"(.)\0\1", false, 0);
1080 }
1081
1082 #[test]
1083 fn invalid_backref_no_captures() {
1084 assert_invalid_backref(r"aa\1", false, 1);
1085 assert_invalid_backref(r"aaaa\2", false, 2);
1086 }
1087
1088 #[test]
1089 fn invalid_backref_unreasonably_large_number() {
1090 // A group number that is a valid usize but far exceeds the number of groups in the
1091 // pattern. The resolver inserts it into the BitSet as-is; the analyzer catches it via
1092 // the total_groups bound check.
1093 assert_invalid_backref(r".\1999999999", false, 1999999999);
1094 }
1095
1096 #[test]
1097 fn invalid_backref_with_captures() {
1098 assert_invalid_backref(r"a(a)\2", false, 2);
1099 assert_invalid_backref(r"a(a)\2\1", false, 2);
1100 }
1101
1102 #[test]
1103 fn invalid_backref_with_captures_explict_capture_group_zero() {
1104 assert_invalid_backref(r"(a(b)\2)c", true, 2);
1105 assert_invalid_backref(r"(a(b)\1\2)c", true, 2);
1106 assert_invalid_backref(r"(a\1)b", true, 1);
1107 assert_invalid_backref(r"(a(b))\2", true, 2);
1108 }
1109
1110 #[test]
1111 fn unresolved_subroutine_call_error_takes_precedence_over_invalid_backref() {
1112 // Regression test for issue where encountering an unresolved subroutine call would
1113 // cause the analyzer to stop visiting groups, leading to an incomplete group count.
1114 // This would then cause a misleading "Invalid back reference" error instead of
1115 // the correct error.
1116 let tree = Expr::parse_tree(r"(?<a>a)(?<b>b)\g<no_exist>(?<c>c)\k<a>\k<c>").unwrap();
1117 let result = analyze(&tree, AnalyzeContext::default());
1118
1119 // Should get the unresolved subroutine call error, not an invalid backref error
1120 assert_compile_error(
1121 result,
1122 |e| matches!(e, CompileError::SubroutineCallTargetNotFound(s, _) if s.contains("no_exist")),
1123 );
1124 }
1125
1126 #[test]
1127 fn allow_analysis_of_self_backref() {
1128 // even if it will never match, see issue 103
1129 assert!(!analyze(
1130 &Expr::parse_tree(r"(.\1)").unwrap(),
1131 AnalyzeContext::default()
1132 )
1133 .is_err());
1134 assert!(!analyze(
1135 &Expr::parse_tree(r"((.\1))").unwrap(),
1136 AnalyzeContext {
1137 explicit_capture_group_0: true,
1138 ..Default::default()
1139 }
1140 )
1141 .is_err());
1142 assert!(!analyze(
1143 &Expr::parse_tree(r"(([ab]+)\1b)").unwrap(),
1144 AnalyzeContext::default()
1145 )
1146 .is_err());
1147 // in the following scenario it can match
1148 assert!(!analyze(
1149 &Expr::parse_tree(r"(([ab]+?)(?(1)\1| )c)+").unwrap(),
1150 AnalyzeContext::default(),
1151 )
1152 .is_err());
1153 }
1154
1155 #[test]
1156 fn allow_backref_even_when_capture_group_occurs_after_backref() {
1157 assert!(!analyze(
1158 &Expr::parse_tree(r"\1(.)").unwrap(),
1159 AnalyzeContext::default()
1160 )
1161 .is_err());
1162 assert!(!analyze(
1163 &Expr::parse_tree(r"(\1(.))").unwrap(),
1164 AnalyzeContext {
1165 explicit_capture_group_0: true,
1166 ..Default::default()
1167 }
1168 )
1169 .is_err());
1170 }
1171
1172 #[test]
1173 fn valid_backref_occurs_after_capture_group() {
1174 assert!(!analyze(
1175 &Expr::parse_tree(r"(.)\1").unwrap(),
1176 AnalyzeContext::default()
1177 )
1178 .is_err());
1179 assert!(!analyze(
1180 &Expr::parse_tree(r"((.)\1)").unwrap(),
1181 AnalyzeContext {
1182 explicit_capture_group_0: true,
1183 ..Default::default()
1184 }
1185 )
1186 .is_err());
1187
1188 assert!(!analyze(
1189 &Expr::parse_tree(r"((.)\2\2)\1").unwrap(),
1190 AnalyzeContext::default()
1191 )
1192 .is_err());
1193 assert!(!analyze(
1194 &Expr::parse_tree(r"(.)\1(.)\2").unwrap(),
1195 AnalyzeContext::default()
1196 )
1197 .is_err());
1198 assert!(!analyze(
1199 &Expr::parse_tree(r"(.)foo(.)\2").unwrap(),
1200 AnalyzeContext::default()
1201 )
1202 .is_err());
1203 assert!(!analyze(
1204 &Expr::parse_tree(r"(.)(foo)(.)\3\2\1").unwrap(),
1205 AnalyzeContext::default(),
1206 )
1207 .is_err());
1208 assert!(!analyze(
1209 &Expr::parse_tree(r"(.)(foo)(.)\3\1").unwrap(),
1210 AnalyzeContext::default()
1211 )
1212 .is_err());
1213 assert!(!analyze(
1214 &Expr::parse_tree(r"(.)(foo)(.)\2\1").unwrap(),
1215 AnalyzeContext::default()
1216 )
1217 .is_err());
1218 }
1219
1220 #[test]
1221 fn feature_not_yet_supported() {
1222 let tree = &Expr::parse_tree(r"(a)\k<1-0>").unwrap();
1223 assert_compile_error(analyze(tree, AnalyzeContext::default()), |e| {
1224 matches!(e, CompileError::FeatureNotYetSupported(_))
1225 });
1226 }
1227
1228 #[test]
1229 fn subroutine_call_undefined() {
1230 let tree = &Expr::parse_tree(r"\g<wrong_name>(?<different_name>a)").unwrap();
1231 assert_compile_error(analyze(tree, AnalyzeContext::default()), |e| {
1232 matches!(e, CompileError::SubroutineCallTargetNotFound(_, _))
1233 });
1234 }
1235
1236 #[test]
1237 fn subroutine_call_undefined_by_name_message() {
1238 let tree = &Expr::parse_tree(r"\g<wrong_name>(?<different_name>a)").unwrap();
1239 assert_compile_error(
1240 analyze(tree, AnalyzeContext::default()),
1241 |e| matches!(e, CompileError::SubroutineCallTargetNotFound(s, _) if s.contains("wrong_name")),
1242 );
1243 }
1244
1245 #[test]
1246 fn subroutine_call_undefined_by_number() {
1247 use crate::parse::NamedGroups;
1248 use bit_set::BitSet;
1249 // ByNumber is always resolved by the parser so we must construct the ExprTree directly
1250 let tree = ExprTree {
1251 expr: Expr::AstNode(
1252 crate::AstNode::SubroutineCall(crate::CaptureGroupTarget::ByNumber(99)),
1253 0,
1254 ),
1255 backrefs: BitSet::new(),
1256 named_groups: NamedGroups::default(),
1257 numeric_capture_group_references: false,
1258 contains_subroutines: true,
1259 self_recursive: false,
1260 total_groups: 0,
1261 out_of_range_backref: None,
1262 numbered_groups_ignored: false,
1263 };
1264 assert_compile_error(
1265 analyze(&tree, AnalyzeContext::default()),
1266 |e| matches!(e, CompileError::SubroutineCallTargetNotFound(s, _) if s.contains("99")),
1267 );
1268 }
1269
1270 #[test]
1271 fn subroutine_call_undefined_by_relative() {
1272 use crate::parse::NamedGroups;
1273 use bit_set::BitSet;
1274 // Relative can only fail to resolve on integer overflow (essentially never),
1275 // so we must construct the ExprTree directly
1276 let tree = ExprTree {
1277 expr: Expr::AstNode(
1278 crate::AstNode::SubroutineCall(crate::CaptureGroupTarget::Relative(-1)),
1279 0,
1280 ),
1281 backrefs: BitSet::new(),
1282 named_groups: NamedGroups::default(),
1283 numeric_capture_group_references: false,
1284 contains_subroutines: true,
1285 self_recursive: false,
1286 total_groups: 0,
1287 out_of_range_backref: None,
1288 numbered_groups_ignored: false,
1289 };
1290 assert_compile_error(
1291 analyze(&tree, AnalyzeContext::default()),
1292 |e| matches!(e, CompileError::SubroutineCallTargetNotFound(s, _) if s.contains("-1")),
1293 );
1294 }
1295
1296 #[test]
1297 fn unresolved_ast_node_error() {
1298 use crate::parse::NamedGroups;
1299 use bit_set::BitSet;
1300 // Construct a tree with an unresolved Backref AstNode (not a SubroutineCall),
1301 // which should produce an UnresolvedAstNode error containing the node's debug representation
1302 let tree = ExprTree {
1303 expr: Expr::AstNode(
1304 crate::AstNode::Backref {
1305 target: crate::CaptureGroupTarget::ByNumber(1),
1306 casei: false,
1307 relative_recursion_level: None,
1308 },
1309 0,
1310 ),
1311 backrefs: BitSet::new(),
1312 named_groups: NamedGroups::default(),
1313 numeric_capture_group_references: false,
1314 contains_subroutines: false,
1315 self_recursive: false,
1316 total_groups: 0,
1317 out_of_range_backref: None,
1318 numbered_groups_ignored: false,
1319 };
1320 assert_compile_error(
1321 analyze(&tree, AnalyzeContext::default()),
1322 |e| matches!(e, CompileError::UnresolvedAstNode(_, s) if s.contains("Backref")),
1323 );
1324 }
1325
1326 #[test]
1327 fn numeric_capture_group_references_cannot_be_used_with_named_groups() {
1328 use crate::parse_flags::FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST;
1329
1330 // Test case 1: Named group followed by numeric backref (no alternation)
1331 let tree = Expr::parse_tree_with_flags(
1332 r"(?<name>a)\1",
1333 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1334 )
1335 .unwrap();
1336 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1337 matches!(e, CompileError::NamedBackrefOnly)
1338 });
1339
1340 // Test case 2: Numeric backref followed by named group
1341 let tree = Expr::parse_tree_with_flags(
1342 r"(a)\1(?<name>b)",
1343 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1344 )
1345 .unwrap();
1346 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1347 matches!(e, CompileError::NamedBackrefOnly)
1348 });
1349
1350 // Test case 3: Alternation with numeric backref and named group in first branch
1351 let tree = Expr::parse_tree_with_flags(
1352 r"(?<name>a)\1|b",
1353 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1354 )
1355 .unwrap();
1356 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1357 matches!(e, CompileError::NamedBackrefOnly)
1358 });
1359
1360 // Test case 4: Alternation with named group in first branch, numeric backref in second
1361 let tree = Expr::parse_tree_with_flags(
1362 r"(?<name>a)|\1",
1363 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1364 )
1365 .unwrap();
1366 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1367 matches!(e, CompileError::NamedBackrefOnly)
1368 });
1369
1370 // Test case 5: Numbered group containing named group, with numeric backref
1371 let tree = Expr::parse_tree_with_flags(
1372 r"(a|(?<name>b))\1",
1373 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1374 )
1375 .unwrap();
1376 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1377 matches!(e, CompileError::NamedBackrefOnly)
1378 });
1379
1380 // Test case 6: Multiple branches with named groups and numeric backrefs
1381 let tree = Expr::parse_tree_with_flags(
1382 r"(?<x>a)|(?<y>b)|\1",
1383 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1384 )
1385 .unwrap();
1386 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1387 matches!(e, CompileError::NamedBackrefOnly)
1388 });
1389
1390 // Test case 7: Numeric subroutine call with named group
1391 let tree = Expr::parse_tree_with_flags(
1392 r"(?<foo>\w+)\g<1>",
1393 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1394 )
1395 .unwrap();
1396 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1397 matches!(e, CompileError::NamedBackrefOnly)
1398 });
1399
1400 // Test case 8: Named group with numeric subroutine call in alternation
1401 let tree = Expr::parse_tree_with_flags(
1402 r"(?<foo>a)|\g<1>",
1403 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1404 )
1405 .unwrap();
1406 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1407 matches!(e, CompileError::NamedBackrefOnly)
1408 });
1409
1410 // Positive cases - these should work
1411
1412 // Only numeric backrefs and subroutine calls, no named groups
1413 let tree = Expr::parse_tree_with_flags(
1414 r"(a)(b+)\1\g<2>",
1415 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1416 )
1417 .unwrap();
1418 assert_analyze_ok(&tree, AnalyzeContext::default());
1419
1420 // Only named groups and named backrefs and named subroutine calls
1421 let tree = Expr::parse_tree_with_flags(
1422 r"(?<name>a)\k<name>\g<name>",
1423 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1424 )
1425 .unwrap();
1426 assert_analyze_ok(&tree, AnalyzeContext::default());
1427
1428 // Multiple named and numbered groups, no backrefs or subroutine calls
1429 let tree = Expr::parse_tree_with_flags(
1430 r"(?<a>a)|(?<b>b)(c)(d+)",
1431 FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
1432 )
1433 .unwrap();
1434 assert_analyze_ok(&tree, AnalyzeContext::default());
1435 }
1436
1437 #[test]
1438 fn is_literal() {
1439 let tree = Expr::parse_tree("abc").unwrap();
1440 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1441 assert_eq!(info.is_literal_get_casei(), Some(false));
1442 }
1443
1444 #[test]
1445 fn is_literal_casei() {
1446 let tree = Expr::parse_tree("(?i)abc").unwrap();
1447 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1448 assert_eq!(info.is_literal_get_casei(), Some(true));
1449 }
1450
1451 #[test]
1452 fn is_literal_with_repeat() {
1453 let tree = Expr::parse_tree("abc*").unwrap();
1454 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1455 assert_eq!(info.is_literal_get_casei(), None);
1456 }
1457
1458 #[test]
1459 fn anchored_for_starttext_assertions() {
1460 let tree = Expr::parse_tree(r"^(\w+)\1").unwrap();
1461 assert_eq!(can_compile_as_anchored(&tree.expr), true);
1462
1463 let tree = Expr::parse_tree(r"^").unwrap();
1464 assert_eq!(can_compile_as_anchored(&tree.expr), true);
1465 }
1466
1467 #[test]
1468 fn anchored_for_continue_from_prev_match_assertions() {
1469 let tree = Expr::parse_tree(r"\G(\w+)\1").unwrap();
1470 assert_eq!(can_compile_as_anchored(&tree.expr), true);
1471 }
1472
1473 #[test]
1474 fn backref_inherits_group_size_info() {
1475 // Test that backrefs properly inherit min_size and const_size from referenced groups
1476 let tree = Expr::parse_tree(r"(abc)\1").unwrap();
1477 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1478 // The concatenation should have min_size = 3 + 3 = 6 (group + backref)
1479 assert_eq!(info.min_size, 6);
1480 assert!(info.const_size);
1481
1482 // Test with a variable-length group
1483 let tree = Expr::parse_tree(r"(a+)\1").unwrap();
1484 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1485 // The group has min_size = 1, but const_size = false due to the +
1486 // So the total should be min_size = 2, const_size = false
1487 assert_eq!(info.min_size, 2);
1488 assert!(!info.const_size);
1489
1490 // Test with optional group
1491 let tree = Expr::parse_tree(r"(a?)\1").unwrap();
1492 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1493 // Both group and backref can be empty, so min_size = 0
1494 assert_eq!(info.min_size, 0);
1495 assert!(!info.const_size);
1496 }
1497
1498 #[test]
1499 fn backref_forward_reference() {
1500 // Test forward references (backref before group definition)
1501 // These should use conservative defaults but still work
1502 let tree = Expr::parse_tree(r"\1(abc)").unwrap();
1503 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1504 // Forward ref gets min_size=0, group gets min_size=3, total=3
1505 assert_eq!(info.min_size, 3);
1506 // Forward ref sets const_size=false, so overall is false
1507 assert!(!info.const_size);
1508 }
1509
1510 #[test]
1511 fn backref_in_lookbehind() {
1512 assert!(!analyze(
1513 &Expr::parse_tree(r"(hello)(?<=\b\1)").unwrap(),
1514 AnalyzeContext::default(),
1515 )
1516 .is_err());
1517 assert!(!analyze(
1518 &Expr::parse_tree(r"(..)(?<=\1\1)").unwrap(),
1519 AnalyzeContext::default()
1520 )
1521 .is_err());
1522 assert!(!analyze(
1523 &Expr::parse_tree(r"(abc)(?<=\1)def").unwrap(),
1524 AnalyzeContext::default()
1525 )
1526 .is_err());
1527 }
1528
1529 #[test]
1530 fn backref_inside_recursed_group_not_supported() {
1531 let tree = Expr::parse_tree(r"(?<foo>a|\(\g<foo>\)\k<foo>?)").unwrap();
1532 assert_compile_error(
1533 analyze(&tree, AnalyzeContext::default()),
1534 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("Backreference") && s.contains("recursed")),
1535 );
1536
1537 // Test with numbered groups
1538 let tree = Expr::parse_tree(r"(\g<1>\1)").unwrap();
1539 assert_compile_error(
1540 analyze(&tree, AnalyzeContext::default()),
1541 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("Backreference") && s.contains("recursed")),
1542 );
1543
1544 // Another example with alternation inside recursed group
1545 let tree = Expr::parse_tree(r"(a|\g<1>b\1)").unwrap();
1546 assert_compile_error(
1547 analyze(&tree, AnalyzeContext::default()),
1548 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("Backreference") && s.contains("recursed")),
1549 );
1550 }
1551
1552 #[test]
1553 fn backref_outside_recursed_group_is_allowed() {
1554 let tree = Expr::parse_tree(r"(?<foo>a|\(\g<foo>\))\k<foo>").unwrap();
1555 let result = analyze(&tree, AnalyzeContext::default());
1556 assert!(
1557 result.is_ok(),
1558 "Backref outside recursed group should pass analysis"
1559 );
1560 }
1561
1562 #[test]
1563 fn not_anchored_for_startline_assertions() {
1564 let tree = Expr::parse_tree(r"(?m)^(\w+)\1").unwrap();
1565 assert_eq!(can_compile_as_anchored(&tree.expr), false);
1566 }
1567
1568 #[test]
1569 fn start_line_analysis() {
1570 use crate::parse_flags::FLAG_ONIGURUMA_MODE;
1571 use crate::Assertion;
1572
1573 let tree = Expr::parse_tree(r"(?m)^").unwrap();
1574 let info = analyze(&tree, AnalyzeContext::default()).expect("can analyze start line");
1575 assert_eq!(info.min_size, 0);
1576 assert!(info.const_size);
1577 assert!(!info.hard);
1578 assert_matches!(info.expr, Expr::Assertion(Assertion::StartLine { .. }));
1579
1580 let tree = Expr::parse_tree_with_flags(r"(?m)^", FLAG_ONIGURUMA_MODE).unwrap();
1581 let info =
1582 analyze(&tree, AnalyzeContext::default()).expect("can analyze Oniguruma start line");
1583 assert_eq!(info.min_size, 0);
1584 assert!(info.hard);
1585 assert_matches!(
1586 info.expr,
1587 Expr::Assertion(Assertion::StartLineOniguruma { .. })
1588 );
1589
1590 let tree = Expr::parse_tree_with_flags(r"(?m)(?=^)", FLAG_ONIGURUMA_MODE).unwrap();
1591 let info = analyze(&tree, AnalyzeContext::default())
1592 .expect("can analyze Oniguruma start line inside lookaround");
1593 assert_eq!(info.min_size, 0);
1594 assert!(info.hard);
1595 assert_matches!(
1596 info.children[0].expr,
1597 Expr::Assertion(Assertion::StartLineOniguruma { .. })
1598 );
1599 assert!(!info.children[0].hard);
1600 }
1601
1602 #[test]
1603 fn min_pos_in_group_calculated_correctly_with_no_groups() {
1604 let tree = Expr::parse_tree(r"\G").unwrap();
1605 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1606 assert_eq!(info.min_size, 0);
1607 assert_eq!(info.min_pos_in_group, 0);
1608 assert!(info.const_size);
1609
1610 let tree = Expr::parse_tree(r"\G(?=abc)\w+").unwrap();
1611 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1612 // the lookahead itself has min size 0
1613 assert_eq!(info.children[1].min_size, 0);
1614 assert!(info.children[1].const_size);
1615 // the children of the lookahead have min_size 3 from the literal
1616 assert_eq!(info.children[1].children[0].min_size, 3);
1617 assert!(info.children[1].children[0].const_size);
1618 // after lookahead, the position is reset
1619 assert_eq!(info.children[2].min_pos_in_group, 0);
1620 assert_eq!(info.children[2].min_size, 1);
1621 assert_eq!(info.min_pos_in_group, 0);
1622 assert!(!info.const_size);
1623
1624 let tree = Expr::parse_tree(r"(?:ab*|cd){2}(?=bar)\w").unwrap();
1625 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1626 // the whole expression has min size 3 (a times 2 plus \w)
1627 assert_eq!(info.min_size, 3);
1628 // the min pos of the lookahead is 2
1629 assert_eq!(info.children[1].min_pos_in_group, 2);
1630 // after lookahead, the position is reset
1631 assert_eq!(info.children[2].min_pos_in_group, 2);
1632 assert_eq!(info.children[2].min_size, 1);
1633 assert!(!info.const_size);
1634 }
1635
1636 #[test]
1637 fn backtracking_control_verb_is_hard_and_const_size() {
1638 let tree = Expr::parse_tree(r"(*FAIL)").unwrap();
1639 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1640 assert_eq!(info.min_size, 0);
1641 assert_eq!(info.min_pos_in_group, 0);
1642 assert!(info.const_size);
1643 }
1644
1645 #[test]
1646 fn min_pos_in_group_calculated_correctly_with_capture_groups() {
1647 let tree = Expr::parse_tree(r"a(bc)d(e(f)g)").unwrap();
1648 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1649 assert_eq!(info.min_pos_in_group, 0);
1650 // before the capture begins, the min pos in group 0 is 1
1651 assert_eq!(info.children[1].min_pos_in_group, 1);
1652 // inside capture group 1, the min pos of the Concat inside the group is 0
1653 assert_matches!(info.children[1].children[0].expr, Expr::Concat(_));
1654 assert_eq!(info.children[1].children[0].min_pos_in_group, 0);
1655 assert!(info.children[1].children[0].const_size);
1656 // inside capture group 1, the min pos of the c inside the group is 1
1657 assert_matches!(info.children[1].children[0].children[1].expr, Expr::Literal { val, casei: false } if val == "c");
1658 assert_eq!(info.children[1].children[0].children[1].min_pos_in_group, 1);
1659
1660 // prove we are looking at the position of the d after capture group 1
1661 assert_matches!(info.children[2].expr, Expr::Literal { val, casei: false } if val == "d");
1662 assert_eq!(info.children[2].min_pos_in_group, 3);
1663 assert_eq!(info.children[2].start_group(), 2);
1664 assert_eq!(info.children[2].min_size, 1);
1665
1666 // prove we are looking at the position of the e in capture group 2
1667 assert_matches!(info.children[3].children[0].children[0].expr, Expr::Literal { val, casei: false } if val == "e");
1668 assert_eq!(info.children[3].children[0].children[0].min_pos_in_group, 0);
1669 }
1670
1671 #[test]
1672 fn absent_repeater_is_hard_and_not_const_size() {
1673 let tree = Expr::parse_tree(r"(?~abc)").unwrap();
1674 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1675 assert_eq!(info.min_size, 0);
1676 assert!(!info.const_size);
1677 assert!(info.hard);
1678 }
1679
1680 #[test]
1681 fn absent_expression_is_hard_and_not_const_size() {
1682 let tree = Expr::parse_tree(r"(?~|abc|\d+)").unwrap();
1683 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1684 // min_size comes from exp part (\d+ has min_size 1)
1685 assert_eq!(info.min_size, 1);
1686 assert!(!info.const_size);
1687 assert!(info.hard);
1688 }
1689
1690 #[test]
1691 fn range_clear_is_hard_and_const_size() {
1692 let tree = Expr::parse_tree(r"(?~|)").unwrap();
1693 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1694 assert_eq!(info.min_size, 0);
1695 assert!(info.const_size);
1696 assert!(info.hard);
1697 }
1698
1699 #[test]
1700 fn left_recursive_subroutine_direct() {
1701 // Direct left recursion: group 1 calls itself at position 0
1702 let tree = Expr::parse_tree(r"(\g<1>a)").unwrap();
1703 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1704 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1705 });
1706
1707 let tree = Expr::parse_tree(r"abc(\g<1>a)").unwrap();
1708 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1709 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1710 });
1711 }
1712
1713 #[test]
1714 fn not_left_recursive_subroutine_after_group() {
1715 let tree = Expr::parse_tree(r"(a)\g<1>").unwrap();
1716 let result = analyze(&tree, AnalyzeContext::default());
1717 assert!(result.is_ok());
1718
1719 let tree = Expr::parse_tree(r"(?<test>a)\g<test>").unwrap();
1720 let result = analyze(&tree, AnalyzeContext::default());
1721 assert!(result.is_ok());
1722 }
1723
1724 #[test]
1725 fn left_recursive_subroutine_at_start() {
1726 // Left recursion at start of group: (\g<1>a)
1727 let tree = Expr::parse_tree(r"(\g<1>a)").unwrap();
1728 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1729 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1730 });
1731
1732 let tree = Expr::parse_tree(r"(?<test>\g<test>a)").unwrap();
1733 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1734 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1735 });
1736 }
1737
1738 #[test]
1739 fn left_recursive_subroutine_indirect() {
1740 // Indirect left recursion: non-nested subroutine calls to each other
1741 let tree = Expr::parse_tree(r"(\g<2>)(\g<1>)").unwrap();
1742 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1743 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1744 });
1745
1746 let tree = Expr::parse_tree(r"(\g<2>)(\g<1>a)").unwrap();
1747 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1748 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1749 });
1750 }
1751
1752 #[test]
1753 fn left_recursive_subroutine_with_alternation() {
1754 // Left recursion through alternation, depending which branch is taken it could be left-recursive
1755 let tree = Expr::parse_tree(r"(a|\g<1>)").unwrap();
1756 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1757 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1758 });
1759 }
1760
1761 #[test]
1762 fn unbounded_recursive_after_char() {
1763 // Not left recursive because subroutine call is after a character was consumed,
1764 // but still never-ending because the recursive call is mandatory.
1765 let tree = Expr::parse_tree(r"(a\g<1>)").unwrap();
1766 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1767 matches!(e, CompileError::NeverEndingRecursion)
1768 });
1769 }
1770
1771 #[test]
1772 fn bounded_recursive_after_char_is_allowed() {
1773 let tree = Expr::parse_tree(r"(a\g<1>?)").unwrap();
1774 let result = analyze(&tree, AnalyzeContext::default());
1775 assert!(result.is_ok());
1776 }
1777
1778 #[test]
1779 fn not_left_recursive_zero_repetition() {
1780 // Not left recursive because subroutine call is unreachable
1781 let tree = Expr::parse_tree(r"(a?\g<1>){0}").unwrap();
1782 let result = analyze(&tree, AnalyzeContext::default());
1783 assert!(result.is_ok());
1784 }
1785
1786 #[test]
1787 fn left_recursive_with_both_positions() {
1788 // Left recursive because \g<1> appears at position 0 in the group even though also at end at position 1
1789 let tree = Expr::parse_tree(r"(\g<1>a\g<1>)").unwrap();
1790 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1791 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1792 });
1793 }
1794
1795 #[test]
1796 fn left_recursive_with_lookahead() {
1797 let tree = Expr::parse_tree(r"((?=a)\g<1>)").unwrap();
1798 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1799 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1800 });
1801 }
1802
1803 #[test]
1804 fn self_recursive_group_zero() {
1805 // Self-recursive on group 0 after a character
1806 let tree = Expr::parse_tree(r"a\g<0>").unwrap();
1807 // Group 0 calls itself at position 1 (after 'a'), so this is NOT left recursive
1808 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1809 matches!(e, CompileError::NeverEndingRecursion)
1810 });
1811 }
1812
1813 #[test]
1814 fn not_left_recursive_forward_call() {
1815 // Forward subroutine call - not left recursive: \g<1>(a)
1816 let tree = Expr::parse_tree(r"\g<1>(a)").unwrap();
1817 let result = analyze(&tree, AnalyzeContext::default());
1818 // The call happens before the group is defined, but it's at position 0 of group 0 (implicit)
1819 // which calls group 1. Group 1 doesn't call anything, so no cycle.
1820 assert!(result.is_ok());
1821 }
1822
1823 #[test]
1824 fn not_left_recursive_group_zero_explicit() {
1825 // Self-recursive on explicit group 0: (a\g<0>)
1826 let tree = Expr::parse_tree(r"(a\g<0>)").unwrap();
1827 assert_compile_error(
1828 analyze(
1829 &tree,
1830 AnalyzeContext {
1831 explicit_capture_group_0: true,
1832 ..Default::default()
1833 },
1834 ),
1835 |e| matches!(e, CompileError::NeverEndingRecursion),
1836 );
1837 }
1838
1839 #[test]
1840 fn not_left_recursive_group_zero_subroutine_call_unreachable() {
1841 let tree = Expr::parse_tree(r"\g<0>{0}abc").unwrap();
1842 let result = analyze(
1843 &tree,
1844 AnalyzeContext {
1845 explicit_capture_group_0: true,
1846 ..Default::default()
1847 },
1848 );
1849 assert!(result.is_ok());
1850 }
1851
1852 #[test]
1853 fn left_recursive_group_zero_at_start() {
1854 // Self-recursive on explicit group 0 at start: (\g<0>a)
1855 let tree = Expr::parse_tree(r"(\g<0>a)").unwrap();
1856 let result = analyze(
1857 &tree,
1858 AnalyzeContext {
1859 explicit_capture_group_0: true,
1860 ..Default::default()
1861 },
1862 );
1863 // With explicit group 0, \g<0> at position 0 is left-recursive
1864 assert!(result.is_err());
1865 }
1866
1867 #[test]
1868 fn three_way_indirect_recursion() {
1869 // Three-way indirect recursion where each recursive call is mandatory.
1870 let tree = Expr::parse_tree(r"(\g<2>)(\g<3>)(a\g<1>)").unwrap();
1871 // Group 1 -> Group 2 (at pos 0)
1872 // Group 2 -> Group 3 (at pos 0)
1873 // Group 3 -> Group 1 (at pos 1, after 'a')
1874 // This forms a cycle, but the call from group 3 to group 1 is at position 1
1875 // So it's not left-recursive
1876 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1877 matches!(e, CompileError::NeverEndingRecursion)
1878 });
1879 }
1880
1881 #[test]
1882 fn three_way_left_recursive() {
1883 // Three-way left recursion
1884 let tree = Expr::parse_tree(r"(\g<2>)(\g<3>)(\g<1>)").unwrap();
1885 let result = analyze(&tree, AnalyzeContext::default());
1886 // Group 1 -> Group 2 (at pos 0)
1887 // Group 2 -> Group 3 (at pos 0)
1888 // Group 3 -> Group 1 (at pos 0)
1889 // This forms a left-recursive cycle
1890 assert!(result.is_err());
1891
1892 let tree = Expr::parse_tree(r"(\g<2>a)(\g<3>b)(\g<1>c)").unwrap();
1893 let result = analyze(&tree, AnalyzeContext::default());
1894 assert!(result.is_err());
1895 }
1896
1897 #[test]
1898 fn left_recursive_with_call_to_defined_group() {
1899 // Even though the call from Group 1 to Group 2 is inside {0} at root level,
1900 // Group 1's pattern can still be executed when called from Group 2
1901 // Group 1 contains a?\g<2> - calls group 2 (when executed)
1902 // Group 2 contains \g<1> - calls group 1 at position 0
1903 // This creates a cycle: Group 2 -> Group 1 (at pos 0) -> Group 2 (at pos 0)
1904 let tree = Expr::parse_tree(r"(a?\g<2>){0}(\g<1>)").unwrap();
1905 assert_compile_error(analyze(&tree, AnalyzeContext::default()), |e| {
1906 matches!(e, CompileError::LeftRecursiveSubroutineCall(_))
1907 });
1908 }
1909
1910 #[test]
1911 fn no_left_recursion_complex_pattern() {
1912 // Group n (1): |\g<m>\g<n> - calls m then itself, but m has min_size > 0
1913 // Group m (2): a(b)\g<m> - calls itself after 'ab'
1914 let tree = Expr::parse_tree(r"(?<n>|\g<m>\g<n>)\z|\zEND (?<m>a(b)\g<m>)").unwrap();
1915 let result = analyze(&tree, AnalyzeContext::default());
1916
1917 assert!(
1918 result.is_ok(),
1919 "Pattern should not be left-recursive because group m has min_size > 0"
1920 );
1921 }
1922
1923 // Tests for forward-referenced subroutine calls
1924 // These verify that the analyzer correctly handles subroutine calls to groups
1925 // that are defined later in the pattern, and that group indexes are computed correctly.
1926
1927 #[test]
1928 fn forward_subroutine_call_single_group() {
1929 // Forward reference: calls group 1 before it's defined
1930 let tree = Expr::parse_tree(r"\g<1>(.a.)").unwrap();
1931 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1932
1933 // The pattern should have 1 capture group
1934 assert_eq!(info.start_group(), 1);
1935 assert_eq!(info.end_group(), 2);
1936
1937 // Verify the Info has the correct Expr nodes - a Concat with 2 children
1938 assert!(matches!(info.expr, Expr::Concat(_)));
1939 assert_eq!(info.children.len(), 2);
1940
1941 // First child is the SubroutineCall
1942 assert!(matches!(info.children[0].expr, Expr::SubroutineCall(1)));
1943 // SubroutineCall should have group range 1..1 (no new groups)
1944 assert_eq!(info.children[0].start_group(), 1);
1945 assert_eq!(info.children[0].end_group(), 1);
1946 // SubroutineCall should get the min_size from the group
1947 assert_eq!(info.children[0].min_size, 3);
1948 assert!(info.children[0].const_size);
1949
1950 // Second child is the group
1951 assert!(matches!(info.children[1].expr, Expr::Group(_)));
1952 assert_eq!(info.children[1].start_group(), 1);
1953 assert_eq!(info.children[1].end_group(), 2);
1954 // The group itself should also have min_size 3
1955 assert_eq!(info.children[1].min_size, 3);
1956 assert!(info.children[1].const_size);
1957
1958 // Overall pattern should have min_size 6 (subroutine call + group)
1959 assert_eq!(info.min_size, 6);
1960 assert!(info.const_size);
1961 }
1962
1963 #[test]
1964 fn forward_subroutine_call_with_multiple_groups() {
1965 // Forward reference with multiple groups defined after the subroutine call
1966 let tree = Expr::parse_tree(r"\g<2>(a)(bc+)").unwrap();
1967 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
1968
1969 // The pattern should have 2 capture groups
1970 assert_eq!(info.start_group(), 1);
1971 assert_eq!(info.end_group(), 3);
1972
1973 // Verify the Info Expr nodes - it's a Concat with 3 children
1974 assert!(matches!(info.expr, Expr::Concat(_)));
1975 assert_eq!(info.children.len(), 3);
1976
1977 // SubroutineCall to group 2
1978 assert!(matches!(info.children[0].expr, Expr::SubroutineCall(2)));
1979 // The subroutine call itself is not in a capture group
1980 assert_eq!(info.children[0].start_group(), 1);
1981 assert_eq!(info.children[0].end_group(), 1);
1982 // SubroutineCall should get the min_size from the group
1983 assert_eq!(info.children[0].min_size, 2);
1984 assert!(!info.children[0].const_size);
1985
1986 // First group (capture group 1)
1987 assert!(matches!(info.children[1].expr, Expr::Group(_)));
1988 assert_eq!(info.children[1].start_group(), 1);
1989 assert_eq!(info.children[1].end_group(), 2);
1990 assert_eq!(info.children[1].min_size, 1);
1991 assert!(info.children[1].const_size);
1992
1993 // Second group (capture group 2)
1994 assert!(matches!(info.children[2].expr, Expr::Group(_)));
1995 assert_eq!(info.children[2].start_group(), 2);
1996 assert_eq!(info.children[2].end_group(), 3);
1997 assert_eq!(info.children[2].min_size, 2);
1998 assert!(!info.children[2].const_size);
1999 }
2000
2001 #[test]
2002 fn forward_subroutine_call_with_nested_groups() {
2003 // Forward reference with multiple nested groups defined after the subroutine call
2004 let tree = Expr::parse_tree(r"(foo)\g<4>(a(b)?)(c(d))(?!e)").unwrap();
2005 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2006
2007 // The pattern should have 5 capture groups
2008 assert_eq!(info.start_group(), 1);
2009 assert_eq!(info.end_group(), 6);
2010
2011 // Verify the Info Expr nodes - it's a Concat with 5 children
2012 assert!(matches!(info.expr, Expr::Concat(_)));
2013 assert_eq!(info.children.len(), 5);
2014
2015 // SubroutineCall to group 4
2016 assert!(matches!(info.children[1].expr, Expr::SubroutineCall(4)));
2017 // The subroutine call itself is not in a capture group. but after group 1
2018 assert_eq!(info.children[1].start_group(), 2);
2019 assert_eq!(info.children[1].end_group(), 2);
2020 // SubroutineCall should get the min_size from the group
2021 assert_eq!(info.children[1].min_size, 2);
2022 assert!(info.children[1].const_size);
2023
2024 // First group after the subroutine call (capture group 2)
2025 assert!(matches!(info.children[2].expr, Expr::Group(_)));
2026 assert_eq!(info.children[2].start_group(), 2);
2027 assert_eq!(info.children[2].end_group(), 4);
2028 assert_eq!(info.children[2].min_size, 1);
2029 assert!(!info.children[2].const_size);
2030
2031 // Second group after the subroutine call (nested inside group 2)
2032 let group_info = &info.children[2].children[0].children[1].children[0];
2033 assert!(matches!(group_info.expr, Expr::Group(_)));
2034 assert_eq!(group_info.start_group(), 3);
2035 assert_eq!(group_info.end_group(), 4);
2036 assert_eq!(group_info.min_size, 1);
2037 assert!(group_info.const_size);
2038
2039 // Third group after the subroutine call
2040 assert!(matches!(info.children[3].expr, Expr::Group(_)));
2041 assert_eq!(info.children[3].start_group(), 4);
2042 assert_eq!(info.children[3].end_group(), 6);
2043 assert_eq!(info.children[3].min_size, 2);
2044 assert!(info.children[3].const_size);
2045
2046 // Fourth group after the subroutine call (nested inside group 4)
2047 let group_info = &info.children[3].children[0].children[1];
2048 assert!(matches!(group_info.expr, Expr::Group(_)));
2049 assert_eq!(group_info.start_group(), 5);
2050 assert_eq!(group_info.end_group(), 6);
2051 assert_eq!(group_info.min_size, 1);
2052 assert!(group_info.const_size);
2053
2054 // Negative lookahead should start after group 5
2055 assert!(matches!(info.children[4].expr, Expr::LookAround(_, _)));
2056 assert_eq!(info.children[4].start_group(), 6);
2057 assert_eq!(info.children[4].end_group(), 6);
2058 }
2059
2060 #[test]
2061 fn define_group_is_easy_zero_size() {
2062 // A DEFINE block should be analyzed as: min_size=0, const_size=true, hard=false
2063 // It matches nothing itself, so it doesn't need backtracking.
2064 let tree = Expr::parse_tree(r"(?(DEFINE)(?<word>\w+))").unwrap();
2065 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2066
2067 assert!(matches!(info.expr, Expr::DefineGroup { .. }));
2068 assert_eq!(info.min_size, 0);
2069 assert!(info.const_size);
2070 assert!(!info.hard);
2071 }
2072
2073 #[test]
2074 fn define_group_assigns_group_numbers() {
2075 // Groups inside a DEFINE block should still be assigned group numbers,
2076 // so that subroutine calls can reference them.
2077 let tree = Expr::parse_tree(r"(?(DEFINE)(?<first>a)(?<second>b))").unwrap();
2078 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2079
2080 // The definitions child: a Concat of two groups (groups 1 and 2)
2081 assert_eq!(info.children[0].start_group(), 1);
2082 assert_eq!(info.children[0].end_group(), 3);
2083
2084 // Group numbers are assigned in the usual order
2085 let tree = Expr::parse_tree(
2086 r"(abc)(?(DEFINE)(?<second>a)ignored: no group(?<third>b(?<fourth>c)))(?<fifth>d)",
2087 )
2088 .unwrap();
2089 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2090
2091 assert_eq!(info.start_group(), 1);
2092 assert_eq!(info.end_group(), 6);
2093 assert_eq!(info.children[0].start_group(), 1);
2094 assert_eq!(info.children[1].children[0].start_group(), 2);
2095 assert_eq!(info.children[2].start_group(), 5);
2096 assert_eq!(info.children[2].end_group(), 6);
2097 }
2098
2099 // Tests for max_size
2100
2101 #[test]
2102 fn max_size_for_literal() {
2103 let tree = Expr::parse_tree("a").unwrap();
2104 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2105 assert_eq!(info.max_size, 1);
2106 }
2107
2108 #[test]
2109 fn max_size_for_concat_of_literals() {
2110 let tree = Expr::parse_tree("abc").unwrap();
2111 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2112 assert_eq!(info.max_size, 3);
2113 }
2114
2115 #[test]
2116 fn max_size_for_general_newline() {
2117 let tree = Expr::parse_tree(r"\R").unwrap();
2118 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2119 assert_eq!(info.max_size, 2);
2120 }
2121
2122 #[test]
2123 fn max_size_for_greedy_star() {
2124 let tree = Expr::parse_tree("a*").unwrap();
2125 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2126 assert_eq!(info.max_size, usize::MAX);
2127 }
2128
2129 #[test]
2130 fn max_size_for_greedy_plus() {
2131 let tree = Expr::parse_tree("a+").unwrap();
2132 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2133 assert_eq!(info.max_size, usize::MAX);
2134 }
2135
2136 #[test]
2137 fn max_size_for_optional() {
2138 let tree = Expr::parse_tree("a?").unwrap();
2139 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2140 assert_eq!(info.max_size, 1);
2141 }
2142
2143 #[test]
2144 fn max_size_for_bounded_repeat() {
2145 let tree = Expr::parse_tree("a{1,3}").unwrap();
2146 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2147 assert_eq!(info.max_size, 3);
2148 }
2149
2150 #[test]
2151 fn max_size_for_exact_repeat() {
2152 let tree = Expr::parse_tree("a{3}").unwrap();
2153 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2154 assert_eq!(info.max_size, 3);
2155 }
2156
2157 #[test]
2158 fn max_size_for_alternation() {
2159 let tree = Expr::parse_tree("a|bc").unwrap();
2160 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2161 assert_eq!(info.max_size, 2);
2162 }
2163
2164 #[test]
2165 fn max_size_for_group() {
2166 let tree = Expr::parse_tree(r"(abc)").unwrap();
2167 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2168 assert_eq!(info.max_size, 3);
2169 }
2170
2171 #[test]
2172 fn max_size_for_backref_inherits_group() {
2173 let tree = Expr::parse_tree(r"(ab)\1").unwrap();
2174 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2175 assert_eq!(info.max_size, 4);
2176 }
2177
2178 #[test]
2179 fn max_size_for_concat_accumulates() {
2180 // ab*cd = concat(literal a, repeat b*, literal c, literal d)
2181 // max_size = 1 + MAX + 1 + 1 = MAX
2182 let tree = Expr::parse_tree("ab*cd").unwrap();
2183 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2184 assert_eq!(info.max_size, usize::MAX);
2185 }
2186
2187 #[test]
2188 fn max_size_for_empty_assertion_is_zero() {
2189 let tree = Expr::parse_tree(r"\b").unwrap();
2190 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2191 assert_eq!(info.max_size, 0);
2192 }
2193
2194 // Tests for leftmost_longest flag
2195
2196 #[cfg(feature = "leftmost_longest")]
2197 #[test]
2198 fn leftmost_longest_rejects_non_greedy_star() {
2199 let tree = Expr::parse_tree(r"a*?").unwrap();
2200 let result = analyze(
2201 &tree,
2202 AnalyzeContext {
2203 leftmost_longest: true,
2204 ..Default::default()
2205 },
2206 );
2207 assert_compile_error(
2208 result,
2209 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("non-greedy")),
2210 );
2211 }
2212
2213 #[cfg(feature = "leftmost_longest")]
2214 #[test]
2215 fn leftmost_longest_rejects_non_greedy_plus() {
2216 let tree = Expr::parse_tree(r"a+?").unwrap();
2217 let result = analyze(
2218 &tree,
2219 AnalyzeContext {
2220 leftmost_longest: true,
2221 ..Default::default()
2222 },
2223 );
2224 assert_compile_error(
2225 result,
2226 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("non-greedy")),
2227 );
2228 }
2229
2230 #[cfg(feature = "leftmost_longest")]
2231 #[test]
2232 fn leftmost_longest_rejects_non_greedy_optional() {
2233 let tree = Expr::parse_tree(r"a??").unwrap();
2234 let result = analyze(
2235 &tree,
2236 AnalyzeContext {
2237 leftmost_longest: true,
2238 ..Default::default()
2239 },
2240 );
2241 assert_compile_error(
2242 result,
2243 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("non-greedy")),
2244 );
2245 }
2246
2247 #[cfg(feature = "leftmost_longest")]
2248 #[test]
2249 fn leftmost_longest_rejects_non_greedy_bounded() {
2250 let tree = Expr::parse_tree(r"a{1,3}?").unwrap();
2251 let result = analyze(
2252 &tree,
2253 AnalyzeContext {
2254 leftmost_longest: true,
2255 ..Default::default()
2256 },
2257 );
2258 assert_compile_error(
2259 result,
2260 |e| matches!(e, CompileError::FeatureNotYetSupported(s) if s.contains("non-greedy")),
2261 );
2262 }
2263
2264 #[cfg(feature = "leftmost_longest")]
2265 #[test]
2266 fn leftmost_longest_accepts_greedy_quantifiers() {
2267 assert_analyze_ok(
2268 &Expr::parse_tree(r"a*").unwrap(),
2269 AnalyzeContext {
2270 leftmost_longest: true,
2271 ..Default::default()
2272 },
2273 );
2274 assert_analyze_ok(
2275 &Expr::parse_tree(r"a+").unwrap(),
2276 AnalyzeContext {
2277 leftmost_longest: true,
2278 ..Default::default()
2279 },
2280 );
2281 assert_analyze_ok(
2282 &Expr::parse_tree(r"a?").unwrap(),
2283 AnalyzeContext {
2284 leftmost_longest: true,
2285 ..Default::default()
2286 },
2287 );
2288 assert_analyze_ok(
2289 &Expr::parse_tree(r"a{1,3}").unwrap(),
2290 AnalyzeContext {
2291 leftmost_longest: true,
2292 ..Default::default()
2293 },
2294 );
2295 }
2296
2297 #[cfg(feature = "leftmost_longest")]
2298 #[test]
2299 fn leftmost_longest_promotes_non_const_to_hard() {
2300 // Without leftmost_longest, a* is not hard (can be delegated to regex-automata)
2301 let tree = Expr::parse_tree(r"a*").unwrap();
2302 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2303 assert!(!info.hard);
2304 assert!(!info.const_size);
2305
2306 // With leftmost_longest, a* becomes hard because it's not const_size
2307 let info = analyze(
2308 &tree,
2309 AnalyzeContext {
2310 leftmost_longest: true,
2311 ..Default::default()
2312 },
2313 )
2314 .unwrap();
2315 assert!(info.hard);
2316 assert!(!info.const_size);
2317 }
2318
2319 #[cfg(feature = "leftmost_longest")]
2320 #[test]
2321 fn leftmost_longest_keeps_const_size_easy() {
2322 let tree = Expr::parse_tree(r"abc").unwrap();
2323 let info = analyze(
2324 &tree,
2325 AnalyzeContext {
2326 leftmost_longest: true,
2327 ..Default::default()
2328 },
2329 )
2330 .unwrap();
2331 assert!(!info.hard);
2332 assert!(info.const_size);
2333 }
2334
2335 // Tests for EndText assertion with find_not_empty
2336
2337 #[test]
2338 fn end_text_hard_with_find_not_empty() {
2339 let tree = Expr::parse_tree(r"$").unwrap();
2340 let info = analyze(
2341 &tree,
2342 AnalyzeContext {
2343 find_not_empty: true,
2344 ..Default::default()
2345 },
2346 )
2347 .unwrap();
2348 assert!(info.hard);
2349 assert!(info.const_size);
2350 }
2351
2352 #[test]
2353 fn end_text_not_hard_without_find_not_empty() {
2354 let tree = Expr::parse_tree(r"$").unwrap();
2355 let info = analyze(&tree, AnalyzeContext::default()).unwrap();
2356 assert!(!info.hard);
2357 assert!(info.const_size);
2358 }
2359
2360 #[test]
2361 fn end_text_not_hard_in_lookaround_with_find_not_empty() {
2362 // Inside a lookaround, $ does not get the find_not_empty hard treatment
2363 let tree = Expr::parse_tree(r"(?=$)").unwrap();
2364 let info = analyze(
2365 &tree,
2366 AnalyzeContext {
2367 find_not_empty: true,
2368 ..Default::default()
2369 },
2370 )
2371 .unwrap();
2372 // The lookahead's child is directly the EndText assertion
2373 let end_text_info = &info.children[0];
2374 assert!(!end_text_info.hard);
2375 assert!(end_text_info.const_size);
2376 }
2377 }