fancy_regex/seek.rs
1// Copyright 2026 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//! Seek pre-filter: build a simplified approximation of a pattern used to
22//! skip to plausible match positions before handing off to the backtracking VM.
23//!
24//! Every quantifier in the approximation is emitted lazily because we only care about
25//! the start and being lazy doesn't change the result.
26
27use alloc::format;
28use alloc::string::String;
29use alloc::vec::Vec;
30
31#[cfg(not(feature = "std"))]
32use alloc::collections::BTreeMap as Map;
33#[cfg(feature = "std")]
34use std::collections::HashMap as Map;
35
36use crate::analyze::Info;
37use crate::compile::MAX_SUBROUTINE_RECURSION_DEPTH;
38use crate::{write_quantifier, Absent, Assertion, Expr};
39
40/// Returns `true` if the expression tree contains a `StartText` or `EndText` assertion anywhere.
41///
42/// This is used to decide whether it is safe to inline a group body when approximating a backref:
43/// text-anchor assertions in an inlined body would be evaluated at the wrong string position and
44/// could cause false negatives (missing valid match positions).
45pub(crate) fn expr_contains_positional_anchor(expr: &Expr) -> bool {
46 match expr {
47 // StartText (^), EndText ($), StartLine ((?m)^), EndLine ((?m)$) are positional anchors
48 // that depend on absolute position in the string. When a group containing such anchors
49 // is inlined for a backref approximation, the anchors would be evaluated at the wrong
50 // position (the backref position rather than the original capture position), potentially
51 // producing false negatives.
52 Expr::Assertion(
53 Assertion::StartText
54 | Assertion::EndText
55 | Assertion::EndTextIgnoreTrailingNewlines { .. }
56 | Assertion::StartLine { .. }
57 | Assertion::StartLineOniguruma { .. }
58 | Assertion::EndLine { .. },
59 ) => true,
60 _ => expr.children_iter().any(expr_contains_positional_anchor),
61 }
62}
63
64/// Cap on the seek-pattern buffer length. Inlining a backref/subroutine
65/// substitutes the referenced group's body, and when that body transitively
66/// references the same group (e.g. `(\s+((\3|\4|\5)))?` where `\4`/`\5` point
67/// at ancestors of the backref) the substitution branches at every level and,
68/// bounded only by the recursion depth, expands the buffer exponentially — so
69/// a short pattern can produce a multi-megabyte seek string. Once the buffer
70/// is already this large, further inlining stops and a permissive placeholder
71/// is emitted instead: the seek pattern only narrows candidate start positions
72/// and never decides matches, so a less-selective approximation stays correct.
73pub(crate) const MAX_SEEK_PATTERN_LEN: usize = 4096;
74
75/// Emit a lazy permissive size placeholder — `(?s:.)*?`, `(?s:.)+?`, or `(?s:.){N,}?` — into `buf`.
76///
77/// Used when a hard node cannot be represented in the seek pattern but has a known minimum
78/// size. The placeholder is an over-approximation that avoids false negatives: it admits any
79/// run of characters of at least `min_size` length.
80pub(crate) fn emit_min_size_placeholder(buf: &mut String, min_size: usize, precedence: u8) {
81 if precedence > 2 {
82 buf.push_str("(?:");
83 }
84 buf.push_str("(?s:.)");
85 write_quantifier(buf, min_size, usize::MAX, false);
86 if precedence > 2 {
87 buf.push(')');
88 }
89}
90
91/// Write the seek-pattern approximation for `info` into `buf`.
92///
93/// Easy subtrees without capture groups are serialised verbatim via [`Expr::to_str`],
94/// unless they contain assertions that must be stripped.
95/// Hard nodes are handled as follows:
96/// - `Backref` / `SubroutineCall`: inline the referenced group's body (up to
97/// `MAX_SUBROUTINE_RECURSION_DEPTH`). For backrefs, positional anchors (`^`, `$`, `\Z`)
98/// are dropped from the inlined body because backreferences only capture text, not
99/// positions. If inlining is not possible, a permissive `(?s:.){min_size,}` placeholder
100/// is emitted instead of silently dropping, to maintain correctness.
101/// - `LookAround`, `KeepOut`, `ContinueFromPreviousMatchEnd`, `BacktrackingControlVerb`,
102/// `BackrefExistsCondition`, `Absent`: dropped (emit nothing — safe over-approximation,
103/// their `min_size` is 0).
104/// - `AtomicGroup`: keep the contents, discard the atomicity wrapper.
105/// - `Group`: keep the contents, discard the capture group wrapper.
106/// - `Conditional`: emit the union of the true and false branches.
107/// - `GeneralNewline`: replaced with an explicit alternation.
108/// - `Assertion`: emitted (unless they are part of a backref as mentioned above, or the
109/// assertion is a word boundary and drop_word_boundaries is set - more on that below.)
110/// (or replaced with an empty atom when a quantifier still needs one).
111///
112/// `drop_word_boundaries` must be set when the seek pattern feeds a reverse DFA searching
113/// a Unicode haystack — regex-automata cannot evaluate word boundaries in reverse on
114/// Unicode input, so emitting them would produce an invalid pattern. It is left `false`
115/// for forward seeks, where word boundaries are safe and useful. See [`SeekOptions`].
116pub(crate) fn build_seek_pattern<'a>(
117 info: &Info<'a>,
118 group_info_map: &Map<usize, &'a Info<'a>>,
119 depth: usize,
120 buf: &mut String,
121 precedence: u8,
122 drop_word_boundaries: bool,
123) {
124 let mut inlined_groups = Vec::new();
125 build_seek_pattern_impl(
126 info,
127 group_info_map,
128 depth,
129 buf,
130 precedence,
131 &mut inlined_groups,
132 SeekOptions {
133 drop_positional_anchors: false,
134 drop_word_boundaries,
135 },
136 );
137}
138
139pub(crate) fn build_seek_pattern_impl<'a>(
140 info: &Info<'a>,
141 group_info_map: &Map<usize, &'a Info<'a>>,
142 depth: usize,
143 buf: &mut String,
144 precedence: u8,
145 inlined_groups: &mut Vec<usize>,
146 opts: SeekOptions,
147) {
148 // Drop positional anchors at this node when requested (used when inlining for a backref).
149 if opts.drop_positional_anchors {
150 if let Expr::Assertion(
151 Assertion::StartText
152 | Assertion::EndText
153 | Assertion::StartLine { .. }
154 | Assertion::StartLineOniguruma { .. }
155 | Assertion::EndLine { .. },
156 ) = info.expr
157 {
158 return;
159 }
160 // \Z is an odd one out, although it is a zero-width assertion, for the purposes of seeking
161 // it still needs to consume the newlines
162 if let Expr::Assertion(Assertion::EndTextIgnoreTrailingNewlines { crlf }) = info.expr {
163 if *crlf {
164 buf.push_str(r"[\r\n]*");
165 } else {
166 buf.push_str(r"\n*");
167 }
168 return;
169 }
170 }
171
172 let has_capture_groups = info.start_group() != info.end_group();
173 if !info.hard && !has_capture_groups {
174 // An easy subtree without capture groups can be serialised verbatim unless it
175 // contains assertions that must be stripped while inlining: word boundaries
176 // (when `drop_word_boundaries` is set) or positional anchors (when
177 // `drop_positional_anchors` is set). Each descendant scan is short-circuited by
178 // its own option flag, so we only pay the cost when stripping is actually
179 // requested — i.e. when word boundaries are not being dropped, the word-boundary
180 // scan is skipped entirely.
181 let needs_assertion_strip = (opts.drop_word_boundaries
182 && info.expr.has_descendant_or_self(|expr| {
183 matches!(
184 expr,
185 Expr::Assertion(
186 Assertion::WordBoundary
187 | Assertion::NotWordBoundary
188 | Assertion::LeftWordBoundary
189 | Assertion::RightWordBoundary
190 | Assertion::LeftWordHalfBoundary
191 | Assertion::RightWordHalfBoundary
192 )
193 )
194 }))
195 || (opts.drop_positional_anchors && expr_contains_positional_anchor(info.expr));
196 // Use to_str directly when the subtree contains no assertions that need dropping.
197 if !needs_assertion_strip {
198 info.expr.to_str(buf, precedence);
199 return;
200 }
201 // The easy subtree contains assertions that need to be stripped.
202 // Fall through to the match below, which recurses via build_seek_pattern_impl.
203 }
204
205 match info.expr {
206 Expr::Empty | Expr::DefineGroup { .. } => {}
207 Expr::Assertion(assertion) => {
208 // Note: easy positional assertions (StartText, EndText, StartLine, EndLine) are
209 // handled by the to_str early return above (drop_positional_anchors=false) or by
210 // the early drop at the top of this function (drop_positional_anchors=true).
211 // Reverse seek patterns also reach this arm for easy assertions.
212 match assertion {
213 Assertion::EndTextIgnoreTrailingNewlines { crlf: false } => buf.push_str(r"\n*$"),
214 Assertion::EndTextIgnoreTrailingNewlines { crlf: true } => {
215 buf.push_str(r"[\r\n]*$")
216 }
217 Assertion::WordBoundary
218 | Assertion::NotWordBoundary
219 | Assertion::LeftWordBoundary
220 | Assertion::RightWordBoundary
221 | Assertion::LeftWordHalfBoundary
222 | Assertion::RightWordHalfBoundary => {
223 // The VM verifies boundaries omitted from a reverse seek DFA,
224 // which would otherwise quit on non-ASCII input.
225 if !opts.drop_word_boundaries {
226 info.expr.to_str(buf, precedence);
227 } else if precedence > 2 {
228 // A quantifier still needs an atom when its boundary is omitted.
229 buf.push_str("(?:)");
230 }
231 }
232 // Easy positional anchors — handled by early return / early drop above.
233 // They can only reach here when drop_positional_anchors=false and the subtree
234 // is easy (handled by to_str) but the Group/Concat parent fell through to match.
235 // Emit them faithfully.
236 Assertion::StartText
237 | Assertion::EndText
238 | Assertion::StartLine { .. }
239 | Assertion::StartLineOniguruma { .. }
240 | Assertion::EndLine { .. } => info.expr.to_str(buf, precedence),
241 }
242 }
243 Expr::Concat(_) => {
244 if precedence > 1 {
245 buf.push_str("(?:");
246 }
247 for child in &info.children {
248 build_seek_pattern_impl(child, group_info_map, depth, buf, 2, inlined_groups, opts);
249 }
250 if precedence > 1 {
251 buf.push(')');
252 }
253 }
254 Expr::Alt(_) => {
255 if precedence > 0 {
256 buf.push_str("(?:");
257 }
258 let mut first = true;
259 for child in &info.children {
260 if !first {
261 buf.push('|');
262 }
263 build_seek_pattern_impl(child, group_info_map, depth, buf, 1, inlined_groups, opts);
264 first = false;
265 }
266 if precedence > 0 {
267 buf.push(')');
268 }
269 }
270 Expr::Group(_) => {
271 // Drop the capture group wrapper; keep the contents.
272 if !info.children.is_empty() {
273 build_seek_pattern_impl(
274 &info.children[0],
275 group_info_map,
276 depth,
277 buf,
278 precedence,
279 inlined_groups,
280 opts,
281 );
282 }
283 }
284 Expr::Repeat { lo, hi, .. } => {
285 if precedence > 2 {
286 buf.push_str("(?:");
287 }
288 if !info.children.is_empty() {
289 build_seek_pattern_impl(
290 &info.children[0],
291 group_info_map,
292 depth,
293 buf,
294 3,
295 inlined_groups,
296 opts,
297 );
298 }
299 write_quantifier(buf, *lo, *hi, false);
300 if precedence > 2 {
301 buf.push(')');
302 }
303 }
304 Expr::Backref { group, casei }
305 | Expr::BackrefWithRelativeRecursionLevel { group, casei, .. } => {
306 // Inline the body of the referenced capture group, wrapping with (?i:...) when
307 // the backref is case-insensitive so the approximation remains correct.
308 //
309 // Positional anchors are dropped from the inlined body: a backref matches the
310 // captured text, not a position, so anchors from the group definition do not hold
311 // at the backref's position.
312 //
313 // For BackrefWithRelativeRecursionLevel, the relative_level is ignored here:
314 // for seeking purposes, the group body is the same regardless of recursion level.
315 //
316 // If inlining is not possible (depth limit, group not in map, or recursive cycle), emit a permissive
317 // placeholder so that no match positions are incorrectly skipped.
318 if depth < MAX_SUBROUTINE_RECURSION_DEPTH && buf.len() < MAX_SEEK_PATTERN_LEN {
319 if let Some(group_info) = group_info_map.get(group) {
320 if inlined_groups.contains(group) {
321 emit_min_size_placeholder(buf, group_info.min_size, precedence);
322 return;
323 }
324 if !group_info.children.is_empty() {
325 let child = &group_info.children[0];
326 inlined_groups.push(*group);
327 if *casei {
328 let mut inner = String::new();
329 build_seek_pattern_impl(
330 child,
331 group_info_map,
332 depth + 1,
333 &mut inner,
334 // Precedence 0 (alternation) so content inside (?i:...) is unambiguous.
335 0,
336 inlined_groups,
337 SeekOptions {
338 drop_positional_anchors: true,
339 drop_word_boundaries: opts.drop_word_boundaries,
340 },
341 );
342 inlined_groups.pop();
343 if !inner.is_empty() {
344 buf.push_str("(?i:");
345 buf.push_str(&inner);
346 buf.push(')');
347 }
348 } else {
349 build_seek_pattern_impl(
350 child,
351 group_info_map,
352 depth + 1,
353 buf,
354 precedence,
355 inlined_groups,
356 SeekOptions {
357 drop_positional_anchors: true,
358 drop_word_boundaries: opts.drop_word_boundaries,
359 },
360 );
361 inlined_groups.pop();
362 }
363 return;
364 }
365 // Empty group (no children): min_size=0, nothing to emit.
366 return;
367 }
368 }
369 // Could not inline (depth limit or group not found): emit a permissive placeholder
370 // so we don't falsely skip positions where the backref's target could have matched.
371 emit_min_size_placeholder(buf, info.min_size, precedence);
372 }
373 Expr::SubroutineCall(target_group) => {
374 // Inline the body of the target group once, honouring the recursion depth limit.
375 if depth < MAX_SUBROUTINE_RECURSION_DEPTH && buf.len() < MAX_SEEK_PATTERN_LEN {
376 if let Some(group_info) = group_info_map.get(target_group) {
377 if inlined_groups.contains(target_group) {
378 let placeholder_min = usize::from(group_info.min_size > 0);
379 emit_min_size_placeholder(buf, placeholder_min, precedence);
380 return;
381 }
382
383 if !group_info.children.is_empty() {
384 inlined_groups.push(*target_group);
385 build_seek_pattern_impl(
386 &group_info.children[0],
387 group_info_map,
388 depth + 1,
389 buf,
390 precedence,
391 inlined_groups,
392 opts,
393 );
394 inlined_groups.pop();
395 return;
396 }
397 return;
398 }
399 }
400 emit_min_size_placeholder(buf, info.min_size, precedence);
401 }
402 // LookAround is zero-width — drop it.
403 Expr::LookAround(_, _) => {}
404 Expr::AtomicGroup(_) => {
405 // Keep the contents; atomicity is invisible to the seek approximation.
406 if !info.children.is_empty() {
407 build_seek_pattern_impl(
408 &info.children[0],
409 group_info_map,
410 depth,
411 buf,
412 precedence,
413 inlined_groups,
414 opts,
415 );
416 }
417 }
418 Expr::GeneralNewline { unicode } => {
419 // Replace \R with an explicit alternation accepted by regex-automata.
420 if *unicode {
421 buf.push_str(r"(?:\r\n|[\n\x0B\x0C\r\x85\u{2028}\u{2029}])");
422 } else {
423 buf.push_str(r"(?:\r\n|[\n\x0B\x0C\r])");
424 }
425 }
426 Expr::Conditional { .. } => {
427 // Emit the union of (condition + true_branch) and (false_branch).
428 //
429 // Including the condition prefix in the true alternative ensures that consuming
430 // conditions (e.g. `(?(a)b|c)` where `a` is matched and consumed) are
431 // over-approximated correctly. For zero-width conditions (e.g. backref-exists
432 // checks) the condition emits nothing and the result degenerates to
433 // `true_branch | false_branch`, preserving the original behaviour.
434 let mut cond_pat = String::new();
435 let mut true_pat = String::new();
436 let mut false_pat = String::new();
437 if !info.children.is_empty() {
438 build_seek_pattern_impl(
439 &info.children[0],
440 group_info_map,
441 depth,
442 &mut cond_pat,
443 2,
444 inlined_groups,
445 opts,
446 );
447 }
448 if info.children.len() >= 2 {
449 build_seek_pattern_impl(
450 &info.children[1],
451 group_info_map,
452 depth,
453 &mut true_pat,
454 2,
455 inlined_groups,
456 opts,
457 );
458 }
459 if info.children.len() >= 3 {
460 build_seek_pattern_impl(
461 &info.children[2],
462 group_info_map,
463 depth,
464 &mut false_pat,
465 1,
466 inlined_groups,
467 opts,
468 );
469 }
470 // Build the "condition then true-branch" alternative.
471 let cond_true = if cond_pat.is_empty() {
472 true_pat.clone()
473 } else if true_pat.is_empty() {
474 cond_pat.clone()
475 } else {
476 format!("(?:{}{})", cond_pat, true_pat)
477 };
478 if cond_true.is_empty() && false_pat.is_empty() {
479 if precedence > 2 {
480 buf.push_str("(?:)");
481 }
482 return;
483 }
484 // An empty branch still matches the empty string. Keep it in the union
485 // so the seek pattern does not require the other branch to match.
486 if precedence > 0 {
487 buf.push_str("(?:");
488 }
489 buf.push_str(&cond_true);
490 buf.push('|');
491 buf.push_str(&false_pat);
492 if precedence > 0 {
493 buf.push(')');
494 }
495 }
496 // Absent repeater `(?~expr)` matches any content not containing `expr`.
497 // Approximate with `(?s:.*?)` (any characters, including newline) since the repeater
498 // can consume an arbitrary number of characters.
499 Expr::Absent(Absent::Repeater(_)) => buf.push_str("(?s:.*?)"),
500 // Absent expression `(?~|absent|exp)` matches `exp` subject to the absent constraint.
501 // Approximate by seeking only for `exp`, dropping the constraint — this is a safe
502 // over-approximation since any position where `exp` matches (ignoring the constraint)
503 // is a superset of positions where the full expression matches.
504 Expr::Absent(crate::Absent::Expression { .. }) => {
505 if info.children.len() >= 2 {
506 build_seek_pattern_impl(
507 &info.children[1],
508 group_info_map,
509 depth,
510 buf,
511 precedence,
512 inlined_groups,
513 opts,
514 );
515 }
516 }
517 // Zero-width / control nodes — drop them (all have min_size = 0).
518 Expr::KeepOut
519 | Expr::ContinueFromPreviousMatchEnd
520 | Expr::BacktrackingControlVerb(_)
521 | Expr::BackrefExistsCondition { .. }
522 | Expr::Absent(_) => {}
523 // Approximate since we don't want to have to deal with ascii vs unicode handling here
524 Expr::LiteralBytes { bytes } => buf.push_str(&format!("(?s:.{{0,{}}}?)", bytes.len())),
525 // Easy leaf nodes (Literal, Any, Delegate) are always handled by the easy no-captures
526 // early return above and never reach here. Listed explicitly so that adding a new
527 // Expr variant produces a compile error until the seek-pattern case is handled.
528 Expr::Literal { .. } | Expr::Any { .. } | Expr::Delegate { .. } => {
529 info.expr.to_str(buf, precedence)
530 }
531 // These variants cause a compile error during analysis and are therefore unreachable
532 // after a successful `analyze()` call.
533 Expr::AstNode(..) => {
534 unreachable!("unexpected expr variant after analysis")
535 }
536 }
537}
538
539/// Options controlling which assertions are dropped when building a seek pattern.
540///
541/// Both flags relate to inlining a group body (for a backref or subroutine call) where the
542/// original position of the match is no longer meaningful: positional anchors (`^`, `$`) and
543/// word-boundary assertions must be dropped or approximated to stay correct.
544#[derive(Clone, Copy, Default)]
545pub(crate) struct SeekOptions {
546 /// Drop positional anchors (`^`, `$`, `\Z`) from the inlined body.
547 pub(crate) drop_positional_anchors: bool,
548 /// Drop word-boundary assertions (`\b`, `\B`, half boundaries) from the inlined body.
549 pub(crate) drop_word_boundaries: bool,
550}
551
552/// Returns `true` if `pattern` contains at least one character that provides useful filtering
553/// (i.e. a literal character, character class, or anchor rather than just wildcards/quantifiers).
554///
555/// This is a conservative approximation: any pattern containing `[`, `\`, `^`, `$`, or an
556/// alphanumeric character is considered useful. The primary goal is to reject fully
557/// unconstrained patterns such as `.*`.
558pub fn seek_pattern_is_useful(pattern: &str) -> bool {
559 pattern
560 .bytes()
561 .any(|b| matches!(b, b'[' | b'\\' | b'^' | b'$' | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'))
562}
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567 use crate::analyze::{analyze, AnalyzeContext};
568 use crate::compile::populate_group_info_map;
569 use crate::optimize::{optimize, OptimizeOptions};
570 use crate::ExprTree;
571 use crate::Regex;
572 use alloc::string::ToString;
573
574 /// Build the seek pattern for a regex string and return it.
575 fn get_seek_pattern(re: &str) -> String {
576 let mut tree = Expr::parse_tree(re).unwrap();
577 get_seek_pattern_for_tree(&mut tree)
578 }
579
580 /// Build the seek pattern for a regex string parsed with the given flags.
581 fn get_seek_pattern_with_flags(re: &str, flags: u32) -> String {
582 let mut tree = Expr::parse_tree_with_flags(re, flags).unwrap();
583 get_seek_pattern_for_tree(&mut tree)
584 }
585
586 // Build the seek pattern for the given ExprTree
587 fn get_seek_pattern_for_tree(tree: &mut ExprTree) -> String {
588 let requires_capture_group_fixup = optimize(tree, OptimizeOptions::default());
589
590 let info = analyze(
591 &tree,
592 AnalyzeContext {
593 explicit_capture_group_0: requires_capture_group_fixup,
594 ..AnalyzeContext::default()
595 },
596 )
597 .unwrap();
598
599 let mut group_info_map = Map::new();
600 populate_group_info_map(&mut group_info_map, &info);
601 let mut buf = String::new();
602 build_seek_pattern(&info, &group_info_map, 0, &mut buf, 0, false);
603 buf
604 }
605
606 #[test]
607 fn seek_pattern_conditionals_preserve_empty_alternatives() {
608 for (pattern, haystack) in [
609 (r"(a)?b(?(1)c)", "b"),
610 (r"(a)?b(?(1)c|)", "b"),
611 (r"(a)?b(?(1)|c)", "ab"),
612 ] {
613 let seek_pattern = get_seek_pattern(pattern);
614 assert!(
615 regex::Regex::new(&seek_pattern).unwrap().is_match(haystack),
616 "{pattern:?} produced {seek_pattern:?}, excluding {haystack:?}"
617 );
618 }
619 }
620
621 #[test]
622 fn seek_pattern_backref_no_anchor() {
623 // Simple backref with no positional anchors: group body is inlined verbatim.
624 // The `(?:...)` wrapping comes from Concat precedence handling when stripping groups.
625 assert_eq!(get_seek_pattern(r"(abc)\1"), "(?:abc)(?:abc)");
626 assert_eq!(
627 get_seek_pattern(r"(?i)(abc)\1"),
628 "(?:(?i:a)(?i:b)(?i:c))(?i:(?i:a)(?i:b)(?i:c))"
629 );
630 }
631
632 #[test]
633 fn seek_pattern_backref_with_start_anchor() {
634 // Backref to a group whose body starts with `^`: the anchor should be dropped from the
635 // inlined backref position but kept at the group definition site.
636 // `(^a)\1` — seek = `(?:^a)` (group) + `(?:a)` (backref, anchor dropped)
637 assert_eq!(get_seek_pattern(r"(^a)\1"), "(?:^a)(?:a)");
638 }
639
640 #[test]
641 fn seek_pattern_backref_with_start_anchor_variable_length() {
642 // The group has a start anchor plus a variable-length content.
643 // Anchor is dropped when inlining for the backref.
644 assert_eq!(get_seek_pattern(r"(^a+)\1"), "(?:^a+)(?:a+)");
645 }
646
647 #[test]
648 fn seek_pattern_backref_with_end_anchor() {
649 // Backref to a group ending with `$`: the anchor is dropped in the inline position.
650 assert_eq!(get_seek_pattern(r"(a$)\1"), "(?:a$)(?:a)");
651 }
652
653 #[test]
654 fn seek_pattern_backref_only_anchor() {
655 // Backref to a group that is only a positional anchor.
656 // The group emits `^` (min_size=0); the backref drops `^` and emits nothing.
657 assert_eq!(get_seek_pattern(r"(^)\1"), "^");
658 }
659
660 #[test]
661 fn seek_pattern_lookahead_dropped() {
662 // Lookahead is zero-width and is dropped; only the literal is kept.
663 assert_eq!(get_seek_pattern(r"(?=foo)bar"), "bar");
664 }
665
666 #[test]
667 fn seek_pattern_casei_literal_backref_with_anchor() {
668 // Group contains a case-insensitive literal and a start anchor.
669 // The anchor is dropped during backref inlining; the casei literal emits (?i:...).
670 assert_eq!(get_seek_pattern(r"(?i:(^a))\1"), "(?:^(?i:a))(?:(?i:a))");
671 }
672
673 #[test]
674 fn seek_pattern_easy_expr_preserved() {
675 // Easy (non-hard) expressions without capture groups are serialised verbatim via to_str.
676 assert_eq!(get_seek_pattern(r"abc"), "abc");
677 assert_eq!(get_seek_pattern(r"a|b"), "a|b");
678 assert_eq!(get_seek_pattern(r"a+b*c?"), "a+b*c?");
679 assert_eq!(get_seek_pattern(r"\ba+b*c?\b"), r"\ba+b*c?\b");
680 assert_eq!(
681 get_seek_pattern(r"\b{start-half}foo\b{end-half}"),
682 r"\b{start-half}foo\b{end-half}"
683 );
684 }
685
686 #[test]
687 fn seek_pattern_easy_expr_with_capture_group_strips_group_wrapper() {
688 // Easy expressions with capture groups drop the capture group wrappings.
689 assert_eq!(get_seek_pattern(r"(abc)"), "abc");
690 assert_eq!(
691 get_seek_pattern(r"(abc(def))(?<named>ghi)"),
692 "(?:abc(?:def))(?:ghi)"
693 );
694 }
695
696 #[test]
697 fn seek_pattern_optimized_easy_expr_strips_group_wrapper() {
698 // Optimized patterns lose the capture group wrappings
699 assert_eq!(get_seek_pattern(r"(?=abc)"), "(?:abc)");
700 assert_eq!(
701 get_seek_pattern(r"(h)(e)(l)(l)(o)\s*(?=world)"),
702 r"(?:hello\s*)(?:world)"
703 );
704 }
705
706 #[test]
707 fn seek_pattern_end_text_ignore_trailing_newlines_non_crlf() {
708 // \Z (non-CRLF mode) — approximate with `\n*$` so the seek only visits positions
709 // near end-of-text.
710 assert_eq!(get_seek_pattern(r"abc\Z"), r"abc\n*$");
711 }
712
713 #[test]
714 fn seek_pattern_end_text_ignore_trailing_newlines_crlf() {
715 // \Z in CRLF mode — approximate with `(?:\r?\n)*$`.
716 assert_eq!(get_seek_pattern(r"(?R)abc\Z"), r"abc[\r\n]*$");
717 }
718
719 #[test]
720 fn seek_pattern_end_text_ignore_trailing_newlines_only() {
721 // \Z alone (hard assertion) — just the seek pattern with no surrounding literal.
722 assert_eq!(get_seek_pattern(r"\Z"), r"\n*$");
723 }
724
725 #[test]
726 fn seek_pattern_backref_with_end_text_ignore_trailing_newlines() {
727 // Backref to a group that ends with \Z: \Z is a positional anchor and should be
728 // dropped when inlining the group body for the backref.
729 // `(a\Z)\1` — seek = `(?:a\n*$)` (group) + `(?:a\n*)` (backref, \Z anchor dropped, newline matching kept)
730 assert_eq!(get_seek_pattern(r"(a\Z)\1"), r"(?:a\n*$)(?:a\n*)");
731 }
732
733 #[test]
734 fn seek_pattern_subroutine_call_inlined() {
735 assert_eq!(
736 get_seek_pattern(r"([A-Z][a-z0-9]*)::\g<1>"),
737 r"(?:[A-Z][a-z0-9]*)::(?:[A-Z][a-z0-9]*)"
738 );
739 }
740
741 #[test]
742 fn seek_pattern_subroutine_call_inlined_and_anchors_are_preserved() {
743 assert_eq!(
744 get_seek_pattern(r"((?m:^)[A-Z][a-z0-9]*)\n\g<1>"),
745 "(?:(?m:^)[A-Z][a-z0-9]*)\\n(?:(?m:^)[A-Z][a-z0-9]*)"
746 );
747 }
748
749 #[test]
750 fn seek_pattern_self_referential_backref_is_bounded() {
751 // Inlining a backref whose target transitively references the backref's
752 // own ancestors would expand exponentially with recursion depth if we
753 // didn't have cycle detection or a length cap to cause it to fall back
754 // to a permissive placeholder instead of continuing to recurse.
755 // Together these help to keep the seek pattern small (and, therefore, compilation
756 // fast) rather than producing a multi-megabyte string which would likely not help
757 // to narrow candidate start positions much better anyway.
758 let seek = get_seek_pattern(r"(end)(\s+(function))?(\s+((\3|\4|\5)))?");
759 assert!(
760 seek.len() <= MAX_SEEK_PATTERN_LEN,
761 "seek pattern should stay bounded, got {} bytes",
762 seek.len()
763 );
764 // Compiling it must succeed and stay well-formed.
765 Regex::new(r"(end)(\s+(function))?(\s+((\3|\4|\5)))?").unwrap();
766 }
767
768 #[test]
769 fn seek_recursive_subroutine_with_empty_base_preserves_leftmost_match() {
770 let pattern = r"(?<g>(?:a\g<g>)?)b";
771 let haystack = "aab";
772
773 let mut options_no_seek = crate::RegexOptionsBuilder::new();
774 let expected = options_no_seek
775 .seek(false)
776 .build(pattern.to_string())
777 .unwrap()
778 .find(haystack)
779 .unwrap();
780
781 let mut options = crate::RegexOptionsBuilder::new();
782 options.seek(true);
783 let actual = options
784 .build(pattern.to_string())
785 .unwrap()
786 .find(haystack)
787 .unwrap();
788
789 assert_eq!(
790 expected.map(|m| (m.start(), m.end())),
791 actual.map(|m| (m.start(), m.end()))
792 );
793 assert_eq!(expected.unwrap().start, 0);
794 }
795
796 #[test]
797 fn seek_pattern_recursive_subroutine_is_inlined_once() {
798 let pattern = r"(?<tuple>\((?:[^()]|\g<tuple>)+\))\s*(?!=[=>])(?==)";
799 let seek = get_seek_pattern(pattern);
800 assert_eq!(
801 seek,
802 r#"(?:(?:\((?:[^()]|\((?:[^()]|(?s:.)+?)+?\))+?\))\s*)="#
803 );
804 }
805
806 #[test]
807 fn seek_pattern_literal_bytes() {
808 // In Unicode mode \xFF parses to a `Literal` (handled by the easy to_str path).
809 assert_eq!(get_seek_pattern(r"\xFF"), r"ÿ");
810 }
811
812 #[test]
813 fn seek_pattern_literal_bytes_ascii_mode() {
814 // In non-Unicode mode \xFF parses to `LiteralBytes`, which is hard and so
815 // reaches the seek-pattern arm that interpolates the byte length.
816 assert_eq!(get_seek_pattern_with_flags(r"\xFF", 0), r"(?s:.{0,1}?)");
817 // Two separate byte escapes are a Concat of two LiteralBytes nodes.
818 assert_eq!(
819 get_seek_pattern_with_flags(r"\xFF\xFF", 0),
820 r"(?s:.{0,1}?)(?s:.{0,1}?)"
821 );
822 }
823}