]> git.proxmox.com Git - rustc.git/blame - vendor/regex-automata/src/dfa/dense.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / vendor / regex-automata / src / dfa / dense.rs
CommitLineData
487cf647
FG
1/*!
2Types and routines specific to dense DFAs.
3
4This module is the home of [`dense::DFA`](DFA).
5
6This module also contains a [`dense::Builder`](Builder) and a
781aab86 7[`dense::Config`](Config) for building and configuring a dense DFA.
487cf647
FG
8*/
9
781aab86 10#[cfg(feature = "dfa-build")]
487cf647
FG
11use core::cmp;
12use core::{convert::TryFrom, fmt, iter, mem::size_of, slice};
13
781aab86 14#[cfg(feature = "dfa-build")]
487cf647
FG
15use alloc::{
16 collections::{BTreeMap, BTreeSet},
17 vec,
18 vec::Vec,
19};
20
781aab86 21#[cfg(feature = "dfa-build")]
487cf647
FG
22use crate::{
23 dfa::{
781aab86
FG
24 accel::Accel, determinize, minimize::Minimizer, remapper::Remapper,
25 sparse,
487cf647
FG
26 },
27 nfa::thompson,
781aab86 28 util::{look::LookMatcher, search::MatchKind},
487cf647
FG
29};
30use crate::{
31 dfa::{
32 accel::Accels,
33 automaton::{fmt_state_indicator, Automaton},
34 special::Special,
781aab86 35 start::StartKind,
487cf647
FG
36 DEAD,
37 },
38 util::{
781aab86
FG
39 alphabet::{self, ByteClasses, ByteSet},
40 int::{Pointer, Usize},
41 prefilter::Prefilter,
42 primitives::{PatternID, StateID},
43 search::{Anchored, Input, MatchError},
44 start::{Start, StartByteMap},
45 wire::{self, DeserializeError, Endian, SerializeError},
487cf647
FG
46 },
47};
48
49/// The label that is pre-pended to a serialized DFA.
50const LABEL: &str = "rust-regex-automata-dfa-dense";
51
52/// The format version of dense regexes. This version gets incremented when a
53/// change occurs. A change may not necessarily be a breaking change, but the
54/// version does permit good error messages in the case where a breaking change
55/// is made.
56const VERSION: u32 = 2;
57
58/// The configuration used for compiling a dense DFA.
59///
781aab86
FG
60/// As a convenience, [`DFA::config`] is an alias for [`Config::new`]. The
61/// advantage of the former is that it often lets you avoid importing the
62/// `Config` type directly.
63///
487cf647
FG
64/// A dense DFA configuration is a simple data object that is typically used
65/// with [`dense::Builder::configure`](self::Builder::configure).
66///
781aab86
FG
67/// The default configuration guarantees that a search will never return
68/// a "quit" error, although it is possible for a search to fail if
69/// [`Config::starts_for_each_pattern`] wasn't enabled (which it is not by
70/// default) and an [`Anchored::Pattern`] mode is requested via [`Input`].
71#[cfg(feature = "dfa-build")]
72#[derive(Clone, Debug, Default)]
487cf647
FG
73pub struct Config {
74 // As with other configuration types in this crate, we put all our knobs
75 // in options so that we can distinguish between "default" and "not set."
76 // This makes it possible to easily combine multiple configurations
77 // without default values overwriting explicitly specified values. See the
78 // 'overwrite' method.
79 //
80 // For docs on the fields below, see the corresponding method setters.
487cf647 81 accelerate: Option<bool>,
781aab86 82 pre: Option<Option<Prefilter>>,
487cf647
FG
83 minimize: Option<bool>,
84 match_kind: Option<MatchKind>,
781aab86 85 start_kind: Option<StartKind>,
487cf647
FG
86 starts_for_each_pattern: Option<bool>,
87 byte_classes: Option<bool>,
88 unicode_word_boundary: Option<bool>,
781aab86
FG
89 quitset: Option<ByteSet>,
90 specialize_start_states: Option<bool>,
487cf647
FG
91 dfa_size_limit: Option<Option<usize>>,
92 determinize_size_limit: Option<Option<usize>>,
93}
94
781aab86 95#[cfg(feature = "dfa-build")]
487cf647
FG
96impl Config {
97 /// Return a new default dense DFA compiler configuration.
98 pub fn new() -> Config {
99 Config::default()
100 }
101
487cf647
FG
102 /// Enable state acceleration.
103 ///
104 /// When enabled, DFA construction will analyze each state to determine
105 /// whether it is eligible for simple acceleration. Acceleration typically
106 /// occurs when most of a state's transitions loop back to itself, leaving
107 /// only a select few bytes that will exit the state. When this occurs,
108 /// other routines like `memchr` can be used to look for those bytes which
109 /// may be much faster than traversing the DFA.
110 ///
111 /// Callers may elect to disable this if consistent performance is more
112 /// desirable than variable performance. Namely, acceleration can sometimes
113 /// make searching slower than it otherwise would be if the transitions
114 /// that leave accelerated states are traversed frequently.
115 ///
116 /// See [`Automaton::accelerator`](crate::dfa::Automaton::accelerator) for
117 /// an example.
118 ///
119 /// This is enabled by default.
120 pub fn accelerate(mut self, yes: bool) -> Config {
121 self.accelerate = Some(yes);
122 self
123 }
124
781aab86
FG
125 /// Set a prefilter to be used whenever a start state is entered.
126 ///
127 /// A [`Prefilter`] in this context is meant to accelerate searches by
128 /// looking for literal prefixes that every match for the corresponding
129 /// pattern (or patterns) must start with. Once a prefilter produces a
130 /// match, the underlying search routine continues on to try and confirm
131 /// the match.
132 ///
133 /// Be warned that setting a prefilter does not guarantee that the search
134 /// will be faster. While it's usually a good bet, if the prefilter
135 /// produces a lot of false positive candidates (i.e., positions matched
136 /// by the prefilter but not by the regex), then the overall result can
137 /// be slower than if you had just executed the regex engine without any
138 /// prefilters.
139 ///
140 /// Note that unless [`Config::specialize_start_states`] has been
141 /// explicitly set, then setting this will also enable (when `pre` is
142 /// `Some`) or disable (when `pre` is `None`) start state specialization.
143 /// This occurs because without start state specialization, a prefilter
144 /// is likely to be less effective. And without a prefilter, start state
145 /// specialization is usually pointless.
146 ///
147 /// **WARNING:** Note that prefilters are not preserved as part of
148 /// serialization. Serializing a DFA will drop its prefilter.
149 ///
150 /// By default no prefilter is set.
151 ///
152 /// # Example
153 ///
154 /// ```
155 /// use regex_automata::{
156 /// dfa::{dense::DFA, Automaton},
157 /// util::prefilter::Prefilter,
158 /// Input, HalfMatch, MatchKind,
159 /// };
160 ///
161 /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "bar"]);
162 /// let re = DFA::builder()
163 /// .configure(DFA::config().prefilter(pre))
164 /// .build(r"(foo|bar)[a-z]+")?;
165 /// let input = Input::new("foo1 barfox bar");
166 /// assert_eq!(
167 /// Some(HalfMatch::must(0, 11)),
168 /// re.try_search_fwd(&input)?,
169 /// );
170 ///
171 /// # Ok::<(), Box<dyn std::error::Error>>(())
172 /// ```
173 ///
174 /// Be warned though that an incorrect prefilter can lead to incorrect
175 /// results!
176 ///
177 /// ```
178 /// use regex_automata::{
179 /// dfa::{dense::DFA, Automaton},
180 /// util::prefilter::Prefilter,
181 /// Input, HalfMatch, MatchKind,
182 /// };
183 ///
184 /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "car"]);
185 /// let re = DFA::builder()
186 /// .configure(DFA::config().prefilter(pre))
187 /// .build(r"(foo|bar)[a-z]+")?;
188 /// let input = Input::new("foo1 barfox bar");
189 /// assert_eq!(
190 /// // No match reported even though there clearly is one!
191 /// None,
192 /// re.try_search_fwd(&input)?,
193 /// );
194 ///
195 /// # Ok::<(), Box<dyn std::error::Error>>(())
196 /// ```
197 pub fn prefilter(mut self, pre: Option<Prefilter>) -> Config {
198 self.pre = Some(pre);
199 if self.specialize_start_states.is_none() {
200 self.specialize_start_states =
201 Some(self.get_prefilter().is_some());
202 }
203 self
204 }
205
487cf647
FG
206 /// Minimize the DFA.
207 ///
208 /// When enabled, the DFA built will be minimized such that it is as small
209 /// as possible.
210 ///
211 /// Whether one enables minimization or not depends on the types of costs
212 /// you're willing to pay and how much you care about its benefits. In
213 /// particular, minimization has worst case `O(n*k*logn)` time and `O(k*n)`
214 /// space, where `n` is the number of DFA states and `k` is the alphabet
215 /// size. In practice, minimization can be quite costly in terms of both
216 /// space and time, so it should only be done if you're willing to wait
217 /// longer to produce a DFA. In general, you might want a minimal DFA in
218 /// the following circumstances:
219 ///
220 /// 1. You would like to optimize for the size of the automaton. This can
221 /// manifest in one of two ways. Firstly, if you're converting the
222 /// DFA into Rust code (or a table embedded in the code), then a minimal
223 /// DFA will translate into a corresponding reduction in code size, and
224 /// thus, also the final compiled binary size. Secondly, if you are
225 /// building many DFAs and putting them on the heap, you'll be able to
226 /// fit more if they are smaller. Note though that building a minimal
227 /// DFA itself requires additional space; you only realize the space
228 /// savings once the minimal DFA is constructed (at which point, the
229 /// space used for minimization is freed).
230 /// 2. You've observed that a smaller DFA results in faster match
231 /// performance. Naively, this isn't guaranteed since there is no
232 /// inherent difference between matching with a bigger-than-minimal
233 /// DFA and a minimal DFA. However, a smaller DFA may make use of your
234 /// CPU's cache more efficiently.
235 /// 3. You are trying to establish an equivalence between regular
236 /// languages. The standard method for this is to build a minimal DFA
237 /// for each language and then compare them. If the DFAs are equivalent
238 /// (up to state renaming), then the languages are equivalent.
239 ///
240 /// Typically, minimization only makes sense as an offline process. That
241 /// is, one might minimize a DFA before serializing it to persistent
242 /// storage. In practical terms, minimization can take around an order of
243 /// magnitude more time than compiling the initial DFA via determinization.
244 ///
245 /// This option is disabled by default.
246 pub fn minimize(mut self, yes: bool) -> Config {
247 self.minimize = Some(yes);
248 self
249 }
250
251 /// Set the desired match semantics.
252 ///
253 /// The default is [`MatchKind::LeftmostFirst`], which corresponds to the
254 /// match semantics of Perl-like regex engines. That is, when multiple
255 /// patterns would match at the same leftmost position, the pattern that
256 /// appears first in the concrete syntax is chosen.
257 ///
258 /// Currently, the only other kind of match semantics supported is
259 /// [`MatchKind::All`]. This corresponds to classical DFA construction
260 /// where all possible matches are added to the DFA.
261 ///
262 /// Typically, `All` is used when one wants to execute an overlapping
263 /// search and `LeftmostFirst` otherwise. In particular, it rarely makes
264 /// sense to use `All` with the various "leftmost" find routines, since the
265 /// leftmost routines depend on the `LeftmostFirst` automata construction
266 /// strategy. Specifically, `LeftmostFirst` adds dead states to the DFA
267 /// as a way to terminate the search and report a match. `LeftmostFirst`
268 /// also supports non-greedy matches using this strategy where as `All`
269 /// does not.
270 ///
271 /// # Example: overlapping search
272 ///
273 /// This example shows the typical use of `MatchKind::All`, which is to
274 /// report overlapping matches.
275 ///
276 /// ```
781aab86 277 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
487cf647
FG
278 /// use regex_automata::{
279 /// dfa::{Automaton, OverlappingState, dense},
781aab86 280 /// HalfMatch, Input, MatchKind,
487cf647
FG
281 /// };
282 ///
283 /// let dfa = dense::Builder::new()
284 /// .configure(dense::Config::new().match_kind(MatchKind::All))
285 /// .build_many(&[r"\w+$", r"\S+$"])?;
781aab86 286 /// let input = Input::new("@foo");
487cf647
FG
287 /// let mut state = OverlappingState::start();
288 ///
289 /// let expected = Some(HalfMatch::must(1, 4));
781aab86
FG
290 /// dfa.try_search_overlapping_fwd(&input, &mut state)?;
291 /// assert_eq!(expected, state.get_match());
487cf647
FG
292 ///
293 /// // The first pattern also matches at the same position, so re-running
294 /// // the search will yield another match. Notice also that the first
295 /// // pattern is returned after the second. This is because the second
296 /// // pattern begins its match before the first, is therefore an earlier
297 /// // match and is thus reported first.
298 /// let expected = Some(HalfMatch::must(0, 4));
781aab86
FG
299 /// dfa.try_search_overlapping_fwd(&input, &mut state)?;
300 /// assert_eq!(expected, state.get_match());
487cf647
FG
301 ///
302 /// # Ok::<(), Box<dyn std::error::Error>>(())
303 /// ```
304 ///
305 /// # Example: reverse automaton to find start of match
306 ///
307 /// Another example for using `MatchKind::All` is for constructing a
308 /// reverse automaton to find the start of a match. `All` semantics are
309 /// used for this in order to find the longest possible match, which
310 /// corresponds to the leftmost starting position.
311 ///
312 /// Note that if you need the starting position then
313 /// [`dfa::regex::Regex`](crate::dfa::regex::Regex) will handle this for
314 /// you, so it's usually not necessary to do this yourself.
315 ///
316 /// ```
781aab86
FG
317 /// use regex_automata::{
318 /// dfa::{dense, Automaton, StartKind},
319 /// nfa::thompson::NFA,
320 /// Anchored, HalfMatch, Input, MatchKind,
321 /// };
487cf647
FG
322 ///
323 /// let haystack = "123foobar456".as_bytes();
781aab86 324 /// let pattern = r"[a-z]+r";
487cf647
FG
325 ///
326 /// let dfa_fwd = dense::DFA::new(pattern)?;
327 /// let dfa_rev = dense::Builder::new()
781aab86 328 /// .thompson(NFA::config().reverse(true))
487cf647 329 /// .configure(dense::Config::new()
781aab86
FG
330 /// // This isn't strictly necessary since both anchored and
331 /// // unanchored searches are supported by default. But since
332 /// // finding the start-of-match only requires anchored searches,
333 /// // we can get rid of the unanchored configuration and possibly
334 /// // slim down our DFA considerably.
335 /// .start_kind(StartKind::Anchored)
487cf647
FG
336 /// .match_kind(MatchKind::All)
337 /// )
338 /// .build(pattern)?;
339 /// let expected_fwd = HalfMatch::must(0, 9);
340 /// let expected_rev = HalfMatch::must(0, 3);
781aab86 341 /// let got_fwd = dfa_fwd.try_search_fwd(&Input::new(haystack))?.unwrap();
487cf647
FG
342 /// // Here we don't specify the pattern to search for since there's only
343 /// // one pattern and we're doing a leftmost search. But if this were an
344 /// // overlapping search, you'd need to specify the pattern that matched
345 /// // in the forward direction. (Otherwise, you might wind up finding the
346 /// // starting position of a match of some other pattern.) That in turn
347 /// // requires building the reverse automaton with starts_for_each_pattern
348 /// // enabled. Indeed, this is what Regex does internally.
781aab86
FG
349 /// let input = Input::new(haystack)
350 /// .range(..got_fwd.offset())
351 /// .anchored(Anchored::Yes);
352 /// let got_rev = dfa_rev.try_search_rev(&input)?.unwrap();
487cf647
FG
353 /// assert_eq!(expected_fwd, got_fwd);
354 /// assert_eq!(expected_rev, got_rev);
355 ///
356 /// # Ok::<(), Box<dyn std::error::Error>>(())
357 /// ```
358 pub fn match_kind(mut self, kind: MatchKind) -> Config {
359 self.match_kind = Some(kind);
360 self
361 }
362
781aab86
FG
363 /// The type of starting state configuration to use for a DFA.
364 ///
365 /// By default, the starting state configuration is [`StartKind::Both`].
366 ///
367 /// # Example
368 ///
369 /// ```
370 /// use regex_automata::{
371 /// dfa::{dense::DFA, Automaton, StartKind},
372 /// Anchored, HalfMatch, Input,
373 /// };
374 ///
375 /// let haystack = "quux foo123";
376 /// let expected = HalfMatch::must(0, 11);
377 ///
378 /// // By default, DFAs support both anchored and unanchored searches.
379 /// let dfa = DFA::new(r"[0-9]+")?;
380 /// let input = Input::new(haystack);
381 /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
382 ///
383 /// // But if we only need anchored searches, then we can build a DFA
384 /// // that only supports anchored searches. This leads to a smaller DFA
385 /// // (potentially significantly smaller in some cases), but a DFA that
386 /// // will panic if you try to use it with an unanchored search.
387 /// let dfa = DFA::builder()
388 /// .configure(DFA::config().start_kind(StartKind::Anchored))
389 /// .build(r"[0-9]+")?;
390 /// let input = Input::new(haystack)
391 /// .range(8..)
392 /// .anchored(Anchored::Yes);
393 /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
394 ///
395 /// # Ok::<(), Box<dyn std::error::Error>>(())
396 /// ```
397 pub fn start_kind(mut self, kind: StartKind) -> Config {
398 self.start_kind = Some(kind);
399 self
400 }
401
487cf647
FG
402 /// Whether to compile a separate start state for each pattern in the
403 /// automaton.
404 ///
405 /// When enabled, a separate **anchored** start state is added for each
406 /// pattern in the DFA. When this start state is used, then the DFA will
407 /// only search for matches for the pattern specified, even if there are
408 /// other patterns in the DFA.
409 ///
410 /// The main downside of this option is that it can potentially increase
411 /// the size of the DFA and/or increase the time it takes to build the DFA.
412 ///
413 /// There are a few reasons one might want to enable this (it's disabled
414 /// by default):
415 ///
416 /// 1. When looking for the start of an overlapping match (using a
417 /// reverse DFA), doing it correctly requires starting the reverse search
418 /// using the starting state of the pattern that matched in the forward
419 /// direction. Indeed, when building a [`Regex`](crate::dfa::regex::Regex),
420 /// it will automatically enable this option when building the reverse DFA
421 /// internally.
422 /// 2. When you want to use a DFA with multiple patterns to both search
423 /// for matches of any pattern or to search for anchored matches of one
424 /// particular pattern while using the same DFA. (Otherwise, you would need
425 /// to compile a new DFA for each pattern.)
426 /// 3. Since the start states added for each pattern are anchored, if you
427 /// compile an unanchored DFA with one pattern while also enabling this
428 /// option, then you can use the same DFA to perform anchored or unanchored
429 /// searches. The latter you get with the standard search APIs. The former
430 /// you get from the various `_at` search methods that allow you specify a
431 /// pattern ID to search for.
432 ///
433 /// By default this is disabled.
434 ///
435 /// # Example
436 ///
437 /// This example shows how to use this option to permit the same DFA to
438 /// run both anchored and unanchored searches for a single pattern.
439 ///
440 /// ```
441 /// use regex_automata::{
781aab86
FG
442 /// dfa::{dense, Automaton},
443 /// Anchored, HalfMatch, PatternID, Input,
487cf647
FG
444 /// };
445 ///
446 /// let dfa = dense::Builder::new()
447 /// .configure(dense::Config::new().starts_for_each_pattern(true))
448 /// .build(r"foo[0-9]+")?;
781aab86 449 /// let haystack = "quux foo123";
487cf647
FG
450 ///
451 /// // Here's a normal unanchored search. Notice that we use 'None' for the
452 /// // pattern ID. Since the DFA was built as an unanchored machine, it
453 /// // use its default unanchored starting state.
454 /// let expected = HalfMatch::must(0, 11);
781aab86
FG
455 /// let input = Input::new(haystack);
456 /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
487cf647
FG
457 /// // But now if we explicitly specify the pattern to search ('0' being
458 /// // the only pattern in the DFA), then it will use the starting state
459 /// // for that specific pattern which is always anchored. Since the
460 /// // pattern doesn't have a match at the beginning of the haystack, we
461 /// // find nothing.
781aab86
FG
462 /// let input = Input::new(haystack)
463 /// .anchored(Anchored::Pattern(PatternID::must(0)));
464 /// assert_eq!(None, dfa.try_search_fwd(&input)?);
487cf647
FG
465 /// // And finally, an anchored search is not the same as putting a '^' at
466 /// // beginning of the pattern. An anchored search can only match at the
467 /// // beginning of the *search*, which we can change:
781aab86
FG
468 /// let input = Input::new(haystack)
469 /// .anchored(Anchored::Pattern(PatternID::must(0)))
470 /// .range(5..);
471 /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
487cf647
FG
472 ///
473 /// # Ok::<(), Box<dyn std::error::Error>>(())
474 /// ```
475 pub fn starts_for_each_pattern(mut self, yes: bool) -> Config {
476 self.starts_for_each_pattern = Some(yes);
477 self
478 }
479
480 /// Whether to attempt to shrink the size of the DFA's alphabet or not.
481 ///
482 /// This option is enabled by default and should never be disabled unless
483 /// one is debugging a generated DFA.
484 ///
485 /// When enabled, the DFA will use a map from all possible bytes to their
486 /// corresponding equivalence class. Each equivalence class represents a
487 /// set of bytes that does not discriminate between a match and a non-match
488 /// in the DFA. For example, the pattern `[ab]+` has at least two
489 /// equivalence classes: a set containing `a` and `b` and a set containing
490 /// every byte except for `a` and `b`. `a` and `b` are in the same
781aab86
FG
491 /// equivalence class because they never discriminate between a match and a
492 /// non-match.
487cf647
FG
493 ///
494 /// The advantage of this map is that the size of the transition table
495 /// can be reduced drastically from `#states * 256 * sizeof(StateID)` to
496 /// `#states * k * sizeof(StateID)` where `k` is the number of equivalence
497 /// classes (rounded up to the nearest power of 2). As a result, total
498 /// space usage can decrease substantially. Moreover, since a smaller
499 /// alphabet is used, DFA compilation becomes faster as well.
500 ///
501 /// **WARNING:** This is only useful for debugging DFAs. Disabling this
502 /// does not yield any speed advantages. Namely, even when this is
503 /// disabled, a byte class map is still used while searching. The only
504 /// difference is that every byte will be forced into its own distinct
505 /// equivalence class. This is useful for debugging the actual generated
506 /// transitions because it lets one see the transitions defined on actual
507 /// bytes instead of the equivalence classes.
508 pub fn byte_classes(mut self, yes: bool) -> Config {
509 self.byte_classes = Some(yes);
510 self
511 }
512
513 /// Heuristically enable Unicode word boundaries.
514 ///
515 /// When set, this will attempt to implement Unicode word boundaries as if
516 /// they were ASCII word boundaries. This only works when the search input
517 /// is ASCII only. If a non-ASCII byte is observed while searching, then a
781aab86 518 /// [`MatchError::quit`](crate::MatchError::quit) error is returned.
487cf647
FG
519 ///
520 /// A possible alternative to enabling this option is to simply use an
521 /// ASCII word boundary, e.g., via `(?-u:\b)`. The main reason to use this
522 /// option is if you absolutely need Unicode support. This option lets one
523 /// use a fast search implementation (a DFA) for some potentially very
524 /// common cases, while providing the option to fall back to some other
525 /// regex engine to handle the general case when an error is returned.
526 ///
527 /// If the pattern provided has no Unicode word boundary in it, then this
528 /// option has no effect. (That is, quitting on a non-ASCII byte only
529 /// occurs when this option is enabled _and_ a Unicode word boundary is
530 /// present in the pattern.)
531 ///
532 /// This is almost equivalent to setting all non-ASCII bytes to be quit
533 /// bytes. The only difference is that this will cause non-ASCII bytes to
534 /// be quit bytes _only_ when a Unicode word boundary is present in the
535 /// pattern.
536 ///
537 /// When enabling this option, callers _must_ be prepared to handle
538 /// a [`MatchError`](crate::MatchError) error during search.
539 /// When using a [`Regex`](crate::dfa::regex::Regex), this corresponds
540 /// to using the `try_` suite of methods. Alternatively, if
541 /// callers can guarantee that their input is ASCII only, then a
781aab86 542 /// [`MatchError::quit`](crate::MatchError::quit) error will never be
487cf647
FG
543 /// returned while searching.
544 ///
545 /// This is disabled by default.
546 ///
547 /// # Example
548 ///
549 /// This example shows how to heuristically enable Unicode word boundaries
550 /// in a pattern. It also shows what happens when a search comes across a
551 /// non-ASCII byte.
552 ///
553 /// ```
554 /// use regex_automata::{
555 /// dfa::{Automaton, dense},
781aab86 556 /// HalfMatch, Input, MatchError,
487cf647
FG
557 /// };
558 ///
559 /// let dfa = dense::Builder::new()
560 /// .configure(dense::Config::new().unicode_word_boundary(true))
561 /// .build(r"\b[0-9]+\b")?;
562 ///
563 /// // The match occurs before the search ever observes the snowman
564 /// // character, so no error occurs.
781aab86 565 /// let haystack = "foo 123 ☃".as_bytes();
487cf647 566 /// let expected = Some(HalfMatch::must(0, 7));
781aab86 567 /// let got = dfa.try_search_fwd(&Input::new(haystack))?;
487cf647
FG
568 /// assert_eq!(expected, got);
569 ///
570 /// // Notice that this search fails, even though the snowman character
571 /// // occurs after the ending match offset. This is because search
572 /// // routines read one byte past the end of the search to account for
573 /// // look-around, and indeed, this is required here to determine whether
574 /// // the trailing \b matches.
781aab86
FG
575 /// let haystack = "foo 123 ☃".as_bytes();
576 /// let expected = MatchError::quit(0xE2, 8);
577 /// let got = dfa.try_search_fwd(&Input::new(haystack));
578 /// assert_eq!(Err(expected), got);
579 ///
580 /// // Another example is executing a search where the span of the haystack
581 /// // we specify is all ASCII, but there is non-ASCII just before it. This
582 /// // correctly also reports an error.
583 /// let input = Input::new("β123").range(2..);
584 /// let expected = MatchError::quit(0xB2, 1);
585 /// let got = dfa.try_search_fwd(&input);
586 /// assert_eq!(Err(expected), got);
587 ///
588 /// // And similarly for the trailing word boundary.
589 /// let input = Input::new("123β").range(..3);
590 /// let expected = MatchError::quit(0xCE, 3);
591 /// let got = dfa.try_search_fwd(&input);
487cf647
FG
592 /// assert_eq!(Err(expected), got);
593 ///
594 /// # Ok::<(), Box<dyn std::error::Error>>(())
595 /// ```
596 pub fn unicode_word_boundary(mut self, yes: bool) -> Config {
597 // We have a separate option for this instead of just setting the
598 // appropriate quit bytes here because we don't want to set quit bytes
599 // for every regex. We only want to set them when the regex contains a
600 // Unicode word boundary.
601 self.unicode_word_boundary = Some(yes);
602 self
603 }
604
605 /// Add a "quit" byte to the DFA.
606 ///
607 /// When a quit byte is seen during search time, then search will return
781aab86 608 /// a [`MatchError::quit`](crate::MatchError::quit) error indicating the
487cf647
FG
609 /// offset at which the search stopped.
610 ///
611 /// A quit byte will always overrule any other aspects of a regex. For
612 /// example, if the `x` byte is added as a quit byte and the regex `\w` is
613 /// used, then observing `x` will cause the search to quit immediately
614 /// despite the fact that `x` is in the `\w` class.
615 ///
616 /// This mechanism is primarily useful for heuristically enabling certain
617 /// features like Unicode word boundaries in a DFA. Namely, if the input
618 /// to search is ASCII, then a Unicode word boundary can be implemented
619 /// via an ASCII word boundary with no change in semantics. Thus, a DFA
620 /// can attempt to match a Unicode word boundary but give up as soon as it
621 /// observes a non-ASCII byte. Indeed, if callers set all non-ASCII bytes
622 /// to be quit bytes, then Unicode word boundaries will be permitted when
623 /// building DFAs. Of course, callers should enable
624 /// [`Config::unicode_word_boundary`] if they want this behavior instead.
625 /// (The advantage being that non-ASCII quit bytes will only be added if a
626 /// Unicode word boundary is in the pattern.)
627 ///
628 /// When enabling this option, callers _must_ be prepared to handle a
629 /// [`MatchError`](crate::MatchError) error during search. When using a
630 /// [`Regex`](crate::dfa::regex::Regex), this corresponds to using the
631 /// `try_` suite of methods.
632 ///
633 /// By default, there are no quit bytes set.
634 ///
635 /// # Panics
636 ///
637 /// This panics if heuristic Unicode word boundaries are enabled and any
638 /// non-ASCII byte is removed from the set of quit bytes. Namely, enabling
639 /// Unicode word boundaries requires setting every non-ASCII byte to a quit
640 /// byte. So if the caller attempts to undo any of that, then this will
641 /// panic.
642 ///
643 /// # Example
644 ///
645 /// This example shows how to cause a search to terminate if it sees a
646 /// `\n` byte. This could be useful if, for example, you wanted to prevent
647 /// a user supplied pattern from matching across a line boundary.
648 ///
649 /// ```
781aab86
FG
650 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
651 /// use regex_automata::{dfa::{Automaton, dense}, Input, MatchError};
487cf647
FG
652 ///
653 /// let dfa = dense::Builder::new()
654 /// .configure(dense::Config::new().quit(b'\n', true))
655 /// .build(r"foo\p{any}+bar")?;
656 ///
657 /// let haystack = "foo\nbar".as_bytes();
658 /// // Normally this would produce a match, since \p{any} contains '\n'.
659 /// // But since we instructed the automaton to enter a quit state if a
660 /// // '\n' is observed, this produces a match error instead.
781aab86
FG
661 /// let expected = MatchError::quit(b'\n', 3);
662 /// let got = dfa.try_search_fwd(&Input::new(haystack)).unwrap_err();
487cf647
FG
663 /// assert_eq!(expected, got);
664 ///
665 /// # Ok::<(), Box<dyn std::error::Error>>(())
666 /// ```
667 pub fn quit(mut self, byte: u8, yes: bool) -> Config {
668 if self.get_unicode_word_boundary() && !byte.is_ascii() && !yes {
669 panic!(
670 "cannot set non-ASCII byte to be non-quit when \
671 Unicode word boundaries are enabled"
672 );
673 }
781aab86
FG
674 if self.quitset.is_none() {
675 self.quitset = Some(ByteSet::empty());
487cf647
FG
676 }
677 if yes {
781aab86 678 self.quitset.as_mut().unwrap().add(byte);
487cf647 679 } else {
781aab86 680 self.quitset.as_mut().unwrap().remove(byte);
487cf647
FG
681 }
682 self
683 }
684
781aab86
FG
685 /// Enable specializing start states in the DFA.
686 ///
687 /// When start states are specialized, an implementor of a search routine
688 /// using a lazy DFA can tell when the search has entered a starting state.
689 /// When start states aren't specialized, then it is impossible to know
690 /// whether the search has entered a start state.
691 ///
692 /// Ideally, this option wouldn't need to exist and we could always
693 /// specialize start states. The problem is that start states can be quite
694 /// active. This in turn means that an efficient search routine is likely
695 /// to ping-pong between a heavily optimized hot loop that handles most
696 /// states and to a less optimized specialized handling of start states.
697 /// This causes branches to get heavily mispredicted and overall can
698 /// materially decrease throughput. Therefore, specializing start states
699 /// should only be enabled when it is needed.
700 ///
701 /// Knowing whether a search is in a start state is typically useful when a
702 /// prefilter is active for the search. A prefilter is typically only run
703 /// when in a start state and a prefilter can greatly accelerate a search.
704 /// Therefore, the possible cost of specializing start states is worth it
705 /// in this case. Otherwise, if you have no prefilter, there is likely no
706 /// reason to specialize start states.
707 ///
708 /// This is disabled by default, but note that it is automatically
709 /// enabled (or disabled) if [`Config::prefilter`] is set. Namely, unless
710 /// `specialize_start_states` has already been set, [`Config::prefilter`]
711 /// will automatically enable or disable it based on whether a prefilter
712 /// is present or not, respectively. This is done because a prefilter's
713 /// effectiveness is rooted in being executed whenever the DFA is in a
714 /// start state, and that's only possible to do when they are specialized.
715 ///
716 /// Note that it is plausibly reasonable to _disable_ this option
717 /// explicitly while _enabling_ a prefilter. In that case, a prefilter
718 /// will still be run at the beginning of a search, but never again. This
719 /// in theory could strike a good balance if you're in a situation where a
720 /// prefilter is likely to produce many false positive candidates.
721 ///
722 /// # Example
723 ///
724 /// This example shows how to enable start state specialization and then
725 /// shows how to check whether a state is a start state or not.
726 ///
727 /// ```
728 /// use regex_automata::{dfa::{Automaton, dense::DFA}, Input};
729 ///
730 /// let dfa = DFA::builder()
731 /// .configure(DFA::config().specialize_start_states(true))
732 /// .build(r"[a-z]+")?;
733 ///
734 /// let haystack = "123 foobar 4567".as_bytes();
735 /// let sid = dfa.start_state_forward(&Input::new(haystack))?;
736 /// // The ID returned by 'start_state_forward' will always be tagged as
737 /// // a start state when start state specialization is enabled.
738 /// assert!(dfa.is_special_state(sid));
739 /// assert!(dfa.is_start_state(sid));
740 ///
741 /// # Ok::<(), Box<dyn std::error::Error>>(())
742 /// ```
743 ///
744 /// Compare the above with the default DFA configuration where start states
745 /// are _not_ specialized. In this case, the start state is not tagged at
746 /// all:
747 ///
748 /// ```
749 /// use regex_automata::{dfa::{Automaton, dense::DFA}, Input};
750 ///
751 /// let dfa = DFA::new(r"[a-z]+")?;
752 ///
753 /// let haystack = "123 foobar 4567";
754 /// let sid = dfa.start_state_forward(&Input::new(haystack))?;
755 /// // Start states are not special in the default configuration!
756 /// assert!(!dfa.is_special_state(sid));
757 /// assert!(!dfa.is_start_state(sid));
758 ///
759 /// # Ok::<(), Box<dyn std::error::Error>>(())
760 /// ```
761 pub fn specialize_start_states(mut self, yes: bool) -> Config {
762 self.specialize_start_states = Some(yes);
763 self
764 }
765
487cf647
FG
766 /// Set a size limit on the total heap used by a DFA.
767 ///
768 /// This size limit is expressed in bytes and is applied during
769 /// determinization of an NFA into a DFA. If the DFA's heap usage, and only
770 /// the DFA, exceeds this configured limit, then determinization is stopped
771 /// and an error is returned.
772 ///
773 /// This limit does not apply to auxiliary storage used during
774 /// determinization that isn't part of the generated DFA.
775 ///
776 /// This limit is only applied during determinization. Currently, there is
777 /// no way to post-pone this check to after minimization if minimization
778 /// was enabled.
779 ///
780 /// The total limit on heap used during determinization is the sum of the
781 /// DFA and determinization size limits.
782 ///
783 /// The default is no limit.
784 ///
785 /// # Example
786 ///
787 /// This example shows a DFA that fails to build because of a configured
788 /// size limit. This particular example also serves as a cautionary tale
789 /// demonstrating just how big DFAs with large Unicode character classes
790 /// can get.
791 ///
792 /// ```
781aab86
FG
793 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
794 /// use regex_automata::{dfa::{dense, Automaton}, Input};
487cf647 795 ///
781aab86 796 /// // 6MB isn't enough!
487cf647 797 /// dense::Builder::new()
781aab86 798 /// .configure(dense::Config::new().dfa_size_limit(Some(6_000_000)))
487cf647
FG
799 /// .build(r"\w{20}")
800 /// .unwrap_err();
801 ///
781aab86 802 /// // ... but 7MB probably is!
487cf647
FG
803 /// // (Note that DFA sizes aren't necessarily stable between releases.)
804 /// let dfa = dense::Builder::new()
781aab86 805 /// .configure(dense::Config::new().dfa_size_limit(Some(7_000_000)))
487cf647
FG
806 /// .build(r"\w{20}")?;
807 /// let haystack = "A".repeat(20).into_bytes();
781aab86 808 /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
487cf647
FG
809 ///
810 /// # Ok::<(), Box<dyn std::error::Error>>(())
811 /// ```
812 ///
781aab86
FG
813 /// While one needs a little more than 6MB to represent `\w{20}`, it
814 /// turns out that you only need a little more than 6KB to represent
487cf647 815 /// `(?-u:\w{20})`. So only use Unicode if you need it!
781aab86
FG
816 ///
817 /// As with [`Config::determinize_size_limit`], the size of a DFA is
818 /// influenced by other factors, such as what start state configurations
819 /// to support. For example, if you only need unanchored searches and not
820 /// anchored searches, then configuring the DFA to only support unanchored
821 /// searches can reduce its size. By default, DFAs support both unanchored
822 /// and anchored searches.
823 ///
824 /// ```
825 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
826 /// use regex_automata::{dfa::{dense, Automaton, StartKind}, Input};
827 ///
828 /// // 3MB isn't enough!
829 /// dense::Builder::new()
830 /// .configure(dense::Config::new()
831 /// .dfa_size_limit(Some(3_000_000))
832 /// .start_kind(StartKind::Unanchored)
833 /// )
834 /// .build(r"\w{20}")
835 /// .unwrap_err();
836 ///
837 /// // ... but 4MB probably is!
838 /// // (Note that DFA sizes aren't necessarily stable between releases.)
839 /// let dfa = dense::Builder::new()
840 /// .configure(dense::Config::new()
841 /// .dfa_size_limit(Some(4_000_000))
842 /// .start_kind(StartKind::Unanchored)
843 /// )
844 /// .build(r"\w{20}")?;
845 /// let haystack = "A".repeat(20).into_bytes();
846 /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
847 ///
848 /// # Ok::<(), Box<dyn std::error::Error>>(())
849 /// ```
487cf647
FG
850 pub fn dfa_size_limit(mut self, bytes: Option<usize>) -> Config {
851 self.dfa_size_limit = Some(bytes);
852 self
853 }
854
855 /// Set a size limit on the total heap used by determinization.
856 ///
857 /// This size limit is expressed in bytes and is applied during
858 /// determinization of an NFA into a DFA. If the heap used for auxiliary
859 /// storage during determinization (memory that is not in the DFA but
860 /// necessary for building the DFA) exceeds this configured limit, then
861 /// determinization is stopped and an error is returned.
862 ///
863 /// This limit does not apply to heap used by the DFA itself.
864 ///
865 /// The total limit on heap used during determinization is the sum of the
866 /// DFA and determinization size limits.
867 ///
868 /// The default is no limit.
869 ///
870 /// # Example
871 ///
872 /// This example shows a DFA that fails to build because of a
873 /// configured size limit on the amount of heap space used by
874 /// determinization. This particular example complements the example for
875 /// [`Config::dfa_size_limit`] by demonstrating that not only does Unicode
876 /// potentially make DFAs themselves big, but it also results in more
877 /// auxiliary storage during determinization. (Although, auxiliary storage
878 /// is still not as much as the DFA itself.)
879 ///
880 /// ```
781aab86
FG
881 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
882 /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
883 /// use regex_automata::{dfa::{dense, Automaton}, Input};
487cf647 884 ///
781aab86 885 /// // 600KB isn't enough!
487cf647
FG
886 /// dense::Builder::new()
887 /// .configure(dense::Config::new()
781aab86
FG
888 /// .determinize_size_limit(Some(600_000))
889 /// )
890 /// .build(r"\w{20}")
891 /// .unwrap_err();
892 ///
893 /// // ... but 700KB probably is!
894 /// // (Note that auxiliary storage sizes aren't necessarily stable between
895 /// // releases.)
896 /// let dfa = dense::Builder::new()
897 /// .configure(dense::Config::new()
898 /// .determinize_size_limit(Some(700_000))
899 /// )
900 /// .build(r"\w{20}")?;
901 /// let haystack = "A".repeat(20).into_bytes();
902 /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
903 ///
904 /// # Ok::<(), Box<dyn std::error::Error>>(())
905 /// ```
906 ///
907 /// Note that some parts of the configuration on a DFA can have a
908 /// big impact on how big the DFA is, and thus, how much memory is
909 /// used. For example, the default setting for [`Config::start_kind`] is
910 /// [`StartKind::Both`]. But if you only need an anchored search, for
911 /// example, then it can be much cheaper to build a DFA that only supports
912 /// anchored searches. (Running an unanchored search with it would panic.)
913 ///
914 /// ```
915 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
916 /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
917 /// use regex_automata::{
918 /// dfa::{dense, Automaton, StartKind},
919 /// Anchored, Input,
920 /// };
921 ///
922 /// // 200KB isn't enough!
923 /// dense::Builder::new()
924 /// .configure(dense::Config::new()
925 /// .determinize_size_limit(Some(200_000))
926 /// .start_kind(StartKind::Anchored)
487cf647
FG
927 /// )
928 /// .build(r"\w{20}")
929 /// .unwrap_err();
930 ///
781aab86 931 /// // ... but 300KB probably is!
487cf647
FG
932 /// // (Note that auxiliary storage sizes aren't necessarily stable between
933 /// // releases.)
934 /// let dfa = dense::Builder::new()
935 /// .configure(dense::Config::new()
781aab86
FG
936 /// .determinize_size_limit(Some(300_000))
937 /// .start_kind(StartKind::Anchored)
487cf647
FG
938 /// )
939 /// .build(r"\w{20}")?;
940 /// let haystack = "A".repeat(20).into_bytes();
781aab86
FG
941 /// let input = Input::new(&haystack).anchored(Anchored::Yes);
942 /// assert!(dfa.try_search_fwd(&input)?.is_some());
487cf647
FG
943 ///
944 /// # Ok::<(), Box<dyn std::error::Error>>(())
945 /// ```
946 pub fn determinize_size_limit(mut self, bytes: Option<usize>) -> Config {
947 self.determinize_size_limit = Some(bytes);
948 self
949 }
950
487cf647
FG
951 /// Returns whether this configuration has enabled simple state
952 /// acceleration.
953 pub fn get_accelerate(&self) -> bool {
954 self.accelerate.unwrap_or(true)
955 }
956
781aab86
FG
957 /// Returns the prefilter attached to this configuration, if any.
958 pub fn get_prefilter(&self) -> Option<&Prefilter> {
959 self.pre.as_ref().unwrap_or(&None).as_ref()
960 }
961
487cf647
FG
962 /// Returns whether this configuration has enabled the expensive process
963 /// of minimizing a DFA.
964 pub fn get_minimize(&self) -> bool {
965 self.minimize.unwrap_or(false)
966 }
967
968 /// Returns the match semantics set in this configuration.
969 pub fn get_match_kind(&self) -> MatchKind {
970 self.match_kind.unwrap_or(MatchKind::LeftmostFirst)
971 }
972
781aab86
FG
973 /// Returns the starting state configuration for a DFA.
974 pub fn get_starts(&self) -> StartKind {
975 self.start_kind.unwrap_or(StartKind::Both)
976 }
977
487cf647
FG
978 /// Returns whether this configuration has enabled anchored starting states
979 /// for every pattern in the DFA.
980 pub fn get_starts_for_each_pattern(&self) -> bool {
981 self.starts_for_each_pattern.unwrap_or(false)
982 }
983
984 /// Returns whether this configuration has enabled byte classes or not.
985 /// This is typically a debugging oriented option, as disabling it confers
986 /// no speed benefit.
987 pub fn get_byte_classes(&self) -> bool {
988 self.byte_classes.unwrap_or(true)
989 }
990
991 /// Returns whether this configuration has enabled heuristic Unicode word
992 /// boundary support. When enabled, it is possible for a search to return
993 /// an error.
994 pub fn get_unicode_word_boundary(&self) -> bool {
995 self.unicode_word_boundary.unwrap_or(false)
996 }
997
998 /// Returns whether this configuration will instruct the DFA to enter a
999 /// quit state whenever the given byte is seen during a search. When at
1000 /// least one byte has this enabled, it is possible for a search to return
1001 /// an error.
1002 pub fn get_quit(&self, byte: u8) -> bool {
781aab86
FG
1003 self.quitset.map_or(false, |q| q.contains(byte))
1004 }
1005
1006 /// Returns whether this configuration will instruct the DFA to
1007 /// "specialize" start states. When enabled, the DFA will mark start states
1008 /// as "special" so that search routines using the DFA can detect when
1009 /// it's in a start state and do some kind of optimization (like run a
1010 /// prefilter).
1011 pub fn get_specialize_start_states(&self) -> bool {
1012 self.specialize_start_states.unwrap_or(false)
487cf647
FG
1013 }
1014
1015 /// Returns the DFA size limit of this configuration if one was set.
1016 /// The size limit is total number of bytes on the heap that a DFA is
1017 /// permitted to use. If the DFA exceeds this limit during construction,
1018 /// then construction is stopped and an error is returned.
1019 pub fn get_dfa_size_limit(&self) -> Option<usize> {
1020 self.dfa_size_limit.unwrap_or(None)
1021 }
1022
1023 /// Returns the determinization size limit of this configuration if one
1024 /// was set. The size limit is total number of bytes on the heap that
1025 /// determinization is permitted to use. If determinization exceeds this
1026 /// limit during construction, then construction is stopped and an error is
1027 /// returned.
1028 ///
1029 /// This is different from the DFA size limit in that this only applies to
1030 /// the auxiliary storage used during determinization. Once determinization
1031 /// is complete, this memory is freed.
1032 ///
1033 /// The limit on the total heap memory used is the sum of the DFA and
1034 /// determinization size limits.
1035 pub fn get_determinize_size_limit(&self) -> Option<usize> {
1036 self.determinize_size_limit.unwrap_or(None)
1037 }
1038
1039 /// Overwrite the default configuration such that the options in `o` are
1040 /// always used. If an option in `o` is not set, then the corresponding
1041 /// option in `self` is used. If it's not set in `self` either, then it
1042 /// remains not set.
781aab86 1043 pub(crate) fn overwrite(&self, o: Config) -> Config {
487cf647 1044 Config {
487cf647 1045 accelerate: o.accelerate.or(self.accelerate),
781aab86 1046 pre: o.pre.or_else(|| self.pre.clone()),
487cf647
FG
1047 minimize: o.minimize.or(self.minimize),
1048 match_kind: o.match_kind.or(self.match_kind),
781aab86 1049 start_kind: o.start_kind.or(self.start_kind),
487cf647
FG
1050 starts_for_each_pattern: o
1051 .starts_for_each_pattern
1052 .or(self.starts_for_each_pattern),
1053 byte_classes: o.byte_classes.or(self.byte_classes),
1054 unicode_word_boundary: o
1055 .unicode_word_boundary
1056 .or(self.unicode_word_boundary),
781aab86
FG
1057 quitset: o.quitset.or(self.quitset),
1058 specialize_start_states: o
1059 .specialize_start_states
1060 .or(self.specialize_start_states),
487cf647
FG
1061 dfa_size_limit: o.dfa_size_limit.or(self.dfa_size_limit),
1062 determinize_size_limit: o
1063 .determinize_size_limit
1064 .or(self.determinize_size_limit),
1065 }
1066 }
1067}
1068
1069/// A builder for constructing a deterministic finite automaton from regular
1070/// expressions.
1071///
1072/// This builder provides two main things:
1073///
1074/// 1. It provides a few different `build` routines for actually constructing
1075/// a DFA from different kinds of inputs. The most convenient is
1076/// [`Builder::build`], which builds a DFA directly from a pattern string. The
1077/// most flexible is [`Builder::build_from_nfa`], which builds a DFA straight
1078/// from an NFA.
1079/// 2. The builder permits configuring a number of things.
1080/// [`Builder::configure`] is used with [`Config`] to configure aspects of
1081/// the DFA and the construction process itself. [`Builder::syntax`] and
1082/// [`Builder::thompson`] permit configuring the regex parser and Thompson NFA
1083/// construction, respectively. The syntax and thompson configurations only
1084/// apply when building from a pattern string.
1085///
1086/// This builder always constructs a *single* DFA. As such, this builder
1087/// can only be used to construct regexes that either detect the presence
1088/// of a match or find the end location of a match. A single DFA cannot
1089/// produce both the start and end of a match. For that information, use a
1090/// [`Regex`](crate::dfa::regex::Regex), which can be similarly configured
1091/// using [`regex::Builder`](crate::dfa::regex::Builder). The main reason to
1092/// use a DFA directly is if the end location of a match is enough for your use
1093/// case. Namely, a `Regex` will construct two DFAs instead of one, since a
1094/// second reverse DFA is needed to find the start of a match.
1095///
1096/// Note that if one wants to build a sparse DFA, you must first build a dense
1097/// DFA and convert that to a sparse DFA. There is no way to build a sparse
1098/// DFA without first building a dense DFA.
1099///
1100/// # Example
1101///
1102/// This example shows how to build a minimized DFA that completely disables
1103/// Unicode. That is:
1104///
1105/// * Things such as `\w`, `.` and `\b` are no longer Unicode-aware. `\w`
1106/// and `\b` are ASCII-only while `.` matches any byte except for `\n`
1107/// (instead of any UTF-8 encoding of a Unicode scalar value except for
1108/// `\n`). Things that are Unicode only, such as `\pL`, are not allowed.
1109/// * The pattern itself is permitted to match invalid UTF-8. For example,
1110/// things like `[^a]` that match any byte except for `a` are permitted.
487cf647
FG
1111///
1112/// ```
1113/// use regex_automata::{
1114/// dfa::{Automaton, dense},
781aab86
FG
1115/// util::syntax,
1116/// HalfMatch, Input,
487cf647
FG
1117/// };
1118///
1119/// let dfa = dense::Builder::new()
1120/// .configure(dense::Config::new().minimize(false))
781aab86 1121/// .syntax(syntax::Config::new().unicode(false).utf8(false))
487cf647
FG
1122/// .build(r"foo[^b]ar.*")?;
1123///
1124/// let haystack = b"\xFEfoo\xFFar\xE2\x98\xFF\n";
1125/// let expected = Some(HalfMatch::must(0, 10));
781aab86 1126/// let got = dfa.try_search_fwd(&Input::new(haystack))?;
487cf647
FG
1127/// assert_eq!(expected, got);
1128///
1129/// # Ok::<(), Box<dyn std::error::Error>>(())
1130/// ```
781aab86 1131#[cfg(feature = "dfa-build")]
487cf647
FG
1132#[derive(Clone, Debug)]
1133pub struct Builder {
1134 config: Config,
781aab86
FG
1135 #[cfg(feature = "syntax")]
1136 thompson: thompson::Compiler,
487cf647
FG
1137}
1138
781aab86 1139#[cfg(feature = "dfa-build")]
487cf647
FG
1140impl Builder {
1141 /// Create a new dense DFA builder with the default configuration.
1142 pub fn new() -> Builder {
1143 Builder {
1144 config: Config::default(),
781aab86
FG
1145 #[cfg(feature = "syntax")]
1146 thompson: thompson::Compiler::new(),
487cf647
FG
1147 }
1148 }
1149
1150 /// Build a DFA from the given pattern.
1151 ///
1152 /// If there was a problem parsing or compiling the pattern, then an error
1153 /// is returned.
781aab86
FG
1154 #[cfg(feature = "syntax")]
1155 pub fn build(&self, pattern: &str) -> Result<OwnedDFA, BuildError> {
487cf647
FG
1156 self.build_many(&[pattern])
1157 }
1158
1159 /// Build a DFA from the given patterns.
1160 ///
1161 /// When matches are returned, the pattern ID corresponds to the index of
1162 /// the pattern in the slice given.
781aab86 1163 #[cfg(feature = "syntax")]
487cf647
FG
1164 pub fn build_many<P: AsRef<str>>(
1165 &self,
1166 patterns: &[P],
781aab86
FG
1167 ) -> Result<OwnedDFA, BuildError> {
1168 let nfa = self
1169 .thompson
1170 .clone()
1171 // We can always forcefully disable captures because DFAs do not
1172 // support them.
1173 .configure(
1174 thompson::Config::new()
1175 .which_captures(thompson::WhichCaptures::None),
1176 )
1177 .build_many(patterns)
1178 .map_err(BuildError::nfa)?;
487cf647
FG
1179 self.build_from_nfa(&nfa)
1180 }
1181
1182 /// Build a DFA from the given NFA.
1183 ///
1184 /// # Example
1185 ///
1186 /// This example shows how to build a DFA if you already have an NFA in
1187 /// hand.
1188 ///
1189 /// ```
1190 /// use regex_automata::{
1191 /// dfa::{Automaton, dense},
781aab86
FG
1192 /// nfa::thompson::NFA,
1193 /// HalfMatch, Input,
487cf647
FG
1194 /// };
1195 ///
1196 /// let haystack = "foo123bar".as_bytes();
1197 ///
1198 /// // This shows how to set non-default options for building an NFA.
781aab86
FG
1199 /// let nfa = NFA::compiler()
1200 /// .configure(NFA::config().shrink(true))
487cf647
FG
1201 /// .build(r"[0-9]+")?;
1202 /// let dfa = dense::Builder::new().build_from_nfa(&nfa)?;
1203 /// let expected = Some(HalfMatch::must(0, 6));
781aab86 1204 /// let got = dfa.try_search_fwd(&Input::new(haystack))?;
487cf647
FG
1205 /// assert_eq!(expected, got);
1206 ///
1207 /// # Ok::<(), Box<dyn std::error::Error>>(())
1208 /// ```
1209 pub fn build_from_nfa(
1210 &self,
1211 nfa: &thompson::NFA,
781aab86
FG
1212 ) -> Result<OwnedDFA, BuildError> {
1213 let mut quitset = self.config.quitset.unwrap_or(ByteSet::empty());
487cf647 1214 if self.config.get_unicode_word_boundary()
781aab86 1215 && nfa.look_set_any().contains_word_unicode()
487cf647
FG
1216 {
1217 for b in 0x80..=0xFF {
781aab86 1218 quitset.add(b);
487cf647
FG
1219 }
1220 }
1221 let classes = if !self.config.get_byte_classes() {
1222 // DFAs will always use the equivalence class map, but enabling
1223 // this option is useful for debugging. Namely, this will cause all
1224 // transitions to be defined over their actual bytes instead of an
1225 // opaque equivalence class identifier. The former is much easier
1226 // to grok as a human.
1227 ByteClasses::singletons()
1228 } else {
1229 let mut set = nfa.byte_class_set().clone();
1230 // It is important to distinguish any "quit" bytes from all other
1231 // bytes. Otherwise, a non-quit byte may end up in the same class
1232 // as a quit byte, and thus cause the DFA stop when it shouldn't.
781aab86
FG
1233 //
1234 // Test case:
1235 //
1236 // regex-cli find hybrid regex -w @conn.json.1000x.log \
1237 // '^#' '\b10\.55\.182\.100\b'
1238 if !quitset.is_empty() {
1239 set.add_set(&quitset);
487cf647
FG
1240 }
1241 set.byte_classes()
1242 };
1243
1244 let mut dfa = DFA::initial(
1245 classes,
1246 nfa.pattern_len(),
781aab86
FG
1247 self.config.get_starts(),
1248 nfa.look_matcher(),
487cf647 1249 self.config.get_starts_for_each_pattern(),
781aab86
FG
1250 self.config.get_prefilter().map(|p| p.clone()),
1251 quitset,
1252 Flags::from_nfa(&nfa),
487cf647
FG
1253 )?;
1254 determinize::Config::new()
487cf647 1255 .match_kind(self.config.get_match_kind())
781aab86 1256 .quit(quitset)
487cf647
FG
1257 .dfa_size_limit(self.config.get_dfa_size_limit())
1258 .determinize_size_limit(self.config.get_determinize_size_limit())
1259 .run(nfa, &mut dfa)?;
1260 if self.config.get_minimize() {
1261 dfa.minimize();
1262 }
1263 if self.config.get_accelerate() {
1264 dfa.accelerate();
1265 }
781aab86
FG
1266 // The state shuffling done before this point always assumes that start
1267 // states should be marked as "special," even though it isn't the
1268 // default configuration. State shuffling is complex enough as it is,
1269 // so it's simpler to just "fix" our special state ID ranges to not
1270 // include starting states after-the-fact.
1271 if !self.config.get_specialize_start_states() {
1272 dfa.special.set_no_special_start_states();
1273 }
1274 // Look for and set the universal starting states.
1275 dfa.set_universal_starts();
487cf647
FG
1276 Ok(dfa)
1277 }
1278
1279 /// Apply the given dense DFA configuration options to this builder.
1280 pub fn configure(&mut self, config: Config) -> &mut Builder {
1281 self.config = self.config.overwrite(config);
1282 self
1283 }
1284
1285 /// Set the syntax configuration for this builder using
781aab86 1286 /// [`syntax::Config`](crate::util::syntax::Config).
487cf647
FG
1287 ///
1288 /// This permits setting things like case insensitivity, Unicode and multi
1289 /// line mode.
1290 ///
1291 /// These settings only apply when constructing a DFA directly from a
1292 /// pattern.
781aab86 1293 #[cfg(feature = "syntax")]
487cf647
FG
1294 pub fn syntax(
1295 &mut self,
781aab86 1296 config: crate::util::syntax::Config,
487cf647
FG
1297 ) -> &mut Builder {
1298 self.thompson.syntax(config);
1299 self
1300 }
1301
1302 /// Set the Thompson NFA configuration for this builder using
1303 /// [`nfa::thompson::Config`](crate::nfa::thompson::Config).
1304 ///
1305 /// This permits setting things like whether the DFA should match the regex
1306 /// in reverse or if additional time should be spent shrinking the size of
1307 /// the NFA.
1308 ///
1309 /// These settings only apply when constructing a DFA directly from a
1310 /// pattern.
781aab86 1311 #[cfg(feature = "syntax")]
487cf647
FG
1312 pub fn thompson(&mut self, config: thompson::Config) -> &mut Builder {
1313 self.thompson.configure(config);
1314 self
1315 }
1316}
1317
781aab86 1318#[cfg(feature = "dfa-build")]
487cf647
FG
1319impl Default for Builder {
1320 fn default() -> Builder {
1321 Builder::new()
1322 }
1323}
1324
1325/// A convenience alias for an owned DFA. We use this particular instantiation
1326/// a lot in this crate, so it's worth giving it a name. This instantiation
1327/// is commonly used for mutable APIs on the DFA while building it. The main
1328/// reason for making DFAs generic is no_std support, and more generally,
1329/// making it possible to load a DFA from an arbitrary slice of bytes.
1330#[cfg(feature = "alloc")]
781aab86 1331pub(crate) type OwnedDFA = DFA<alloc::vec::Vec<u32>>;
487cf647
FG
1332
1333/// A dense table-based deterministic finite automaton (DFA).
1334///
1335/// All dense DFAs have one or more start states, zero or more match states
1336/// and a transition table that maps the current state and the current byte
1337/// of input to the next state. A DFA can use this information to implement
1338/// fast searching. In particular, the use of a dense DFA generally makes the
1339/// trade off that match speed is the most valuable characteristic, even if
1340/// building the DFA may take significant time *and* space. (More concretely,
1341/// building a DFA takes time and space that is exponential in the size of the
1342/// pattern in the worst case.) As such, the processing of every byte of input
1343/// is done with a small constant number of operations that does not vary with
1344/// the pattern, its size or the size of the alphabet. If your needs don't line
1345/// up with this trade off, then a dense DFA may not be an adequate solution to
1346/// your problem.
1347///
1348/// In contrast, a [`sparse::DFA`] makes the opposite
1349/// trade off: it uses less space but will execute a variable number of
1350/// instructions per byte at match time, which makes it slower for matching.
1351/// (Note that space usage is still exponential in the size of the pattern in
1352/// the worst case.)
1353///
1354/// A DFA can be built using the default configuration via the
1355/// [`DFA::new`] constructor. Otherwise, one can
1356/// configure various aspects via [`dense::Builder`](Builder).
1357///
1358/// A single DFA fundamentally supports the following operations:
1359///
1360/// 1. Detection of a match.
1361/// 2. Location of the end of a match.
1362/// 3. In the case of a DFA with multiple patterns, which pattern matched is
1363/// reported as well.
1364///
1365/// A notable absence from the above list of capabilities is the location of
1366/// the *start* of a match. In order to provide both the start and end of
1367/// a match, *two* DFAs are required. This functionality is provided by a
1368/// [`Regex`](crate::dfa::regex::Regex).
1369///
1370/// # Type parameters
1371///
1372/// A `DFA` has one type parameter, `T`, which is used to represent state IDs,
1373/// pattern IDs and accelerators. `T` is typically a `Vec<u32>` or a `&[u32]`.
1374///
1375/// # The `Automaton` trait
1376///
1377/// This type implements the [`Automaton`] trait, which means it can be used
1378/// for searching. For example:
1379///
1380/// ```
781aab86 1381/// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1382///
1383/// let dfa = DFA::new("foo[0-9]+")?;
1384/// let expected = HalfMatch::must(0, 8);
781aab86 1385/// assert_eq!(Some(expected), dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1386/// # Ok::<(), Box<dyn std::error::Error>>(())
1387/// ```
1388#[derive(Clone)]
1389pub struct DFA<T> {
1390 /// The transition table for this DFA. This includes the transitions
1391 /// themselves, along with the stride, number of states and the equivalence
1392 /// class mapping.
1393 tt: TransitionTable<T>,
1394 /// The set of starting state identifiers for this DFA. The starting state
1395 /// IDs act as pointers into the transition table. The specific starting
1396 /// state chosen for each search is dependent on the context at which the
1397 /// search begins.
1398 st: StartTable<T>,
1399 /// The set of match states and the patterns that match for each
1400 /// corresponding match state.
1401 ///
1402 /// This structure is technically only needed because of support for
1403 /// multi-regexes. Namely, multi-regexes require answering not just whether
1404 /// a match exists, but _which_ patterns match. So we need to store the
1405 /// matching pattern IDs for each match state. We do this even when there
1406 /// is only one pattern for the sake of simplicity. In practice, this uses
781aab86 1407 /// up very little space for the case of one pattern.
487cf647
FG
1408 ms: MatchStates<T>,
1409 /// Information about which states are "special." Special states are states
1410 /// that are dead, quit, matching, starting or accelerated. For more info,
1411 /// see the docs for `Special`.
1412 special: Special,
1413 /// The accelerators for this DFA.
1414 ///
1415 /// If a state is accelerated, then there exist only a small number of
1416 /// bytes that can cause the DFA to leave the state. This permits searching
1417 /// to use optimized routines to find those specific bytes instead of using
1418 /// the transition table.
1419 ///
1420 /// All accelerated states exist in a contiguous range in the DFA's
1421 /// transition table. See dfa/special.rs for more details on how states are
1422 /// arranged.
1423 accels: Accels<T>,
781aab86
FG
1424 /// Any prefilter attached to this DFA.
1425 ///
1426 /// Note that currently prefilters are not serialized. When deserializing
1427 /// a DFA from bytes, this is always set to `None`.
1428 pre: Option<Prefilter>,
1429 /// The set of "quit" bytes for this DFA.
1430 ///
1431 /// This is only used when computing the start state for a particular
1432 /// position in a haystack. Namely, in the case where there is a quit
1433 /// byte immediately before the start of the search, this set needs to be
1434 /// explicitly consulted. In all other cases, quit bytes are detected by
1435 /// the DFA itself, by transitioning all quit bytes to a special "quit
1436 /// state."
1437 quitset: ByteSet,
1438 /// Various flags describing the behavior of this DFA.
1439 flags: Flags,
487cf647
FG
1440}
1441
781aab86 1442#[cfg(feature = "dfa-build")]
487cf647
FG
1443impl OwnedDFA {
1444 /// Parse the given regular expression using a default configuration and
1445 /// return the corresponding DFA.
1446 ///
1447 /// If you want a non-default configuration, then use the
1448 /// [`dense::Builder`](Builder) to set your own configuration.
1449 ///
1450 /// # Example
1451 ///
1452 /// ```
781aab86 1453 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
487cf647
FG
1454 ///
1455 /// let dfa = dense::DFA::new("foo[0-9]+bar")?;
781aab86
FG
1456 /// let expected = Some(HalfMatch::must(0, 11));
1457 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
487cf647
FG
1458 /// # Ok::<(), Box<dyn std::error::Error>>(())
1459 /// ```
781aab86
FG
1460 #[cfg(feature = "syntax")]
1461 pub fn new(pattern: &str) -> Result<OwnedDFA, BuildError> {
487cf647
FG
1462 Builder::new().build(pattern)
1463 }
1464
1465 /// Parse the given regular expressions using a default configuration and
1466 /// return the corresponding multi-DFA.
1467 ///
1468 /// If you want a non-default configuration, then use the
1469 /// [`dense::Builder`](Builder) to set your own configuration.
1470 ///
1471 /// # Example
1472 ///
1473 /// ```
781aab86 1474 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
487cf647
FG
1475 ///
1476 /// let dfa = dense::DFA::new_many(&["[0-9]+", "[a-z]+"])?;
781aab86
FG
1477 /// let expected = Some(HalfMatch::must(1, 3));
1478 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
487cf647
FG
1479 /// # Ok::<(), Box<dyn std::error::Error>>(())
1480 /// ```
781aab86
FG
1481 #[cfg(feature = "syntax")]
1482 pub fn new_many<P: AsRef<str>>(
1483 patterns: &[P],
1484 ) -> Result<OwnedDFA, BuildError> {
487cf647
FG
1485 Builder::new().build_many(patterns)
1486 }
1487}
1488
781aab86 1489#[cfg(feature = "dfa-build")]
487cf647
FG
1490impl OwnedDFA {
1491 /// Create a new DFA that matches every input.
1492 ///
1493 /// # Example
1494 ///
1495 /// ```
781aab86 1496 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
487cf647
FG
1497 ///
1498 /// let dfa = dense::DFA::always_match()?;
1499 ///
781aab86
FG
1500 /// let expected = Some(HalfMatch::must(0, 0));
1501 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new(""))?);
1502 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo"))?);
487cf647
FG
1503 /// # Ok::<(), Box<dyn std::error::Error>>(())
1504 /// ```
781aab86 1505 pub fn always_match() -> Result<OwnedDFA, BuildError> {
487cf647
FG
1506 let nfa = thompson::NFA::always_match();
1507 Builder::new().build_from_nfa(&nfa)
1508 }
1509
1510 /// Create a new DFA that never matches any input.
1511 ///
1512 /// # Example
1513 ///
1514 /// ```
781aab86 1515 /// use regex_automata::{dfa::{Automaton, dense}, Input};
487cf647
FG
1516 ///
1517 /// let dfa = dense::DFA::never_match()?;
781aab86
FG
1518 /// assert_eq!(None, dfa.try_search_fwd(&Input::new(""))?);
1519 /// assert_eq!(None, dfa.try_search_fwd(&Input::new("foo"))?);
487cf647
FG
1520 /// # Ok::<(), Box<dyn std::error::Error>>(())
1521 /// ```
781aab86 1522 pub fn never_match() -> Result<OwnedDFA, BuildError> {
487cf647
FG
1523 let nfa = thompson::NFA::never_match();
1524 Builder::new().build_from_nfa(&nfa)
1525 }
1526
781aab86
FG
1527 /// Create an initial DFA with the given equivalence classes, pattern
1528 /// length and whether anchored starting states are enabled for each
1529 /// pattern. An initial DFA can be further mutated via determinization.
487cf647
FG
1530 fn initial(
1531 classes: ByteClasses,
781aab86
FG
1532 pattern_len: usize,
1533 starts: StartKind,
1534 lookm: &LookMatcher,
487cf647 1535 starts_for_each_pattern: bool,
781aab86
FG
1536 pre: Option<Prefilter>,
1537 quitset: ByteSet,
1538 flags: Flags,
1539 ) -> Result<OwnedDFA, BuildError> {
1540 let start_pattern_len =
1541 if starts_for_each_pattern { Some(pattern_len) } else { None };
487cf647
FG
1542 Ok(DFA {
1543 tt: TransitionTable::minimal(classes),
781aab86
FG
1544 st: StartTable::dead(starts, lookm, start_pattern_len)?,
1545 ms: MatchStates::empty(pattern_len),
487cf647
FG
1546 special: Special::new(),
1547 accels: Accels::empty(),
781aab86
FG
1548 pre,
1549 quitset,
1550 flags,
487cf647
FG
1551 })
1552 }
1553}
1554
781aab86
FG
1555#[cfg(feature = "dfa-build")]
1556impl DFA<&[u32]> {
1557 /// Return a new default dense DFA compiler configuration.
1558 ///
1559 /// This is a convenience routine to avoid needing to import the [`Config`]
1560 /// type when customizing the construction of a dense DFA.
1561 pub fn config() -> Config {
1562 Config::new()
1563 }
1564
1565 /// Create a new dense DFA builder with the default configuration.
1566 ///
1567 /// This is a convenience routine to avoid needing to import the
1568 /// [`Builder`] type in common cases.
1569 pub fn builder() -> Builder {
1570 Builder::new()
1571 }
1572}
1573
487cf647
FG
1574impl<T: AsRef<[u32]>> DFA<T> {
1575 /// Cheaply return a borrowed version of this dense DFA. Specifically,
1576 /// the DFA returned always uses `&[u32]` for its transition table.
1577 pub fn as_ref(&self) -> DFA<&'_ [u32]> {
1578 DFA {
1579 tt: self.tt.as_ref(),
1580 st: self.st.as_ref(),
1581 ms: self.ms.as_ref(),
1582 special: self.special,
1583 accels: self.accels(),
781aab86
FG
1584 pre: self.pre.clone(),
1585 quitset: self.quitset,
1586 flags: self.flags,
487cf647
FG
1587 }
1588 }
1589
1590 /// Return an owned version of this sparse DFA. Specifically, the DFA
1591 /// returned always uses `Vec<u32>` for its transition table.
1592 ///
1593 /// Effectively, this returns a dense DFA whose transition table lives on
1594 /// the heap.
1595 #[cfg(feature = "alloc")]
1596 pub fn to_owned(&self) -> OwnedDFA {
1597 DFA {
1598 tt: self.tt.to_owned(),
1599 st: self.st.to_owned(),
1600 ms: self.ms.to_owned(),
1601 special: self.special,
1602 accels: self.accels().to_owned(),
781aab86
FG
1603 pre: self.pre.clone(),
1604 quitset: self.quitset,
1605 flags: self.flags,
487cf647
FG
1606 }
1607 }
1608
781aab86
FG
1609 /// Returns the starting state configuration for this DFA.
1610 ///
1611 /// The default is [`StartKind::Both`], which means the DFA supports both
1612 /// unanchored and anchored searches. However, this can generally lead to
1613 /// bigger DFAs. Therefore, a DFA might be compiled with support for just
1614 /// unanchored or anchored searches. In that case, running a search with
1615 /// an unsupported configuration will panic.
1616 pub fn start_kind(&self) -> StartKind {
1617 self.st.kind
1618 }
1619
1620 /// Returns the start byte map used for computing the `Start` configuration
1621 /// at the beginning of a search.
1622 pub(crate) fn start_map(&self) -> &StartByteMap {
1623 &self.st.start_map
1624 }
1625
487cf647
FG
1626 /// Returns true only if this DFA has starting states for each pattern.
1627 ///
1628 /// When a DFA has starting states for each pattern, then a search with the
1629 /// DFA can be configured to only look for anchored matches of a specific
781aab86
FG
1630 /// pattern. Specifically, APIs like [`Automaton::try_search_fwd`] can
1631 /// accept a non-None `pattern_id` if and only if this method returns true.
1632 /// Otherwise, calling `try_search_fwd` will panic.
487cf647
FG
1633 ///
1634 /// Note that if the DFA has no patterns, this always returns false.
781aab86
FG
1635 pub fn starts_for_each_pattern(&self) -> bool {
1636 self.st.pattern_len.is_some()
1637 }
1638
1639 /// Returns the equivalence classes that make up the alphabet for this DFA.
1640 ///
1641 /// Unless [`Config::byte_classes`] was disabled, it is possible that
1642 /// multiple distinct bytes are grouped into the same equivalence class
1643 /// if it is impossible for them to discriminate between a match and a
1644 /// non-match. This has the effect of reducing the overall alphabet size
1645 /// and in turn potentially substantially reducing the size of the DFA's
1646 /// transition table.
1647 ///
1648 /// The downside of using equivalence classes like this is that every state
1649 /// transition will automatically use this map to convert an arbitrary
1650 /// byte to its corresponding equivalence class. In practice this has a
1651 /// negligible impact on performance.
1652 pub fn byte_classes(&self) -> &ByteClasses {
1653 &self.tt.classes
487cf647
FG
1654 }
1655
1656 /// Returns the total number of elements in the alphabet for this DFA.
1657 ///
1658 /// That is, this returns the total number of transitions that each state
1659 /// in this DFA must have. Typically, a normal byte oriented DFA would
1660 /// always have an alphabet size of 256, corresponding to the number of
1661 /// unique values in a single byte. However, this implementation has two
1662 /// peculiarities that impact the alphabet length:
1663 ///
1664 /// * Every state has a special "EOI" transition that is only followed
1665 /// after the end of some haystack is reached. This EOI transition is
1666 /// necessary to account for one byte of look-ahead when implementing
1667 /// things like `\b` and `$`.
1668 /// * Bytes are grouped into equivalence classes such that no two bytes in
1669 /// the same class can distinguish a match from a non-match. For example,
1670 /// in the regex `^[a-z]+$`, the ASCII bytes `a-z` could all be in the
1671 /// same equivalence class. This leads to a massive space savings.
1672 ///
1673 /// Note though that the alphabet length does _not_ necessarily equal the
1674 /// total stride space taken up by a single DFA state in the transition
1675 /// table. Namely, for performance reasons, the stride is always the
1676 /// smallest power of two that is greater than or equal to the alphabet
1677 /// length. For this reason, [`DFA::stride`] or [`DFA::stride2`] are
1678 /// often more useful. The alphabet length is typically useful only for
1679 /// informational purposes.
1680 pub fn alphabet_len(&self) -> usize {
1681 self.tt.alphabet_len()
1682 }
1683
1684 /// Returns the total stride for every state in this DFA, expressed as the
1685 /// exponent of a power of 2. The stride is the amount of space each state
1686 /// takes up in the transition table, expressed as a number of transitions.
1687 /// (Unused transitions map to dead states.)
1688 ///
1689 /// The stride of a DFA is always equivalent to the smallest power of 2
1690 /// that is greater than or equal to the DFA's alphabet length. This
1691 /// definition uses extra space, but permits faster translation between
1692 /// premultiplied state identifiers and contiguous indices (by using shifts
1693 /// instead of relying on integer division).
1694 ///
1695 /// For example, if the DFA's stride is 16 transitions, then its `stride2`
1696 /// is `4` since `2^4 = 16`.
1697 ///
1698 /// The minimum `stride2` value is `1` (corresponding to a stride of `2`)
1699 /// while the maximum `stride2` value is `9` (corresponding to a stride of
1700 /// `512`). The maximum is not `8` since the maximum alphabet size is `257`
1701 /// when accounting for the special EOI transition. However, an alphabet
1702 /// length of that size is exceptionally rare since the alphabet is shrunk
1703 /// into equivalence classes.
1704 pub fn stride2(&self) -> usize {
1705 self.tt.stride2
1706 }
1707
1708 /// Returns the total stride for every state in this DFA. This corresponds
1709 /// to the total number of transitions used by each state in this DFA's
1710 /// transition table.
1711 ///
1712 /// Please see [`DFA::stride2`] for more information. In particular, this
1713 /// returns the stride as the number of transitions, where as `stride2`
1714 /// returns it as the exponent of a power of 2.
1715 pub fn stride(&self) -> usize {
1716 self.tt.stride()
1717 }
1718
487cf647
FG
1719 /// Returns the memory usage, in bytes, of this DFA.
1720 ///
1721 /// The memory usage is computed based on the number of bytes used to
1722 /// represent this DFA.
1723 ///
1724 /// This does **not** include the stack size used up by this DFA. To
1725 /// compute that, use `std::mem::size_of::<dense::DFA>()`.
1726 pub fn memory_usage(&self) -> usize {
1727 self.tt.memory_usage()
1728 + self.st.memory_usage()
1729 + self.ms.memory_usage()
1730 + self.accels.memory_usage()
1731 }
1732}
1733
1734/// Routines for converting a dense DFA to other representations, such as
1735/// sparse DFAs or raw bytes suitable for persistent storage.
1736impl<T: AsRef<[u32]>> DFA<T> {
1737 /// Convert this dense DFA to a sparse DFA.
1738 ///
1739 /// If a `StateID` is too small to represent all states in the sparse
1740 /// DFA, then this returns an error. In most cases, if a dense DFA is
1741 /// constructable with `StateID` then a sparse DFA will be as well.
1742 /// However, it is not guaranteed.
1743 ///
1744 /// # Example
1745 ///
1746 /// ```
781aab86 1747 /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
487cf647
FG
1748 ///
1749 /// let dense = dense::DFA::new("foo[0-9]+")?;
1750 /// let sparse = dense.to_sparse()?;
1751 ///
781aab86
FG
1752 /// let expected = Some(HalfMatch::must(0, 8));
1753 /// assert_eq!(expected, sparse.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1754 /// # Ok::<(), Box<dyn std::error::Error>>(())
1755 /// ```
781aab86
FG
1756 #[cfg(feature = "dfa-build")]
1757 pub fn to_sparse(&self) -> Result<sparse::DFA<Vec<u8>>, BuildError> {
487cf647
FG
1758 sparse::DFA::from_dense(self)
1759 }
1760
1761 /// Serialize this DFA as raw bytes to a `Vec<u8>` in little endian
1762 /// format. Upon success, the `Vec<u8>` and the initial padding length are
1763 /// returned.
1764 ///
1765 /// The written bytes are guaranteed to be deserialized correctly and
1766 /// without errors in a semver compatible release of this crate by a
1767 /// `DFA`'s deserialization APIs (assuming all other criteria for the
1768 /// deserialization APIs has been satisfied):
1769 ///
1770 /// * [`DFA::from_bytes`]
1771 /// * [`DFA::from_bytes_unchecked`]
1772 ///
1773 /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1774 /// an address that does not have the same alignment as `u32`. The padding
1775 /// corresponds to the number of leading bytes written to the returned
1776 /// `Vec<u8>`.
1777 ///
1778 /// # Example
1779 ///
1780 /// This example shows how to serialize and deserialize a DFA:
1781 ///
1782 /// ```
781aab86 1783 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1784 ///
1785 /// // Compile our original DFA.
1786 /// let original_dfa = DFA::new("foo[0-9]+")?;
1787 ///
1788 /// // N.B. We use native endianness here to make the example work, but
1789 /// // using to_bytes_little_endian would work on a little endian target.
1790 /// let (buf, _) = original_dfa.to_bytes_native_endian();
1791 /// // Even if buf has initial padding, DFA::from_bytes will automatically
1792 /// // ignore it.
1793 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1794 ///
781aab86
FG
1795 /// let expected = Some(HalfMatch::must(0, 8));
1796 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1797 /// # Ok::<(), Box<dyn std::error::Error>>(())
1798 /// ```
781aab86 1799 #[cfg(feature = "dfa-build")]
487cf647 1800 pub fn to_bytes_little_endian(&self) -> (Vec<u8>, usize) {
781aab86 1801 self.to_bytes::<wire::LE>()
487cf647
FG
1802 }
1803
1804 /// Serialize this DFA as raw bytes to a `Vec<u8>` in big endian
1805 /// format. Upon success, the `Vec<u8>` and the initial padding length are
1806 /// returned.
1807 ///
1808 /// The written bytes are guaranteed to be deserialized correctly and
1809 /// without errors in a semver compatible release of this crate by a
1810 /// `DFA`'s deserialization APIs (assuming all other criteria for the
1811 /// deserialization APIs has been satisfied):
1812 ///
1813 /// * [`DFA::from_bytes`]
1814 /// * [`DFA::from_bytes_unchecked`]
1815 ///
1816 /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1817 /// an address that does not have the same alignment as `u32`. The padding
1818 /// corresponds to the number of leading bytes written to the returned
1819 /// `Vec<u8>`.
1820 ///
1821 /// # Example
1822 ///
1823 /// This example shows how to serialize and deserialize a DFA:
1824 ///
1825 /// ```
781aab86 1826 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1827 ///
1828 /// // Compile our original DFA.
1829 /// let original_dfa = DFA::new("foo[0-9]+")?;
1830 ///
1831 /// // N.B. We use native endianness here to make the example work, but
1832 /// // using to_bytes_big_endian would work on a big endian target.
1833 /// let (buf, _) = original_dfa.to_bytes_native_endian();
1834 /// // Even if buf has initial padding, DFA::from_bytes will automatically
1835 /// // ignore it.
1836 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1837 ///
781aab86
FG
1838 /// let expected = Some(HalfMatch::must(0, 8));
1839 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1840 /// # Ok::<(), Box<dyn std::error::Error>>(())
1841 /// ```
781aab86 1842 #[cfg(feature = "dfa-build")]
487cf647 1843 pub fn to_bytes_big_endian(&self) -> (Vec<u8>, usize) {
781aab86 1844 self.to_bytes::<wire::BE>()
487cf647
FG
1845 }
1846
1847 /// Serialize this DFA as raw bytes to a `Vec<u8>` in native endian
1848 /// format. Upon success, the `Vec<u8>` and the initial padding length are
1849 /// returned.
1850 ///
1851 /// The written bytes are guaranteed to be deserialized correctly and
1852 /// without errors in a semver compatible release of this crate by a
1853 /// `DFA`'s deserialization APIs (assuming all other criteria for the
1854 /// deserialization APIs has been satisfied):
1855 ///
1856 /// * [`DFA::from_bytes`]
1857 /// * [`DFA::from_bytes_unchecked`]
1858 ///
1859 /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1860 /// an address that does not have the same alignment as `u32`. The padding
1861 /// corresponds to the number of leading bytes written to the returned
1862 /// `Vec<u8>`.
1863 ///
1864 /// Generally speaking, native endian format should only be used when
1865 /// you know that the target you're compiling the DFA for matches the
1866 /// endianness of the target on which you're compiling DFA. For example,
1867 /// if serialization and deserialization happen in the same process or on
1868 /// the same machine. Otherwise, when serializing a DFA for use in a
1869 /// portable environment, you'll almost certainly want to serialize _both_
1870 /// a little endian and a big endian version and then load the correct one
1871 /// based on the target's configuration.
1872 ///
1873 /// # Example
1874 ///
1875 /// This example shows how to serialize and deserialize a DFA:
1876 ///
1877 /// ```
781aab86 1878 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1879 ///
1880 /// // Compile our original DFA.
1881 /// let original_dfa = DFA::new("foo[0-9]+")?;
1882 ///
1883 /// let (buf, _) = original_dfa.to_bytes_native_endian();
1884 /// // Even if buf has initial padding, DFA::from_bytes will automatically
1885 /// // ignore it.
1886 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1887 ///
781aab86
FG
1888 /// let expected = Some(HalfMatch::must(0, 8));
1889 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1890 /// # Ok::<(), Box<dyn std::error::Error>>(())
1891 /// ```
781aab86 1892 #[cfg(feature = "dfa-build")]
487cf647 1893 pub fn to_bytes_native_endian(&self) -> (Vec<u8>, usize) {
781aab86 1894 self.to_bytes::<wire::NE>()
487cf647
FG
1895 }
1896
1897 /// The implementation of the public `to_bytes` serialization methods,
1898 /// which is generic over endianness.
781aab86 1899 #[cfg(feature = "dfa-build")]
487cf647
FG
1900 fn to_bytes<E: Endian>(&self) -> (Vec<u8>, usize) {
1901 let len = self.write_to_len();
781aab86 1902 let (mut buf, padding) = wire::alloc_aligned_buffer::<u32>(len);
487cf647
FG
1903 // This should always succeed since the only possible serialization
1904 // error is providing a buffer that's too small, but we've ensured that
1905 // `buf` is big enough here.
1906 self.as_ref().write_to::<E>(&mut buf[padding..]).unwrap();
1907 (buf, padding)
1908 }
1909
1910 /// Serialize this DFA as raw bytes to the given slice, in little endian
1911 /// format. Upon success, the total number of bytes written to `dst` is
1912 /// returned.
1913 ///
1914 /// The written bytes are guaranteed to be deserialized correctly and
1915 /// without errors in a semver compatible release of this crate by a
1916 /// `DFA`'s deserialization APIs (assuming all other criteria for the
1917 /// deserialization APIs has been satisfied):
1918 ///
1919 /// * [`DFA::from_bytes`]
1920 /// * [`DFA::from_bytes_unchecked`]
1921 ///
1922 /// Note that unlike the various `to_byte_*` routines, this does not write
1923 /// any padding. Callers are responsible for handling alignment correctly.
1924 ///
1925 /// # Errors
1926 ///
1927 /// This returns an error if the given destination slice is not big enough
1928 /// to contain the full serialized DFA. If an error occurs, then nothing
1929 /// is written to `dst`.
1930 ///
1931 /// # Example
1932 ///
1933 /// This example shows how to serialize and deserialize a DFA without
1934 /// dynamic memory allocation.
1935 ///
1936 /// ```
781aab86 1937 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1938 ///
1939 /// // Compile our original DFA.
1940 /// let original_dfa = DFA::new("foo[0-9]+")?;
1941 ///
781aab86
FG
1942 /// // Create a 4KB buffer on the stack to store our serialized DFA. We
1943 /// // need to use a special type to force the alignment of our [u8; N]
1944 /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
1945 /// // the DFA may fail because of an alignment mismatch.
1946 /// #[repr(C)]
1947 /// struct Aligned<B: ?Sized> {
1948 /// _align: [u32; 0],
1949 /// bytes: B,
1950 /// }
1951 /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
487cf647
FG
1952 /// // N.B. We use native endianness here to make the example work, but
1953 /// // using write_to_little_endian would work on a little endian target.
781aab86
FG
1954 /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
1955 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
487cf647 1956 ///
781aab86
FG
1957 /// let expected = Some(HalfMatch::must(0, 8));
1958 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
1959 /// # Ok::<(), Box<dyn std::error::Error>>(())
1960 /// ```
1961 pub fn write_to_little_endian(
1962 &self,
1963 dst: &mut [u8],
1964 ) -> Result<usize, SerializeError> {
781aab86 1965 self.as_ref().write_to::<wire::LE>(dst)
487cf647
FG
1966 }
1967
1968 /// Serialize this DFA as raw bytes to the given slice, in big endian
1969 /// format. Upon success, the total number of bytes written to `dst` is
1970 /// returned.
1971 ///
1972 /// The written bytes are guaranteed to be deserialized correctly and
1973 /// without errors in a semver compatible release of this crate by a
1974 /// `DFA`'s deserialization APIs (assuming all other criteria for the
1975 /// deserialization APIs has been satisfied):
1976 ///
1977 /// * [`DFA::from_bytes`]
1978 /// * [`DFA::from_bytes_unchecked`]
1979 ///
1980 /// Note that unlike the various `to_byte_*` routines, this does not write
1981 /// any padding. Callers are responsible for handling alignment correctly.
1982 ///
1983 /// # Errors
1984 ///
1985 /// This returns an error if the given destination slice is not big enough
1986 /// to contain the full serialized DFA. If an error occurs, then nothing
1987 /// is written to `dst`.
1988 ///
1989 /// # Example
1990 ///
1991 /// This example shows how to serialize and deserialize a DFA without
1992 /// dynamic memory allocation.
1993 ///
1994 /// ```
781aab86 1995 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
1996 ///
1997 /// // Compile our original DFA.
1998 /// let original_dfa = DFA::new("foo[0-9]+")?;
1999 ///
781aab86
FG
2000 /// // Create a 4KB buffer on the stack to store our serialized DFA. We
2001 /// // need to use a special type to force the alignment of our [u8; N]
2002 /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
2003 /// // the DFA may fail because of an alignment mismatch.
2004 /// #[repr(C)]
2005 /// struct Aligned<B: ?Sized> {
2006 /// _align: [u32; 0],
2007 /// bytes: B,
2008 /// }
2009 /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
487cf647
FG
2010 /// // N.B. We use native endianness here to make the example work, but
2011 /// // using write_to_big_endian would work on a big endian target.
781aab86
FG
2012 /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
2013 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
487cf647 2014 ///
781aab86
FG
2015 /// let expected = Some(HalfMatch::must(0, 8));
2016 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2017 /// # Ok::<(), Box<dyn std::error::Error>>(())
2018 /// ```
2019 pub fn write_to_big_endian(
2020 &self,
2021 dst: &mut [u8],
2022 ) -> Result<usize, SerializeError> {
781aab86 2023 self.as_ref().write_to::<wire::BE>(dst)
487cf647
FG
2024 }
2025
2026 /// Serialize this DFA as raw bytes to the given slice, in native endian
2027 /// format. Upon success, the total number of bytes written to `dst` is
2028 /// returned.
2029 ///
2030 /// The written bytes are guaranteed to be deserialized correctly and
2031 /// without errors in a semver compatible release of this crate by a
2032 /// `DFA`'s deserialization APIs (assuming all other criteria for the
2033 /// deserialization APIs has been satisfied):
2034 ///
2035 /// * [`DFA::from_bytes`]
2036 /// * [`DFA::from_bytes_unchecked`]
2037 ///
2038 /// Generally speaking, native endian format should only be used when
2039 /// you know that the target you're compiling the DFA for matches the
2040 /// endianness of the target on which you're compiling DFA. For example,
2041 /// if serialization and deserialization happen in the same process or on
2042 /// the same machine. Otherwise, when serializing a DFA for use in a
2043 /// portable environment, you'll almost certainly want to serialize _both_
2044 /// a little endian and a big endian version and then load the correct one
2045 /// based on the target's configuration.
2046 ///
2047 /// Note that unlike the various `to_byte_*` routines, this does not write
2048 /// any padding. Callers are responsible for handling alignment correctly.
2049 ///
2050 /// # Errors
2051 ///
2052 /// This returns an error if the given destination slice is not big enough
2053 /// to contain the full serialized DFA. If an error occurs, then nothing
2054 /// is written to `dst`.
2055 ///
2056 /// # Example
2057 ///
2058 /// This example shows how to serialize and deserialize a DFA without
2059 /// dynamic memory allocation.
2060 ///
2061 /// ```
781aab86 2062 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
2063 ///
2064 /// // Compile our original DFA.
2065 /// let original_dfa = DFA::new("foo[0-9]+")?;
2066 ///
781aab86
FG
2067 /// // Create a 4KB buffer on the stack to store our serialized DFA. We
2068 /// // need to use a special type to force the alignment of our [u8; N]
2069 /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
2070 /// // the DFA may fail because of an alignment mismatch.
2071 /// #[repr(C)]
2072 /// struct Aligned<B: ?Sized> {
2073 /// _align: [u32; 0],
2074 /// bytes: B,
2075 /// }
2076 /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
2077 /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
2078 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
487cf647 2079 ///
781aab86
FG
2080 /// let expected = Some(HalfMatch::must(0, 8));
2081 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2082 /// # Ok::<(), Box<dyn std::error::Error>>(())
2083 /// ```
2084 pub fn write_to_native_endian(
2085 &self,
2086 dst: &mut [u8],
2087 ) -> Result<usize, SerializeError> {
781aab86 2088 self.as_ref().write_to::<wire::NE>(dst)
487cf647
FG
2089 }
2090
2091 /// Return the total number of bytes required to serialize this DFA.
2092 ///
2093 /// This is useful for determining the size of the buffer required to pass
2094 /// to one of the serialization routines:
2095 ///
2096 /// * [`DFA::write_to_little_endian`]
2097 /// * [`DFA::write_to_big_endian`]
2098 /// * [`DFA::write_to_native_endian`]
2099 ///
2100 /// Passing a buffer smaller than the size returned by this method will
2101 /// result in a serialization error. Serialization routines are guaranteed
2102 /// to succeed when the buffer is big enough.
2103 ///
2104 /// # Example
2105 ///
2106 /// This example shows how to dynamically allocate enough room to serialize
2107 /// a DFA.
2108 ///
2109 /// ```
781aab86 2110 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647 2111 ///
487cf647
FG
2112 /// let original_dfa = DFA::new("foo[0-9]+")?;
2113 ///
2114 /// let mut buf = vec![0; original_dfa.write_to_len()];
781aab86
FG
2115 /// // This is guaranteed to succeed, because the only serialization error
2116 /// // that can occur is when the provided buffer is too small. But
2117 /// // write_to_len guarantees a correct size.
2118 /// let written = original_dfa.write_to_native_endian(&mut buf).unwrap();
2119 /// // But this is not guaranteed to succeed! In particular,
2120 /// // deserialization requires proper alignment for &[u32], but our buffer
2121 /// // was allocated as a &[u8] whose required alignment is smaller than
2122 /// // &[u32]. However, it's likely to work in practice because of how most
2123 /// // allocators work. So if you write code like this, make sure to either
2124 /// // handle the error correctly and/or run it under Miri since Miri will
2125 /// // likely provoke the error by returning Vec<u8> buffers with alignment
2126 /// // less than &[u32].
2127 /// let dfa: DFA<&[u32]> = match DFA::from_bytes(&buf[..written]) {
2128 /// // As mentioned above, it is legal for an error to be returned
2129 /// // here. It is quite difficult to get a Vec<u8> with a guaranteed
2130 /// // alignment equivalent to Vec<u32>.
2131 /// Err(_) => return Ok(()),
2132 /// Ok((dfa, _)) => dfa,
2133 /// };
487cf647 2134 ///
781aab86
FG
2135 /// let expected = Some(HalfMatch::must(0, 8));
2136 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2137 /// # Ok::<(), Box<dyn std::error::Error>>(())
2138 /// ```
2139 ///
2140 /// Note that this example isn't actually guaranteed to work! In
2141 /// particular, if `buf` is not aligned to a 4-byte boundary, then the
2142 /// `DFA::from_bytes` call will fail. If you need this to work, then you
2143 /// either need to deal with adding some initial padding yourself, or use
2144 /// one of the `to_bytes` methods, which will do it for you.
2145 pub fn write_to_len(&self) -> usize {
781aab86
FG
2146 wire::write_label_len(LABEL)
2147 + wire::write_endianness_check_len()
2148 + wire::write_version_len()
487cf647 2149 + size_of::<u32>() // unused, intended for future flexibility
781aab86 2150 + self.flags.write_to_len()
487cf647
FG
2151 + self.tt.write_to_len()
2152 + self.st.write_to_len()
2153 + self.ms.write_to_len()
2154 + self.special.write_to_len()
2155 + self.accels.write_to_len()
781aab86 2156 + self.quitset.write_to_len()
487cf647
FG
2157 }
2158}
2159
2160impl<'a> DFA<&'a [u32]> {
2161 /// Safely deserialize a DFA with a specific state identifier
2162 /// representation. Upon success, this returns both the deserialized DFA
2163 /// and the number of bytes read from the given slice. Namely, the contents
2164 /// of the slice beyond the DFA are not read.
2165 ///
2166 /// Deserializing a DFA using this routine will never allocate heap memory.
2167 /// For safety purposes, the DFA's transition table will be verified such
2168 /// that every transition points to a valid state. If this verification is
2169 /// too costly, then a [`DFA::from_bytes_unchecked`] API is provided, which
2170 /// will always execute in constant time.
2171 ///
2172 /// The bytes given must be generated by one of the serialization APIs
2173 /// of a `DFA` using a semver compatible release of this crate. Those
2174 /// include:
2175 ///
2176 /// * [`DFA::to_bytes_little_endian`]
2177 /// * [`DFA::to_bytes_big_endian`]
2178 /// * [`DFA::to_bytes_native_endian`]
2179 /// * [`DFA::write_to_little_endian`]
2180 /// * [`DFA::write_to_big_endian`]
2181 /// * [`DFA::write_to_native_endian`]
2182 ///
2183 /// The `to_bytes` methods allocate and return a `Vec<u8>` for you, along
2184 /// with handling alignment correctly. The `write_to` methods do not
2185 /// allocate and write to an existing slice (which may be on the stack).
2186 /// Since deserialization always uses the native endianness of the target
2187 /// platform, the serialization API you use should match the endianness of
2188 /// the target platform. (It's often a good idea to generate serialized
2189 /// DFAs for both forms of endianness and then load the correct one based
2190 /// on endianness.)
2191 ///
2192 /// # Errors
2193 ///
2194 /// Generally speaking, it's easier to state the conditions in which an
2195 /// error is _not_ returned. All of the following must be true:
2196 ///
2197 /// * The bytes given must be produced by one of the serialization APIs
2198 /// on this DFA, as mentioned above.
2199 /// * The endianness of the target platform matches the endianness used to
2200 /// serialized the provided DFA.
2201 /// * The slice given must have the same alignment as `u32`.
2202 ///
2203 /// If any of the above are not true, then an error will be returned.
2204 ///
2205 /// # Panics
2206 ///
2207 /// This routine will never panic for any input.
2208 ///
2209 /// # Example
2210 ///
2211 /// This example shows how to serialize a DFA to raw bytes, deserialize it
2212 /// and then use it for searching.
2213 ///
2214 /// ```
781aab86 2215 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
2216 ///
2217 /// let initial = DFA::new("foo[0-9]+")?;
2218 /// let (bytes, _) = initial.to_bytes_native_endian();
2219 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&bytes)?.0;
2220 ///
781aab86
FG
2221 /// let expected = Some(HalfMatch::must(0, 8));
2222 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2223 /// # Ok::<(), Box<dyn std::error::Error>>(())
2224 /// ```
2225 ///
2226 /// # Example: dealing with alignment and padding
2227 ///
2228 /// In the above example, we used the `to_bytes_native_endian` method to
2229 /// serialize a DFA, but we ignored part of its return value corresponding
2230 /// to padding added to the beginning of the serialized DFA. This is OK
2231 /// because deserialization will skip this initial padding. What matters
2232 /// is that the address immediately following the padding has an alignment
2233 /// that matches `u32`. That is, the following is an equivalent but
2234 /// alternative way to write the above example:
2235 ///
2236 /// ```
781aab86 2237 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
2238 ///
2239 /// let initial = DFA::new("foo[0-9]+")?;
2240 /// // Serialization returns the number of leading padding bytes added to
2241 /// // the returned Vec<u8>.
2242 /// let (bytes, pad) = initial.to_bytes_native_endian();
2243 /// let dfa: DFA<&[u32]> = DFA::from_bytes(&bytes[pad..])?.0;
2244 ///
781aab86
FG
2245 /// let expected = Some(HalfMatch::must(0, 8));
2246 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2247 /// # Ok::<(), Box<dyn std::error::Error>>(())
2248 /// ```
2249 ///
2250 /// This padding is necessary because Rust's standard library does
2251 /// not expose any safe and robust way of creating a `Vec<u8>` with a
2252 /// guaranteed alignment other than 1. Now, in practice, the underlying
2253 /// allocator is likely to provide a `Vec<u8>` that meets our alignment
2254 /// requirements, which means `pad` is zero in practice most of the time.
2255 ///
2256 /// The purpose of exposing the padding like this is flexibility for the
2257 /// caller. For example, if one wants to embed a serialized DFA into a
2258 /// compiled program, then it's important to guarantee that it starts at a
2259 /// `u32`-aligned address. The simplest way to do this is to discard the
2260 /// padding bytes and set it up so that the serialized DFA itself begins at
2261 /// a properly aligned address. We can show this in two parts. The first
2262 /// part is serializing the DFA to a file:
2263 ///
2264 /// ```no_run
781aab86 2265 /// use regex_automata::dfa::dense::DFA;
487cf647
FG
2266 ///
2267 /// let dfa = DFA::new("foo[0-9]+")?;
2268 ///
2269 /// let (bytes, pad) = dfa.to_bytes_big_endian();
2270 /// // Write the contents of the DFA *without* the initial padding.
2271 /// std::fs::write("foo.bigendian.dfa", &bytes[pad..])?;
2272 ///
2273 /// // Do it again, but this time for little endian.
2274 /// let (bytes, pad) = dfa.to_bytes_little_endian();
2275 /// std::fs::write("foo.littleendian.dfa", &bytes[pad..])?;
2276 /// # Ok::<(), Box<dyn std::error::Error>>(())
2277 /// ```
2278 ///
2279 /// And now the second part is embedding the DFA into the compiled program
2280 /// and deserializing it at runtime on first use. We use conditional
2281 /// compilation to choose the correct endianness.
2282 ///
2283 /// ```no_run
781aab86
FG
2284 /// use regex_automata::{
2285 /// dfa::{Automaton, dense::DFA},
2286 /// util::{lazy::Lazy, wire::AlignAs},
2287 /// HalfMatch, Input,
2288 /// };
487cf647 2289 ///
781aab86
FG
2290 /// // This crate provides its own "lazy" type, kind of like
2291 /// // lazy_static! or once_cell::sync::Lazy. But it works in no-alloc
2292 /// // no-std environments and let's us write this using completely
2293 /// // safe code.
2294 /// static RE: Lazy<DFA<&'static [u32]>> = Lazy::new(|| {
487cf647
FG
2295 /// # const _: &str = stringify! {
2296 /// // This assignment is made possible (implicitly) via the
781aab86
FG
2297 /// // CoerceUnsized trait. This is what guarantees that our
2298 /// // bytes are stored in memory on a 4 byte boundary. You
2299 /// // *must* do this or something equivalent for correct
2300 /// // deserialization.
2301 /// static ALIGNED: &AlignAs<[u8], u32> = &AlignAs {
487cf647
FG
2302 /// _align: [],
2303 /// #[cfg(target_endian = "big")]
2304 /// bytes: *include_bytes!("foo.bigendian.dfa"),
2305 /// #[cfg(target_endian = "little")]
2306 /// bytes: *include_bytes!("foo.littleendian.dfa"),
2307 /// };
2308 /// # };
781aab86 2309 /// # static ALIGNED: &AlignAs<[u8], u32> = &AlignAs {
487cf647
FG
2310 /// # _align: [],
2311 /// # bytes: [],
2312 /// # };
2313 ///
781aab86
FG
2314 /// let (dfa, _) = DFA::from_bytes(&ALIGNED.bytes)
2315 /// .expect("serialized DFA should be valid");
2316 /// dfa
2317 /// });
487cf647 2318 ///
781aab86
FG
2319 /// let expected = Ok(Some(HalfMatch::must(0, 8)));
2320 /// assert_eq!(expected, RE.try_search_fwd(&Input::new("foo12345")));
487cf647
FG
2321 /// ```
2322 ///
781aab86
FG
2323 /// An alternative to [`util::lazy::Lazy`](crate::util::lazy::Lazy)
2324 /// is [`lazy_static`](https://crates.io/crates/lazy_static) or
2325 /// [`once_cell`](https://crates.io/crates/once_cell), which provide
2326 /// stronger guarantees (like the initialization function only being
2327 /// executed once). And `once_cell` in particular provides a more
2328 /// expressive API. But a `Lazy` value from this crate is likely just fine
2329 /// in most circumstances.
2330 ///
2331 /// Note that regardless of which initialization method you use, you
2332 /// will still need to use the [`AlignAs`](crate::util::wire::AlignAs)
2333 /// trick above to force correct alignment, but this is safe to do and
2334 /// `from_bytes` will return an error if you get it wrong.
487cf647
FG
2335 pub fn from_bytes(
2336 slice: &'a [u8],
2337 ) -> Result<(DFA<&'a [u32]>, usize), DeserializeError> {
781aab86
FG
2338 // SAFETY: This is safe because we validate the transition table, start
2339 // table, match states and accelerators below. If any validation fails,
2340 // then we return an error.
487cf647 2341 let (dfa, nread) = unsafe { DFA::from_bytes_unchecked(slice)? };
781aab86 2342 dfa.tt.validate(&dfa.special)?;
487cf647
FG
2343 dfa.st.validate(&dfa.tt)?;
2344 dfa.ms.validate(&dfa)?;
2345 dfa.accels.validate()?;
2346 // N.B. dfa.special doesn't have a way to do unchecked deserialization,
2347 // so it has already been validated.
2348 Ok((dfa, nread))
2349 }
2350
2351 /// Deserialize a DFA with a specific state identifier representation in
2352 /// constant time by omitting the verification of the validity of the
2353 /// transition table and other data inside the DFA.
2354 ///
2355 /// This is just like [`DFA::from_bytes`], except it can potentially return
2356 /// a DFA that exhibits undefined behavior if its transition table contains
2357 /// invalid state identifiers.
2358 ///
2359 /// This routine is useful if you need to deserialize a DFA cheaply
2360 /// and cannot afford the transition table validation performed by
2361 /// `from_bytes`.
2362 ///
2363 /// # Example
2364 ///
2365 /// ```
781aab86 2366 /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
487cf647
FG
2367 ///
2368 /// let initial = DFA::new("foo[0-9]+")?;
2369 /// let (bytes, _) = initial.to_bytes_native_endian();
2370 /// // SAFETY: This is guaranteed to be safe since the bytes given come
2371 /// // directly from a compatible serialization routine.
2372 /// let dfa: DFA<&[u32]> = unsafe { DFA::from_bytes_unchecked(&bytes)?.0 };
2373 ///
781aab86
FG
2374 /// let expected = Some(HalfMatch::must(0, 8));
2375 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
487cf647
FG
2376 /// # Ok::<(), Box<dyn std::error::Error>>(())
2377 /// ```
2378 pub unsafe fn from_bytes_unchecked(
2379 slice: &'a [u8],
2380 ) -> Result<(DFA<&'a [u32]>, usize), DeserializeError> {
2381 let mut nr = 0;
2382
781aab86
FG
2383 nr += wire::skip_initial_padding(slice);
2384 wire::check_alignment::<StateID>(&slice[nr..])?;
2385 nr += wire::read_label(&slice[nr..], LABEL)?;
2386 nr += wire::read_endianness_check(&slice[nr..])?;
2387 nr += wire::read_version(&slice[nr..], VERSION)?;
487cf647 2388
781aab86 2389 let _unused = wire::try_read_u32(&slice[nr..], "unused space")?;
487cf647
FG
2390 nr += size_of::<u32>();
2391
781aab86
FG
2392 let (flags, nread) = Flags::from_bytes(&slice[nr..])?;
2393 nr += nread;
2394
487cf647
FG
2395 let (tt, nread) = TransitionTable::from_bytes_unchecked(&slice[nr..])?;
2396 nr += nread;
2397
2398 let (st, nread) = StartTable::from_bytes_unchecked(&slice[nr..])?;
2399 nr += nread;
2400
2401 let (ms, nread) = MatchStates::from_bytes_unchecked(&slice[nr..])?;
2402 nr += nread;
2403
2404 let (special, nread) = Special::from_bytes(&slice[nr..])?;
2405 nr += nread;
781aab86 2406 special.validate_state_len(tt.len(), tt.stride2)?;
487cf647
FG
2407
2408 let (accels, nread) = Accels::from_bytes_unchecked(&slice[nr..])?;
2409 nr += nread;
2410
781aab86
FG
2411 let (quitset, nread) = ByteSet::from_bytes(&slice[nr..])?;
2412 nr += nread;
2413
2414 // Prefilters don't support serialization, so they're always absent.
2415 let pre = None;
2416 Ok((DFA { tt, st, ms, special, accels, pre, quitset, flags }, nr))
487cf647
FG
2417 }
2418
2419 /// The implementation of the public `write_to` serialization methods,
2420 /// which is generic over endianness.
2421 ///
2422 /// This is defined only for &[u32] to reduce binary size/compilation time.
2423 fn write_to<E: Endian>(
2424 &self,
2425 mut dst: &mut [u8],
2426 ) -> Result<usize, SerializeError> {
2427 let nwrite = self.write_to_len();
2428 if dst.len() < nwrite {
2429 return Err(SerializeError::buffer_too_small("dense DFA"));
2430 }
2431 dst = &mut dst[..nwrite];
2432
2433 let mut nw = 0;
781aab86
FG
2434 nw += wire::write_label(LABEL, &mut dst[nw..])?;
2435 nw += wire::write_endianness_check::<E>(&mut dst[nw..])?;
2436 nw += wire::write_version::<E>(VERSION, &mut dst[nw..])?;
487cf647
FG
2437 nw += {
2438 // Currently unused, intended for future flexibility
2439 E::write_u32(0, &mut dst[nw..]);
2440 size_of::<u32>()
2441 };
781aab86 2442 nw += self.flags.write_to::<E>(&mut dst[nw..])?;
487cf647
FG
2443 nw += self.tt.write_to::<E>(&mut dst[nw..])?;
2444 nw += self.st.write_to::<E>(&mut dst[nw..])?;
2445 nw += self.ms.write_to::<E>(&mut dst[nw..])?;
2446 nw += self.special.write_to::<E>(&mut dst[nw..])?;
2447 nw += self.accels.write_to::<E>(&mut dst[nw..])?;
781aab86 2448 nw += self.quitset.write_to::<E>(&mut dst[nw..])?;
487cf647
FG
2449 Ok(nw)
2450 }
2451}
2452
781aab86
FG
2453// The following methods implement mutable routines on the internal
2454// representation of a DFA. As such, we must fix the first type parameter to a
2455// `Vec<u32>` since a generic `T: AsRef<[u32]>` does not permit mutation. We
2456// can get away with this because these methods are internal to the crate and
2457// are exclusively used during construction of the DFA.
2458#[cfg(feature = "dfa-build")]
487cf647
FG
2459impl OwnedDFA {
2460 /// Add a start state of this DFA.
2461 pub(crate) fn set_start_state(
2462 &mut self,
781aab86
FG
2463 anchored: Anchored,
2464 start: Start,
487cf647
FG
2465 id: StateID,
2466 ) {
2467 assert!(self.tt.is_valid(id), "invalid start state");
781aab86 2468 self.st.set_start(anchored, start, id);
487cf647
FG
2469 }
2470
2471 /// Set the given transition to this DFA. Both the `from` and `to` states
2472 /// must already exist.
2473 pub(crate) fn set_transition(
2474 &mut self,
2475 from: StateID,
2476 byte: alphabet::Unit,
2477 to: StateID,
2478 ) {
2479 self.tt.set(from, byte, to);
2480 }
2481
2482 /// An an empty state (a state where all transitions lead to a dead state)
2483 /// and return its identifier. The identifier returned is guaranteed to
2484 /// not point to any other existing state.
2485 ///
2486 /// If adding a state would exceed `StateID::LIMIT`, then this returns an
2487 /// error.
781aab86 2488 pub(crate) fn add_empty_state(&mut self) -> Result<StateID, BuildError> {
487cf647
FG
2489 self.tt.add_empty_state()
2490 }
2491
2492 /// Swap the two states given in the transition table.
2493 ///
2494 /// This routine does not do anything to check the correctness of this
2495 /// swap. Callers must ensure that other states pointing to id1 and id2 are
2496 /// updated appropriately.
2497 pub(crate) fn swap_states(&mut self, id1: StateID, id2: StateID) {
2498 self.tt.swap(id1, id2);
2499 }
2500
781aab86
FG
2501 /// Remap all of the state identifiers in this DFA according to the map
2502 /// function given. This includes all transitions and all starting state
2503 /// identifiers.
2504 pub(crate) fn remap(&mut self, map: impl Fn(StateID) -> StateID) {
2505 // We could loop over each state ID and call 'remap_state' here, but
2506 // this is more direct: just map every transition directly. This
2507 // technically might do a little extra work since the alphabet length
2508 // is likely less than the stride, but if that is indeed an issue we
2509 // should benchmark it and fix it.
2510 for sid in self.tt.table_mut().iter_mut() {
2511 *sid = map(*sid);
2512 }
2513 for sid in self.st.table_mut().iter_mut() {
2514 *sid = map(*sid);
2515 }
2516 }
2517
2518 /// Remap the transitions for the state given according to the function
2519 /// given. This applies the given map function to every transition in the
2520 /// given state and changes the transition in place to the result of the
2521 /// map function for that transition.
2522 pub(crate) fn remap_state(
2523 &mut self,
2524 id: StateID,
2525 map: impl Fn(StateID) -> StateID,
2526 ) {
2527 self.tt.remap(id, map);
2528 }
2529
2530 /// Truncate the states in this DFA to the given length.
487cf647
FG
2531 ///
2532 /// This routine does not do anything to check the correctness of this
2533 /// truncation. Callers must ensure that other states pointing to truncated
2534 /// states are updated appropriately.
781aab86
FG
2535 pub(crate) fn truncate_states(&mut self, len: usize) {
2536 self.tt.truncate(len);
487cf647
FG
2537 }
2538
2539 /// Minimize this DFA in place using Hopcroft's algorithm.
2540 pub(crate) fn minimize(&mut self) {
2541 Minimizer::new(self).run();
2542 }
2543
2544 /// Updates the match state pattern ID map to use the one provided.
2545 ///
2546 /// This is useful when it's convenient to manipulate matching states
2547 /// (and their corresponding pattern IDs) as a map. In particular, the
2548 /// representation used by a DFA for this map is not amenable to mutation,
2549 /// so if things need to be changed (like when shuffling states), it's
2550 /// often easier to work with the map form.
2551 pub(crate) fn set_pattern_map(
2552 &mut self,
2553 map: &BTreeMap<StateID, Vec<PatternID>>,
781aab86 2554 ) -> Result<(), BuildError> {
487cf647
FG
2555 self.ms = self.ms.new_with_map(map)?;
2556 Ok(())
2557 }
2558
2559 /// Find states that have a small number of non-loop transitions and mark
2560 /// them as candidates for acceleration during search.
2561 pub(crate) fn accelerate(&mut self) {
2562 // dead and quit states can never be accelerated.
781aab86 2563 if self.state_len() <= 2 {
487cf647
FG
2564 return;
2565 }
2566
2567 // Go through every state and record their accelerator, if possible.
2568 let mut accels = BTreeMap::new();
2569 // Count the number of accelerated match, start and non-match/start
2570 // states.
2571 let (mut cmatch, mut cstart, mut cnormal) = (0, 0, 0);
2572 for state in self.states() {
2573 if let Some(accel) = state.accelerate(self.byte_classes()) {
781aab86
FG
2574 debug!(
2575 "accelerating full DFA state {}: {:?}",
2576 state.id().as_usize(),
2577 accel,
2578 );
487cf647
FG
2579 accels.insert(state.id(), accel);
2580 if self.is_match_state(state.id()) {
2581 cmatch += 1;
2582 } else if self.is_start_state(state.id()) {
2583 cstart += 1;
2584 } else {
2585 assert!(!self.is_dead_state(state.id()));
2586 assert!(!self.is_quit_state(state.id()));
2587 cnormal += 1;
2588 }
2589 }
2590 }
2591 // If no states were able to be accelerated, then we're done.
2592 if accels.is_empty() {
2593 return;
2594 }
2595 let original_accels_len = accels.len();
2596
2597 // A remapper keeps track of state ID changes. Once we're done
2598 // shuffling, the remapper is used to rewrite all transitions in the
2599 // DFA based on the new positions of states.
781aab86 2600 let mut remapper = Remapper::new(self);
487cf647
FG
2601
2602 // As we swap states, if they are match states, we need to swap their
2603 // pattern ID lists too (for multi-regexes). We do this by converting
2604 // the lists to an easily swappable map, and then convert back to
2605 // MatchStates once we're done.
2606 let mut new_matches = self.ms.to_map(self);
2607
2608 // There is at least one state that gets accelerated, so these are
2609 // guaranteed to get set to sensible values below.
2610 self.special.min_accel = StateID::MAX;
2611 self.special.max_accel = StateID::ZERO;
2612 let update_special_accel =
2613 |special: &mut Special, accel_id: StateID| {
2614 special.min_accel = cmp::min(special.min_accel, accel_id);
2615 special.max_accel = cmp::max(special.max_accel, accel_id);
2616 };
2617
2618 // Start by shuffling match states. Any match states that are
2619 // accelerated get moved to the end of the match state range.
2620 if cmatch > 0 && self.special.matches() {
2621 // N.B. special.{min,max}_match do not need updating, since the
2622 // range/number of match states does not change. Only the ordering
2623 // of match states may change.
2624 let mut next_id = self.special.max_match;
2625 let mut cur_id = next_id;
2626 while cur_id >= self.special.min_match {
2627 if let Some(accel) = accels.remove(&cur_id) {
2628 accels.insert(next_id, accel);
2629 update_special_accel(&mut self.special, next_id);
2630
2631 // No need to do any actual swapping for equivalent IDs.
2632 if cur_id != next_id {
2633 remapper.swap(self, cur_id, next_id);
2634
2635 // Swap pattern IDs for match states.
2636 let cur_pids = new_matches.remove(&cur_id).unwrap();
2637 let next_pids = new_matches.remove(&next_id).unwrap();
2638 new_matches.insert(cur_id, next_pids);
2639 new_matches.insert(next_id, cur_pids);
2640 }
2641 next_id = self.tt.prev_state_id(next_id);
2642 }
2643 cur_id = self.tt.prev_state_id(cur_id);
2644 }
2645 }
2646
2647 // This is where it gets tricky. Without acceleration, start states
2648 // normally come right after match states. But we want accelerated
2649 // states to be a single contiguous range (to make it very fast
2650 // to determine whether a state *is* accelerated), while also keeping
2651 // match and starting states as contiguous ranges for the same reason.
2652 // So what we do here is shuffle states such that it looks like this:
2653 //
2654 // DQMMMMAAAAASSSSSSNNNNNNN
2655 // | |
2656 // |---------|
2657 // accelerated states
2658 //
2659 // Where:
2660 // D - dead state
2661 // Q - quit state
2662 // M - match state (may be accelerated)
2663 // A - normal state that is accelerated
2664 // S - start state (may be accelerated)
2665 // N - normal state that is NOT accelerated
2666 //
2667 // We implement this by shuffling states, which is done by a sequence
2668 // of pairwise swaps. We start by looking at all normal states to be
2669 // accelerated. When we find one, we swap it with the earliest starting
2670 // state, and then swap that with the earliest normal state. This
2671 // preserves the contiguous property.
2672 //
2673 // Once we're done looking for accelerated normal states, now we look
2674 // for accelerated starting states by moving them to the beginning
2675 // of the starting state range (just like we moved accelerated match
2676 // states to the end of the matching state range).
2677 //
2678 // For a more detailed/different perspective on this, see the docs
2679 // in dfa/special.rs.
2680 if cnormal > 0 {
2681 // our next available starting and normal states for swapping.
2682 let mut next_start_id = self.special.min_start;
781aab86 2683 let mut cur_id = self.to_state_id(self.state_len() - 1);
487cf647
FG
2684 // This is guaranteed to exist since cnormal > 0.
2685 let mut next_norm_id =
2686 self.tt.next_state_id(self.special.max_start);
2687 while cur_id >= next_norm_id {
2688 if let Some(accel) = accels.remove(&cur_id) {
2689 remapper.swap(self, next_start_id, cur_id);
2690 remapper.swap(self, next_norm_id, cur_id);
2691 // Keep our accelerator map updated with new IDs if the
2692 // states we swapped were also accelerated.
2693 if let Some(accel2) = accels.remove(&next_norm_id) {
2694 accels.insert(cur_id, accel2);
2695 }
2696 if let Some(accel2) = accels.remove(&next_start_id) {
2697 accels.insert(next_norm_id, accel2);
2698 }
2699 accels.insert(next_start_id, accel);
2700 update_special_accel(&mut self.special, next_start_id);
2701 // Our start range shifts one to the right now.
2702 self.special.min_start =
2703 self.tt.next_state_id(self.special.min_start);
2704 self.special.max_start =
2705 self.tt.next_state_id(self.special.max_start);
2706 next_start_id = self.tt.next_state_id(next_start_id);
2707 next_norm_id = self.tt.next_state_id(next_norm_id);
2708 }
2709 // This is pretty tricky, but if our 'next_norm_id' state also
2710 // happened to be accelerated, then the result is that it is
2711 // now in the position of cur_id, so we need to consider it
2712 // again. This loop is still guaranteed to terminate though,
2713 // because when accels contains cur_id, we're guaranteed to
2714 // increment next_norm_id even if cur_id remains unchanged.
2715 if !accels.contains_key(&cur_id) {
2716 cur_id = self.tt.prev_state_id(cur_id);
2717 }
2718 }
2719 }
2720 // Just like we did for match states, but we want to move accelerated
2721 // start states to the beginning of the range instead of the end.
2722 if cstart > 0 {
2723 // N.B. special.{min,max}_start do not need updating, since the
2724 // range/number of start states does not change at this point. Only
2725 // the ordering of start states may change.
2726 let mut next_id = self.special.min_start;
2727 let mut cur_id = next_id;
2728 while cur_id <= self.special.max_start {
2729 if let Some(accel) = accels.remove(&cur_id) {
2730 remapper.swap(self, cur_id, next_id);
2731 accels.insert(next_id, accel);
2732 update_special_accel(&mut self.special, next_id);
2733 next_id = self.tt.next_state_id(next_id);
2734 }
2735 cur_id = self.tt.next_state_id(cur_id);
2736 }
2737 }
2738
2739 // Remap all transitions in our DFA and assert some things.
2740 remapper.remap(self);
2741 // This unwrap is OK because acceleration never changes the number of
2742 // match states or patterns in those match states. Since acceleration
2743 // runs after the pattern map has been set at least once, we know that
2744 // our match states cannot error.
2745 self.set_pattern_map(&new_matches).unwrap();
2746 self.special.set_max();
2747 self.special.validate().expect("special state ranges should validate");
2748 self.special
781aab86 2749 .validate_state_len(self.state_len(), self.stride2())
487cf647 2750 .expect(
781aab86 2751 "special state ranges should be consistent with state length",
487cf647
FG
2752 );
2753 assert_eq!(
2754 self.special.accel_len(self.stride()),
2755 // We record the number of accelerated states initially detected
2756 // since the accels map is itself mutated in the process above.
2757 // If mutated incorrectly, its size may change, and thus can't be
2758 // trusted as a source of truth of how many accelerated states we
2759 // expected there to be.
2760 original_accels_len,
2761 "mismatch with expected number of accelerated states",
2762 );
2763
2764 // And finally record our accelerators. We kept our accels map updated
2765 // as we shuffled states above, so the accelerators should now
2766 // correspond to a contiguous range in the state ID space. (Which we
2767 // assert.)
2768 let mut prev: Option<StateID> = None;
2769 for (id, accel) in accels {
2770 assert!(prev.map_or(true, |p| self.tt.next_state_id(p) == id));
2771 prev = Some(id);
2772 self.accels.add(accel);
2773 }
2774 }
2775
2776 /// Shuffle the states in this DFA so that starting states, match
2777 /// states and accelerated states are all contiguous.
2778 ///
2779 /// See dfa/special.rs for more details.
2780 pub(crate) fn shuffle(
2781 &mut self,
2782 mut matches: BTreeMap<StateID, Vec<PatternID>>,
781aab86 2783 ) -> Result<(), BuildError> {
487cf647 2784 // The determinizer always adds a quit state and it is always second.
781aab86 2785 self.special.quit_id = self.to_state_id(1);
487cf647
FG
2786 // If all we have are the dead and quit states, then we're done and
2787 // the DFA will never produce a match.
781aab86 2788 if self.state_len() <= 2 {
487cf647
FG
2789 self.special.set_max();
2790 return Ok(());
2791 }
2792
781aab86
FG
2793 // Collect all our non-DEAD start states into a convenient set and
2794 // confirm there is no overlap with match states. In the classicl DFA
2795 // construction, start states can be match states. But because of
2796 // look-around, we delay all matches by a byte, which prevents start
2797 // states from being match states.
487cf647
FG
2798 let mut is_start: BTreeSet<StateID> = BTreeSet::new();
2799 for (start_id, _, _) in self.starts() {
781aab86
FG
2800 // If a starting configuration points to a DEAD state, then we
2801 // don't want to shuffle it. The DEAD state is always the first
2802 // state with ID=0. So we can just leave it be.
2803 if start_id == DEAD {
2804 continue;
2805 }
487cf647
FG
2806 assert!(
2807 !matches.contains_key(&start_id),
2808 "{:?} is both a start and a match state, which is not allowed",
2809 start_id,
2810 );
2811 is_start.insert(start_id);
2812 }
2813
2814 // We implement shuffling by a sequence of pairwise swaps of states.
2815 // Since we have a number of things referencing states via their
2816 // IDs and swapping them changes their IDs, we need to record every
2817 // swap we make so that we can remap IDs. The remapper handles this
2818 // book-keeping for us.
781aab86 2819 let mut remapper = Remapper::new(self);
487cf647
FG
2820
2821 // Shuffle matching states.
2822 if matches.is_empty() {
2823 self.special.min_match = DEAD;
2824 self.special.max_match = DEAD;
2825 } else {
2826 // The determinizer guarantees that the first two states are the
2827 // dead and quit states, respectively. We want our match states to
2828 // come right after quit.
781aab86 2829 let mut next_id = self.to_state_id(2);
487cf647
FG
2830 let mut new_matches = BTreeMap::new();
2831 self.special.min_match = next_id;
2832 for (id, pids) in matches {
2833 remapper.swap(self, next_id, id);
2834 new_matches.insert(next_id, pids);
2835 // If we swapped a start state, then update our set.
2836 if is_start.contains(&next_id) {
2837 is_start.remove(&next_id);
2838 is_start.insert(id);
2839 }
2840 next_id = self.tt.next_state_id(next_id);
2841 }
2842 matches = new_matches;
2843 self.special.max_match = cmp::max(
2844 self.special.min_match,
2845 self.tt.prev_state_id(next_id),
2846 );
2847 }
2848
2849 // Shuffle starting states.
2850 {
781aab86 2851 let mut next_id = self.to_state_id(2);
487cf647
FG
2852 if self.special.matches() {
2853 next_id = self.tt.next_state_id(self.special.max_match);
2854 }
2855 self.special.min_start = next_id;
2856 for id in is_start {
2857 remapper.swap(self, next_id, id);
2858 next_id = self.tt.next_state_id(next_id);
2859 }
2860 self.special.max_start = cmp::max(
2861 self.special.min_start,
2862 self.tt.prev_state_id(next_id),
2863 );
2864 }
2865
2866 // Finally remap all transitions in our DFA.
2867 remapper.remap(self);
2868 self.set_pattern_map(&matches)?;
2869 self.special.set_max();
2870 self.special.validate().expect("special state ranges should validate");
2871 self.special
781aab86 2872 .validate_state_len(self.state_len(), self.stride2())
487cf647 2873 .expect(
781aab86 2874 "special state ranges should be consistent with state length",
487cf647
FG
2875 );
2876 Ok(())
2877 }
487cf647 2878
781aab86
FG
2879 /// Checks whether there are universal start states (both anchored and
2880 /// unanchored), and if so, sets the relevant fields to the start state
2881 /// IDs.
2882 ///
2883 /// Universal start states occur precisely when the all patterns in the
2884 /// DFA have no look-around assertions in their prefix.
2885 fn set_universal_starts(&mut self) {
2886 assert_eq!(6, Start::len(), "expected 6 start configurations");
2887
2888 let start_id = |dfa: &mut OwnedDFA, inp: &Input<'_>, start: Start| {
2889 // This OK because we only call 'start' under conditions
2890 // in which we know it will succeed.
2891 dfa.st.start(inp, start).expect("valid Input configuration")
2892 };
2893 if self.start_kind().has_unanchored() {
2894 let inp = Input::new("").anchored(Anchored::No);
2895 let sid = start_id(self, &inp, Start::NonWordByte);
2896 if sid == start_id(self, &inp, Start::WordByte)
2897 && sid == start_id(self, &inp, Start::Text)
2898 && sid == start_id(self, &inp, Start::LineLF)
2899 && sid == start_id(self, &inp, Start::LineCR)
2900 && sid == start_id(self, &inp, Start::CustomLineTerminator)
2901 {
2902 self.st.universal_start_unanchored = Some(sid);
2903 }
2904 }
2905 if self.start_kind().has_anchored() {
2906 let inp = Input::new("").anchored(Anchored::Yes);
2907 let sid = start_id(self, &inp, Start::NonWordByte);
2908 if sid == start_id(self, &inp, Start::WordByte)
2909 && sid == start_id(self, &inp, Start::Text)
2910 && sid == start_id(self, &inp, Start::LineLF)
2911 && sid == start_id(self, &inp, Start::LineCR)
2912 && sid == start_id(self, &inp, Start::CustomLineTerminator)
2913 {
2914 self.st.universal_start_anchored = Some(sid);
2915 }
2916 }
487cf647 2917 }
781aab86 2918}
487cf647 2919
781aab86
FG
2920// A variety of generic internal methods for accessing DFA internals.
2921impl<T: AsRef<[u32]>> DFA<T> {
487cf647
FG
2922 /// Return the info about special states.
2923 pub(crate) fn special(&self) -> &Special {
2924 &self.special
2925 }
2926
2927 /// Return the info about special states as a mutable borrow.
781aab86 2928 #[cfg(feature = "dfa-build")]
487cf647
FG
2929 pub(crate) fn special_mut(&mut self) -> &mut Special {
2930 &mut self.special
2931 }
2932
781aab86
FG
2933 /// Returns the quit set (may be empty) used by this DFA.
2934 pub(crate) fn quitset(&self) -> &ByteSet {
2935 &self.quitset
2936 }
2937
2938 /// Returns the flags for this DFA.
2939 pub(crate) fn flags(&self) -> &Flags {
2940 &self.flags
2941 }
2942
487cf647
FG
2943 /// Returns an iterator over all states in this DFA.
2944 ///
2945 /// This iterator yields a tuple for each state. The first element of the
2946 /// tuple corresponds to a state's identifier, and the second element
2947 /// corresponds to the state itself (comprised of its transitions).
2948 pub(crate) fn states(&self) -> StateIter<'_, T> {
2949 self.tt.states()
2950 }
2951
2952 /// Return the total number of states in this DFA. Every DFA has at least
2953 /// 1 state, even the empty DFA.
781aab86
FG
2954 pub(crate) fn state_len(&self) -> usize {
2955 self.tt.len()
487cf647
FG
2956 }
2957
2958 /// Return an iterator over all pattern IDs for the given match state.
2959 ///
2960 /// If the given state is not a match state, then this panics.
781aab86 2961 #[cfg(feature = "dfa-build")]
487cf647
FG
2962 pub(crate) fn pattern_id_slice(&self, id: StateID) -> &[PatternID] {
2963 assert!(self.is_match_state(id));
2964 self.ms.pattern_id_slice(self.match_state_index(id))
2965 }
2966
2967 /// Return the total number of pattern IDs for the given match state.
2968 ///
2969 /// If the given state is not a match state, then this panics.
2970 pub(crate) fn match_pattern_len(&self, id: StateID) -> usize {
2971 assert!(self.is_match_state(id));
2972 self.ms.pattern_len(self.match_state_index(id))
2973 }
2974
2975 /// Returns the total number of patterns matched by this DFA.
781aab86
FG
2976 pub(crate) fn pattern_len(&self) -> usize {
2977 self.ms.pattern_len
487cf647
FG
2978 }
2979
2980 /// Returns a map from match state ID to a list of pattern IDs that match
2981 /// in that state.
781aab86 2982 #[cfg(feature = "dfa-build")]
487cf647
FG
2983 pub(crate) fn pattern_map(&self) -> BTreeMap<StateID, Vec<PatternID>> {
2984 self.ms.to_map(self)
2985 }
2986
2987 /// Returns the ID of the quit state for this DFA.
781aab86 2988 #[cfg(feature = "dfa-build")]
487cf647 2989 pub(crate) fn quit_id(&self) -> StateID {
781aab86 2990 self.to_state_id(1)
487cf647
FG
2991 }
2992
2993 /// Convert the given state identifier to the state's index. The state's
2994 /// index corresponds to the position in which it appears in the transition
2995 /// table. When a DFA is NOT premultiplied, then a state's identifier is
2996 /// also its index. When a DFA is premultiplied, then a state's identifier
2997 /// is equal to `index * alphabet_len`. This routine reverses that.
2998 pub(crate) fn to_index(&self, id: StateID) -> usize {
2999 self.tt.to_index(id)
3000 }
3001
781aab86 3002 /// Convert an index to a state (in the range 0..self.state_len()) to an
487cf647
FG
3003 /// actual state identifier.
3004 ///
3005 /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3006 /// to some other information (such as a remapped state ID).
781aab86
FG
3007 #[cfg(feature = "dfa-build")]
3008 pub(crate) fn to_state_id(&self, index: usize) -> StateID {
3009 self.tt.to_state_id(index)
487cf647
FG
3010 }
3011
3012 /// Return the table of state IDs for this DFA's start states.
3013 pub(crate) fn starts(&self) -> StartStateIter<'_> {
3014 self.st.iter()
3015 }
3016
3017 /// Returns the index of the match state for the given ID. If the
3018 /// given ID does not correspond to a match state, then this may
3019 /// panic or produce an incorrect result.
781aab86 3020 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3021 fn match_state_index(&self, id: StateID) -> usize {
3022 debug_assert!(self.is_match_state(id));
3023 // This is one of the places where we rely on the fact that match
3024 // states are contiguous in the transition table. Namely, that the
781aab86 3025 // first match state ID always corresponds to dfa.special.min_match.
487cf647
FG
3026 // From there, since we know the stride, we can compute the overall
3027 // index of any match state given the match state's ID.
3028 let min = self.special().min_match.as_usize();
3029 // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3030 // so both the subtraction and the unchecked StateID construction is
3031 // OK.
3032 self.to_index(StateID::new_unchecked(id.as_usize() - min))
3033 }
3034
3035 /// Returns the index of the accelerator state for the given ID. If the
3036 /// given ID does not correspond to an accelerator state, then this may
3037 /// panic or produce an incorrect result.
3038 fn accelerator_index(&self, id: StateID) -> usize {
3039 let min = self.special().min_accel.as_usize();
3040 // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3041 // so both the subtraction and the unchecked StateID construction is
3042 // OK.
3043 self.to_index(StateID::new_unchecked(id.as_usize() - min))
3044 }
3045
3046 /// Return the accelerators for this DFA.
3047 fn accels(&self) -> Accels<&[u32]> {
3048 self.accels.as_ref()
3049 }
3050
3051 /// Return this DFA's transition table as a slice.
3052 fn trans(&self) -> &[StateID] {
3053 self.tt.table()
3054 }
3055}
3056
3057impl<T: AsRef<[u32]>> fmt::Debug for DFA<T> {
3058 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3059 writeln!(f, "dense::DFA(")?;
3060 for state in self.states() {
3061 fmt_state_indicator(f, self, state.id())?;
3062 let id = if f.alternate() {
3063 state.id().as_usize()
3064 } else {
3065 self.to_index(state.id())
3066 };
3067 write!(f, "{:06?}: ", id)?;
3068 state.fmt(f)?;
3069 write!(f, "\n")?;
3070 }
3071 writeln!(f, "")?;
781aab86 3072 for (i, (start_id, anchored, sty)) in self.starts().enumerate() {
487cf647
FG
3073 let id = if f.alternate() {
3074 start_id.as_usize()
3075 } else {
3076 self.to_index(start_id)
3077 };
3078 if i % self.st.stride == 0 {
781aab86
FG
3079 match anchored {
3080 Anchored::No => writeln!(f, "START-GROUP(unanchored)")?,
3081 Anchored::Yes => writeln!(f, "START-GROUP(anchored)")?,
3082 Anchored::Pattern(pid) => {
487cf647
FG
3083 writeln!(f, "START_GROUP(pattern: {:?})", pid)?
3084 }
3085 }
3086 }
3087 writeln!(f, " {:?} => {:06?}", sty, id)?;
3088 }
781aab86 3089 if self.pattern_len() > 1 {
487cf647 3090 writeln!(f, "")?;
781aab86 3091 for i in 0..self.ms.len() {
487cf647
FG
3092 let id = self.ms.match_state_id(self, i);
3093 let id = if f.alternate() {
3094 id.as_usize()
3095 } else {
3096 self.to_index(id)
3097 };
3098 write!(f, "MATCH({:06?}): ", id)?;
3099 for (i, &pid) in self.ms.pattern_id_slice(i).iter().enumerate()
3100 {
3101 if i > 0 {
3102 write!(f, ", ")?;
3103 }
3104 write!(f, "{:?}", pid)?;
3105 }
3106 writeln!(f, "")?;
3107 }
3108 }
781aab86
FG
3109 writeln!(f, "state length: {:?}", self.state_len())?;
3110 writeln!(f, "pattern length: {:?}", self.pattern_len())?;
3111 writeln!(f, "flags: {:?}", self.flags)?;
487cf647
FG
3112 writeln!(f, ")")?;
3113 Ok(())
3114 }
3115}
3116
781aab86 3117// SAFETY: We assert that our implementation of each method is correct.
487cf647 3118unsafe impl<T: AsRef<[u32]>> Automaton for DFA<T> {
781aab86 3119 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3120 fn is_special_state(&self, id: StateID) -> bool {
3121 self.special.is_special_state(id)
3122 }
3123
781aab86 3124 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3125 fn is_dead_state(&self, id: StateID) -> bool {
3126 self.special.is_dead_state(id)
3127 }
3128
781aab86 3129 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3130 fn is_quit_state(&self, id: StateID) -> bool {
3131 self.special.is_quit_state(id)
3132 }
3133
781aab86 3134 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3135 fn is_match_state(&self, id: StateID) -> bool {
3136 self.special.is_match_state(id)
3137 }
3138
781aab86 3139 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3140 fn is_start_state(&self, id: StateID) -> bool {
3141 self.special.is_start_state(id)
3142 }
3143
781aab86 3144 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3145 fn is_accel_state(&self, id: StateID) -> bool {
3146 self.special.is_accel_state(id)
3147 }
3148
781aab86 3149 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3150 fn next_state(&self, current: StateID, input: u8) -> StateID {
3151 let input = self.byte_classes().get(input);
3152 let o = current.as_usize() + usize::from(input);
3153 self.trans()[o]
3154 }
3155
781aab86 3156 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3157 unsafe fn next_state_unchecked(
3158 &self,
3159 current: StateID,
781aab86 3160 byte: u8,
487cf647 3161 ) -> StateID {
781aab86
FG
3162 // We don't (or shouldn't) need an unchecked variant for the byte
3163 // class mapping, since bound checks should be omitted automatically
3164 // by virtue of its representation. If this ends up not being true as
3165 // confirmed by codegen, please file an issue. ---AG
3166 let class = self.byte_classes().get(byte);
3167 let o = current.as_usize() + usize::from(class);
3168 let next = *self.trans().get_unchecked(o);
3169 next
487cf647
FG
3170 }
3171
781aab86 3172 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3173 fn next_eoi_state(&self, current: StateID) -> StateID {
3174 let eoi = self.byte_classes().eoi().as_usize();
3175 let o = current.as_usize() + eoi;
3176 self.trans()[o]
3177 }
3178
781aab86
FG
3179 #[cfg_attr(feature = "perf-inline", inline(always))]
3180 fn pattern_len(&self) -> usize {
3181 self.ms.pattern_len
487cf647
FG
3182 }
3183
781aab86
FG
3184 #[cfg_attr(feature = "perf-inline", inline(always))]
3185 fn match_len(&self, id: StateID) -> usize {
487cf647
FG
3186 self.match_pattern_len(id)
3187 }
3188
781aab86 3189 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3190 fn match_pattern(&self, id: StateID, match_index: usize) -> PatternID {
3191 // This is an optimization for the very common case of a DFA with a
3192 // single pattern. This conditional avoids a somewhat more costly path
3193 // that finds the pattern ID from the state machine, which requires
3194 // a bit of slicing/pointer-chasing. This optimization tends to only
3195 // matter when matches are frequent.
781aab86 3196 if self.ms.pattern_len == 1 {
487cf647
FG
3197 return PatternID::ZERO;
3198 }
3199 let state_index = self.match_state_index(id);
3200 self.ms.pattern_id(state_index, match_index)
3201 }
3202
781aab86
FG
3203 #[cfg_attr(feature = "perf-inline", inline(always))]
3204 fn has_empty(&self) -> bool {
3205 self.flags.has_empty
3206 }
3207
3208 #[cfg_attr(feature = "perf-inline", inline(always))]
3209 fn is_utf8(&self) -> bool {
3210 self.flags.is_utf8
3211 }
3212
3213 #[cfg_attr(feature = "perf-inline", inline(always))]
3214 fn is_always_start_anchored(&self) -> bool {
3215 self.flags.is_always_start_anchored
3216 }
3217
3218 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3219 fn start_state_forward(
3220 &self,
781aab86
FG
3221 input: &Input<'_>,
3222 ) -> Result<StateID, MatchError> {
3223 if !self.quitset.is_empty() && input.start() > 0 {
3224 let offset = input.start() - 1;
3225 let byte = input.haystack()[offset];
3226 if self.quitset.contains(byte) {
3227 return Err(MatchError::quit(byte, offset));
3228 }
3229 }
3230 let start = self.st.start_map.fwd(&input);
3231 self.st.start(input, start)
487cf647
FG
3232 }
3233
781aab86 3234 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3235 fn start_state_reverse(
3236 &self,
781aab86
FG
3237 input: &Input<'_>,
3238 ) -> Result<StateID, MatchError> {
3239 if !self.quitset.is_empty() && input.end() < input.haystack().len() {
3240 let offset = input.end();
3241 let byte = input.haystack()[offset];
3242 if self.quitset.contains(byte) {
3243 return Err(MatchError::quit(byte, offset));
3244 }
3245 }
3246 let start = self.st.start_map.rev(&input);
3247 self.st.start(input, start)
487cf647
FG
3248 }
3249
781aab86
FG
3250 #[cfg_attr(feature = "perf-inline", inline(always))]
3251 fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
3252 match mode {
3253 Anchored::No => self.st.universal_start_unanchored,
3254 Anchored::Yes => self.st.universal_start_anchored,
3255 Anchored::Pattern(_) => None,
3256 }
3257 }
3258
3259 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
3260 fn accelerator(&self, id: StateID) -> &[u8] {
3261 if !self.is_accel_state(id) {
3262 return &[];
3263 }
3264 self.accels.needles(self.accelerator_index(id))
3265 }
781aab86
FG
3266
3267 #[cfg_attr(feature = "perf-inline", inline(always))]
3268 fn get_prefilter(&self) -> Option<&Prefilter> {
3269 self.pre.as_ref()
3270 }
487cf647
FG
3271}
3272
3273/// The transition table portion of a dense DFA.
3274///
3275/// The transition table is the core part of the DFA in that it describes how
3276/// to move from one state to another based on the input sequence observed.
3277#[derive(Clone)]
3278pub(crate) struct TransitionTable<T> {
3279 /// A contiguous region of memory representing the transition table in
3280 /// row-major order. The representation is dense. That is, every state
3281 /// has precisely the same number of transitions. The maximum number of
3282 /// transitions per state is 257 (256 for each possible byte value, plus 1
3283 /// for the special EOI transition). If a DFA has been instructed to use
3284 /// byte classes (the default), then the number of transitions is usually
3285 /// substantially fewer.
3286 ///
3287 /// In practice, T is either `Vec<u32>` or `&[u32]`.
3288 table: T,
3289 /// A set of equivalence classes, where a single equivalence class
3290 /// represents a set of bytes that never discriminate between a match
3291 /// and a non-match in the DFA. Each equivalence class corresponds to a
3292 /// single character in this DFA's alphabet, where the maximum number of
3293 /// characters is 257 (each possible value of a byte plus the special
3294 /// EOI transition). Consequently, the number of equivalence classes
3295 /// corresponds to the number of transitions for each DFA state. Note
3296 /// though that the *space* used by each DFA state in the transition table
3297 /// may be larger. The total space used by each DFA state is known as the
3298 /// stride.
3299 ///
3300 /// The only time the number of equivalence classes is fewer than 257 is if
3301 /// the DFA's kind uses byte classes (which is the default). Equivalence
3302 /// classes should generally only be disabled when debugging, so that
3303 /// the transitions themselves aren't obscured. Disabling them has no
3304 /// other benefit, since the equivalence class map is always used while
3305 /// searching. In the vast majority of cases, the number of equivalence
3306 /// classes is substantially smaller than 257, particularly when large
3307 /// Unicode classes aren't used.
3308 classes: ByteClasses,
3309 /// The stride of each DFA state, expressed as a power-of-two exponent.
3310 ///
3311 /// The stride of a DFA corresponds to the total amount of space used by
3312 /// each DFA state in the transition table. This may be bigger than the
3313 /// size of a DFA's alphabet, since the stride is always the smallest
3314 /// power of two greater than or equal to the alphabet size.
3315 ///
3316 /// While this wastes space, this avoids the need for integer division
3317 /// to convert between premultiplied state IDs and their corresponding
3318 /// indices. Instead, we can use simple bit-shifts.
3319 ///
3320 /// See the docs for the `stride2` method for more details.
3321 ///
3322 /// The minimum `stride2` value is `1` (corresponding to a stride of `2`)
3323 /// while the maximum `stride2` value is `9` (corresponding to a stride of
3324 /// `512`). The maximum is not `8` since the maximum alphabet size is `257`
3325 /// when accounting for the special EOI transition. However, an alphabet
3326 /// length of that size is exceptionally rare since the alphabet is shrunk
3327 /// into equivalence classes.
3328 stride2: usize,
3329}
3330
3331impl<'a> TransitionTable<&'a [u32]> {
3332 /// Deserialize a transition table starting at the beginning of `slice`.
3333 /// Upon success, return the total number of bytes read along with the
3334 /// transition table.
3335 ///
3336 /// If there was a problem deserializing any part of the transition table,
3337 /// then this returns an error. Notably, if the given slice does not have
3338 /// the same alignment as `StateID`, then this will return an error (among
3339 /// other possible errors).
3340 ///
3341 /// This is guaranteed to execute in constant time.
3342 ///
3343 /// # Safety
3344 ///
781aab86 3345 /// This routine is not safe because it does not check the validity of the
487cf647
FG
3346 /// transition table itself. In particular, the transition table can be
3347 /// quite large, so checking its validity can be somewhat expensive. An
3348 /// invalid transition table is not safe because other code may rely on the
3349 /// transition table being correct (such as explicit bounds check elision).
3350 /// Therefore, an invalid transition table can lead to undefined behavior.
3351 ///
3352 /// Callers that use this function must either pass on the safety invariant
3353 /// or guarantee that the bytes given contain a valid transition table.
3354 /// This guarantee is upheld by the bytes written by `write_to`.
3355 unsafe fn from_bytes_unchecked(
3356 mut slice: &'a [u8],
3357 ) -> Result<(TransitionTable<&'a [u32]>, usize), DeserializeError> {
781aab86 3358 let slice_start = slice.as_ptr().as_usize();
487cf647 3359
781aab86
FG
3360 let (state_len, nr) =
3361 wire::try_read_u32_as_usize(slice, "state length")?;
487cf647
FG
3362 slice = &slice[nr..];
3363
781aab86 3364 let (stride2, nr) = wire::try_read_u32_as_usize(slice, "stride2")?;
487cf647
FG
3365 slice = &slice[nr..];
3366
3367 let (classes, nr) = ByteClasses::from_bytes(slice)?;
3368 slice = &slice[nr..];
3369
3370 // The alphabet length (determined by the byte class map) cannot be
3371 // bigger than the stride (total space used by each DFA state).
3372 if stride2 > 9 {
3373 return Err(DeserializeError::generic(
3374 "dense DFA has invalid stride2 (too big)",
3375 ));
3376 }
3377 // It also cannot be zero, since even a DFA that never matches anything
3378 // has a non-zero number of states with at least two equivalence
3379 // classes: one for all 256 byte values and another for the EOI
3380 // sentinel.
3381 if stride2 < 1 {
3382 return Err(DeserializeError::generic(
3383 "dense DFA has invalid stride2 (too small)",
3384 ));
3385 }
3386 // This is OK since 1 <= stride2 <= 9.
3387 let stride =
3388 1usize.checked_shl(u32::try_from(stride2).unwrap()).unwrap();
3389 if classes.alphabet_len() > stride {
3390 return Err(DeserializeError::generic(
3391 "alphabet size cannot be bigger than transition table stride",
3392 ));
3393 }
3394
781aab86
FG
3395 let trans_len =
3396 wire::shl(state_len, stride2, "dense table transition length")?;
3397 let table_bytes_len = wire::mul(
3398 trans_len,
487cf647 3399 StateID::SIZE,
781aab86 3400 "dense table state byte length",
487cf647 3401 )?;
781aab86
FG
3402 wire::check_slice_len(slice, table_bytes_len, "transition table")?;
3403 wire::check_alignment::<StateID>(slice)?;
487cf647
FG
3404 let table_bytes = &slice[..table_bytes_len];
3405 slice = &slice[table_bytes_len..];
3406 // SAFETY: Since StateID is always representable as a u32, all we need
3407 // to do is ensure that we have the proper length and alignment. We've
3408 // checked both above, so the cast below is safe.
3409 //
781aab86
FG
3410 // N.B. This is the only not-safe code in this function.
3411 let table = core::slice::from_raw_parts(
3412 table_bytes.as_ptr().cast::<u32>(),
3413 trans_len,
3414 );
487cf647 3415 let tt = TransitionTable { table, classes, stride2 };
781aab86 3416 Ok((tt, slice.as_ptr().as_usize() - slice_start))
487cf647
FG
3417 }
3418}
3419
781aab86 3420#[cfg(feature = "dfa-build")]
487cf647
FG
3421impl TransitionTable<Vec<u32>> {
3422 /// Create a minimal transition table with just two states: a dead state
3423 /// and a quit state. The alphabet length and stride of the transition
3424 /// table is determined by the given set of equivalence classes.
3425 fn minimal(classes: ByteClasses) -> TransitionTable<Vec<u32>> {
3426 let mut tt = TransitionTable {
3427 table: vec![],
3428 classes,
3429 stride2: classes.stride2(),
3430 };
3431 // Two states, regardless of alphabet size, can always fit into u32.
3432 tt.add_empty_state().unwrap(); // dead state
3433 tt.add_empty_state().unwrap(); // quit state
3434 tt
3435 }
3436
3437 /// Set a transition in this table. Both the `from` and `to` states must
3438 /// already exist, otherwise this panics. `unit` should correspond to the
3439 /// transition out of `from` to set to `to`.
3440 fn set(&mut self, from: StateID, unit: alphabet::Unit, to: StateID) {
3441 assert!(self.is_valid(from), "invalid 'from' state");
3442 assert!(self.is_valid(to), "invalid 'to' state");
3443 self.table[from.as_usize() + self.classes.get_by_unit(unit)] =
3444 to.as_u32();
3445 }
3446
3447 /// Add an empty state (a state where all transitions lead to a dead state)
3448 /// and return its identifier. The identifier returned is guaranteed to
3449 /// not point to any other existing state.
3450 ///
3451 /// If adding a state would exhaust the state identifier space, then this
3452 /// returns an error.
781aab86 3453 fn add_empty_state(&mut self) -> Result<StateID, BuildError> {
487cf647
FG
3454 // Normally, to get a fresh state identifier, we would just
3455 // take the index of the next state added to the transition
3456 // table. However, we actually perform an optimization here
3457 // that premultiplies state IDs by the stride, such that they
3458 // point immediately at the beginning of their transitions in
3459 // the transition table. This avoids an extra multiplication
3460 // instruction for state lookup at search time.
3461 //
3462 // Premultiplied identifiers means that instead of your matching
3463 // loop looking something like this:
3464 //
3465 // state = dfa.start
3466 // for byte in haystack:
3467 // next = dfa.transitions[state * stride + byte]
3468 // if dfa.is_match(next):
3469 // return true
3470 // return false
3471 //
3472 // it can instead look like this:
3473 //
3474 // state = dfa.start
3475 // for byte in haystack:
3476 // next = dfa.transitions[state + byte]
3477 // if dfa.is_match(next):
3478 // return true
3479 // return false
3480 //
3481 // In other words, we save a multiplication instruction in the
3482 // critical path. This turns out to be a decent performance win.
3483 // The cost of using premultiplied state ids is that they can
3484 // require a bigger state id representation. (And they also make
3485 // the code a bit more complex, especially during minimization and
3486 // when reshuffling states, as one needs to convert back and forth
3487 // between state IDs and state indices.)
3488 //
3489 // To do this, we simply take the index of the state into the
3490 // entire transition table, rather than the index of the state
3491 // itself. e.g., If the stride is 64, then the ID of the 3rd state
3492 // is 192, not 2.
3493 let next = self.table.len();
781aab86
FG
3494 let id =
3495 StateID::new(next).map_err(|_| BuildError::too_many_states())?;
487cf647
FG
3496 self.table.extend(iter::repeat(0).take(self.stride()));
3497 Ok(id)
3498 }
3499
3500 /// Swap the two states given in this transition table.
3501 ///
3502 /// This routine does not do anything to check the correctness of this
3503 /// swap. Callers must ensure that other states pointing to id1 and id2 are
3504 /// updated appropriately.
3505 ///
3506 /// Both id1 and id2 must point to valid states, otherwise this panics.
3507 fn swap(&mut self, id1: StateID, id2: StateID) {
3508 assert!(self.is_valid(id1), "invalid 'id1' state: {:?}", id1);
3509 assert!(self.is_valid(id2), "invalid 'id2' state: {:?}", id2);
3510 // We only need to swap the parts of the state that are used. So if the
3511 // stride is 64, but the alphabet length is only 33, then we save a lot
3512 // of work.
3513 for b in 0..self.classes.alphabet_len() {
3514 self.table.swap(id1.as_usize() + b, id2.as_usize() + b);
3515 }
3516 }
3517
781aab86
FG
3518 /// Remap the transitions for the state given according to the function
3519 /// given. This applies the given map function to every transition in the
3520 /// given state and changes the transition in place to the result of the
3521 /// map function for that transition.
3522 fn remap(&mut self, id: StateID, map: impl Fn(StateID) -> StateID) {
3523 for byte in 0..self.alphabet_len() {
3524 let i = id.as_usize() + byte;
3525 let next = self.table()[i];
3526 self.table_mut()[id.as_usize() + byte] = map(next);
3527 }
3528 }
3529
3530 /// Truncate the states in this transition table to the given length.
487cf647
FG
3531 ///
3532 /// This routine does not do anything to check the correctness of this
3533 /// truncation. Callers must ensure that other states pointing to truncated
3534 /// states are updated appropriately.
781aab86
FG
3535 fn truncate(&mut self, len: usize) {
3536 self.table.truncate(len << self.stride2);
487cf647
FG
3537 }
3538}
3539
3540impl<T: AsRef<[u32]>> TransitionTable<T> {
3541 /// Writes a serialized form of this transition table to the buffer given.
3542 /// If the buffer is too small, then an error is returned. To determine
3543 /// how big the buffer must be, use `write_to_len`.
3544 fn write_to<E: Endian>(
3545 &self,
3546 mut dst: &mut [u8],
3547 ) -> Result<usize, SerializeError> {
3548 let nwrite = self.write_to_len();
3549 if dst.len() < nwrite {
3550 return Err(SerializeError::buffer_too_small("transition table"));
3551 }
3552 dst = &mut dst[..nwrite];
3553
781aab86 3554 // write state length
487cf647 3555 // Unwrap is OK since number of states is guaranteed to fit in a u32.
781aab86 3556 E::write_u32(u32::try_from(self.len()).unwrap(), dst);
487cf647
FG
3557 dst = &mut dst[size_of::<u32>()..];
3558
3559 // write state stride (as power of 2)
3560 // Unwrap is OK since stride2 is guaranteed to be <= 9.
3561 E::write_u32(u32::try_from(self.stride2).unwrap(), dst);
3562 dst = &mut dst[size_of::<u32>()..];
3563
3564 // write byte class map
3565 let n = self.classes.write_to(dst)?;
3566 dst = &mut dst[n..];
3567
3568 // write actual transitions
3569 for &sid in self.table() {
781aab86 3570 let n = wire::write_state_id::<E>(sid, &mut dst);
487cf647
FG
3571 dst = &mut dst[n..];
3572 }
3573 Ok(nwrite)
3574 }
3575
3576 /// Returns the number of bytes the serialized form of this transition
3577 /// table will use.
3578 fn write_to_len(&self) -> usize {
781aab86 3579 size_of::<u32>() // state length
487cf647
FG
3580 + size_of::<u32>() // stride2
3581 + self.classes.write_to_len()
3582 + (self.table().len() * StateID::SIZE)
3583 }
3584
3585 /// Validates that every state ID in this transition table is valid.
3586 ///
3587 /// That is, every state ID can be used to correctly index a state in this
3588 /// table.
781aab86 3589 fn validate(&self, sp: &Special) -> Result<(), DeserializeError> {
487cf647 3590 for state in self.states() {
781aab86
FG
3591 // We check that the ID itself is well formed. That is, if it's
3592 // a special state then it must actually be a quit, dead, accel,
3593 // match or start state.
3594 if sp.is_special_state(state.id()) {
3595 let is_actually_special = sp.is_dead_state(state.id())
3596 || sp.is_quit_state(state.id())
3597 || sp.is_match_state(state.id())
3598 || sp.is_start_state(state.id())
3599 || sp.is_accel_state(state.id());
3600 if !is_actually_special {
3601 // This is kind of a cryptic error message...
3602 return Err(DeserializeError::generic(
3603 "found dense state tagged as special but \
3604 wasn't actually special",
3605 ));
3606 }
3607 }
487cf647
FG
3608 for (_, to) in state.transitions() {
3609 if !self.is_valid(to) {
3610 return Err(DeserializeError::generic(
3611 "found invalid state ID in transition table",
3612 ));
3613 }
3614 }
3615 }
3616 Ok(())
3617 }
3618
3619 /// Converts this transition table to a borrowed value.
3620 fn as_ref(&self) -> TransitionTable<&'_ [u32]> {
3621 TransitionTable {
3622 table: self.table.as_ref(),
3623 classes: self.classes.clone(),
3624 stride2: self.stride2,
3625 }
3626 }
3627
3628 /// Converts this transition table to an owned value.
3629 #[cfg(feature = "alloc")]
781aab86 3630 fn to_owned(&self) -> TransitionTable<alloc::vec::Vec<u32>> {
487cf647
FG
3631 TransitionTable {
3632 table: self.table.as_ref().to_vec(),
3633 classes: self.classes.clone(),
3634 stride2: self.stride2,
3635 }
3636 }
3637
3638 /// Return the state for the given ID. If the given ID is not valid, then
3639 /// this panics.
3640 fn state(&self, id: StateID) -> State<'_> {
3641 assert!(self.is_valid(id));
3642
3643 let i = id.as_usize();
3644 State {
3645 id,
3646 stride2: self.stride2,
3647 transitions: &self.table()[i..i + self.alphabet_len()],
3648 }
3649 }
3650
3651 /// Returns an iterator over all states in this transition table.
3652 ///
3653 /// This iterator yields a tuple for each state. The first element of the
3654 /// tuple corresponds to a state's identifier, and the second element
3655 /// corresponds to the state itself (comprised of its transitions).
3656 fn states(&self) -> StateIter<'_, T> {
3657 StateIter {
3658 tt: self,
3659 it: self.table().chunks(self.stride()).enumerate(),
3660 }
3661 }
3662
3663 /// Convert a state identifier to an index to a state (in the range
781aab86 3664 /// 0..self.len()).
487cf647
FG
3665 ///
3666 /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3667 /// to some other information (such as a remapped state ID).
3668 ///
3669 /// If the given ID is not valid, then this may panic or produce an
3670 /// incorrect index.
3671 fn to_index(&self, id: StateID) -> usize {
3672 id.as_usize() >> self.stride2
3673 }
3674
781aab86 3675 /// Convert an index to a state (in the range 0..self.len()) to an actual
487cf647
FG
3676 /// state identifier.
3677 ///
3678 /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3679 /// to some other information (such as a remapped state ID).
3680 ///
3681 /// If the given index is not in the specified range, then this may panic
3682 /// or produce an incorrect state ID.
781aab86 3683 fn to_state_id(&self, index: usize) -> StateID {
487cf647
FG
3684 // CORRECTNESS: If the given index is not valid, then it is not
3685 // required for this to panic or return a valid state ID.
3686 StateID::new_unchecked(index << self.stride2)
3687 }
3688
3689 /// Returns the state ID for the state immediately following the one given.
3690 ///
3691 /// This does not check whether the state ID returned is invalid. In fact,
3692 /// if the state ID given is the last state in this DFA, then the state ID
3693 /// returned is guaranteed to be invalid.
781aab86 3694 #[cfg(feature = "dfa-build")]
487cf647 3695 fn next_state_id(&self, id: StateID) -> StateID {
781aab86 3696 self.to_state_id(self.to_index(id).checked_add(1).unwrap())
487cf647
FG
3697 }
3698
3699 /// Returns the state ID for the state immediately preceding the one given.
3700 ///
3701 /// If the dead ID given (which is zero), then this panics.
781aab86 3702 #[cfg(feature = "dfa-build")]
487cf647 3703 fn prev_state_id(&self, id: StateID) -> StateID {
781aab86 3704 self.to_state_id(self.to_index(id).checked_sub(1).unwrap())
487cf647
FG
3705 }
3706
3707 /// Returns the table as a slice of state IDs.
3708 fn table(&self) -> &[StateID] {
781aab86 3709 wire::u32s_to_state_ids(self.table.as_ref())
487cf647
FG
3710 }
3711
3712 /// Returns the total number of states in this transition table.
3713 ///
3714 /// Note that a DFA always has at least two states: the dead and quit
3715 /// states. In particular, the dead state always has ID 0 and is
3716 /// correspondingly always the first state. The dead state is never a match
3717 /// state.
781aab86 3718 fn len(&self) -> usize {
487cf647
FG
3719 self.table().len() >> self.stride2
3720 }
3721
3722 /// Returns the total stride for every state in this DFA. This corresponds
3723 /// to the total number of transitions used by each state in this DFA's
3724 /// transition table.
3725 fn stride(&self) -> usize {
3726 1 << self.stride2
3727 }
3728
3729 /// Returns the total number of elements in the alphabet for this
3730 /// transition table. This is always less than or equal to `self.stride()`.
3731 /// It is only equal when the alphabet length is a power of 2. Otherwise,
3732 /// it is always strictly less.
3733 fn alphabet_len(&self) -> usize {
3734 self.classes.alphabet_len()
3735 }
3736
3737 /// Returns true if and only if the given state ID is valid for this
3738 /// transition table. Validity in this context means that the given ID can
3739 /// be used as a valid offset with `self.stride()` to index this transition
3740 /// table.
3741 fn is_valid(&self, id: StateID) -> bool {
3742 let id = id.as_usize();
3743 id < self.table().len() && id % self.stride() == 0
3744 }
3745
3746 /// Return the memory usage, in bytes, of this transition table.
3747 ///
3748 /// This does not include the size of a `TransitionTable` value itself.
3749 fn memory_usage(&self) -> usize {
3750 self.table().len() * StateID::SIZE
3751 }
3752}
3753
781aab86 3754#[cfg(feature = "dfa-build")]
487cf647
FG
3755impl<T: AsMut<[u32]>> TransitionTable<T> {
3756 /// Returns the table as a slice of state IDs.
3757 fn table_mut(&mut self) -> &mut [StateID] {
781aab86 3758 wire::u32s_to_state_ids_mut(self.table.as_mut())
487cf647
FG
3759 }
3760}
3761
3762/// The set of all possible starting states in a DFA.
3763///
3764/// The set of starting states corresponds to the possible choices one can make
3765/// in terms of starting a DFA. That is, before following the first transition,
3766/// you first need to select the state that you start in.
3767///
3768/// Normally, a DFA converted from an NFA that has a single starting state
3769/// would itself just have one starting state. However, our support for look
3770/// around generally requires more starting states. The correct starting state
3771/// is chosen based on certain properties of the position at which we begin
3772/// our search.
3773///
3774/// Before listing those properties, we first must define two terms:
3775///
3776/// * `haystack` - The bytes to execute the search. The search always starts
3777/// at the beginning of `haystack` and ends before or at the end of
3778/// `haystack`.
3779/// * `context` - The (possibly empty) bytes surrounding `haystack`. `haystack`
3780/// must be contained within `context` such that `context` is at least as big
3781/// as `haystack`.
3782///
3783/// This split is crucial for dealing with look-around. For example, consider
3784/// the context `foobarbaz`, the haystack `bar` and the regex `^bar$`. This
3785/// regex should _not_ match the haystack since `bar` does not appear at the
3786/// beginning of the input. Similarly, the regex `\Bbar\B` should match the
3787/// haystack because `bar` is not surrounded by word boundaries. But a search
3788/// that does not take context into account would not permit `\B` to match
3789/// since the beginning of any string matches a word boundary. Similarly, a
3790/// search that does not take context into account when searching `^bar$` in
3791/// the haystack `bar` would produce a match when it shouldn't.
3792///
3793/// Thus, it follows that the starting state is chosen based on the following
3794/// criteria, derived from the position at which the search starts in the
3795/// `context` (corresponding to the start of `haystack`):
3796///
3797/// 1. If the search starts at the beginning of `context`, then the `Text`
3798/// start state is used. (Since `^` corresponds to
781aab86 3799/// `hir::Anchor::Start`.)
487cf647
FG
3800/// 2. If the search starts at a position immediately following a line
3801/// terminator, then the `Line` start state is used. (Since `(?m:^)`
781aab86 3802/// corresponds to `hir::Anchor::StartLF`.)
487cf647
FG
3803/// 3. If the search starts at a position immediately following a byte
3804/// classified as a "word" character (`[_0-9a-zA-Z]`), then the `WordByte`
3805/// start state is used. (Since `(?-u:\b)` corresponds to a word boundary.)
3806/// 4. Otherwise, if the search starts at a position immediately following
3807/// a byte that is not classified as a "word" character (`[^_0-9a-zA-Z]`),
3808/// then the `NonWordByte` start state is used. (Since `(?-u:\B)`
3809/// corresponds to a not-word-boundary.)
3810///
3811/// (N.B. Unicode word boundaries are not supported by the DFA because they
3812/// require multi-byte look-around and this is difficult to support in a DFA.)
3813///
3814/// To further complicate things, we also support constructing individual
3815/// anchored start states for each pattern in the DFA. (Which is required to
3816/// implement overlapping regexes correctly, but is also generally useful.)
3817/// Thus, when individual start states for each pattern are enabled, then the
3818/// total number of start states represented is `4 + (4 * #patterns)`, where
3819/// the 4 comes from each of the 4 possibilities above. The first 4 represents
3820/// the starting states for the entire DFA, which support searching for
3821/// multiple patterns simultaneously (possibly unanchored).
3822///
3823/// If individual start states are disabled, then this will only store 4
3824/// start states. Typically, individual start states are only enabled when
3825/// constructing the reverse DFA for regex matching. But they are also useful
3826/// for building DFAs that can search for a specific pattern or even to support
3827/// both anchored and unanchored searches with the same DFA.
3828///
3829/// Note though that while the start table always has either `4` or
3830/// `4 + (4 * #patterns)` starting state *ids*, the total number of states
3831/// might be considerably smaller. That is, many of the IDs may be duplicative.
3832/// (For example, if a regex doesn't have a `\b` sub-pattern, then there's no
3833/// reason to generate a unique starting state for handling word boundaries.
3834/// Similarly for start/end anchors.)
3835#[derive(Clone)]
3836pub(crate) struct StartTable<T> {
3837 /// The initial start state IDs.
3838 ///
3839 /// In practice, T is either `Vec<u32>` or `&[u32]`.
3840 ///
781aab86
FG
3841 /// The first `2 * stride` (currently always 8) entries always correspond
3842 /// to the starts states for the entire DFA, with the first 4 entries being
3843 /// for unanchored searches and the second 4 entries being for anchored
3844 /// searches. To keep things simple, we always use 8 entries even if the
3845 /// `StartKind` is not both.
3846 ///
3847 /// After that, there are `stride * patterns` state IDs, where `patterns`
3848 /// may be zero in the case of a DFA with no patterns or in the case where
3849 /// the DFA was built without enabling starting states for each pattern.
487cf647 3850 table: T,
781aab86
FG
3851 /// The starting state configuration supported. When 'both', both
3852 /// unanchored and anchored searches work. When 'unanchored', anchored
3853 /// searches panic. When 'anchored', unanchored searches panic.
3854 kind: StartKind,
3855 /// The start state configuration for every possible byte.
3856 start_map: StartByteMap,
487cf647
FG
3857 /// The number of starting state IDs per pattern.
3858 stride: usize,
3859 /// The total number of patterns for which starting states are encoded.
781aab86
FG
3860 /// This is `None` for DFAs that were built without start states for each
3861 /// pattern. Thus, one cannot use this field to say how many patterns
3862 /// are in the DFA in all cases. It is specific to how many patterns are
3863 /// represented in this start table.
3864 pattern_len: Option<usize>,
3865 /// The universal starting state for unanchored searches. This is only
3866 /// present when the DFA supports unanchored searches and when all starting
3867 /// state IDs for an unanchored search are equivalent.
3868 universal_start_unanchored: Option<StateID>,
3869 /// The universal starting state for anchored searches. This is only
3870 /// present when the DFA supports anchored searches and when all starting
3871 /// state IDs for an anchored search are equivalent.
3872 universal_start_anchored: Option<StateID>,
487cf647
FG
3873}
3874
781aab86 3875#[cfg(feature = "dfa-build")]
487cf647
FG
3876impl StartTable<Vec<u32>> {
3877 /// Create a valid set of start states all pointing to the dead state.
3878 ///
3879 /// When the corresponding DFA is constructed with start states for each
3880 /// pattern, then `patterns` should be the number of patterns. Otherwise,
3881 /// it should be zero.
3882 ///
3883 /// If the total table size could exceed the allocatable limit, then this
3884 /// returns an error. In practice, this is unlikely to be able to occur,
3885 /// since it's likely that allocation would have failed long before it got
3886 /// to this point.
781aab86
FG
3887 fn dead(
3888 kind: StartKind,
3889 lookm: &LookMatcher,
3890 pattern_len: Option<usize>,
3891 ) -> Result<StartTable<Vec<u32>>, BuildError> {
3892 if let Some(len) = pattern_len {
3893 assert!(len <= PatternID::LIMIT);
3894 }
3895 let stride = Start::len();
3896 // OK because 2*4 is never going to overflow anything.
3897 let starts_len = stride.checked_mul(2).unwrap();
3898 let pattern_starts_len =
3899 match stride.checked_mul(pattern_len.unwrap_or(0)) {
3900 Some(x) => x,
3901 None => return Err(BuildError::too_many_start_states()),
3902 };
3903 let table_len = match starts_len.checked_add(pattern_starts_len) {
487cf647 3904 Some(x) => x,
781aab86 3905 None => return Err(BuildError::too_many_start_states()),
487cf647 3906 };
781aab86
FG
3907 if let Err(_) = isize::try_from(table_len) {
3908 return Err(BuildError::too_many_start_states());
487cf647
FG
3909 }
3910 let table = vec![DEAD.as_u32(); table_len];
781aab86
FG
3911 let start_map = StartByteMap::new(lookm);
3912 Ok(StartTable {
3913 table,
3914 kind,
3915 start_map,
3916 stride,
3917 pattern_len,
3918 universal_start_unanchored: None,
3919 universal_start_anchored: None,
3920 })
487cf647
FG
3921 }
3922}
3923
3924impl<'a> StartTable<&'a [u32]> {
3925 /// Deserialize a table of start state IDs starting at the beginning of
3926 /// `slice`. Upon success, return the total number of bytes read along with
3927 /// the table of starting state IDs.
3928 ///
3929 /// If there was a problem deserializing any part of the starting IDs,
3930 /// then this returns an error. Notably, if the given slice does not have
3931 /// the same alignment as `StateID`, then this will return an error (among
3932 /// other possible errors).
3933 ///
3934 /// This is guaranteed to execute in constant time.
3935 ///
3936 /// # Safety
3937 ///
781aab86 3938 /// This routine is not safe because it does not check the validity of the
487cf647
FG
3939 /// starting state IDs themselves. In particular, the number of starting
3940 /// IDs can be of variable length, so it's possible that checking their
3941 /// validity cannot be done in constant time. An invalid starting state
3942 /// ID is not safe because other code may rely on the starting IDs being
3943 /// correct (such as explicit bounds check elision). Therefore, an invalid
3944 /// start ID can lead to undefined behavior.
3945 ///
3946 /// Callers that use this function must either pass on the safety invariant
3947 /// or guarantee that the bytes given contain valid starting state IDs.
3948 /// This guarantee is upheld by the bytes written by `write_to`.
3949 unsafe fn from_bytes_unchecked(
3950 mut slice: &'a [u8],
3951 ) -> Result<(StartTable<&'a [u32]>, usize), DeserializeError> {
781aab86 3952 let slice_start = slice.as_ptr().as_usize();
487cf647 3953
781aab86 3954 let (kind, nr) = StartKind::from_bytes(slice)?;
487cf647
FG
3955 slice = &slice[nr..];
3956
781aab86 3957 let (start_map, nr) = StartByteMap::from_bytes(slice)?;
487cf647
FG
3958 slice = &slice[nr..];
3959
781aab86
FG
3960 let (stride, nr) =
3961 wire::try_read_u32_as_usize(slice, "start table stride")?;
3962 slice = &slice[nr..];
3963 if stride != Start::len() {
487cf647
FG
3964 return Err(DeserializeError::generic(
3965 "invalid starting table stride",
3966 ));
3967 }
781aab86
FG
3968
3969 let (maybe_pattern_len, nr) =
3970 wire::try_read_u32_as_usize(slice, "start table patterns")?;
3971 slice = &slice[nr..];
3972 let pattern_len = if maybe_pattern_len.as_u32() == u32::MAX {
3973 None
3974 } else {
3975 Some(maybe_pattern_len)
3976 };
3977 if pattern_len.map_or(false, |len| len > PatternID::LIMIT) {
487cf647
FG
3978 return Err(DeserializeError::generic(
3979 "invalid number of patterns",
3980 ));
3981 }
781aab86
FG
3982
3983 let (universal_unanchored, nr) =
3984 wire::try_read_u32(slice, "universal unanchored start")?;
3985 slice = &slice[nr..];
3986 let universal_start_unanchored = if universal_unanchored == u32::MAX {
3987 None
3988 } else {
3989 Some(StateID::try_from(universal_unanchored).map_err(|e| {
3990 DeserializeError::state_id_error(
3991 e,
3992 "universal unanchored start",
3993 )
3994 })?)
3995 };
3996
3997 let (universal_anchored, nr) =
3998 wire::try_read_u32(slice, "universal anchored start")?;
3999 slice = &slice[nr..];
4000 let universal_start_anchored = if universal_anchored == u32::MAX {
4001 None
4002 } else {
4003 Some(StateID::try_from(universal_anchored).map_err(|e| {
4004 DeserializeError::state_id_error(e, "universal anchored start")
4005 })?)
4006 };
4007
4008 let pattern_table_size = wire::mul(
487cf647 4009 stride,
781aab86
FG
4010 pattern_len.unwrap_or(0),
4011 "invalid pattern length",
4012 )?;
4013 // Our start states always start with a two stride of start states for
4014 // the entire automaton. The first stride is for unanchored starting
4015 // states and the second stride is for anchored starting states. What
4016 // follows it are an optional set of start states for each pattern.
4017 let start_state_len = wire::add(
4018 wire::mul(2, stride, "start state stride too big")?,
487cf647
FG
4019 pattern_table_size,
4020 "invalid 'any' pattern starts size",
4021 )?;
781aab86
FG
4022 let table_bytes_len = wire::mul(
4023 start_state_len,
487cf647
FG
4024 StateID::SIZE,
4025 "pattern table bytes length",
4026 )?;
781aab86
FG
4027 wire::check_slice_len(slice, table_bytes_len, "start ID table")?;
4028 wire::check_alignment::<StateID>(slice)?;
487cf647
FG
4029 let table_bytes = &slice[..table_bytes_len];
4030 slice = &slice[table_bytes_len..];
4031 // SAFETY: Since StateID is always representable as a u32, all we need
4032 // to do is ensure that we have the proper length and alignment. We've
4033 // checked both above, so the cast below is safe.
4034 //
781aab86
FG
4035 // N.B. This is the only not-safe code in this function.
4036 let table = core::slice::from_raw_parts(
4037 table_bytes.as_ptr().cast::<u32>(),
4038 start_state_len,
4039 );
4040 let st = StartTable {
4041 table,
4042 kind,
4043 start_map,
4044 stride,
4045 pattern_len,
4046 universal_start_unanchored,
4047 universal_start_anchored,
487cf647 4048 };
781aab86 4049 Ok((st, slice.as_ptr().as_usize() - slice_start))
487cf647
FG
4050 }
4051}
4052
4053impl<T: AsRef<[u32]>> StartTable<T> {
4054 /// Writes a serialized form of this start table to the buffer given. If
4055 /// the buffer is too small, then an error is returned. To determine how
4056 /// big the buffer must be, use `write_to_len`.
4057 fn write_to<E: Endian>(
4058 &self,
4059 mut dst: &mut [u8],
4060 ) -> Result<usize, SerializeError> {
4061 let nwrite = self.write_to_len();
4062 if dst.len() < nwrite {
4063 return Err(SerializeError::buffer_too_small(
4064 "starting table ids",
4065 ));
4066 }
4067 dst = &mut dst[..nwrite];
4068
781aab86
FG
4069 // write start kind
4070 let nw = self.kind.write_to::<E>(dst)?;
4071 dst = &mut dst[nw..];
4072 // write start byte map
4073 let nw = self.start_map.write_to(dst)?;
4074 dst = &mut dst[nw..];
487cf647
FG
4075 // write stride
4076 // Unwrap is OK since the stride is always 4 (currently).
4077 E::write_u32(u32::try_from(self.stride).unwrap(), dst);
4078 dst = &mut dst[size_of::<u32>()..];
781aab86 4079 // write pattern length
487cf647 4080 // Unwrap is OK since number of patterns is guaranteed to fit in a u32.
781aab86
FG
4081 E::write_u32(
4082 u32::try_from(self.pattern_len.unwrap_or(0xFFFF_FFFF)).unwrap(),
4083 dst,
4084 );
4085 dst = &mut dst[size_of::<u32>()..];
4086 // write universal start unanchored state id, u32::MAX if absent
4087 E::write_u32(
4088 self.universal_start_unanchored
4089 .map_or(u32::MAX, |sid| sid.as_u32()),
4090 dst,
4091 );
4092 dst = &mut dst[size_of::<u32>()..];
4093 // write universal start anchored state id, u32::MAX if absent
4094 E::write_u32(
4095 self.universal_start_anchored.map_or(u32::MAX, |sid| sid.as_u32()),
4096 dst,
4097 );
487cf647
FG
4098 dst = &mut dst[size_of::<u32>()..];
4099 // write start IDs
4100 for &sid in self.table() {
781aab86 4101 let n = wire::write_state_id::<E>(sid, &mut dst);
487cf647
FG
4102 dst = &mut dst[n..];
4103 }
4104 Ok(nwrite)
4105 }
4106
4107 /// Returns the number of bytes the serialized form of this start ID table
4108 /// will use.
4109 fn write_to_len(&self) -> usize {
781aab86
FG
4110 self.kind.write_to_len()
4111 + self.start_map.write_to_len()
4112 + size_of::<u32>() // stride
487cf647 4113 + size_of::<u32>() // # patterns
781aab86
FG
4114 + size_of::<u32>() // universal unanchored start
4115 + size_of::<u32>() // universal anchored start
487cf647
FG
4116 + (self.table().len() * StateID::SIZE)
4117 }
4118
4119 /// Validates that every state ID in this start table is valid by checking
4120 /// it against the given transition table (which must be for the same DFA).
4121 ///
4122 /// That is, every state ID can be used to correctly index a state.
4123 fn validate(
4124 &self,
4125 tt: &TransitionTable<T>,
4126 ) -> Result<(), DeserializeError> {
781aab86
FG
4127 if !self.universal_start_unanchored.map_or(true, |s| tt.is_valid(s)) {
4128 return Err(DeserializeError::generic(
4129 "found invalid universal unanchored starting state ID",
4130 ));
4131 }
4132 if !self.universal_start_anchored.map_or(true, |s| tt.is_valid(s)) {
4133 return Err(DeserializeError::generic(
4134 "found invalid universal anchored starting state ID",
4135 ));
4136 }
487cf647
FG
4137 for &id in self.table() {
4138 if !tt.is_valid(id) {
4139 return Err(DeserializeError::generic(
4140 "found invalid starting state ID",
4141 ));
4142 }
4143 }
4144 Ok(())
4145 }
4146
4147 /// Converts this start list to a borrowed value.
4148 fn as_ref(&self) -> StartTable<&'_ [u32]> {
4149 StartTable {
4150 table: self.table.as_ref(),
781aab86
FG
4151 kind: self.kind,
4152 start_map: self.start_map.clone(),
487cf647 4153 stride: self.stride,
781aab86
FG
4154 pattern_len: self.pattern_len,
4155 universal_start_unanchored: self.universal_start_unanchored,
4156 universal_start_anchored: self.universal_start_anchored,
487cf647
FG
4157 }
4158 }
4159
4160 /// Converts this start list to an owned value.
4161 #[cfg(feature = "alloc")]
781aab86 4162 fn to_owned(&self) -> StartTable<alloc::vec::Vec<u32>> {
487cf647
FG
4163 StartTable {
4164 table: self.table.as_ref().to_vec(),
781aab86
FG
4165 kind: self.kind,
4166 start_map: self.start_map.clone(),
487cf647 4167 stride: self.stride,
781aab86
FG
4168 pattern_len: self.pattern_len,
4169 universal_start_unanchored: self.universal_start_unanchored,
4170 universal_start_anchored: self.universal_start_anchored,
487cf647
FG
4171 }
4172 }
4173
781aab86
FG
4174 /// Return the start state for the given input and starting configuration.
4175 /// This returns an error if the input configuration is not supported by
4176 /// this DFA. For example, requesting an unanchored search when the DFA was
4177 /// not built with unanchored starting states. Or asking for an anchored
4178 /// pattern search with an invalid pattern ID or on a DFA that was not
4179 /// built with start states for each pattern.
4180 #[cfg_attr(feature = "perf-inline", inline(always))]
4181 fn start(
4182 &self,
4183 input: &Input<'_>,
4184 start: Start,
4185 ) -> Result<StateID, MatchError> {
4186 let start_index = start.as_usize();
4187 let mode = input.get_anchored();
4188 let index = match mode {
4189 Anchored::No => {
4190 if !self.kind.has_unanchored() {
4191 return Err(MatchError::unsupported_anchored(mode));
4192 }
4193 start_index
4194 }
4195 Anchored::Yes => {
4196 if !self.kind.has_anchored() {
4197 return Err(MatchError::unsupported_anchored(mode));
4198 }
4199 self.stride + start_index
4200 }
4201 Anchored::Pattern(pid) => {
4202 let len = match self.pattern_len {
4203 None => {
4204 return Err(MatchError::unsupported_anchored(mode))
4205 }
4206 Some(len) => len,
4207 };
4208 if pid.as_usize() >= len {
4209 return Ok(DEAD);
4210 }
4211 (2 * self.stride)
4212 + (self.stride * pid.as_usize())
4213 + start_index
487cf647
FG
4214 }
4215 };
781aab86 4216 Ok(self.table()[index])
487cf647
FG
4217 }
4218
4219 /// Returns an iterator over all start state IDs in this table.
4220 ///
4221 /// Each item is a triple of: start state ID, the start state type and the
4222 /// pattern ID (if any).
4223 fn iter(&self) -> StartStateIter<'_> {
4224 StartStateIter { st: self.as_ref(), i: 0 }
4225 }
4226
4227 /// Returns the table as a slice of state IDs.
4228 fn table(&self) -> &[StateID] {
781aab86 4229 wire::u32s_to_state_ids(self.table.as_ref())
487cf647
FG
4230 }
4231
4232 /// Return the memory usage, in bytes, of this start list.
4233 ///
4234 /// This does not include the size of a `StartList` value itself.
4235 fn memory_usage(&self) -> usize {
4236 self.table().len() * StateID::SIZE
4237 }
4238}
4239
781aab86 4240#[cfg(feature = "dfa-build")]
487cf647
FG
4241impl<T: AsMut<[u32]>> StartTable<T> {
4242 /// Set the start state for the given index and pattern.
4243 ///
4244 /// If the pattern ID or state ID are not valid, then this will panic.
781aab86
FG
4245 fn set_start(&mut self, anchored: Anchored, start: Start, id: StateID) {
4246 let start_index = start.as_usize();
4247 let index = match anchored {
4248 Anchored::No => start_index,
4249 Anchored::Yes => self.stride + start_index,
4250 Anchored::Pattern(pid) => {
4251 let pid = pid.as_usize();
4252 let len = self
4253 .pattern_len
4254 .expect("start states for each pattern enabled");
4255 assert!(pid < len, "invalid pattern ID {:?}", pid);
4256 self.stride
4257 .checked_mul(pid)
4258 .unwrap()
4259 .checked_add(self.stride.checked_mul(2).unwrap())
4260 .unwrap()
4261 .checked_add(start_index)
4262 .unwrap()
4263 }
487cf647
FG
4264 };
4265 self.table_mut()[index] = id;
4266 }
4267
4268 /// Returns the table as a mutable slice of state IDs.
4269 fn table_mut(&mut self) -> &mut [StateID] {
781aab86 4270 wire::u32s_to_state_ids_mut(self.table.as_mut())
487cf647
FG
4271 }
4272}
4273
4274/// An iterator over start state IDs.
4275///
781aab86
FG
4276/// This iterator yields a triple of start state ID, the anchored mode and the
4277/// start state type. If a pattern ID is relevant, then the anchored mode will
4278/// contain it. Start states with an anchored mode containing a pattern ID will
4279/// only occur when the DFA was compiled with start states for each pattern
4280/// (which is disabled by default).
487cf647
FG
4281pub(crate) struct StartStateIter<'a> {
4282 st: StartTable<&'a [u32]>,
4283 i: usize,
4284}
4285
4286impl<'a> Iterator for StartStateIter<'a> {
781aab86 4287 type Item = (StateID, Anchored, Start);
487cf647 4288
781aab86 4289 fn next(&mut self) -> Option<(StateID, Anchored, Start)> {
487cf647
FG
4290 let i = self.i;
4291 let table = self.st.table();
4292 if i >= table.len() {
4293 return None;
4294 }
4295 self.i += 1;
4296
4297 // This unwrap is okay since the stride of the starting state table
4298 // must always match the number of start state types.
4299 let start_type = Start::from_usize(i % self.st.stride).unwrap();
781aab86
FG
4300 let anchored = if i < self.st.stride {
4301 Anchored::No
4302 } else if i < (2 * self.st.stride) {
4303 Anchored::Yes
487cf647 4304 } else {
781aab86
FG
4305 let pid = (i - (2 * self.st.stride)) / self.st.stride;
4306 Anchored::Pattern(PatternID::new(pid).unwrap())
487cf647 4307 };
781aab86 4308 Some((table[i], anchored, start_type))
487cf647
FG
4309 }
4310}
4311
4312/// This type represents that patterns that should be reported whenever a DFA
4313/// enters a match state. This structure exists to support DFAs that search for
4314/// matches for multiple regexes.
4315///
4316/// This structure relies on the fact that all match states in a DFA occur
4317/// contiguously in the DFA's transition table. (See dfa/special.rs for a more
4318/// detailed breakdown of the representation.) Namely, when a match occurs, we
4319/// know its state ID. Since we know the start and end of the contiguous region
4320/// of match states, we can use that to compute the position at which the match
4321/// state occurs. That in turn is used as an offset into this structure.
4322#[derive(Clone, Debug)]
4323struct MatchStates<T> {
4324 /// Slices is a flattened sequence of pairs, where each pair points to a
4325 /// sub-slice of pattern_ids. The first element of the pair is an offset
4326 /// into pattern_ids and the second element of the pair is the number
4327 /// of 32-bit pattern IDs starting at that position. That is, each pair
4328 /// corresponds to a single DFA match state and its corresponding match
4329 /// IDs. The number of pairs always corresponds to the number of distinct
4330 /// DFA match states.
4331 ///
4332 /// In practice, T is either Vec<u32> or &[u32].
4333 slices: T,
4334 /// A flattened sequence of pattern IDs for each DFA match state. The only
4335 /// way to correctly read this sequence is indirectly via `slices`.
4336 ///
4337 /// In practice, T is either Vec<u32> or &[u32].
4338 pattern_ids: T,
4339 /// The total number of unique patterns represented by these match states.
781aab86 4340 pattern_len: usize,
487cf647
FG
4341}
4342
4343impl<'a> MatchStates<&'a [u32]> {
4344 unsafe fn from_bytes_unchecked(
4345 mut slice: &'a [u8],
4346 ) -> Result<(MatchStates<&'a [u32]>, usize), DeserializeError> {
781aab86 4347 let slice_start = slice.as_ptr().as_usize();
487cf647
FG
4348
4349 // Read the total number of match states.
781aab86
FG
4350 let (state_len, nr) =
4351 wire::try_read_u32_as_usize(slice, "match state length")?;
487cf647
FG
4352 slice = &slice[nr..];
4353
4354 // Read the slice start/length pairs.
781aab86
FG
4355 let pair_len = wire::mul(2, state_len, "match state offset pairs")?;
4356 let slices_bytes_len = wire::mul(
4357 pair_len,
487cf647
FG
4358 PatternID::SIZE,
4359 "match state slice offset byte length",
4360 )?;
781aab86
FG
4361 wire::check_slice_len(slice, slices_bytes_len, "match state slices")?;
4362 wire::check_alignment::<PatternID>(slice)?;
487cf647
FG
4363 let slices_bytes = &slice[..slices_bytes_len];
4364 slice = &slice[slices_bytes_len..];
4365 // SAFETY: Since PatternID is always representable as a u32, all we
4366 // need to do is ensure that we have the proper length and alignment.
4367 // We've checked both above, so the cast below is safe.
4368 //
781aab86
FG
4369 // N.B. This is one of the few not-safe snippets in this function,
4370 // so we mark it explicitly to call it out.
4371 let slices = core::slice::from_raw_parts(
4372 slices_bytes.as_ptr().cast::<u32>(),
4373 pair_len,
4374 );
487cf647
FG
4375
4376 // Read the total number of unique pattern IDs (which is always 1 more
4377 // than the maximum pattern ID in this automaton, since pattern IDs are
4378 // handed out contiguously starting at 0).
781aab86
FG
4379 let (pattern_len, nr) =
4380 wire::try_read_u32_as_usize(slice, "pattern length")?;
487cf647
FG
4381 slice = &slice[nr..];
4382
781aab86 4383 // Now read the pattern ID length. We don't need to store this
487cf647 4384 // explicitly, but we need it to know how many pattern IDs to read.
781aab86
FG
4385 let (idlen, nr) =
4386 wire::try_read_u32_as_usize(slice, "pattern ID length")?;
487cf647
FG
4387 slice = &slice[nr..];
4388
4389 // Read the actual pattern IDs.
4390 let pattern_ids_len =
781aab86
FG
4391 wire::mul(idlen, PatternID::SIZE, "pattern ID byte length")?;
4392 wire::check_slice_len(slice, pattern_ids_len, "match pattern IDs")?;
4393 wire::check_alignment::<PatternID>(slice)?;
487cf647
FG
4394 let pattern_ids_bytes = &slice[..pattern_ids_len];
4395 slice = &slice[pattern_ids_len..];
4396 // SAFETY: Since PatternID is always representable as a u32, all we
4397 // need to do is ensure that we have the proper length and alignment.
4398 // We've checked both above, so the cast below is safe.
4399 //
781aab86
FG
4400 // N.B. This is one of the few not-safe snippets in this function,
4401 // so we mark it explicitly to call it out.
4402 let pattern_ids = core::slice::from_raw_parts(
4403 pattern_ids_bytes.as_ptr().cast::<u32>(),
4404 idlen,
4405 );
487cf647 4406
781aab86
FG
4407 let ms = MatchStates { slices, pattern_ids, pattern_len };
4408 Ok((ms, slice.as_ptr().as_usize() - slice_start))
487cf647
FG
4409 }
4410}
4411
781aab86 4412#[cfg(feature = "dfa-build")]
487cf647 4413impl MatchStates<Vec<u32>> {
781aab86
FG
4414 fn empty(pattern_len: usize) -> MatchStates<Vec<u32>> {
4415 assert!(pattern_len <= PatternID::LIMIT);
4416 MatchStates { slices: vec![], pattern_ids: vec![], pattern_len }
487cf647
FG
4417 }
4418
4419 fn new(
4420 matches: &BTreeMap<StateID, Vec<PatternID>>,
781aab86
FG
4421 pattern_len: usize,
4422 ) -> Result<MatchStates<Vec<u32>>, BuildError> {
4423 let mut m = MatchStates::empty(pattern_len);
487cf647
FG
4424 for (_, pids) in matches.iter() {
4425 let start = PatternID::new(m.pattern_ids.len())
781aab86 4426 .map_err(|_| BuildError::too_many_match_pattern_ids())?;
487cf647
FG
4427 m.slices.push(start.as_u32());
4428 // This is always correct since the number of patterns in a single
4429 // match state can never exceed maximum number of allowable
4430 // patterns. Why? Because a pattern can only appear once in a
4431 // particular match state, by construction. (And since our pattern
4432 // ID limit is one less than u32::MAX, we're guaranteed that the
4433 // length fits in a u32.)
4434 m.slices.push(u32::try_from(pids.len()).unwrap());
4435 for &pid in pids {
4436 m.pattern_ids.push(pid.as_u32());
4437 }
4438 }
781aab86 4439 m.pattern_len = pattern_len;
487cf647
FG
4440 Ok(m)
4441 }
4442
4443 fn new_with_map(
4444 &self,
4445 matches: &BTreeMap<StateID, Vec<PatternID>>,
781aab86
FG
4446 ) -> Result<MatchStates<Vec<u32>>, BuildError> {
4447 MatchStates::new(matches, self.pattern_len)
487cf647
FG
4448 }
4449}
4450
4451impl<T: AsRef<[u32]>> MatchStates<T> {
4452 /// Writes a serialized form of these match states to the buffer given. If
4453 /// the buffer is too small, then an error is returned. To determine how
4454 /// big the buffer must be, use `write_to_len`.
4455 fn write_to<E: Endian>(
4456 &self,
4457 mut dst: &mut [u8],
4458 ) -> Result<usize, SerializeError> {
4459 let nwrite = self.write_to_len();
4460 if dst.len() < nwrite {
4461 return Err(SerializeError::buffer_too_small("match states"));
4462 }
4463 dst = &mut dst[..nwrite];
4464
781aab86 4465 // write state ID length
487cf647 4466 // Unwrap is OK since number of states is guaranteed to fit in a u32.
781aab86 4467 E::write_u32(u32::try_from(self.len()).unwrap(), dst);
487cf647
FG
4468 dst = &mut dst[size_of::<u32>()..];
4469
4470 // write slice offset pairs
4471 for &pid in self.slices() {
781aab86 4472 let n = wire::write_pattern_id::<E>(pid, &mut dst);
487cf647
FG
4473 dst = &mut dst[n..];
4474 }
4475
781aab86 4476 // write unique pattern ID length
487cf647 4477 // Unwrap is OK since number of patterns is guaranteed to fit in a u32.
781aab86 4478 E::write_u32(u32::try_from(self.pattern_len).unwrap(), dst);
487cf647
FG
4479 dst = &mut dst[size_of::<u32>()..];
4480
781aab86 4481 // write pattern ID length
487cf647
FG
4482 // Unwrap is OK since we check at construction (and deserialization)
4483 // that the number of patterns is representable as a u32.
4484 E::write_u32(u32::try_from(self.pattern_ids().len()).unwrap(), dst);
4485 dst = &mut dst[size_of::<u32>()..];
4486
4487 // write pattern IDs
4488 for &pid in self.pattern_ids() {
781aab86 4489 let n = wire::write_pattern_id::<E>(pid, &mut dst);
487cf647
FG
4490 dst = &mut dst[n..];
4491 }
4492
4493 Ok(nwrite)
4494 }
4495
781aab86
FG
4496 /// Returns the number of bytes the serialized form of these match states
4497 /// will use.
487cf647 4498 fn write_to_len(&self) -> usize {
781aab86 4499 size_of::<u32>() // match state length
487cf647 4500 + (self.slices().len() * PatternID::SIZE)
781aab86
FG
4501 + size_of::<u32>() // unique pattern ID length
4502 + size_of::<u32>() // pattern ID length
487cf647
FG
4503 + (self.pattern_ids().len() * PatternID::SIZE)
4504 }
4505
4506 /// Valides that the match state info is itself internally consistent and
4507 /// consistent with the recorded match state region in the given DFA.
4508 fn validate(&self, dfa: &DFA<T>) -> Result<(), DeserializeError> {
781aab86 4509 if self.len() != dfa.special.match_len(dfa.stride()) {
487cf647 4510 return Err(DeserializeError::generic(
781aab86 4511 "match state length mismatch",
487cf647
FG
4512 ));
4513 }
781aab86 4514 for si in 0..self.len() {
487cf647
FG
4515 let start = self.slices()[si * 2].as_usize();
4516 let len = self.slices()[si * 2 + 1].as_usize();
4517 if start >= self.pattern_ids().len() {
4518 return Err(DeserializeError::generic(
4519 "invalid pattern ID start offset",
4520 ));
4521 }
4522 if start + len > self.pattern_ids().len() {
4523 return Err(DeserializeError::generic(
4524 "invalid pattern ID length",
4525 ));
4526 }
4527 for mi in 0..len {
4528 let pid = self.pattern_id(si, mi);
781aab86 4529 if pid.as_usize() >= self.pattern_len {
487cf647
FG
4530 return Err(DeserializeError::generic(
4531 "invalid pattern ID",
4532 ));
4533 }
4534 }
4535 }
4536 Ok(())
4537 }
4538
4539 /// Converts these match states back into their map form. This is useful
4540 /// when shuffling states, as the normal MatchStates representation is not
4541 /// amenable to easy state swapping. But with this map, to swap id1 and
4542 /// id2, all you need to do is:
4543 ///
4544 /// if let Some(pids) = map.remove(&id1) {
4545 /// map.insert(id2, pids);
4546 /// }
4547 ///
4548 /// Once shuffling is done, use MatchStates::new to convert back.
781aab86 4549 #[cfg(feature = "dfa-build")]
487cf647
FG
4550 fn to_map(&self, dfa: &DFA<T>) -> BTreeMap<StateID, Vec<PatternID>> {
4551 let mut map = BTreeMap::new();
781aab86 4552 for i in 0..self.len() {
487cf647
FG
4553 let mut pids = vec![];
4554 for j in 0..self.pattern_len(i) {
4555 pids.push(self.pattern_id(i, j));
4556 }
4557 map.insert(self.match_state_id(dfa, i), pids);
4558 }
4559 map
4560 }
4561
4562 /// Converts these match states to a borrowed value.
4563 fn as_ref(&self) -> MatchStates<&'_ [u32]> {
4564 MatchStates {
4565 slices: self.slices.as_ref(),
4566 pattern_ids: self.pattern_ids.as_ref(),
781aab86 4567 pattern_len: self.pattern_len,
487cf647
FG
4568 }
4569 }
4570
4571 /// Converts these match states to an owned value.
4572 #[cfg(feature = "alloc")]
781aab86 4573 fn to_owned(&self) -> MatchStates<alloc::vec::Vec<u32>> {
487cf647
FG
4574 MatchStates {
4575 slices: self.slices.as_ref().to_vec(),
4576 pattern_ids: self.pattern_ids.as_ref().to_vec(),
781aab86 4577 pattern_len: self.pattern_len,
487cf647
FG
4578 }
4579 }
4580
4581 /// Returns the match state ID given the match state index. (Where the
4582 /// first match state corresponds to index 0.)
4583 ///
4584 /// This panics if there is no match state at the given index.
4585 fn match_state_id(&self, dfa: &DFA<T>, index: usize) -> StateID {
4586 assert!(dfa.special.matches(), "no match states to index");
4587 // This is one of the places where we rely on the fact that match
4588 // states are contiguous in the transition table. Namely, that the
4589 // first match state ID always corresponds to dfa.special.min_start.
4590 // From there, since we know the stride, we can compute the ID of any
4591 // match state given its index.
4592 let stride2 = u32::try_from(dfa.stride2()).unwrap();
4593 let offset = index.checked_shl(stride2).unwrap();
4594 let id = dfa.special.min_match.as_usize().checked_add(offset).unwrap();
4595 let sid = StateID::new(id).unwrap();
4596 assert!(dfa.is_match_state(sid));
4597 sid
4598 }
4599
4600 /// Returns the pattern ID at the given match index for the given match
4601 /// state.
4602 ///
4603 /// The match state index is the state index minus the state index of the
4604 /// first match state in the DFA.
4605 ///
4606 /// The match index is the index of the pattern ID for the given state.
4607 /// The index must be less than `self.pattern_len(state_index)`.
781aab86 4608 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
4609 fn pattern_id(&self, state_index: usize, match_index: usize) -> PatternID {
4610 self.pattern_id_slice(state_index)[match_index]
4611 }
4612
4613 /// Returns the number of patterns in the given match state.
4614 ///
4615 /// The match state index is the state index minus the state index of the
4616 /// first match state in the DFA.
781aab86 4617 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
4618 fn pattern_len(&self, state_index: usize) -> usize {
4619 self.slices()[state_index * 2 + 1].as_usize()
4620 }
4621
4622 /// Returns all of the pattern IDs for the given match state index.
4623 ///
4624 /// The match state index is the state index minus the state index of the
4625 /// first match state in the DFA.
781aab86 4626 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647
FG
4627 fn pattern_id_slice(&self, state_index: usize) -> &[PatternID] {
4628 let start = self.slices()[state_index * 2].as_usize();
4629 let len = self.pattern_len(state_index);
4630 &self.pattern_ids()[start..start + len]
4631 }
4632
4633 /// Returns the pattern ID offset slice of u32 as a slice of PatternID.
781aab86 4634 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647 4635 fn slices(&self) -> &[PatternID] {
781aab86 4636 wire::u32s_to_pattern_ids(self.slices.as_ref())
487cf647
FG
4637 }
4638
4639 /// Returns the total number of match states.
781aab86
FG
4640 #[cfg_attr(feature = "perf-inline", inline(always))]
4641 fn len(&self) -> usize {
487cf647
FG
4642 assert_eq!(0, self.slices().len() % 2);
4643 self.slices().len() / 2
4644 }
4645
4646 /// Returns the pattern ID slice of u32 as a slice of PatternID.
781aab86 4647 #[cfg_attr(feature = "perf-inline", inline(always))]
487cf647 4648 fn pattern_ids(&self) -> &[PatternID] {
781aab86 4649 wire::u32s_to_pattern_ids(self.pattern_ids.as_ref())
487cf647
FG
4650 }
4651
4652 /// Return the memory usage, in bytes, of these match pairs.
4653 fn memory_usage(&self) -> usize {
4654 (self.slices().len() + self.pattern_ids().len()) * PatternID::SIZE
4655 }
4656}
4657
781aab86
FG
4658/// A common set of flags for both dense and sparse DFAs. This primarily
4659/// centralizes the serialization format of these flags at a bitset.
4660#[derive(Clone, Copy, Debug)]
4661pub(crate) struct Flags {
4662 /// Whether the DFA can match the empty string. When this is false, all
4663 /// matches returned by this DFA are guaranteed to have non-zero length.
4664 pub(crate) has_empty: bool,
4665 /// Whether the DFA should only produce matches with spans that correspond
4666 /// to valid UTF-8. This also includes omitting any zero-width matches that
4667 /// split the UTF-8 encoding of a codepoint.
4668 pub(crate) is_utf8: bool,
4669 /// Whether the DFA is always anchored or not, regardless of `Input`
4670 /// configuration. This is useful for avoiding a reverse scan even when
4671 /// executing unanchored searches.
4672 pub(crate) is_always_start_anchored: bool,
4673}
4674
4675impl Flags {
4676 /// Creates a set of flags for a DFA from an NFA.
4677 ///
4678 /// N.B. This constructor was defined at the time of writing because all
4679 /// of the flags are derived directly from the NFA. If this changes in the
4680 /// future, we might be more thoughtful about how the `Flags` value is
4681 /// itself built.
4682 #[cfg(feature = "dfa-build")]
4683 fn from_nfa(nfa: &thompson::NFA) -> Flags {
4684 Flags {
4685 has_empty: nfa.has_empty(),
4686 is_utf8: nfa.is_utf8(),
4687 is_always_start_anchored: nfa.is_always_start_anchored(),
4688 }
4689 }
4690
4691 /// Deserializes the flags from the given slice. On success, this also
4692 /// returns the number of bytes read from the slice.
4693 pub(crate) fn from_bytes(
4694 slice: &[u8],
4695 ) -> Result<(Flags, usize), DeserializeError> {
4696 let (bits, nread) = wire::try_read_u32(slice, "flag bitset")?;
4697 let flags = Flags {
4698 has_empty: bits & (1 << 0) != 0,
4699 is_utf8: bits & (1 << 1) != 0,
4700 is_always_start_anchored: bits & (1 << 2) != 0,
4701 };
4702 Ok((flags, nread))
4703 }
4704
4705 /// Writes these flags to the given byte slice. If the buffer is too small,
4706 /// then an error is returned. To determine how big the buffer must be,
4707 /// use `write_to_len`.
4708 pub(crate) fn write_to<E: Endian>(
4709 &self,
4710 dst: &mut [u8],
4711 ) -> Result<usize, SerializeError> {
4712 fn bool_to_int(b: bool) -> u32 {
4713 if b {
4714 1
4715 } else {
4716 0
4717 }
4718 }
4719
4720 let nwrite = self.write_to_len();
4721 if dst.len() < nwrite {
4722 return Err(SerializeError::buffer_too_small("flag bitset"));
4723 }
4724 let bits = (bool_to_int(self.has_empty) << 0)
4725 | (bool_to_int(self.is_utf8) << 1)
4726 | (bool_to_int(self.is_always_start_anchored) << 2);
4727 E::write_u32(bits, dst);
4728 Ok(nwrite)
4729 }
4730
4731 /// Returns the number of bytes the serialized form of these flags
4732 /// will use.
4733 pub(crate) fn write_to_len(&self) -> usize {
4734 size_of::<u32>()
4735 }
4736}
4737
487cf647
FG
4738/// An iterator over all states in a DFA.
4739///
4740/// This iterator yields a tuple for each state. The first element of the
4741/// tuple corresponds to a state's identifier, and the second element
4742/// corresponds to the state itself (comprised of its transitions).
4743///
4744/// `'a` corresponding to the lifetime of original DFA, `T` corresponds to
4745/// the type of the transition table itself.
4746pub(crate) struct StateIter<'a, T> {
4747 tt: &'a TransitionTable<T>,
4748 it: iter::Enumerate<slice::Chunks<'a, StateID>>,
4749}
4750
4751impl<'a, T: AsRef<[u32]>> Iterator for StateIter<'a, T> {
4752 type Item = State<'a>;
4753
4754 fn next(&mut self) -> Option<State<'a>> {
4755 self.it.next().map(|(index, _)| {
781aab86 4756 let id = self.tt.to_state_id(index);
487cf647
FG
4757 self.tt.state(id)
4758 })
4759 }
4760}
4761
4762/// An immutable representation of a single DFA state.
4763///
4764/// `'a` correspondings to the lifetime of a DFA's transition table.
4765pub(crate) struct State<'a> {
4766 id: StateID,
4767 stride2: usize,
4768 transitions: &'a [StateID],
4769}
4770
4771impl<'a> State<'a> {
4772 /// Return an iterator over all transitions in this state. This yields
4773 /// a number of transitions equivalent to the alphabet length of the
4774 /// corresponding DFA.
4775 ///
4776 /// Each transition is represented by a tuple. The first element is
4777 /// the input byte for that transition and the second element is the
4778 /// transitions itself.
4779 pub(crate) fn transitions(&self) -> StateTransitionIter<'_> {
4780 StateTransitionIter {
4781 len: self.transitions.len(),
4782 it: self.transitions.iter().enumerate(),
4783 }
4784 }
4785
4786 /// Return an iterator over a sparse representation of the transitions in
4787 /// this state. Only non-dead transitions are returned.
4788 ///
4789 /// The "sparse" representation in this case corresponds to a sequence of
4790 /// triples. The first two elements of the triple comprise an inclusive
4791 /// byte range while the last element corresponds to the transition taken
4792 /// for all bytes in the range.
4793 ///
4794 /// This is somewhat more condensed than the classical sparse
4795 /// representation (where you have an element for every non-dead
4796 /// transition), but in practice, checking if a byte is in a range is very
4797 /// cheap and using ranges tends to conserve quite a bit more space.
4798 pub(crate) fn sparse_transitions(&self) -> StateSparseTransitionIter<'_> {
4799 StateSparseTransitionIter { dense: self.transitions(), cur: None }
4800 }
4801
4802 /// Returns the identifier for this state.
4803 pub(crate) fn id(&self) -> StateID {
4804 self.id
4805 }
4806
4807 /// Analyzes this state to determine whether it can be accelerated. If so,
4808 /// it returns an accelerator that contains at least one byte.
781aab86 4809 #[cfg(feature = "dfa-build")]
487cf647
FG
4810 fn accelerate(&self, classes: &ByteClasses) -> Option<Accel> {
4811 // We just try to add bytes to our accelerator. Once adding fails
4812 // (because we've added too many bytes), then give up.
4813 let mut accel = Accel::new();
4814 for (class, id) in self.transitions() {
4815 if id == self.id() {
4816 continue;
4817 }
4818 for unit in classes.elements(class) {
4819 if let Some(byte) = unit.as_u8() {
4820 if !accel.add(byte) {
4821 return None;
4822 }
4823 }
4824 }
4825 }
4826 if accel.is_empty() {
4827 None
4828 } else {
4829 Some(accel)
4830 }
4831 }
4832}
4833
4834impl<'a> fmt::Debug for State<'a> {
4835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781aab86
FG
4836 for (i, (start, end, sid)) in self.sparse_transitions().enumerate() {
4837 let id = if f.alternate() {
4838 sid.as_usize()
487cf647 4839 } else {
781aab86 4840 sid.as_usize() >> self.stride2
487cf647
FG
4841 };
4842 if i > 0 {
4843 write!(f, ", ")?;
4844 }
4845 if start == end {
781aab86 4846 write!(f, "{:?} => {:?}", start, id)?;
487cf647 4847 } else {
781aab86 4848 write!(f, "{:?}-{:?} => {:?}", start, end, id)?;
487cf647
FG
4849 }
4850 }
4851 Ok(())
4852 }
4853}
4854
487cf647
FG
4855/// An iterator over all transitions in a single DFA state. This yields
4856/// a number of transitions equivalent to the alphabet length of the
4857/// corresponding DFA.
4858///
4859/// Each transition is represented by a tuple. The first element is the input
4860/// byte for that transition and the second element is the transition itself.
4861#[derive(Debug)]
4862pub(crate) struct StateTransitionIter<'a> {
4863 len: usize,
4864 it: iter::Enumerate<slice::Iter<'a, StateID>>,
4865}
4866
4867impl<'a> Iterator for StateTransitionIter<'a> {
4868 type Item = (alphabet::Unit, StateID);
4869
4870 fn next(&mut self) -> Option<(alphabet::Unit, StateID)> {
4871 self.it.next().map(|(i, &id)| {
4872 let unit = if i + 1 == self.len {
4873 alphabet::Unit::eoi(i)
4874 } else {
4875 let b = u8::try_from(i)
4876 .expect("raw byte alphabet is never exceeded");
4877 alphabet::Unit::u8(b)
4878 };
4879 (unit, id)
4880 })
4881 }
4882}
4883
487cf647
FG
4884/// An iterator over all non-DEAD transitions in a single DFA state using a
4885/// sparse representation.
4886///
4887/// Each transition is represented by a triple. The first two elements of the
4888/// triple comprise an inclusive byte range while the last element corresponds
4889/// to the transition taken for all bytes in the range.
4890///
4891/// As a convenience, this always returns `alphabet::Unit` values of the same
4892/// type. That is, you'll never get a (byte, EOI) or a (EOI, byte). Only (byte,
4893/// byte) and (EOI, EOI) values are yielded.
4894#[derive(Debug)]
4895pub(crate) struct StateSparseTransitionIter<'a> {
4896 dense: StateTransitionIter<'a>,
4897 cur: Option<(alphabet::Unit, alphabet::Unit, StateID)>,
4898}
4899
4900impl<'a> Iterator for StateSparseTransitionIter<'a> {
4901 type Item = (alphabet::Unit, alphabet::Unit, StateID);
4902
4903 fn next(&mut self) -> Option<(alphabet::Unit, alphabet::Unit, StateID)> {
4904 while let Some((unit, next)) = self.dense.next() {
4905 let (prev_start, prev_end, prev_next) = match self.cur {
4906 Some(t) => t,
4907 None => {
4908 self.cur = Some((unit, unit, next));
4909 continue;
4910 }
4911 };
4912 if prev_next == next && !unit.is_eoi() {
4913 self.cur = Some((prev_start, unit, prev_next));
4914 } else {
4915 self.cur = Some((unit, unit, next));
4916 if prev_next != DEAD {
4917 return Some((prev_start, prev_end, prev_next));
4918 }
4919 }
4920 }
4921 if let Some((start, end, next)) = self.cur.take() {
4922 if next != DEAD {
4923 return Some((start, end, next));
4924 }
4925 }
4926 None
4927 }
4928}
4929
781aab86
FG
4930/// An error that occurred during the construction of a DFA.
4931///
4932/// This error does not provide many introspection capabilities. There are
4933/// generally only two things you can do with it:
4934///
4935/// * Obtain a human readable message via its `std::fmt::Display` impl.
4936/// * Access an underlying [`nfa::thompson::BuildError`](thompson::BuildError)
4937/// type from its `source` method via the `std::error::Error` trait. This error
4938/// only occurs when using convenience routines for building a DFA directly
4939/// from a pattern string.
4940///
4941/// When the `std` feature is enabled, this implements the `std::error::Error`
4942/// trait.
4943#[cfg(feature = "dfa-build")]
4944#[derive(Clone, Debug)]
4945pub struct BuildError {
4946 kind: BuildErrorKind,
487cf647
FG
4947}
4948
781aab86 4949/// The kind of error that occurred during the construction of a DFA.
487cf647 4950///
781aab86
FG
4951/// Note that this error is non-exhaustive. Adding new variants is not
4952/// considered a breaking change.
4953#[cfg(feature = "dfa-build")]
4954#[derive(Clone, Debug)]
4955enum BuildErrorKind {
4956 /// An error that occurred while constructing an NFA as a precursor step
4957 /// before a DFA is compiled.
4958 NFA(thompson::BuildError),
4959 /// An error that occurred because an unsupported regex feature was used.
4960 /// The message string describes which unsupported feature was used.
4961 ///
4962 /// The primary regex feature that is unsupported by DFAs is the Unicode
4963 /// word boundary look-around assertion (`\b`). This can be worked around
4964 /// by either using an ASCII word boundary (`(?-u:\b)`) or by enabling
4965 /// Unicode word boundaries when building a DFA.
4966 Unsupported(&'static str),
4967 /// An error that occurs if too many states are produced while building a
4968 /// DFA.
4969 TooManyStates,
4970 /// An error that occurs if too many start states are needed while building
4971 /// a DFA.
4972 ///
4973 /// This is a kind of oddball error that occurs when building a DFA with
4974 /// start states enabled for each pattern and enough patterns to cause
4975 /// the table of start states to overflow `usize`.
4976 TooManyStartStates,
4977 /// This is another oddball error that can occur if there are too many
4978 /// patterns spread out across too many match states.
4979 TooManyMatchPatternIDs,
4980 /// An error that occurs if the DFA got too big during determinization.
4981 DFAExceededSizeLimit { limit: usize },
4982 /// An error that occurs if auxiliary storage (not the DFA) used during
4983 /// determinization got too big.
4984 DeterminizeExceededSizeLimit { limit: usize },
487cf647
FG
4985}
4986
781aab86
FG
4987#[cfg(feature = "dfa-build")]
4988impl BuildError {
4989 /// Return the kind of this error.
4990 fn kind(&self) -> &BuildErrorKind {
4991 &self.kind
4992 }
4993
4994 pub(crate) fn nfa(err: thompson::BuildError) -> BuildError {
4995 BuildError { kind: BuildErrorKind::NFA(err) }
4996 }
4997
4998 pub(crate) fn unsupported_dfa_word_boundary_unicode() -> BuildError {
4999 let msg = "cannot build DFAs for regexes with Unicode word \
5000 boundaries; switch to ASCII word boundaries, or \
5001 heuristically enable Unicode word boundaries or use a \
5002 different regex engine";
5003 BuildError { kind: BuildErrorKind::Unsupported(msg) }
5004 }
5005
5006 pub(crate) fn too_many_states() -> BuildError {
5007 BuildError { kind: BuildErrorKind::TooManyStates }
5008 }
5009
5010 pub(crate) fn too_many_start_states() -> BuildError {
5011 BuildError { kind: BuildErrorKind::TooManyStartStates }
5012 }
5013
5014 pub(crate) fn too_many_match_pattern_ids() -> BuildError {
5015 BuildError { kind: BuildErrorKind::TooManyMatchPatternIDs }
5016 }
5017
5018 pub(crate) fn dfa_exceeded_size_limit(limit: usize) -> BuildError {
5019 BuildError { kind: BuildErrorKind::DFAExceededSizeLimit { limit } }
5020 }
5021
5022 pub(crate) fn determinize_exceeded_size_limit(limit: usize) -> BuildError {
5023 BuildError {
5024 kind: BuildErrorKind::DeterminizeExceededSizeLimit { limit },
487cf647
FG
5025 }
5026 }
781aab86 5027}
487cf647 5028
781aab86
FG
5029#[cfg(all(feature = "std", feature = "dfa-build"))]
5030impl std::error::Error for BuildError {
5031 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
5032 match self.kind() {
5033 BuildErrorKind::NFA(ref err) => Some(err),
5034 _ => None,
5035 }
487cf647 5036 }
781aab86 5037}
487cf647 5038
781aab86
FG
5039#[cfg(feature = "dfa-build")]
5040impl core::fmt::Display for BuildError {
5041 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5042 match self.kind() {
5043 BuildErrorKind::NFA(_) => write!(f, "error building NFA"),
5044 BuildErrorKind::Unsupported(ref msg) => {
5045 write!(f, "unsupported regex feature for DFAs: {}", msg)
487cf647 5046 }
781aab86
FG
5047 BuildErrorKind::TooManyStates => write!(
5048 f,
5049 "number of DFA states exceeds limit of {}",
5050 StateID::LIMIT,
5051 ),
5052 BuildErrorKind::TooManyStartStates => {
5053 let stride = Start::len();
5054 // The start table has `stride` entries for starting states for
5055 // the entire DFA, and then `stride` entries for each pattern
5056 // if start states for each pattern are enabled (which is the
5057 // only way this error can occur). Thus, the total number of
5058 // patterns that can fit in the table is `stride` less than
5059 // what we can allocate.
5060 let max = usize::try_from(core::isize::MAX).unwrap();
5061 let limit = (max - stride) / stride;
5062 write!(
5063 f,
5064 "compiling DFA with start states exceeds pattern \
5065 pattern limit of {}",
5066 limit,
5067 )
487cf647 5068 }
781aab86
FG
5069 BuildErrorKind::TooManyMatchPatternIDs => write!(
5070 f,
5071 "compiling DFA with total patterns in all match states \
5072 exceeds limit of {}",
5073 PatternID::LIMIT,
5074 ),
5075 BuildErrorKind::DFAExceededSizeLimit { limit } => write!(
5076 f,
5077 "DFA exceeded size limit of {:?} during determinization",
5078 limit,
5079 ),
5080 BuildErrorKind::DeterminizeExceededSizeLimit { limit } => {
5081 write!(f, "determinization exceeded size limit of {:?}", limit)
487cf647
FG
5082 }
5083 }
487cf647
FG
5084 }
5085}
5086
781aab86 5087#[cfg(all(test, feature = "syntax", feature = "dfa-build"))]
487cf647
FG
5088mod tests {
5089 use super::*;
5090
5091 #[test]
5092 fn errors_with_unicode_word_boundary() {
5093 let pattern = r"\b";
5094 assert!(Builder::new().build(pattern).is_err());
5095 }
5096
5097 #[test]
5098 fn roundtrip_never_match() {
5099 let dfa = DFA::never_match().unwrap();
5100 let (buf, _) = dfa.to_bytes_native_endian();
5101 let dfa: DFA<&[u32]> = DFA::from_bytes(&buf).unwrap().0;
5102
781aab86 5103 assert_eq!(None, dfa.try_search_fwd(&Input::new("foo12345")).unwrap());
487cf647
FG
5104 }
5105
5106 #[test]
5107 fn roundtrip_always_match() {
5108 use crate::HalfMatch;
5109
5110 let dfa = DFA::always_match().unwrap();
5111 let (buf, _) = dfa.to_bytes_native_endian();
5112 let dfa: DFA<&[u32]> = DFA::from_bytes(&buf).unwrap().0;
5113
5114 assert_eq!(
5115 Some(HalfMatch::must(0, 0)),
781aab86 5116 dfa.try_search_fwd(&Input::new("foo12345")).unwrap()
487cf647
FG
5117 );
5118 }
781aab86
FG
5119
5120 // See the analogous test in src/hybrid/dfa.rs.
5121 #[test]
5122 fn heuristic_unicode_reverse() {
5123 let dfa = DFA::builder()
5124 .configure(DFA::config().unicode_word_boundary(true))
5125 .thompson(thompson::Config::new().reverse(true))
5126 .build(r"\b[0-9]+\b")
5127 .unwrap();
5128
5129 let input = Input::new("β123").range(2..);
5130 let expected = MatchError::quit(0xB2, 1);
5131 let got = dfa.try_search_rev(&input);
5132 assert_eq!(Err(expected), got);
5133
5134 let input = Input::new("123β").range(..3);
5135 let expected = MatchError::quit(0xCE, 3);
5136 let got = dfa.try_search_rev(&input);
5137 assert_eq!(Err(expected), got);
5138 }
487cf647 5139}