Debian Codegraph @

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

raw
1 // Copyright 2025 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 //! Optimization of regex expressions.
22
23 use crate::parse::ExprTree;
24 use crate::Expr;
25 use crate::LookAround;
26
27 use alloc::boxed::Box;
28 use alloc::sync::Arc;
29 use alloc::vec;
30 use alloc::vec::Vec;
31 use core::mem;
32
33 /// Rewrite the expression tree to help the VM compile an efficient program.
34 /// Returns a boolean to say whether the new tree explicitly contains capture group 0.
35 pub fn optimize(tree: &mut ExprTree) -> bool {
36 // self recursion prevents us from moving the trailing lookahead out of group 0
37 let requires_capture_group_fixup = if !tree.self_recursive {
38 // KeepOut (\K) optimization is tried first; it also handles a trailing positive
39 // lookahead when both are present, so we skip the standalone lookahead pass in
40 // that case to avoid creating a second explicit capture group 0.
41 if optimize_keepout(tree) {
42 true
43 } else {
44 optimize_trailing_lookahead(tree)
45 }
46 } else {
47 false
48 };
49
50 let has_backrefs = !tree.backrefs.is_empty();
51 optimize_nested_repeats(&mut tree.expr, has_backrefs);
52 optimize_ambiguous_concat_repeats(&mut tree.expr);
53
54 requires_capture_group_fixup
55 }
56
57 /// Simplify nested repeat quantifiers (e.g. `(?:x+)+` → `x+`) to help
58 /// the VM avoid catastrophic backtracking from deeply nested quantifiers.
59 /// Repeats around capture groups get special consideration not to affect
60 /// capture semantics. This means that:
61 /// - if backreferences are used, the optimization is not valid.
62 /// - if the outer group is optional, the capture group can be skipped entirely,
63 /// so we need to preserve that behavior.
64 fn optimize_nested_repeats(expr: &mut Expr, has_backrefs: bool) {
65 for child in expr.children_iter_mut() {
66 optimize_nested_repeats(child, has_backrefs);
67 }
68
69 let replacement = if let Expr::Repeat {
70 child,
71 lo: outer_lo,
72 hi: outer_hi,
73 greedy: outer_greedy,
74 } = expr
75 {
76 if let Expr::Repeat {
77 child: inner_child,
78 lo: inner_lo,
79 hi: inner_hi,
80 greedy: inner_greedy,
81 } = child.as_ref()
82 {
83 // the outer repeat's child is itself a bare Repeat (no
84 // capture group involved). Folding the two quantifiers together is
85 // always safe.
86 if let Some(result_kind) = can_simplify(
87 *outer_lo,
88 *outer_hi,
89 *outer_greedy,
90 *inner_lo,
91 *inner_hi,
92 *inner_greedy,
93 ) {
94 let result_kind =
95 downgrade_to_optional(result_kind, has_backrefs, inner_child.as_ref());
96 Some(compose_repeat(
97 Box::new(inner_child.as_ref().clone()),
98 result_kind,
99 ))
100 } else {
101 None
102 }
103 } else if let Expr::Group(group) = child.as_mut() {
104 if let Expr::Repeat {
105 child: inner_child,
106 lo: inner_lo,
107 hi: inner_hi,
108 greedy: inner_greedy,
109 } = group.as_ref()
110 {
111 if *outer_lo == 0 {
112 // outer_lo == 0 (ZeroOrMore or Optional). When there are no
113 // backreferences and the group's content is self-absorbing (an
114 // unbounded repeat like `x+`), downgrade the outer {0,} (ZeroOrMore)
115 // to ? (Optional). This is safe because (X+)* = (X+)? when X is
116 // self-absorbing, and without backreferences the differing group
117 // participation count is unobservable. The ? form is more efficient
118 // for the VM (single backtrack point instead of a loop).
119 if !has_backrefs && *outer_hi == usize::MAX && is_self_absorbing(group.as_ref())
120 {
121 *outer_hi = 1;
122 }
123 None
124 } else {
125 // Here we only optimize when outer_lo is > 0 (i.e. not Optional or ZeroOrMore)
126 // This is because, when the outer repeat is optional, the capture group can be
127 // skipped entirely, correctly yielding an unmatched (None) capture.
128 // If we were to use the simplified form, it would always enter the group,
129 // yielding Some(""). So we must not simplify in that case to preserve
130 // capture semantics.
131
132 if let Some(result_kind) = can_simplify(
133 *outer_lo,
134 *outer_hi,
135 *outer_greedy,
136 *inner_lo,
137 *inner_hi,
138 *inner_greedy,
139 ) {
140 let result_kind =
141 downgrade_to_optional(result_kind, has_backrefs, inner_child.as_ref());
142 Some(Expr::Group(Arc::new(compose_repeat(
143 Box::new(inner_child.as_ref().clone()),
144 result_kind,
145 ))))
146 } else {
147 None
148 }
149 }
150 } else {
151 None
152 }
153 } else {
154 None
155 }
156 } else {
157 None
158 };
159
160 if let Some(replacement) = replacement {
161 *expr = replacement;
162 }
163 }
164
165 fn optimize_ambiguous_concat_repeats(expr: &mut Expr) {
166 for child in expr.children_iter_mut() {
167 optimize_ambiguous_concat_repeats(child);
168 }
169
170 if let Expr::Concat(children) = expr {
171 rewrite_concat_repeat_windows(children);
172 }
173
174 let should_rewrite = if let Expr::Repeat {
175 child,
176 lo,
177 hi,
178 greedy,
179 } = &*expr
180 {
181 *greedy && *hi == usize::MAX && check_repeated_concat(child.as_ref(), *lo)
182 } else {
183 false
184 };
185
186 if should_rewrite {
187 let owned = mem::replace(expr, Expr::Empty);
188 if let Expr::Repeat { child, lo, .. } = owned {
189 *expr = build_repeated_concat(*child, lo);
190 }
191 }
192 }
193
194 fn rewrite_concat_repeat_windows(children: &mut Vec<Expr>) {
195 let mut ix = 0;
196 while ix + 2 < children.len() {
197 if check_concat_repeat_triplet(&children[ix], &children[ix + 1], &children[ix + 2]) {
198 let mut left = Expr::Empty;
199 let mut middle = Expr::Empty;
200 let mut right = Expr::Empty;
201 mem::swap(&mut left, &mut children[ix]);
202 mem::swap(&mut middle, &mut children[ix + 1]);
203 mem::swap(&mut right, &mut children[ix + 2]);
204 let (prefix, optional_tail) = build_concat_repeat_triplet(left, middle, right);
205 children.splice(ix..ix + 3, [prefix, optional_tail]);
206 ix += 2;
207 } else {
208 ix += 1;
209 }
210 }
211 }
212
213 fn check_concat_repeat_triplet(left: &Expr, middle: &Expr, right: &Expr) -> bool {
214 let Expr::Repeat {
215 child: left_inner,
216 lo: left_lo,
217 hi: left_hi,
218 greedy: left_greedy,
219 } = left
220 else {
221 return false;
222 };
223 let Expr::Repeat {
224 child: right_inner,
225 lo: right_lo,
226 hi: right_hi,
227 greedy: right_greedy,
228 } = right
229 else {
230 return false;
231 };
232 let Expr::Repeat {
233 lo: middle_lo,
234 hi: middle_hi,
235 ..
236 } = middle
237 else {
238 return false;
239 };
240
241 is_unbounded_simple_repeat(*left_lo, *left_hi, *left_greedy)
242 && is_unbounded_simple_repeat(*right_lo, *right_hi, *right_greedy)
243 && compatible_edge_repeat_bounds(*left_lo, *right_lo)
244 && *middle_lo == 0
245 && *middle_hi != 0
246 && left_inner.as_ref() == right_inner.as_ref()
247 }
248
249 fn build_concat_repeat_triplet(left: Expr, middle: Expr, right: Expr) -> (Expr, Expr) {
250 let Expr::Repeat {
251 child: left_inner,
252 lo: left_lo,
253 ..
254 } = left
255 else {
256 unreachable!("check_concat_repeat_triplet guarantees left is a Repeat");
257 };
258 let Expr::Repeat {
259 child: middle_inner,
260 hi: middle_hi,
261 greedy: middle_greedy,
262 ..
263 } = middle
264 else {
265 unreachable!("check_concat_repeat_triplet guarantees middle is a Repeat");
266 };
267 let right_lo = if let Expr::Repeat { lo, .. } = &right {
268 *lo
269 } else {
270 unreachable!("check_concat_repeat_triplet guarantees right is a Repeat");
271 };
272
273 let mandatory_middle = Expr::Repeat {
274 child: middle_inner,
275 lo: 1,
276 hi: middle_hi,
277 greedy: middle_greedy,
278 };
279
280 if left_lo < right_lo {
281 // The right repeat is the less permissive (higher lo) side — keep it as a mandatory
282 // suffix. Make the left repeat and middle optional as a prefix instead, so that the
283 // rewritten expression is no more permissive than the original.
284 // E.g. `\w*\.?\w+` → `(?:\w*\.{1})?\w+`
285 let left_repeat = Expr::Repeat {
286 child: left_inner,
287 lo: left_lo,
288 hi: usize::MAX,
289 greedy: true,
290 };
291 let head = Expr::Concat(vec![left_repeat, mandatory_middle]);
292 let optional_head = Expr::Repeat {
293 child: Box::new(head),
294 lo: 0,
295 hi: 1,
296 greedy: true,
297 };
298 (optional_head, right)
299 } else {
300 // The left repeat is the less permissive (higher or equal lo) side — keep it as a
301 // mandatory prefix. Make the middle and right repeat optional as a suffix.
302 // E.g. `\w+\.?\w+` → `\w+(?:\.{1}\w+)?`
303 // E.g. `\w+\.?\w*` → `\w+(?:\.{1}\w*)?`
304 let prefix = Expr::Repeat {
305 child: left_inner,
306 lo: left_lo,
307 hi: usize::MAX,
308 greedy: true,
309 };
310 let tail = Expr::Concat(vec![mandatory_middle, right]);
311 let optional_tail = Expr::Repeat {
312 child: Box::new(tail),
313 lo: 0,
314 hi: 1,
315 greedy: true,
316 };
317 (prefix, optional_tail)
318 }
319 }
320
321 fn check_repeated_concat(child: &Expr, outer_lo: usize) -> bool {
322 if outer_lo != 0 && outer_lo != 1 {
323 return false;
324 }
325 let Expr::Concat(children) = child else {
326 return false;
327 };
328 let [prefix, optional_tail] = children.as_slice() else {
329 return false;
330 };
331 let Expr::Repeat {
332 child: tail_inner,
333 lo: tail_lo,
334 hi: tail_hi,
335 greedy: tail_greedy,
336 } = optional_tail
337 else {
338 return false;
339 };
340 if !*tail_greedy || *tail_lo != 0 || *tail_hi != 1 {
341 return false;
342 }
343 let Expr::Concat(tail_children) = tail_inner.as_ref() else {
344 return false;
345 };
346 let [_middle_part, right] = tail_children.as_slice() else {
347 return false;
348 };
349 let Expr::Repeat {
350 child: prefix_inner,
351 lo: prefix_lo,
352 hi: prefix_hi,
353 greedy: prefix_greedy,
354 } = prefix
355 else {
356 return false;
357 };
358 let Expr::Repeat {
359 child: right_inner,
360 lo: right_lo,
361 hi: right_hi,
362 greedy: right_greedy,
363 } = right
364 else {
365 return false;
366 };
367
368 is_unbounded_simple_repeat(*prefix_lo, *prefix_hi, *prefix_greedy)
369 && is_unbounded_simple_repeat(*right_lo, *right_hi, *right_greedy)
370 && compatible_edge_repeat_bounds(*prefix_lo, *right_lo)
371 && prefix_inner.as_ref() == right_inner.as_ref()
372 }
373
374 fn build_repeated_concat(child: Expr, outer_lo: usize) -> Expr {
375 let Expr::Concat(mut children) = child else {
376 unreachable!("check_repeated_concat guarantees child is a Concat");
377 };
378 // children = [prefix_repeat, optional_tail]
379 let optional_tail = children.pop().unwrap();
380 let prefix = children.pop().unwrap();
381
382 let Expr::Repeat {
383 child: tail_inner, ..
384 } = optional_tail
385 else {
386 unreachable!("check_repeated_concat guarantees tail is a Repeat");
387 };
388 let Expr::Concat(mut tail_children) = *tail_inner else {
389 unreachable!("check_repeated_concat guarantees tail inner is a Concat");
390 };
391 // tail_children = [middle_part, right_repeat]
392 let right = tail_children.pop().unwrap();
393 let middle_part = tail_children.pop().unwrap();
394
395 let repeated_tail = Expr::Repeat {
396 child: Box::new(Expr::Concat(vec![middle_part, right])),
397 lo: 0,
398 hi: usize::MAX,
399 greedy: true,
400 };
401 let core = Expr::Concat(vec![prefix, repeated_tail]);
402 match outer_lo {
403 1 => core,
404 0 => Expr::Repeat {
405 child: Box::new(core),
406 lo: 0,
407 hi: 1,
408 greedy: true,
409 },
410 _ => unreachable!("check_repeated_concat guarantees outer_lo is 0 or 1"),
411 }
412 }
413
414 fn is_unbounded_simple_repeat(lo: usize, hi: usize, greedy: bool) -> bool {
415 greedy && hi == usize::MAX && matches!(lo, 0 | 1)
416 }
417
418 fn compatible_edge_repeat_bounds(left_lo: usize, right_lo: usize) -> bool {
419 matches!((left_lo, right_lo), (0, 0) | (0, 1) | (1, 0) | (1, 1))
420 }
421
422 fn compose_repeat(child: Box<Expr>, result_kind: QuantifierKind) -> Expr {
423 let (lo, hi) = result_kind.bounds();
424 Expr::Repeat {
425 child,
426 lo,
427 hi,
428 greedy: true,
429 }
430 }
431
432 /// Checks whether `(expr)*` is equivalent to `(expr)?`, i.e. whether the language
433 /// of `expr` is closed under concatenation (L(expr)·L(expr) ⊆ L(expr)).
434 ///
435 /// This is true for unbounded repeats (`X+` and `X*`) and `Empty`, but not for
436 /// bounded repeats like `X?` (where two iterations can match `X{2}` which a single
437 /// iteration cannot) or for simple atoms like a `Literal`.
438 fn is_self_absorbing(expr: &Expr) -> bool {
439 match expr {
440 Expr::Repeat { hi, .. } => *hi == usize::MAX,
441 Expr::Group(inner) => is_self_absorbing(inner.as_ref()),
442 Expr::Empty => true,
443 _ => false,
444 }
445 }
446
447 /// When the pattern has no backreferences, a `ZeroOrMore` result can be downgraded
448 /// to `Optional` if the inner child is self-absorbing (its language is closed under
449 /// concatenation). This produces a more efficient VM program because `?` creates a
450 /// single backtrack point instead of a loop, and the match result is unchanged.
451 fn downgrade_to_optional(
452 result_kind: QuantifierKind,
453 has_backrefs: bool,
454 inner_child: &Expr,
455 ) -> QuantifierKind {
456 if !has_backrefs && result_kind == QuantifierKind::ZeroOrMore && is_self_absorbing(inner_child)
457 {
458 QuantifierKind::Optional
459 } else {
460 result_kind
461 }
462 }
463
464 fn can_simplify(
465 outer_lo: usize,
466 outer_hi: usize,
467 outer_greedy: bool,
468 inner_lo: usize,
469 inner_hi: usize,
470 inner_greedy: bool,
471 ) -> Option<QuantifierKind> {
472 if !outer_greedy || !inner_greedy {
473 return None;
474 }
475
476 let outer = quantifier_kind(outer_lo, outer_hi)?;
477 let inner = quantifier_kind(inner_lo, inner_hi)?;
478
479 match (inner, outer) {
480 (QuantifierKind::OneOrMore, QuantifierKind::OneOrMore) => Some(QuantifierKind::OneOrMore),
481 (QuantifierKind::ZeroOrMore, QuantifierKind::OneOrMore) => Some(QuantifierKind::ZeroOrMore),
482 (QuantifierKind::Optional, QuantifierKind::OneOrMore) => Some(QuantifierKind::ZeroOrMore),
483 (QuantifierKind::OneOrMore, QuantifierKind::ZeroOrMore) => Some(QuantifierKind::ZeroOrMore),
484 (QuantifierKind::ZeroOrMore, QuantifierKind::ZeroOrMore) => {
485 Some(QuantifierKind::ZeroOrMore)
486 }
487 (QuantifierKind::Optional, QuantifierKind::ZeroOrMore) => Some(QuantifierKind::ZeroOrMore),
488 (QuantifierKind::OneOrMore, QuantifierKind::Optional) => Some(QuantifierKind::ZeroOrMore),
489 (QuantifierKind::ZeroOrMore, QuantifierKind::Optional) => Some(QuantifierKind::ZeroOrMore),
490 (QuantifierKind::Optional, QuantifierKind::Optional) => Some(QuantifierKind::Optional),
491 }
492 }
493
494 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
495 enum QuantifierKind {
496 Optional,
497 ZeroOrMore,
498 OneOrMore,
499 }
500
501 impl QuantifierKind {
502 fn bounds(self) -> (usize, usize) {
503 match self {
504 QuantifierKind::Optional => (0, 1),
505 QuantifierKind::ZeroOrMore => (0, usize::MAX),
506 QuantifierKind::OneOrMore => (1, usize::MAX),
507 }
508 }
509 }
510
511 fn quantifier_kind(lo: usize, hi: usize) -> Option<QuantifierKind> {
512 match (lo, hi) {
513 (0, 1) => Some(QuantifierKind::Optional),
514 (0, usize::MAX) => Some(QuantifierKind::ZeroOrMore),
515 (1, usize::MAX) => Some(QuantifierKind::OneOrMore),
516 _ => None,
517 }
518 }
519
520 fn optimize_keepout(tree: &mut ExprTree) -> bool {
521 // Rewrites a root-level `\K` (KeepOut) in a Concat into an explicit capture group 0.
522 //
523 // `\K` resets the reported match start to the current position, so whatever follows it
524 // is the "real" match. By wrapping the suffix in a capture group we can delegate the
525 // whole expression to regex-automata and read the result from group 1.
526 //
527 // Example: `\w+:\s*"\K[^"]*` → `\w+:\s*"([^"]*)`
528 //
529 // When a trailing positive lookahead is also present the two optimizations are merged
530 // into a single new capture group to avoid needing two explicit group-0 wrappers:
531 //
532 // Example: `\w+:\s*"\K[^"]*(?=")` → `\w+:\s*"([^"]*)"`
533 //
534 // The optimization requires that none of the prefix children (before the \K) contain
535 // capture groups. If they do, the new wrapper group would not be group 1, which
536 // breaks the `explicit_capture_group_0` mechanism that reads the match span from group 1.
537
538 let Expr::Concat(ref mut children) = tree.expr else {
539 return false;
540 };
541
542 // Find the first KeepOut at the root concat level.
543 let Some(keepout_pos) = children.iter().position(|e| matches!(e, Expr::KeepOut)) else {
544 return false;
545 };
546
547 // Safety check: any capture group in the prefix would be numbered before our new
548 // wrapper group, so it would become group 1 instead of our wrapper.
549 // Note: `has_descendant` checks only strict descendants, not the node itself,
550 // so we need the explicit `matches!(child, Expr::Group(_))` check alongside it.
551 let prefix_has_capture_groups = children[..keepout_pos].iter().any(|child| {
552 matches!(child, Expr::Group(_)) || child.has_descendant(|e| matches!(e, Expr::Group(_)))
553 });
554 if prefix_has_capture_groups {
555 return false;
556 }
557
558 // Drain KeepOut and everything after it.
559 let mut tail: Vec<Expr> = children.drain(keepout_pos..).collect();
560 // Remove the KeepOut itself (first element of `tail`).
561 tail.remove(0);
562
563 // Check whether the last remaining child is a trailing positive lookahead.
564 // If so, pull its inner expression out so we can keep it outside the new group.
565 let lookahead_inner = if let Some(Expr::LookAround(_, LookAround::LookAhead)) = tail.last() {
566 let last = tail.pop().expect("just checked last is Some");
567 if let Expr::LookAround(inner, LookAround::LookAhead) = last {
568 Some(*inner)
569 } else {
570 unreachable!("already checked it is a lookahead");
571 }
572 } else {
573 None
574 };
575
576 // Build the content of the new capture group from the remaining tail.
577 let group_content = match tail.len() {
578 0 => Expr::Empty,
579 1 => tail.remove(0),
580 _ => Expr::Concat(tail),
581 };
582 let group0 = Expr::Group(Arc::new(group_content));
583
584 // Append: Group(suffix) and then the lookahead's inner expression (if any).
585 children.push(group0);
586 if let Some(la_inner) = lookahead_inner {
587 children.push(la_inner);
588 }
589
590 tree.total_groups += 1;
591 true
592 }
593
594 fn optimize_trailing_lookahead(tree: &mut ExprTree) -> bool {
595 // returns a boolean to say whether the optimization was applied.
596 // - if it was applied, capture group 0 is no longer implicit, but explicit
597 // if/when the whole expression gets delegated to regex-automata
598 // converts i.e. original pattern `a(?=b)` when wrapped in the capture group 0
599 // as `(a(?=b))`
600 // to `(a)b`
601
602 if let Expr::Concat(ref mut root_concat_children) = tree.expr {
603 // we get the last child if it is a positive lookahead
604 if let Some(Expr::LookAround(_, LookAround::LookAhead)) = root_concat_children.last() {
605 // then pop the lookahead
606 let lookahead_expr = root_concat_children
607 .pop()
608 .expect("lookaround should be popped");
609 // take the rest of the children from the original Concat
610 let group0_children = mem::take(root_concat_children);
611
612 // extract the inner expression from the lookahead
613 if let Expr::LookAround(inner, LookAround::LookAhead) = lookahead_expr {
614 let group0 = Expr::Group(Arc::new(Expr::Concat(group0_children)));
615 // compose new Concat: [Group0, lookahead inner expr]
616 let new_concat = Expr::Concat(vec![group0, *inner]);
617 tree.expr = new_concat;
618 tree.total_groups += 1;
619 return true;
620 } else {
621 unreachable!("already checked it is a lookahead");
622 }
623 }
624 } else if let Expr::LookAround(ref mut inner, LookAround::LookAhead) = &mut tree.expr {
625 let group0 = Expr::Group(Arc::new(Expr::Empty));
626 let mut swap = Expr::Empty;
627 mem::swap(&mut swap, inner);
628 // compose new Concat: [Group0, lookahead inner expr]
629 tree.expr = Expr::Concat(vec![group0, swap]);
630 tree.total_groups += 1;
631 return true;
632 }
633 false
634 }
635
636 #[cfg(test)]
637 mod tests {
638 use super::optimize;
639 use super::vec;
640 use super::Arc;
641 use super::Box;
642 use crate::parse::make_literal;
643 use crate::Expr;
644 use alloc::string::String;
645
646 fn optimized_pattern(pattern: &str) -> String {
647 optimized_pattern_with_flags(pattern, crate::parse_flags::FLAG_UNICODE)
648 }
649
650 fn optimized_pattern_with_flags(pattern: &str, flags: u32) -> String {
651 let mut tree = Expr::parse_tree_with_flags(pattern, flags).unwrap();
652 optimize(&mut tree);
653 let mut s = String::new();
654 tree.expr.to_str(&mut s, 0);
655 s
656 }
657
658 fn oniguruma_flags() -> u32 {
659 crate::parse_flags::FLAG_ONIGURUMA_MODE | crate::parse_flags::FLAG_UNICODE
660 }
661
662 #[test]
663 fn trailing_positive_lookahead_optimized() {
664 let mut tree = Expr::parse_tree("a(?=b)").unwrap();
665 let requires_capture_group_fixup = optimize(&mut tree);
666 assert_eq!(requires_capture_group_fixup, true);
667 let mut s = String::new();
668 tree.expr.to_str(&mut s, 0);
669 assert_eq!(s, "(a)b");
670 }
671
672 #[test]
673 fn standalone_positive_lookahead_optimized() {
674 let mut tree = Expr::parse_tree("(?=b)").unwrap();
675 let requires_capture_group_fixup = optimize(&mut tree);
676 assert_eq!(requires_capture_group_fixup, true);
677 let mut s = String::new();
678 tree.expr.to_str(&mut s, 0);
679 assert_eq!(s, "()b");
680 }
681
682 #[test]
683 fn trailing_positive_lookahead_with_alternative_optimized() {
684 let mut tree = Expr::parse_tree("a(?=b|c)").unwrap();
685 let requires_capture_group_fixup = optimize(&mut tree);
686 assert_eq!(requires_capture_group_fixup, true);
687 let mut s = String::new();
688 tree.expr.to_str(&mut s, 0);
689 assert_eq!(s, "(a)(?:b|c)");
690 }
691
692 #[test]
693 fn trailing_positive_lookahead_moved_even_if_not_easy() {
694 let mut tree = Expr::parse_tree(r"(a)\1(?=c)").unwrap();
695 let requires_capture_group_fixup = optimize(&mut tree);
696 assert_eq!(requires_capture_group_fixup, true);
697 assert_eq!(
698 tree.expr,
699 Expr::Concat(vec![
700 Expr::Group(Arc::new(Expr::Concat(vec![
701 Expr::Group(Arc::new(make_literal("a"))),
702 Expr::Backref {
703 group: 1,
704 casei: false
705 }
706 ]))),
707 make_literal("c"),
708 ])
709 );
710 }
711
712 #[test]
713 fn trailing_positive_lookahead_left_alone_when_self_recursive() {
714 let tree = Expr::parse_tree(r"ab?\g<0>?(?=a|$)").unwrap();
715 let mut optimized_tree = tree.clone();
716 let requires_capture_group_fixup = optimize(&mut optimized_tree);
717 assert_eq!(requires_capture_group_fixup, false);
718 assert_eq!(&optimized_tree.expr, &tree.expr);
719 }
720
721 #[test]
722 fn trailing_negative_lookahead_left_alone() {
723 let tree = Expr::parse_tree(r"a(?!b)").unwrap();
724 let mut optimized_tree = tree.clone();
725 let requires_capture_group_fixup = optimize(&mut optimized_tree);
726 assert_eq!(requires_capture_group_fixup, false);
727 assert_eq!(&optimized_tree.expr, &tree.expr);
728 }
729
730 #[test]
731 fn trailing_positive_lookbehind_left_alone() {
732 let tree = Expr::parse_tree(r"(?<=b)").unwrap();
733 let mut optimized_tree = tree.clone();
734 let requires_capture_group_fixup = optimize(&mut optimized_tree);
735 assert_eq!(requires_capture_group_fixup, false);
736 assert_eq!(&optimized_tree.expr, &tree.expr);
737 }
738
739 #[test]
740 fn non_trailing_positive_lookahead_left_alone() {
741 let tree = Expr::parse_tree(r"a(?=(b))\1").unwrap();
742 let mut optimized_tree = tree.clone();
743 let requires_capture_group_fixup = optimize(&mut optimized_tree);
744 assert_eq!(requires_capture_group_fixup, false);
745 assert_eq!(&optimized_tree.expr, &tree.expr);
746
747 let tree = Expr::parse_tree(r"(?=(b))\1").unwrap();
748 let mut optimized_tree = tree.clone();
749 let requires_capture_group_fixup = optimize(&mut optimized_tree);
750 assert_eq!(requires_capture_group_fixup, false);
751 assert_eq!(&optimized_tree.expr, &tree.expr);
752 }
753
754 #[test]
755 fn keepout_optimized() {
756 let mut tree = Expr::parse_tree(r"ab\Kcd").unwrap();
757 let requires_capture_group_fixup = optimize(&mut tree);
758 assert_eq!(requires_capture_group_fixup, true);
759 let mut s = String::new();
760 tree.expr.to_str(&mut s, 0);
761 assert_eq!(s, "ab(cd)");
762 }
763
764 #[test]
765 fn keepout_at_start_of_concat_optimized() {
766 let mut tree = Expr::parse_tree(r"\Kcd").unwrap();
767 let requires_capture_group_fixup = optimize(&mut tree);
768 assert_eq!(requires_capture_group_fixup, true);
769 let mut s = String::new();
770 tree.expr.to_str(&mut s, 0);
771 assert_eq!(s, "(cd)");
772 }
773
774 #[test]
775 fn keepout_with_trailing_lookahead_optimized_into_single_group() {
776 // \K and trailing positive lookahead should be merged into one capture group,
777 // not two separate group-0 wrappers.
778 let mut tree = Expr::parse_tree(r#"ab\Kcd(?=e)"#).unwrap();
779 let requires_capture_group_fixup = optimize(&mut tree);
780 assert_eq!(requires_capture_group_fixup, true);
781 let mut s = String::new();
782 tree.expr.to_str(&mut s, 0);
783 assert_eq!(s, "ab(cd)e");
784 }
785
786 #[test]
787 fn keepout_left_alone_when_self_recursive() {
788 let tree = Expr::parse_tree(r"ab?\g<0>?\Kc").unwrap();
789 let mut optimized_tree = tree.clone();
790 let requires_capture_group_fixup = optimize(&mut optimized_tree);
791 assert_eq!(requires_capture_group_fixup, false);
792 assert_eq!(&optimized_tree.expr, &tree.expr);
793 }
794
795 #[test]
796 fn keepout_inside_group_left_alone() {
797 // \K inside a capturing group (not the root concat) should not be optimized
798 let tree = Expr::parse_tree(r"c(a\Kb)d").unwrap();
799 let mut optimized_tree = tree.clone();
800 let requires_capture_group_fixup = optimize(&mut optimized_tree);
801 assert_eq!(requires_capture_group_fixup, false);
802 assert_eq!(&optimized_tree.expr, &tree.expr);
803 }
804
805 #[test]
806 fn keepout_with_prefix_capture_group_left_alone() {
807 // When there's a capture group before \K, applying the optimization would make
808 // that group become the first group (group 1) instead of our new wrapper, so
809 // we must leave the pattern unchanged.
810 let tree = Expr::parse_tree(r"(\w+)\K\s*(\w+)").unwrap();
811 let mut optimized_tree = tree.clone();
812 let requires_capture_group_fixup = optimize(&mut optimized_tree);
813 assert_eq!(requires_capture_group_fixup, false);
814 assert_eq!(&optimized_tree.expr, &tree.expr);
815 }
816
817 #[test]
818 fn nested_plus_plus_simplified() {
819 assert_eq!(optimized_pattern(r"(x+){1,}"), "(x+)");
820 }
821
822 #[test]
823 fn nested_star_plus_simplified() {
824 assert_eq!(optimized_pattern(r"(x*){1,}"), "(x*)");
825 }
826
827 #[test]
828 fn nested_optional_plus_simplified() {
829 assert_eq!(optimized_pattern(r"(x?){1,}"), "(x*)");
830 }
831
832 #[test]
833 fn nested_optional_optional_not_simplified() {
834 // (x?)? — outer is Optional (lo=0), so the capture group can be
835 // skipped entirely (→ None). Simplifying to (x?) would always enter
836 // the group (→ Some("")), changing capture semantics.
837 assert_eq!(optimized_pattern(r"(x?){0,1}"), "(x?)?");
838 }
839
840 #[test]
841 fn nested_optional_star_not_simplified() {
842 // Outer (x*){?} has lo=0, so the capture group can be
843 // skipped (→ None). Simplifying would always enter the group.
844 assert_eq!(optimized_pattern(r"(x*){0,1}"), "(x*)?");
845 }
846
847 #[test]
848 fn nested_repeats_in_children_simplified() {
849 // (x+){1,} is simplified (outer lo=1, group always participates).
850 // (y*){0,} has outer lo=0, so the group can be skipped → None.
851 // With no backreferences and a self-absorbing group content (y*),
852 // the outer {0,} (*) is downgraded to ? since (y*)* = (y*)? = y*.
853 assert_eq!(optimized_pattern(r"(x+){1,}(y*){0,}"), "(x+)(y*)?");
854 }
855
856 #[test]
857 fn capture_group_preserved_when_nested_repeat_simplified() {
858 assert_eq!(optimized_pattern(r"(x+){1,}"), "(x+)");
859 }
860
861 #[test]
862 fn non_greedy_nested_repeats_left_alone() {
863 assert_eq!(optimized_pattern(r"(x+?){1,}"), "(x+?)+");
864 assert_eq!(optimized_pattern(r"(x+){0,1}?"), "(x+)??");
865 }
866
867 #[test]
868 fn non_capturing_group_nested_repeats_still_simplified() {
869 // Non-capturing groups are transparent (unwrapped by the parser), so
870 // they hit the bare-Repeat branch which has no outer_lo guard.
871 // These are safe because there is no capture group to preserve.
872 assert_eq!(optimized_pattern(r"(?:x+){1,}"), "x+");
873 assert_eq!(optimized_pattern(r"(?:x*){0,}"), "x*");
874 assert_eq!(optimized_pattern(r"(?:x+)+"), "x+");
875 assert_eq!(optimized_pattern(r"(?:x*)*"), "x*");
876 assert_eq!(optimized_pattern(r"(?:x*)+"), "x*");
877 assert_eq!(optimized_pattern(r"(?:x+)*"), "x*");
878 }
879
880 #[test]
881 fn bounded_quantifier_left_alone() {
882 let max = usize::MAX;
883 assert_eq!(
884 super::can_simplify(1, max, true, 1, max, true),
885 Some(super::QuantifierKind::OneOrMore)
886 );
887 assert_eq!(super::can_simplify(2, max, true, 1, max, true), None);
888 }
889
890 #[test]
891 fn nested_repeat_does_not_affect_capture_group_fixup_return() {
892 let mut tree = Expr::parse_tree(r"(x+){1,}").unwrap();
893 let requires_capture_group_fixup = optimize(&mut tree);
894 assert_eq!(requires_capture_group_fixup, false);
895 assert_eq!(optimized_pattern(r"(x+){1,}"), "(x+)");
896 }
897
898 #[test]
899 fn nested_repeats_from_oniguruma_adjacent_quantifiers_not_simplified() {
900 // (x+){1,}{0,} — the outer {0,} has lo=0 so the capture group can be
901 // skipped (→ None). Simplifying to (x*) would always enter the group.
902 // With no backreferences, the trailing * is downgraded to ? since
903 // (x+)* and (x+)? are equivalent (both match zero or more x) and
904 // (x+)? is more efficient for the VM (single backtrack point).
905 assert_eq!(
906 optimized_pattern_with_flags(r"(x+){1,}{0,}", oniguruma_flags()),
907 "(x+)?"
908 );
909 }
910
911 #[test]
912 fn backref_prevents_star_to_optional_downgrade() {
913 // When there's a backreference, the * → ? downgrade must NOT happen
914 // because the group participation count is observable via \1.
915 let mut tree = Expr::parse_tree_with_flags(r"(x+){1,}{0,}\1", oniguruma_flags()).unwrap();
916 optimize(&mut tree);
917 // The inner {1,} is simplified to (x+), but the outer {0,} stays
918 // as ZeroOrMore (not downgraded to Optional) because has_backrefs is true.
919 assert_eq!(
920 tree.expr,
921 Expr::Concat(vec![
922 Expr::Repeat {
923 child: Box::new(Expr::Group(Arc::new(Expr::Repeat {
924 child: Box::new(make_literal("x")),
925 lo: 1,
926 hi: usize::MAX,
927 greedy: true,
928 }))),
929 lo: 0,
930 hi: usize::MAX,
931 greedy: true,
932 },
933 Expr::Backref {
934 group: 1,
935 casei: false,
936 },
937 ])
938 );
939 }
940
941 #[test]
942 fn non_self_absorbing_group_not_downgraded() {
943 // (x?){0,} — inner is Optional (lo=0, hi=1), not self-absorbing.
944 // Even without backreferences, * is NOT downgraded to ? because
945 // (x?)* = x* ≠ (x?)? = x? (they match different strings).
946 assert_eq!(optimized_pattern(r"(x?){0,}"), "(x?)*");
947 }
948
949 #[test]
950 fn ambiguous_concat_repeats_simplified_basic() {
951 assert_eq!(optimized_pattern(r"\s*\w?\s*"), r"\s*(?:\w{1}\s*)?");
952 }
953
954 #[test]
955 fn ambiguous_concat_repeats_simplified_with_bounded_middle() {
956 // left=\w* (lo=0) < right=\w+ (lo=1): right is mandatory suffix, left+middle become optional prefix
957 assert_eq!(
958 optimized_pattern(r"foo\w*\s{0,5}\w+"),
959 r"foo(?:\w*\s{1,5})?\w+"
960 );
961 }
962
963 #[test]
964 fn ambiguous_concat_repeats_simplified_with_nongreedy_middle() {
965 // left=\w* (lo=0) < right=\w+ (lo=1): same as above with non-greedy middle
966 assert_eq!(
967 optimized_pattern(r"foo\w*\s{0,5}?\w+"),
968 r"foo(?:\w*\s{1,5}?)?\w+"
969 );
970 }
971
972 #[test]
973 fn ambiguous_concat_repeats_simplified_with_plus_and_star() {
974 // left=\s+ (lo=1) >= right=\s* (lo=0): left is mandatory prefix, right+middle become optional suffix
975 assert_eq!(optimized_pattern(r"\s+\w{0,1}\s*"), r"\s+(?:\w{1}\s*)?");
976 assert_eq!(optimized_pattern(r"^\s+\w{0,1}\s*$"), r"^\s+(?:\w{1}\s*)?$");
977 }
978
979 #[test]
980 fn ambiguous_concat_repeats_inside_plus_simplified() {
981 assert_eq!(optimized_pattern(r"(?:\s*\w?\s*)+"), r"\s*(?:\w{1}\s*)*");
982 }
983
984 #[test]
985 fn ambiguous_concat_repeats_inside_star_simplified() {
986 assert_eq!(
987 optimized_pattern(r"(?:\s*\w?\s*)*"),
988 r"(?:\s*(?:\w{1}\s*)*)?"
989 );
990 }
991
992 #[test]
993 fn ambiguous_concat_repeats_star_optional_plus_uses_suffix() {
994 // left=\w* (lo=0) < right=\w+ (lo=1): the more restrictive side becomes the mandatory
995 // suffix to avoid making the rewritten expression more permissive than the original.
996 // \w*\.?\w+ cannot match an empty string (requires at least one word char from \w+),
997 // so the rewritten form must also require at least one word char.
998 assert_eq!(optimized_pattern(r"\w*\.?\w+"), r"(?:\w*\.{1})?\w+");
999 }
1000
1001 #[test]
1002 fn ambiguous_concat_repeats_plus_optional_star_uses_prefix() {
1003 // left=\w+ (lo=1) >= right=\w* (lo=0): left is the mandatory prefix
1004 assert_eq!(optimized_pattern(r"\w+\.?\w*"), r"\w+(?:\.{1}\w*)?");
1005 }
1006 }