Debian Codegraph @

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

raw
1 /*!
2 This module contains a boat load of wrappers around each of our internal regex
3 engines. They encapsulate a few things:
4
5 1. The wrappers manage the conditional existence of the regex engine. Namely,
6 the PikeVM is the only required regex engine. The rest are optional. These
7 wrappers present a uniform API regardless of which engines are available. And
8 availability might be determined by compile time features or by dynamic
9 configuration via `meta::Config`. Encapsulating the conditional compilation
10 features is in particular a huge simplification for the higher level code that
11 composes these engines.
12 2. The wrappers manage construction of each engine, including skipping it if
13 the engine is unavailable or configured to not be used.
14 3. The wrappers manage whether an engine *can* be used for a particular
15 search configuration. For example, `BoundedBacktracker::get` only returns a
16 backtracking engine when the haystack is bigger than the maximum supported
17 length. The wrappers also sometimes take a position on when an engine *ought*
18 to be used, but only in cases where the logic is extremely local to the engine
19 itself. Otherwise, things like "choose between the backtracker and the one-pass
20 DFA" are managed by the higher level meta strategy code.
21
22 There are also corresponding wrappers for the various `Cache` types for each
23 regex engine that needs them. If an engine is unavailable or not used, then a
24 cache for it will *not* actually be allocated.
25 */
26
27 use alloc::vec::Vec;
28
29 use crate::{
30 meta::{
31 error::{BuildError, RetryError, RetryFailError},
32 regex::RegexInfo,
33 },
34 nfa::thompson::{pikevm, NFA},
35 util::{prefilter::Prefilter, primitives::NonMaxUsize},
36 HalfMatch, Input, Match, MatchKind, PatternID, PatternSet,
37 };
38
39 #[cfg(feature = "dfa-build")]
40 use crate::dfa;
41 #[cfg(feature = "dfa-onepass")]
42 use crate::dfa::onepass;
43 #[cfg(feature = "hybrid")]
44 use crate::hybrid;
45 #[cfg(feature = "nfa-backtrack")]
46 use crate::nfa::thompson::backtrack;
47
48 #[derive(Debug)]
49 pub(crate) struct PikeVM(PikeVMEngine);
50
51 impl PikeVM {
52 pub(crate) fn new(
53 info: &RegexInfo,
54 pre: Option<Prefilter>,
55 nfa: &NFA,
56 ) -> Result<PikeVM, BuildError> {
57 PikeVMEngine::new(info, pre, nfa).map(PikeVM)
58 }
59
60 pub(crate) fn create_cache(&self) -> PikeVMCache {
61 PikeVMCache::new(self)
62 }
63
64 #[cfg_attr(feature = "perf-inline", inline(always))]
65 pub(crate) fn get(&self) -> &PikeVMEngine {
66 &self.0
67 }
68 }
69
70 #[derive(Debug)]
71 pub(crate) struct PikeVMEngine(pikevm::PikeVM);
72
73 impl PikeVMEngine {
74 pub(crate) fn new(
75 info: &RegexInfo,
76 pre: Option<Prefilter>,
77 nfa: &NFA,
78 ) -> Result<PikeVMEngine, BuildError> {
79 let pikevm_config = pikevm::Config::new()
80 .match_kind(info.config().get_match_kind())
81 .prefilter(pre);
82 let engine = pikevm::Builder::new()
83 .configure(pikevm_config)
84 .build_from_nfa(nfa.clone())
85 .map_err(BuildError::nfa)?;
86 debug!("PikeVM built");
87 Ok(PikeVMEngine(engine))
88 }
89
90 #[cfg_attr(feature = "perf-inline", inline(always))]
91 pub(crate) fn is_match(
92 &self,
93 cache: &mut PikeVMCache,
94 input: &Input<'_>,
95 ) -> bool {
96 self.0.is_match(cache.0.as_mut().unwrap(), input.clone())
97 }
98
99 #[cfg_attr(feature = "perf-inline", inline(always))]
100 pub(crate) fn search_slots(
101 &self,
102 cache: &mut PikeVMCache,
103 input: &Input<'_>,
104 slots: &mut [Option<NonMaxUsize>],
105 ) -> Option<PatternID> {
106 self.0.search_slots(cache.0.as_mut().unwrap(), input, slots)
107 }
108
109 #[cfg_attr(feature = "perf-inline", inline(always))]
110 pub(crate) fn which_overlapping_matches(
111 &self,
112 cache: &mut PikeVMCache,
113 input: &Input<'_>,
114 patset: &mut PatternSet,
115 ) {
116 self.0.which_overlapping_matches(
117 cache.0.as_mut().unwrap(),
118 input,
119 patset,
120 )
121 }
122 }
123
124 #[derive(Clone, Debug)]
125 pub(crate) struct PikeVMCache(Option<pikevm::Cache>);
126
127 impl PikeVMCache {
128 pub(crate) fn none() -> PikeVMCache {
129 PikeVMCache(None)
130 }
131
132 pub(crate) fn new(builder: &PikeVM) -> PikeVMCache {
133 PikeVMCache(Some(builder.get().0.create_cache()))
134 }
135
136 pub(crate) fn reset(&mut self, builder: &PikeVM) {
137 self.0.as_mut().unwrap().reset(&builder.get().0);
138 }
139
140 pub(crate) fn memory_usage(&self) -> usize {
141 self.0.as_ref().map_or(0, |c| c.memory_usage())
142 }
143 }
144
145 #[derive(Debug)]
146 pub(crate) struct BoundedBacktracker(Option<BoundedBacktrackerEngine>);
147
148 impl BoundedBacktracker {
149 pub(crate) fn new(
150 info: &RegexInfo,
151 pre: Option<Prefilter>,
152 nfa: &NFA,
153 ) -> Result<BoundedBacktracker, BuildError> {
154 BoundedBacktrackerEngine::new(info, pre, nfa).map(BoundedBacktracker)
155 }
156
157 pub(crate) fn create_cache(&self) -> BoundedBacktrackerCache {
158 BoundedBacktrackerCache::new(self)
159 }
160
161 #[cfg_attr(feature = "perf-inline", inline(always))]
162 pub(crate) fn get(
163 &self,
164 input: &Input<'_>,
165 ) -> Option<&BoundedBacktrackerEngine> {
166 let engine = self.0.as_ref()?;
167 // It is difficult to make the backtracker give up early if it is
168 // guaranteed to eventually wind up in a match state. This is because
169 // of the greedy nature of a backtracker: it just blindly mushes
170 // forward. Every other regex engine is able to give up more quickly,
171 // so even if the backtracker might be able to zip through faster than
172 // (say) the PikeVM, we prefer the theoretical benefit that some other
173 // engine might be able to scan much less of the haystack than the
174 // backtracker.
175 //
176 // Now, if the haystack is really short already, then we allow the
177 // backtracker to run. (This hasn't been litigated quantitatively with
178 // benchmarks. Just a hunch.)
179 if input.get_earliest() && input.haystack().len() > 128 {
180 return None;
181 }
182 // If the backtracker is just going to return an error because the
183 // haystack is too long, then obviously do not use it.
184 if input.get_span().len() > engine.max_haystack_len() {
185 return None;
186 }
187 Some(engine)
188 }
189 }
190
191 #[derive(Debug)]
192 pub(crate) struct BoundedBacktrackerEngine(
193 #[cfg(feature = "nfa-backtrack")] backtrack::BoundedBacktracker,
194 #[cfg(not(feature = "nfa-backtrack"))] (),
195 );
196
197 impl BoundedBacktrackerEngine {
198 pub(crate) fn new(
199 info: &RegexInfo,
200 pre: Option<Prefilter>,
201 nfa: &NFA,
202 ) -> Result<Option<BoundedBacktrackerEngine>, BuildError> {
203 #[cfg(feature = "nfa-backtrack")]
204 {
205 if !info.config().get_backtrack()
206 || info.config().get_match_kind() != MatchKind::LeftmostFirst
207 {
208 return Ok(None);
209 }
210 let backtrack_config = backtrack::Config::new().prefilter(pre);
211 let engine = backtrack::Builder::new()
212 .configure(backtrack_config)
213 .build_from_nfa(nfa.clone())
214 .map_err(BuildError::nfa)?;
215 debug!("BoundedBacktracker built");
216 Ok(Some(BoundedBacktrackerEngine(engine)))
217 }
218 #[cfg(not(feature = "nfa-backtrack"))]
219 {
220 Ok(None)
221 }
222 }
223
224 #[cfg_attr(feature = "perf-inline", inline(always))]
225 pub(crate) fn is_match(
226 &self,
227 cache: &mut BoundedBacktrackerCache,
228 input: &Input<'_>,
229 ) -> bool {
230 #[cfg(feature = "nfa-backtrack")]
231 {
232 // OK because we only permit access to this engine when we know
233 // the haystack is short enough for the backtracker to run without
234 // reporting an error.
235 self.0
236 .try_is_match(cache.0.as_mut().unwrap(), input.clone())
237 .unwrap()
238 }
239 #[cfg(not(feature = "nfa-backtrack"))]
240 {
241 // Impossible to reach because this engine is never constructed
242 // if the requisite features aren't enabled.
243 unreachable!()
244 }
245 }
246
247 #[cfg_attr(feature = "perf-inline", inline(always))]
248 pub(crate) fn search_slots(
249 &self,
250 cache: &mut BoundedBacktrackerCache,
251 input: &Input<'_>,
252 slots: &mut [Option<NonMaxUsize>],
253 ) -> Option<PatternID> {
254 #[cfg(feature = "nfa-backtrack")]
255 {
256 // OK because we only permit access to this engine when we know
257 // the haystack is short enough for the backtracker to run without
258 // reporting an error.
259 self.0
260 .try_search_slots(cache.0.as_mut().unwrap(), input, slots)
261 .unwrap()
262 }
263 #[cfg(not(feature = "nfa-backtrack"))]
264 {
265 // Impossible to reach because this engine is never constructed
266 // if the requisite features aren't enabled.
267 unreachable!()
268 }
269 }
270
271 #[cfg_attr(feature = "perf-inline", inline(always))]
272 fn max_haystack_len(&self) -> usize {
273 #[cfg(feature = "nfa-backtrack")]
274 {
275 self.0.max_haystack_len()
276 }
277 #[cfg(not(feature = "nfa-backtrack"))]
278 {
279 // Impossible to reach because this engine is never constructed
280 // if the requisite features aren't enabled.
281 unreachable!()
282 }
283 }
284 }
285
286 #[derive(Clone, Debug)]
287 pub(crate) struct BoundedBacktrackerCache(
288 #[cfg(feature = "nfa-backtrack")] Option<backtrack::Cache>,
289 #[cfg(not(feature = "nfa-backtrack"))] (),
290 );
291
292 impl BoundedBacktrackerCache {
293 pub(crate) fn none() -> BoundedBacktrackerCache {
294 #[cfg(feature = "nfa-backtrack")]
295 {
296 BoundedBacktrackerCache(None)
297 }
298 #[cfg(not(feature = "nfa-backtrack"))]
299 {
300 BoundedBacktrackerCache(())
301 }
302 }
303
304 pub(crate) fn new(
305 builder: &BoundedBacktracker,
306 ) -> BoundedBacktrackerCache {
307 #[cfg(feature = "nfa-backtrack")]
308 {
309 BoundedBacktrackerCache(
310 builder.0.as_ref().map(|e| e.0.create_cache()),
311 )
312 }
313 #[cfg(not(feature = "nfa-backtrack"))]
314 {
315 BoundedBacktrackerCache(())
316 }
317 }
318
319 pub(crate) fn reset(&mut self, builder: &BoundedBacktracker) {
320 #[cfg(feature = "nfa-backtrack")]
321 if let Some(ref e) = builder.0 {
322 self.0.as_mut().unwrap().reset(&e.0);
323 }
324 }
325
326 pub(crate) fn memory_usage(&self) -> usize {
327 #[cfg(feature = "nfa-backtrack")]
328 {
329 self.0.as_ref().map_or(0, |c| c.memory_usage())
330 }
331 #[cfg(not(feature = "nfa-backtrack"))]
332 {
333 0
334 }
335 }
336 }
337
338 #[derive(Debug)]
339 pub(crate) struct OnePass(Option<OnePassEngine>);
340
341 impl OnePass {
342 pub(crate) fn new(info: &RegexInfo, nfa: &NFA) -> OnePass {
343 OnePass(OnePassEngine::new(info, nfa))
344 }
345
346 pub(crate) fn create_cache(&self) -> OnePassCache {
347 OnePassCache::new(self)
348 }
349
350 #[cfg_attr(feature = "perf-inline", inline(always))]
351 pub(crate) fn get(&self, input: &Input<'_>) -> Option<&OnePassEngine> {
352 let engine = self.0.as_ref()?;
353 if !input.get_anchored().is_anchored()
354 && !engine.get_nfa().is_always_start_anchored()
355 {
356 return None;
357 }
358 Some(engine)
359 }
360
361 pub(crate) fn memory_usage(&self) -> usize {
362 self.0.as_ref().map_or(0, |e| e.memory_usage())
363 }
364 }
365
366 #[derive(Debug)]
367 pub(crate) struct OnePassEngine(
368 #[cfg(feature = "dfa-onepass")] onepass::DFA,
369 #[cfg(not(feature = "dfa-onepass"))] (),
370 );
371
372 impl OnePassEngine {
373 pub(crate) fn new(info: &RegexInfo, nfa: &NFA) -> Option<OnePassEngine> {
374 #[cfg(feature = "dfa-onepass")]
375 {
376 if !info.config().get_onepass() {
377 return None;
378 }
379 // In order to even attempt building a one-pass DFA, we require
380 // that we either have at least one explicit capturing group or
381 // there's a Unicode word boundary somewhere. If we don't have
382 // either of these things, then the lazy DFA will almost certainly
383 // be useable and be much faster. The only case where it might
384 // not is if the lazy DFA isn't utilizing its cache effectively,
385 // but in those cases, the underlying regex is almost certainly
386 // not one-pass or is too big to fit within the current one-pass
387 // implementation limits.
388 if info.props_union().explicit_captures_len() == 0
389 && !info.props_union().look_set().contains_word_unicode()
390 {
391 debug!("not building OnePass because it isn't worth it");
392 return None;
393 }
394 let onepass_config = onepass::Config::new()
395 .match_kind(info.config().get_match_kind())
396 // Like for the lazy DFA, we unconditionally enable this
397 // because it doesn't cost much and makes the API more
398 // flexible.
399 .starts_for_each_pattern(true)
400 .byte_classes(info.config().get_byte_classes())
401 .size_limit(info.config().get_onepass_size_limit());
402 let result = onepass::Builder::new()
403 .configure(onepass_config)
404 .build_from_nfa(nfa.clone());
405 let engine = match result {
406 Ok(engine) => engine,
407 Err(_err) => {
408 debug!("OnePass failed to build: {}", _err);
409 return None;
410 }
411 };
412 debug!("OnePass built, {} bytes", engine.memory_usage());
413 Some(OnePassEngine(engine))
414 }
415 #[cfg(not(feature = "dfa-onepass"))]
416 {
417 None
418 }
419 }
420
421 #[cfg_attr(feature = "perf-inline", inline(always))]
422 pub(crate) fn search_slots(
423 &self,
424 cache: &mut OnePassCache,
425 input: &Input<'_>,
426 slots: &mut [Option<NonMaxUsize>],
427 ) -> Option<PatternID> {
428 #[cfg(feature = "dfa-onepass")]
429 {
430 // OK because we only permit getting a OnePassEngine when we know
431 // the search is anchored and thus an error cannot occur.
432 self.0
433 .try_search_slots(cache.0.as_mut().unwrap(), input, slots)
434 .unwrap()
435 }
436 #[cfg(not(feature = "dfa-onepass"))]
437 {
438 // Impossible to reach because this engine is never constructed
439 // if the requisite features aren't enabled.
440 unreachable!()
441 }
442 }
443
444 pub(crate) fn memory_usage(&self) -> usize {
445 #[cfg(feature = "dfa-onepass")]
446 {
447 self.0.memory_usage()
448 }
449 #[cfg(not(feature = "dfa-onepass"))]
450 {
451 // Impossible to reach because this engine is never constructed
452 // if the requisite features aren't enabled.
453 unreachable!()
454 }
455 }
456
457 #[cfg_attr(feature = "perf-inline", inline(always))]
458 fn get_nfa(&self) -> &NFA {
459 #[cfg(feature = "dfa-onepass")]
460 {
461 self.0.get_nfa()
462 }
463 #[cfg(not(feature = "dfa-onepass"))]
464 {
465 // Impossible to reach because this engine is never constructed
466 // if the requisite features aren't enabled.
467 unreachable!()
468 }
469 }
470 }
471
472 #[derive(Clone, Debug)]
473 pub(crate) struct OnePassCache(
474 #[cfg(feature = "dfa-onepass")] Option<onepass::Cache>,
475 #[cfg(not(feature = "dfa-onepass"))] (),
476 );
477
478 impl OnePassCache {
479 pub(crate) fn none() -> OnePassCache {
480 #[cfg(feature = "dfa-onepass")]
481 {
482 OnePassCache(None)
483 }
484 #[cfg(not(feature = "dfa-onepass"))]
485 {
486 OnePassCache(())
487 }
488 }
489
490 pub(crate) fn new(builder: &OnePass) -> OnePassCache {
491 #[cfg(feature = "dfa-onepass")]
492 {
493 OnePassCache(builder.0.as_ref().map(|e| e.0.create_cache()))
494 }
495 #[cfg(not(feature = "dfa-onepass"))]
496 {
497 OnePassCache(())
498 }
499 }
500
501 pub(crate) fn reset(&mut self, builder: &OnePass) {
502 #[cfg(feature = "dfa-onepass")]
503 if let Some(ref e) = builder.0 {
504 self.0.as_mut().unwrap().reset(&e.0);
505 }
506 }
507
508 pub(crate) fn memory_usage(&self) -> usize {
509 #[cfg(feature = "dfa-onepass")]
510 {
511 self.0.as_ref().map_or(0, |c| c.memory_usage())
512 }
513 #[cfg(not(feature = "dfa-onepass"))]
514 {
515 0
516 }
517 }
518 }
519
520 #[derive(Debug)]
521 pub(crate) struct Hybrid(Option<HybridEngine>);
522
523 impl Hybrid {
524 pub(crate) fn none() -> Hybrid {
525 Hybrid(None)
526 }
527
528 pub(crate) fn new(
529 info: &RegexInfo,
530 pre: Option<Prefilter>,
531 nfa: &NFA,
532 nfarev: &NFA,
533 ) -> Hybrid {
534 Hybrid(HybridEngine::new(info, pre, nfa, nfarev))
535 }
536
537 pub(crate) fn create_cache(&self) -> HybridCache {
538 HybridCache::new(self)
539 }
540
541 #[cfg_attr(feature = "perf-inline", inline(always))]
542 pub(crate) fn get(&self, _input: &Input<'_>) -> Option<&HybridEngine> {
543 let engine = self.0.as_ref()?;
544 Some(engine)
545 }
546
547 pub(crate) fn is_some(&self) -> bool {
548 self.0.is_some()
549 }
550 }
551
552 #[derive(Debug)]
553 pub(crate) struct HybridEngine(
554 #[cfg(feature = "hybrid")] hybrid::regex::Regex,
555 #[cfg(not(feature = "hybrid"))] (),
556 );
557
558 impl HybridEngine {
559 pub(crate) fn new(
560 info: &RegexInfo,
561 pre: Option<Prefilter>,
562 nfa: &NFA,
563 nfarev: &NFA,
564 ) -> Option<HybridEngine> {
565 #[cfg(feature = "hybrid")]
566 {
567 if !info.config().get_hybrid() {
568 return None;
569 }
570 let dfa_config = hybrid::dfa::Config::new()
571 .match_kind(info.config().get_match_kind())
572 .prefilter(pre.clone())
573 // Enabling this is necessary for ensuring we can service any
574 // kind of 'Input' search without error. For the lazy DFA,
575 // this is not particularly costly, since the start states are
576 // generated lazily.
577 .starts_for_each_pattern(true)
578 .byte_classes(info.config().get_byte_classes())
579 .unicode_word_boundary(true)
580 .specialize_start_states(pre.is_some())
581 .cache_capacity(info.config().get_hybrid_cache_capacity())
582 // This makes it possible for building a lazy DFA to
583 // fail even though the NFA has already been built. Namely,
584 // if the cache capacity is too small to fit some minimum
585 // number of states (which is small, like 4 or 5), then the
586 // DFA will refuse to build.
587 //
588 // We shouldn't enable this to make building always work, since
589 // this could cause the allocation of a cache bigger than the
590 // provided capacity amount.
591 //
592 // This is effectively the only reason why building a lazy DFA
593 // could fail. If it does, then we simply suppress the error
594 // and return None.
595 .skip_cache_capacity_check(false)
596 // This and enabling heuristic Unicode word boundary support
597 // above make it so the lazy DFA can quit at match time.
598 .minimum_cache_clear_count(Some(3))
599 .minimum_bytes_per_state(Some(10));
600 let result = hybrid::dfa::Builder::new()
601 .configure(dfa_config.clone())
602 .build_from_nfa(nfa.clone());
603 let fwd = match result {
604 Ok(fwd) => fwd,
605 Err(_err) => {
606 debug!("forward lazy DFA failed to build: {}", _err);
607 return None;
608 }
609 };
610 let result = hybrid::dfa::Builder::new()
611 .configure(
612 dfa_config
613 .clone()
614 .match_kind(MatchKind::All)
615 .prefilter(None)
616 .specialize_start_states(false),
617 )
618 .build_from_nfa(nfarev.clone());
619 let rev = match result {
620 Ok(rev) => rev,
621 Err(_err) => {
622 debug!("reverse lazy DFA failed to build: {}", _err);
623 return None;
624 }
625 };
626 let engine =
627 hybrid::regex::Builder::new().build_from_dfas(fwd, rev);
628 debug!("lazy DFA built");
629 Some(HybridEngine(engine))
630 }
631 #[cfg(not(feature = "hybrid"))]
632 {
633 None
634 }
635 }
636
637 #[cfg_attr(feature = "perf-inline", inline(always))]
638 pub(crate) fn try_search(
639 &self,
640 cache: &mut HybridCache,
641 input: &Input<'_>,
642 ) -> Result<Option<Match>, RetryFailError> {
643 #[cfg(feature = "hybrid")]
644 {
645 let cache = cache.0.as_mut().unwrap();
646 self.0.try_search(cache, input).map_err(|e| e.into())
647 }
648 #[cfg(not(feature = "hybrid"))]
649 {
650 // Impossible to reach because this engine is never constructed
651 // if the requisite features aren't enabled.
652 unreachable!()
653 }
654 }
655
656 #[cfg_attr(feature = "perf-inline", inline(always))]
657 pub(crate) fn try_search_half_fwd(
658 &self,
659 cache: &mut HybridCache,
660 input: &Input<'_>,
661 ) -> Result<Option<HalfMatch>, RetryFailError> {
662 #[cfg(feature = "hybrid")]
663 {
664 let fwd = self.0.forward();
665 let mut fwdcache = cache.0.as_mut().unwrap().as_parts_mut().0;
666 fwd.try_search_fwd(&mut fwdcache, input).map_err(|e| e.into())
667 }
668 #[cfg(not(feature = "hybrid"))]
669 {
670 // Impossible to reach because this engine is never constructed
671 // if the requisite features aren't enabled.
672 unreachable!()
673 }
674 }
675
676 #[cfg_attr(feature = "perf-inline", inline(always))]
677 pub(crate) fn try_search_half_fwd_stopat(
678 &self,
679 cache: &mut HybridCache,
680 input: &Input<'_>,
681 ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
682 #[cfg(feature = "hybrid")]
683 {
684 let dfa = self.0.forward();
685 let mut cache = cache.0.as_mut().unwrap().as_parts_mut().0;
686 crate::meta::stopat::hybrid_try_search_half_fwd(
687 dfa, &mut cache, input,
688 )
689 }
690 #[cfg(not(feature = "hybrid"))]
691 {
692 // Impossible to reach because this engine is never constructed
693 // if the requisite features aren't enabled.
694 unreachable!()
695 }
696 }
697
698 #[cfg_attr(feature = "perf-inline", inline(always))]
699 pub(crate) fn try_search_half_rev(
700 &self,
701 cache: &mut HybridCache,
702 input: &Input<'_>,
703 ) -> Result<Option<HalfMatch>, RetryFailError> {
704 #[cfg(feature = "hybrid")]
705 {
706 let rev = self.0.reverse();
707 let mut revcache = cache.0.as_mut().unwrap().as_parts_mut().1;
708 rev.try_search_rev(&mut revcache, input).map_err(|e| e.into())
709 }
710 #[cfg(not(feature = "hybrid"))]
711 {
712 // Impossible to reach because this engine is never constructed
713 // if the requisite features aren't enabled.
714 unreachable!()
715 }
716 }
717
718 #[cfg_attr(feature = "perf-inline", inline(always))]
719 pub(crate) fn try_search_half_rev_limited(
720 &self,
721 cache: &mut HybridCache,
722 input: &Input<'_>,
723 min_start: usize,
724 ) -> Result<Option<HalfMatch>, RetryError> {
725 #[cfg(feature = "hybrid")]
726 {
727 let dfa = self.0.reverse();
728 let mut cache = cache.0.as_mut().unwrap().as_parts_mut().1;
729 crate::meta::limited::hybrid_try_search_half_rev(
730 dfa, &mut cache, input, min_start,
731 )
732 }
733 #[cfg(not(feature = "hybrid"))]
734 {
735 // Impossible to reach because this engine is never constructed
736 // if the requisite features aren't enabled.
737 unreachable!()
738 }
739 }
740
741 #[inline]
742 pub(crate) fn try_which_overlapping_matches(
743 &self,
744 cache: &mut HybridCache,
745 input: &Input<'_>,
746 patset: &mut PatternSet,
747 ) -> Result<(), RetryFailError> {
748 #[cfg(feature = "hybrid")]
749 {
750 let fwd = self.0.forward();
751 let mut fwdcache = cache.0.as_mut().unwrap().as_parts_mut().0;
752 fwd.try_which_overlapping_matches(&mut fwdcache, input, patset)
753 .map_err(|e| e.into())
754 }
755 #[cfg(not(feature = "hybrid"))]
756 {
757 // Impossible to reach because this engine is never constructed
758 // if the requisite features aren't enabled.
759 unreachable!()
760 }
761 }
762 }
763
764 #[derive(Clone, Debug)]
765 pub(crate) struct HybridCache(
766 #[cfg(feature = "hybrid")] Option<hybrid::regex::Cache>,
767 #[cfg(not(feature = "hybrid"))] (),
768 );
769
770 impl HybridCache {
771 pub(crate) fn none() -> HybridCache {
772 #[cfg(feature = "hybrid")]
773 {
774 HybridCache(None)
775 }
776 #[cfg(not(feature = "hybrid"))]
777 {
778 HybridCache(())
779 }
780 }
781
782 pub(crate) fn new(builder: &Hybrid) -> HybridCache {
783 #[cfg(feature = "hybrid")]
784 {
785 HybridCache(builder.0.as_ref().map(|e| e.0.create_cache()))
786 }
787 #[cfg(not(feature = "hybrid"))]
788 {
789 HybridCache(())
790 }
791 }
792
793 pub(crate) fn reset(&mut self, builder: &Hybrid) {
794 #[cfg(feature = "hybrid")]
795 if let Some(ref e) = builder.0 {
796 self.0.as_mut().unwrap().reset(&e.0);
797 }
798 }
799
800 pub(crate) fn memory_usage(&self) -> usize {
801 #[cfg(feature = "hybrid")]
802 {
803 self.0.as_ref().map_or(0, |c| c.memory_usage())
804 }
805 #[cfg(not(feature = "hybrid"))]
806 {
807 0
808 }
809 }
810 }
811
812 #[derive(Debug)]
813 pub(crate) struct DFA(Option<DFAEngine>);
814
815 impl DFA {
816 pub(crate) fn none() -> DFA {
817 DFA(None)
818 }
819
820 pub(crate) fn new(
821 info: &RegexInfo,
822 pre: Option<Prefilter>,
823 nfa: &NFA,
824 nfarev: &NFA,
825 ) -> DFA {
826 DFA(DFAEngine::new(info, pre, nfa, nfarev))
827 }
828
829 #[cfg_attr(feature = "perf-inline", inline(always))]
830 pub(crate) fn get(&self, _input: &Input<'_>) -> Option<&DFAEngine> {
831 let engine = self.0.as_ref()?;
832 Some(engine)
833 }
834
835 pub(crate) fn is_some(&self) -> bool {
836 self.0.is_some()
837 }
838
839 pub(crate) fn memory_usage(&self) -> usize {
840 self.0.as_ref().map_or(0, |e| e.memory_usage())
841 }
842 }
843
844 #[derive(Debug)]
845 pub(crate) struct DFAEngine(
846 #[cfg(feature = "dfa-build")] dfa::regex::Regex,
847 #[cfg(not(feature = "dfa-build"))] (),
848 );
849
850 impl DFAEngine {
851 pub(crate) fn new(
852 info: &RegexInfo,
853 pre: Option<Prefilter>,
854 nfa: &NFA,
855 nfarev: &NFA,
856 ) -> Option<DFAEngine> {
857 #[cfg(feature = "dfa-build")]
858 {
859 if !info.config().get_dfa() {
860 return None;
861 }
862 // If our NFA is anything but small, don't even bother with a DFA.
863 if let Some(state_limit) = info.config().get_dfa_state_limit() {
864 if nfa.states().len() > state_limit {
865 debug!(
866 "skipping full DFA because NFA has {} states, \
867 which exceeds the heuristic limit of {}",
868 nfa.states().len(),
869 state_limit,
870 );
871 return None;
872 }
873 }
874 // We cut the size limit in four because the total heap used by
875 // DFA construction is determinization aux memory and the DFA
876 // itself, and those things are configured independently in the
877 // lower level DFA builder API. And then split that in two because
878 // of forward and reverse DFAs.
879 let size_limit = info.config().get_dfa_size_limit().map(|n| n / 4);
880 let dfa_config = dfa::dense::Config::new()
881 .match_kind(info.config().get_match_kind())
882 .prefilter(pre.clone())
883 // Enabling this is necessary for ensuring we can service any
884 // kind of 'Input' search without error. For the full DFA, this
885 // can be quite costly. But since we have such a small bound
886 // on the size of the DFA, in practice, any multl-regexes are
887 // probably going to blow the limit anyway.
888 .starts_for_each_pattern(true)
889 .byte_classes(info.config().get_byte_classes())
890 .unicode_word_boundary(true)
891 .specialize_start_states(pre.is_some())
892 .determinize_size_limit(size_limit)
893 .dfa_size_limit(size_limit);
894 let result = dfa::dense::Builder::new()
895 .configure(dfa_config.clone())
896 .build_from_nfa(&nfa);
897 let fwd = match result {
898 Ok(fwd) => fwd,
899 Err(_err) => {
900 debug!("forward full DFA failed to build: {}", _err);
901 return None;
902 }
903 };
904 let result = dfa::dense::Builder::new()
905 .configure(
906 dfa_config
907 .clone()
908 // We never need unanchored reverse searches, so
909 // there's no point in building it into the DFA, which
910 // WILL take more space. (This isn't done for the lazy
911 // DFA because the DFA is, well, lazy. It doesn't pay
912 // the cost for supporting unanchored searches unless
913 // you actually do an unanchored search, which we
914 // don't.)
915 .start_kind(dfa::StartKind::Anchored)
916 .match_kind(MatchKind::All)
917 .prefilter(None)
918 .specialize_start_states(false),
919 )
920 .build_from_nfa(&nfarev);
921 let rev = match result {
922 Ok(rev) => rev,
923 Err(_err) => {
924 debug!("reverse full DFA failed to build: {}", _err);
925 return None;
926 }
927 };
928 let engine = dfa::regex::Builder::new().build_from_dfas(fwd, rev);
929 debug!(
930 "fully compiled forward and reverse DFAs built, {} bytes",
931 engine.forward().memory_usage()
932 + engine.reverse().memory_usage(),
933 );
934 Some(DFAEngine(engine))
935 }
936 #[cfg(not(feature = "dfa-build"))]
937 {
938 None
939 }
940 }
941
942 #[cfg_attr(feature = "perf-inline", inline(always))]
943 pub(crate) fn try_search(
944 &self,
945 input: &Input<'_>,
946 ) -> Result<Option<Match>, RetryFailError> {
947 #[cfg(feature = "dfa-build")]
948 {
949 self.0.try_search(input).map_err(|e| e.into())
950 }
951 #[cfg(not(feature = "dfa-build"))]
952 {
953 // Impossible to reach because this engine is never constructed
954 // if the requisite features aren't enabled.
955 unreachable!()
956 }
957 }
958
959 #[cfg_attr(feature = "perf-inline", inline(always))]
960 pub(crate) fn try_search_half_fwd(
961 &self,
962 input: &Input<'_>,
963 ) -> Result<Option<HalfMatch>, RetryFailError> {
964 #[cfg(feature = "dfa-build")]
965 {
966 use crate::dfa::Automaton;
967 self.0.forward().try_search_fwd(input).map_err(|e| e.into())
968 }
969 #[cfg(not(feature = "dfa-build"))]
970 {
971 // Impossible to reach because this engine is never constructed
972 // if the requisite features aren't enabled.
973 unreachable!()
974 }
975 }
976
977 #[cfg_attr(feature = "perf-inline", inline(always))]
978 pub(crate) fn try_search_half_fwd_stopat(
979 &self,
980 input: &Input<'_>,
981 ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
982 #[cfg(feature = "dfa-build")]
983 {
984 let dfa = self.0.forward();
985 crate::meta::stopat::dfa_try_search_half_fwd(dfa, input)
986 }
987 #[cfg(not(feature = "dfa-build"))]
988 {
989 // Impossible to reach because this engine is never constructed
990 // if the requisite features aren't enabled.
991 unreachable!()
992 }
993 }
994
995 #[cfg_attr(feature = "perf-inline", inline(always))]
996 pub(crate) fn try_search_half_rev(
997 &self,
998 input: &Input<'_>,
999 ) -> Result<Option<HalfMatch>, RetryFailError> {
1000 #[cfg(feature = "dfa-build")]
1001 {
1002 use crate::dfa::Automaton;
1003 self.0.reverse().try_search_rev(&input).map_err(|e| e.into())
1004 }
1005 #[cfg(not(feature = "dfa-build"))]
1006 {
1007 // Impossible to reach because this engine is never constructed
1008 // if the requisite features aren't enabled.
1009 unreachable!()
1010 }
1011 }
1012
1013 #[cfg_attr(feature = "perf-inline", inline(always))]
1014 pub(crate) fn try_search_half_rev_limited(
1015 &self,
1016 input: &Input<'_>,
1017 min_start: usize,
1018 ) -> Result<Option<HalfMatch>, RetryError> {
1019 #[cfg(feature = "dfa-build")]
1020 {
1021 let dfa = self.0.reverse();
1022 crate::meta::limited::dfa_try_search_half_rev(
1023 dfa, input, min_start,
1024 )
1025 }
1026 #[cfg(not(feature = "dfa-build"))]
1027 {
1028 // Impossible to reach because this engine is never constructed
1029 // if the requisite features aren't enabled.
1030 unreachable!()
1031 }
1032 }
1033
1034 #[inline]
1035 pub(crate) fn try_which_overlapping_matches(
1036 &self,
1037 input: &Input<'_>,
1038 patset: &mut PatternSet,
1039 ) -> Result<(), RetryFailError> {
1040 #[cfg(feature = "dfa-build")]
1041 {
1042 use crate::dfa::Automaton;
1043 self.0
1044 .forward()
1045 .try_which_overlapping_matches(input, patset)
1046 .map_err(|e| e.into())
1047 }
1048 #[cfg(not(feature = "dfa-build"))]
1049 {
1050 // Impossible to reach because this engine is never constructed
1051 // if the requisite features aren't enabled.
1052 unreachable!()
1053 }
1054 }
1055
1056 pub(crate) fn memory_usage(&self) -> usize {
1057 #[cfg(feature = "dfa-build")]
1058 {
1059 self.0.forward().memory_usage() + self.0.reverse().memory_usage()
1060 }
1061 #[cfg(not(feature = "dfa-build"))]
1062 {
1063 // Impossible to reach because this engine is never constructed
1064 // if the requisite features aren't enabled.
1065 unreachable!()
1066 }
1067 }
1068 }
1069
1070 #[derive(Debug)]
1071 pub(crate) struct ReverseHybrid(Option<ReverseHybridEngine>);
1072
1073 impl ReverseHybrid {
1074 pub(crate) fn none() -> ReverseHybrid {
1075 ReverseHybrid(None)
1076 }
1077
1078 pub(crate) fn new(info: &RegexInfo, nfarev: &NFA) -> ReverseHybrid {
1079 ReverseHybrid(ReverseHybridEngine::new(info, nfarev))
1080 }
1081
1082 pub(crate) fn create_cache(&self) -> ReverseHybridCache {
1083 ReverseHybridCache::new(self)
1084 }
1085
1086 #[cfg_attr(feature = "perf-inline", inline(always))]
1087 pub(crate) fn get(
1088 &self,
1089 _input: &Input<'_>,
1090 ) -> Option<&ReverseHybridEngine> {
1091 let engine = self.0.as_ref()?;
1092 Some(engine)
1093 }
1094 }
1095
1096 #[derive(Debug)]
1097 pub(crate) struct ReverseHybridEngine(
1098 #[cfg(feature = "hybrid")] hybrid::dfa::DFA,
1099 #[cfg(not(feature = "hybrid"))] (),
1100 );
1101
1102 impl ReverseHybridEngine {
1103 pub(crate) fn new(
1104 info: &RegexInfo,
1105 nfarev: &NFA,
1106 ) -> Option<ReverseHybridEngine> {
1107 #[cfg(feature = "hybrid")]
1108 {
1109 if !info.config().get_hybrid() {
1110 return None;
1111 }
1112 // Since we only use this for reverse searches, we can hard-code
1113 // a number of things like match semantics, prefilters, starts
1114 // for each pattern and so on.
1115 let dfa_config = hybrid::dfa::Config::new()
1116 .match_kind(MatchKind::All)
1117 .prefilter(None)
1118 .starts_for_each_pattern(false)
1119 .byte_classes(info.config().get_byte_classes())
1120 .unicode_word_boundary(true)
1121 .specialize_start_states(false)
1122 .cache_capacity(info.config().get_hybrid_cache_capacity())
1123 .skip_cache_capacity_check(false)
1124 .minimum_cache_clear_count(Some(3))
1125 .minimum_bytes_per_state(Some(10));
1126 let result = hybrid::dfa::Builder::new()
1127 .configure(dfa_config)
1128 .build_from_nfa(nfarev.clone());
1129 let rev = match result {
1130 Ok(rev) => rev,
1131 Err(_err) => {
1132 debug!("lazy reverse DFA failed to build: {}", _err);
1133 return None;
1134 }
1135 };
1136 debug!("lazy reverse DFA built");
1137 Some(ReverseHybridEngine(rev))
1138 }
1139 #[cfg(not(feature = "hybrid"))]
1140 {
1141 None
1142 }
1143 }
1144
1145 #[cfg_attr(feature = "perf-inline", inline(always))]
1146 pub(crate) fn try_search_half_rev_limited(
1147 &self,
1148 cache: &mut ReverseHybridCache,
1149 input: &Input<'_>,
1150 min_start: usize,
1151 ) -> Result<Option<HalfMatch>, RetryError> {
1152 #[cfg(feature = "hybrid")]
1153 {
1154 let dfa = &self.0;
1155 let mut cache = cache.0.as_mut().unwrap();
1156 crate::meta::limited::hybrid_try_search_half_rev(
1157 dfa, &mut cache, input, min_start,
1158 )
1159 }
1160 #[cfg(not(feature = "hybrid"))]
1161 {
1162 // Impossible to reach because this engine is never constructed
1163 // if the requisite features aren't enabled.
1164 unreachable!()
1165 }
1166 }
1167 }
1168
1169 #[derive(Clone, Debug)]
1170 pub(crate) struct ReverseHybridCache(
1171 #[cfg(feature = "hybrid")] Option<hybrid::dfa::Cache>,
1172 #[cfg(not(feature = "hybrid"))] (),
1173 );
1174
1175 impl ReverseHybridCache {
1176 pub(crate) fn none() -> ReverseHybridCache {
1177 #[cfg(feature = "hybrid")]
1178 {
1179 ReverseHybridCache(None)
1180 }
1181 #[cfg(not(feature = "hybrid"))]
1182 {
1183 ReverseHybridCache(())
1184 }
1185 }
1186
1187 pub(crate) fn new(builder: &ReverseHybrid) -> ReverseHybridCache {
1188 #[cfg(feature = "hybrid")]
1189 {
1190 ReverseHybridCache(builder.0.as_ref().map(|e| e.0.create_cache()))
1191 }
1192 #[cfg(not(feature = "hybrid"))]
1193 {
1194 ReverseHybridCache(())
1195 }
1196 }
1197
1198 pub(crate) fn reset(&mut self, builder: &ReverseHybrid) {
1199 #[cfg(feature = "hybrid")]
1200 if let Some(ref e) = builder.0 {
1201 self.0.as_mut().unwrap().reset(&e.0);
1202 }
1203 }
1204
1205 pub(crate) fn memory_usage(&self) -> usize {
1206 #[cfg(feature = "hybrid")]
1207 {
1208 self.0.as_ref().map_or(0, |c| c.memory_usage())
1209 }
1210 #[cfg(not(feature = "hybrid"))]
1211 {
1212 0
1213 }
1214 }
1215 }
1216
1217 #[derive(Debug)]
1218 pub(crate) struct ReverseDFA(Option<ReverseDFAEngine>);
1219
1220 impl ReverseDFA {
1221 pub(crate) fn none() -> ReverseDFA {
1222 ReverseDFA(None)
1223 }
1224
1225 pub(crate) fn new(info: &RegexInfo, nfarev: &NFA) -> ReverseDFA {
1226 ReverseDFA(ReverseDFAEngine::new(info, nfarev))
1227 }
1228
1229 #[cfg_attr(feature = "perf-inline", inline(always))]
1230 pub(crate) fn get(&self, _input: &Input<'_>) -> Option<&ReverseDFAEngine> {
1231 let engine = self.0.as_ref()?;
1232 Some(engine)
1233 }
1234
1235 pub(crate) fn is_some(&self) -> bool {
1236 self.0.is_some()
1237 }
1238
1239 pub(crate) fn memory_usage(&self) -> usize {
1240 self.0.as_ref().map_or(0, |e| e.memory_usage())
1241 }
1242 }
1243
1244 #[derive(Debug)]
1245 pub(crate) struct ReverseDFAEngine(
1246 #[cfg(feature = "dfa-build")] dfa::dense::DFA<Vec<u32>>,
1247 #[cfg(not(feature = "dfa-build"))] (),
1248 );
1249
1250 impl ReverseDFAEngine {
1251 pub(crate) fn new(
1252 info: &RegexInfo,
1253 nfarev: &NFA,
1254 ) -> Option<ReverseDFAEngine> {
1255 #[cfg(feature = "dfa-build")]
1256 {
1257 if !info.config().get_dfa() {
1258 return None;
1259 }
1260 // If our NFA is anything but small, don't even bother with a DFA.
1261 if let Some(state_limit) = info.config().get_dfa_state_limit() {
1262 if nfarev.states().len() > state_limit {
1263 debug!(
1264 "skipping full reverse DFA because NFA has {} states, \
1265 which exceeds the heuristic limit of {}",
1266 nfarev.states().len(),
1267 state_limit,
1268 );
1269 return None;
1270 }
1271 }
1272 // We cut the size limit in two because the total heap used by DFA
1273 // construction is determinization aux memory and the DFA itself,
1274 // and those things are configured independently in the lower level
1275 // DFA builder API.
1276 let size_limit = info.config().get_dfa_size_limit().map(|n| n / 2);
1277 // Since we only use this for reverse searches, we can hard-code
1278 // a number of things like match semantics, prefilters, starts
1279 // for each pattern and so on. We also disable acceleration since
1280 // it's incompatible with limited searches (which is the only
1281 // operation we support for this kind of engine at the moment).
1282 let dfa_config = dfa::dense::Config::new()
1283 .match_kind(MatchKind::All)
1284 .prefilter(None)
1285 .accelerate(false)
1286 .start_kind(dfa::StartKind::Anchored)
1287 .starts_for_each_pattern(false)
1288 .byte_classes(info.config().get_byte_classes())
1289 .unicode_word_boundary(true)
1290 .specialize_start_states(false)
1291 .determinize_size_limit(size_limit)
1292 .dfa_size_limit(size_limit);
1293 let result = dfa::dense::Builder::new()
1294 .configure(dfa_config)
1295 .build_from_nfa(&nfarev);
1296 let rev = match result {
1297 Ok(rev) => rev,
1298 Err(_err) => {
1299 debug!("full reverse DFA failed to build: {}", _err);
1300 return None;
1301 }
1302 };
1303 debug!(
1304 "fully compiled reverse DFA built, {} bytes",
1305 rev.memory_usage()
1306 );
1307 Some(ReverseDFAEngine(rev))
1308 }
1309 #[cfg(not(feature = "dfa-build"))]
1310 {
1311 None
1312 }
1313 }
1314
1315 #[cfg_attr(feature = "perf-inline", inline(always))]
1316 pub(crate) fn try_search_half_rev_limited(
1317 &self,
1318 input: &Input<'_>,
1319 min_start: usize,
1320 ) -> Result<Option<HalfMatch>, RetryError> {
1321 #[cfg(feature = "dfa-build")]
1322 {
1323 let dfa = &self.0;
1324 crate::meta::limited::dfa_try_search_half_rev(
1325 dfa, input, min_start,
1326 )
1327 }
1328 #[cfg(not(feature = "dfa-build"))]
1329 {
1330 // Impossible to reach because this engine is never constructed
1331 // if the requisite features aren't enabled.
1332 unreachable!()
1333 }
1334 }
1335
1336 pub(crate) fn memory_usage(&self) -> usize {
1337 #[cfg(feature = "dfa-build")]
1338 {
1339 self.0.memory_usage()
1340 }
1341 #[cfg(not(feature = "dfa-build"))]
1342 {
1343 // Impossible to reach because this engine is never constructed
1344 // if the requisite features aren't enabled.
1345 unreachable!()
1346 }
1347 }
1348 }