Debian Codegraph @

third_party/rust/regex-automata/src/meta/strategy.rs

raw
1 use core::{
2 fmt::Debug,
3 panic::{RefUnwindSafe, UnwindSafe},
4 };
5
6 use alloc::sync::Arc;
7
8 use regex_syntax::hir::{literal, Hir};
9
10 use crate::{
11 meta::{
12 error::{BuildError, RetryError, RetryFailError, RetryQuadraticError},
13 regex::{Cache, RegexInfo},
14 reverse_inner, wrappers,
15 },
16 nfa::thompson::{self, WhichCaptures, NFA},
17 util::{
18 captures::{Captures, GroupInfo},
19 look::LookMatcher,
20 prefilter::{self, Prefilter, PrefilterI},
21 primitives::{NonMaxUsize, PatternID},
22 search::{Anchored, HalfMatch, Input, Match, MatchKind, PatternSet},
23 },
24 };
25
26 /// A trait that represents a single meta strategy. Its main utility is in
27 /// providing a way to do dynamic dispatch over a few choices.
28 ///
29 /// Why dynamic dispatch? I actually don't have a super compelling reason, and
30 /// importantly, I have not benchmarked it with the main alternative: an enum.
31 /// I went with dynamic dispatch initially because the regex engine search code
32 /// really can't be inlined into caller code in most cases because it's just
33 /// too big. In other words, it is already expected that every regex search
34 /// will entail at least the cost of a function call.
35 ///
36 /// I do wonder whether using enums would result in better codegen overall
37 /// though. It's a worthwhile experiment to try. Probably the most interesting
38 /// benchmark to run in such a case would be one with a high match count. That
39 /// is, a benchmark to test the overall latency of a search call.
40 pub(super) trait Strategy:
41 Debug + Send + Sync + RefUnwindSafe + UnwindSafe + 'static
42 {
43 fn group_info(&self) -> &GroupInfo;
44
45 fn create_cache(&self) -> Cache;
46
47 fn reset_cache(&self, cache: &mut Cache);
48
49 fn is_accelerated(&self) -> bool;
50
51 fn memory_usage(&self) -> usize;
52
53 fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match>;
54
55 fn search_half(
56 &self,
57 cache: &mut Cache,
58 input: &Input<'_>,
59 ) -> Option<HalfMatch>;
60
61 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool;
62
63 fn search_slots(
64 &self,
65 cache: &mut Cache,
66 input: &Input<'_>,
67 slots: &mut [Option<NonMaxUsize>],
68 ) -> Option<PatternID>;
69
70 fn which_overlapping_matches(
71 &self,
72 cache: &mut Cache,
73 input: &Input<'_>,
74 patset: &mut PatternSet,
75 );
76 }
77
78 pub(super) fn new(
79 info: &RegexInfo,
80 hirs: &[&Hir],
81 ) -> Result<Arc<dyn Strategy>, BuildError> {
82 // At this point, we're committed to a regex engine of some kind. So pull
83 // out a prefilter if we can, which will feed to each of the constituent
84 // regex engines.
85 let pre = if info.is_always_anchored_start() {
86 // PERF: I'm not sure we necessarily want to do this... We may want to
87 // run a prefilter for quickly rejecting in some cases. The problem
88 // is that anchored searches overlap quite a bit with the use case
89 // of "run a regex on every line to extract data." In that case, the
90 // regex always matches, so running a prefilter doesn't really help us
91 // there. The main place where a prefilter helps in an anchored search
92 // is if the anchored search is not expected to match frequently. That
93 // is, the prefilter gives us a way to possibly reject a haystack very
94 // quickly.
95 //
96 // Maybe we should do use a prefilter, but only for longer haystacks?
97 // Or maybe we should only use a prefilter when we think it's "fast"?
98 //
99 // Interestingly, I think we currently lack the infrastructure for
100 // disabling a prefilter based on haystack length. That would probably
101 // need to be a new 'Input' option. (Interestingly, an 'Input' used to
102 // carry a 'Prefilter' with it, but I moved away from that.)
103 debug!("skipping literal extraction since regex is anchored");
104 None
105 } else if let Some(pre) = info.config().get_prefilter() {
106 debug!(
107 "skipping literal extraction since the caller provided a prefilter"
108 );
109 Some(pre.clone())
110 } else if info.config().get_auto_prefilter() {
111 let kind = info.config().get_match_kind();
112 let prefixes = crate::util::prefilter::prefixes(kind, hirs);
113 // If we can build a full `Strategy` from just the extracted prefixes,
114 // then we can short-circuit and avoid building a regex engine at all.
115 if let Some(pre) = Pre::from_prefixes(info, &prefixes) {
116 debug!(
117 "found that the regex can be broken down to a literal \
118 search, avoiding the regex engine entirely",
119 );
120 return Ok(pre);
121 }
122 // This now attempts another short-circuit of the regex engine: if we
123 // have a huge alternation of just plain literals, then we can just use
124 // Aho-Corasick for that and avoid the regex engine entirely.
125 //
126 // You might think this case would just be handled by
127 // `Pre::from_prefixes`, but that technique relies on heuristic literal
128 // extraction from the corresponding `Hir`. That works, but part of
129 // heuristics limit the size and number of literals returned. This case
130 // will specifically handle patterns with very large alternations.
131 //
132 // One wonders if we should just roll this our heuristic literal
133 // extraction, and then I think this case could disappear entirely.
134 if let Some(pre) = Pre::from_alternation_literals(info, hirs) {
135 debug!(
136 "found plain alternation of literals, \
137 avoiding regex engine entirely and using Aho-Corasick"
138 );
139 return Ok(pre);
140 }
141 prefixes.literals().and_then(|strings| {
142 debug!(
143 "creating prefilter from {} literals: {:?}",
144 strings.len(),
145 strings,
146 );
147 Prefilter::new(kind, strings)
148 })
149 } else {
150 debug!("skipping literal extraction since prefilters were disabled");
151 None
152 };
153 let mut core = Core::new(info.clone(), pre.clone(), hirs)?;
154 // Now that we have our core regex engines built, there are a few cases
155 // where we can do a little bit better than just a normal "search forward
156 // and maybe use a prefilter when in a start state." However, these cases
157 // may not always work or otherwise build on top of the Core searcher.
158 // For example, the reverse anchored optimization seems like it might
159 // always work, but only the DFAs support reverse searching and the DFAs
160 // might give up or quit for reasons. If we had, e.g., a PikeVM that
161 // supported reverse searching, then we could avoid building a full Core
162 // engine for this case.
163 core = match ReverseAnchored::new(core) {
164 Err(core) => core,
165 Ok(ra) => {
166 debug!("using reverse anchored strategy");
167 return Ok(Arc::new(ra));
168 }
169 };
170 core = match ReverseSuffix::new(core, hirs) {
171 Err(core) => core,
172 Ok(rs) => {
173 debug!("using reverse suffix strategy");
174 return Ok(Arc::new(rs));
175 }
176 };
177 core = match ReverseInner::new(core, hirs) {
178 Err(core) => core,
179 Ok(ri) => {
180 debug!("using reverse inner strategy");
181 return Ok(Arc::new(ri));
182 }
183 };
184 debug!("using core strategy");
185 Ok(Arc::new(core))
186 }
187
188 #[derive(Clone, Debug)]
189 struct Pre<P> {
190 pre: P,
191 group_info: GroupInfo,
192 }
193
194 impl<P: PrefilterI> Pre<P> {
195 fn new(pre: P) -> Arc<dyn Strategy> {
196 // The only thing we support when we use prefilters directly as a
197 // strategy is the start and end of the overall match for a single
198 // pattern. In other words, exactly one implicit capturing group. Which
199 // is exactly what we use here for a GroupInfo.
200 let group_info = GroupInfo::new([[None::<&str>]]).unwrap();
201 Arc::new(Pre { pre, group_info })
202 }
203 }
204
205 // This is a little weird, but we don't actually care about the type parameter
206 // here because we're selecting which underlying prefilter to use. So we just
207 // define it on an arbitrary type.
208 impl Pre<()> {
209 /// Given a sequence of prefixes, attempt to return a full `Strategy` using
210 /// just the prefixes.
211 ///
212 /// Basically, this occurs when the prefixes given not just prefixes,
213 /// but an enumeration of the entire language matched by the regular
214 /// expression.
215 ///
216 /// A number of other conditions need to be true too. For example, there
217 /// can be only one pattern, the number of explicit capture groups is 0, no
218 /// look-around assertions and so on.
219 ///
220 /// Note that this ignores `Config::get_auto_prefilter` because if this
221 /// returns something, then it isn't a prefilter but a matcher itself.
222 /// Therefore, it shouldn't suffer from the problems typical to prefilters
223 /// (such as a high false positive rate).
224 fn from_prefixes(
225 info: &RegexInfo,
226 prefixes: &literal::Seq,
227 ) -> Option<Arc<dyn Strategy>> {
228 let kind = info.config().get_match_kind();
229 // Check to see if our prefixes are exact, which means we might be
230 // able to bypass the regex engine entirely and just rely on literal
231 // searches.
232 if !prefixes.is_exact() {
233 return None;
234 }
235 // We also require that we have a single regex pattern. Namely,
236 // we reuse the prefilter infrastructure to implement search and
237 // prefilters only report spans. Prefilters don't know about pattern
238 // IDs. The multi-regex case isn't a lost cause, we might still use
239 // Aho-Corasick and we might still just use a regular prefilter, but
240 // that's done below.
241 if info.pattern_len() != 1 {
242 return None;
243 }
244 // We can't have any capture groups either. The literal engines don't
245 // know how to deal with things like '(foo)(bar)'. In that case, a
246 // prefilter will just be used and then the regex engine will resolve
247 // the capture groups.
248 if info.props()[0].explicit_captures_len() != 0 {
249 return None;
250 }
251 // We also require that it has zero look-around assertions. Namely,
252 // literal extraction treats look-around assertions as if they match
253 // *every* empty string. But of course, that isn't true. So for
254 // example, 'foo\bquux' never matches anything, but 'fooquux' is
255 // extracted from that as an exact literal. Such cases should just run
256 // the regex engine. 'fooquux' will be used as a normal prefilter, and
257 // then the regex engine will try to look for an actual match.
258 if !info.props()[0].look_set().is_empty() {
259 return None;
260 }
261 // Finally, currently, our prefilters are all oriented around
262 // leftmost-first match semantics, so don't try to use them if the
263 // caller asked for anything else.
264 if kind != MatchKind::LeftmostFirst {
265 return None;
266 }
267 // The above seems like a lot of requirements to meet, but it applies
268 // to a lot of cases. 'foo', '[abc][123]' and 'foo|bar|quux' all meet
269 // the above criteria, for example.
270 //
271 // Note that this is effectively a latency optimization. If we didn't
272 // do this, then the extracted literals would still get bundled into
273 // a prefilter, and every regex engine capable of running unanchored
274 // searches supports prefilters. So this optimization merely sidesteps
275 // having to run the regex engine at all to confirm the match. Thus, it
276 // decreases the latency of a match.
277
278 // OK because we know the set is exact and thus finite.
279 let prefixes = prefixes.literals().unwrap();
280 debug!(
281 "trying to bypass regex engine by creating \
282 prefilter from {} literals: {:?}",
283 prefixes.len(),
284 prefixes,
285 );
286 let choice = match prefilter::Choice::new(kind, prefixes) {
287 Some(choice) => choice,
288 None => {
289 debug!(
290 "regex bypass failed because no prefilter could be built"
291 );
292 return None;
293 }
294 };
295 let strat: Arc<dyn Strategy> = match choice {
296 prefilter::Choice::Memchr(pre) => Pre::new(pre),
297 prefilter::Choice::Memchr2(pre) => Pre::new(pre),
298 prefilter::Choice::Memchr3(pre) => Pre::new(pre),
299 prefilter::Choice::Memmem(pre) => Pre::new(pre),
300 prefilter::Choice::Teddy(pre) => Pre::new(pre),
301 prefilter::Choice::ByteSet(pre) => Pre::new(pre),
302 prefilter::Choice::AhoCorasick(pre) => Pre::new(pre),
303 };
304 Some(strat)
305 }
306
307 /// Attempts to extract an alternation of literals, and if it's deemed
308 /// worth doing, returns an Aho-Corasick prefilter as a strategy.
309 ///
310 /// And currently, this only returns something when 'hirs.len() == 1'. This
311 /// could in theory do something if there are multiple HIRs where all of
312 /// them are alternation of literals, but I haven't had the time to go down
313 /// that path yet.
314 fn from_alternation_literals(
315 info: &RegexInfo,
316 hirs: &[&Hir],
317 ) -> Option<Arc<dyn Strategy>> {
318 use crate::util::prefilter::AhoCorasick;
319
320 let lits = crate::meta::literal::alternation_literals(info, hirs)?;
321 let ac = AhoCorasick::new(MatchKind::LeftmostFirst, &lits)?;
322 Some(Pre::new(ac))
323 }
324 }
325
326 // This implements Strategy for anything that implements PrefilterI.
327 //
328 // Note that this must only be used for regexes of length 1. Multi-regexes
329 // don't work here. The prefilter interface only provides the span of a match
330 // and not the pattern ID. (I did consider making it more expressive, but I
331 // couldn't figure out how to tie everything together elegantly.) Thus, so long
332 // as the regex only contains one pattern, we can simply assume that a match
333 // corresponds to PatternID::ZERO. And indeed, that's what we do here.
334 //
335 // In practice, since this impl is used to report matches directly and thus
336 // completely bypasses the regex engine, we only wind up using this under the
337 // following restrictions:
338 //
339 // * There must be only one pattern. As explained above.
340 // * The literal sequence must be finite and only contain exact literals.
341 // * There must not be any look-around assertions. If there are, the literals
342 // extracted might be exact, but a match doesn't necessarily imply an overall
343 // match. As a trivial example, 'foo\bbar' does not match 'foobar'.
344 // * The pattern must not have any explicit capturing groups. If it does, the
345 // caller might expect them to be resolved. e.g., 'foo(bar)'.
346 //
347 // So when all of those things are true, we use a prefilter directly as a
348 // strategy.
349 //
350 // In the case where the number of patterns is more than 1, we don't use this
351 // but do use a special Aho-Corasick strategy if all of the regexes are just
352 // simple literals or alternations of literals. (We also use the Aho-Corasick
353 // strategy when len(patterns)==1 if the number of literals is large. In that
354 // case, literal extraction gives up and will return an infinite set.)
355 impl<P: PrefilterI> Strategy for Pre<P> {
356 fn group_info(&self) -> &GroupInfo {
357 &self.group_info
358 }
359
360 fn create_cache(&self) -> Cache {
361 Cache {
362 capmatches: Captures::all(self.group_info().clone()),
363 pikevm: wrappers::PikeVMCache::none(),
364 backtrack: wrappers::BoundedBacktrackerCache::none(),
365 onepass: wrappers::OnePassCache::none(),
366 hybrid: wrappers::HybridCache::none(),
367 revhybrid: wrappers::ReverseHybridCache::none(),
368 }
369 }
370
371 fn reset_cache(&self, _cache: &mut Cache) {}
372
373 fn is_accelerated(&self) -> bool {
374 self.pre.is_fast()
375 }
376
377 fn memory_usage(&self) -> usize {
378 self.pre.memory_usage()
379 }
380
381 fn search(&self, _cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
382 if input.is_done() {
383 return None;
384 }
385 if input.get_anchored().is_anchored() {
386 return self
387 .pre
388 .prefix(input.haystack(), input.get_span())
389 .map(|sp| Match::new(PatternID::ZERO, sp));
390 }
391 self.pre
392 .find(input.haystack(), input.get_span())
393 .map(|sp| Match::new(PatternID::ZERO, sp))
394 }
395
396 fn search_half(
397 &self,
398 cache: &mut Cache,
399 input: &Input<'_>,
400 ) -> Option<HalfMatch> {
401 self.search(cache, input).map(|m| HalfMatch::new(m.pattern(), m.end()))
402 }
403
404 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
405 self.search(cache, input).is_some()
406 }
407
408 fn search_slots(
409 &self,
410 cache: &mut Cache,
411 input: &Input<'_>,
412 slots: &mut [Option<NonMaxUsize>],
413 ) -> Option<PatternID> {
414 let m = self.search(cache, input)?;
415 if let Some(slot) = slots.get_mut(0) {
416 *slot = NonMaxUsize::new(m.start());
417 }
418 if let Some(slot) = slots.get_mut(1) {
419 *slot = NonMaxUsize::new(m.end());
420 }
421 Some(m.pattern())
422 }
423
424 fn which_overlapping_matches(
425 &self,
426 cache: &mut Cache,
427 input: &Input<'_>,
428 patset: &mut PatternSet,
429 ) {
430 if self.search(cache, input).is_some() {
431 patset.insert(PatternID::ZERO);
432 }
433 }
434 }
435
436 #[derive(Debug)]
437 struct Core {
438 info: RegexInfo,
439 pre: Option<Prefilter>,
440 nfa: NFA,
441 nfarev: Option<NFA>,
442 pikevm: wrappers::PikeVM,
443 backtrack: wrappers::BoundedBacktracker,
444 onepass: wrappers::OnePass,
445 hybrid: wrappers::Hybrid,
446 dfa: wrappers::DFA,
447 }
448
449 impl Core {
450 fn new(
451 info: RegexInfo,
452 pre: Option<Prefilter>,
453 hirs: &[&Hir],
454 ) -> Result<Core, BuildError> {
455 let mut lookm = LookMatcher::new();
456 lookm.set_line_terminator(info.config().get_line_terminator());
457 let thompson_config = thompson::Config::new()
458 .utf8(info.config().get_utf8_empty())
459 .nfa_size_limit(info.config().get_nfa_size_limit())
460 .shrink(false)
461 .which_captures(info.config().get_which_captures())
462 .look_matcher(lookm);
463 let nfa = thompson::Compiler::new()
464 .configure(thompson_config.clone())
465 .build_many_from_hir(hirs)
466 .map_err(BuildError::nfa)?;
467 // It's possible for the PikeVM or the BB to fail to build, even though
468 // at this point, we already have a full NFA in hand. They can fail
469 // when a Unicode word boundary is used but where Unicode word boundary
470 // support is disabled at compile time, thus making it impossible to
471 // match. (Construction can also fail if the NFA was compiled without
472 // captures, but we always enable that above.)
473 let pikevm = wrappers::PikeVM::new(&info, pre.clone(), &nfa)?;
474 let backtrack =
475 wrappers::BoundedBacktracker::new(&info, pre.clone(), &nfa)?;
476 // The onepass engine can of course fail to build, but we expect it to
477 // fail in many cases because it is an optimization that doesn't apply
478 // to all regexes. The 'OnePass' wrapper encapsulates this failure (and
479 // logs a message if it occurs).
480 let onepass = wrappers::OnePass::new(&info, &nfa);
481 // We try to encapsulate whether a particular regex engine should be
482 // used within each respective wrapper, but the DFAs need a reverse NFA
483 // to build itself, and we really do not want to build a reverse NFA if
484 // we know we aren't going to use the lazy DFA. So we do a config check
485 // up front, which is in practice the only way we won't try to use the
486 // DFA.
487 let (nfarev, hybrid, dfa) =
488 if !info.config().get_hybrid() && !info.config().get_dfa() {
489 (None, wrappers::Hybrid::none(), wrappers::DFA::none())
490 } else {
491 // FIXME: Technically, we don't quite yet KNOW that we need
492 // a reverse NFA. It's possible for the DFAs below to both
493 // fail to build just based on the forward NFA. In which case,
494 // building the reverse NFA was totally wasted work. But...
495 // fixing this requires breaking DFA construction apart into
496 // two pieces: one for the forward part and another for the
497 // reverse part. Quite annoying. Making it worse, when building
498 // both DFAs fails, it's quite likely that the NFA is large and
499 // that it will take quite some time to build the reverse NFA
500 // too. So... it's really probably worth it to do this!
501 let nfarev = thompson::Compiler::new()
502 // Currently, reverse NFAs don't support capturing groups,
503 // so we MUST disable them. But even if we didn't have to,
504 // we would, because nothing in this crate does anything
505 // useful with capturing groups in reverse. And of course,
506 // the lazy DFA ignores capturing groups in all cases.
507 .configure(
508 thompson_config
509 .clone()
510 .which_captures(WhichCaptures::None)
511 .reverse(true),
512 )
513 .build_many_from_hir(hirs)
514 .map_err(BuildError::nfa)?;
515 let dfa = if !info.config().get_dfa() {
516 wrappers::DFA::none()
517 } else {
518 wrappers::DFA::new(&info, pre.clone(), &nfa, &nfarev)
519 };
520 let hybrid = if !info.config().get_hybrid() {
521 wrappers::Hybrid::none()
522 } else if dfa.is_some() {
523 debug!("skipping lazy DFA because we have a full DFA");
524 wrappers::Hybrid::none()
525 } else {
526 wrappers::Hybrid::new(&info, pre.clone(), &nfa, &nfarev)
527 };
528 (Some(nfarev), hybrid, dfa)
529 };
530 Ok(Core {
531 info,
532 pre,
533 nfa,
534 nfarev,
535 pikevm,
536 backtrack,
537 onepass,
538 hybrid,
539 dfa,
540 })
541 }
542
543 #[cfg_attr(feature = "perf-inline", inline(always))]
544 fn try_search_mayfail(
545 &self,
546 cache: &mut Cache,
547 input: &Input<'_>,
548 ) -> Option<Result<Option<Match>, RetryFailError>> {
549 if let Some(e) = self.dfa.get(input) {
550 trace!("using full DFA for search at {:?}", input.get_span());
551 Some(e.try_search(input))
552 } else if let Some(e) = self.hybrid.get(input) {
553 trace!("using lazy DFA for search at {:?}", input.get_span());
554 Some(e.try_search(&mut cache.hybrid, input))
555 } else {
556 None
557 }
558 }
559
560 fn search_nofail(
561 &self,
562 cache: &mut Cache,
563 input: &Input<'_>,
564 ) -> Option<Match> {
565 let caps = &mut cache.capmatches;
566 caps.set_pattern(None);
567 // We manually inline 'try_search_slots_nofail' here because we need to
568 // borrow from 'cache.capmatches' in this method, but if we do, then
569 // we can't pass 'cache' wholesale to to 'try_slots_no_hybrid'. It's a
570 // classic example of how the borrow checker inhibits decomposition.
571 // There are of course work-arounds (more types and/or interior
572 // mutability), but that's more annoying than this IMO.
573 let pid = if let Some(ref e) = self.onepass.get(input) {
574 trace!("using OnePass for search at {:?}", input.get_span());
575 e.search_slots(&mut cache.onepass, input, caps.slots_mut())
576 } else if let Some(ref e) = self.backtrack.get(input) {
577 trace!(
578 "using BoundedBacktracker for search at {:?}",
579 input.get_span()
580 );
581 e.search_slots(&mut cache.backtrack, input, caps.slots_mut())
582 } else {
583 trace!("using PikeVM for search at {:?}", input.get_span());
584 let e = self.pikevm.get();
585 e.search_slots(&mut cache.pikevm, input, caps.slots_mut())
586 };
587 caps.set_pattern(pid);
588 caps.get_match()
589 }
590
591 fn search_half_nofail(
592 &self,
593 cache: &mut Cache,
594 input: &Input<'_>,
595 ) -> Option<HalfMatch> {
596 // Only the lazy/full DFA returns half-matches, since the DFA requires
597 // a reverse scan to find the start position. These fallback regex
598 // engines can find the start and end in a single pass, so we just do
599 // that and throw away the start offset to conform to the API.
600 let m = self.search_nofail(cache, input)?;
601 Some(HalfMatch::new(m.pattern(), m.end()))
602 }
603
604 fn search_slots_nofail(
605 &self,
606 cache: &mut Cache,
607 input: &Input<'_>,
608 slots: &mut [Option<NonMaxUsize>],
609 ) -> Option<PatternID> {
610 if let Some(ref e) = self.onepass.get(input) {
611 trace!(
612 "using OnePass for capture search at {:?}",
613 input.get_span()
614 );
615 e.search_slots(&mut cache.onepass, input, slots)
616 } else if let Some(ref e) = self.backtrack.get(input) {
617 trace!(
618 "using BoundedBacktracker for capture search at {:?}",
619 input.get_span()
620 );
621 e.search_slots(&mut cache.backtrack, input, slots)
622 } else {
623 trace!(
624 "using PikeVM for capture search at {:?}",
625 input.get_span()
626 );
627 let e = self.pikevm.get();
628 e.search_slots(&mut cache.pikevm, input, slots)
629 }
630 }
631
632 fn is_match_nofail(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
633 if let Some(ref e) = self.onepass.get(input) {
634 trace!(
635 "using OnePass for is-match search at {:?}",
636 input.get_span()
637 );
638 e.search_slots(&mut cache.onepass, input, &mut []).is_some()
639 } else if let Some(ref e) = self.backtrack.get(input) {
640 trace!(
641 "using BoundedBacktracker for is-match search at {:?}",
642 input.get_span()
643 );
644 e.is_match(&mut cache.backtrack, input)
645 } else {
646 trace!(
647 "using PikeVM for is-match search at {:?}",
648 input.get_span()
649 );
650 let e = self.pikevm.get();
651 e.is_match(&mut cache.pikevm, input)
652 }
653 }
654
655 fn is_capture_search_needed(&self, slots_len: usize) -> bool {
656 slots_len > self.nfa.group_info().implicit_slot_len()
657 }
658 }
659
660 impl Strategy for Core {
661 #[cfg_attr(feature = "perf-inline", inline(always))]
662 fn group_info(&self) -> &GroupInfo {
663 self.nfa.group_info()
664 }
665
666 #[cfg_attr(feature = "perf-inline", inline(always))]
667 fn create_cache(&self) -> Cache {
668 Cache {
669 capmatches: Captures::all(self.group_info().clone()),
670 pikevm: self.pikevm.create_cache(),
671 backtrack: self.backtrack.create_cache(),
672 onepass: self.onepass.create_cache(),
673 hybrid: self.hybrid.create_cache(),
674 revhybrid: wrappers::ReverseHybridCache::none(),
675 }
676 }
677
678 #[cfg_attr(feature = "perf-inline", inline(always))]
679 fn reset_cache(&self, cache: &mut Cache) {
680 cache.pikevm.reset(&self.pikevm);
681 cache.backtrack.reset(&self.backtrack);
682 cache.onepass.reset(&self.onepass);
683 cache.hybrid.reset(&self.hybrid);
684 }
685
686 fn is_accelerated(&self) -> bool {
687 self.pre.as_ref().map_or(false, |pre| pre.is_fast())
688 }
689
690 fn memory_usage(&self) -> usize {
691 self.info.memory_usage()
692 + self.pre.as_ref().map_or(0, |pre| pre.memory_usage())
693 + self.nfa.memory_usage()
694 + self.nfarev.as_ref().map_or(0, |nfa| nfa.memory_usage())
695 + self.onepass.memory_usage()
696 + self.dfa.memory_usage()
697 }
698
699 #[cfg_attr(feature = "perf-inline", inline(always))]
700 fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
701 // We manually inline try_search_mayfail here because letting the
702 // compiler do it seems to produce pretty crappy codegen.
703 return if let Some(e) = self.dfa.get(input) {
704 trace!("using full DFA for full search at {:?}", input.get_span());
705 match e.try_search(input) {
706 Ok(x) => x,
707 Err(_err) => {
708 trace!("full DFA search failed: {}", _err);
709 self.search_nofail(cache, input)
710 }
711 }
712 } else if let Some(e) = self.hybrid.get(input) {
713 trace!("using lazy DFA for full search at {:?}", input.get_span());
714 match e.try_search(&mut cache.hybrid, input) {
715 Ok(x) => x,
716 Err(_err) => {
717 trace!("lazy DFA search failed: {}", _err);
718 self.search_nofail(cache, input)
719 }
720 }
721 } else {
722 self.search_nofail(cache, input)
723 };
724 }
725
726 #[cfg_attr(feature = "perf-inline", inline(always))]
727 fn search_half(
728 &self,
729 cache: &mut Cache,
730 input: &Input<'_>,
731 ) -> Option<HalfMatch> {
732 // The main difference with 'search' is that if we're using a DFA, we
733 // can use a single forward scan without needing to run the reverse
734 // DFA.
735 if let Some(e) = self.dfa.get(input) {
736 trace!("using full DFA for half search at {:?}", input.get_span());
737 match e.try_search_half_fwd(input) {
738 Ok(x) => x,
739 Err(_err) => {
740 trace!("full DFA half search failed: {}", _err);
741 self.search_half_nofail(cache, input)
742 }
743 }
744 } else if let Some(e) = self.hybrid.get(input) {
745 trace!("using lazy DFA for half search at {:?}", input.get_span());
746 match e.try_search_half_fwd(&mut cache.hybrid, input) {
747 Ok(x) => x,
748 Err(_err) => {
749 trace!("lazy DFA half search failed: {}", _err);
750 self.search_half_nofail(cache, input)
751 }
752 }
753 } else {
754 self.search_half_nofail(cache, input)
755 }
756 }
757
758 #[cfg_attr(feature = "perf-inline", inline(always))]
759 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
760 if let Some(e) = self.dfa.get(input) {
761 trace!(
762 "using full DFA for is-match search at {:?}",
763 input.get_span()
764 );
765 match e.try_search_half_fwd(input) {
766 Ok(x) => x.is_some(),
767 Err(_err) => {
768 trace!("full DFA half search failed: {}", _err);
769 self.is_match_nofail(cache, input)
770 }
771 }
772 } else if let Some(e) = self.hybrid.get(input) {
773 trace!(
774 "using lazy DFA for is-match search at {:?}",
775 input.get_span()
776 );
777 match e.try_search_half_fwd(&mut cache.hybrid, input) {
778 Ok(x) => x.is_some(),
779 Err(_err) => {
780 trace!("lazy DFA half search failed: {}", _err);
781 self.is_match_nofail(cache, input)
782 }
783 }
784 } else {
785 self.is_match_nofail(cache, input)
786 }
787 }
788
789 #[cfg_attr(feature = "perf-inline", inline(always))]
790 fn search_slots(
791 &self,
792 cache: &mut Cache,
793 input: &Input<'_>,
794 slots: &mut [Option<NonMaxUsize>],
795 ) -> Option<PatternID> {
796 // Even if the regex has explicit capture groups, if the caller didn't
797 // provide any explicit slots, then it doesn't make sense to try and do
798 // extra work to get offsets for those slots. Ideally the caller should
799 // realize this and not call this routine in the first place, but alas,
800 // we try to save the caller from themselves if they do.
801 if !self.is_capture_search_needed(slots.len()) {
802 trace!("asked for slots unnecessarily, trying fast path");
803 let m = self.search(cache, input)?;
804 copy_match_to_slots(m, slots);
805 return Some(m.pattern());
806 }
807 // If the onepass DFA is available for this search (which only happens
808 // when it's anchored), then skip running a fallible DFA. The onepass
809 // DFA isn't as fast as a full or lazy DFA, but it is typically quite
810 // a bit faster than the backtracker or the PikeVM. So it isn't as
811 // advantageous to try and do a full/lazy DFA scan first.
812 //
813 // We still theorize that it's better to do a full/lazy DFA scan, even
814 // when it's anchored, because it's usually much faster and permits us
815 // to say "no match" much more quickly. This does hurt the case of,
816 // say, parsing each line in a log file into capture groups, because
817 // in that case, the line always matches. So the lazy DFA scan is
818 // usually just wasted work. But, the lazy DFA is usually quite fast
819 // and doesn't cost too much here.
820 if self.onepass.get(&input).is_some() {
821 return self.search_slots_nofail(cache, &input, slots);
822 }
823 let m = match self.try_search_mayfail(cache, input) {
824 Some(Ok(Some(m))) => m,
825 Some(Ok(None)) => return None,
826 Some(Err(_err)) => {
827 trace!("fast capture search failed: {}", _err);
828 return self.search_slots_nofail(cache, input, slots);
829 }
830 None => {
831 return self.search_slots_nofail(cache, input, slots);
832 }
833 };
834 // At this point, now that we've found the bounds of the
835 // match, we need to re-run something that can resolve
836 // capturing groups. But we only need to run on it on the
837 // match bounds and not the entire haystack.
838 trace!(
839 "match found at {}..{} in capture search, \
840 using another engine to find captures",
841 m.start(),
842 m.end(),
843 );
844 let input = input
845 .clone()
846 .span(m.start()..m.end())
847 .anchored(Anchored::Pattern(m.pattern()));
848 Some(
849 self.search_slots_nofail(cache, &input, slots)
850 .expect("should find a match"),
851 )
852 }
853
854 #[cfg_attr(feature = "perf-inline", inline(always))]
855 fn which_overlapping_matches(
856 &self,
857 cache: &mut Cache,
858 input: &Input<'_>,
859 patset: &mut PatternSet,
860 ) {
861 if let Some(e) = self.dfa.get(input) {
862 trace!(
863 "using full DFA for overlapping search at {:?}",
864 input.get_span()
865 );
866 let _err = match e.try_which_overlapping_matches(input, patset) {
867 Ok(()) => return,
868 Err(err) => err,
869 };
870 trace!("fast overlapping search failed: {}", _err);
871 } else if let Some(e) = self.hybrid.get(input) {
872 trace!(
873 "using lazy DFA for overlapping search at {:?}",
874 input.get_span()
875 );
876 let _err = match e.try_which_overlapping_matches(
877 &mut cache.hybrid,
878 input,
879 patset,
880 ) {
881 Ok(()) => {
882 return;
883 }
884 Err(err) => err,
885 };
886 trace!("fast overlapping search failed: {}", _err);
887 }
888 trace!(
889 "using PikeVM for overlapping search at {:?}",
890 input.get_span()
891 );
892 let e = self.pikevm.get();
893 e.which_overlapping_matches(&mut cache.pikevm, input, patset)
894 }
895 }
896
897 #[derive(Debug)]
898 struct ReverseAnchored {
899 core: Core,
900 }
901
902 impl ReverseAnchored {
903 fn new(core: Core) -> Result<ReverseAnchored, Core> {
904 if !core.info.is_always_anchored_end() {
905 debug!(
906 "skipping reverse anchored optimization because \
907 the regex is not always anchored at the end"
908 );
909 return Err(core);
910 }
911 // Note that the caller can still request an anchored search even when
912 // the regex isn't anchored at the start. We detect that case in the
913 // search routines below and just fallback to the core engine. This
914 // is fine because both searches are anchored. It's just a matter of
915 // picking one. Falling back to the core engine is a little simpler,
916 // since if we used the reverse anchored approach, we'd have to add an
917 // extra check to ensure the match reported starts at the place where
918 // the caller requested the search to start.
919 if core.info.is_always_anchored_start() {
920 debug!(
921 "skipping reverse anchored optimization because \
922 the regex is also anchored at the start"
923 );
924 return Err(core);
925 }
926 // Only DFAs can do reverse searches (currently), so we need one of
927 // them in order to do this optimization. It's possible (although
928 // pretty unlikely) that we have neither and need to give up.
929 if !core.hybrid.is_some() && !core.dfa.is_some() {
930 debug!(
931 "skipping reverse anchored optimization because \
932 we don't have a lazy DFA or a full DFA"
933 );
934 return Err(core);
935 }
936 Ok(ReverseAnchored { core })
937 }
938
939 #[cfg_attr(feature = "perf-inline", inline(always))]
940 fn try_search_half_anchored_rev(
941 &self,
942 cache: &mut Cache,
943 input: &Input<'_>,
944 ) -> Result<Option<HalfMatch>, RetryFailError> {
945 // We of course always want an anchored search. In theory, the
946 // underlying regex engines should automatically enable anchored
947 // searches since the regex is itself anchored, but this more clearly
948 // expresses intent and is always correct.
949 let input = input.clone().anchored(Anchored::Yes);
950 if let Some(e) = self.core.dfa.get(&input) {
951 trace!(
952 "using full DFA for reverse anchored search at {:?}",
953 input.get_span()
954 );
955 e.try_search_half_rev(&input)
956 } else if let Some(e) = self.core.hybrid.get(&input) {
957 trace!(
958 "using lazy DFA for reverse anchored search at {:?}",
959 input.get_span()
960 );
961 e.try_search_half_rev(&mut cache.hybrid, &input)
962 } else {
963 unreachable!("ReverseAnchored always has a DFA")
964 }
965 }
966 }
967
968 // Note that in this impl, we don't check that 'input.end() ==
969 // input.haystack().len()'. In particular, when that condition is false, a
970 // match is always impossible because we know that the regex is always anchored
971 // at the end (or else 'ReverseAnchored' won't be built). We don't check that
972 // here because the 'Regex' wrapper actually does that for us in all cases.
973 // Thus, in this impl, we can actually assume that the end position in 'input'
974 // is equivalent to the length of the haystack.
975 impl Strategy for ReverseAnchored {
976 #[cfg_attr(feature = "perf-inline", inline(always))]
977 fn group_info(&self) -> &GroupInfo {
978 self.core.group_info()
979 }
980
981 #[cfg_attr(feature = "perf-inline", inline(always))]
982 fn create_cache(&self) -> Cache {
983 self.core.create_cache()
984 }
985
986 #[cfg_attr(feature = "perf-inline", inline(always))]
987 fn reset_cache(&self, cache: &mut Cache) {
988 self.core.reset_cache(cache);
989 }
990
991 fn is_accelerated(&self) -> bool {
992 // Since this is anchored at the end, a reverse anchored search is
993 // almost certainly guaranteed to result in a much faster search than
994 // a standard forward search.
995 true
996 }
997
998 fn memory_usage(&self) -> usize {
999 self.core.memory_usage()
1000 }
1001
1002 #[cfg_attr(feature = "perf-inline", inline(always))]
1003 fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1004 if input.get_anchored().is_anchored() {
1005 return self.core.search(cache, input);
1006 }
1007 match self.try_search_half_anchored_rev(cache, input) {
1008 Err(_err) => {
1009 trace!("fast reverse anchored search failed: {}", _err);
1010 self.core.search_nofail(cache, input)
1011 }
1012 Ok(None) => None,
1013 Ok(Some(hm)) => {
1014 Some(Match::new(hm.pattern(), hm.offset()..input.end()))
1015 }
1016 }
1017 }
1018
1019 #[cfg_attr(feature = "perf-inline", inline(always))]
1020 fn search_half(
1021 &self,
1022 cache: &mut Cache,
1023 input: &Input<'_>,
1024 ) -> Option<HalfMatch> {
1025 if input.get_anchored().is_anchored() {
1026 return self.core.search_half(cache, input);
1027 }
1028 match self.try_search_half_anchored_rev(cache, input) {
1029 Err(_err) => {
1030 trace!("fast reverse anchored search failed: {}", _err);
1031 self.core.search_half_nofail(cache, input)
1032 }
1033 Ok(None) => None,
1034 Ok(Some(hm)) => {
1035 // Careful here! 'try_search_half' is a *forward* search that
1036 // only cares about the *end* position of a match. But
1037 // 'hm.offset()' is actually the start of the match. So we
1038 // actually just throw that away here and, since we know we
1039 // have a match, return the only possible position at which a
1040 // match can occur: input.end().
1041 Some(HalfMatch::new(hm.pattern(), input.end()))
1042 }
1043 }
1044 }
1045
1046 #[cfg_attr(feature = "perf-inline", inline(always))]
1047 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1048 if input.get_anchored().is_anchored() {
1049 return self.core.is_match(cache, input);
1050 }
1051 match self.try_search_half_anchored_rev(cache, input) {
1052 Err(_err) => {
1053 trace!("fast reverse anchored search failed: {}", _err);
1054 self.core.is_match_nofail(cache, input)
1055 }
1056 Ok(None) => false,
1057 Ok(Some(_)) => true,
1058 }
1059 }
1060
1061 #[cfg_attr(feature = "perf-inline", inline(always))]
1062 fn search_slots(
1063 &self,
1064 cache: &mut Cache,
1065 input: &Input<'_>,
1066 slots: &mut [Option<NonMaxUsize>],
1067 ) -> Option<PatternID> {
1068 if input.get_anchored().is_anchored() {
1069 return self.core.search_slots(cache, input, slots);
1070 }
1071 match self.try_search_half_anchored_rev(cache, input) {
1072 Err(_err) => {
1073 trace!("fast reverse anchored search failed: {}", _err);
1074 self.core.search_slots_nofail(cache, input, slots)
1075 }
1076 Ok(None) => None,
1077 Ok(Some(hm)) => {
1078 if !self.core.is_capture_search_needed(slots.len()) {
1079 trace!("asked for slots unnecessarily, skipping captures");
1080 let m = Match::new(hm.pattern(), hm.offset()..input.end());
1081 copy_match_to_slots(m, slots);
1082 return Some(m.pattern());
1083 }
1084 let start = hm.offset();
1085 let input = input
1086 .clone()
1087 .span(start..input.end())
1088 .anchored(Anchored::Pattern(hm.pattern()));
1089 self.core.search_slots_nofail(cache, &input, slots)
1090 }
1091 }
1092 }
1093
1094 #[cfg_attr(feature = "perf-inline", inline(always))]
1095 fn which_overlapping_matches(
1096 &self,
1097 cache: &mut Cache,
1098 input: &Input<'_>,
1099 patset: &mut PatternSet,
1100 ) {
1101 // It seems like this could probably benefit from a reverse anchored
1102 // optimization, perhaps by doing an overlapping reverse search (which
1103 // the DFAs do support). I haven't given it much thought though, and
1104 // I'm currently focus more on the single pattern case.
1105 self.core.which_overlapping_matches(cache, input, patset)
1106 }
1107 }
1108
1109 #[derive(Debug)]
1110 struct ReverseSuffix {
1111 core: Core,
1112 pre: Prefilter,
1113 }
1114
1115 impl ReverseSuffix {
1116 fn new(core: Core, hirs: &[&Hir]) -> Result<ReverseSuffix, Core> {
1117 if !core.info.config().get_auto_prefilter() {
1118 debug!(
1119 "skipping reverse suffix optimization because \
1120 automatic prefilters are disabled"
1121 );
1122 return Err(core);
1123 }
1124 // Like the reverse inner optimization, we don't do this for regexes
1125 // that are always anchored. It could lead to scanning too much, but
1126 // could say "no match" much more quickly than running the regex
1127 // engine if the initial literal scan doesn't match. With that said,
1128 // the reverse suffix optimization has lower overhead, since it only
1129 // requires a reverse scan after a literal match to confirm or reject
1130 // the match. (Although, in the case of confirmation, it then needs to
1131 // do another forward scan to find the end position.)
1132 //
1133 // Note that the caller can still request an anchored search even
1134 // when the regex isn't anchored. We detect that case in the search
1135 // routines below and just fallback to the core engine. Currently this
1136 // optimization assumes all searches are unanchored, so if we do want
1137 // to enable this optimization for anchored searches, it will need a
1138 // little work to support it.
1139 if core.info.is_always_anchored_start() {
1140 debug!(
1141 "skipping reverse suffix optimization because \
1142 the regex is always anchored at the start",
1143 );
1144 return Err(core);
1145 }
1146 // Only DFAs can do reverse searches (currently), so we need one of
1147 // them in order to do this optimization. It's possible (although
1148 // pretty unlikely) that we have neither and need to give up.
1149 if !core.hybrid.is_some() && !core.dfa.is_some() {
1150 debug!(
1151 "skipping reverse suffix optimization because \
1152 we don't have a lazy DFA or a full DFA"
1153 );
1154 return Err(core);
1155 }
1156 if core.pre.as_ref().map_or(false, |p| p.is_fast()) {
1157 debug!(
1158 "skipping reverse suffix optimization because \
1159 we already have a prefilter that we think is fast"
1160 );
1161 return Err(core);
1162 }
1163 let kind = core.info.config().get_match_kind();
1164 let suffixes = crate::util::prefilter::suffixes(kind, hirs);
1165 let lcs = match suffixes.longest_common_suffix() {
1166 None => {
1167 debug!(
1168 "skipping reverse suffix optimization because \
1169 a longest common suffix could not be found",
1170 );
1171 return Err(core);
1172 }
1173 Some(lcs) if lcs.is_empty() => {
1174 debug!(
1175 "skipping reverse suffix optimization because \
1176 the longest common suffix is the empty string",
1177 );
1178 return Err(core);
1179 }
1180 Some(lcs) => lcs,
1181 };
1182 let pre = match Prefilter::new(kind, &[lcs]) {
1183 Some(pre) => pre,
1184 None => {
1185 debug!(
1186 "skipping reverse suffix optimization because \
1187 a prefilter could not be constructed from the \
1188 longest common suffix",
1189 );
1190 return Err(core);
1191 }
1192 };
1193 if !pre.is_fast() {
1194 debug!(
1195 "skipping reverse suffix optimization because \
1196 while we have a suffix prefilter, it is not \
1197 believed to be 'fast'"
1198 );
1199 return Err(core);
1200 }
1201 Ok(ReverseSuffix { core, pre })
1202 }
1203
1204 #[cfg_attr(feature = "perf-inline", inline(always))]
1205 fn try_search_half_start(
1206 &self,
1207 cache: &mut Cache,
1208 input: &Input<'_>,
1209 ) -> Result<Option<HalfMatch>, RetryError> {
1210 let mut span = input.get_span();
1211 let mut min_start = 0;
1212 loop {
1213 let litmatch = match self.pre.find(input.haystack(), span) {
1214 None => return Ok(None),
1215 Some(span) => span,
1216 };
1217 trace!("reverse suffix scan found suffix match at {:?}", litmatch);
1218 let revinput = input
1219 .clone()
1220 .anchored(Anchored::Yes)
1221 .span(input.start()..litmatch.end);
1222 match self
1223 .try_search_half_rev_limited(cache, &revinput, min_start)?
1224 {
1225 None => {
1226 if span.start >= span.end {
1227 break;
1228 }
1229 span.start = litmatch.start.checked_add(1).unwrap();
1230 }
1231 Some(hm) => return Ok(Some(hm)),
1232 }
1233 min_start = litmatch.end;
1234 }
1235 Ok(None)
1236 }
1237
1238 #[cfg_attr(feature = "perf-inline", inline(always))]
1239 fn try_search_half_fwd(
1240 &self,
1241 cache: &mut Cache,
1242 input: &Input<'_>,
1243 ) -> Result<Option<HalfMatch>, RetryFailError> {
1244 if let Some(e) = self.core.dfa.get(&input) {
1245 trace!(
1246 "using full DFA for forward reverse suffix search at {:?}",
1247 input.get_span()
1248 );
1249 e.try_search_half_fwd(&input)
1250 } else if let Some(e) = self.core.hybrid.get(&input) {
1251 trace!(
1252 "using lazy DFA for forward reverse suffix search at {:?}",
1253 input.get_span()
1254 );
1255 e.try_search_half_fwd(&mut cache.hybrid, &input)
1256 } else {
1257 unreachable!("ReverseSuffix always has a DFA")
1258 }
1259 }
1260
1261 #[cfg_attr(feature = "perf-inline", inline(always))]
1262 fn try_search_half_rev_limited(
1263 &self,
1264 cache: &mut Cache,
1265 input: &Input<'_>,
1266 min_start: usize,
1267 ) -> Result<Option<HalfMatch>, RetryError> {
1268 if let Some(e) = self.core.dfa.get(&input) {
1269 trace!(
1270 "using full DFA for reverse suffix search at {:?}, \
1271 but will be stopped at {} to avoid quadratic behavior",
1272 input.get_span(),
1273 min_start,
1274 );
1275 e.try_search_half_rev_limited(&input, min_start)
1276 } else if let Some(e) = self.core.hybrid.get(&input) {
1277 trace!(
1278 "using lazy DFA for reverse inner search at {:?}, \
1279 but will be stopped at {} to avoid quadratic behavior",
1280 input.get_span(),
1281 min_start,
1282 );
1283 e.try_search_half_rev_limited(&mut cache.hybrid, &input, min_start)
1284 } else {
1285 unreachable!("ReverseSuffix always has a DFA")
1286 }
1287 }
1288 }
1289
1290 impl Strategy for ReverseSuffix {
1291 #[cfg_attr(feature = "perf-inline", inline(always))]
1292 fn group_info(&self) -> &GroupInfo {
1293 self.core.group_info()
1294 }
1295
1296 #[cfg_attr(feature = "perf-inline", inline(always))]
1297 fn create_cache(&self) -> Cache {
1298 self.core.create_cache()
1299 }
1300
1301 #[cfg_attr(feature = "perf-inline", inline(always))]
1302 fn reset_cache(&self, cache: &mut Cache) {
1303 self.core.reset_cache(cache);
1304 }
1305
1306 fn is_accelerated(&self) -> bool {
1307 self.pre.is_fast()
1308 }
1309
1310 fn memory_usage(&self) -> usize {
1311 self.core.memory_usage() + self.pre.memory_usage()
1312 }
1313
1314 #[cfg_attr(feature = "perf-inline", inline(always))]
1315 fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1316 if input.get_anchored().is_anchored() {
1317 return self.core.search(cache, input);
1318 }
1319 match self.try_search_half_start(cache, input) {
1320 Err(RetryError::Quadratic(_err)) => {
1321 trace!("reverse suffix optimization failed: {}", _err);
1322 self.core.search(cache, input)
1323 }
1324 Err(RetryError::Fail(_err)) => {
1325 trace!("reverse suffix reverse fast search failed: {}", _err);
1326 self.core.search_nofail(cache, input)
1327 }
1328 Ok(None) => None,
1329 Ok(Some(hm_start)) => {
1330 let fwdinput = input
1331 .clone()
1332 .anchored(Anchored::Pattern(hm_start.pattern()))
1333 .span(hm_start.offset()..input.end());
1334 match self.try_search_half_fwd(cache, &fwdinput) {
1335 Err(_err) => {
1336 trace!(
1337 "reverse suffix forward fast search failed: {}",
1338 _err
1339 );
1340 self.core.search_nofail(cache, input)
1341 }
1342 Ok(None) => {
1343 unreachable!(
1344 "suffix match plus reverse match implies \
1345 there must be a match",
1346 )
1347 }
1348 Ok(Some(hm_end)) => Some(Match::new(
1349 hm_start.pattern(),
1350 hm_start.offset()..hm_end.offset(),
1351 )),
1352 }
1353 }
1354 }
1355 }
1356
1357 #[cfg_attr(feature = "perf-inline", inline(always))]
1358 fn search_half(
1359 &self,
1360 cache: &mut Cache,
1361 input: &Input<'_>,
1362 ) -> Option<HalfMatch> {
1363 if input.get_anchored().is_anchored() {
1364 return self.core.search_half(cache, input);
1365 }
1366 match self.try_search_half_start(cache, input) {
1367 Err(RetryError::Quadratic(_err)) => {
1368 trace!("reverse suffix half optimization failed: {}", _err);
1369 self.core.search_half(cache, input)
1370 }
1371 Err(RetryError::Fail(_err)) => {
1372 trace!(
1373 "reverse suffix reverse fast half search failed: {}",
1374 _err
1375 );
1376 self.core.search_half_nofail(cache, input)
1377 }
1378 Ok(None) => None,
1379 Ok(Some(hm_start)) => {
1380 // This is a bit subtle. It is tempting to just stop searching
1381 // at this point and return a half-match with an offset
1382 // corresponding to where the suffix was found. But the suffix
1383 // match does not necessarily correspond to the end of the
1384 // proper leftmost-first match. Consider /[a-z]+ing/ against
1385 // 'tingling'. The first suffix match is the first 'ing', and
1386 // the /[a-z]+/ matches the 't'. So if we stopped here, then
1387 // we'd report 'ting' as the match. But 'tingling' is the
1388 // correct match because of greediness.
1389 let fwdinput = input
1390 .clone()
1391 .anchored(Anchored::Pattern(hm_start.pattern()))
1392 .span(hm_start.offset()..input.end());
1393 match self.try_search_half_fwd(cache, &fwdinput) {
1394 Err(_err) => {
1395 trace!(
1396 "reverse suffix forward fast search failed: {}",
1397 _err
1398 );
1399 self.core.search_half_nofail(cache, input)
1400 }
1401 Ok(None) => {
1402 unreachable!(
1403 "suffix match plus reverse match implies \
1404 there must be a match",
1405 )
1406 }
1407 Ok(Some(hm_end)) => Some(hm_end),
1408 }
1409 }
1410 }
1411 }
1412
1413 #[cfg_attr(feature = "perf-inline", inline(always))]
1414 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1415 if input.get_anchored().is_anchored() {
1416 return self.core.is_match(cache, input);
1417 }
1418 match self.try_search_half_start(cache, input) {
1419 Err(RetryError::Quadratic(_err)) => {
1420 trace!("reverse suffix half optimization failed: {}", _err);
1421 self.core.is_match_nofail(cache, input)
1422 }
1423 Err(RetryError::Fail(_err)) => {
1424 trace!(
1425 "reverse suffix reverse fast half search failed: {}",
1426 _err
1427 );
1428 self.core.is_match_nofail(cache, input)
1429 }
1430 Ok(None) => false,
1431 Ok(Some(_)) => true,
1432 }
1433 }
1434
1435 #[cfg_attr(feature = "perf-inline", inline(always))]
1436 fn search_slots(
1437 &self,
1438 cache: &mut Cache,
1439 input: &Input<'_>,
1440 slots: &mut [Option<NonMaxUsize>],
1441 ) -> Option<PatternID> {
1442 if input.get_anchored().is_anchored() {
1443 return self.core.search_slots(cache, input, slots);
1444 }
1445 if !self.core.is_capture_search_needed(slots.len()) {
1446 trace!("asked for slots unnecessarily, trying fast path");
1447 let m = self.search(cache, input)?;
1448 copy_match_to_slots(m, slots);
1449 return Some(m.pattern());
1450 }
1451 let hm_start = match self.try_search_half_start(cache, input) {
1452 Err(RetryError::Quadratic(_err)) => {
1453 trace!(
1454 "reverse suffix captures optimization failed: {}",
1455 _err
1456 );
1457 return self.core.search_slots(cache, input, slots);
1458 }
1459 Err(RetryError::Fail(_err)) => {
1460 trace!(
1461 "reverse suffix reverse fast captures search failed: {}",
1462 _err
1463 );
1464 return self.core.search_slots_nofail(cache, input, slots);
1465 }
1466 Ok(None) => return None,
1467 Ok(Some(hm_start)) => hm_start,
1468 };
1469 trace!(
1470 "match found at {}..{} in capture search, \
1471 using another engine to find captures",
1472 hm_start.offset(),
1473 input.end(),
1474 );
1475 let start = hm_start.offset();
1476 let input = input
1477 .clone()
1478 .span(start..input.end())
1479 .anchored(Anchored::Pattern(hm_start.pattern()));
1480 self.core.search_slots_nofail(cache, &input, slots)
1481 }
1482
1483 #[cfg_attr(feature = "perf-inline", inline(always))]
1484 fn which_overlapping_matches(
1485 &self,
1486 cache: &mut Cache,
1487 input: &Input<'_>,
1488 patset: &mut PatternSet,
1489 ) {
1490 self.core.which_overlapping_matches(cache, input, patset)
1491 }
1492 }
1493
1494 #[derive(Debug)]
1495 struct ReverseInner {
1496 core: Core,
1497 preinner: Prefilter,
1498 nfarev: NFA,
1499 hybrid: wrappers::ReverseHybrid,
1500 dfa: wrappers::ReverseDFA,
1501 }
1502
1503 impl ReverseInner {
1504 fn new(core: Core, hirs: &[&Hir]) -> Result<ReverseInner, Core> {
1505 if !core.info.config().get_auto_prefilter() {
1506 debug!(
1507 "skipping reverse inner optimization because \
1508 automatic prefilters are disabled"
1509 );
1510 return Err(core);
1511 }
1512 // Currently we hard-code the assumption of leftmost-first match
1513 // semantics. This isn't a huge deal because 'all' semantics tend to
1514 // only be used for forward overlapping searches with multiple regexes,
1515 // and this optimization only supports a single pattern at the moment.
1516 if core.info.config().get_match_kind() != MatchKind::LeftmostFirst {
1517 debug!(
1518 "skipping reverse inner optimization because \
1519 match kind is {:?} but this only supports leftmost-first",
1520 core.info.config().get_match_kind(),
1521 );
1522 return Err(core);
1523 }
1524 // It's likely that a reverse inner scan has too much overhead for it
1525 // to be worth it when the regex is anchored at the start. It is
1526 // possible for it to be quite a bit faster if the initial literal
1527 // scan fails to detect a match, in which case, we can say "no match"
1528 // very quickly. But this could be undesirable, e.g., scanning too far
1529 // or when the literal scan matches. If it matches, then confirming the
1530 // match requires a reverse scan followed by a forward scan to confirm
1531 // or reject, which is a fair bit of work.
1532 //
1533 // Note that the caller can still request an anchored search even
1534 // when the regex isn't anchored. We detect that case in the search
1535 // routines below and just fallback to the core engine. Currently this
1536 // optimization assumes all searches are unanchored, so if we do want
1537 // to enable this optimization for anchored searches, it will need a
1538 // little work to support it.
1539 if core.info.is_always_anchored_start() {
1540 debug!(
1541 "skipping reverse inner optimization because \
1542 the regex is always anchored at the start",
1543 );
1544 return Err(core);
1545 }
1546 // Only DFAs can do reverse searches (currently), so we need one of
1547 // them in order to do this optimization. It's possible (although
1548 // pretty unlikely) that we have neither and need to give up.
1549 if !core.hybrid.is_some() && !core.dfa.is_some() {
1550 debug!(
1551 "skipping reverse inner optimization because \
1552 we don't have a lazy DFA or a full DFA"
1553 );
1554 return Err(core);
1555 }
1556 if core.pre.as_ref().map_or(false, |p| p.is_fast()) {
1557 debug!(
1558 "skipping reverse inner optimization because \
1559 we already have a prefilter that we think is fast"
1560 );
1561 return Err(core);
1562 } else if core.pre.is_some() {
1563 debug!(
1564 "core engine has a prefix prefilter, but it is \
1565 probably not fast, so continuing with attempt to \
1566 use reverse inner prefilter"
1567 );
1568 }
1569 let (concat_prefix, preinner) = match reverse_inner::extract(hirs) {
1570 Some(x) => x,
1571 // N.B. the 'extract' function emits debug messages explaining
1572 // why we bailed out here.
1573 None => return Err(core),
1574 };
1575 debug!("building reverse NFA for prefix before inner literal");
1576 let mut lookm = LookMatcher::new();
1577 lookm.set_line_terminator(core.info.config().get_line_terminator());
1578 let thompson_config = thompson::Config::new()
1579 .reverse(true)
1580 .utf8(core.info.config().get_utf8_empty())
1581 .nfa_size_limit(core.info.config().get_nfa_size_limit())
1582 .shrink(false)
1583 .which_captures(WhichCaptures::None)
1584 .look_matcher(lookm);
1585 let result = thompson::Compiler::new()
1586 .configure(thompson_config)
1587 .build_from_hir(&concat_prefix);
1588 let nfarev = match result {
1589 Ok(nfarev) => nfarev,
1590 Err(_err) => {
1591 debug!(
1592 "skipping reverse inner optimization because the \
1593 reverse NFA failed to build: {}",
1594 _err,
1595 );
1596 return Err(core);
1597 }
1598 };
1599 debug!("building reverse DFA for prefix before inner literal");
1600 let dfa = if !core.info.config().get_dfa() {
1601 wrappers::ReverseDFA::none()
1602 } else {
1603 wrappers::ReverseDFA::new(&core.info, &nfarev)
1604 };
1605 let hybrid = if !core.info.config().get_hybrid() {
1606 wrappers::ReverseHybrid::none()
1607 } else if dfa.is_some() {
1608 debug!(
1609 "skipping lazy DFA for reverse inner optimization \
1610 because we have a full DFA"
1611 );
1612 wrappers::ReverseHybrid::none()
1613 } else {
1614 wrappers::ReverseHybrid::new(&core.info, &nfarev)
1615 };
1616 Ok(ReverseInner { core, preinner, nfarev, hybrid, dfa })
1617 }
1618
1619 #[cfg_attr(feature = "perf-inline", inline(always))]
1620 fn try_search_full(
1621 &self,
1622 cache: &mut Cache,
1623 input: &Input<'_>,
1624 ) -> Result<Option<Match>, RetryError> {
1625 let mut span = input.get_span();
1626 let mut min_match_start = 0;
1627 let mut min_pre_start = 0;
1628 loop {
1629 let litmatch = match self.preinner.find(input.haystack(), span) {
1630 None => return Ok(None),
1631 Some(span) => span,
1632 };
1633 if litmatch.start < min_pre_start {
1634 trace!(
1635 "found inner prefilter match at {:?}, which starts \
1636 before the end of the last forward scan at {}, \
1637 quitting to avoid quadratic behavior",
1638 litmatch,
1639 min_pre_start,
1640 );
1641 return Err(RetryError::Quadratic(RetryQuadraticError::new()));
1642 }
1643 trace!("reverse inner scan found inner match at {:?}", litmatch);
1644 let revinput = input
1645 .clone()
1646 .anchored(Anchored::Yes)
1647 .span(input.start()..litmatch.start);
1648 // Note that in addition to the literal search above scanning past
1649 // our minimum start point, this routine can also return an error
1650 // as a result of detecting possible quadratic behavior if the
1651 // reverse scan goes past the minimum start point. That is, the
1652 // literal search might not, but the reverse regex search for the
1653 // prefix might!
1654 match self.try_search_half_rev_limited(
1655 cache,
1656 &revinput,
1657 min_match_start,
1658 )? {
1659 None => {
1660 if span.start >= span.end {
1661 break;
1662 }
1663 span.start = litmatch.start.checked_add(1).unwrap();
1664 }
1665 Some(hm_start) => {
1666 let fwdinput = input
1667 .clone()
1668 .anchored(Anchored::Pattern(hm_start.pattern()))
1669 .span(hm_start.offset()..input.end());
1670 match self.try_search_half_fwd_stopat(cache, &fwdinput)? {
1671 Err(stopat) => {
1672 min_pre_start = stopat;
1673 span.start =
1674 litmatch.start.checked_add(1).unwrap();
1675 }
1676 Ok(hm_end) => {
1677 return Ok(Some(Match::new(
1678 hm_start.pattern(),
1679 hm_start.offset()..hm_end.offset(),
1680 )))
1681 }
1682 }
1683 }
1684 }
1685 min_match_start = litmatch.end;
1686 }
1687 Ok(None)
1688 }
1689
1690 #[cfg_attr(feature = "perf-inline", inline(always))]
1691 fn try_search_half_fwd_stopat(
1692 &self,
1693 cache: &mut Cache,
1694 input: &Input<'_>,
1695 ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
1696 if let Some(e) = self.core.dfa.get(&input) {
1697 trace!(
1698 "using full DFA for forward reverse inner search at {:?}",
1699 input.get_span()
1700 );
1701 e.try_search_half_fwd_stopat(&input)
1702 } else if let Some(e) = self.core.hybrid.get(&input) {
1703 trace!(
1704 "using lazy DFA for forward reverse inner search at {:?}",
1705 input.get_span()
1706 );
1707 e.try_search_half_fwd_stopat(&mut cache.hybrid, &input)
1708 } else {
1709 unreachable!("ReverseInner always has a DFA")
1710 }
1711 }
1712
1713 #[cfg_attr(feature = "perf-inline", inline(always))]
1714 fn try_search_half_rev_limited(
1715 &self,
1716 cache: &mut Cache,
1717 input: &Input<'_>,
1718 min_start: usize,
1719 ) -> Result<Option<HalfMatch>, RetryError> {
1720 if let Some(e) = self.dfa.get(&input) {
1721 trace!(
1722 "using full DFA for reverse inner search at {:?}, \
1723 but will be stopped at {} to avoid quadratic behavior",
1724 input.get_span(),
1725 min_start,
1726 );
1727 e.try_search_half_rev_limited(&input, min_start)
1728 } else if let Some(e) = self.hybrid.get(&input) {
1729 trace!(
1730 "using lazy DFA for reverse inner search at {:?}, \
1731 but will be stopped at {} to avoid quadratic behavior",
1732 input.get_span(),
1733 min_start,
1734 );
1735 e.try_search_half_rev_limited(
1736 &mut cache.revhybrid,
1737 &input,
1738 min_start,
1739 )
1740 } else {
1741 unreachable!("ReverseInner always has a DFA")
1742 }
1743 }
1744 }
1745
1746 impl Strategy for ReverseInner {
1747 #[cfg_attr(feature = "perf-inline", inline(always))]
1748 fn group_info(&self) -> &GroupInfo {
1749 self.core.group_info()
1750 }
1751
1752 #[cfg_attr(feature = "perf-inline", inline(always))]
1753 fn create_cache(&self) -> Cache {
1754 let mut cache = self.core.create_cache();
1755 cache.revhybrid = self.hybrid.create_cache();
1756 cache
1757 }
1758
1759 #[cfg_attr(feature = "perf-inline", inline(always))]
1760 fn reset_cache(&self, cache: &mut Cache) {
1761 self.core.reset_cache(cache);
1762 cache.revhybrid.reset(&self.hybrid);
1763 }
1764
1765 fn is_accelerated(&self) -> bool {
1766 self.preinner.is_fast()
1767 }
1768
1769 fn memory_usage(&self) -> usize {
1770 self.core.memory_usage()
1771 + self.preinner.memory_usage()
1772 + self.nfarev.memory_usage()
1773 + self.dfa.memory_usage()
1774 }
1775
1776 #[cfg_attr(feature = "perf-inline", inline(always))]
1777 fn search(&self, cache: &mut Cache, input: &Input<'_>) -> Option<Match> {
1778 if input.get_anchored().is_anchored() {
1779 return self.core.search(cache, input);
1780 }
1781 match self.try_search_full(cache, input) {
1782 Err(RetryError::Quadratic(_err)) => {
1783 trace!("reverse inner optimization failed: {}", _err);
1784 self.core.search(cache, input)
1785 }
1786 Err(RetryError::Fail(_err)) => {
1787 trace!("reverse inner fast search failed: {}", _err);
1788 self.core.search_nofail(cache, input)
1789 }
1790 Ok(matornot) => matornot,
1791 }
1792 }
1793
1794 #[cfg_attr(feature = "perf-inline", inline(always))]
1795 fn search_half(
1796 &self,
1797 cache: &mut Cache,
1798 input: &Input<'_>,
1799 ) -> Option<HalfMatch> {
1800 if input.get_anchored().is_anchored() {
1801 return self.core.search_half(cache, input);
1802 }
1803 match self.try_search_full(cache, input) {
1804 Err(RetryError::Quadratic(_err)) => {
1805 trace!("reverse inner half optimization failed: {}", _err);
1806 self.core.search_half(cache, input)
1807 }
1808 Err(RetryError::Fail(_err)) => {
1809 trace!("reverse inner fast half search failed: {}", _err);
1810 self.core.search_half_nofail(cache, input)
1811 }
1812 Ok(None) => None,
1813 Ok(Some(m)) => Some(HalfMatch::new(m.pattern(), m.end())),
1814 }
1815 }
1816
1817 #[cfg_attr(feature = "perf-inline", inline(always))]
1818 fn is_match(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1819 if input.get_anchored().is_anchored() {
1820 return self.core.is_match(cache, input);
1821 }
1822 match self.try_search_full(cache, input) {
1823 Err(RetryError::Quadratic(_err)) => {
1824 trace!("reverse inner half optimization failed: {}", _err);
1825 self.core.is_match_nofail(cache, input)
1826 }
1827 Err(RetryError::Fail(_err)) => {
1828 trace!("reverse inner fast half search failed: {}", _err);
1829 self.core.is_match_nofail(cache, input)
1830 }
1831 Ok(None) => false,
1832 Ok(Some(_)) => true,
1833 }
1834 }
1835
1836 #[cfg_attr(feature = "perf-inline", inline(always))]
1837 fn search_slots(
1838 &self,
1839 cache: &mut Cache,
1840 input: &Input<'_>,
1841 slots: &mut [Option<NonMaxUsize>],
1842 ) -> Option<PatternID> {
1843 if input.get_anchored().is_anchored() {
1844 return self.core.search_slots(cache, input, slots);
1845 }
1846 if !self.core.is_capture_search_needed(slots.len()) {
1847 trace!("asked for slots unnecessarily, trying fast path");
1848 let m = self.search(cache, input)?;
1849 copy_match_to_slots(m, slots);
1850 return Some(m.pattern());
1851 }
1852 let m = match self.try_search_full(cache, input) {
1853 Err(RetryError::Quadratic(_err)) => {
1854 trace!("reverse inner captures optimization failed: {}", _err);
1855 return self.core.search_slots(cache, input, slots);
1856 }
1857 Err(RetryError::Fail(_err)) => {
1858 trace!("reverse inner fast captures search failed: {}", _err);
1859 return self.core.search_slots_nofail(cache, input, slots);
1860 }
1861 Ok(None) => return None,
1862 Ok(Some(m)) => m,
1863 };
1864 trace!(
1865 "match found at {}..{} in capture search, \
1866 using another engine to find captures",
1867 m.start(),
1868 m.end(),
1869 );
1870 let input = input
1871 .clone()
1872 .span(m.start()..m.end())
1873 .anchored(Anchored::Pattern(m.pattern()));
1874 self.core.search_slots_nofail(cache, &input, slots)
1875 }
1876
1877 #[cfg_attr(feature = "perf-inline", inline(always))]
1878 fn which_overlapping_matches(
1879 &self,
1880 cache: &mut Cache,
1881 input: &Input<'_>,
1882 patset: &mut PatternSet,
1883 ) {
1884 self.core.which_overlapping_matches(cache, input, patset)
1885 }
1886 }
1887
1888 /// Copies the offsets in the given match to the corresponding positions in
1889 /// `slots`.
1890 ///
1891 /// In effect, this sets the slots corresponding to the implicit group for the
1892 /// pattern in the given match. If the indices for the corresponding slots do
1893 /// not exist, then no slots are set.
1894 ///
1895 /// This is useful when the caller provides slots (or captures), but you use a
1896 /// regex engine that doesn't operate on slots (like a lazy DFA). This function
1897 /// lets you map the match you get back to the slots provided by the caller.
1898 #[cfg_attr(feature = "perf-inline", inline(always))]
1899 fn copy_match_to_slots(m: Match, slots: &mut [Option<NonMaxUsize>]) {
1900 let slot_start = m.pattern().as_usize() * 2;
1901 let slot_end = slot_start + 1;
1902 if let Some(slot) = slots.get_mut(slot_start) {
1903 *slot = NonMaxUsize::new(m.start());
1904 }
1905 if let Some(slot) = slots.get_mut(slot_end) {
1906 *slot = NonMaxUsize::new(m.end());
1907 }
1908 }