regex_automata/nfa/thompson/pikevm.rs
1/*!
2An NFA backed Pike VM for executing regex searches with capturing groups.
3
4This module provides a [`PikeVM`] that works by simulating an NFA and
5resolving all spans of capturing groups that participate in a match.
6*/
7
8#[cfg(feature = "internal-instrument-pikevm")]
9use core::cell::RefCell;
10
11use alloc::{vec, vec::Vec};
12
13use crate::{
14 nfa::thompson::{self, BuildError, State, NFA},
15 util::{
16 captures::Captures,
17 empty, iter,
18 prefilter::Prefilter,
19 primitives::{NonMaxUsize, PatternID, SmallIndex, StateID},
20 search::{
21 Anchored, HalfMatch, Input, Match, MatchKind, PatternSet, Span,
22 },
23 sparse_set::SparseSet,
24 },
25};
26
27/// A simple macro for conditionally executing instrumentation logic when
28/// the 'trace' log level is enabled. This is a compile-time no-op when the
29/// 'internal-instrument-pikevm' feature isn't enabled. The intent here is that
30/// this makes it easier to avoid doing extra work when instrumentation isn't
31/// enabled.
32///
33/// This macro accepts a closure of type `|&mut Counters|`. The closure can
34/// then increment counters (or whatever) in accordance with what one wants
35/// to track.
36macro_rules! instrument {
37 ($fun:expr) => {
38 #[cfg(feature = "internal-instrument-pikevm")]
39 {
40 let fun: &mut dyn FnMut(&mut Counters) = &mut $fun;
41 COUNTERS.with(|c: &RefCell<Counters>| fun(&mut *c.borrow_mut()));
42 }
43 };
44}
45
46#[cfg(feature = "internal-instrument-pikevm")]
47std::thread_local! {
48 /// Effectively global state used to keep track of instrumentation
49 /// counters. The "proper" way to do this is to thread it through the
50 /// PikeVM, but it makes the code quite icky. Since this is just a
51 /// debugging feature, we're content to relegate it to thread local
52 /// state. When instrumentation is enabled, the counters are reset at the
53 /// beginning of every search and printed (with the 'trace' log level) at
54 /// the end of every search.
55 static COUNTERS: RefCell<Counters> = RefCell::new(Counters::empty());
56}
57
58/// The configuration used for building a [`PikeVM`].
59///
60/// A PikeVM configuration is a simple data object that is typically used with
61/// [`Builder::configure`]. It can be cheaply cloned.
62///
63/// A default configuration can be created either with `Config::new`, or
64/// perhaps more conveniently, with [`PikeVM::config`].
65#[derive(Clone, Debug, Default)]
66pub struct Config {
67 match_kind: Option<MatchKind>,
68 pre: Option<Option<Prefilter>>,
69}
70
71impl Config {
72 /// Return a new default PikeVM configuration.
73 pub fn new() -> Config {
74 Config::default()
75 }
76
77 /// Set the desired match semantics.
78 ///
79 /// The default is [`MatchKind::LeftmostFirst`], which corresponds to the
80 /// match semantics of Perl-like regex engines. That is, when multiple
81 /// patterns would match at the same leftmost position, the pattern that
82 /// appears first in the concrete syntax is chosen.
83 ///
84 /// Currently, the only other kind of match semantics supported is
85 /// [`MatchKind::All`]. This corresponds to "classical DFA" construction
86 /// where all possible matches are visited in the NFA by the `PikeVM`.
87 ///
88 /// Typically, `All` is used when one wants to execute an overlapping
89 /// search and `LeftmostFirst` otherwise. In particular, it rarely makes
90 /// sense to use `All` with the various "leftmost" find routines, since the
91 /// leftmost routines depend on the `LeftmostFirst` automata construction
92 /// strategy. Specifically, `LeftmostFirst` results in the `PikeVM`
93 /// simulating dead states as a way to terminate the search and report a
94 /// match. `LeftmostFirst` also supports non-greedy matches using this
95 /// strategy where as `All` does not.
96 pub fn match_kind(mut self, kind: MatchKind) -> Config {
97 self.match_kind = Some(kind);
98 self
99 }
100
101 /// Set a prefilter to be used whenever a start state is entered.
102 ///
103 /// A [`Prefilter`] in this context is meant to accelerate searches by
104 /// looking for literal prefixes that every match for the corresponding
105 /// pattern (or patterns) must start with. Once a prefilter produces a
106 /// match, the underlying search routine continues on to try and confirm
107 /// the match.
108 ///
109 /// Be warned that setting a prefilter does not guarantee that the search
110 /// will be faster. While it's usually a good bet, if the prefilter
111 /// produces a lot of false positive candidates (i.e., positions matched
112 /// by the prefilter but not by the regex), then the overall result can
113 /// be slower than if you had just executed the regex engine without any
114 /// prefilters.
115 ///
116 /// By default no prefilter is set.
117 ///
118 /// # Example
119 ///
120 /// ```
121 /// use regex_automata::{
122 /// nfa::thompson::pikevm::PikeVM,
123 /// util::prefilter::Prefilter,
124 /// Input, Match, MatchKind,
125 /// };
126 ///
127 /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "bar"]);
128 /// let re = PikeVM::builder()
129 /// .configure(PikeVM::config().prefilter(pre))
130 /// .build(r"(foo|bar)[a-z]+")?;
131 /// let mut cache = re.create_cache();
132 /// let input = Input::new("foo1 barfox bar");
133 /// assert_eq!(Some(Match::must(0, 5..11)), re.find(&mut cache, input));
134 ///
135 /// # Ok::<(), Box<dyn std::error::Error>>(())
136 /// ```
137 ///
138 /// Be warned though that an incorrect prefilter can lead to incorrect
139 /// results!
140 ///
141 /// ```
142 /// use regex_automata::{
143 /// nfa::thompson::pikevm::PikeVM,
144 /// util::prefilter::Prefilter,
145 /// Input, HalfMatch, MatchKind,
146 /// };
147 ///
148 /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "car"]);
149 /// let re = PikeVM::builder()
150 /// .configure(PikeVM::config().prefilter(pre))
151 /// .build(r"(foo|bar)[a-z]+")?;
152 /// let mut cache = re.create_cache();
153 /// let input = Input::new("foo1 barfox bar");
154 /// // No match reported even though there clearly is one!
155 /// assert_eq!(None, re.find(&mut cache, input));
156 ///
157 /// # Ok::<(), Box<dyn std::error::Error>>(())
158 /// ```
159 pub fn prefilter(mut self, pre: Option<Prefilter>) -> Config {
160 self.pre = Some(pre);
161 self
162 }
163
164 /// Returns the match semantics set in this configuration.
165 pub fn get_match_kind(&self) -> MatchKind {
166 self.match_kind.unwrap_or(MatchKind::LeftmostFirst)
167 }
168
169 /// Returns the prefilter set in this configuration, if one at all.
170 pub fn get_prefilter(&self) -> Option<&Prefilter> {
171 self.pre.as_ref().unwrap_or(&None).as_ref()
172 }
173
174 /// Overwrite the default configuration such that the options in `o` are
175 /// always used. If an option in `o` is not set, then the corresponding
176 /// option in `self` is used. If it's not set in `self` either, then it
177 /// remains not set.
178 pub(crate) fn overwrite(&self, o: Config) -> Config {
179 Config {
180 match_kind: o.match_kind.or(self.match_kind),
181 pre: o.pre.or_else(|| self.pre.clone()),
182 }
183 }
184}
185
186/// A builder for a `PikeVM`.
187///
188/// This builder permits configuring options for the syntax of a pattern,
189/// the NFA construction and the `PikeVM` construction. This builder is
190/// different from a general purpose regex builder in that it permits fine
191/// grain configuration of the construction process. The trade off for this is
192/// complexity, and the possibility of setting a configuration that might not
193/// make sense. For example, there are two different UTF-8 modes:
194///
195/// * [`util::syntax::Config::utf8`](crate::util::syntax::Config::utf8)
196/// controls whether the pattern itself can contain sub-expressions that match
197/// invalid UTF-8.
198/// * [`thompson::Config::utf8`] controls whether empty matches that split a
199/// Unicode codepoint are reported or not.
200///
201/// Generally speaking, callers will want to either enable all of these or
202/// disable all of these.
203///
204/// # Example
205///
206/// This example shows how to disable UTF-8 mode in the syntax and the regex
207/// itself. This is generally what you want for matching on arbitrary bytes.
208///
209/// ```
210/// use regex_automata::{
211/// nfa::thompson::{self, pikevm::PikeVM},
212/// util::syntax,
213/// Match,
214/// };
215///
216/// let re = PikeVM::builder()
217/// .syntax(syntax::Config::new().utf8(false))
218/// .thompson(thompson::Config::new().utf8(false))
219/// .build(r"foo(?-u:[^b])ar.*")?;
220/// let mut cache = re.create_cache();
221///
222/// let haystack = b"\xFEfoo\xFFarzz\xE2\x98\xFF\n";
223/// let expected = Some(Match::must(0, 1..9));
224/// let got = re.find_iter(&mut cache, haystack).next();
225/// assert_eq!(expected, got);
226/// // Notice that `(?-u:[^b])` matches invalid UTF-8,
227/// // but the subsequent `.*` does not! Disabling UTF-8
228/// // on the syntax permits this.
229/// //
230/// // N.B. This example does not show the impact of
231/// // disabling UTF-8 mode on a PikeVM Config, since that
232/// // only impacts regexes that can produce matches of
233/// // length 0.
234/// assert_eq!(b"foo\xFFarzz", &haystack[got.unwrap().range()]);
235///
236/// # Ok::<(), Box<dyn std::error::Error>>(())
237/// ```
238#[derive(Clone, Debug)]
239pub struct Builder {
240 config: Config,
241 #[cfg(feature = "syntax")]
242 thompson: thompson::Compiler,
243}
244
245impl Builder {
246 /// Create a new PikeVM builder with its default configuration.
247 pub fn new() -> Builder {
248 Builder {
249 config: Config::default(),
250 #[cfg(feature = "syntax")]
251 thompson: thompson::Compiler::new(),
252 }
253 }
254
255 /// Build a `PikeVM` from the given pattern.
256 ///
257 /// If there was a problem parsing or compiling the pattern, then an error
258 /// is returned.
259 #[cfg(feature = "syntax")]
260 pub fn build(&self, pattern: &str) -> Result<PikeVM, BuildError> {
261 self.build_many(&[pattern])
262 }
263
264 /// Build a `PikeVM` from the given patterns.
265 #[cfg(feature = "syntax")]
266 pub fn build_many<P: AsRef<str>>(
267 &self,
268 patterns: &[P],
269 ) -> Result<PikeVM, BuildError> {
270 let nfa = self.thompson.build_many(patterns)?;
271 self.build_from_nfa(nfa)
272 }
273
274 /// Build a `PikeVM` directly from its NFA.
275 ///
276 /// Note that when using this method, any configuration that applies to the
277 /// construction of the NFA itself will of course be ignored, since the NFA
278 /// given here is already built.
279 pub fn build_from_nfa(&self, nfa: NFA) -> Result<PikeVM, BuildError> {
280 nfa.look_set_any().available().map_err(BuildError::word)?;
281 Ok(PikeVM { config: self.config.clone(), nfa })
282 }
283
284 /// Apply the given `PikeVM` configuration options to this builder.
285 pub fn configure(&mut self, config: Config) -> &mut Builder {
286 self.config = self.config.overwrite(config);
287 self
288 }
289
290 /// Set the syntax configuration for this builder using
291 /// [`syntax::Config`](crate::util::syntax::Config).
292 ///
293 /// This permits setting things like case insensitivity, Unicode and multi
294 /// line mode.
295 ///
296 /// These settings only apply when constructing a PikeVM directly from a
297 /// pattern.
298 #[cfg(feature = "syntax")]
299 pub fn syntax(
300 &mut self,
301 config: crate::util::syntax::Config,
302 ) -> &mut Builder {
303 self.thompson.syntax(config);
304 self
305 }
306
307 /// Set the Thompson NFA configuration for this builder using
308 /// [`nfa::thompson::Config`](crate::nfa::thompson::Config).
309 ///
310 /// This permits setting things like if additional time should be spent
311 /// shrinking the size of the NFA.
312 ///
313 /// These settings only apply when constructing a PikeVM directly from a
314 /// pattern.
315 #[cfg(feature = "syntax")]
316 pub fn thompson(&mut self, config: thompson::Config) -> &mut Builder {
317 self.thompson.configure(config);
318 self
319 }
320}
321
322/// A virtual machine for executing regex searches with capturing groups.
323///
324/// # Infallible APIs
325///
326/// Unlike most other regex engines in this crate, a `PikeVM` never returns an
327/// error at search time. It supports all [`Anchored`] configurations, never
328/// quits and works on haystacks of arbitrary length.
329///
330/// There are two caveats to mention though:
331///
332/// * If an invalid pattern ID is given to a search via [`Anchored::Pattern`],
333/// then the PikeVM will report "no match." This is consistent with all other
334/// regex engines in this crate.
335/// * When using [`PikeVM::which_overlapping_matches`] with a [`PatternSet`]
336/// that has insufficient capacity to store all valid pattern IDs, then if a
337/// match occurs for a `PatternID` that cannot be inserted, it is silently
338/// dropped as if it did not match.
339///
340/// # Advice
341///
342/// The `PikeVM` is generally the most "powerful" regex engine in this crate.
343/// "Powerful" in this context means that it can handle any regular expression
344/// that is parseable by `regex-syntax` and any size haystack. Regrettably,
345/// the `PikeVM` is also simultaneously often the _slowest_ regex engine in
346/// practice. This results in an annoying situation where one generally tries
347/// to pick any other regex engine (or perhaps none at all) before being
348/// forced to fall back to a `PikeVM`.
349///
350/// For example, a common strategy for dealing with capturing groups is to
351/// actually look for the overall match of the regex using a faster regex
352/// engine, like a [lazy DFA](crate::hybrid::regex::Regex). Once the overall
353/// match is found, one can then run the `PikeVM` on just the match span to
354/// find the spans of the capturing groups. In this way, the faster regex
355/// engine does the majority of the work, while the `PikeVM` only lends its
356/// power in a more limited role.
357///
358/// Unfortunately, this isn't always possible because the faster regex engines
359/// don't support all of the regex features in `regex-syntax`. This notably
360/// includes (and is currently limited to) Unicode word boundaries. So if
361/// your pattern has Unicode word boundaries, you typically can't use a
362/// DFA-based regex engine at all (unless you [enable heuristic support for
363/// it](crate::hybrid::dfa::Config::unicode_word_boundary)). (The [one-pass
364/// DFA](crate::dfa::onepass::DFA) can handle Unicode word boundaries for
365/// anchored searches only, but in a cruel sort of joke, many Unicode features
366/// tend to result in making the regex _not_ one-pass.)
367///
368/// # Example
369///
370/// This example shows that the `PikeVM` implements Unicode word boundaries
371/// correctly by default.
372///
373/// ```
374/// # if cfg!(miri) { return Ok(()); } // miri takes too long
375/// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
376///
377/// let re = PikeVM::new(r"\b\w+\b")?;
378/// let mut cache = re.create_cache();
379///
380/// let mut it = re.find_iter(&mut cache, "Шерлок Холмс");
381/// assert_eq!(Some(Match::must(0, 0..12)), it.next());
382/// assert_eq!(Some(Match::must(0, 13..23)), it.next());
383/// assert_eq!(None, it.next());
384/// # Ok::<(), Box<dyn std::error::Error>>(())
385/// ```
386#[derive(Clone, Debug)]
387pub struct PikeVM {
388 config: Config,
389 nfa: NFA,
390}
391
392impl PikeVM {
393 /// Parse the given regular expression using the default configuration and
394 /// return the corresponding `PikeVM`.
395 ///
396 /// If you want a non-default configuration, then use the [`Builder`] to
397 /// set your own configuration.
398 ///
399 /// # Example
400 ///
401 /// ```
402 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
403 ///
404 /// let re = PikeVM::new("foo[0-9]+bar")?;
405 /// let mut cache = re.create_cache();
406 /// assert_eq!(
407 /// Some(Match::must(0, 3..14)),
408 /// re.find_iter(&mut cache, "zzzfoo12345barzzz").next(),
409 /// );
410 /// # Ok::<(), Box<dyn std::error::Error>>(())
411 /// ```
412 #[cfg(feature = "syntax")]
413 pub fn new(pattern: &str) -> Result<PikeVM, BuildError> {
414 PikeVM::builder().build(pattern)
415 }
416
417 /// Like `new`, but parses multiple patterns into a single "multi regex."
418 /// This similarly uses the default regex configuration.
419 ///
420 /// # Example
421 ///
422 /// ```
423 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
424 ///
425 /// let re = PikeVM::new_many(&["[a-z]+", "[0-9]+"])?;
426 /// let mut cache = re.create_cache();
427 ///
428 /// let mut it = re.find_iter(&mut cache, "abc 1 foo 4567 0 quux");
429 /// assert_eq!(Some(Match::must(0, 0..3)), it.next());
430 /// assert_eq!(Some(Match::must(1, 4..5)), it.next());
431 /// assert_eq!(Some(Match::must(0, 6..9)), it.next());
432 /// assert_eq!(Some(Match::must(1, 10..14)), it.next());
433 /// assert_eq!(Some(Match::must(1, 15..16)), it.next());
434 /// assert_eq!(Some(Match::must(0, 17..21)), it.next());
435 /// assert_eq!(None, it.next());
436 /// # Ok::<(), Box<dyn std::error::Error>>(())
437 /// ```
438 #[cfg(feature = "syntax")]
439 pub fn new_many<P: AsRef<str>>(
440 patterns: &[P],
441 ) -> Result<PikeVM, BuildError> {
442 PikeVM::builder().build_many(patterns)
443 }
444
445 /// Like `new`, but builds a PikeVM directly from an NFA. This is useful
446 /// if you already have an NFA, or even if you hand-assembled the NFA.
447 ///
448 /// # Example
449 ///
450 /// This shows how to hand assemble a regular expression via its HIR,
451 /// compile an NFA from it and build a PikeVM from the NFA.
452 ///
453 /// ```
454 /// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
455 /// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
456 ///
457 /// let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![
458 /// ClassBytesRange::new(b'0', b'9'),
459 /// ClassBytesRange::new(b'A', b'Z'),
460 /// ClassBytesRange::new(b'_', b'_'),
461 /// ClassBytesRange::new(b'a', b'z'),
462 /// ])));
463 ///
464 /// let config = NFA::config().nfa_size_limit(Some(1_000));
465 /// let nfa = NFA::compiler().configure(config).build_from_hir(&hir)?;
466 ///
467 /// let re = PikeVM::new_from_nfa(nfa)?;
468 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
469 /// let expected = Some(Match::must(0, 3..4));
470 /// re.captures(&mut cache, "!@#A#@!", &mut caps);
471 /// assert_eq!(expected, caps.get_match());
472 ///
473 /// # Ok::<(), Box<dyn std::error::Error>>(())
474 /// ```
475 pub fn new_from_nfa(nfa: NFA) -> Result<PikeVM, BuildError> {
476 PikeVM::builder().build_from_nfa(nfa)
477 }
478
479 /// Create a new `PikeVM` that matches every input.
480 ///
481 /// # Example
482 ///
483 /// ```
484 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
485 ///
486 /// let re = PikeVM::always_match()?;
487 /// let mut cache = re.create_cache();
488 ///
489 /// let expected = Match::must(0, 0..0);
490 /// assert_eq!(Some(expected), re.find_iter(&mut cache, "").next());
491 /// assert_eq!(Some(expected), re.find_iter(&mut cache, "foo").next());
492 /// # Ok::<(), Box<dyn std::error::Error>>(())
493 /// ```
494 pub fn always_match() -> Result<PikeVM, BuildError> {
495 let nfa = thompson::NFA::always_match();
496 PikeVM::new_from_nfa(nfa)
497 }
498
499 /// Create a new `PikeVM` that never matches any input.
500 ///
501 /// # Example
502 ///
503 /// ```
504 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
505 ///
506 /// let re = PikeVM::never_match()?;
507 /// let mut cache = re.create_cache();
508 ///
509 /// assert_eq!(None, re.find_iter(&mut cache, "").next());
510 /// assert_eq!(None, re.find_iter(&mut cache, "foo").next());
511 /// # Ok::<(), Box<dyn std::error::Error>>(())
512 /// ```
513 pub fn never_match() -> Result<PikeVM, BuildError> {
514 let nfa = thompson::NFA::never_match();
515 PikeVM::new_from_nfa(nfa)
516 }
517
518 /// Return a default configuration for a `PikeVM`.
519 ///
520 /// This is a convenience routine to avoid needing to import the `Config`
521 /// type when customizing the construction of a `PikeVM`.
522 ///
523 /// # Example
524 ///
525 /// This example shows how to disable UTF-8 mode. When UTF-8 mode is
526 /// disabled, zero-width matches that split a codepoint are allowed.
527 /// Otherwise they are never reported.
528 ///
529 /// In the code below, notice that `""` is permitted to match positions
530 /// that split the encoding of a codepoint.
531 ///
532 /// ```
533 /// use regex_automata::{nfa::thompson::{self, pikevm::PikeVM}, Match};
534 ///
535 /// let re = PikeVM::builder()
536 /// .thompson(thompson::Config::new().utf8(false))
537 /// .build(r"")?;
538 /// let mut cache = re.create_cache();
539 ///
540 /// let haystack = "a☃z";
541 /// let mut it = re.find_iter(&mut cache, haystack);
542 /// assert_eq!(Some(Match::must(0, 0..0)), it.next());
543 /// assert_eq!(Some(Match::must(0, 1..1)), it.next());
544 /// assert_eq!(Some(Match::must(0, 2..2)), it.next());
545 /// assert_eq!(Some(Match::must(0, 3..3)), it.next());
546 /// assert_eq!(Some(Match::must(0, 4..4)), it.next());
547 /// assert_eq!(Some(Match::must(0, 5..5)), it.next());
548 /// assert_eq!(None, it.next());
549 ///
550 /// # Ok::<(), Box<dyn std::error::Error>>(())
551 /// ```
552 pub fn config() -> Config {
553 Config::new()
554 }
555
556 /// Return a builder for configuring the construction of a `PikeVM`.
557 ///
558 /// This is a convenience routine to avoid needing to import the
559 /// [`Builder`] type in common cases.
560 ///
561 /// # Example
562 ///
563 /// This example shows how to use the builder to disable UTF-8 mode
564 /// everywhere.
565 ///
566 /// ```
567 /// use regex_automata::{
568 /// nfa::thompson::{self, pikevm::PikeVM},
569 /// util::syntax,
570 /// Match,
571 /// };
572 ///
573 /// let re = PikeVM::builder()
574 /// .syntax(syntax::Config::new().utf8(false))
575 /// .thompson(thompson::Config::new().utf8(false))
576 /// .build(r"foo(?-u:[^b])ar.*")?;
577 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
578 ///
579 /// let haystack = b"\xFEfoo\xFFarzz\xE2\x98\xFF\n";
580 /// let expected = Some(Match::must(0, 1..9));
581 /// re.captures(&mut cache, haystack, &mut caps);
582 /// assert_eq!(expected, caps.get_match());
583 ///
584 /// # Ok::<(), Box<dyn std::error::Error>>(())
585 /// ```
586 pub fn builder() -> Builder {
587 Builder::new()
588 }
589
590 /// Create a new empty set of capturing groups that is guaranteed to be
591 /// valid for the search APIs on this `PikeVM`.
592 ///
593 /// A `Captures` value created for a specific `PikeVM` cannot be used with
594 /// any other `PikeVM`.
595 ///
596 /// This is a convenience function for [`Captures::all`]. See the
597 /// [`Captures`] documentation for an explanation of its alternative
598 /// constructors that permit the `PikeVM` to do less work during a search,
599 /// and thus might make it faster.
600 pub fn create_captures(&self) -> Captures {
601 Captures::all(self.get_nfa().group_info().clone())
602 }
603
604 /// Create a new cache for this `PikeVM`.
605 ///
606 /// The cache returned should only be used for searches for this
607 /// `PikeVM`. If you want to reuse the cache for another `PikeVM`, then
608 /// you must call [`Cache::reset`] with that `PikeVM` (or, equivalently,
609 /// [`PikeVM::reset_cache`]).
610 pub fn create_cache(&self) -> Cache {
611 Cache::new(self)
612 }
613
614 /// Reset the given cache such that it can be used for searching with the
615 /// this `PikeVM` (and only this `PikeVM`).
616 ///
617 /// A cache reset permits reusing memory already allocated in this cache
618 /// with a different `PikeVM`.
619 ///
620 /// # Example
621 ///
622 /// This shows how to re-purpose a cache for use with a different `PikeVM`.
623 ///
624 /// ```
625 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
626 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
627 ///
628 /// let re1 = PikeVM::new(r"\w")?;
629 /// let re2 = PikeVM::new(r"\W")?;
630 ///
631 /// let mut cache = re1.create_cache();
632 /// assert_eq!(
633 /// Some(Match::must(0, 0..2)),
634 /// re1.find_iter(&mut cache, "Δ").next(),
635 /// );
636 ///
637 /// // Using 'cache' with re2 is not allowed. It may result in panics or
638 /// // incorrect results. In order to re-purpose the cache, we must reset
639 /// // it with the PikeVM we'd like to use it with.
640 /// //
641 /// // Similarly, after this reset, using the cache with 're1' is also not
642 /// // allowed.
643 /// re2.reset_cache(&mut cache);
644 /// assert_eq!(
645 /// Some(Match::must(0, 0..3)),
646 /// re2.find_iter(&mut cache, "☃").next(),
647 /// );
648 ///
649 /// # Ok::<(), Box<dyn std::error::Error>>(())
650 /// ```
651 pub fn reset_cache(&self, cache: &mut Cache) {
652 cache.reset(self);
653 }
654
655 /// Returns the total number of patterns compiled into this `PikeVM`.
656 ///
657 /// In the case of a `PikeVM` that contains no patterns, this returns `0`.
658 ///
659 /// # Example
660 ///
661 /// This example shows the pattern length for a `PikeVM` that never
662 /// matches:
663 ///
664 /// ```
665 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
666 ///
667 /// let re = PikeVM::never_match()?;
668 /// assert_eq!(re.pattern_len(), 0);
669 /// # Ok::<(), Box<dyn std::error::Error>>(())
670 /// ```
671 ///
672 /// And another example for a `PikeVM` that matches at every position:
673 ///
674 /// ```
675 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
676 ///
677 /// let re = PikeVM::always_match()?;
678 /// assert_eq!(re.pattern_len(), 1);
679 /// # Ok::<(), Box<dyn std::error::Error>>(())
680 /// ```
681 ///
682 /// And finally, a `PikeVM` that was constructed from multiple patterns:
683 ///
684 /// ```
685 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
686 ///
687 /// let re = PikeVM::new_many(&["[0-9]+", "[a-z]+", "[A-Z]+"])?;
688 /// assert_eq!(re.pattern_len(), 3);
689 /// # Ok::<(), Box<dyn std::error::Error>>(())
690 /// ```
691 pub fn pattern_len(&self) -> usize {
692 self.nfa.pattern_len()
693 }
694
695 /// Return the config for this `PikeVM`.
696 #[inline]
697 pub fn get_config(&self) -> &Config {
698 &self.config
699 }
700
701 /// Returns a reference to the underlying NFA.
702 #[inline]
703 pub fn get_nfa(&self) -> &NFA {
704 &self.nfa
705 }
706}
707
708impl PikeVM {
709 /// Returns true if and only if this `PikeVM` matches the given haystack.
710 ///
711 /// This routine may short circuit if it knows that scanning future
712 /// input will never lead to a different result. In particular, if the
713 /// underlying NFA enters a match state, then this routine will return
714 /// `true` immediately without inspecting any future input. (Consider how
715 /// this might make a difference given the regex `a+` on the haystack
716 /// `aaaaaaaaaaaaaaa`. This routine can stop after it sees the first `a`,
717 /// but routines like `find` need to continue searching because `+` is
718 /// greedy by default.)
719 ///
720 /// # Example
721 ///
722 /// This shows basic usage:
723 ///
724 /// ```
725 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
726 ///
727 /// let re = PikeVM::new("foo[0-9]+bar")?;
728 /// let mut cache = re.create_cache();
729 ///
730 /// assert!(re.is_match(&mut cache, "foo12345bar"));
731 /// assert!(!re.is_match(&mut cache, "foobar"));
732 /// # Ok::<(), Box<dyn std::error::Error>>(())
733 /// ```
734 ///
735 /// # Example: consistency with search APIs
736 ///
737 /// `is_match` is guaranteed to return `true` whenever `find` returns a
738 /// match. This includes searches that are executed entirely within a
739 /// codepoint:
740 ///
741 /// ```
742 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Input};
743 ///
744 /// let re = PikeVM::new("a*")?;
745 /// let mut cache = re.create_cache();
746 ///
747 /// assert!(!re.is_match(&mut cache, Input::new("☃").span(1..2)));
748 /// # Ok::<(), Box<dyn std::error::Error>>(())
749 /// ```
750 ///
751 /// Notice that when UTF-8 mode is disabled, then the above reports a
752 /// match because the restriction against zero-width matches that split a
753 /// codepoint has been lifted:
754 ///
755 /// ```
756 /// use regex_automata::{nfa::thompson::{pikevm::PikeVM, NFA}, Input};
757 ///
758 /// let re = PikeVM::builder()
759 /// .thompson(NFA::config().utf8(false))
760 /// .build("a*")?;
761 /// let mut cache = re.create_cache();
762 ///
763 /// assert!(re.is_match(&mut cache, Input::new("☃").span(1..2)));
764 /// # Ok::<(), Box<dyn std::error::Error>>(())
765 /// ```
766 #[inline]
767 pub fn is_match<'h, I: Into<Input<'h>>>(
768 &self,
769 cache: &mut Cache,
770 input: I,
771 ) -> bool {
772 let input = input.into().earliest(true);
773 self.search_slots(cache, &input, &mut []).is_some()
774 }
775
776 /// Executes a leftmost forward search and returns a `Match` if one exists.
777 ///
778 /// This routine only includes the overall match span. To get access to the
779 /// individual spans of each capturing group, use [`PikeVM::captures`].
780 ///
781 /// # Example
782 ///
783 /// Leftmost first match semantics corresponds to the match with the
784 /// smallest starting offset, but where the end offset is determined by
785 /// preferring earlier branches in the original regular expression. For
786 /// example, `Sam|Samwise` will match `Sam` in `Samwise`, but `Samwise|Sam`
787 /// will match `Samwise` in `Samwise`.
788 ///
789 /// Generally speaking, the "leftmost first" match is how most backtracking
790 /// regular expressions tend to work. This is in contrast to POSIX-style
791 /// regular expressions that yield "leftmost longest" matches. Namely,
792 /// both `Sam|Samwise` and `Samwise|Sam` match `Samwise` when using
793 /// leftmost longest semantics. (This crate does not currently support
794 /// leftmost longest semantics.)
795 ///
796 /// ```
797 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
798 ///
799 /// let re = PikeVM::new("foo[0-9]+")?;
800 /// let mut cache = re.create_cache();
801 /// let expected = Match::must(0, 0..8);
802 /// assert_eq!(Some(expected), re.find(&mut cache, "foo12345"));
803 ///
804 /// // Even though a match is found after reading the first byte (`a`),
805 /// // the leftmost first match semantics demand that we find the earliest
806 /// // match that prefers earlier parts of the pattern over later parts.
807 /// let re = PikeVM::new("abc|a")?;
808 /// let mut cache = re.create_cache();
809 /// let expected = Match::must(0, 0..3);
810 /// assert_eq!(Some(expected), re.find(&mut cache, "abc"));
811 ///
812 /// # Ok::<(), Box<dyn std::error::Error>>(())
813 /// ```
814 #[inline]
815 pub fn find<'h, I: Into<Input<'h>>>(
816 &self,
817 cache: &mut Cache,
818 input: I,
819 ) -> Option<Match> {
820 let input = input.into();
821 if self.get_nfa().pattern_len() == 1 {
822 let mut slots = [None, None];
823 let pid = self.search_slots(cache, &input, &mut slots)?;
824 let start = slots[0]?.get();
825 let end = slots[1]?.get();
826 return Some(Match::new(pid, Span { start, end }));
827 }
828 let ginfo = self.get_nfa().group_info();
829 let slots_len = ginfo.implicit_slot_len();
830 let mut slots = vec![None; slots_len];
831 let pid = self.search_slots(cache, &input, &mut slots)?;
832 let start = slots[pid.as_usize() * 2]?.get();
833 let end = slots[pid.as_usize() * 2 + 1]?.get();
834 Some(Match::new(pid, Span { start, end }))
835 }
836
837 /// Executes a leftmost forward search and writes the spans of capturing
838 /// groups that participated in a match into the provided [`Captures`]
839 /// value. If no match was found, then [`Captures::is_match`] is guaranteed
840 /// to return `false`.
841 ///
842 /// # Example
843 ///
844 /// ```
845 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
846 ///
847 /// let re = PikeVM::new(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$")?;
848 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
849 ///
850 /// re.captures(&mut cache, "2010-03-14", &mut caps);
851 /// assert!(caps.is_match());
852 /// assert_eq!(Some(Span::from(0..4)), caps.get_group(1));
853 /// assert_eq!(Some(Span::from(5..7)), caps.get_group(2));
854 /// assert_eq!(Some(Span::from(8..10)), caps.get_group(3));
855 ///
856 /// # Ok::<(), Box<dyn std::error::Error>>(())
857 /// ```
858 #[inline]
859 pub fn captures<'h, I: Into<Input<'h>>>(
860 &self,
861 cache: &mut Cache,
862 input: I,
863 caps: &mut Captures,
864 ) {
865 self.search(cache, &input.into(), caps)
866 }
867
868 /// Returns an iterator over all non-overlapping leftmost matches in the
869 /// given bytes. If no match exists, then the iterator yields no elements.
870 ///
871 /// # Example
872 ///
873 /// ```
874 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
875 ///
876 /// let re = PikeVM::new("foo[0-9]+")?;
877 /// let mut cache = re.create_cache();
878 ///
879 /// let text = "foo1 foo12 foo123";
880 /// let matches: Vec<Match> = re.find_iter(&mut cache, text).collect();
881 /// assert_eq!(matches, vec![
882 /// Match::must(0, 0..4),
883 /// Match::must(0, 5..10),
884 /// Match::must(0, 11..17),
885 /// ]);
886 /// # Ok::<(), Box<dyn std::error::Error>>(())
887 /// ```
888 #[inline]
889 pub fn find_iter<'r, 'c, 'h, I: Into<Input<'h>>>(
890 &'r self,
891 cache: &'c mut Cache,
892 input: I,
893 ) -> FindMatches<'r, 'c, 'h> {
894 let caps = Captures::matches(self.get_nfa().group_info().clone());
895 let it = iter::Searcher::new(input.into());
896 FindMatches { re: self, cache, caps, it }
897 }
898
899 /// Returns an iterator over all non-overlapping `Captures` values. If no
900 /// match exists, then the iterator yields no elements.
901 ///
902 /// This yields the same matches as [`PikeVM::find_iter`], but it includes
903 /// the spans of all capturing groups that participate in each match.
904 ///
905 /// **Tip:** See [`util::iter::Searcher`](crate::util::iter::Searcher) for
906 /// how to correctly iterate over all matches in a haystack while avoiding
907 /// the creation of a new `Captures` value for every match. (Which you are
908 /// forced to do with an `Iterator`.)
909 ///
910 /// # Example
911 ///
912 /// ```
913 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
914 ///
915 /// let re = PikeVM::new("foo(?P<numbers>[0-9]+)")?;
916 /// let mut cache = re.create_cache();
917 ///
918 /// let text = "foo1 foo12 foo123";
919 /// let matches: Vec<Span> = re
920 /// .captures_iter(&mut cache, text)
921 /// // The unwrap is OK since 'numbers' matches if the pattern matches.
922 /// .map(|caps| caps.get_group_by_name("numbers").unwrap())
923 /// .collect();
924 /// assert_eq!(matches, vec![
925 /// Span::from(3..4),
926 /// Span::from(8..10),
927 /// Span::from(14..17),
928 /// ]);
929 /// # Ok::<(), Box<dyn std::error::Error>>(())
930 /// ```
931 #[inline]
932 pub fn captures_iter<'r, 'c, 'h, I: Into<Input<'h>>>(
933 &'r self,
934 cache: &'c mut Cache,
935 input: I,
936 ) -> CapturesMatches<'r, 'c, 'h> {
937 let caps = self.create_captures();
938 let it = iter::Searcher::new(input.into());
939 CapturesMatches { re: self, cache, caps, it }
940 }
941}
942
943impl PikeVM {
944 /// Executes a leftmost forward search and writes the spans of capturing
945 /// groups that participated in a match into the provided [`Captures`]
946 /// value. If no match was found, then [`Captures::is_match`] is guaranteed
947 /// to return `false`.
948 ///
949 /// This is like [`PikeVM::captures`], but it accepts a concrete `&Input`
950 /// instead of an `Into<Input>`.
951 ///
952 /// # Example: specific pattern search
953 ///
954 /// This example shows how to build a multi-PikeVM that permits searching
955 /// for specific patterns.
956 ///
957 /// ```
958 /// use regex_automata::{
959 /// nfa::thompson::pikevm::PikeVM,
960 /// Anchored, Match, PatternID, Input,
961 /// };
962 ///
963 /// let re = PikeVM::new_many(&["[a-z0-9]{6}", "[a-z][a-z0-9]{5}"])?;
964 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
965 /// let haystack = "foo123";
966 ///
967 /// // Since we are using the default leftmost-first match and both
968 /// // patterns match at the same starting position, only the first pattern
969 /// // will be returned in this case when doing a search for any of the
970 /// // patterns.
971 /// let expected = Some(Match::must(0, 0..6));
972 /// re.search(&mut cache, &Input::new(haystack), &mut caps);
973 /// assert_eq!(expected, caps.get_match());
974 ///
975 /// // But if we want to check whether some other pattern matches, then we
976 /// // can provide its pattern ID.
977 /// let expected = Some(Match::must(1, 0..6));
978 /// let input = Input::new(haystack)
979 /// .anchored(Anchored::Pattern(PatternID::must(1)));
980 /// re.search(&mut cache, &input, &mut caps);
981 /// assert_eq!(expected, caps.get_match());
982 ///
983 /// # Ok::<(), Box<dyn std::error::Error>>(())
984 /// ```
985 ///
986 /// # Example: specifying the bounds of a search
987 ///
988 /// This example shows how providing the bounds of a search can produce
989 /// different results than simply sub-slicing the haystack.
990 ///
991 /// ```
992 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
993 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match, Input};
994 ///
995 /// let re = PikeVM::new(r"\b[0-9]{3}\b")?;
996 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
997 /// let haystack = "foo123bar";
998 ///
999 /// // Since we sub-slice the haystack, the search doesn't know about
1000 /// // the larger context and assumes that `123` is surrounded by word
1001 /// // boundaries. And of course, the match position is reported relative
1002 /// // to the sub-slice as well, which means we get `0..3` instead of
1003 /// // `3..6`.
1004 /// let expected = Some(Match::must(0, 0..3));
1005 /// re.search(&mut cache, &Input::new(&haystack[3..6]), &mut caps);
1006 /// assert_eq!(expected, caps.get_match());
1007 ///
1008 /// // But if we provide the bounds of the search within the context of the
1009 /// // entire haystack, then the search can take the surrounding context
1010 /// // into account. (And if we did find a match, it would be reported
1011 /// // as a valid offset into `haystack` instead of its sub-slice.)
1012 /// let expected = None;
1013 /// let input = Input::new(haystack).range(3..6);
1014 /// re.search(&mut cache, &input, &mut caps);
1015 /// assert_eq!(expected, caps.get_match());
1016 ///
1017 /// # Ok::<(), Box<dyn std::error::Error>>(())
1018 /// ```
1019 #[inline]
1020 pub fn search(
1021 &self,
1022 cache: &mut Cache,
1023 input: &Input<'_>,
1024 caps: &mut Captures,
1025 ) {
1026 caps.set_pattern(None);
1027 let pid = self.search_slots(cache, input, caps.slots_mut());
1028 caps.set_pattern(pid);
1029 }
1030
1031 /// Executes a leftmost forward search and writes the spans of capturing
1032 /// groups that participated in a match into the provided `slots`, and
1033 /// returns the matching pattern ID. The contents of the slots for patterns
1034 /// other than the matching pattern are unspecified. If no match was found,
1035 /// then `None` is returned and the contents of `slots` is unspecified.
1036 ///
1037 /// This is like [`PikeVM::search`], but it accepts a raw slots slice
1038 /// instead of a `Captures` value. This is useful in contexts where you
1039 /// don't want or need to allocate a `Captures`.
1040 ///
1041 /// It is legal to pass _any_ number of slots to this routine. If the regex
1042 /// engine would otherwise write a slot offset that doesn't fit in the
1043 /// provided slice, then it is simply skipped. In general though, there are
1044 /// usually three slice lengths you might want to use:
1045 ///
1046 /// * An empty slice, if you only care about which pattern matched.
1047 /// * A slice with
1048 /// [`pattern_len() * 2`](crate::nfa::thompson::NFA::pattern_len)
1049 /// slots, if you only care about the overall match spans for each matching
1050 /// pattern.
1051 /// * A slice with
1052 /// [`slot_len()`](crate::util::captures::GroupInfo::slot_len) slots, which
1053 /// permits recording match offsets for every capturing group in every
1054 /// pattern.
1055 ///
1056 /// # Example
1057 ///
1058 /// This example shows how to find the overall match offsets in a
1059 /// multi-pattern search without allocating a `Captures` value. Indeed, we
1060 /// can put our slots right on the stack.
1061 ///
1062 /// ```
1063 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1064 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID, Input};
1065 ///
1066 /// let re = PikeVM::new_many(&[
1067 /// r"\pL+",
1068 /// r"\d+",
1069 /// ])?;
1070 /// let mut cache = re.create_cache();
1071 /// let input = Input::new("!@#123");
1072 ///
1073 /// // We only care about the overall match offsets here, so we just
1074 /// // allocate two slots for each pattern. Each slot records the start
1075 /// // and end of the match.
1076 /// let mut slots = [None; 4];
1077 /// let pid = re.search_slots(&mut cache, &input, &mut slots);
1078 /// assert_eq!(Some(PatternID::must(1)), pid);
1079 ///
1080 /// // The overall match offsets are always at 'pid * 2' and 'pid * 2 + 1'.
1081 /// // See 'GroupInfo' for more details on the mapping between groups and
1082 /// // slot indices.
1083 /// let slot_start = pid.unwrap().as_usize() * 2;
1084 /// let slot_end = slot_start + 1;
1085 /// assert_eq!(Some(3), slots[slot_start].map(|s| s.get()));
1086 /// assert_eq!(Some(6), slots[slot_end].map(|s| s.get()));
1087 ///
1088 /// # Ok::<(), Box<dyn std::error::Error>>(())
1089 /// ```
1090 #[inline]
1091 pub fn search_slots(
1092 &self,
1093 cache: &mut Cache,
1094 input: &Input<'_>,
1095 slots: &mut [Option<NonMaxUsize>],
1096 ) -> Option<PatternID> {
1097 let utf8empty = self.get_nfa().has_empty() && self.get_nfa().is_utf8();
1098 if !utf8empty {
1099 let hm = self.search_slots_imp(cache, input, slots)?;
1100 return Some(hm.pattern());
1101 }
1102 // There is an unfortunate special case where if the regex can
1103 // match the empty string and UTF-8 mode is enabled, the search
1104 // implementation requires that the slots have at least as much space
1105 // to report the bounds of any match. This is so zero-width matches
1106 // that split a codepoint can be filtered out.
1107 //
1108 // Note that if utf8empty is true, we specialize the case for when
1109 // the number of patterns is 1. In that case, we can just use a stack
1110 // allocation. Otherwise we resort to a heap allocation, which we
1111 // convince ourselves we're fine with due to the pathological nature of
1112 // this case.
1113 let min = self.get_nfa().group_info().implicit_slot_len();
1114 if slots.len() >= min {
1115 let hm = self.search_slots_imp(cache, input, slots)?;
1116 return Some(hm.pattern());
1117 }
1118 if self.get_nfa().pattern_len() == 1 {
1119 let mut enough = [None, None];
1120 let got = self.search_slots_imp(cache, input, &mut enough);
1121 // This is OK because we know `enough` is strictly bigger than
1122 // `slots`, otherwise this special case isn't reached.
1123 slots.copy_from_slice(&enough[..slots.len()]);
1124 return got.map(|hm| hm.pattern());
1125 }
1126 let mut enough = vec![None; min];
1127 let got = self.search_slots_imp(cache, input, &mut enough);
1128 // This is OK because we know `enough` is strictly bigger than `slots`,
1129 // otherwise this special case isn't reached.
1130 slots.copy_from_slice(&enough[..slots.len()]);
1131 got.map(|hm| hm.pattern())
1132 }
1133
1134 /// This is the actual implementation of `search_slots_imp` that
1135 /// doesn't account for the special case when 1) the NFA has UTF-8 mode
1136 /// enabled, 2) the NFA can match the empty string and 3) the caller has
1137 /// provided an insufficient number of slots to record match offsets.
1138 #[inline(never)]
1139 fn search_slots_imp(
1140 &self,
1141 cache: &mut Cache,
1142 input: &Input<'_>,
1143 slots: &mut [Option<NonMaxUsize>],
1144 ) -> Option<HalfMatch> {
1145 let utf8empty = self.get_nfa().has_empty() && self.get_nfa().is_utf8();
1146 let hm = match self.search_imp(cache, input, slots) {
1147 None => return None,
1148 Some(hm) if !utf8empty => return Some(hm),
1149 Some(hm) => hm,
1150 };
1151 empty::skip_splits_fwd(input, hm, hm.offset(), |input| {
1152 Ok(self
1153 .search_imp(cache, input, slots)
1154 .map(|hm| (hm, hm.offset())))
1155 })
1156 // OK because the PikeVM never errors.
1157 .unwrap()
1158 }
1159
1160 /// Writes the set of patterns that match anywhere in the given search
1161 /// configuration to `patset`. If multiple patterns match at the same
1162 /// position and this `PikeVM` was configured with [`MatchKind::All`]
1163 /// semantics, then all matching patterns are written to the given set.
1164 ///
1165 /// Unless all of the patterns in this `PikeVM` are anchored, then
1166 /// generally speaking, this will visit every byte in the haystack.
1167 ///
1168 /// This search routine *does not* clear the pattern set. This gives some
1169 /// flexibility to the caller (e.g., running multiple searches with the
1170 /// same pattern set), but does make the API bug-prone if you're reusing
1171 /// the same pattern set for multiple searches but intended them to be
1172 /// independent.
1173 ///
1174 /// If a pattern ID matched but the given `PatternSet` does not have
1175 /// sufficient capacity to store it, then it is not inserted and silently
1176 /// dropped.
1177 ///
1178 /// # Example
1179 ///
1180 /// This example shows how to find all matching patterns in a haystack,
1181 /// even when some patterns match at the same position as other patterns.
1182 ///
1183 /// ```
1184 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1185 /// use regex_automata::{
1186 /// nfa::thompson::pikevm::PikeVM,
1187 /// Input, MatchKind, PatternSet,
1188 /// };
1189 ///
1190 /// let patterns = &[
1191 /// r"\w+", r"\d+", r"\pL+", r"foo", r"bar", r"barfoo", r"foobar",
1192 /// ];
1193 /// let re = PikeVM::builder()
1194 /// .configure(PikeVM::config().match_kind(MatchKind::All))
1195 /// .build_many(patterns)?;
1196 /// let mut cache = re.create_cache();
1197 ///
1198 /// let input = Input::new("foobar");
1199 /// let mut patset = PatternSet::new(re.pattern_len());
1200 /// re.which_overlapping_matches(&mut cache, &input, &mut patset);
1201 /// let expected = vec![0, 2, 3, 4, 6];
1202 /// let got: Vec<usize> = patset.iter().map(|p| p.as_usize()).collect();
1203 /// assert_eq!(expected, got);
1204 ///
1205 /// # Ok::<(), Box<dyn std::error::Error>>(())
1206 /// ```
1207 #[inline]
1208 pub fn which_overlapping_matches(
1209 &self,
1210 cache: &mut Cache,
1211 input: &Input<'_>,
1212 patset: &mut PatternSet,
1213 ) {
1214 self.which_overlapping_imp(cache, input, patset)
1215 }
1216}
1217
1218impl PikeVM {
1219 /// The implementation of standard leftmost search.
1220 ///
1221 /// Capturing group spans are written to `slots`, but only if requested.
1222 /// `slots` can be any length. Any slot in the NFA that is activated but
1223 /// which is out of bounds for the given `slots` is ignored.
1224 fn search_imp(
1225 &self,
1226 cache: &mut Cache,
1227 input: &Input<'_>,
1228 slots: &mut [Option<NonMaxUsize>],
1229 ) -> Option<HalfMatch> {
1230 // The caller may provide more slots than the NFA has. Ignore the
1231 // excess so that each row in the slot table stays within its bounds.
1232 let slots_len =
1233 core::cmp::min(slots.len(), self.nfa.group_info().slot_len());
1234 let slots = &mut slots[..slots_len];
1235 cache.setup_search(slots.len());
1236 if input.is_done() {
1237 return None;
1238 }
1239 // Why do we even care about this? Well, in our 'Captures'
1240 // representation, we use usize::MAX as a sentinel to indicate "no
1241 // match." This isn't problematic so long as our haystack doesn't have
1242 // a maximal length. Byte slices are guaranteed by Rust to have a
1243 // length that fits into isize, and so this assert should always pass.
1244 // But we put it here to make our assumption explicit.
1245 assert!(
1246 input.haystack().len() < usize::MAX,
1247 "byte slice lengths must be less than usize MAX",
1248 );
1249 instrument!(|c| c.reset(&self.nfa));
1250
1251 // Whether we want to visit all match states instead of emulating the
1252 // 'leftmost' semantics of typical backtracking regex engines.
1253 let allmatches =
1254 self.config.get_match_kind().continue_past_first_match();
1255 let (anchored, start_id) = match self.start_config(input) {
1256 None => return None,
1257 Some(config) => config,
1258 };
1259
1260 let pre =
1261 if anchored { None } else { self.get_config().get_prefilter() };
1262 let Cache { ref mut stack, ref mut curr, ref mut next } = cache;
1263 let mut hm = None;
1264 // Yes, our search doesn't end at input.end(), but includes it. This
1265 // is necessary because matches are delayed by one byte, just like
1266 // how the DFA engines work. The delay is used to handle look-behind
1267 // assertions. In the case of the PikeVM, the delay is implemented
1268 // by not considering a match to exist until it is visited in
1269 // 'steps'. Technically, we know a match exists in the previous
1270 // iteration via 'epsilon_closure'. (It's the same thing in NFA-to-DFA
1271 // determinization. We don't mark a DFA state as a match state if it
1272 // contains an NFA match state, but rather, whether the DFA state was
1273 // generated by a transition from a DFA state that contains an NFA
1274 // match state.)
1275 let mut at = input.start();
1276 while at <= input.end() {
1277 // If we have no states left to visit, then there are some cases
1278 // where we know we can quit early or even skip ahead.
1279 if curr.set.is_empty() {
1280 // We have a match and we haven't been instructed to continue
1281 // on even after finding a match, so we can quit.
1282 if hm.is_some() && !allmatches {
1283 break;
1284 }
1285 // If we're running an anchored search and we've advanced
1286 // beyond the start position with no other states to try, then
1287 // we will never observe a match and thus can stop.
1288 if anchored && at > input.start() {
1289 break;
1290 }
1291 // If there no states left to explore at this position and we
1292 // know we can't terminate early, then we are effectively at
1293 // the starting state of the NFA. If we fell through here,
1294 // we'd end up adding our '(?s-u:.)*?' prefix and it would be
1295 // the only thing in 'curr'. So we might as well just skip
1296 // ahead until we find something that we know might advance us
1297 // forward.
1298 if let Some(pre) = pre {
1299 let span = Span::from(at..input.end());
1300 match pre.find(input.haystack(), span) {
1301 None => break,
1302 Some(ref span) => at = span.start,
1303 }
1304 }
1305 }
1306 // Instead of using the NFA's unanchored start state, we actually
1307 // always use its anchored starting state. As a result, when doing
1308 // an unanchored search, we need to simulate our own '(?s-u:.)*?'
1309 // prefix, to permit a match to appear anywhere.
1310 //
1311 // Now, we don't *have* to do things this way. We could use the
1312 // NFA's unanchored starting state and do one 'epsilon_closure'
1313 // call from that starting state before the main loop here. And
1314 // that is just as correct. However, it turns out to be slower
1315 // than our approach here because it slightly increases the cost
1316 // of processing each byte by requiring us to visit more NFA
1317 // states to deal with the additional NFA states in the unanchored
1318 // prefix. By simulating it explicitly here, we lower those costs
1319 // substantially. The cost is itself small, but it adds up for
1320 // large haystacks.
1321 //
1322 // In order to simulate the '(?s-u:.)*?' prefix---which is not
1323 // greedy---we are careful not to perform an epsilon closure on
1324 // the start state if we already have a match. Namely, if we
1325 // did otherwise, we would never reach a terminating condition
1326 // because there would always be additional states to process.
1327 // In effect, the exclusion of running 'epsilon_closure' when
1328 // we have a match corresponds to the "dead" states we have in
1329 // our DFA regex engines. Namely, in a DFA, match states merely
1330 // instruct the search execution to record the current offset as
1331 // the most recently seen match. It is the dead state that actually
1332 // indicates when to stop the search (other than EOF or quit
1333 // states).
1334 //
1335 // However, when 'allmatches' is true, the caller has asked us to
1336 // leave in every possible match state. This tends not to make a
1337 // whole lot of sense in unanchored searches, because it means the
1338 // search really cannot terminate until EOF. And often, in that
1339 // case, you wind up skipping over a bunch of matches and are left
1340 // with the "last" match. Arguably, it just doesn't make a lot of
1341 // sense to run a 'leftmost' search (which is what this routine is)
1342 // with 'allmatches' set to true. But the DFAs support it and this
1343 // matches their behavior. (Generally, 'allmatches' is useful for
1344 // overlapping searches or leftmost anchored searches to find the
1345 // longest possible match by ignoring match priority.)
1346 //
1347 // Additionally, when we're running an anchored search, this
1348 // epsilon closure should only be computed at the beginning of the
1349 // search. If we re-computed it at every position, we would be
1350 // simulating an unanchored search when we were tasked to perform
1351 // an anchored search.
1352 if (hm.is_none() || allmatches)
1353 && (!anchored || at == input.start())
1354 {
1355 // Since we are adding to the 'curr' active states and since
1356 // this is for the start ID, we use a slots slice that is
1357 // guaranteed to have the right length but where every element
1358 // is absent. This is exactly what we want, because this
1359 // epsilon closure is responsible for simulating an unanchored
1360 // '(?s:.)*?' prefix. It is specifically outside of any
1361 // capturing groups, and thus, using slots that are always
1362 // absent is correct.
1363 //
1364 // Note though that we can't just use '&mut []' here, since
1365 // this epsilon closure may traverse through 'Captures' epsilon
1366 // transitions, and thus must be able to write offsets to the
1367 // slots given which are later copied to slot values in 'curr'.
1368 let slots = next.slot_table.all_absent();
1369 self.epsilon_closure(stack, slots, curr, input, at, start_id);
1370 }
1371 if let Some(pid) = self.nexts(stack, curr, next, input, at, slots)
1372 {
1373 hm = Some(HalfMatch::new(pid, at));
1374 }
1375 // Unless the caller asked us to return early, we need to mush on
1376 // to see if we can extend our match. (But note that 'nexts' will
1377 // quit right after seeing a match when match_kind==LeftmostFirst,
1378 // as is consistent with leftmost-first match priority.)
1379 if input.get_earliest() && hm.is_some() {
1380 break;
1381 }
1382 core::mem::swap(curr, next);
1383 next.set.clear();
1384 at += 1;
1385 }
1386 instrument!(|c| c.eprint(&self.nfa));
1387 hm
1388 }
1389
1390 /// The implementation for the 'which_overlapping_matches' API. Basically,
1391 /// we do a single scan through the entire haystack (unless our regex
1392 /// or search is anchored) and record every pattern that matched. In
1393 /// particular, when MatchKind::All is used, this supports overlapping
1394 /// matches. So if we have the regexes 'sam' and 'samwise', they will
1395 /// *both* be reported in the pattern set when searching the haystack
1396 /// 'samwise'.
1397 fn which_overlapping_imp(
1398 &self,
1399 cache: &mut Cache,
1400 input: &Input<'_>,
1401 patset: &mut PatternSet,
1402 ) {
1403 // NOTE: This is effectively a copy of 'search_imp' above, but with no
1404 // captures support and instead writes patterns that matched directly
1405 // to 'patset'. See that routine for better commentary about what's
1406 // going on in this routine. We probably could unify the routines using
1407 // generics or more helper routines, but I'm not sure it's worth it.
1408 //
1409 // NOTE: We somewhat go out of our way here to support things like
1410 // 'input.get_earliest()' and 'leftmost-first' match semantics. Neither
1411 // of those seem particularly relevant to this routine, but they are
1412 // both supported by the DFA analogs of this routine by construction
1413 // and composition, so it seems like good sense to have the PikeVM
1414 // match that behavior.
1415
1416 cache.setup_search(0);
1417 if input.is_done() {
1418 return;
1419 }
1420 assert!(
1421 input.haystack().len() < usize::MAX,
1422 "byte slice lengths must be less than usize MAX",
1423 );
1424 instrument!(|c| c.reset(&self.nfa));
1425
1426 let allmatches =
1427 self.config.get_match_kind().continue_past_first_match();
1428 let (anchored, start_id) = match self.start_config(input) {
1429 None => return,
1430 Some(config) => config,
1431 };
1432
1433 let Cache { ref mut stack, ref mut curr, ref mut next } = cache;
1434 for at in input.start()..=input.end() {
1435 let any_matches = !patset.is_empty();
1436 if curr.set.is_empty() {
1437 if any_matches && !allmatches {
1438 break;
1439 }
1440 if anchored && at > input.start() {
1441 break;
1442 }
1443 }
1444 if !any_matches || allmatches {
1445 let slots = &mut [];
1446 self.epsilon_closure(stack, slots, curr, input, at, start_id);
1447 }
1448 self.nexts_overlapping(stack, curr, next, input, at, patset);
1449 // If we found a match and filled our set, then there is no more
1450 // additional info that we can provide. Thus, we can quit. We also
1451 // quit if the caller asked us to stop at the earliest point that
1452 // we know a match exists.
1453 if patset.is_full() || input.get_earliest() {
1454 break;
1455 }
1456 core::mem::swap(curr, next);
1457 next.set.clear();
1458 }
1459 instrument!(|c| c.eprint(&self.nfa));
1460 }
1461
1462 /// Process the active states in 'curr' to find the states (written to
1463 /// 'next') we should process for the next byte in the haystack.
1464 ///
1465 /// 'stack' is used to perform a depth first traversal of the NFA when
1466 /// computing an epsilon closure.
1467 ///
1468 /// When a match is found, the slots for that match state (in 'curr') are
1469 /// copied to 'caps'. Moreover, once a match is seen, processing for 'curr'
1470 /// stops (unless the PikeVM was configured with MatchKind::All semantics).
1471 #[cfg_attr(feature = "perf-inline", inline(always))]
1472 fn nexts(
1473 &self,
1474 stack: &mut Vec<FollowEpsilon>,
1475 curr: &mut ActiveStates,
1476 next: &mut ActiveStates,
1477 input: &Input<'_>,
1478 at: usize,
1479 slots: &mut [Option<NonMaxUsize>],
1480 ) -> Option<PatternID> {
1481 instrument!(|c| c.record_state_set(&curr.set));
1482 let mut pid = None;
1483 let ActiveStates { ref set, ref mut slot_table } = *curr;
1484 for sid in set.iter() {
1485 pid = match self.next(stack, slot_table, next, input, at, sid) {
1486 None => continue,
1487 Some(pid) => Some(pid),
1488 };
1489 slots.copy_from_slice(slot_table.for_state(sid));
1490 if !self.config.get_match_kind().continue_past_first_match() {
1491 break;
1492 }
1493 }
1494 pid
1495 }
1496
1497 /// Like 'nexts', but for the overlapping case. This doesn't write any
1498 /// slots, and instead just writes which pattern matched in 'patset'.
1499 #[cfg_attr(feature = "perf-inline", inline(always))]
1500 fn nexts_overlapping(
1501 &self,
1502 stack: &mut Vec<FollowEpsilon>,
1503 curr: &mut ActiveStates,
1504 next: &mut ActiveStates,
1505 input: &Input<'_>,
1506 at: usize,
1507 patset: &mut PatternSet,
1508 ) {
1509 instrument!(|c| c.record_state_set(&curr.set));
1510 let utf8empty = self.get_nfa().has_empty() && self.get_nfa().is_utf8();
1511 let ActiveStates { ref set, ref mut slot_table } = *curr;
1512 for sid in set.iter() {
1513 let pid = match self.next(stack, slot_table, next, input, at, sid)
1514 {
1515 None => continue,
1516 Some(pid) => pid,
1517 };
1518 // This handles the case of finding a zero-width match that splits
1519 // a codepoint. Namely, if we're in UTF-8 mode AND we know we can
1520 // match the empty string, then the only valid way of getting to
1521 // this point with an offset that splits a codepoint is when we
1522 // have an empty match. Such matches, in UTF-8 mode, must not be
1523 // reported. So we just skip them here and pretend as if we did
1524 // not see a match.
1525 if utf8empty && !input.is_char_boundary(at) {
1526 continue;
1527 }
1528 let _ = patset.try_insert(pid);
1529 if !self.config.get_match_kind().continue_past_first_match() {
1530 break;
1531 }
1532 }
1533 }
1534
1535 /// Starting from 'sid', if the position 'at' in the 'input' haystack has a
1536 /// transition defined out of 'sid', then add the state transitioned to and
1537 /// its epsilon closure to the 'next' set of states to explore.
1538 ///
1539 /// 'stack' is used by the epsilon closure computation to perform a depth
1540 /// first traversal of the NFA.
1541 ///
1542 /// 'curr_slot_table' should be the table of slots for the current set of
1543 /// states being explored. If there is a transition out of 'sid', then
1544 /// sid's row in the slot table is used to perform the epsilon closure.
1545 #[cfg_attr(feature = "perf-inline", inline(always))]
1546 fn next(
1547 &self,
1548 stack: &mut Vec<FollowEpsilon>,
1549 curr_slot_table: &mut SlotTable,
1550 next: &mut ActiveStates,
1551 input: &Input<'_>,
1552 at: usize,
1553 sid: StateID,
1554 ) -> Option<PatternID> {
1555 instrument!(|c| c.record_step(sid));
1556 match *self.nfa.state(sid) {
1557 State::Fail
1558 | State::Look { .. }
1559 | State::Union { .. }
1560 | State::BinaryUnion { .. }
1561 | State::Capture { .. } => None,
1562 State::ByteRange { ref trans } => {
1563 if trans.matches(input.haystack(), at) {
1564 let slots = curr_slot_table.for_state(sid);
1565 // OK because 'at <= haystack.len() < usize::MAX', so
1566 // adding 1 will never wrap.
1567 let at = at.wrapping_add(1);
1568 self.epsilon_closure(
1569 stack, slots, next, input, at, trans.next,
1570 );
1571 }
1572 None
1573 }
1574 State::Sparse(ref sparse) => {
1575 if let Some(next_sid) = sparse.matches(input.haystack(), at) {
1576 let slots = curr_slot_table.for_state(sid);
1577 // OK because 'at <= haystack.len() < usize::MAX', so
1578 // adding 1 will never wrap.
1579 let at = at.wrapping_add(1);
1580 self.epsilon_closure(
1581 stack, slots, next, input, at, next_sid,
1582 );
1583 }
1584 None
1585 }
1586 State::Dense(ref dense) => {
1587 if let Some(next_sid) = dense.matches(input.haystack(), at) {
1588 let slots = curr_slot_table.for_state(sid);
1589 // OK because 'at <= haystack.len() < usize::MAX', so
1590 // adding 1 will never wrap.
1591 let at = at.wrapping_add(1);
1592 self.epsilon_closure(
1593 stack, slots, next, input, at, next_sid,
1594 );
1595 }
1596 None
1597 }
1598 State::Match { pattern_id } => Some(pattern_id),
1599 }
1600 }
1601
1602 /// Compute the epsilon closure of 'sid', writing the closure into 'next'
1603 /// while copying slot values from 'curr_slots' into corresponding states
1604 /// in 'next'. 'curr_slots' should be the slot values corresponding to
1605 /// 'sid'.
1606 ///
1607 /// The given 'stack' is used to perform a depth first traversal of the
1608 /// NFA by recursively following all epsilon transitions out of 'sid'.
1609 /// Conditional epsilon transitions are followed if and only if they are
1610 /// satisfied for the position 'at' in the 'input' haystack.
1611 ///
1612 /// While this routine may write to 'curr_slots', once it returns, any
1613 /// writes are undone and the original values (even if absent) are
1614 /// restored.
1615 #[cfg_attr(feature = "perf-inline", inline(always))]
1616 fn epsilon_closure(
1617 &self,
1618 stack: &mut Vec<FollowEpsilon>,
1619 curr_slots: &mut [Option<NonMaxUsize>],
1620 next: &mut ActiveStates,
1621 input: &Input<'_>,
1622 at: usize,
1623 sid: StateID,
1624 ) {
1625 instrument!(|c| {
1626 c.record_closure(sid);
1627 c.record_stack_push(sid);
1628 });
1629 stack.push(FollowEpsilon::Explore(sid));
1630 while let Some(frame) = stack.pop() {
1631 match frame {
1632 FollowEpsilon::RestoreCapture { slot, offset: pos } => {
1633 curr_slots[slot] = pos;
1634 }
1635 FollowEpsilon::Explore(sid) => {
1636 self.epsilon_closure_explore(
1637 stack, curr_slots, next, input, at, sid,
1638 );
1639 }
1640 }
1641 }
1642 }
1643
1644 /// Explore all of the epsilon transitions out of 'sid'. This is mostly
1645 /// split out from 'epsilon_closure' in order to clearly delineate
1646 /// the actual work of computing an epsilon closure from the stack
1647 /// book-keeping.
1648 ///
1649 /// This will push any additional explorations needed on to 'stack'.
1650 ///
1651 /// 'curr_slots' should refer to the slots for the currently active NFA
1652 /// state. That is, the current state we are stepping through. These
1653 /// slots are mutated in place as new 'Captures' states are traversed
1654 /// during epsilon closure, but the slots are restored to their original
1655 /// values once the full epsilon closure is completed. The ultimate use of
1656 /// 'curr_slots' is to copy them to the corresponding 'next_slots', so that
1657 /// the capturing group spans are forwarded from the currently active state
1658 /// to the next.
1659 ///
1660 /// 'next' refers to the next set of active states. Computing an epsilon
1661 /// closure may increase the next set of active states.
1662 ///
1663 /// 'input' refers to the caller's input configuration and 'at' refers to
1664 /// the current position in the haystack. These are used to check whether
1665 /// conditional epsilon transitions (like look-around) are satisfied at
1666 /// the current position. If they aren't, then the epsilon closure won't
1667 /// include them.
1668 #[cfg_attr(feature = "perf-inline", inline(always))]
1669 fn epsilon_closure_explore(
1670 &self,
1671 stack: &mut Vec<FollowEpsilon>,
1672 curr_slots: &mut [Option<NonMaxUsize>],
1673 next: &mut ActiveStates,
1674 input: &Input<'_>,
1675 at: usize,
1676 mut sid: StateID,
1677 ) {
1678 // We can avoid pushing some state IDs on to our stack in precisely
1679 // the cases where a 'push(x)' would be immediately followed by a 'x
1680 // = pop()'. This is achieved by this outer-loop. We simply set 'sid'
1681 // to be the next state ID we want to explore once we're done with
1682 // our initial exploration. In practice, this avoids a lot of stack
1683 // thrashing.
1684 loop {
1685 instrument!(|c| c.record_set_insert(sid));
1686 // Record this state as part of our next set of active states. If
1687 // we've already explored it, then no need to do it again.
1688 if !next.set.insert(sid) {
1689 return;
1690 }
1691 match *self.nfa.state(sid) {
1692 State::Fail
1693 | State::Match { .. }
1694 | State::ByteRange { .. }
1695 | State::Sparse { .. }
1696 | State::Dense { .. } => {
1697 next.slot_table.for_state(sid).copy_from_slice(curr_slots);
1698 return;
1699 }
1700 State::Look { look, next } => {
1701 // OK because we don't permit building a searcher with a
1702 // Unicode word boundary if the requisite Unicode data is
1703 // unavailable.
1704 if !self.nfa.look_matcher().matches_inline(
1705 look,
1706 input.haystack(),
1707 at,
1708 ) {
1709 return;
1710 }
1711 sid = next;
1712 }
1713 State::Union { ref alternates } => {
1714 sid = match alternates.get(0) {
1715 None => return,
1716 Some(&sid) => sid,
1717 };
1718 instrument!(|c| {
1719 for &alt in &alternates[1..] {
1720 c.record_stack_push(alt);
1721 }
1722 });
1723 stack.extend(
1724 alternates[1..]
1725 .iter()
1726 .copied()
1727 .rev()
1728 .map(FollowEpsilon::Explore),
1729 );
1730 }
1731 State::BinaryUnion { alt1, alt2 } => {
1732 sid = alt1;
1733 instrument!(|c| c.record_stack_push(sid));
1734 stack.push(FollowEpsilon::Explore(alt2));
1735 }
1736 State::Capture { next, slot, .. } => {
1737 // There's no need to do anything with slots that
1738 // ultimately won't be copied into the caller-provided
1739 // 'Captures' value. So we just skip dealing with them at
1740 // all.
1741 if slot.as_usize() < curr_slots.len() {
1742 instrument!(|c| c.record_stack_push(sid));
1743 stack.push(FollowEpsilon::RestoreCapture {
1744 slot,
1745 offset: curr_slots[slot],
1746 });
1747 // OK because length of a slice must fit into an isize.
1748 curr_slots[slot] = Some(NonMaxUsize::new(at).unwrap());
1749 }
1750 sid = next;
1751 }
1752 }
1753 }
1754 }
1755
1756 /// Return the starting configuration of a PikeVM search.
1757 ///
1758 /// The "start config" is basically whether the search should be anchored
1759 /// or not and the NFA state ID at which to begin the search. The state ID
1760 /// returned always corresponds to an anchored starting state even when the
1761 /// search is unanchored. This is because the PikeVM search loop deals with
1762 /// unanchored searches with an explicit epsilon closure out of the start
1763 /// state.
1764 ///
1765 /// This routine accounts for both the caller's `Input` configuration
1766 /// and the pattern itself. For example, even if the caller asks for an
1767 /// unanchored search, if the pattern itself is anchored, then this will
1768 /// always return 'true' because implementing an unanchored search in that
1769 /// case would be incorrect.
1770 ///
1771 /// Similarly, if the caller requests an anchored search for a particular
1772 /// pattern, then the starting state ID returned will reflect that.
1773 ///
1774 /// If a pattern ID is given in the input configuration that is not in
1775 /// this regex, then `None` is returned.
1776 fn start_config(&self, input: &Input<'_>) -> Option<(bool, StateID)> {
1777 match input.get_anchored() {
1778 // Only way we're unanchored is if both the caller asked for an
1779 // unanchored search *and* the pattern is itself not anchored.
1780 Anchored::No => Some((
1781 self.nfa.is_always_start_anchored(),
1782 self.nfa.start_anchored(),
1783 )),
1784 Anchored::Yes => Some((true, self.nfa.start_anchored())),
1785 Anchored::Pattern(pid) => {
1786 Some((true, self.nfa.start_pattern(pid)?))
1787 }
1788 }
1789 }
1790}
1791
1792/// An iterator over all non-overlapping matches for a particular search.
1793///
1794/// The iterator yields a [`Match`] value until no more matches could be found.
1795///
1796/// The lifetime parameters are as follows:
1797///
1798/// * `'r` represents the lifetime of the PikeVM.
1799/// * `'c` represents the lifetime of the PikeVM's cache.
1800/// * `'h` represents the lifetime of the haystack being searched.
1801///
1802/// This iterator can be created with the [`PikeVM::find_iter`] method.
1803#[derive(Debug)]
1804pub struct FindMatches<'r, 'c, 'h> {
1805 re: &'r PikeVM,
1806 cache: &'c mut Cache,
1807 caps: Captures,
1808 it: iter::Searcher<'h>,
1809}
1810
1811impl<'r, 'c, 'h> Iterator for FindMatches<'r, 'c, 'h> {
1812 type Item = Match;
1813
1814 #[inline]
1815 fn next(&mut self) -> Option<Match> {
1816 // Splitting 'self' apart seems necessary to appease borrowck.
1817 let FindMatches { re, ref mut cache, ref mut caps, ref mut it } =
1818 *self;
1819 // 'advance' converts errors into panics, which is OK here because
1820 // the PikeVM can never return an error.
1821 it.advance(|input| {
1822 re.search(cache, input, caps);
1823 Ok(caps.get_match())
1824 })
1825 }
1826}
1827
1828/// An iterator over all non-overlapping leftmost matches, with their capturing
1829/// groups, for a particular search.
1830///
1831/// The iterator yields a [`Captures`] value until no more matches could be
1832/// found.
1833///
1834/// The lifetime parameters are as follows:
1835///
1836/// * `'r` represents the lifetime of the PikeVM.
1837/// * `'c` represents the lifetime of the PikeVM's cache.
1838/// * `'h` represents the lifetime of the haystack being searched.
1839///
1840/// This iterator can be created with the [`PikeVM::captures_iter`] method.
1841#[derive(Debug)]
1842pub struct CapturesMatches<'r, 'c, 'h> {
1843 re: &'r PikeVM,
1844 cache: &'c mut Cache,
1845 caps: Captures,
1846 it: iter::Searcher<'h>,
1847}
1848
1849impl<'r, 'c, 'h> Iterator for CapturesMatches<'r, 'c, 'h> {
1850 type Item = Captures;
1851
1852 #[inline]
1853 fn next(&mut self) -> Option<Captures> {
1854 // Splitting 'self' apart seems necessary to appease borrowck.
1855 let CapturesMatches { re, ref mut cache, ref mut caps, ref mut it } =
1856 *self;
1857 // 'advance' converts errors into panics, which is OK here because
1858 // the PikeVM can never return an error.
1859 it.advance(|input| {
1860 re.search(cache, input, caps);
1861 Ok(caps.get_match())
1862 });
1863 if caps.is_match() {
1864 Some(caps.clone())
1865 } else {
1866 None
1867 }
1868 }
1869}
1870
1871/// A cache represents mutable state that a [`PikeVM`] requires during a
1872/// search.
1873///
1874/// For a given [`PikeVM`], its corresponding cache may be created either via
1875/// [`PikeVM::create_cache`], or via [`Cache::new`]. They are equivalent in
1876/// every way, except the former does not require explicitly importing `Cache`.
1877///
1878/// A particular `Cache` is coupled with the [`PikeVM`] from which it
1879/// was created. It may only be used with that `PikeVM`. A cache and its
1880/// allocations may be re-purposed via [`Cache::reset`], in which case, it can
1881/// only be used with the new `PikeVM` (and not the old one).
1882#[derive(Clone, Debug)]
1883pub struct Cache {
1884 /// Stack used while computing epsilon closure. This effectively lets us
1885 /// move what is more naturally expressed through recursion to a stack
1886 /// on the heap.
1887 stack: Vec<FollowEpsilon>,
1888 /// The current active states being explored for the current byte in the
1889 /// haystack.
1890 curr: ActiveStates,
1891 /// The next set of states we're building that will be explored for the
1892 /// next byte in the haystack.
1893 next: ActiveStates,
1894}
1895
1896impl Cache {
1897 /// Create a new [`PikeVM`] cache.
1898 ///
1899 /// A potentially more convenient routine to create a cache is
1900 /// [`PikeVM::create_cache`], as it does not require also importing the
1901 /// `Cache` type.
1902 ///
1903 /// If you want to reuse the returned `Cache` with some other `PikeVM`,
1904 /// then you must call [`Cache::reset`] with the desired `PikeVM`.
1905 pub fn new(re: &PikeVM) -> Cache {
1906 Cache {
1907 stack: vec![],
1908 curr: ActiveStates::new(re),
1909 next: ActiveStates::new(re),
1910 }
1911 }
1912
1913 /// Reset this cache such that it can be used for searching with a
1914 /// different [`PikeVM`].
1915 ///
1916 /// A cache reset permits reusing memory already allocated in this cache
1917 /// with a different `PikeVM`.
1918 ///
1919 /// # Example
1920 ///
1921 /// This shows how to re-purpose a cache for use with a different `PikeVM`.
1922 ///
1923 /// ```
1924 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1925 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
1926 ///
1927 /// let re1 = PikeVM::new(r"\w")?;
1928 /// let re2 = PikeVM::new(r"\W")?;
1929 ///
1930 /// let mut cache = re1.create_cache();
1931 /// assert_eq!(
1932 /// Some(Match::must(0, 0..2)),
1933 /// re1.find_iter(&mut cache, "Δ").next(),
1934 /// );
1935 ///
1936 /// // Using 'cache' with re2 is not allowed. It may result in panics or
1937 /// // incorrect results. In order to re-purpose the cache, we must reset
1938 /// // it with the PikeVM we'd like to use it with.
1939 /// //
1940 /// // Similarly, after this reset, using the cache with 're1' is also not
1941 /// // allowed.
1942 /// cache.reset(&re2);
1943 /// assert_eq!(
1944 /// Some(Match::must(0, 0..3)),
1945 /// re2.find_iter(&mut cache, "☃").next(),
1946 /// );
1947 ///
1948 /// # Ok::<(), Box<dyn std::error::Error>>(())
1949 /// ```
1950 pub fn reset(&mut self, re: &PikeVM) {
1951 self.curr.reset(re);
1952 self.next.reset(re);
1953 }
1954
1955 /// Returns the heap memory usage, in bytes, of this cache.
1956 ///
1957 /// This does **not** include the stack size used up by this cache. To
1958 /// compute that, use `std::mem::size_of::<Cache>()`.
1959 pub fn memory_usage(&self) -> usize {
1960 use core::mem::size_of;
1961 (self.stack.len() * size_of::<FollowEpsilon>())
1962 + self.curr.memory_usage()
1963 + self.next.memory_usage()
1964 }
1965
1966 /// Clears this cache. This should be called at the start of every search
1967 /// to ensure we start with a clean slate.
1968 ///
1969 /// This also sets the length of the capturing groups used in the current
1970 /// search. This permits an optimization where by 'SlotTable::for_state'
1971 /// only returns the number of slots equivalent to the number of slots
1972 /// given in the 'Captures' value. This may be less than the total number
1973 /// of possible slots, e.g., when one only wants to track overall match
1974 /// offsets. This in turn permits less copying of capturing group spans
1975 /// in the PikeVM.
1976 fn setup_search(&mut self, captures_slot_len: usize) {
1977 self.stack.clear();
1978 self.curr.setup_search(captures_slot_len);
1979 self.next.setup_search(captures_slot_len);
1980 }
1981}
1982
1983/// A set of active states used to "simulate" the execution of an NFA via the
1984/// PikeVM.
1985///
1986/// There are two sets of these used during NFA simulation. One set corresponds
1987/// to the "current" set of states being traversed for the current position
1988/// in a haystack. The other set corresponds to the "next" set of states being
1989/// built, which will become the new "current" set for the next position in the
1990/// haystack. These two sets correspond to CLIST and NLIST in Thompson's
1991/// original paper regexes: https://dl.acm.org/doi/pdf/10.1145/363347.363387
1992///
1993/// In addition to representing a set of NFA states, this also maintains slot
1994/// values for each state. These slot values are what turn the NFA simulation
1995/// into the "Pike VM." Namely, they track capturing group values for each
1996/// state. During the computation of epsilon closure, we copy slot values from
1997/// states in the "current" set to the "next" set. Eventually, once a match
1998/// is found, the slot values for that match state are what we write to the
1999/// caller provided 'Captures' value.
2000#[derive(Clone, Debug)]
2001struct ActiveStates {
2002 /// The set of active NFA states. This set preserves insertion order, which
2003 /// is critical for simulating the match semantics of backtracking regex
2004 /// engines.
2005 set: SparseSet,
2006 /// The slots for every NFA state, where each slot stores a (possibly
2007 /// absent) offset. Every capturing group has two slots. One for a start
2008 /// offset and one for an end offset.
2009 slot_table: SlotTable,
2010}
2011
2012impl ActiveStates {
2013 /// Create a new set of active states for the given PikeVM. The active
2014 /// states returned may only be used with the given PikeVM. (Use 'reset'
2015 /// to re-purpose the allocation for a different PikeVM.)
2016 fn new(re: &PikeVM) -> ActiveStates {
2017 let mut active = ActiveStates {
2018 set: SparseSet::new(0),
2019 slot_table: SlotTable::new(),
2020 };
2021 active.reset(re);
2022 active
2023 }
2024
2025 /// Reset this set of active states such that it can be used with the given
2026 /// PikeVM (and only that PikeVM).
2027 fn reset(&mut self, re: &PikeVM) {
2028 self.set.resize(re.get_nfa().states().len());
2029 self.slot_table.reset(re);
2030 }
2031
2032 /// Return the heap memory usage, in bytes, used by this set of active
2033 /// states.
2034 ///
2035 /// This does not include the stack size of this value.
2036 fn memory_usage(&self) -> usize {
2037 self.set.memory_usage() + self.slot_table.memory_usage()
2038 }
2039
2040 /// Setup this set of active states for a new search. The given slot
2041 /// length should be the number of slots in a caller provided 'Captures'
2042 /// (and may be zero).
2043 fn setup_search(&mut self, captures_slot_len: usize) {
2044 self.set.clear();
2045 self.slot_table.setup_search(captures_slot_len);
2046 }
2047}
2048
2049/// A table of slots, where each row represent a state in an NFA. Thus, the
2050/// table has room for storing slots for every single state in an NFA.
2051///
2052/// This table is represented with a single contiguous allocation. In general,
2053/// the notion of "capturing group" doesn't really exist at this level of
2054/// abstraction, hence the name "slot" instead. (Indeed, every capturing group
2055/// maps to a pair of slots, one for the start offset and one for the end
2056/// offset.) Slots are indexed by the 'Captures' NFA state.
2057///
2058/// N.B. Not every state actually needs a row of slots. Namely, states that
2059/// only have epsilon transitions currently never have anything written to
2060/// their rows in this table. Thus, the table is somewhat wasteful in its heap
2061/// usage. However, it is important to maintain fast random access by state
2062/// ID, which means one giant table tends to work well. RE2 takes a different
2063/// approach here and allocates each row as its own reference counted thing.
2064/// I explored such a strategy at one point here, but couldn't get it to work
2065/// well using entirely safe code. (To the ambitious reader: I encourage you to
2066/// re-litigate that experiment.) I very much wanted to stick to safe code, but
2067/// could be convinced otherwise if there was a solid argument and the safety
2068/// was encapsulated well.
2069#[derive(Clone, Debug)]
2070struct SlotTable {
2071 /// The actual table of offsets.
2072 table: Vec<Option<NonMaxUsize>>,
2073 /// The number of slots per state, i.e., the table's stride or the length
2074 /// of each row.
2075 slots_per_state: usize,
2076 /// The number of slots in the caller-provided 'Captures' value for the
2077 /// current search. Setting this to 'slots_per_state' is always correct,
2078 /// but may be wasteful.
2079 slots_for_captures: usize,
2080}
2081
2082impl SlotTable {
2083 /// Create a new slot table.
2084 ///
2085 /// One should call 'reset' with the corresponding PikeVM before use.
2086 fn new() -> SlotTable {
2087 SlotTable { table: vec![], slots_for_captures: 0, slots_per_state: 0 }
2088 }
2089
2090 /// Reset this slot table such that it can be used with the given PikeVM
2091 /// (and only that PikeVM).
2092 fn reset(&mut self, re: &PikeVM) {
2093 let nfa = re.get_nfa();
2094 self.slots_per_state = nfa.group_info().slot_len();
2095 // This is always correct, but may be reduced for a particular search
2096 // if a 'Captures' has fewer slots, e.g., none at all or only slots
2097 // for tracking the overall match instead of all slots for every
2098 // group.
2099 self.slots_for_captures = core::cmp::max(
2100 self.slots_per_state,
2101 nfa.pattern_len().checked_mul(2).unwrap(),
2102 );
2103 let len = nfa
2104 .states()
2105 .len()
2106 .checked_mul(self.slots_per_state)
2107 // Add space to account for scratch space used during a search.
2108 .and_then(|x| x.checked_add(self.slots_for_captures))
2109 // It seems like this could actually panic on legitimate inputs on
2110 // 32-bit targets, and very likely to panic on 16-bit. Should we
2111 // somehow convert this to an error? What about something similar
2112 // for the lazy DFA cache? If you're tripping this assert, please
2113 // file a bug.
2114 .expect("slot table length doesn't overflow");
2115 // This happens about as often as a regex is compiled, so it probably
2116 // should be at debug level, but I found it quite distracting and not
2117 // particularly useful.
2118 trace!(
2119 "resizing PikeVM active states table to {} entries \
2120 (slots_per_state={})",
2121 len,
2122 self.slots_per_state,
2123 );
2124 self.table.resize(len, None);
2125 }
2126
2127 /// Return the heap memory usage, in bytes, used by this slot table.
2128 ///
2129 /// This does not include the stack size of this value.
2130 fn memory_usage(&self) -> usize {
2131 self.table.len() * core::mem::size_of::<Option<NonMaxUsize>>()
2132 }
2133
2134 /// Perform any per-search setup for this slot table.
2135 ///
2136 /// In particular, this sets the length of the number of slots used in the
2137 /// 'Captures' given by the caller (if any at all). This number may be
2138 /// smaller than the total number of slots available, e.g., when the caller
2139 /// is only interested in tracking the overall match and not the spans of
2140 /// every matching capturing group. Only tracking the overall match can
2141 /// save a substantial amount of time copying capturing spans during a
2142 /// search.
2143 fn setup_search(&mut self, captures_slot_len: usize) {
2144 self.slots_for_captures = captures_slot_len;
2145 }
2146
2147 /// Return a mutable slice of the slots for the given state.
2148 ///
2149 /// Note that the length of the slice returned may be less than the total
2150 /// number of slots available for this state. In particular, the length
2151 /// always matches the number of slots indicated via 'setup_search'.
2152 fn for_state(&mut self, sid: StateID) -> &mut [Option<NonMaxUsize>] {
2153 let i = sid.as_usize() * self.slots_per_state;
2154 &mut self.table[i..i + self.slots_for_captures]
2155 }
2156
2157 /// Return a slice of slots of appropriate length where every slot offset
2158 /// is guaranteed to be absent. This is useful in cases where you need to
2159 /// compute an epsilon closure outside of the user supplied regex, and thus
2160 /// never want it to have any capturing slots set.
2161 fn all_absent(&mut self) -> &mut [Option<NonMaxUsize>] {
2162 let i = self.table.len() - self.slots_for_captures;
2163 &mut self.table[i..i + self.slots_for_captures]
2164 }
2165}
2166
2167/// Represents a stack frame for use while computing an epsilon closure.
2168///
2169/// (An "epsilon closure" refers to the set of reachable NFA states from a
2170/// single state without consuming any input. That is, the set of all epsilon
2171/// transitions not only from that single state, but from every other state
2172/// reachable by an epsilon transition as well. This is why it's called a
2173/// "closure." Computing an epsilon closure is also done during DFA
2174/// determinization! Compare and contrast the epsilon closure here in this
2175/// PikeVM and the one used for determinization in crate::util::determinize.)
2176///
2177/// Computing the epsilon closure in a Thompson NFA proceeds via a depth
2178/// first traversal over all epsilon transitions from a particular state.
2179/// (A depth first traversal is important because it emulates the same priority
2180/// of matches that is typically found in backtracking regex engines.) This
2181/// depth first traversal is naturally expressed using recursion, but to avoid
2182/// a call stack size proportional to the size of a regex, we put our stack on
2183/// the heap instead.
2184///
2185/// This stack thus consists of call frames. The typical call frame is
2186/// `Explore`, which instructs epsilon closure to explore the epsilon
2187/// transitions from that state. (Subsequent epsilon transitions are then
2188/// pushed on to the stack as more `Explore` frames.) If the state ID being
2189/// explored has no epsilon transitions, then the capturing group slots are
2190/// copied from the original state that sparked the epsilon closure (from the
2191/// 'step' routine) to the state ID being explored. This way, capturing group
2192/// slots are forwarded from the previous state to the next.
2193///
2194/// The other stack frame, `RestoreCaptures`, instructs the epsilon closure to
2195/// set the position for a particular slot back to some particular offset. This
2196/// frame is pushed when `Explore` sees a `Capture` transition. `Explore` will
2197/// set the offset of the slot indicated in `Capture` to the current offset,
2198/// and then push the old offset on to the stack as a `RestoreCapture` frame.
2199/// Thus, the new offset is only used until the epsilon closure reverts back to
2200/// the `RestoreCapture` frame. In effect, this gives the `Capture` epsilon
2201/// transition its "scope" to only states that come "after" it during depth
2202/// first traversal.
2203#[derive(Clone, Debug)]
2204enum FollowEpsilon {
2205 /// Explore the epsilon transitions from a state ID.
2206 Explore(StateID),
2207 /// Reset the given `slot` to the given `offset` (which might be `None`).
2208 RestoreCapture { slot: SmallIndex, offset: Option<NonMaxUsize> },
2209}
2210
2211/// A set of counters that "instruments" a PikeVM search. To enable this, you
2212/// must enable the 'internal-instrument-pikevm' feature. Then run your Rust
2213/// program with RUST_LOG=regex_automata::nfa::thompson::pikevm=trace set in
2214/// the environment. The metrics collected will be dumped automatically for
2215/// every search executed by the PikeVM.
2216///
2217/// NOTE: When 'internal-instrument-pikevm' is enabled, it will likely cause an
2218/// absolute decrease in wall-clock performance, even if the 'trace' log level
2219/// isn't enabled. (Although, we do try to avoid extra costs when 'trace' isn't
2220/// enabled.) The main point of instrumentation is to get counts of various
2221/// events that occur during the PikeVM's execution.
2222///
2223/// This is a somewhat hacked together collection of metrics that are useful
2224/// to gather from a PikeVM search. In particular, it lets us scrutinize the
2225/// performance profile of a search beyond what general purpose profiling tools
2226/// give us. Namely, we orient the profiling data around the specific states of
2227/// the NFA.
2228///
2229/// In other words, this lets us see which parts of the NFA graph are most
2230/// frequently activated. This then provides direction for optimization
2231/// opportunities.
2232///
2233/// The really sad part about this is that it absolutely clutters up the PikeVM
2234/// implementation. :'( Another approach would be to just manually add this
2235/// code in whenever I want this kind of profiling data, but it's complicated
2236/// and tedious enough that I went with this approach... for now.
2237///
2238/// When instrumentation is enabled (which also turns on 'logging'), then a
2239/// `Counters` is initialized for every search and `trace`'d just before the
2240/// search returns to the caller.
2241///
2242/// Tip: When debugging performance problems with the PikeVM, it's best to try
2243/// to work with an NFA that is as small as possible. Otherwise the state graph
2244/// is likely to be too big to digest.
2245#[cfg(feature = "internal-instrument-pikevm")]
2246#[derive(Clone, Debug)]
2247struct Counters {
2248 /// The number of times the NFA is in a particular permutation of states.
2249 state_sets: alloc::collections::BTreeMap<Vec<StateID>, u64>,
2250 /// The number of times 'step' is called for a particular state ID (which
2251 /// indexes this array).
2252 steps: Vec<u64>,
2253 /// The number of times an epsilon closure was computed for a state.
2254 closures: Vec<u64>,
2255 /// The number of times a particular state ID is pushed on to a stack while
2256 /// computing an epsilon closure.
2257 stack_pushes: Vec<u64>,
2258 /// The number of times a particular state ID is inserted into a sparse set
2259 /// while computing an epsilon closure.
2260 set_inserts: Vec<u64>,
2261}
2262
2263#[cfg(feature = "internal-instrument-pikevm")]
2264impl Counters {
2265 fn empty() -> Counters {
2266 Counters {
2267 state_sets: alloc::collections::BTreeMap::new(),
2268 steps: vec![],
2269 closures: vec![],
2270 stack_pushes: vec![],
2271 set_inserts: vec![],
2272 }
2273 }
2274
2275 fn reset(&mut self, nfa: &NFA) {
2276 let len = nfa.states().len();
2277
2278 self.state_sets.clear();
2279
2280 self.steps.clear();
2281 self.steps.resize(len, 0);
2282
2283 self.closures.clear();
2284 self.closures.resize(len, 0);
2285
2286 self.stack_pushes.clear();
2287 self.stack_pushes.resize(len, 0);
2288
2289 self.set_inserts.clear();
2290 self.set_inserts.resize(len, 0);
2291 }
2292
2293 fn eprint(&self, nfa: &NFA) {
2294 trace!("===== START PikeVM Instrumentation Output =====");
2295 // We take the top-K most occurring state sets. Otherwise the output
2296 // is likely to be overwhelming. And we probably only care about the
2297 // most frequently occurring ones anyway.
2298 const LIMIT: usize = 20;
2299 let mut set_counts =
2300 self.state_sets.iter().collect::<Vec<(&Vec<StateID>, &u64)>>();
2301 set_counts.sort_by_key(|(_, &count)| core::cmp::Reverse(count));
2302 trace!("## PikeVM frequency of state sets (top {LIMIT})");
2303 for (set, count) in set_counts.iter().take(LIMIT) {
2304 trace!("{set:?}: {count}");
2305 }
2306 if set_counts.len() > LIMIT {
2307 trace!(
2308 "... {} sets omitted (out of {} total)",
2309 set_counts.len() - LIMIT,
2310 set_counts.len(),
2311 );
2312 }
2313
2314 trace!("");
2315 trace!("## PikeVM total frequency of events");
2316 trace!(
2317 "steps: {}, closures: {}, stack-pushes: {}, set-inserts: {}",
2318 self.steps.iter().copied().sum::<u64>(),
2319 self.closures.iter().copied().sum::<u64>(),
2320 self.stack_pushes.iter().copied().sum::<u64>(),
2321 self.set_inserts.iter().copied().sum::<u64>(),
2322 );
2323
2324 trace!("");
2325 trace!("## PikeVM frequency of events broken down by state");
2326 for sid in 0..self.steps.len() {
2327 trace!(
2328 "{:06}: steps: {}, closures: {}, \
2329 stack-pushes: {}, set-inserts: {}",
2330 sid,
2331 self.steps[sid],
2332 self.closures[sid],
2333 self.stack_pushes[sid],
2334 self.set_inserts[sid],
2335 );
2336 }
2337
2338 trace!("");
2339 trace!("## NFA debug display");
2340 trace!("{nfa:?}");
2341 trace!("===== END PikeVM Instrumentation Output =====");
2342 }
2343
2344 fn record_state_set(&mut self, set: &SparseSet) {
2345 let set = set.iter().collect::<Vec<StateID>>();
2346 *self.state_sets.entry(set).or_insert(0) += 1;
2347 }
2348
2349 fn record_step(&mut self, sid: StateID) {
2350 self.steps[sid] += 1;
2351 }
2352
2353 fn record_closure(&mut self, sid: StateID) {
2354 self.closures[sid] += 1;
2355 }
2356
2357 fn record_stack_push(&mut self, sid: StateID) {
2358 self.stack_pushes[sid] += 1;
2359 }
2360
2361 fn record_set_insert(&mut self, sid: StateID) {
2362 self.set_inserts[sid] += 1;
2363 }
2364}