Debian Codegraph @

third_party/rust/regex-automata/src/dfa/automaton.rs

raw
1 #[cfg(feature = "alloc")]
2 use crate::util::search::PatternSet;
3 use crate::{
4 dfa::search,
5 util::{
6 empty,
7 prefilter::Prefilter,
8 primitives::{PatternID, StateID},
9 search::{Anchored, HalfMatch, Input, MatchError},
10 },
11 };
12
13 /// A trait describing the interface of a deterministic finite automaton (DFA).
14 ///
15 /// The complexity of this trait probably means that it's unlikely for others
16 /// to implement it. The primary purpose of the trait is to provide for a way
17 /// of abstracting over different types of DFAs. In this crate, that means
18 /// dense DFAs and sparse DFAs. (Dense DFAs are fast but memory hungry, where
19 /// as sparse DFAs are slower but come with a smaller memory footprint. But
20 /// they otherwise provide exactly equivalent expressive power.) For example, a
21 /// [`dfa::regex::Regex`](crate::dfa::regex::Regex) is generic over this trait.
22 ///
23 /// Normally, a DFA's execution model is very simple. You might have a single
24 /// start state, zero or more final or "match" states and a function that
25 /// transitions from one state to the next given the next byte of input.
26 /// Unfortunately, the interface described by this trait is significantly
27 /// more complicated than this. The complexity has a number of different
28 /// reasons, mostly motivated by performance, functionality or space savings:
29 ///
30 /// * A DFA can search for multiple patterns simultaneously. This
31 /// means extra information is returned when a match occurs. Namely,
32 /// a match is not just an offset, but an offset plus a pattern ID.
33 /// [`Automaton::pattern_len`] returns the number of patterns compiled into
34 /// the DFA, [`Automaton::match_len`] returns the total number of patterns
35 /// that match in a particular state and [`Automaton::match_pattern`] permits
36 /// iterating over the patterns that match in a particular state.
37 /// * A DFA can have multiple start states, and the choice of which start
38 /// state to use depends on the content of the string being searched and
39 /// position of the search, as well as whether the search is an anchored
40 /// search for a specific pattern in the DFA. Moreover, computing the start
41 /// state also depends on whether you're doing a forward or a reverse search.
42 /// [`Automaton::start_state_forward`] and [`Automaton::start_state_reverse`]
43 /// are used to compute the start state for forward and reverse searches,
44 /// respectively.
45 /// * All matches are delayed by one byte to support things like `$` and `\b`
46 /// at the end of a pattern. Therefore, every use of a DFA is required to use
47 /// [`Automaton::next_eoi_state`]
48 /// at the end of the search to compute the final transition.
49 /// * For optimization reasons, some states are treated specially. Every
50 /// state is either special or not, which can be determined via the
51 /// [`Automaton::is_special_state`] method. If it's special, then the state
52 /// must be at least one of a few possible types of states. (Note that some
53 /// types can overlap, for example, a match state can also be an accel state.
54 /// But some types can't. If a state is a dead state, then it can never be any
55 /// other type of state.) Those types are:
56 /// * A dead state. A dead state means the DFA will never enter a match
57 /// state. This can be queried via the [`Automaton::is_dead_state`] method.
58 /// * A quit state. A quit state occurs if the DFA had to stop the search
59 /// prematurely for some reason. This can be queried via the
60 /// [`Automaton::is_quit_state`] method.
61 /// * A match state. A match state occurs when a match is found. When a DFA
62 /// enters a match state, the search may stop immediately (when looking
63 /// for the earliest match), or it may continue to find the leftmost-first
64 /// match. This can be queried via the [`Automaton::is_match_state`]
65 /// method.
66 /// * A start state. A start state is where a search begins. For every
67 /// search, there is exactly one start state that is used, however, a
68 /// DFA may contain many start states. When the search is in a start
69 /// state, it may use a prefilter to quickly skip to candidate matches
70 /// without executing the DFA on every byte. This can be queried via the
71 /// [`Automaton::is_start_state`] method.
72 /// * An accel state. An accel state is a state that is accelerated.
73 /// That is, it is a state where _most_ of its transitions loop back to
74 /// itself and only a small number of transitions lead to other states.
75 /// This kind of state is said to be accelerated because a search routine
76 /// can quickly look for the bytes leading out of the state instead of
77 /// continuing to execute the DFA on each byte. This can be queried via the
78 /// [`Automaton::is_accel_state`] method. And the bytes that lead out of
79 /// the state can be queried via the [`Automaton::accelerator`] method.
80 ///
81 /// There are a number of provided methods on this trait that implement
82 /// efficient searching (for forwards and backwards) with a DFA using
83 /// all of the above features of this trait. In particular, given the
84 /// complexity of all these features, implementing a search routine in
85 /// this trait can be a little subtle. With that said, it is possible to
86 /// somewhat simplify the search routine. For example, handling accelerated
87 /// states is strictly optional, since it is always correct to assume that
88 /// `Automaton::is_accel_state` returns false. However, one complex part of
89 /// writing a search routine using this trait is handling the 1-byte delay of a
90 /// match. That is not optional.
91 ///
92 /// # Safety
93 ///
94 /// This trait is not safe to implement so that code may rely on the
95 /// correctness of implementations of this trait to avoid undefined behavior.
96 /// The primary correctness guarantees are:
97 ///
98 /// * `Automaton::start_state` always returns a valid state ID or an error or
99 /// panics.
100 /// * `Automaton::next_state`, when given a valid state ID, always returns
101 /// a valid state ID for all values of `anchored` and `byte`, or otherwise
102 /// panics.
103 ///
104 /// In general, the rest of the methods on `Automaton` need to uphold their
105 /// contracts as well. For example, `Automaton::is_dead` should only returns
106 /// true if the given state ID is actually a dead state.
107 pub unsafe trait Automaton {
108 /// Transitions from the current state to the next state, given the next
109 /// byte of input.
110 ///
111 /// Implementations must guarantee that the returned ID is always a valid
112 /// ID when `current` refers to a valid ID. Moreover, the transition
113 /// function must be defined for all possible values of `input`.
114 ///
115 /// # Panics
116 ///
117 /// If the given ID does not refer to a valid state, then this routine
118 /// may panic but it also may not panic and instead return an invalid ID.
119 /// However, if the caller provides an invalid ID then this must never
120 /// sacrifice memory safety.
121 ///
122 /// # Example
123 ///
124 /// This shows a simplistic example for walking a DFA for a given haystack
125 /// by using the `next_state` method.
126 ///
127 /// ```
128 /// use regex_automata::{dfa::{Automaton, dense}, Input};
129 ///
130 /// let dfa = dense::DFA::new(r"[a-z]+r")?;
131 /// let haystack = "bar".as_bytes();
132 ///
133 /// // The start state is determined by inspecting the position and the
134 /// // initial bytes of the haystack.
135 /// let mut state = dfa.start_state_forward(&Input::new(haystack))?;
136 /// // Walk all the bytes in the haystack.
137 /// for &b in haystack {
138 /// state = dfa.next_state(state, b);
139 /// }
140 /// // Matches are always delayed by 1 byte, so we must explicitly walk the
141 /// // special "EOI" transition at the end of the search.
142 /// state = dfa.next_eoi_state(state);
143 /// assert!(dfa.is_match_state(state));
144 ///
145 /// # Ok::<(), Box<dyn std::error::Error>>(())
146 /// ```
147 fn next_state(&self, current: StateID, input: u8) -> StateID;
148
149 /// Transitions from the current state to the next state, given the next
150 /// byte of input.
151 ///
152 /// Unlike [`Automaton::next_state`], implementations may implement this
153 /// more efficiently by assuming that the `current` state ID is valid.
154 /// Typically, this manifests by eliding bounds checks.
155 ///
156 /// # Safety
157 ///
158 /// Callers of this method must guarantee that `current` refers to a valid
159 /// state ID. If `current` is not a valid state ID for this automaton, then
160 /// calling this routine may result in undefined behavior.
161 ///
162 /// If `current` is valid, then implementations must guarantee that the ID
163 /// returned is valid for all possible values of `input`.
164 unsafe fn next_state_unchecked(
165 &self,
166 current: StateID,
167 input: u8,
168 ) -> StateID;
169
170 /// Transitions from the current state to the next state for the special
171 /// EOI symbol.
172 ///
173 /// Implementations must guarantee that the returned ID is always a valid
174 /// ID when `current` refers to a valid ID.
175 ///
176 /// This routine must be called at the end of every search in a correct
177 /// implementation of search. Namely, DFAs in this crate delay matches
178 /// by one byte in order to support look-around operators. Thus, after
179 /// reaching the end of a haystack, a search implementation must follow one
180 /// last EOI transition.
181 ///
182 /// It is best to think of EOI as an additional symbol in the alphabet of
183 /// a DFA that is distinct from every other symbol. That is, the alphabet
184 /// of DFAs in this crate has a logical size of 257 instead of 256, where
185 /// 256 corresponds to every possible inhabitant of `u8`. (In practice, the
186 /// physical alphabet size may be smaller because of alphabet compression
187 /// via equivalence classes, but EOI is always represented somehow in the
188 /// alphabet.)
189 ///
190 /// # Panics
191 ///
192 /// If the given ID does not refer to a valid state, then this routine
193 /// may panic but it also may not panic and instead return an invalid ID.
194 /// However, if the caller provides an invalid ID then this must never
195 /// sacrifice memory safety.
196 ///
197 /// # Example
198 ///
199 /// This shows a simplistic example for walking a DFA for a given haystack,
200 /// and then finishing the search with the final EOI transition.
201 ///
202 /// ```
203 /// use regex_automata::{dfa::{Automaton, dense}, Input};
204 ///
205 /// let dfa = dense::DFA::new(r"[a-z]+r")?;
206 /// let haystack = "bar".as_bytes();
207 ///
208 /// // The start state is determined by inspecting the position and the
209 /// // initial bytes of the haystack.
210 /// //
211 /// // The unwrap is OK because we aren't requesting a start state for a
212 /// // specific pattern.
213 /// let mut state = dfa.start_state_forward(&Input::new(haystack))?;
214 /// // Walk all the bytes in the haystack.
215 /// for &b in haystack {
216 /// state = dfa.next_state(state, b);
217 /// }
218 /// // Matches are always delayed by 1 byte, so we must explicitly walk
219 /// // the special "EOI" transition at the end of the search. Without this
220 /// // final transition, the assert below will fail since the DFA will not
221 /// // have entered a match state yet!
222 /// state = dfa.next_eoi_state(state);
223 /// assert!(dfa.is_match_state(state));
224 ///
225 /// # Ok::<(), Box<dyn std::error::Error>>(())
226 /// ```
227 fn next_eoi_state(&self, current: StateID) -> StateID;
228
229 /// Return the ID of the start state for this lazy DFA when executing a
230 /// forward search.
231 ///
232 /// Unlike typical DFA implementations, the start state for DFAs in this
233 /// crate is dependent on a few different factors:
234 ///
235 /// * The [`Anchored`] mode of the search. Unanchored, anchored and
236 /// anchored searches for a specific [`PatternID`] all use different start
237 /// states.
238 /// * The position at which the search begins, via [`Input::start`]. This
239 /// and the byte immediately preceding the start of the search (if one
240 /// exists) influence which look-behind assertions are true at the start
241 /// of the search. This in turn influences which start state is selected.
242 /// * Whether the search is a forward or reverse search. This routine can
243 /// only be used for forward searches.
244 ///
245 /// # Errors
246 ///
247 /// This may return a [`MatchError`] if the search needs to give up
248 /// when determining the start state (for example, if it sees a "quit"
249 /// byte). This can also return an error if the given `Input` contains an
250 /// unsupported [`Anchored`] configuration.
251 fn start_state_forward(
252 &self,
253 input: &Input<'_>,
254 ) -> Result<StateID, MatchError>;
255
256 /// Return the ID of the start state for this lazy DFA when executing a
257 /// reverse search.
258 ///
259 /// Unlike typical DFA implementations, the start state for DFAs in this
260 /// crate is dependent on a few different factors:
261 ///
262 /// * The [`Anchored`] mode of the search. Unanchored, anchored and
263 /// anchored searches for a specific [`PatternID`] all use different start
264 /// states.
265 /// * The position at which the search begins, via [`Input::start`]. This
266 /// and the byte immediately preceding the start of the search (if one
267 /// exists) influence which look-behind assertions are true at the start
268 /// of the search. This in turn influences which start state is selected.
269 /// * Whether the search is a forward or reverse search. This routine can
270 /// only be used for reverse searches.
271 ///
272 /// # Errors
273 ///
274 /// This may return a [`MatchError`] if the search needs to give up
275 /// when determining the start state (for example, if it sees a "quit"
276 /// byte). This can also return an error if the given `Input` contains an
277 /// unsupported [`Anchored`] configuration.
278 fn start_state_reverse(
279 &self,
280 input: &Input<'_>,
281 ) -> Result<StateID, MatchError>;
282
283 /// If this DFA has a universal starting state for the given anchor mode
284 /// and the DFA supports universal starting states, then this returns that
285 /// state's identifier.
286 ///
287 /// A DFA is said to have a universal starting state when the starting
288 /// state is invariant with respect to the haystack. Usually, the starting
289 /// state is chosen depending on the bytes immediately surrounding the
290 /// starting position of a search. However, the starting state only differs
291 /// when one or more of the patterns in the DFA have look-around assertions
292 /// in its prefix.
293 ///
294 /// Stated differently, if none of the patterns in a DFA have look-around
295 /// assertions in their prefix, then the DFA has a universal starting state
296 /// and _may_ be returned by this method.
297 ///
298 /// It is always correct for implementations to return `None`, and indeed,
299 /// this is what the default implementation does. When this returns `None`,
300 /// callers must use either `start_state_forward` or `start_state_reverse`
301 /// to get the starting state.
302 ///
303 /// # Use case
304 ///
305 /// There are a few reasons why one might want to use this:
306 ///
307 /// * If you know your regex patterns have no look-around assertions in
308 /// their prefix, then calling this routine is likely cheaper and perhaps
309 /// more semantically meaningful.
310 /// * When implementing prefilter support in a DFA regex implementation,
311 /// it is necessary to re-compute the start state after a candidate
312 /// is returned from the prefilter. However, this is only needed when
313 /// there isn't a universal start state. When one exists, one can avoid
314 /// re-computing the start state.
315 ///
316 /// # Example
317 ///
318 /// ```
319 /// use regex_automata::{
320 /// dfa::{Automaton, dense::DFA},
321 /// Anchored,
322 /// };
323 ///
324 /// // There are no look-around assertions in the prefixes of any of the
325 /// // patterns, so we get a universal start state.
326 /// let dfa = DFA::new_many(&["[0-9]+", "[a-z]+$", "[A-Z]+"])?;
327 /// assert!(dfa.universal_start_state(Anchored::No).is_some());
328 /// assert!(dfa.universal_start_state(Anchored::Yes).is_some());
329 ///
330 /// // One of the patterns has a look-around assertion in its prefix,
331 /// // so this means there is no longer a universal start state.
332 /// let dfa = DFA::new_many(&["[0-9]+", "^[a-z]+$", "[A-Z]+"])?;
333 /// assert!(!dfa.universal_start_state(Anchored::No).is_some());
334 /// assert!(!dfa.universal_start_state(Anchored::Yes).is_some());
335 /// # Ok::<(), Box<dyn std::error::Error>>(())
336 /// ```
337 #[inline]
338 fn universal_start_state(&self, _mode: Anchored) -> Option<StateID> {
339 None
340 }
341
342 /// Returns true if and only if the given identifier corresponds to a
343 /// "special" state. A special state is one or more of the following:
344 /// a dead state, a quit state, a match state, a start state or an
345 /// accelerated state.
346 ///
347 /// A correct implementation _may_ always return false for states that
348 /// are either start states or accelerated states, since that information
349 /// is only intended to be used for optimization purposes. Correct
350 /// implementations must return true if the state is a dead, quit or match
351 /// state. This is because search routines using this trait must be able
352 /// to rely on `is_special_state` as an indicator that a state may need
353 /// special treatment. (For example, when a search routine sees a dead
354 /// state, it must terminate.)
355 ///
356 /// This routine permits search implementations to use a single branch to
357 /// check whether a state needs special attention before executing the next
358 /// transition. The example below shows how to do this.
359 ///
360 /// # Example
361 ///
362 /// This example shows how `is_special_state` can be used to implement a
363 /// correct search routine with minimal branching. In particular, this
364 /// search routine implements "leftmost" matching, which means that it
365 /// doesn't immediately stop once a match is found. Instead, it continues
366 /// until it reaches a dead state.
367 ///
368 /// ```
369 /// use regex_automata::{
370 /// dfa::{Automaton, dense},
371 /// HalfMatch, MatchError, Input,
372 /// };
373 ///
374 /// fn find<A: Automaton>(
375 /// dfa: &A,
376 /// haystack: &[u8],
377 /// ) -> Result<Option<HalfMatch>, MatchError> {
378 /// // The start state is determined by inspecting the position and the
379 /// // initial bytes of the haystack. Note that start states can never
380 /// // be match states (since DFAs in this crate delay matches by 1
381 /// // byte), so we don't need to check if the start state is a match.
382 /// let mut state = dfa.start_state_forward(&Input::new(haystack))?;
383 /// let mut last_match = None;
384 /// // Walk all the bytes in the haystack. We can quit early if we see
385 /// // a dead or a quit state. The former means the automaton will
386 /// // never transition to any other state. The latter means that the
387 /// // automaton entered a condition in which its search failed.
388 /// for (i, &b) in haystack.iter().enumerate() {
389 /// state = dfa.next_state(state, b);
390 /// if dfa.is_special_state(state) {
391 /// if dfa.is_match_state(state) {
392 /// last_match = Some(HalfMatch::new(
393 /// dfa.match_pattern(state, 0),
394 /// i,
395 /// ));
396 /// } else if dfa.is_dead_state(state) {
397 /// return Ok(last_match);
398 /// } else if dfa.is_quit_state(state) {
399 /// // It is possible to enter into a quit state after
400 /// // observing a match has occurred. In that case, we
401 /// // should return the match instead of an error.
402 /// if last_match.is_some() {
403 /// return Ok(last_match);
404 /// }
405 /// return Err(MatchError::quit(b, i));
406 /// }
407 /// // Implementors may also want to check for start or accel
408 /// // states and handle them differently for performance
409 /// // reasons. But it is not necessary for correctness.
410 /// }
411 /// }
412 /// // Matches are always delayed by 1 byte, so we must explicitly walk
413 /// // the special "EOI" transition at the end of the search.
414 /// state = dfa.next_eoi_state(state);
415 /// if dfa.is_match_state(state) {
416 /// last_match = Some(HalfMatch::new(
417 /// dfa.match_pattern(state, 0),
418 /// haystack.len(),
419 /// ));
420 /// }
421 /// Ok(last_match)
422 /// }
423 ///
424 /// // We use a greedy '+' operator to show how the search doesn't just
425 /// // stop once a match is detected. It continues extending the match.
426 /// // Using '[a-z]+?' would also work as expected and stop the search
427 /// // early. Greediness is built into the automaton.
428 /// let dfa = dense::DFA::new(r"[a-z]+")?;
429 /// let haystack = "123 foobar 4567".as_bytes();
430 /// let mat = find(&dfa, haystack)?.unwrap();
431 /// assert_eq!(mat.pattern().as_usize(), 0);
432 /// assert_eq!(mat.offset(), 10);
433 ///
434 /// // Here's another example that tests our handling of the special EOI
435 /// // transition. This will fail to find a match if we don't call
436 /// // 'next_eoi_state' at the end of the search since the match isn't
437 /// // found until the final byte in the haystack.
438 /// let dfa = dense::DFA::new(r"[0-9]{4}")?;
439 /// let haystack = "123 foobar 4567".as_bytes();
440 /// let mat = find(&dfa, haystack)?.unwrap();
441 /// assert_eq!(mat.pattern().as_usize(), 0);
442 /// assert_eq!(mat.offset(), 15);
443 ///
444 /// // And note that our search implementation above automatically works
445 /// // with multi-DFAs. Namely, `dfa.match_pattern(match_state, 0)` selects
446 /// // the appropriate pattern ID for us.
447 /// let dfa = dense::DFA::new_many(&[r"[a-z]+", r"[0-9]+"])?;
448 /// let haystack = "123 foobar 4567".as_bytes();
449 /// let mat = find(&dfa, haystack)?.unwrap();
450 /// assert_eq!(mat.pattern().as_usize(), 1);
451 /// assert_eq!(mat.offset(), 3);
452 /// let mat = find(&dfa, &haystack[3..])?.unwrap();
453 /// assert_eq!(mat.pattern().as_usize(), 0);
454 /// assert_eq!(mat.offset(), 7);
455 /// let mat = find(&dfa, &haystack[10..])?.unwrap();
456 /// assert_eq!(mat.pattern().as_usize(), 1);
457 /// assert_eq!(mat.offset(), 5);
458 ///
459 /// # Ok::<(), Box<dyn std::error::Error>>(())
460 /// ```
461 fn is_special_state(&self, id: StateID) -> bool;
462
463 /// Returns true if and only if the given identifier corresponds to a dead
464 /// state. When a DFA enters a dead state, it is impossible to leave. That
465 /// is, every transition on a dead state by definition leads back to the
466 /// same dead state.
467 ///
468 /// In practice, the dead state always corresponds to the identifier `0`.
469 /// Moreover, in practice, there is only one dead state.
470 ///
471 /// The existence of a dead state is not strictly required in the classical
472 /// model of finite state machines, where one generally only cares about
473 /// the question of whether an input sequence matches or not. Dead states
474 /// are not needed to answer that question, since one can immediately quit
475 /// as soon as one enters a final or "match" state. However, we don't just
476 /// care about matches but also care about the location of matches, and
477 /// more specifically, care about semantics like "greedy" matching.
478 ///
479 /// For example, given the pattern `a+` and the input `aaaz`, the dead
480 /// state won't be entered until the state machine reaches `z` in the
481 /// input, at which point, the search routine can quit. But without the
482 /// dead state, the search routine wouldn't know when to quit. In a
483 /// classical representation, the search routine would stop after seeing
484 /// the first `a` (which is when the search would enter a match state). But
485 /// this wouldn't implement "greedy" matching where `a+` matches as many
486 /// `a`'s as possible.
487 ///
488 /// # Example
489 ///
490 /// See the example for [`Automaton::is_special_state`] for how to use this
491 /// method correctly.
492 fn is_dead_state(&self, id: StateID) -> bool;
493
494 /// Returns true if and only if the given identifier corresponds to a quit
495 /// state. A quit state is like a dead state (it has no transitions other
496 /// than to itself), except it indicates that the DFA failed to complete
497 /// the search. When this occurs, callers can neither accept or reject that
498 /// a match occurred.
499 ///
500 /// In practice, the quit state always corresponds to the state immediately
501 /// following the dead state. (Which is not usually represented by `1`,
502 /// since state identifiers are pre-multiplied by the state machine's
503 /// alphabet stride, and the alphabet stride varies between DFAs.)
504 ///
505 /// The typical way in which a quit state can occur is when heuristic
506 /// support for Unicode word boundaries is enabled via the
507 /// [`dense::Config::unicode_word_boundary`](crate::dfa::dense::Config::unicode_word_boundary)
508 /// option. But other options, like the lower level
509 /// [`dense::Config::quit`](crate::dfa::dense::Config::quit)
510 /// configuration, can also result in a quit state being entered. The
511 /// purpose of the quit state is to provide a way to execute a fast DFA
512 /// in common cases while delegating to slower routines when the DFA quits.
513 ///
514 /// The default search implementations provided by this crate will return a
515 /// [`MatchError::quit`] error when a quit state is entered.
516 ///
517 /// # Example
518 ///
519 /// See the example for [`Automaton::is_special_state`] for how to use this
520 /// method correctly.
521 fn is_quit_state(&self, id: StateID) -> bool;
522
523 /// Returns true if and only if the given identifier corresponds to a
524 /// match state. A match state is also referred to as a "final" state and
525 /// indicates that a match has been found.
526 ///
527 /// If all you care about is whether a particular pattern matches in the
528 /// input sequence, then a search routine can quit early as soon as the
529 /// machine enters a match state. However, if you're looking for the
530 /// standard "leftmost-first" match location, then search _must_ continue
531 /// until either the end of the input or until the machine enters a dead
532 /// state. (Since either condition implies that no other useful work can
533 /// be done.) Namely, when looking for the location of a match, then
534 /// search implementations should record the most recent location in
535 /// which a match state was entered, but otherwise continue executing the
536 /// search as normal. (The search may even leave the match state.) Once
537 /// the termination condition is reached, the most recently recorded match
538 /// location should be returned.
539 ///
540 /// Finally, one additional power given to match states in this crate
541 /// is that they are always associated with a specific pattern in order
542 /// to support multi-DFAs. See [`Automaton::match_pattern`] for more
543 /// details and an example for how to query the pattern associated with a
544 /// particular match state.
545 ///
546 /// # Example
547 ///
548 /// See the example for [`Automaton::is_special_state`] for how to use this
549 /// method correctly.
550 fn is_match_state(&self, id: StateID) -> bool;
551
552 /// Returns true only if the given identifier corresponds to a start
553 /// state
554 ///
555 /// A start state is a state in which a DFA begins a search.
556 /// All searches begin in a start state. Moreover, since all matches are
557 /// delayed by one byte, a start state can never be a match state.
558 ///
559 /// The main role of a start state is, as mentioned, to be a starting
560 /// point for a DFA. This starting point is determined via one of
561 /// [`Automaton::start_state_forward`] or
562 /// [`Automaton::start_state_reverse`], depending on whether one is doing
563 /// a forward or a reverse search, respectively.
564 ///
565 /// A secondary use of start states is for prefix acceleration. Namely,
566 /// while executing a search, if one detects that you're in a start state,
567 /// then it may be faster to look for the next match of a prefix of the
568 /// pattern, if one exists. If a prefix exists and since all matches must
569 /// begin with that prefix, then skipping ahead to occurrences of that
570 /// prefix may be much faster than executing the DFA.
571 ///
572 /// As mentioned in the documentation for
573 /// [`is_special_state`](Automaton::is_special_state) implementations
574 /// _may_ always return false, even if the given identifier is a start
575 /// state. This is because knowing whether a state is a start state or not
576 /// is not necessary for correctness and is only treated as a potential
577 /// performance optimization. (For example, the implementations of this
578 /// trait in this crate will only return true when the given identifier
579 /// corresponds to a start state and when [specialization of start
580 /// states](crate::dfa::dense::Config::specialize_start_states) was enabled
581 /// during DFA construction. If start state specialization is disabled
582 /// (which is the default), then this method will always return false.)
583 ///
584 /// # Example
585 ///
586 /// This example shows how to implement your own search routine that does
587 /// a prefix search whenever the search enters a start state.
588 ///
589 /// Note that you do not need to implement your own search routine
590 /// to make use of prefilters like this. The search routines
591 /// provided by this crate already implement prefilter support via
592 /// the [`Prefilter`](crate::util::prefilter::Prefilter) trait.
593 /// A prefilter can be added to your search configuration with
594 /// [`dense::Config::prefilter`](crate::dfa::dense::Config::prefilter) for
595 /// dense and sparse DFAs in this crate.
596 ///
597 /// This example is meant to show how you might deal with prefilters in a
598 /// simplified case if you are implementing your own search routine.
599 ///
600 /// ```
601 /// use regex_automata::{
602 /// dfa::{Automaton, dense},
603 /// HalfMatch, MatchError, Input,
604 /// };
605 ///
606 /// fn find_byte(slice: &[u8], at: usize, byte: u8) -> Option<usize> {
607 /// // Would be faster to use the memchr crate, but this is still
608 /// // faster than running through the DFA.
609 /// slice[at..].iter().position(|&b| b == byte).map(|i| at + i)
610 /// }
611 ///
612 /// fn find<A: Automaton>(
613 /// dfa: &A,
614 /// haystack: &[u8],
615 /// prefix_byte: Option<u8>,
616 /// ) -> Result<Option<HalfMatch>, MatchError> {
617 /// // See the Automaton::is_special_state example for similar code
618 /// // with more comments.
619 ///
620 /// let mut state = dfa.start_state_forward(&Input::new(haystack))?;
621 /// let mut last_match = None;
622 /// let mut pos = 0;
623 /// while pos < haystack.len() {
624 /// let b = haystack[pos];
625 /// state = dfa.next_state(state, b);
626 /// pos += 1;
627 /// if dfa.is_special_state(state) {
628 /// if dfa.is_match_state(state) {
629 /// last_match = Some(HalfMatch::new(
630 /// dfa.match_pattern(state, 0),
631 /// pos - 1,
632 /// ));
633 /// } else if dfa.is_dead_state(state) {
634 /// return Ok(last_match);
635 /// } else if dfa.is_quit_state(state) {
636 /// // It is possible to enter into a quit state after
637 /// // observing a match has occurred. In that case, we
638 /// // should return the match instead of an error.
639 /// if last_match.is_some() {
640 /// return Ok(last_match);
641 /// }
642 /// return Err(MatchError::quit(b, pos - 1));
643 /// } else if dfa.is_start_state(state) {
644 /// // If we're in a start state and know all matches begin
645 /// // with a particular byte, then we can quickly skip to
646 /// // candidate matches without running the DFA through
647 /// // every byte inbetween.
648 /// if let Some(prefix_byte) = prefix_byte {
649 /// pos = match find_byte(haystack, pos, prefix_byte) {
650 /// Some(pos) => pos,
651 /// None => break,
652 /// };
653 /// }
654 /// }
655 /// }
656 /// }
657 /// // Matches are always delayed by 1 byte, so we must explicitly walk
658 /// // the special "EOI" transition at the end of the search.
659 /// state = dfa.next_eoi_state(state);
660 /// if dfa.is_match_state(state) {
661 /// last_match = Some(HalfMatch::new(
662 /// dfa.match_pattern(state, 0),
663 /// haystack.len(),
664 /// ));
665 /// }
666 /// Ok(last_match)
667 /// }
668 ///
669 /// // In this example, it's obvious that all occurrences of our pattern
670 /// // begin with 'Z', so we pass in 'Z'. Note also that we need to
671 /// // enable start state specialization, or else it won't be possible to
672 /// // detect start states during a search. ('is_start_state' would always
673 /// // return false.)
674 /// let dfa = dense::DFA::builder()
675 /// .configure(dense::DFA::config().specialize_start_states(true))
676 /// .build(r"Z[a-z]+")?;
677 /// let haystack = "123 foobar Zbaz quux".as_bytes();
678 /// let mat = find(&dfa, haystack, Some(b'Z'))?.unwrap();
679 /// assert_eq!(mat.pattern().as_usize(), 0);
680 /// assert_eq!(mat.offset(), 15);
681 ///
682 /// // But note that we don't need to pass in a prefix byte. If we don't,
683 /// // then the search routine does no acceleration.
684 /// let mat = find(&dfa, haystack, None)?.unwrap();
685 /// assert_eq!(mat.pattern().as_usize(), 0);
686 /// assert_eq!(mat.offset(), 15);
687 ///
688 /// // However, if we pass an incorrect byte, then the prefix search will
689 /// // result in incorrect results.
690 /// assert_eq!(find(&dfa, haystack, Some(b'X'))?, None);
691 ///
692 /// # Ok::<(), Box<dyn std::error::Error>>(())
693 /// ```
694 fn is_start_state(&self, id: StateID) -> bool;
695
696 /// Returns true if and only if the given identifier corresponds to an
697 /// accelerated state.
698 ///
699 /// An accelerated state is a special optimization
700 /// trick implemented by this crate. Namely, if
701 /// [`dense::Config::accelerate`](crate::dfa::dense::Config::accelerate) is
702 /// enabled (and it is by default), then DFAs generated by this crate will
703 /// tag states meeting certain characteristics as accelerated. States meet
704 /// this criteria whenever most of their transitions are self-transitions.
705 /// That is, transitions that loop back to the same state. When a small
706 /// number of transitions aren't self-transitions, then it follows that
707 /// there are only a small number of bytes that can cause the DFA to leave
708 /// that state. Thus, there is an opportunity to look for those bytes
709 /// using more optimized routines rather than continuing to run through
710 /// the DFA. This trick is similar to the prefilter idea described in
711 /// the documentation of [`Automaton::is_start_state`] with two main
712 /// differences:
713 ///
714 /// 1. It is more limited since acceleration only applies to single bytes.
715 /// This means states are rarely accelerated when Unicode mode is enabled
716 /// (which is enabled by default).
717 /// 2. It can occur anywhere in the DFA, which increases optimization
718 /// opportunities.
719 ///
720 /// Like the prefilter idea, the main downside (and a possible reason to
721 /// disable it) is that it can lead to worse performance in some cases.
722 /// Namely, if a state is accelerated for very common bytes, then the
723 /// overhead of checking for acceleration and using the more optimized
724 /// routines to look for those bytes can cause overall performance to be
725 /// worse than if acceleration wasn't enabled at all.
726 ///
727 /// A simple example of a regex that has an accelerated state is
728 /// `(?-u)[^a]+a`. Namely, the `[^a]+` sub-expression gets compiled down
729 /// into a single state where all transitions except for `a` loop back to
730 /// itself, and where `a` is the only transition (other than the special
731 /// EOI transition) that goes to some other state. Thus, this state can
732 /// be accelerated and implemented more efficiently by calling an
733 /// optimized routine like `memchr` with `a` as the needle. Notice that
734 /// the `(?-u)` to disable Unicode is necessary here, as without it,
735 /// `[^a]` will match any UTF-8 encoding of any Unicode scalar value other
736 /// than `a`. This more complicated expression compiles down to many DFA
737 /// states and the simple acceleration optimization is no longer available.
738 ///
739 /// Typically, this routine is used to guard calls to
740 /// [`Automaton::accelerator`], which returns the accelerated bytes for
741 /// the specified state.
742 fn is_accel_state(&self, id: StateID) -> bool;
743
744 /// Returns the total number of patterns compiled into this DFA.
745 ///
746 /// In the case of a DFA that contains no patterns, this must return `0`.
747 ///
748 /// # Example
749 ///
750 /// This example shows the pattern length for a DFA that never matches:
751 ///
752 /// ```
753 /// use regex_automata::dfa::{Automaton, dense::DFA};
754 ///
755 /// let dfa: DFA<Vec<u32>> = DFA::never_match()?;
756 /// assert_eq!(dfa.pattern_len(), 0);
757 /// # Ok::<(), Box<dyn std::error::Error>>(())
758 /// ```
759 ///
760 /// And another example for a DFA that matches at every position:
761 ///
762 /// ```
763 /// use regex_automata::dfa::{Automaton, dense::DFA};
764 ///
765 /// let dfa: DFA<Vec<u32>> = DFA::always_match()?;
766 /// assert_eq!(dfa.pattern_len(), 1);
767 /// # Ok::<(), Box<dyn std::error::Error>>(())
768 /// ```
769 ///
770 /// And finally, a DFA that was constructed from multiple patterns:
771 ///
772 /// ```
773 /// use regex_automata::dfa::{Automaton, dense::DFA};
774 ///
775 /// let dfa = DFA::new_many(&["[0-9]+", "[a-z]+", "[A-Z]+"])?;
776 /// assert_eq!(dfa.pattern_len(), 3);
777 /// # Ok::<(), Box<dyn std::error::Error>>(())
778 /// ```
779 fn pattern_len(&self) -> usize;
780
781 /// Returns the total number of patterns that match in this state.
782 ///
783 /// If the given state is not a match state, then implementations may
784 /// panic.
785 ///
786 /// If the DFA was compiled with one pattern, then this must necessarily
787 /// always return `1` for all match states.
788 ///
789 /// Implementations must guarantee that [`Automaton::match_pattern`] can be
790 /// called with indices up to (but not including) the length returned by
791 /// this routine without panicking.
792 ///
793 /// # Panics
794 ///
795 /// Implementations are permitted to panic if the provided state ID does
796 /// not correspond to a match state.
797 ///
798 /// # Example
799 ///
800 /// This example shows a simple instance of implementing overlapping
801 /// matches. In particular, it shows not only how to determine how many
802 /// patterns have matched in a particular state, but also how to access
803 /// which specific patterns have matched.
804 ///
805 /// Notice that we must use
806 /// [`MatchKind::All`](crate::MatchKind::All)
807 /// when building the DFA. If we used
808 /// [`MatchKind::LeftmostFirst`](crate::MatchKind::LeftmostFirst)
809 /// instead, then the DFA would not be constructed in a way that
810 /// supports overlapping matches. (It would only report a single pattern
811 /// that matches at any particular point in time.)
812 ///
813 /// Another thing to take note of is the patterns used and the order in
814 /// which the pattern IDs are reported. In the example below, pattern `3`
815 /// is yielded first. Why? Because it corresponds to the match that
816 /// appears first. Namely, the `@` symbol is part of `\S+` but not part
817 /// of any of the other patterns. Since the `\S+` pattern has a match that
818 /// starts to the left of any other pattern, its ID is returned before any
819 /// other.
820 ///
821 /// ```
822 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
823 /// use regex_automata::{dfa::{Automaton, dense}, Input, MatchKind};
824 ///
825 /// let dfa = dense::Builder::new()
826 /// .configure(dense::Config::new().match_kind(MatchKind::All))
827 /// .build_many(&[
828 /// r"[[:word:]]+", r"[a-z]+", r"[A-Z]+", r"[[:^space:]]+",
829 /// ])?;
830 /// let haystack = "@bar".as_bytes();
831 ///
832 /// // The start state is determined by inspecting the position and the
833 /// // initial bytes of the haystack.
834 /// let mut state = dfa.start_state_forward(&Input::new(haystack))?;
835 /// // Walk all the bytes in the haystack.
836 /// for &b in haystack {
837 /// state = dfa.next_state(state, b);
838 /// }
839 /// state = dfa.next_eoi_state(state);
840 ///
841 /// assert!(dfa.is_match_state(state));
842 /// assert_eq!(dfa.match_len(state), 3);
843 /// // The following calls are guaranteed to not panic since `match_len`
844 /// // returned `3` above.
845 /// assert_eq!(dfa.match_pattern(state, 0).as_usize(), 3);
846 /// assert_eq!(dfa.match_pattern(state, 1).as_usize(), 0);
847 /// assert_eq!(dfa.match_pattern(state, 2).as_usize(), 1);
848 ///
849 /// # Ok::<(), Box<dyn std::error::Error>>(())
850 /// ```
851 fn match_len(&self, id: StateID) -> usize;
852
853 /// Returns the pattern ID corresponding to the given match index in the
854 /// given state.
855 ///
856 /// See [`Automaton::match_len`] for an example of how to use this
857 /// method correctly. Note that if you know your DFA is compiled with a
858 /// single pattern, then this routine is never necessary since it will
859 /// always return a pattern ID of `0` for an index of `0` when `id`
860 /// corresponds to a match state.
861 ///
862 /// Typically, this routine is used when implementing an overlapping
863 /// search, as the example for `Automaton::match_len` does.
864 ///
865 /// # Panics
866 ///
867 /// If the state ID is not a match state or if the match index is out
868 /// of bounds for the given state, then this routine may either panic
869 /// or produce an incorrect result. If the state ID is correct and the
870 /// match index is correct, then this routine must always produce a valid
871 /// `PatternID`.
872 fn match_pattern(&self, id: StateID, index: usize) -> PatternID;
873
874 /// Returns true if and only if this automaton can match the empty string.
875 /// When it returns false, all possible matches are guaranteed to have a
876 /// non-zero length.
877 ///
878 /// This is useful as cheap way to know whether code needs to handle the
879 /// case of a zero length match. This is particularly important when UTF-8
880 /// modes are enabled, as when UTF-8 mode is enabled, empty matches that
881 /// split a codepoint must never be reported. This extra handling can
882 /// sometimes be costly, and since regexes matching an empty string are
883 /// somewhat rare, it can be beneficial to treat such regexes specially.
884 ///
885 /// # Example
886 ///
887 /// This example shows a few different DFAs and whether they match the
888 /// empty string or not. Notice the empty string isn't merely a matter
889 /// of a string of length literally `0`, but rather, whether a match can
890 /// occur between specific pairs of bytes.
891 ///
892 /// ```
893 /// use regex_automata::{dfa::{dense::DFA, Automaton}, util::syntax};
894 ///
895 /// // The empty regex matches the empty string.
896 /// let dfa = DFA::new("")?;
897 /// assert!(dfa.has_empty(), "empty matches empty");
898 /// // The '+' repetition operator requires at least one match, and so
899 /// // does not match the empty string.
900 /// let dfa = DFA::new("a+")?;
901 /// assert!(!dfa.has_empty(), "+ does not match empty");
902 /// // But the '*' repetition operator does.
903 /// let dfa = DFA::new("a*")?;
904 /// assert!(dfa.has_empty(), "* does match empty");
905 /// // And wrapping '+' in an operator that can match an empty string also
906 /// // causes it to match the empty string too.
907 /// let dfa = DFA::new("(a+)*")?;
908 /// assert!(dfa.has_empty(), "+ inside of * matches empty");
909 ///
910 /// // If a regex is just made of a look-around assertion, even if the
911 /// // assertion requires some kind of non-empty string around it (such as
912 /// // \b), then it is still treated as if it matches the empty string.
913 /// // Namely, if a match occurs of just a look-around assertion, then the
914 /// // match returned is empty.
915 /// let dfa = DFA::builder()
916 /// .configure(DFA::config().unicode_word_boundary(true))
917 /// .syntax(syntax::Config::new().utf8(false))
918 /// .build(r"^$\A\z\b\B(?-u:\b\B)")?;
919 /// assert!(dfa.has_empty(), "assertions match empty");
920 /// // Even when an assertion is wrapped in a '+', it still matches the
921 /// // empty string.
922 /// let dfa = DFA::new(r"^+")?;
923 /// assert!(dfa.has_empty(), "+ of an assertion matches empty");
924 ///
925 /// // An alternation with even one branch that can match the empty string
926 /// // is also said to match the empty string overall.
927 /// let dfa = DFA::new("foo|(bar)?|quux")?;
928 /// assert!(dfa.has_empty(), "alternations can match empty");
929 ///
930 /// // An NFA that matches nothing does not match the empty string.
931 /// let dfa = DFA::new("[a&&b]")?;
932 /// assert!(!dfa.has_empty(), "never matching means not matching empty");
933 /// // But if it's wrapped in something that doesn't require a match at
934 /// // all, then it can match the empty string!
935 /// let dfa = DFA::new("[a&&b]*")?;
936 /// assert!(dfa.has_empty(), "* on never-match still matches empty");
937 /// // Since a '+' requires a match, using it on something that can never
938 /// // match will itself produce a regex that can never match anything,
939 /// // and thus does not match the empty string.
940 /// let dfa = DFA::new("[a&&b]+")?;
941 /// assert!(!dfa.has_empty(), "+ on never-match still matches nothing");
942 ///
943 /// # Ok::<(), Box<dyn std::error::Error>>(())
944 /// ```
945 fn has_empty(&self) -> bool;
946
947 /// Whether UTF-8 mode is enabled for this DFA or not.
948 ///
949 /// When UTF-8 mode is enabled, all matches reported by a DFA are
950 /// guaranteed to correspond to spans of valid UTF-8. This includes
951 /// zero-width matches. For example, the DFA must guarantee that the empty
952 /// regex will not match at the positions between code units in the UTF-8
953 /// encoding of a single codepoint.
954 ///
955 /// See [`thompson::Config::utf8`](crate::nfa::thompson::Config::utf8) for
956 /// more information.
957 ///
958 /// # Example
959 ///
960 /// This example shows how UTF-8 mode can impact the match spans that may
961 /// be reported in certain cases.
962 ///
963 /// ```
964 /// use regex_automata::{
965 /// dfa::{dense::DFA, Automaton},
966 /// nfa::thompson,
967 /// HalfMatch, Input,
968 /// };
969 ///
970 /// // UTF-8 mode is enabled by default.
971 /// let re = DFA::new("")?;
972 /// assert!(re.is_utf8());
973 /// let mut input = Input::new("☃");
974 /// let got = re.try_search_fwd(&input)?;
975 /// assert_eq!(Some(HalfMatch::must(0, 0)), got);
976 ///
977 /// // Even though an empty regex matches at 1..1, our next match is
978 /// // 3..3 because 1..1 and 2..2 split the snowman codepoint (which is
979 /// // three bytes long).
980 /// input.set_start(1);
981 /// let got = re.try_search_fwd(&input)?;
982 /// assert_eq!(Some(HalfMatch::must(0, 3)), got);
983 ///
984 /// // But if we disable UTF-8, then we'll get matches at 1..1 and 2..2:
985 /// let re = DFA::builder()
986 /// .thompson(thompson::Config::new().utf8(false))
987 /// .build("")?;
988 /// assert!(!re.is_utf8());
989 /// let got = re.try_search_fwd(&input)?;
990 /// assert_eq!(Some(HalfMatch::must(0, 1)), got);
991 ///
992 /// input.set_start(2);
993 /// let got = re.try_search_fwd(&input)?;
994 /// assert_eq!(Some(HalfMatch::must(0, 2)), got);
995 ///
996 /// input.set_start(3);
997 /// let got = re.try_search_fwd(&input)?;
998 /// assert_eq!(Some(HalfMatch::must(0, 3)), got);
999 ///
1000 /// input.set_start(4);
1001 /// let got = re.try_search_fwd(&input)?;
1002 /// assert_eq!(None, got);
1003 ///
1004 /// # Ok::<(), Box<dyn std::error::Error>>(())
1005 /// ```
1006 fn is_utf8(&self) -> bool;
1007
1008 /// Returns true if and only if this DFA is limited to returning matches
1009 /// whose start position is `0`.
1010 ///
1011 /// Note that if you're using DFAs provided by
1012 /// this crate, then this is _orthogonal_ to
1013 /// [`Config::start_kind`](crate::dfa::dense::Config::start_kind).
1014 ///
1015 /// This is useful in some cases because if a DFA is limited to producing
1016 /// matches that start at offset `0`, then a reverse search is never
1017 /// required for finding the start of a match.
1018 ///
1019 /// # Example
1020 ///
1021 /// ```
1022 /// use regex_automata::dfa::{dense::DFA, Automaton};
1023 ///
1024 /// // The empty regex matches anywhere
1025 /// let dfa = DFA::new("")?;
1026 /// assert!(!dfa.is_always_start_anchored(), "empty matches anywhere");
1027 /// // 'a' matches anywhere.
1028 /// let dfa = DFA::new("a")?;
1029 /// assert!(!dfa.is_always_start_anchored(), "'a' matches anywhere");
1030 /// // '^' only matches at offset 0!
1031 /// let dfa = DFA::new("^a")?;
1032 /// assert!(dfa.is_always_start_anchored(), "'^a' matches only at 0");
1033 /// // But '(?m:^)' matches at 0 but at other offsets too.
1034 /// let dfa = DFA::new("(?m:^)a")?;
1035 /// assert!(!dfa.is_always_start_anchored(), "'(?m:^)a' matches anywhere");
1036 ///
1037 /// # Ok::<(), Box<dyn std::error::Error>>(())
1038 /// ```
1039 fn is_always_start_anchored(&self) -> bool;
1040
1041 /// Return a slice of bytes to accelerate for the given state, if possible.
1042 ///
1043 /// If the given state has no accelerator, then an empty slice must be
1044 /// returned. If `Automaton::is_accel_state` returns true for the given ID,
1045 /// then this routine _must_ return a non-empty slice. But note that it is
1046 /// not required for an implementation of this trait to ever return `true`
1047 /// for `is_accel_state`, even if the state _could_ be accelerated. That
1048 /// is, acceleration is an optional optimization. But the return values of
1049 /// `is_accel_state` and `accelerator` must be in sync.
1050 ///
1051 /// If the given ID is not a valid state ID for this automaton, then
1052 /// implementations may panic or produce incorrect results.
1053 ///
1054 /// See [`Automaton::is_accel_state`] for more details on state
1055 /// acceleration.
1056 ///
1057 /// By default, this method will always return an empty slice.
1058 ///
1059 /// # Example
1060 ///
1061 /// This example shows a contrived case in which we build a regex that we
1062 /// know is accelerated and extract the accelerator from a state.
1063 ///
1064 /// ```
1065 /// use regex_automata::{
1066 /// dfa::{Automaton, dense},
1067 /// util::{primitives::StateID, syntax},
1068 /// };
1069 ///
1070 /// let dfa = dense::Builder::new()
1071 /// // We disable Unicode everywhere and permit the regex to match
1072 /// // invalid UTF-8. e.g., [^abc] matches \xFF, which is not valid
1073 /// // UTF-8. If we left Unicode enabled, [^abc] would match any UTF-8
1074 /// // encoding of any Unicode scalar value except for 'a', 'b' or 'c'.
1075 /// // That translates to a much more complicated DFA, and also
1076 /// // inhibits the 'accelerator' optimization that we are trying to
1077 /// // demonstrate in this example.
1078 /// .syntax(syntax::Config::new().unicode(false).utf8(false))
1079 /// .build("[^abc]+a")?;
1080 ///
1081 /// // Here we just pluck out the state that we know is accelerated.
1082 /// // While the stride calculations are something that can be relied
1083 /// // on by callers, the specific position of the accelerated state is
1084 /// // implementation defined.
1085 /// //
1086 /// // N.B. We get '3' by inspecting the state machine using 'regex-cli'.
1087 /// // e.g., try `regex-cli debug dfa dense '[^abc]+a' -BbUC`.
1088 /// let id = StateID::new(3 * dfa.stride()).unwrap();
1089 /// let accelerator = dfa.accelerator(id);
1090 /// // The `[^abc]+` sub-expression permits [a, b, c] to be accelerated.
1091 /// assert_eq!(accelerator, &[b'a', b'b', b'c']);
1092 /// # Ok::<(), Box<dyn std::error::Error>>(())
1093 /// ```
1094 #[inline]
1095 fn accelerator(&self, _id: StateID) -> &[u8] {
1096 &[]
1097 }
1098
1099 /// Returns the prefilter associated with a DFA, if one exists.
1100 ///
1101 /// The default implementation of this trait always returns `None`. And
1102 /// indeed, it is always correct to return `None`.
1103 ///
1104 /// For DFAs in this crate, a prefilter can be attached to a DFA via
1105 /// [`dense::Config::prefilter`](crate::dfa::dense::Config::prefilter).
1106 ///
1107 /// Do note that prefilters are not serialized by DFAs in this crate.
1108 /// So if you deserialize a DFA that had a prefilter attached to it
1109 /// at serialization time, then it will not have a prefilter after
1110 /// deserialization.
1111 #[inline]
1112 fn get_prefilter(&self) -> Option<&Prefilter> {
1113 None
1114 }
1115
1116 /// Executes a forward search and returns the end position of the leftmost
1117 /// match that is found. If no match exists, then `None` is returned.
1118 ///
1119 /// In particular, this method continues searching even after it enters
1120 /// a match state. The search only terminates once it has reached the
1121 /// end of the input or when it has entered a dead or quit state. Upon
1122 /// termination, the position of the last byte seen while still in a match
1123 /// state is returned.
1124 ///
1125 /// # Errors
1126 ///
1127 /// This routine errors if the search could not complete. This can occur
1128 /// in a number of circumstances:
1129 ///
1130 /// * The configuration of the DFA may permit it to "quit" the search.
1131 /// For example, setting quit bytes or enabling heuristic support for
1132 /// Unicode word boundaries. The default configuration does not enable any
1133 /// option that could result in the DFA quitting.
1134 /// * When the provided `Input` configuration is not supported. For
1135 /// example, by providing an unsupported anchor mode.
1136 ///
1137 /// When a search returns an error, callers cannot know whether a match
1138 /// exists or not.
1139 ///
1140 /// # Notes for implementors
1141 ///
1142 /// Implementors of this trait are not required to implement any particular
1143 /// match semantics (such as leftmost-first), which are instead manifest in
1144 /// the DFA's transitions. But this search routine should behave as a
1145 /// general "leftmost" search.
1146 ///
1147 /// In particular, this method must continue searching even after it enters
1148 /// a match state. The search should only terminate once it has reached
1149 /// the end of the input or when it has entered a dead or quit state. Upon
1150 /// termination, the position of the last byte seen while still in a match
1151 /// state is returned.
1152 ///
1153 /// Since this trait provides an implementation for this method by default,
1154 /// it's unlikely that one will need to implement this.
1155 ///
1156 /// # Example
1157 ///
1158 /// This example shows how to use this method with a
1159 /// [`dense::DFA`](crate::dfa::dense::DFA).
1160 ///
1161 /// ```
1162 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1163 ///
1164 /// let dfa = dense::DFA::new("foo[0-9]+")?;
1165 /// let expected = Some(HalfMatch::must(0, 8));
1166 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new(b"foo12345"))?);
1167 ///
1168 /// // Even though a match is found after reading the first byte (`a`),
1169 /// // the leftmost first match semantics demand that we find the earliest
1170 /// // match that prefers earlier parts of the pattern over latter parts.
1171 /// let dfa = dense::DFA::new("abc|a")?;
1172 /// let expected = Some(HalfMatch::must(0, 3));
1173 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new(b"abc"))?);
1174 ///
1175 /// # Ok::<(), Box<dyn std::error::Error>>(())
1176 /// ```
1177 ///
1178 /// # Example: specific pattern search
1179 ///
1180 /// This example shows how to build a multi-DFA that permits searching for
1181 /// specific patterns.
1182 ///
1183 /// ```
1184 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1185 /// use regex_automata::{
1186 /// dfa::{Automaton, dense},
1187 /// Anchored, HalfMatch, PatternID, Input,
1188 /// };
1189 ///
1190 /// let dfa = dense::Builder::new()
1191 /// .configure(dense::Config::new().starts_for_each_pattern(true))
1192 /// .build_many(&["[a-z0-9]{6}", "[a-z][a-z0-9]{5}"])?;
1193 /// let haystack = "foo123".as_bytes();
1194 ///
1195 /// // Since we are using the default leftmost-first match and both
1196 /// // patterns match at the same starting position, only the first pattern
1197 /// // will be returned in this case when doing a search for any of the
1198 /// // patterns.
1199 /// let expected = Some(HalfMatch::must(0, 6));
1200 /// let got = dfa.try_search_fwd(&Input::new(haystack))?;
1201 /// assert_eq!(expected, got);
1202 ///
1203 /// // But if we want to check whether some other pattern matches, then we
1204 /// // can provide its pattern ID.
1205 /// let input = Input::new(haystack)
1206 /// .anchored(Anchored::Pattern(PatternID::must(1)));
1207 /// let expected = Some(HalfMatch::must(1, 6));
1208 /// let got = dfa.try_search_fwd(&input)?;
1209 /// assert_eq!(expected, got);
1210 ///
1211 /// # Ok::<(), Box<dyn std::error::Error>>(())
1212 /// ```
1213 ///
1214 /// # Example: specifying the bounds of a search
1215 ///
1216 /// This example shows how providing the bounds of a search can produce
1217 /// different results than simply sub-slicing the haystack.
1218 ///
1219 /// ```
1220 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1221 ///
1222 /// // N.B. We disable Unicode here so that we use a simple ASCII word
1223 /// // boundary. Alternatively, we could enable heuristic support for
1224 /// // Unicode word boundaries.
1225 /// let dfa = dense::DFA::new(r"(?-u)\b[0-9]{3}\b")?;
1226 /// let haystack = "foo123bar".as_bytes();
1227 ///
1228 /// // Since we sub-slice the haystack, the search doesn't know about the
1229 /// // larger context and assumes that `123` is surrounded by word
1230 /// // boundaries. And of course, the match position is reported relative
1231 /// // to the sub-slice as well, which means we get `3` instead of `6`.
1232 /// let input = Input::new(&haystack[3..6]);
1233 /// let expected = Some(HalfMatch::must(0, 3));
1234 /// let got = dfa.try_search_fwd(&input)?;
1235 /// assert_eq!(expected, got);
1236 ///
1237 /// // But if we provide the bounds of the search within the context of the
1238 /// // entire haystack, then the search can take the surrounding context
1239 /// // into account. (And if we did find a match, it would be reported
1240 /// // as a valid offset into `haystack` instead of its sub-slice.)
1241 /// let input = Input::new(haystack).range(3..6);
1242 /// let expected = None;
1243 /// let got = dfa.try_search_fwd(&input)?;
1244 /// assert_eq!(expected, got);
1245 ///
1246 /// # Ok::<(), Box<dyn std::error::Error>>(())
1247 /// ```
1248 #[inline]
1249 fn try_search_fwd(
1250 &self,
1251 input: &Input<'_>,
1252 ) -> Result<Option<HalfMatch>, MatchError> {
1253 let utf8empty = self.has_empty() && self.is_utf8();
1254 let hm = match search::find_fwd(&self, input)? {
1255 None => return Ok(None),
1256 Some(hm) if !utf8empty => return Ok(Some(hm)),
1257 Some(hm) => hm,
1258 };
1259 // We get to this point when we know our DFA can match the empty string
1260 // AND when UTF-8 mode is enabled. In this case, we skip any matches
1261 // whose offset splits a codepoint. Such a match is necessarily a
1262 // zero-width match, because UTF-8 mode requires the underlying NFA
1263 // to be built such that all non-empty matches span valid UTF-8.
1264 // Therefore, any match that ends in the middle of a codepoint cannot
1265 // be part of a span of valid UTF-8 and thus must be an empty match.
1266 // In such cases, we skip it, so as not to report matches that split a
1267 // codepoint.
1268 //
1269 // Note that this is not a checked assumption. Callers *can* provide an
1270 // NFA with UTF-8 mode enabled but produces non-empty matches that span
1271 // invalid UTF-8. But doing so is documented to result in unspecified
1272 // behavior.
1273 empty::skip_splits_fwd(input, hm, hm.offset(), |input| {
1274 let got = search::find_fwd(&self, input)?;
1275 Ok(got.map(|hm| (hm, hm.offset())))
1276 })
1277 }
1278
1279 /// Executes a reverse search and returns the start of the position of the
1280 /// leftmost match that is found. If no match exists, then `None` is
1281 /// returned.
1282 ///
1283 /// # Errors
1284 ///
1285 /// This routine errors if the search could not complete. This can occur
1286 /// in a number of circumstances:
1287 ///
1288 /// * The configuration of the DFA may permit it to "quit" the search.
1289 /// For example, setting quit bytes or enabling heuristic support for
1290 /// Unicode word boundaries. The default configuration does not enable any
1291 /// option that could result in the DFA quitting.
1292 /// * When the provided `Input` configuration is not supported. For
1293 /// example, by providing an unsupported anchor mode.
1294 ///
1295 /// When a search returns an error, callers cannot know whether a match
1296 /// exists or not.
1297 ///
1298 /// # Example
1299 ///
1300 /// This example shows how to use this method with a
1301 /// [`dense::DFA`](crate::dfa::dense::DFA). In particular, this
1302 /// routine is principally useful when used in conjunction with the
1303 /// [`nfa::thompson::Config::reverse`](crate::nfa::thompson::Config::reverse)
1304 /// configuration. In general, it's unlikely to be correct to use
1305 /// both `try_search_fwd` and `try_search_rev` with the same DFA since
1306 /// any particular DFA will only support searching in one direction with
1307 /// respect to the pattern.
1308 ///
1309 /// ```
1310 /// use regex_automata::{
1311 /// nfa::thompson,
1312 /// dfa::{Automaton, dense},
1313 /// HalfMatch, Input,
1314 /// };
1315 ///
1316 /// let dfa = dense::Builder::new()
1317 /// .thompson(thompson::Config::new().reverse(true))
1318 /// .build("foo[0-9]+")?;
1319 /// let expected = Some(HalfMatch::must(0, 0));
1320 /// assert_eq!(expected, dfa.try_search_rev(&Input::new(b"foo12345"))?);
1321 ///
1322 /// // Even though a match is found after reading the last byte (`c`),
1323 /// // the leftmost first match semantics demand that we find the earliest
1324 /// // match that prefers earlier parts of the pattern over latter parts.
1325 /// let dfa = dense::Builder::new()
1326 /// .thompson(thompson::Config::new().reverse(true))
1327 /// .build("abc|c")?;
1328 /// let expected = Some(HalfMatch::must(0, 0));
1329 /// assert_eq!(expected, dfa.try_search_rev(&Input::new(b"abc"))?);
1330 ///
1331 /// # Ok::<(), Box<dyn std::error::Error>>(())
1332 /// ```
1333 ///
1334 /// # Example: UTF-8 mode
1335 ///
1336 /// This examples demonstrates that UTF-8 mode applies to reverse
1337 /// DFAs. When UTF-8 mode is enabled in the underlying NFA, then all
1338 /// matches reported must correspond to valid UTF-8 spans. This includes
1339 /// prohibiting zero-width matches that split a codepoint.
1340 ///
1341 /// UTF-8 mode is enabled by default. Notice below how the only zero-width
1342 /// matches reported are those at UTF-8 boundaries:
1343 ///
1344 /// ```
1345 /// use regex_automata::{
1346 /// dfa::{dense::DFA, Automaton},
1347 /// nfa::thompson,
1348 /// HalfMatch, Input, MatchKind,
1349 /// };
1350 ///
1351 /// let dfa = DFA::builder()
1352 /// .thompson(thompson::Config::new().reverse(true))
1353 /// .build(r"")?;
1354 ///
1355 /// // Run the reverse DFA to collect all matches.
1356 /// let mut input = Input::new("☃");
1357 /// let mut matches = vec![];
1358 /// loop {
1359 /// match dfa.try_search_rev(&input)? {
1360 /// None => break,
1361 /// Some(hm) => {
1362 /// matches.push(hm);
1363 /// if hm.offset() == 0 || input.end() == 0 {
1364 /// break;
1365 /// } else if hm.offset() < input.end() {
1366 /// input.set_end(hm.offset());
1367 /// } else {
1368 /// // This is only necessary to handle zero-width
1369 /// // matches, which of course occur in this example.
1370 /// // Without this, the search would never advance
1371 /// // backwards beyond the initial match.
1372 /// input.set_end(input.end() - 1);
1373 /// }
1374 /// }
1375 /// }
1376 /// }
1377 ///
1378 /// // No matches split a codepoint.
1379 /// let expected = vec![
1380 /// HalfMatch::must(0, 3),
1381 /// HalfMatch::must(0, 0),
1382 /// ];
1383 /// assert_eq!(expected, matches);
1384 ///
1385 /// # Ok::<(), Box<dyn std::error::Error>>(())
1386 /// ```
1387 ///
1388 /// Now let's look at the same example, but with UTF-8 mode on the
1389 /// original NFA disabled (which results in disabling UTF-8 mode on the
1390 /// DFA):
1391 ///
1392 /// ```
1393 /// use regex_automata::{
1394 /// dfa::{dense::DFA, Automaton},
1395 /// nfa::thompson,
1396 /// HalfMatch, Input, MatchKind,
1397 /// };
1398 ///
1399 /// let dfa = DFA::builder()
1400 /// .thompson(thompson::Config::new().reverse(true).utf8(false))
1401 /// .build(r"")?;
1402 ///
1403 /// // Run the reverse DFA to collect all matches.
1404 /// let mut input = Input::new("☃");
1405 /// let mut matches = vec![];
1406 /// loop {
1407 /// match dfa.try_search_rev(&input)? {
1408 /// None => break,
1409 /// Some(hm) => {
1410 /// matches.push(hm);
1411 /// if hm.offset() == 0 || input.end() == 0 {
1412 /// break;
1413 /// } else if hm.offset() < input.end() {
1414 /// input.set_end(hm.offset());
1415 /// } else {
1416 /// // This is only necessary to handle zero-width
1417 /// // matches, which of course occur in this example.
1418 /// // Without this, the search would never advance
1419 /// // backwards beyond the initial match.
1420 /// input.set_end(input.end() - 1);
1421 /// }
1422 /// }
1423 /// }
1424 /// }
1425 ///
1426 /// // No matches split a codepoint.
1427 /// let expected = vec![
1428 /// HalfMatch::must(0, 3),
1429 /// HalfMatch::must(0, 2),
1430 /// HalfMatch::must(0, 1),
1431 /// HalfMatch::must(0, 0),
1432 /// ];
1433 /// assert_eq!(expected, matches);
1434 ///
1435 /// # Ok::<(), Box<dyn std::error::Error>>(())
1436 /// ```
1437 #[inline]
1438 fn try_search_rev(
1439 &self,
1440 input: &Input<'_>,
1441 ) -> Result<Option<HalfMatch>, MatchError> {
1442 let utf8empty = self.has_empty() && self.is_utf8();
1443 let hm = match search::find_rev(self, input)? {
1444 None => return Ok(None),
1445 Some(hm) if !utf8empty => return Ok(Some(hm)),
1446 Some(hm) => hm,
1447 };
1448 empty::skip_splits_rev(input, hm, hm.offset(), |input| {
1449 let got = search::find_rev(self, input)?;
1450 Ok(got.map(|hm| (hm, hm.offset())))
1451 })
1452 }
1453
1454 /// Executes an overlapping forward search. Matches, if one exists, can be
1455 /// obtained via the [`OverlappingState::get_match`] method.
1456 ///
1457 /// This routine is principally only useful when searching for multiple
1458 /// patterns on inputs where multiple patterns may match the same regions
1459 /// of text. In particular, callers must preserve the automaton's search
1460 /// state from prior calls so that the implementation knows where the last
1461 /// match occurred.
1462 ///
1463 /// When using this routine to implement an iterator of overlapping
1464 /// matches, the `start` of the search should always be set to the end
1465 /// of the last match. If more patterns match at the previous location,
1466 /// then they will be immediately returned. (This is tracked by the given
1467 /// overlapping state.) Otherwise, the search continues at the starting
1468 /// position given.
1469 ///
1470 /// If for some reason you want the search to forget about its previous
1471 /// state and restart the search at a particular position, then setting the
1472 /// state to [`OverlappingState::start`] will accomplish that.
1473 ///
1474 /// # Errors
1475 ///
1476 /// This routine errors if the search could not complete. This can occur
1477 /// in a number of circumstances:
1478 ///
1479 /// * The configuration of the DFA may permit it to "quit" the search.
1480 /// For example, setting quit bytes or enabling heuristic support for
1481 /// Unicode word boundaries. The default configuration does not enable any
1482 /// option that could result in the DFA quitting.
1483 /// * When the provided `Input` configuration is not supported. For
1484 /// example, by providing an unsupported anchor mode.
1485 ///
1486 /// When a search returns an error, callers cannot know whether a match
1487 /// exists or not.
1488 ///
1489 /// # Example
1490 ///
1491 /// This example shows how to run a basic overlapping search with a
1492 /// [`dense::DFA`](crate::dfa::dense::DFA). Notice that we build the
1493 /// automaton with a `MatchKind::All` configuration. Overlapping searches
1494 /// are unlikely to work as one would expect when using the default
1495 /// `MatchKind::LeftmostFirst` match semantics, since leftmost-first
1496 /// matching is fundamentally incompatible with overlapping searches.
1497 /// Namely, overlapping searches need to report matches as they are seen,
1498 /// where as leftmost-first searches will continue searching even after a
1499 /// match has been observed in order to find the conventional end position
1500 /// of the match. More concretely, leftmost-first searches use dead states
1501 /// to terminate a search after a specific match can no longer be extended.
1502 /// Overlapping searches instead do the opposite by continuing the search
1503 /// to find totally new matches (potentially of other patterns).
1504 ///
1505 /// ```
1506 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1507 /// use regex_automata::{
1508 /// dfa::{Automaton, OverlappingState, dense},
1509 /// HalfMatch, Input, MatchKind,
1510 /// };
1511 ///
1512 /// let dfa = dense::Builder::new()
1513 /// .configure(dense::Config::new().match_kind(MatchKind::All))
1514 /// .build_many(&[r"[[:word:]]+$", r"[[:^space:]]+$"])?;
1515 /// let haystack = "@foo";
1516 /// let mut state = OverlappingState::start();
1517 ///
1518 /// let expected = Some(HalfMatch::must(1, 4));
1519 /// dfa.try_search_overlapping_fwd(&Input::new(haystack), &mut state)?;
1520 /// assert_eq!(expected, state.get_match());
1521 ///
1522 /// // The first pattern also matches at the same position, so re-running
1523 /// // the search will yield another match. Notice also that the first
1524 /// // pattern is returned after the second. This is because the second
1525 /// // pattern begins its match before the first, is therefore an earlier
1526 /// // match and is thus reported first.
1527 /// let expected = Some(HalfMatch::must(0, 4));
1528 /// dfa.try_search_overlapping_fwd(&Input::new(haystack), &mut state)?;
1529 /// assert_eq!(expected, state.get_match());
1530 ///
1531 /// # Ok::<(), Box<dyn std::error::Error>>(())
1532 /// ```
1533 #[inline]
1534 fn try_search_overlapping_fwd(
1535 &self,
1536 input: &Input<'_>,
1537 state: &mut OverlappingState,
1538 ) -> Result<(), MatchError> {
1539 let utf8empty = self.has_empty() && self.is_utf8();
1540 search::find_overlapping_fwd(self, input, state)?;
1541 match state.get_match() {
1542 None => Ok(()),
1543 Some(_) if !utf8empty => Ok(()),
1544 Some(_) => skip_empty_utf8_splits_overlapping(
1545 input,
1546 state,
1547 |input, state| {
1548 search::find_overlapping_fwd(self, input, state)
1549 },
1550 ),
1551 }
1552 }
1553
1554 /// Executes a reverse overlapping forward search. Matches, if one exists,
1555 /// can be obtained via the [`OverlappingState::get_match`] method.
1556 ///
1557 /// When using this routine to implement an iterator of overlapping
1558 /// matches, the `start` of the search should remain invariant throughout
1559 /// iteration. The `OverlappingState` given to the search will keep track
1560 /// of the current position of the search. (This is because multiple
1561 /// matches may be reported at the same position, so only the search
1562 /// implementation itself knows when to advance the position.)
1563 ///
1564 /// If for some reason you want the search to forget about its previous
1565 /// state and restart the search at a particular position, then setting the
1566 /// state to [`OverlappingState::start`] will accomplish that.
1567 ///
1568 /// # Errors
1569 ///
1570 /// This routine errors if the search could not complete. This can occur
1571 /// in a number of circumstances:
1572 ///
1573 /// * The configuration of the DFA may permit it to "quit" the search.
1574 /// For example, setting quit bytes or enabling heuristic support for
1575 /// Unicode word boundaries. The default configuration does not enable any
1576 /// option that could result in the DFA quitting.
1577 /// * When the provided `Input` configuration is not supported. For
1578 /// example, by providing an unsupported anchor mode.
1579 ///
1580 /// When a search returns an error, callers cannot know whether a match
1581 /// exists or not.
1582 ///
1583 /// # Example: UTF-8 mode
1584 ///
1585 /// This examples demonstrates that UTF-8 mode applies to reverse
1586 /// DFAs. When UTF-8 mode is enabled in the underlying NFA, then all
1587 /// matches reported must correspond to valid UTF-8 spans. This includes
1588 /// prohibiting zero-width matches that split a codepoint.
1589 ///
1590 /// UTF-8 mode is enabled by default. Notice below how the only zero-width
1591 /// matches reported are those at UTF-8 boundaries:
1592 ///
1593 /// ```
1594 /// use regex_automata::{
1595 /// dfa::{dense::DFA, Automaton, OverlappingState},
1596 /// nfa::thompson,
1597 /// HalfMatch, Input, MatchKind,
1598 /// };
1599 ///
1600 /// let dfa = DFA::builder()
1601 /// .configure(DFA::config().match_kind(MatchKind::All))
1602 /// .thompson(thompson::Config::new().reverse(true))
1603 /// .build_many(&[r"", r"☃"])?;
1604 ///
1605 /// // Run the reverse DFA to collect all matches.
1606 /// let input = Input::new("☃");
1607 /// let mut state = OverlappingState::start();
1608 /// let mut matches = vec![];
1609 /// loop {
1610 /// dfa.try_search_overlapping_rev(&input, &mut state)?;
1611 /// match state.get_match() {
1612 /// None => break,
1613 /// Some(hm) => matches.push(hm),
1614 /// }
1615 /// }
1616 ///
1617 /// // No matches split a codepoint.
1618 /// let expected = vec![
1619 /// HalfMatch::must(0, 3),
1620 /// HalfMatch::must(1, 0),
1621 /// HalfMatch::must(0, 0),
1622 /// ];
1623 /// assert_eq!(expected, matches);
1624 ///
1625 /// # Ok::<(), Box<dyn std::error::Error>>(())
1626 /// ```
1627 ///
1628 /// Now let's look at the same example, but with UTF-8 mode on the
1629 /// original NFA disabled (which results in disabling UTF-8 mode on the
1630 /// DFA):
1631 ///
1632 /// ```
1633 /// use regex_automata::{
1634 /// dfa::{dense::DFA, Automaton, OverlappingState},
1635 /// nfa::thompson,
1636 /// HalfMatch, Input, MatchKind,
1637 /// };
1638 ///
1639 /// let dfa = DFA::builder()
1640 /// .configure(DFA::config().match_kind(MatchKind::All))
1641 /// .thompson(thompson::Config::new().reverse(true).utf8(false))
1642 /// .build_many(&[r"", r"☃"])?;
1643 ///
1644 /// // Run the reverse DFA to collect all matches.
1645 /// let input = Input::new("☃");
1646 /// let mut state = OverlappingState::start();
1647 /// let mut matches = vec![];
1648 /// loop {
1649 /// dfa.try_search_overlapping_rev(&input, &mut state)?;
1650 /// match state.get_match() {
1651 /// None => break,
1652 /// Some(hm) => matches.push(hm),
1653 /// }
1654 /// }
1655 ///
1656 /// // Now *all* positions match, even within a codepoint,
1657 /// // because we lifted the requirement that matches
1658 /// // correspond to valid UTF-8 spans.
1659 /// let expected = vec![
1660 /// HalfMatch::must(0, 3),
1661 /// HalfMatch::must(0, 2),
1662 /// HalfMatch::must(0, 1),
1663 /// HalfMatch::must(1, 0),
1664 /// HalfMatch::must(0, 0),
1665 /// ];
1666 /// assert_eq!(expected, matches);
1667 ///
1668 /// # Ok::<(), Box<dyn std::error::Error>>(())
1669 /// ```
1670 #[inline]
1671 fn try_search_overlapping_rev(
1672 &self,
1673 input: &Input<'_>,
1674 state: &mut OverlappingState,
1675 ) -> Result<(), MatchError> {
1676 let utf8empty = self.has_empty() && self.is_utf8();
1677 search::find_overlapping_rev(self, input, state)?;
1678 match state.get_match() {
1679 None => Ok(()),
1680 Some(_) if !utf8empty => Ok(()),
1681 Some(_) => skip_empty_utf8_splits_overlapping(
1682 input,
1683 state,
1684 |input, state| {
1685 search::find_overlapping_rev(self, input, state)
1686 },
1687 ),
1688 }
1689 }
1690
1691 /// Writes the set of patterns that match anywhere in the given search
1692 /// configuration to `patset`. If multiple patterns match at the same
1693 /// position and the underlying DFA supports overlapping matches, then all
1694 /// matching patterns are written to the given set.
1695 ///
1696 /// Unless all of the patterns in this DFA are anchored, then generally
1697 /// speaking, this will visit every byte in the haystack.
1698 ///
1699 /// This search routine *does not* clear the pattern set. This gives some
1700 /// flexibility to the caller (e.g., running multiple searches with the
1701 /// same pattern set), but does make the API bug-prone if you're reusing
1702 /// the same pattern set for multiple searches but intended them to be
1703 /// independent.
1704 ///
1705 /// If a pattern ID matched but the given `PatternSet` does not have
1706 /// sufficient capacity to store it, then it is not inserted and silently
1707 /// dropped.
1708 ///
1709 /// # Errors
1710 ///
1711 /// This routine errors if the search could not complete. This can occur
1712 /// in a number of circumstances:
1713 ///
1714 /// * The configuration of the DFA may permit it to "quit" the search.
1715 /// For example, setting quit bytes or enabling heuristic support for
1716 /// Unicode word boundaries. The default configuration does not enable any
1717 /// option that could result in the DFA quitting.
1718 /// * When the provided `Input` configuration is not supported. For
1719 /// example, by providing an unsupported anchor mode.
1720 ///
1721 /// When a search returns an error, callers cannot know whether a match
1722 /// exists or not.
1723 ///
1724 /// # Example
1725 ///
1726 /// This example shows how to find all matching patterns in a haystack,
1727 /// even when some patterns match at the same position as other patterns.
1728 ///
1729 /// ```
1730 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1731 /// use regex_automata::{
1732 /// dfa::{Automaton, dense::DFA},
1733 /// Input, MatchKind, PatternSet,
1734 /// };
1735 ///
1736 /// let patterns = &[
1737 /// r"[[:word:]]+",
1738 /// r"[0-9]+",
1739 /// r"[[:alpha:]]+",
1740 /// r"foo",
1741 /// r"bar",
1742 /// r"barfoo",
1743 /// r"foobar",
1744 /// ];
1745 /// let dfa = DFA::builder()
1746 /// .configure(DFA::config().match_kind(MatchKind::All))
1747 /// .build_many(patterns)?;
1748 ///
1749 /// let input = Input::new("foobar");
1750 /// let mut patset = PatternSet::new(dfa.pattern_len());
1751 /// dfa.try_which_overlapping_matches(&input, &mut patset)?;
1752 /// let expected = vec![0, 2, 3, 4, 6];
1753 /// let got: Vec<usize> = patset.iter().map(|p| p.as_usize()).collect();
1754 /// assert_eq!(expected, got);
1755 ///
1756 /// # Ok::<(), Box<dyn std::error::Error>>(())
1757 /// ```
1758 #[cfg(feature = "alloc")]
1759 #[inline]
1760 fn try_which_overlapping_matches(
1761 &self,
1762 input: &Input<'_>,
1763 patset: &mut PatternSet,
1764 ) -> Result<(), MatchError> {
1765 let mut state = OverlappingState::start();
1766 while let Some(m) = {
1767 self.try_search_overlapping_fwd(input, &mut state)?;
1768 state.get_match()
1769 } {
1770 let _ = patset.insert(m.pattern());
1771 // There's nothing left to find, so we can stop. Or the caller
1772 // asked us to.
1773 if patset.is_full() || input.get_earliest() {
1774 break;
1775 }
1776 }
1777 Ok(())
1778 }
1779 }
1780
1781 unsafe impl<'a, A: Automaton + ?Sized> Automaton for &'a A {
1782 #[inline]
1783 fn next_state(&self, current: StateID, input: u8) -> StateID {
1784 (**self).next_state(current, input)
1785 }
1786
1787 #[inline]
1788 unsafe fn next_state_unchecked(
1789 &self,
1790 current: StateID,
1791 input: u8,
1792 ) -> StateID {
1793 (**self).next_state_unchecked(current, input)
1794 }
1795
1796 #[inline]
1797 fn next_eoi_state(&self, current: StateID) -> StateID {
1798 (**self).next_eoi_state(current)
1799 }
1800
1801 #[inline]
1802 fn start_state_forward(
1803 &self,
1804 input: &Input<'_>,
1805 ) -> Result<StateID, MatchError> {
1806 (**self).start_state_forward(input)
1807 }
1808
1809 #[inline]
1810 fn start_state_reverse(
1811 &self,
1812 input: &Input<'_>,
1813 ) -> Result<StateID, MatchError> {
1814 (**self).start_state_reverse(input)
1815 }
1816
1817 #[inline]
1818 fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
1819 (**self).universal_start_state(mode)
1820 }
1821
1822 #[inline]
1823 fn is_special_state(&self, id: StateID) -> bool {
1824 (**self).is_special_state(id)
1825 }
1826
1827 #[inline]
1828 fn is_dead_state(&self, id: StateID) -> bool {
1829 (**self).is_dead_state(id)
1830 }
1831
1832 #[inline]
1833 fn is_quit_state(&self, id: StateID) -> bool {
1834 (**self).is_quit_state(id)
1835 }
1836
1837 #[inline]
1838 fn is_match_state(&self, id: StateID) -> bool {
1839 (**self).is_match_state(id)
1840 }
1841
1842 #[inline]
1843 fn is_start_state(&self, id: StateID) -> bool {
1844 (**self).is_start_state(id)
1845 }
1846
1847 #[inline]
1848 fn is_accel_state(&self, id: StateID) -> bool {
1849 (**self).is_accel_state(id)
1850 }
1851
1852 #[inline]
1853 fn pattern_len(&self) -> usize {
1854 (**self).pattern_len()
1855 }
1856
1857 #[inline]
1858 fn match_len(&self, id: StateID) -> usize {
1859 (**self).match_len(id)
1860 }
1861
1862 #[inline]
1863 fn match_pattern(&self, id: StateID, index: usize) -> PatternID {
1864 (**self).match_pattern(id, index)
1865 }
1866
1867 #[inline]
1868 fn has_empty(&self) -> bool {
1869 (**self).has_empty()
1870 }
1871
1872 #[inline]
1873 fn is_utf8(&self) -> bool {
1874 (**self).is_utf8()
1875 }
1876
1877 #[inline]
1878 fn is_always_start_anchored(&self) -> bool {
1879 (**self).is_always_start_anchored()
1880 }
1881
1882 #[inline]
1883 fn accelerator(&self, id: StateID) -> &[u8] {
1884 (**self).accelerator(id)
1885 }
1886
1887 #[inline]
1888 fn get_prefilter(&self) -> Option<&Prefilter> {
1889 (**self).get_prefilter()
1890 }
1891
1892 #[inline]
1893 fn try_search_fwd(
1894 &self,
1895 input: &Input<'_>,
1896 ) -> Result<Option<HalfMatch>, MatchError> {
1897 (**self).try_search_fwd(input)
1898 }
1899
1900 #[inline]
1901 fn try_search_rev(
1902 &self,
1903 input: &Input<'_>,
1904 ) -> Result<Option<HalfMatch>, MatchError> {
1905 (**self).try_search_rev(input)
1906 }
1907
1908 #[inline]
1909 fn try_search_overlapping_fwd(
1910 &self,
1911 input: &Input<'_>,
1912 state: &mut OverlappingState,
1913 ) -> Result<(), MatchError> {
1914 (**self).try_search_overlapping_fwd(input, state)
1915 }
1916
1917 #[inline]
1918 fn try_search_overlapping_rev(
1919 &self,
1920 input: &Input<'_>,
1921 state: &mut OverlappingState,
1922 ) -> Result<(), MatchError> {
1923 (**self).try_search_overlapping_rev(input, state)
1924 }
1925
1926 #[cfg(feature = "alloc")]
1927 #[inline]
1928 fn try_which_overlapping_matches(
1929 &self,
1930 input: &Input<'_>,
1931 patset: &mut PatternSet,
1932 ) -> Result<(), MatchError> {
1933 (**self).try_which_overlapping_matches(input, patset)
1934 }
1935 }
1936
1937 /// Represents the current state of an overlapping search.
1938 ///
1939 /// This is used for overlapping searches since they need to know something
1940 /// about the previous search. For example, when multiple patterns match at the
1941 /// same position, this state tracks the last reported pattern so that the next
1942 /// search knows whether to report another matching pattern or continue with
1943 /// the search at the next position. Additionally, it also tracks which state
1944 /// the last search call terminated in.
1945 ///
1946 /// This type provides little introspection capabilities. The only thing a
1947 /// caller can do is construct it and pass it around to permit search routines
1948 /// to use it to track state, and also ask whether a match has been found.
1949 ///
1950 /// Callers should always provide a fresh state constructed via
1951 /// [`OverlappingState::start`] when starting a new search. Reusing state from
1952 /// a previous search may result in incorrect results.
1953 #[derive(Clone, Debug, Eq, PartialEq)]
1954 pub struct OverlappingState {
1955 /// The match reported by the most recent overlapping search to use this
1956 /// state.
1957 ///
1958 /// If a search does not find any matches, then it is expected to clear
1959 /// this value.
1960 pub(crate) mat: Option<HalfMatch>,
1961 /// The state ID of the state at which the search was in when the call
1962 /// terminated. When this is a match state, `last_match` must be set to a
1963 /// non-None value.
1964 ///
1965 /// A `None` value indicates the start state of the corresponding
1966 /// automaton. We cannot use the actual ID, since any one automaton may
1967 /// have many start states, and which one is in use depends on several
1968 /// search-time factors.
1969 pub(crate) id: Option<StateID>,
1970 /// The position of the search.
1971 ///
1972 /// When `id` is None (i.e., we are starting a search), this is set to
1973 /// the beginning of the search as given by the caller regardless of its
1974 /// current value. Subsequent calls to an overlapping search pick up at
1975 /// this offset.
1976 pub(crate) at: usize,
1977 /// The index into the matching patterns of the next match to report if the
1978 /// current state is a match state. Note that this may be 1 greater than
1979 /// the total number of matches to report for the current match state. (In
1980 /// which case, no more matches should be reported at the current position
1981 /// and the search should advance to the next position.)
1982 pub(crate) next_match_index: Option<usize>,
1983 /// This is set to true when a reverse overlapping search has entered its
1984 /// EOI transitions.
1985 ///
1986 /// This isn't used in a forward search because it knows to stop once the
1987 /// position exceeds the end of the search range. In a reverse search,
1988 /// since we use unsigned offsets, we don't "know" once we've gone past
1989 /// `0`. So the only way to detect it is with this extra flag. The reverse
1990 /// overlapping search knows to terminate specifically after it has
1991 /// reported all matches after following the EOI transition.
1992 pub(crate) rev_eoi: bool,
1993 }
1994
1995 impl OverlappingState {
1996 /// Create a new overlapping state that begins at the start state of any
1997 /// automaton.
1998 pub fn start() -> OverlappingState {
1999 OverlappingState {
2000 mat: None,
2001 id: None,
2002 at: 0,
2003 next_match_index: None,
2004 rev_eoi: false,
2005 }
2006 }
2007
2008 /// Return the match result of the most recent search to execute with this
2009 /// state.
2010 ///
2011 /// A searches will clear this result automatically, such that if no
2012 /// match is found, this will correctly report `None`.
2013 pub fn get_match(&self) -> Option<HalfMatch> {
2014 self.mat
2015 }
2016 }
2017
2018 /// Runs the given overlapping `search` function (forwards or backwards) until
2019 /// a match is found whose offset does not split a codepoint.
2020 ///
2021 /// This is *not* always correct to call. It should only be called when the DFA
2022 /// has UTF-8 mode enabled *and* it can produce zero-width matches. Calling
2023 /// this when both of those things aren't true might result in legitimate
2024 /// matches getting skipped.
2025 #[cold]
2026 #[inline(never)]
2027 fn skip_empty_utf8_splits_overlapping<F>(
2028 input: &Input<'_>,
2029 state: &mut OverlappingState,
2030 mut search: F,
2031 ) -> Result<(), MatchError>
2032 where
2033 F: FnMut(&Input<'_>, &mut OverlappingState) -> Result<(), MatchError>,
2034 {
2035 // Note that this routine works for forwards and reverse searches
2036 // even though there's no code here to handle those cases. That's
2037 // because overlapping searches drive themselves to completion via
2038 // `OverlappingState`. So all we have to do is push it until no matches are
2039 // found.
2040
2041 let mut hm = match state.get_match() {
2042 None => return Ok(()),
2043 Some(hm) => hm,
2044 };
2045 if input.get_anchored().is_anchored() {
2046 if !input.is_char_boundary(hm.offset()) {
2047 state.mat = None;
2048 }
2049 return Ok(());
2050 }
2051 while !input.is_char_boundary(hm.offset()) {
2052 search(input, state)?;
2053 hm = match state.get_match() {
2054 None => return Ok(()),
2055 Some(hm) => hm,
2056 };
2057 }
2058 Ok(())
2059 }
2060
2061 /// Write a prefix "state" indicator for fmt::Debug impls.
2062 ///
2063 /// Specifically, this tries to succinctly distinguish the different types of
2064 /// states: dead states, quit states, accelerated states, start states and
2065 /// match states. It even accounts for the possible overlappings of different
2066 /// state types.
2067 pub(crate) fn fmt_state_indicator<A: Automaton>(
2068 f: &mut core::fmt::Formatter<'_>,
2069 dfa: A,
2070 id: StateID,
2071 ) -> core::fmt::Result {
2072 if dfa.is_dead_state(id) {
2073 write!(f, "D")?;
2074 if dfa.is_start_state(id) {
2075 write!(f, ">")?;
2076 } else {
2077 write!(f, " ")?;
2078 }
2079 } else if dfa.is_quit_state(id) {
2080 write!(f, "Q ")?;
2081 } else if dfa.is_start_state(id) {
2082 if dfa.is_accel_state(id) {
2083 write!(f, "A>")?;
2084 } else {
2085 write!(f, " >")?;
2086 }
2087 } else if dfa.is_match_state(id) {
2088 if dfa.is_accel_state(id) {
2089 write!(f, "A*")?;
2090 } else {
2091 write!(f, " *")?;
2092 }
2093 } else if dfa.is_accel_state(id) {
2094 write!(f, "A ")?;
2095 } else {
2096 write!(f, " ")?;
2097 }
2098 Ok(())
2099 }
2100
2101 #[cfg(all(test, feature = "syntax", feature = "dfa-build"))]
2102 mod tests {
2103 // A basic test ensuring that our Automaton trait is object safe. (This is
2104 // the main reason why we don't define the search routines as generic over
2105 // Into<Input>.)
2106 #[test]
2107 fn object_safe() {
2108 use crate::{
2109 dfa::{dense, Automaton},
2110 HalfMatch, Input,
2111 };
2112
2113 let dfa = dense::DFA::new("abc").unwrap();
2114 let dfa: &dyn Automaton = &dfa;
2115 assert_eq!(
2116 Ok(Some(HalfMatch::must(0, 6))),
2117 dfa.try_search_fwd(&Input::new(b"xyzabcxyz")),
2118 );
2119 }
2120 }