Skip to main content

regex_automata/nfa/thompson/
compiler.rs

1use core::{borrow::Borrow, cell::RefCell};
2
3use alloc::{sync::Arc, vec, vec::Vec};
4
5use regex_syntax::{
6    hir::{self, Hir},
7    utf8::{Utf8Range, Utf8Sequences},
8    ParserBuilder,
9};
10
11use crate::{
12    nfa::thompson::{
13        builder::Builder,
14        error::BuildError,
15        literal_trie::LiteralTrie,
16        map::{Utf8BoundedMap, Utf8SuffixKey, Utf8SuffixMap},
17        nfa::{Transition, NFA},
18        range_trie::RangeTrie,
19    },
20    util::{
21        look::{Look, LookMatcher},
22        primitives::{PatternID, StateID},
23    },
24};
25
26/// The configuration used for a Thompson NFA compiler.
27#[derive(Clone, Debug, Default)]
28pub struct Config {
29    utf8: Option<bool>,
30    reverse: Option<bool>,
31    nfa_size_limit: Option<Option<usize>>,
32    shrink: Option<bool>,
33    which_captures: Option<WhichCaptures>,
34    look_matcher: Option<LookMatcher>,
35    #[cfg(test)]
36    unanchored_prefix: Option<bool>,
37}
38
39impl Config {
40    /// Return a new default Thompson NFA compiler configuration.
41    pub fn new() -> Config {
42        Config::default()
43    }
44
45    /// Whether to enable UTF-8 mode during search or not.
46    ///
47    /// A regex engine is said to be in UTF-8 mode when it guarantees that
48    /// all matches returned by it have spans consisting of only valid UTF-8.
49    /// That is, it is impossible for a match span to be returned that
50    /// contains any invalid UTF-8.
51    ///
52    /// UTF-8 mode generally consists of two things:
53    ///
54    /// 1. Whether the NFA's states are constructed such that all paths to a
55    /// match state that consume at least one byte always correspond to valid
56    /// UTF-8.
57    /// 2. Whether all paths to a match state that do _not_ consume any bytes
58    /// should always correspond to valid UTF-8 boundaries.
59    ///
60    /// (1) is a guarantee made by whoever constructs the NFA.
61    /// If you're parsing a regex from its concrete syntax, then
62    /// [`syntax::Config::utf8`](crate::util::syntax::Config::utf8) can make
63    /// this guarantee for you. It does it by returning an error if the regex
64    /// pattern could every report a non-empty match span that contains invalid
65    /// UTF-8. So long as `syntax::Config::utf8` mode is enabled and your regex
66    /// successfully parses, then you're guaranteed that the corresponding NFA
67    /// will only ever report non-empty match spans containing valid UTF-8.
68    ///
69    /// (2) is a trickier guarantee because it cannot be enforced by the NFA
70    /// state graph itself. Consider, for example, the regex `a*`. It matches
71    /// the empty strings in `☃` at positions `0`, `1`, `2` and `3`, where
72    /// positions `1` and `2` occur within the UTF-8 encoding of a codepoint,
73    /// and thus correspond to invalid UTF-8 boundaries. Therefore, this
74    /// guarantee must be made at a higher level than the NFA state graph
75    /// itself. This crate deals with this case in each regex engine. Namely,
76    /// when a zero-width match that splits a codepoint is found and UTF-8
77    /// mode enabled, then it is ignored and the engine moves on looking for
78    /// the next match.
79    ///
80    /// Thus, UTF-8 mode is both a promise that the NFA built only reports
81    /// non-empty matches that are valid UTF-8, and an *instruction* to regex
82    /// engines that empty matches that split codepoints should be banned.
83    ///
84    /// Because UTF-8 mode is fundamentally about avoiding invalid UTF-8 spans,
85    /// it only makes sense to enable this option when you *know* your haystack
86    /// is valid UTF-8. (For example, a `&str`.) Enabling UTF-8 mode and
87    /// searching a haystack that contains invalid UTF-8 leads to **unspecified
88    /// behavior**.
89    ///
90    /// Therefore, it may make sense to enable `syntax::Config::utf8` while
91    /// simultaneously *disabling* this option. That would ensure all non-empty
92    /// match spans are valid UTF-8, but that empty match spans may still split
93    /// a codepoint or match at other places that aren't valid UTF-8.
94    ///
95    /// In general, this mode is only relevant if your regex can match the
96    /// empty string. Most regexes don't.
97    ///
98    /// This is enabled by default.
99    ///
100    /// # Example
101    ///
102    /// This example shows how UTF-8 mode can impact the match spans that may
103    /// be reported in certain cases.
104    ///
105    /// ```
106    /// use regex_automata::{
107    ///     nfa::thompson::{self, pikevm::PikeVM},
108    ///     Match, Input,
109    /// };
110    ///
111    /// let re = PikeVM::new("")?;
112    /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
113    ///
114    /// // UTF-8 mode is enabled by default.
115    /// let mut input = Input::new("☃");
116    /// re.search(&mut cache, &input, &mut caps);
117    /// assert_eq!(Some(Match::must(0, 0..0)), caps.get_match());
118    ///
119    /// // Even though an empty regex matches at 1..1, our next match is
120    /// // 3..3 because 1..1 and 2..2 split the snowman codepoint (which is
121    /// // three bytes long).
122    /// input.set_start(1);
123    /// re.search(&mut cache, &input, &mut caps);
124    /// assert_eq!(Some(Match::must(0, 3..3)), caps.get_match());
125    ///
126    /// // But if we disable UTF-8, then we'll get matches at 1..1 and 2..2:
127    /// let re = PikeVM::builder()
128    ///     .thompson(thompson::Config::new().utf8(false))
129    ///     .build("")?;
130    /// re.search(&mut cache, &input, &mut caps);
131    /// assert_eq!(Some(Match::must(0, 1..1)), caps.get_match());
132    ///
133    /// input.set_start(2);
134    /// re.search(&mut cache, &input, &mut caps);
135    /// assert_eq!(Some(Match::must(0, 2..2)), caps.get_match());
136    ///
137    /// input.set_start(3);
138    /// re.search(&mut cache, &input, &mut caps);
139    /// assert_eq!(Some(Match::must(0, 3..3)), caps.get_match());
140    ///
141    /// input.set_start(4);
142    /// re.search(&mut cache, &input, &mut caps);
143    /// assert_eq!(None, caps.get_match());
144    ///
145    /// # Ok::<(), Box<dyn std::error::Error>>(())
146    /// ```
147    pub fn utf8(mut self, yes: bool) -> Config {
148        self.utf8 = Some(yes);
149        self
150    }
151
152    /// Reverse the NFA.
153    ///
154    /// A NFA reversal is performed by reversing all of the concatenated
155    /// sub-expressions in the original pattern, recursively. (Look around
156    /// operators are also inverted.) The resulting NFA can be used to match
157    /// the pattern starting from the end of a string instead of the beginning
158    /// of a string.
159    ///
160    /// Reversing the NFA is useful for building a reverse DFA, which is most
161    /// useful for finding the start of a match after its ending position has
162    /// been found. NFA execution engines typically do not work on reverse
163    /// NFAs. For example, currently, the Pike VM reports the starting location
164    /// of matches without a reverse NFA.
165    ///
166    /// Currently, enabling this setting requires disabling the
167    /// [`captures`](Config::captures) setting. If both are enabled, then the
168    /// compiler will return an error. It is expected that this limitation will
169    /// be lifted in the future.
170    ///
171    /// This is disabled by default.
172    ///
173    /// # Example
174    ///
175    /// This example shows how to build a DFA from a reverse NFA, and then use
176    /// the DFA to search backwards.
177    ///
178    /// ```
179    /// use regex_automata::{
180    ///     dfa::{self, Automaton},
181    ///     nfa::thompson::{NFA, WhichCaptures},
182    ///     HalfMatch, Input,
183    /// };
184    ///
185    /// let dfa = dfa::dense::Builder::new()
186    ///     .thompson(NFA::config()
187    ///         .which_captures(WhichCaptures::None)
188    ///         .reverse(true)
189    ///     )
190    ///     .build("baz[0-9]+")?;
191    /// let expected = Some(HalfMatch::must(0, 3));
192    /// assert_eq!(
193    ///     expected,
194    ///     dfa.try_search_rev(&Input::new("foobaz12345bar"))?,
195    /// );
196    ///
197    /// # Ok::<(), Box<dyn std::error::Error>>(())
198    /// ```
199    pub fn reverse(mut self, yes: bool) -> Config {
200        self.reverse = Some(yes);
201        self
202    }
203
204    /// Sets an approximate size limit on the total heap used by the NFA being
205    /// compiled.
206    ///
207    /// This permits imposing constraints on the size of a compiled NFA. This
208    /// may be useful in contexts where the regex pattern is untrusted and one
209    /// wants to avoid using too much memory.
210    ///
211    /// This size limit does not apply to auxiliary heap used during
212    /// compilation that is not part of the built NFA.
213    ///
214    /// Note that this size limit is applied during compilation in order for
215    /// the limit to prevent too much heap from being used. However, the
216    /// implementation may use an intermediate NFA representation that is
217    /// otherwise slightly bigger than the final public form. Since the size
218    /// limit may be applied to an intermediate representation, there is not
219    /// necessarily a precise correspondence between the configured size limit
220    /// and the heap usage of the final NFA.
221    ///
222    /// There is no size limit by default.
223    ///
224    /// # Example
225    ///
226    /// This example demonstrates how Unicode mode can greatly increase the
227    /// size of the NFA.
228    ///
229    /// ```
230    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
231    /// use regex_automata::nfa::thompson::NFA;
232    ///
233    /// // 300KB isn't enough!
234    /// NFA::compiler()
235    ///     .configure(NFA::config().nfa_size_limit(Some(300_000)))
236    ///     .build(r"\w{20}")
237    ///     .unwrap_err();
238    ///
239    /// // ... but 500KB probably is.
240    /// let nfa = NFA::compiler()
241    ///     .configure(NFA::config().nfa_size_limit(Some(500_000)))
242    ///     .build(r"\w{20}")?;
243    ///
244    /// assert_eq!(nfa.pattern_len(), 1);
245    ///
246    /// # Ok::<(), Box<dyn std::error::Error>>(())
247    /// ```
248    pub fn nfa_size_limit(mut self, bytes: Option<usize>) -> Config {
249        self.nfa_size_limit = Some(bytes);
250        self
251    }
252
253    /// Apply best effort heuristics to shrink the NFA at the expense of more
254    /// time/memory.
255    ///
256    /// Generally speaking, if one is using an NFA to compile a DFA, then the
257    /// extra time used to shrink the NFA will be more than made up for during
258    /// DFA construction (potentially by a lot). In other words, enabling this
259    /// can substantially decrease the overall amount of time it takes to build
260    /// a DFA.
261    ///
262    /// A reason to keep this disabled is if you want to compile an NFA and
263    /// start using it as quickly as possible without needing to build a DFA,
264    /// and you don't mind using a bit of extra memory for the NFA. e.g., for
265    /// an NFA simulation or for a lazy DFA.
266    ///
267    /// NFA shrinking is currently most useful when compiling a reverse
268    /// NFA with large Unicode character classes. In particular, it trades
269    /// additional CPU time during NFA compilation in favor of generating fewer
270    /// NFA states.
271    ///
272    /// This is disabled by default because it can increase compile times
273    /// quite a bit if you aren't building a full DFA.
274    ///
275    /// # Example
276    ///
277    /// This example shows that NFA shrinking can lead to substantial space
278    /// savings in some cases. Notice that, as noted above, we build a reverse
279    /// DFA and use a pattern with a large Unicode character class.
280    ///
281    /// ```
282    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
283    /// use regex_automata::nfa::thompson::{NFA, WhichCaptures};
284    ///
285    /// // Currently we have to disable captures when enabling reverse NFA.
286    /// let config = NFA::config()
287    ///     .which_captures(WhichCaptures::None)
288    ///     .reverse(true);
289    /// let not_shrunk = NFA::compiler()
290    ///     .configure(config.clone().shrink(false))
291    ///     .build(r"\w")?;
292    /// let shrunk = NFA::compiler()
293    ///     .configure(config.clone().shrink(true))
294    ///     .build(r"\w")?;
295    ///
296    /// // While a specific shrink factor is not guaranteed, the savings can be
297    /// // considerable in some cases.
298    /// assert!(shrunk.states().len() * 2 < not_shrunk.states().len());
299    ///
300    /// # Ok::<(), Box<dyn std::error::Error>>(())
301    /// ```
302    pub fn shrink(mut self, yes: bool) -> Config {
303        self.shrink = Some(yes);
304        self
305    }
306
307    /// Whether to include 'Capture' states in the NFA.
308    ///
309    /// Currently, enabling this setting requires disabling the
310    /// [`reverse`](Config::reverse) setting. If both are enabled, then the
311    /// compiler will return an error. It is expected that this limitation will
312    /// be lifted in the future.
313    ///
314    /// This is enabled by default.
315    ///
316    /// # Example
317    ///
318    /// This example demonstrates that some regex engines, like the Pike VM,
319    /// require capturing states to be present in the NFA to report match
320    /// offsets.
321    ///
322    /// (Note that since this method is deprecated, the example below uses
323    /// [`Config::which_captures`] to disable capture states.)
324    ///
325    /// ```
326    /// use regex_automata::nfa::thompson::{
327    ///     pikevm::PikeVM,
328    ///     NFA,
329    ///     WhichCaptures,
330    /// };
331    ///
332    /// let re = PikeVM::builder()
333    ///     .thompson(NFA::config().which_captures(WhichCaptures::None))
334    ///     .build(r"[a-z]+")?;
335    /// let mut cache = re.create_cache();
336    ///
337    /// assert!(re.is_match(&mut cache, "abc"));
338    /// assert_eq!(None, re.find(&mut cache, "abc"));
339    ///
340    /// # Ok::<(), Box<dyn std::error::Error>>(())
341    /// ```
342    #[deprecated(since = "0.3.5", note = "use which_captures instead")]
343    pub fn captures(self, yes: bool) -> Config {
344        self.which_captures(if yes {
345            WhichCaptures::All
346        } else {
347            WhichCaptures::None
348        })
349    }
350
351    /// Configures what kinds of capture groups are compiled into
352    /// [`State::Capture`](crate::nfa::thompson::State::Capture) states in a
353    /// Thompson NFA.
354    ///
355    /// Currently, using any option except for [`WhichCaptures::None`] requires
356    /// disabling the [`reverse`](Config::reverse) setting. If both are
357    /// enabled, then the compiler will return an error. It is expected that
358    /// this limitation will be lifted in the future.
359    ///
360    /// This is set to [`WhichCaptures::All`] by default. Callers may wish to
361    /// use [`WhichCaptures::Implicit`] in cases where one wants avoid the
362    /// overhead of capture states for explicit groups. Usually this occurs
363    /// when one wants to use the `PikeVM` only for determining the overall
364    /// match. Otherwise, the `PikeVM` could use much more memory than is
365    /// necessary.
366    ///
367    /// # Example
368    ///
369    /// This example demonstrates that some regex engines, like the Pike VM,
370    /// require capturing states to be present in the NFA to report match
371    /// offsets.
372    ///
373    /// ```
374    /// use regex_automata::nfa::thompson::{
375    ///     pikevm::PikeVM,
376    ///     NFA,
377    ///     WhichCaptures,
378    /// };
379    ///
380    /// let re = PikeVM::builder()
381    ///     .thompson(NFA::config().which_captures(WhichCaptures::None))
382    ///     .build(r"[a-z]+")?;
383    /// let mut cache = re.create_cache();
384    ///
385    /// assert!(re.is_match(&mut cache, "abc"));
386    /// assert_eq!(None, re.find(&mut cache, "abc"));
387    ///
388    /// # Ok::<(), Box<dyn std::error::Error>>(())
389    /// ```
390    ///
391    /// The same applies to the bounded backtracker:
392    ///
393    /// ```
394    /// use regex_automata::nfa::thompson::{
395    ///     backtrack::BoundedBacktracker,
396    ///     NFA,
397    ///     WhichCaptures,
398    /// };
399    ///
400    /// let re = BoundedBacktracker::builder()
401    ///     .thompson(NFA::config().which_captures(WhichCaptures::None))
402    ///     .build(r"[a-z]+")?;
403    /// let mut cache = re.create_cache();
404    ///
405    /// assert!(re.try_is_match(&mut cache, "abc")?);
406    /// assert_eq!(None, re.try_find(&mut cache, "abc")?);
407    ///
408    /// # Ok::<(), Box<dyn std::error::Error>>(())
409    /// ```
410    pub fn which_captures(mut self, which_captures: WhichCaptures) -> Config {
411        self.which_captures = Some(which_captures);
412        self
413    }
414
415    /// Sets the look-around matcher that should be used with this NFA.
416    ///
417    /// A look-around matcher determines how to match look-around assertions.
418    /// In particular, some assertions are configurable. For example, the
419    /// `(?m:^)` and `(?m:$)` assertions can have their line terminator changed
420    /// from the default of `\n` to any other byte.
421    ///
422    /// # Example
423    ///
424    /// This shows how to change the line terminator for multi-line assertions.
425    ///
426    /// ```
427    /// use regex_automata::{
428    ///     nfa::thompson::{self, pikevm::PikeVM},
429    ///     util::look::LookMatcher,
430    ///     Match, Input,
431    /// };
432    ///
433    /// let mut lookm = LookMatcher::new();
434    /// lookm.set_line_terminator(b'\x00');
435    ///
436    /// let re = PikeVM::builder()
437    ///     .thompson(thompson::Config::new().look_matcher(lookm))
438    ///     .build(r"(?m)^[a-z]+$")?;
439    /// let mut cache = re.create_cache();
440    ///
441    /// // Multi-line assertions now use NUL as a terminator.
442    /// assert_eq!(
443    ///     Some(Match::must(0, 1..4)),
444    ///     re.find(&mut cache, b"\x00abc\x00"),
445    /// );
446    /// // ... and \n is no longer recognized as a terminator.
447    /// assert_eq!(
448    ///     None,
449    ///     re.find(&mut cache, b"\nabc\n"),
450    /// );
451    ///
452    /// # Ok::<(), Box<dyn std::error::Error>>(())
453    /// ```
454    pub fn look_matcher(mut self, m: LookMatcher) -> Config {
455        self.look_matcher = Some(m);
456        self
457    }
458
459    /// Whether to compile an unanchored prefix into this NFA.
460    ///
461    /// This is enabled by default. It is made available for tests only to make
462    /// it easier to unit test the output of the compiler.
463    #[cfg(test)]
464    fn unanchored_prefix(mut self, yes: bool) -> Config {
465        self.unanchored_prefix = Some(yes);
466        self
467    }
468
469    /// Returns whether this configuration has enabled UTF-8 mode.
470    pub fn get_utf8(&self) -> bool {
471        self.utf8.unwrap_or(true)
472    }
473
474    /// Returns whether this configuration has enabled reverse NFA compilation.
475    pub fn get_reverse(&self) -> bool {
476        self.reverse.unwrap_or(false)
477    }
478
479    /// Return the configured NFA size limit, if it exists, in the number of
480    /// bytes of heap used.
481    pub fn get_nfa_size_limit(&self) -> Option<usize> {
482        self.nfa_size_limit.unwrap_or(None)
483    }
484
485    /// Return whether NFA shrinking is enabled.
486    pub fn get_shrink(&self) -> bool {
487        self.shrink.unwrap_or(false)
488    }
489
490    /// Return whether NFA compilation is configured to produce capture states.
491    #[deprecated(since = "0.3.5", note = "use get_which_captures instead")]
492    pub fn get_captures(&self) -> bool {
493        self.get_which_captures().is_any()
494    }
495
496    /// Return what kinds of capture states will be compiled into an NFA.
497    pub fn get_which_captures(&self) -> WhichCaptures {
498        self.which_captures.unwrap_or(WhichCaptures::All)
499    }
500
501    /// Return the look-around matcher for this NFA.
502    pub fn get_look_matcher(&self) -> LookMatcher {
503        self.look_matcher.clone().unwrap_or(LookMatcher::default())
504    }
505
506    /// Return whether NFA compilation is configured to include an unanchored
507    /// prefix.
508    ///
509    /// This is always false when not in test mode.
510    fn get_unanchored_prefix(&self) -> bool {
511        #[cfg(test)]
512        {
513            self.unanchored_prefix.unwrap_or(true)
514        }
515        #[cfg(not(test))]
516        {
517            true
518        }
519    }
520
521    /// Overwrite the default configuration such that the options in `o` are
522    /// always used. If an option in `o` is not set, then the corresponding
523    /// option in `self` is used. If it's not set in `self` either, then it
524    /// remains not set.
525    pub(crate) fn overwrite(&self, o: Config) -> Config {
526        Config {
527            utf8: o.utf8.or(self.utf8),
528            reverse: o.reverse.or(self.reverse),
529            nfa_size_limit: o.nfa_size_limit.or(self.nfa_size_limit),
530            shrink: o.shrink.or(self.shrink),
531            which_captures: o.which_captures.or(self.which_captures),
532            look_matcher: o.look_matcher.or_else(|| self.look_matcher.clone()),
533            #[cfg(test)]
534            unanchored_prefix: o.unanchored_prefix.or(self.unanchored_prefix),
535        }
536    }
537}
538
539/// A configuration indicating which kinds of
540/// [`State::Capture`](crate::nfa::thompson::State::Capture) states to include.
541///
542/// This configuration can be used with [`Config::which_captures`] to control
543/// which capture states are compiled into a Thompson NFA.
544///
545/// The default configuration is [`WhichCaptures::All`].
546#[derive(Clone, Copy, Debug, Default)]
547pub enum WhichCaptures {
548    /// All capture states, including those corresponding to both implicit and
549    /// explicit capture groups, are included in the Thompson NFA.
550    #[default]
551    All,
552    /// Only capture states corresponding to implicit capture groups are
553    /// included. Implicit capture groups appear in every pattern implicitly
554    /// and correspond to the overall match of a pattern.
555    ///
556    /// This is useful when one only cares about the overall match of a
557    /// pattern. By excluding capture states from explicit capture groups,
558    /// one might be able to reduce the memory usage of a multi-pattern regex
559    /// substantially if it was otherwise written to have many explicit capture
560    /// groups.
561    Implicit,
562    /// No capture states are compiled into the Thompson NFA.
563    ///
564    /// This is useful when capture states are either not needed (for example,
565    /// if one is only trying to build a DFA) or if they aren't supported (for
566    /// example, a reverse NFA).
567    ///
568    /// # Warning
569    ///
570    /// Callers must be exceedingly careful when using this
571    /// option. In particular, not all regex engines support
572    /// reporting match spans when using this option (for example,
573    /// [`PikeVM`](crate::nfa::thompson::pikevm::PikeVM) or
574    /// [`BoundedBacktracker`](crate::nfa::thompson::backtrack::BoundedBacktracker)).
575    ///
576    /// Perhaps more confusingly, using this option with such an
577    /// engine means that an `is_match` routine could report `true`
578    /// when `find` reports `None`. This is generally not something
579    /// that _should_ happen, but the low level control provided by
580    /// this crate makes it possible.
581    ///
582    /// Similarly, any regex engines (like [`meta::Regex`](crate::meta::Regex))
583    /// should always return `None` from `find` routines when this option is
584    /// used, even if _some_ of its internal engines could find the match
585    /// boundaries. This is because inputs from user data could influence
586    /// engine selection, and thus influence whether a match is found or not.
587    /// Indeed, `meta::Regex::find` will always return `None` when configured
588    /// with this option.
589    None,
590}
591
592impl WhichCaptures {
593    /// Returns true if this configuration indicates that no capture states
594    /// should be produced in an NFA.
595    pub fn is_none(&self) -> bool {
596        matches!(*self, WhichCaptures::None)
597    }
598
599    /// Returns true if this configuration indicates that some capture states
600    /// should be added to an NFA. Note that this might only include capture
601    /// states for implicit capture groups.
602    pub fn is_any(&self) -> bool {
603        !self.is_none()
604    }
605}
606
607/*
608This compiler below uses Thompson's construction algorithm. The compiler takes
609a regex-syntax::Hir as input and emits an NFA graph as output. The NFA graph
610is structured in a way that permits it to be executed by a virtual machine and
611also used to efficiently build a DFA.
612
613The compiler deals with a slightly expanded set of NFA states than what is
614in a final NFA (as exhibited by builder::State and nfa::State). Notably a
615compiler state includes an empty node that has exactly one unconditional
616epsilon transition to the next state. In other words, it's a "goto" instruction
617if one views Thompson's NFA as a set of bytecode instructions. These goto
618instructions are removed in a subsequent phase before returning the NFA to the
619caller. The purpose of these empty nodes is that they make the construction
620algorithm substantially simpler to implement. We remove them before returning
621to the caller because they can represent substantial overhead when traversing
622the NFA graph (either while searching using the NFA directly or while building
623a DFA).
624
625In the future, it would be nice to provide a Glushkov compiler as well, as it
626would work well as a bit-parallel NFA for smaller regexes. But the Thompson
627construction is one I'm more familiar with and seems more straight-forward to
628deal with when it comes to large Unicode character classes.
629
630Internally, the compiler uses interior mutability to improve composition in the
631face of the borrow checker. In particular, we'd really like to be able to write
632things like this:
633
634    self.c_concat(exprs.iter().map(|e| self.c(e)))
635
636Which elegantly uses iterators to build up a sequence of compiled regex
637sub-expressions and then hands it off to the concatenating compiler routine.
638Without interior mutability, the borrow checker won't let us borrow `self`
639mutably both inside and outside the closure at the same time.
640*/
641
642/// A builder for compiling an NFA from a regex's high-level intermediate
643/// representation (HIR).
644///
645/// This compiler provides a way to translate a parsed regex pattern into an
646/// NFA state graph. The NFA state graph can either be used directly to execute
647/// a search (e.g., with a Pike VM), or it can be further used to build a DFA.
648///
649/// This compiler provides APIs both for compiling regex patterns directly from
650/// their concrete syntax, or via a [`regex_syntax::hir::Hir`].
651///
652/// This compiler has various options that may be configured via
653/// [`thompson::Config`](Config).
654///
655/// Note that a compiler is not the same as a [`thompson::Builder`](Builder).
656/// A `Builder` provides a lower level API that is uncoupled from a regex
657/// pattern's concrete syntax or even its HIR. Instead, it permits stitching
658/// together an NFA by hand. See its docs for examples.
659///
660/// # Example: compilation from concrete syntax
661///
662/// This shows how to compile an NFA from a pattern string while setting a size
663/// limit on how big the NFA is allowed to be (in terms of bytes of heap used).
664///
665/// ```
666/// use regex_automata::{
667///     nfa::thompson::{NFA, pikevm::PikeVM},
668///     Match,
669/// };
670///
671/// let config = NFA::config().nfa_size_limit(Some(1_000));
672/// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
673///
674/// let re = PikeVM::new_from_nfa(nfa)?;
675/// let mut cache = re.create_cache();
676/// let mut caps = re.create_captures();
677/// let expected = Some(Match::must(0, 3..4));
678/// re.captures(&mut cache, "!@#A#@!", &mut caps);
679/// assert_eq!(expected, caps.get_match());
680///
681/// # Ok::<(), Box<dyn std::error::Error>>(())
682/// ```
683///
684/// # Example: compilation from HIR
685///
686/// This shows how to hand assemble a regular expression via its HIR, and then
687/// compile an NFA directly from it.
688///
689/// ```
690/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
691/// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
692///
693/// let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![
694///     ClassBytesRange::new(b'0', b'9'),
695///     ClassBytesRange::new(b'A', b'Z'),
696///     ClassBytesRange::new(b'_', b'_'),
697///     ClassBytesRange::new(b'a', b'z'),
698/// ])));
699///
700/// let config = NFA::config().nfa_size_limit(Some(1_000));
701/// let nfa = NFA::compiler().configure(config).build_from_hir(&hir)?;
702///
703/// let re = PikeVM::new_from_nfa(nfa)?;
704/// let mut cache = re.create_cache();
705/// let mut caps = re.create_captures();
706/// let expected = Some(Match::must(0, 3..4));
707/// re.captures(&mut cache, "!@#A#@!", &mut caps);
708/// assert_eq!(expected, caps.get_match());
709///
710/// # Ok::<(), Box<dyn std::error::Error>>(())
711/// ```
712#[derive(Clone, Debug)]
713pub struct Compiler {
714    /// A regex parser, used when compiling an NFA directly from a pattern
715    /// string.
716    parser: ParserBuilder,
717    /// The compiler configuration.
718    config: Config,
719    /// The builder for actually constructing an NFA. This provides a
720    /// convenient abstraction for writing a compiler.
721    builder: RefCell<Builder>,
722    /// State used for compiling character classes to UTF-8 byte automata.
723    /// State is not retained between character class compilations. This just
724    /// serves to amortize allocation to the extent possible.
725    utf8_state: RefCell<Utf8State>,
726    /// State used for arranging character classes in reverse into a trie.
727    trie_state: RefCell<RangeTrie>,
728    /// State used for caching common suffixes when compiling reverse UTF-8
729    /// automata (for Unicode character classes).
730    utf8_suffix: RefCell<Utf8SuffixMap>,
731}
732
733impl Compiler {
734    /// Create a new NFA builder with its default configuration.
735    pub fn new() -> Compiler {
736        Compiler {
737            parser: ParserBuilder::new(),
738            config: Config::default(),
739            builder: RefCell::new(Builder::new()),
740            utf8_state: RefCell::new(Utf8State::new()),
741            trie_state: RefCell::new(RangeTrie::new()),
742            utf8_suffix: RefCell::new(Utf8SuffixMap::new(1000)),
743        }
744    }
745
746    /// Compile the given regular expression pattern into an NFA.
747    ///
748    /// If there was a problem parsing the regex, then that error is returned.
749    ///
750    /// Otherwise, if there was a problem building the NFA, then an error is
751    /// returned. The only error that can occur is if the compiled regex would
752    /// exceed the size limits configured on this builder, or if any part of
753    /// the NFA would exceed the integer representations used. (For example,
754    /// too many states might plausibly occur on a 16-bit target.)
755    ///
756    /// # Example
757    ///
758    /// ```
759    /// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
760    ///
761    /// let config = NFA::config().nfa_size_limit(Some(1_000));
762    /// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
763    ///
764    /// let re = PikeVM::new_from_nfa(nfa)?;
765    /// let mut cache = re.create_cache();
766    /// let mut caps = re.create_captures();
767    /// let expected = Some(Match::must(0, 3..4));
768    /// re.captures(&mut cache, "!@#A#@!", &mut caps);
769    /// assert_eq!(expected, caps.get_match());
770    ///
771    /// # Ok::<(), Box<dyn std::error::Error>>(())
772    /// ```
773    pub fn build(&self, pattern: &str) -> Result<NFA, BuildError> {
774        self.build_many(&[pattern])
775    }
776
777    /// Compile the given regular expression patterns into a single NFA.
778    ///
779    /// When matches are returned, the pattern ID corresponds to the index of
780    /// the pattern in the slice given.
781    ///
782    /// # Example
783    ///
784    /// ```
785    /// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
786    ///
787    /// let config = NFA::config().nfa_size_limit(Some(1_000));
788    /// let nfa = NFA::compiler().configure(config).build_many(&[
789    ///     r"(?-u)\s",
790    ///     r"(?-u)\w",
791    /// ])?;
792    ///
793    /// let re = PikeVM::new_from_nfa(nfa)?;
794    /// let mut cache = re.create_cache();
795    /// let mut caps = re.create_captures();
796    /// let expected = Some(Match::must(1, 1..2));
797    /// re.captures(&mut cache, "!A! !A!", &mut caps);
798    /// assert_eq!(expected, caps.get_match());
799    ///
800    /// # Ok::<(), Box<dyn std::error::Error>>(())
801    /// ```
802    pub fn build_many<P: AsRef<str>>(
803        &self,
804        patterns: &[P],
805    ) -> Result<NFA, BuildError> {
806        let mut hirs = vec![];
807        for p in patterns {
808            hirs.push(
809                self.parser
810                    .build()
811                    .parse(p.as_ref())
812                    .map_err(BuildError::syntax)?,
813            );
814            debug!("parsed: {:?}", p.as_ref());
815        }
816        self.build_many_from_hir(&hirs)
817    }
818
819    /// Compile the given high level intermediate representation of a regular
820    /// expression into an NFA.
821    ///
822    /// If there was a problem building the NFA, then an error is returned. The
823    /// only error that can occur is if the compiled regex would exceed the
824    /// size limits configured on this builder, or if any part of the NFA would
825    /// exceed the integer representations used. (For example, too many states
826    /// might plausibly occur on a 16-bit target.)
827    ///
828    /// # Example
829    ///
830    /// ```
831    /// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
832    /// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
833    ///
834    /// let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![
835    ///     ClassBytesRange::new(b'0', b'9'),
836    ///     ClassBytesRange::new(b'A', b'Z'),
837    ///     ClassBytesRange::new(b'_', b'_'),
838    ///     ClassBytesRange::new(b'a', b'z'),
839    /// ])));
840    ///
841    /// let config = NFA::config().nfa_size_limit(Some(1_000));
842    /// let nfa = NFA::compiler().configure(config).build_from_hir(&hir)?;
843    ///
844    /// let re = PikeVM::new_from_nfa(nfa)?;
845    /// let mut cache = re.create_cache();
846    /// let mut caps = re.create_captures();
847    /// let expected = Some(Match::must(0, 3..4));
848    /// re.captures(&mut cache, "!@#A#@!", &mut caps);
849    /// assert_eq!(expected, caps.get_match());
850    ///
851    /// # Ok::<(), Box<dyn std::error::Error>>(())
852    /// ```
853    pub fn build_from_hir(&self, expr: &Hir) -> Result<NFA, BuildError> {
854        self.build_many_from_hir(&[expr])
855    }
856
857    /// Compile the given high level intermediate representations of regular
858    /// expressions into a single NFA.
859    ///
860    /// When matches are returned, the pattern ID corresponds to the index of
861    /// the pattern in the slice given.
862    ///
863    /// # Example
864    ///
865    /// ```
866    /// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
867    /// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
868    ///
869    /// let hirs = &[
870    ///     Hir::class(Class::Bytes(ClassBytes::new(vec![
871    ///         ClassBytesRange::new(b'\t', b'\r'),
872    ///         ClassBytesRange::new(b' ', b' '),
873    ///     ]))),
874    ///     Hir::class(Class::Bytes(ClassBytes::new(vec![
875    ///         ClassBytesRange::new(b'0', b'9'),
876    ///         ClassBytesRange::new(b'A', b'Z'),
877    ///         ClassBytesRange::new(b'_', b'_'),
878    ///         ClassBytesRange::new(b'a', b'z'),
879    ///     ]))),
880    /// ];
881    ///
882    /// let config = NFA::config().nfa_size_limit(Some(1_000));
883    /// let nfa = NFA::compiler().configure(config).build_many_from_hir(hirs)?;
884    ///
885    /// let re = PikeVM::new_from_nfa(nfa)?;
886    /// let mut cache = re.create_cache();
887    /// let mut caps = re.create_captures();
888    /// let expected = Some(Match::must(1, 1..2));
889    /// re.captures(&mut cache, "!A! !A!", &mut caps);
890    /// assert_eq!(expected, caps.get_match());
891    ///
892    /// # Ok::<(), Box<dyn std::error::Error>>(())
893    /// ```
894    pub fn build_many_from_hir<H: Borrow<Hir>>(
895        &self,
896        exprs: &[H],
897    ) -> Result<NFA, BuildError> {
898        self.compile(exprs)
899    }
900
901    /// Apply the given NFA configuration options to this builder.
902    ///
903    /// # Example
904    ///
905    /// ```
906    /// use regex_automata::nfa::thompson::NFA;
907    ///
908    /// let config = NFA::config().nfa_size_limit(Some(1_000));
909    /// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
910    /// assert_eq!(nfa.pattern_len(), 1);
911    ///
912    /// # Ok::<(), Box<dyn std::error::Error>>(())
913    /// ```
914    pub fn configure(&mut self, config: Config) -> &mut Compiler {
915        self.config = self.config.overwrite(config);
916        self
917    }
918
919    /// Set the syntax configuration for this builder using
920    /// [`syntax::Config`](crate::util::syntax::Config).
921    ///
922    /// This permits setting things like case insensitivity, Unicode and multi
923    /// line mode.
924    ///
925    /// This syntax configuration only applies when an NFA is built directly
926    /// from a pattern string. If an NFA is built from an HIR, then all syntax
927    /// settings are ignored.
928    ///
929    /// # Example
930    ///
931    /// ```
932    /// use regex_automata::{nfa::thompson::NFA, util::syntax};
933    ///
934    /// let syntax_config = syntax::Config::new().unicode(false);
935    /// let nfa = NFA::compiler().syntax(syntax_config).build(r"\w")?;
936    /// // If Unicode were enabled, the number of states would be much bigger.
937    /// assert!(nfa.states().len() < 15);
938    ///
939    /// # Ok::<(), Box<dyn std::error::Error>>(())
940    /// ```
941    pub fn syntax(
942        &mut self,
943        config: crate::util::syntax::Config,
944    ) -> &mut Compiler {
945        config.apply(&mut self.parser);
946        self
947    }
948}
949
950impl Compiler {
951    /// Compile the sequence of HIR expressions given. Pattern IDs are
952    /// allocated starting from 0, in correspondence with the slice given.
953    ///
954    /// It is legal to provide an empty slice. In that case, the NFA returned
955    /// has no patterns and will never match anything.
956    fn compile<H: Borrow<Hir>>(&self, exprs: &[H]) -> Result<NFA, BuildError> {
957        if exprs.len() > PatternID::LIMIT {
958            return Err(BuildError::too_many_patterns(exprs.len()));
959        }
960        if self.config.get_reverse()
961            && self.config.get_which_captures().is_any()
962        {
963            return Err(BuildError::unsupported_captures());
964        }
965
966        self.builder.borrow_mut().clear();
967        self.builder.borrow_mut().set_utf8(self.config.get_utf8());
968        self.builder.borrow_mut().set_reverse(self.config.get_reverse());
969        self.builder
970            .borrow_mut()
971            .set_look_matcher(self.config.get_look_matcher());
972        self.builder
973            .borrow_mut()
974            .set_size_limit(self.config.get_nfa_size_limit())?;
975
976        // We always add an unanchored prefix unless we were specifically told
977        // not to (for tests only), or if we know that the regex is anchored
978        // for all matches. When an unanchored prefix is not added, then the
979        // NFA's anchored and unanchored start states are equivalent.
980        let all_anchored = exprs.iter().all(|e| {
981            let props = e.borrow().properties();
982            if self.config.get_reverse() {
983                props.look_set_suffix().contains(hir::Look::End)
984            } else {
985                props.look_set_prefix().contains(hir::Look::Start)
986            }
987        });
988        let anchored = !self.config.get_unanchored_prefix() || all_anchored;
989        let unanchored_prefix = if anchored {
990            self.c_empty()?
991        } else {
992            self.c_at_least(&Hir::dot(hir::Dot::AnyByte), false, 0)?
993        };
994
995        let compiled = self.c_alt_iter(exprs.iter().map(|e| {
996            let _ = self.start_pattern()?;
997            let one = self.c_cap(0, None, e.borrow())?;
998            let match_state_id = self.add_match()?;
999            self.patch(one.end, match_state_id)?;
1000            let _ = self.finish_pattern(one.start)?;
1001            Ok(ThompsonRef { start: one.start, end: match_state_id })
1002        }))?;
1003        self.patch(unanchored_prefix.end, compiled.start)?;
1004        let nfa = self
1005            .builder
1006            .borrow_mut()
1007            .build(compiled.start, unanchored_prefix.start)?;
1008
1009        debug!("HIR-to-NFA compilation complete, config: {:?}", self.config);
1010        Ok(nfa)
1011    }
1012
1013    /// Compile an arbitrary HIR expression.
1014    fn c(&self, expr: &Hir) -> Result<ThompsonRef, BuildError> {
1015        use regex_syntax::hir::{Class, HirKind::*};
1016
1017        match *expr.kind() {
1018            Empty => self.c_empty(),
1019            Literal(hir::Literal(ref bytes)) => self.c_literal(bytes),
1020            Class(Class::Bytes(ref c)) => self.c_byte_class(c),
1021            Class(Class::Unicode(ref c)) => self.c_unicode_class(c),
1022            Look(ref look) => self.c_look(look),
1023            Repetition(ref rep) => self.c_repetition(rep),
1024            Capture(ref c) => self.c_cap(c.index, c.name.as_deref(), &c.sub),
1025            Concat(ref es) => self.c_concat(es.iter().map(|e| self.c(e))),
1026            Alternation(ref es) => self.c_alt_slice(es),
1027        }
1028    }
1029
1030    /// Compile a concatenation of the sub-expressions yielded by the given
1031    /// iterator. If the iterator yields no elements, then this compiles down
1032    /// to an "empty" state that always matches.
1033    ///
1034    /// If the compiler is in reverse mode, then the expressions given are
1035    /// automatically compiled in reverse.
1036    fn c_concat<I>(&self, mut it: I) -> Result<ThompsonRef, BuildError>
1037    where
1038        I: DoubleEndedIterator<Item = Result<ThompsonRef, BuildError>>,
1039    {
1040        let first = if self.is_reverse() { it.next_back() } else { it.next() };
1041        let ThompsonRef { start, mut end } = match first {
1042            Some(result) => result?,
1043            None => return self.c_empty(),
1044        };
1045        loop {
1046            let next =
1047                if self.is_reverse() { it.next_back() } else { it.next() };
1048            let compiled = match next {
1049                Some(result) => result?,
1050                None => break,
1051            };
1052            self.patch(end, compiled.start)?;
1053            end = compiled.end;
1054        }
1055        Ok(ThompsonRef { start, end })
1056    }
1057
1058    /// Compile an alternation of the given HIR values.
1059    ///
1060    /// This is like 'c_alt_iter', but it accepts a slice of HIR values instead
1061    /// of an iterator of compiled NFA sub-graphs. The point of accepting a
1062    /// slice here is that it opens up some optimization opportunities. For
1063    /// example, if all of the HIR values are literals, then this routine might
1064    /// re-shuffle them to make NFA epsilon closures substantially faster.
1065    fn c_alt_slice(&self, exprs: &[Hir]) -> Result<ThompsonRef, BuildError> {
1066        // self.c_alt_iter(exprs.iter().map(|e| self.c(e)))
1067        let literal_count = exprs
1068            .iter()
1069            .filter(|e| {
1070                matches!(*e.kind(), hir::HirKind::Literal(hir::Literal(_)))
1071            })
1072            .count();
1073        if literal_count <= 1 || literal_count < exprs.len() {
1074            return self.c_alt_iter(exprs.iter().map(|e| self.c(e)));
1075        }
1076
1077        let mut trie = if self.is_reverse() {
1078            LiteralTrie::reverse()
1079        } else {
1080            LiteralTrie::forward()
1081        };
1082        for expr in exprs.iter() {
1083            let literal = match *expr.kind() {
1084                hir::HirKind::Literal(hir::Literal(ref bytes)) => bytes,
1085                _ => unreachable!(),
1086            };
1087            trie.add(literal)?;
1088        }
1089        trie.compile(&mut self.builder.borrow_mut())
1090    }
1091
1092    /// Compile an alternation, where each element yielded by the given
1093    /// iterator represents an item in the alternation. If the iterator yields
1094    /// no elements, then this compiles down to a "fail" state.
1095    ///
1096    /// In an alternation, expressions appearing earlier are "preferred" at
1097    /// match time over expressions appearing later. At least, this is true
1098    /// when using "leftmost first" match semantics. (If "leftmost longest" are
1099    /// ever added in the future, then this preference order of priority would
1100    /// not apply in that mode.)
1101    fn c_alt_iter<I>(&self, mut it: I) -> Result<ThompsonRef, BuildError>
1102    where
1103        I: Iterator<Item = Result<ThompsonRef, BuildError>>,
1104    {
1105        let first = match it.next() {
1106            None => return self.c_fail(),
1107            Some(result) => result?,
1108        };
1109        let second = match it.next() {
1110            None => return Ok(first),
1111            Some(result) => result?,
1112        };
1113
1114        let union = self.add_union()?;
1115        let end = self.add_empty()?;
1116        self.patch(union, first.start)?;
1117        self.patch(first.end, end)?;
1118        self.patch(union, second.start)?;
1119        self.patch(second.end, end)?;
1120        for result in it {
1121            let compiled = result?;
1122            self.patch(union, compiled.start)?;
1123            self.patch(compiled.end, end)?;
1124        }
1125        Ok(ThompsonRef { start: union, end })
1126    }
1127
1128    /// Compile the given capture sub-expression. `expr` should be the
1129    /// sub-expression contained inside the capture. If "capture" states are
1130    /// enabled, then they are added as appropriate.
1131    ///
1132    /// This accepts the pieces of a capture instead of a `hir::Capture` so
1133    /// that it's easy to manufacture a "fake" group when necessary, e.g., for
1134    /// adding the entire pattern as if it were a group in order to create
1135    /// appropriate "capture" states in the NFA.
1136    fn c_cap(
1137        &self,
1138        index: u32,
1139        name: Option<&str>,
1140        expr: &Hir,
1141    ) -> Result<ThompsonRef, BuildError> {
1142        match self.config.get_which_captures() {
1143            // No capture states means we always skip them.
1144            WhichCaptures::None => return self.c(expr),
1145            // Implicit captures states means we only add when index==0 since
1146            // index==0 implies the group is implicit.
1147            WhichCaptures::Implicit if index > 0 => return self.c(expr),
1148            _ => {}
1149        }
1150
1151        let start = self.add_capture_start(index, name)?;
1152        let inner = self.c(expr)?;
1153        let end = self.add_capture_end(index)?;
1154        self.patch(start, inner.start)?;
1155        self.patch(inner.end, end)?;
1156        Ok(ThompsonRef { start, end })
1157    }
1158
1159    /// Compile the given repetition expression. This handles all types of
1160    /// repetitions and greediness.
1161    fn c_repetition(
1162        &self,
1163        rep: &hir::Repetition,
1164    ) -> Result<ThompsonRef, BuildError> {
1165        match (rep.min, rep.max) {
1166            (0, Some(1)) => self.c_zero_or_one(&rep.sub, rep.greedy),
1167            (min, None) => self.c_at_least(&rep.sub, rep.greedy, min),
1168            (min, Some(max)) if min == max => self.c_exactly(&rep.sub, min),
1169            (min, Some(max)) => self.c_bounded(&rep.sub, rep.greedy, min, max),
1170        }
1171    }
1172
1173    /// Compile the given expression such that it matches at least `min` times,
1174    /// but no more than `max` times.
1175    ///
1176    /// When `greedy` is true, then the preference is for the expression to
1177    /// match as much as possible. Otherwise, it will match as little as
1178    /// possible.
1179    fn c_bounded(
1180        &self,
1181        expr: &Hir,
1182        greedy: bool,
1183        min: u32,
1184        max: u32,
1185    ) -> Result<ThompsonRef, BuildError> {
1186        let prefix = self.c_exactly(expr, min)?;
1187        if min == max {
1188            return Ok(prefix);
1189        }
1190
1191        // It is tempting here to compile the rest here as a concatenation
1192        // of zero-or-one matches. i.e., for `a{2,5}`, compile it as if it
1193        // were `aaa?a?a?`. The problem here is that it leads to this program:
1194        //
1195        //     >000000: 61 => 01
1196        //      000001: 61 => 02
1197        //      000002: union(03, 04)
1198        //      000003: 61 => 04
1199        //      000004: union(05, 06)
1200        //      000005: 61 => 06
1201        //      000006: union(07, 08)
1202        //      000007: 61 => 08
1203        //      000008: MATCH
1204        //
1205        // And effectively, once you hit state 2, the epsilon closure will
1206        // include states 3, 5, 6, 7 and 8, which is quite a bit. It is better
1207        // to instead compile it like so:
1208        //
1209        //     >000000: 61 => 01
1210        //      000001: 61 => 02
1211        //      000002: union(03, 08)
1212        //      000003: 61 => 04
1213        //      000004: union(05, 08)
1214        //      000005: 61 => 06
1215        //      000006: union(07, 08)
1216        //      000007: 61 => 08
1217        //      000008: MATCH
1218        //
1219        // So that the epsilon closure of state 2 is now just 3 and 8.
1220        let empty = self.add_empty()?;
1221        let mut prev_end = prefix.end;
1222        for _ in min..max {
1223            let union = if greedy {
1224                self.add_union()
1225            } else {
1226                self.add_union_reverse()
1227            }?;
1228            let compiled = self.c(expr)?;
1229            self.patch(prev_end, union)?;
1230            self.patch(union, compiled.start)?;
1231            self.patch(union, empty)?;
1232            prev_end = compiled.end;
1233        }
1234        self.patch(prev_end, empty)?;
1235        Ok(ThompsonRef { start: prefix.start, end: empty })
1236    }
1237
1238    /// Compile the given expression such that it may be matched `n` or more
1239    /// times, where `n` can be any integer. (Although a particularly large
1240    /// integer is likely to run afoul of any configured size limits.)
1241    ///
1242    /// When `greedy` is true, then the preference is for the expression to
1243    /// match as much as possible. Otherwise, it will match as little as
1244    /// possible.
1245    fn c_at_least(
1246        &self,
1247        expr: &Hir,
1248        greedy: bool,
1249        n: u32,
1250    ) -> Result<ThompsonRef, BuildError> {
1251        if n == 0 {
1252            // When the expression cannot match the empty string, then we
1253            // can get away with something much simpler: just one 'alt'
1254            // instruction that optionally repeats itself. But if the expr
1255            // can match the empty string... see below.
1256            if expr.properties().minimum_len().map_or(false, |len| len > 0) {
1257                let union = if greedy {
1258                    self.add_union()
1259                } else {
1260                    self.add_union_reverse()
1261                }?;
1262                let compiled = self.c(expr)?;
1263                self.patch(union, compiled.start)?;
1264                self.patch(compiled.end, union)?;
1265                return Ok(ThompsonRef { start: union, end: union });
1266            }
1267
1268            // What's going on here? Shouldn't x* be simpler than this? It
1269            // turns out that when implementing leftmost-first (Perl-like)
1270            // match semantics, x* results in an incorrect preference order
1271            // when computing the transitive closure of states if and only if
1272            // 'x' can match the empty string. So instead, we compile x* as
1273            // (x+)?, which preserves the correct preference order.
1274            //
1275            // See: https://github.com/rust-lang/regex/issues/779
1276            let compiled = self.c(expr)?;
1277            let plus = if greedy {
1278                self.add_union()
1279            } else {
1280                self.add_union_reverse()
1281            }?;
1282            self.patch(compiled.end, plus)?;
1283            self.patch(plus, compiled.start)?;
1284
1285            let question = if greedy {
1286                self.add_union()
1287            } else {
1288                self.add_union_reverse()
1289            }?;
1290            let empty = self.add_empty()?;
1291            self.patch(question, compiled.start)?;
1292            self.patch(question, empty)?;
1293            self.patch(plus, empty)?;
1294            Ok(ThompsonRef { start: question, end: empty })
1295        } else if n == 1 {
1296            let compiled = self.c(expr)?;
1297            let union = if greedy {
1298                self.add_union()
1299            } else {
1300                self.add_union_reverse()
1301            }?;
1302            self.patch(compiled.end, union)?;
1303            self.patch(union, compiled.start)?;
1304            Ok(ThompsonRef { start: compiled.start, end: union })
1305        } else {
1306            let prefix = self.c_exactly(expr, n - 1)?;
1307            let last = self.c(expr)?;
1308            let union = if greedy {
1309                self.add_union()
1310            } else {
1311                self.add_union_reverse()
1312            }?;
1313            self.patch(prefix.end, last.start)?;
1314            self.patch(last.end, union)?;
1315            self.patch(union, last.start)?;
1316            Ok(ThompsonRef { start: prefix.start, end: union })
1317        }
1318    }
1319
1320    /// Compile the given expression such that it may be matched zero or one
1321    /// times.
1322    ///
1323    /// When `greedy` is true, then the preference is for the expression to
1324    /// match as much as possible. Otherwise, it will match as little as
1325    /// possible.
1326    fn c_zero_or_one(
1327        &self,
1328        expr: &Hir,
1329        greedy: bool,
1330    ) -> Result<ThompsonRef, BuildError> {
1331        let union =
1332            if greedy { self.add_union() } else { self.add_union_reverse() }?;
1333        let compiled = self.c(expr)?;
1334        let empty = self.add_empty()?;
1335        self.patch(union, compiled.start)?;
1336        self.patch(union, empty)?;
1337        self.patch(compiled.end, empty)?;
1338        Ok(ThompsonRef { start: union, end: empty })
1339    }
1340
1341    /// Compile the given HIR expression exactly `n` times.
1342    fn c_exactly(
1343        &self,
1344        expr: &Hir,
1345        n: u32,
1346    ) -> Result<ThompsonRef, BuildError> {
1347        let it = (0..n).map(|_| self.c(expr));
1348        self.c_concat(it)
1349    }
1350
1351    /// Compile the given byte oriented character class.
1352    ///
1353    /// This uses "sparse" states to represent an alternation between ranges in
1354    /// this character class. We can use "sparse" states instead of stitching
1355    /// together a "union" state because all ranges in a character class have
1356    /// equal priority *and* are non-overlapping (thus, only one can match, so
1357    /// there's never a question of priority in the first place). This saves a
1358    /// fair bit of overhead when traversing an NFA.
1359    ///
1360    /// This routine compiles an empty character class into a "fail" state.
1361    fn c_byte_class(
1362        &self,
1363        cls: &hir::ClassBytes,
1364    ) -> Result<ThompsonRef, BuildError> {
1365        let end = self.add_empty()?;
1366        let mut trans = Vec::with_capacity(cls.ranges().len());
1367        for r in cls.iter() {
1368            trans.push(Transition {
1369                start: r.start(),
1370                end: r.end(),
1371                next: end,
1372            });
1373        }
1374        Ok(ThompsonRef { start: self.add_sparse(trans)?, end })
1375    }
1376
1377    /// Compile the given Unicode character class.
1378    ///
1379    /// This routine specifically tries to use various types of compression,
1380    /// since UTF-8 automata of large classes can get quite large. The specific
1381    /// type of compression used depends on forward vs reverse compilation, and
1382    /// whether NFA shrinking is enabled or not.
1383    ///
1384    /// Aside from repetitions causing lots of repeat group, this is like the
1385    /// single most expensive part of regex compilation. Therefore, a large part
1386    /// of the expense of compilation may be reduce by disabling Unicode in the
1387    /// pattern.
1388    ///
1389    /// This routine compiles an empty character class into a "fail" state.
1390    fn c_unicode_class(
1391        &self,
1392        cls: &hir::ClassUnicode,
1393    ) -> Result<ThompsonRef, BuildError> {
1394        // If all we have are ASCII ranges wrapped in a Unicode package, then
1395        // there is zero reason to bring out the big guns. We can fit all ASCII
1396        // ranges within a single sparse state.
1397        if cls.is_ascii() {
1398            let end = self.add_empty()?;
1399            let mut trans = Vec::with_capacity(cls.ranges().len());
1400            for r in cls.iter() {
1401                // The unwraps below are OK because we've verified that this
1402                // class only contains ASCII codepoints.
1403                trans.push(Transition {
1404                    // FIXME(1.59): use the 'TryFrom<char> for u8' impl.
1405                    start: u8::try_from(u32::from(r.start())).unwrap(),
1406                    end: u8::try_from(u32::from(r.end())).unwrap(),
1407                    next: end,
1408                });
1409            }
1410            Ok(ThompsonRef { start: self.add_sparse(trans)?, end })
1411        } else if self.is_reverse() {
1412            if !self.config.get_shrink() {
1413                // When we don't want to spend the extra time shrinking, we
1414                // compile the UTF-8 automaton in reverse using something like
1415                // the "naive" approach, but will attempt to re-use common
1416                // suffixes.
1417                self.c_unicode_class_reverse_with_suffix(cls)
1418            } else {
1419                // When we want to shrink our NFA for reverse UTF-8 automata,
1420                // we cannot feed UTF-8 sequences directly to the UTF-8
1421                // compiler, since the UTF-8 compiler requires all sequences
1422                // to be lexicographically sorted. Instead, we organize our
1423                // sequences into a range trie, which can then output our
1424                // sequences in the correct order. Unfortunately, building the
1425                // range trie is fairly expensive (but not nearly as expensive
1426                // as building a DFA). Hence the reason why the 'shrink' option
1427                // exists, so that this path can be toggled off. For example,
1428                // we might want to turn this off if we know we won't be
1429                // compiling a DFA.
1430                let mut trie = self.trie_state.borrow_mut();
1431                trie.clear();
1432
1433                for rng in cls.iter() {
1434                    for mut seq in Utf8Sequences::new(rng.start(), rng.end()) {
1435                        seq.reverse();
1436                        trie.insert(seq.as_slice());
1437                    }
1438                }
1439                let mut builder = self.builder.borrow_mut();
1440                let mut utf8_state = self.utf8_state.borrow_mut();
1441                let mut utf8c =
1442                    Utf8Compiler::new(&mut *builder, &mut *utf8_state)?;
1443                trie.iter(|seq| {
1444                    utf8c.add(&seq)?;
1445                    Ok(())
1446                })?;
1447                utf8c.finish()
1448            }
1449        } else {
1450            // In the forward direction, we always shrink our UTF-8 automata
1451            // because we can stream it right into the UTF-8 compiler. There
1452            // is almost no downside (in either memory or time) to using this
1453            // approach.
1454            let mut builder = self.builder.borrow_mut();
1455            let mut utf8_state = self.utf8_state.borrow_mut();
1456            let mut utf8c =
1457                Utf8Compiler::new(&mut *builder, &mut *utf8_state)?;
1458            for rng in cls.iter() {
1459                for seq in Utf8Sequences::new(rng.start(), rng.end()) {
1460                    utf8c.add(seq.as_slice())?;
1461                }
1462            }
1463            utf8c.finish()
1464        }
1465
1466        // For reference, the code below is the "naive" version of compiling a
1467        // UTF-8 automaton. It is deliciously simple (and works for both the
1468        // forward and reverse cases), but will unfortunately produce very
1469        // large NFAs. When compiling a forward automaton, the size difference
1470        // can sometimes be an order of magnitude. For example, the '\w' regex
1471        // will generate about ~3000 NFA states using the naive approach below,
1472        // but only 283 states when using the approach above. This is because
1473        // the approach above actually compiles a *minimal* (or near minimal,
1474        // because of the bounded hashmap for reusing equivalent states) UTF-8
1475        // automaton.
1476        //
1477        // The code below is kept as a reference point in order to make it
1478        // easier to understand the higher level goal here. Although, it will
1479        // almost certainly bit-rot, so keep that in mind. Also, if you try to
1480        // use it, some of the tests in this module will fail because they look
1481        // for terser byte code produce by the more optimized handling above.
1482        // But the integration test suite should still pass.
1483        //
1484        // One good example of the substantial difference this can make is to
1485        // compare and contrast performance of the Pike VM when the code below
1486        // is active vs the code above. Here's an example to try:
1487        //
1488        //   regex-cli find match pikevm -b -p '(?m)^\w{20}' non-ascii-file
1489        //
1490        // With Unicode classes generated below, this search takes about 45s on
1491        // my machine. But with the compressed version above, the search takes
1492        // only around 1.4s. The NFA is also 20% smaller. This is in part due
1493        // to the compression, but also because of the utilization of 'sparse'
1494        // NFA states. They lead to much less state shuffling during the NFA
1495        // search.
1496        /*
1497        let it = cls
1498            .iter()
1499            .flat_map(|rng| Utf8Sequences::new(rng.start(), rng.end()))
1500            .map(|seq| {
1501                let it = seq
1502                    .as_slice()
1503                    .iter()
1504                    .map(|rng| self.c_range(rng.start, rng.end));
1505                self.c_concat(it)
1506            });
1507        self.c_alt_iter(it)
1508        */
1509    }
1510
1511    /// Compile the given Unicode character class in reverse with suffix
1512    /// caching.
1513    ///
1514    /// This is a "quick" way to compile large Unicode classes into reverse
1515    /// UTF-8 automata while doing a small amount of compression on that
1516    /// automata by reusing common suffixes.
1517    ///
1518    /// A more comprehensive compression scheme can be accomplished by using
1519    /// a range trie to efficiently sort a reverse sequence of UTF-8 byte
1520    /// ranges, and then use Daciuk's algorithm via `Utf8Compiler`.
1521    ///
1522    /// This is the technique used when "NFA shrinking" is disabled.
1523    ///
1524    /// (This also tries to use "sparse" states where possible, just like
1525    /// `c_byte_class` does.)
1526    fn c_unicode_class_reverse_with_suffix(
1527        &self,
1528        cls: &hir::ClassUnicode,
1529    ) -> Result<ThompsonRef, BuildError> {
1530        // N.B. It would likely be better to cache common *prefixes* in the
1531        // reverse direction, but it's not quite clear how to do that. The
1532        // advantage of caching suffixes is that it does give us a win, and
1533        // has a very small additional overhead.
1534        let mut cache = self.utf8_suffix.borrow_mut();
1535        cache.clear();
1536
1537        let union = self.add_union()?;
1538        let alt_end = self.add_empty()?;
1539        for urng in cls.iter() {
1540            for seq in Utf8Sequences::new(urng.start(), urng.end()) {
1541                let mut end = alt_end;
1542                for brng in seq.as_slice() {
1543                    let key = Utf8SuffixKey {
1544                        from: end,
1545                        start: brng.start,
1546                        end: brng.end,
1547                    };
1548                    let hash = cache.hash(&key);
1549                    if let Some(id) = cache.get(&key, hash) {
1550                        end = id;
1551                        continue;
1552                    }
1553
1554                    let compiled = self.c_range(brng.start, brng.end)?;
1555                    self.patch(compiled.end, end)?;
1556                    end = compiled.start;
1557                    cache.set(key, hash, end);
1558                }
1559                self.patch(union, end)?;
1560            }
1561        }
1562        Ok(ThompsonRef { start: union, end: alt_end })
1563    }
1564
1565    /// Compile the given HIR look-around assertion to an NFA look-around
1566    /// assertion.
1567    fn c_look(&self, anchor: &hir::Look) -> Result<ThompsonRef, BuildError> {
1568        let look = match *anchor {
1569            hir::Look::Start => Look::Start,
1570            hir::Look::End => Look::End,
1571            hir::Look::StartLF => Look::StartLF,
1572            hir::Look::EndLF => Look::EndLF,
1573            hir::Look::StartCRLF => Look::StartCRLF,
1574            hir::Look::EndCRLF => Look::EndCRLF,
1575            hir::Look::WordAscii => Look::WordAscii,
1576            hir::Look::WordAsciiNegate => Look::WordAsciiNegate,
1577            hir::Look::WordUnicode => Look::WordUnicode,
1578            hir::Look::WordUnicodeNegate => Look::WordUnicodeNegate,
1579            hir::Look::WordStartAscii => Look::WordStartAscii,
1580            hir::Look::WordEndAscii => Look::WordEndAscii,
1581            hir::Look::WordStartUnicode => Look::WordStartUnicode,
1582            hir::Look::WordEndUnicode => Look::WordEndUnicode,
1583            hir::Look::WordStartHalfAscii => Look::WordStartHalfAscii,
1584            hir::Look::WordEndHalfAscii => Look::WordEndHalfAscii,
1585            hir::Look::WordStartHalfUnicode => Look::WordStartHalfUnicode,
1586            hir::Look::WordEndHalfUnicode => Look::WordEndHalfUnicode,
1587        };
1588        let id = self.add_look(look)?;
1589        Ok(ThompsonRef { start: id, end: id })
1590    }
1591
1592    /// Compile the given byte string to a concatenation of bytes.
1593    fn c_literal(&self, bytes: &[u8]) -> Result<ThompsonRef, BuildError> {
1594        self.c_concat(bytes.iter().copied().map(|b| self.c_range(b, b)))
1595    }
1596
1597    /// Compile a "range" state with one transition that may only be followed
1598    /// if the input byte is in the (inclusive) range given.
1599    ///
1600    /// Both the `start` and `end` locations point to the state created.
1601    /// Callers will likely want to keep the `start`, but patch the `end` to
1602    /// point to some other state.
1603    fn c_range(&self, start: u8, end: u8) -> Result<ThompsonRef, BuildError> {
1604        let id = self.add_range(start, end)?;
1605        Ok(ThompsonRef { start: id, end: id })
1606    }
1607
1608    /// Compile an "empty" state with one unconditional epsilon transition.
1609    ///
1610    /// Both the `start` and `end` locations point to the state created.
1611    /// Callers will likely want to keep the `start`, but patch the `end` to
1612    /// point to some other state.
1613    fn c_empty(&self) -> Result<ThompsonRef, BuildError> {
1614        let id = self.add_empty()?;
1615        Ok(ThompsonRef { start: id, end: id })
1616    }
1617
1618    /// Compile a "fail" state that can never have any outgoing transitions.
1619    fn c_fail(&self) -> Result<ThompsonRef, BuildError> {
1620        let id = self.add_fail()?;
1621        Ok(ThompsonRef { start: id, end: id })
1622    }
1623
1624    // The below helpers are meant to be simple wrappers around the
1625    // corresponding Builder methods. For the most part, they let us write
1626    // 'self.add_foo()' instead of 'self.builder.borrow_mut().add_foo()', where
1627    // the latter is a mouthful. Some of the methods do inject a little bit
1628    // of extra logic. e.g., Flipping look-around operators when compiling in
1629    // reverse mode.
1630
1631    fn patch(&self, from: StateID, to: StateID) -> Result<(), BuildError> {
1632        self.builder.borrow_mut().patch(from, to)
1633    }
1634
1635    fn start_pattern(&self) -> Result<PatternID, BuildError> {
1636        self.builder.borrow_mut().start_pattern()
1637    }
1638
1639    fn finish_pattern(
1640        &self,
1641        start_id: StateID,
1642    ) -> Result<PatternID, BuildError> {
1643        self.builder.borrow_mut().finish_pattern(start_id)
1644    }
1645
1646    fn add_empty(&self) -> Result<StateID, BuildError> {
1647        self.builder.borrow_mut().add_empty()
1648    }
1649
1650    fn add_range(&self, start: u8, end: u8) -> Result<StateID, BuildError> {
1651        self.builder.borrow_mut().add_range(Transition {
1652            start,
1653            end,
1654            next: StateID::ZERO,
1655        })
1656    }
1657
1658    fn add_sparse(
1659        &self,
1660        ranges: Vec<Transition>,
1661    ) -> Result<StateID, BuildError> {
1662        self.builder.borrow_mut().add_sparse(ranges)
1663    }
1664
1665    fn add_look(&self, mut look: Look) -> Result<StateID, BuildError> {
1666        if self.is_reverse() {
1667            look = look.reversed();
1668        }
1669        self.builder.borrow_mut().add_look(StateID::ZERO, look)
1670    }
1671
1672    fn add_union(&self) -> Result<StateID, BuildError> {
1673        self.builder.borrow_mut().add_union(vec![])
1674    }
1675
1676    fn add_union_reverse(&self) -> Result<StateID, BuildError> {
1677        self.builder.borrow_mut().add_union_reverse(vec![])
1678    }
1679
1680    fn add_capture_start(
1681        &self,
1682        capture_index: u32,
1683        name: Option<&str>,
1684    ) -> Result<StateID, BuildError> {
1685        let name = name.map(Arc::from);
1686        self.builder.borrow_mut().add_capture_start(
1687            StateID::ZERO,
1688            capture_index,
1689            name,
1690        )
1691    }
1692
1693    fn add_capture_end(
1694        &self,
1695        capture_index: u32,
1696    ) -> Result<StateID, BuildError> {
1697        self.builder.borrow_mut().add_capture_end(StateID::ZERO, capture_index)
1698    }
1699
1700    fn add_fail(&self) -> Result<StateID, BuildError> {
1701        self.builder.borrow_mut().add_fail()
1702    }
1703
1704    fn add_match(&self) -> Result<StateID, BuildError> {
1705        self.builder.borrow_mut().add_match()
1706    }
1707
1708    fn is_reverse(&self) -> bool {
1709        self.config.get_reverse()
1710    }
1711}
1712
1713/// A value that represents the result of compiling a sub-expression of a
1714/// regex's HIR. Specifically, this represents a sub-graph of the NFA that
1715/// has an initial state at `start` and a final state at `end`.
1716#[derive(Clone, Copy, Debug)]
1717pub(crate) struct ThompsonRef {
1718    pub(crate) start: StateID,
1719    pub(crate) end: StateID,
1720}
1721
1722/// A UTF-8 compiler based on Daciuk's algorithm for compiling minimal DFAs
1723/// from a lexicographically sorted sequence of strings in linear time.
1724///
1725/// The trick here is that any Unicode codepoint range can be converted to
1726/// a sequence of byte ranges that form a UTF-8 automaton. Connecting them
1727/// together via an alternation is trivial, and indeed, it works. However,
1728/// there is a lot of redundant structure in many UTF-8 automatons. Since our
1729/// UTF-8 ranges are in lexicographic order, we can use Daciuk's algorithm
1730/// to build nearly minimal DFAs in linear time. (They are guaranteed to be
1731/// minimal because we use a bounded cache of previously build DFA states.)
1732///
1733/// The drawback is that this sadly doesn't work for reverse automata, since
1734/// the ranges are no longer in lexicographic order. For that, we invented the
1735/// range trie (which gets its own module). Once a range trie is built, we then
1736/// use this same Utf8Compiler to build a reverse UTF-8 automaton.
1737///
1738/// The high level idea is described here:
1739/// https://blog.burntsushi.net/transducers/#finite-state-machines-as-data-structures
1740///
1741/// There is also another implementation of this in the `fst` crate.
1742#[derive(Debug)]
1743struct Utf8Compiler<'a> {
1744    builder: &'a mut Builder,
1745    state: &'a mut Utf8State,
1746    target: StateID,
1747}
1748
1749#[derive(Clone, Debug)]
1750struct Utf8State {
1751    compiled: Utf8BoundedMap,
1752    uncompiled: Vec<Utf8Node>,
1753}
1754
1755#[derive(Clone, Debug)]
1756struct Utf8Node {
1757    trans: Vec<Transition>,
1758    last: Option<Utf8LastTransition>,
1759}
1760
1761#[derive(Clone, Debug)]
1762struct Utf8LastTransition {
1763    start: u8,
1764    end: u8,
1765}
1766
1767impl Utf8State {
1768    fn new() -> Utf8State {
1769        Utf8State { compiled: Utf8BoundedMap::new(10_000), uncompiled: vec![] }
1770    }
1771
1772    fn clear(&mut self) {
1773        self.compiled.clear();
1774        self.uncompiled.clear();
1775    }
1776}
1777
1778impl<'a> Utf8Compiler<'a> {
1779    fn new(
1780        builder: &'a mut Builder,
1781        state: &'a mut Utf8State,
1782    ) -> Result<Utf8Compiler<'a>, BuildError> {
1783        let target = builder.add_empty()?;
1784        state.clear();
1785        let mut utf8c = Utf8Compiler { builder, state, target };
1786        utf8c.add_empty();
1787        Ok(utf8c)
1788    }
1789
1790    fn finish(&mut self) -> Result<ThompsonRef, BuildError> {
1791        self.compile_from(0)?;
1792        let node = self.pop_root();
1793        let start = self.compile(node)?;
1794        Ok(ThompsonRef { start, end: self.target })
1795    }
1796
1797    fn add(&mut self, ranges: &[Utf8Range]) -> Result<(), BuildError> {
1798        let prefix_len = ranges
1799            .iter()
1800            .zip(&self.state.uncompiled)
1801            .take_while(|&(range, node)| {
1802                node.last.as_ref().map_or(false, |t| {
1803                    (t.start, t.end) == (range.start, range.end)
1804                })
1805            })
1806            .count();
1807        assert!(prefix_len < ranges.len());
1808        self.compile_from(prefix_len)?;
1809        self.add_suffix(&ranges[prefix_len..]);
1810        Ok(())
1811    }
1812
1813    fn compile_from(&mut self, from: usize) -> Result<(), BuildError> {
1814        let mut next = self.target;
1815        while from + 1 < self.state.uncompiled.len() {
1816            let node = self.pop_freeze(next);
1817            next = self.compile(node)?;
1818        }
1819        self.top_last_freeze(next);
1820        Ok(())
1821    }
1822
1823    fn compile(
1824        &mut self,
1825        node: Vec<Transition>,
1826    ) -> Result<StateID, BuildError> {
1827        let hash = self.state.compiled.hash(&node);
1828        if let Some(id) = self.state.compiled.get(&node, hash) {
1829            return Ok(id);
1830        }
1831        let id = self.builder.add_sparse(node.clone())?;
1832        self.state.compiled.set(node, hash, id);
1833        Ok(id)
1834    }
1835
1836    fn add_suffix(&mut self, ranges: &[Utf8Range]) {
1837        assert!(!ranges.is_empty());
1838        let last = self
1839            .state
1840            .uncompiled
1841            .len()
1842            .checked_sub(1)
1843            .expect("non-empty nodes");
1844        assert!(self.state.uncompiled[last].last.is_none());
1845        self.state.uncompiled[last].last = Some(Utf8LastTransition {
1846            start: ranges[0].start,
1847            end: ranges[0].end,
1848        });
1849        for r in &ranges[1..] {
1850            self.state.uncompiled.push(Utf8Node {
1851                trans: vec![],
1852                last: Some(Utf8LastTransition { start: r.start, end: r.end }),
1853            });
1854        }
1855    }
1856
1857    fn add_empty(&mut self) {
1858        self.state.uncompiled.push(Utf8Node { trans: vec![], last: None });
1859    }
1860
1861    fn pop_freeze(&mut self, next: StateID) -> Vec<Transition> {
1862        let mut uncompiled = self.state.uncompiled.pop().unwrap();
1863        uncompiled.set_last_transition(next);
1864        uncompiled.trans
1865    }
1866
1867    fn pop_root(&mut self) -> Vec<Transition> {
1868        assert_eq!(self.state.uncompiled.len(), 1);
1869        assert!(self.state.uncompiled[0].last.is_none());
1870        self.state.uncompiled.pop().expect("non-empty nodes").trans
1871    }
1872
1873    fn top_last_freeze(&mut self, next: StateID) {
1874        let last = self
1875            .state
1876            .uncompiled
1877            .len()
1878            .checked_sub(1)
1879            .expect("non-empty nodes");
1880        self.state.uncompiled[last].set_last_transition(next);
1881    }
1882}
1883
1884impl Utf8Node {
1885    fn set_last_transition(&mut self, next: StateID) {
1886        if let Some(last) = self.last.take() {
1887            self.trans.push(Transition {
1888                start: last.start,
1889                end: last.end,
1890                next,
1891            });
1892        }
1893    }
1894}
1895
1896#[cfg(test)]
1897mod tests {
1898    use alloc::vec;
1899
1900    use crate::{
1901        nfa::thompson::{SparseTransitions, State},
1902        util::primitives::SmallIndex,
1903    };
1904
1905    use super::*;
1906
1907    fn build(pattern: &str) -> NFA {
1908        NFA::compiler()
1909            .configure(
1910                NFA::config()
1911                    .which_captures(WhichCaptures::None)
1912                    .unanchored_prefix(false),
1913            )
1914            .build(pattern)
1915            .unwrap()
1916    }
1917
1918    fn pid(id: usize) -> PatternID {
1919        PatternID::new(id).unwrap()
1920    }
1921
1922    fn sid(id: usize) -> StateID {
1923        StateID::new(id).unwrap()
1924    }
1925
1926    fn s_byte(byte: u8, next: usize) -> State {
1927        let next = sid(next);
1928        let trans = Transition { start: byte, end: byte, next };
1929        State::ByteRange { trans }
1930    }
1931
1932    fn s_range(start: u8, end: u8, next: usize) -> State {
1933        let next = sid(next);
1934        let trans = Transition { start, end, next };
1935        State::ByteRange { trans }
1936    }
1937
1938    fn s_sparse(transitions: &[(u8, u8, usize)]) -> State {
1939        let transitions = transitions
1940            .iter()
1941            .map(|&(start, end, next)| Transition {
1942                start,
1943                end,
1944                next: sid(next),
1945            })
1946            .collect();
1947        State::Sparse(SparseTransitions { transitions })
1948    }
1949
1950    fn s_look(look: Look, next: usize) -> State {
1951        let next = sid(next);
1952        State::Look { look, next }
1953    }
1954
1955    fn s_bin_union(alt1: usize, alt2: usize) -> State {
1956        State::BinaryUnion { alt1: sid(alt1), alt2: sid(alt2) }
1957    }
1958
1959    fn s_union(alts: &[usize]) -> State {
1960        State::Union {
1961            alternates: alts
1962                .iter()
1963                .map(|&id| sid(id))
1964                .collect::<Vec<StateID>>()
1965                .into_boxed_slice(),
1966        }
1967    }
1968
1969    fn s_cap(next: usize, pattern: usize, index: usize, slot: usize) -> State {
1970        State::Capture {
1971            next: sid(next),
1972            pattern_id: pid(pattern),
1973            group_index: SmallIndex::new(index).unwrap(),
1974            slot: SmallIndex::new(slot).unwrap(),
1975        }
1976    }
1977
1978    fn s_fail() -> State {
1979        State::Fail
1980    }
1981
1982    fn s_match(id: usize) -> State {
1983        State::Match { pattern_id: pid(id) }
1984    }
1985
1986    // Test that building an unanchored NFA has an appropriate `(?s:.)*?`
1987    // prefix.
1988    #[test]
1989    fn compile_unanchored_prefix() {
1990        let nfa = NFA::compiler()
1991            .configure(NFA::config().which_captures(WhichCaptures::None))
1992            .build(r"a")
1993            .unwrap();
1994        assert_eq!(
1995            nfa.states(),
1996            &[
1997                s_bin_union(2, 1),
1998                s_range(0, 255, 0),
1999                s_byte(b'a', 3),
2000                s_match(0),
2001            ]
2002        );
2003    }
2004
2005    #[test]
2006    fn compile_no_unanchored_prefix_with_start_anchor() {
2007        let nfa = NFA::compiler()
2008            .configure(NFA::config().which_captures(WhichCaptures::None))
2009            .build(r"^a")
2010            .unwrap();
2011        assert_eq!(
2012            nfa.states(),
2013            &[s_look(Look::Start, 1), s_byte(b'a', 2), s_match(0)]
2014        );
2015    }
2016
2017    #[test]
2018    fn compile_yes_unanchored_prefix_with_end_anchor() {
2019        let nfa = NFA::compiler()
2020            .configure(NFA::config().which_captures(WhichCaptures::None))
2021            .build(r"a$")
2022            .unwrap();
2023        assert_eq!(
2024            nfa.states(),
2025            &[
2026                s_bin_union(2, 1),
2027                s_range(0, 255, 0),
2028                s_byte(b'a', 3),
2029                s_look(Look::End, 4),
2030                s_match(0),
2031            ]
2032        );
2033    }
2034
2035    #[test]
2036    fn compile_yes_reverse_unanchored_prefix_with_start_anchor() {
2037        let nfa = NFA::compiler()
2038            .configure(
2039                NFA::config()
2040                    .reverse(true)
2041                    .which_captures(WhichCaptures::None),
2042            )
2043            .build(r"^a")
2044            .unwrap();
2045        assert_eq!(
2046            nfa.states(),
2047            &[
2048                s_bin_union(2, 1),
2049                s_range(0, 255, 0),
2050                s_byte(b'a', 3),
2051                // Anchors get flipped in a reverse automaton.
2052                s_look(Look::End, 4),
2053                s_match(0),
2054            ],
2055        );
2056    }
2057
2058    #[test]
2059    fn compile_no_reverse_unanchored_prefix_with_end_anchor() {
2060        let nfa = NFA::compiler()
2061            .configure(
2062                NFA::config()
2063                    .reverse(true)
2064                    .which_captures(WhichCaptures::None),
2065            )
2066            .build(r"a$")
2067            .unwrap();
2068        assert_eq!(
2069            nfa.states(),
2070            &[
2071                // Anchors get flipped in a reverse automaton.
2072                s_look(Look::Start, 1),
2073                s_byte(b'a', 2),
2074                s_match(0),
2075            ],
2076        );
2077    }
2078
2079    #[test]
2080    fn compile_empty() {
2081        assert_eq!(build("").states(), &[s_match(0),]);
2082    }
2083
2084    #[test]
2085    fn compile_literal() {
2086        assert_eq!(build("a").states(), &[s_byte(b'a', 1), s_match(0),]);
2087        assert_eq!(
2088            build("ab").states(),
2089            &[s_byte(b'a', 1), s_byte(b'b', 2), s_match(0),]
2090        );
2091        assert_eq!(
2092            build("☃").states(),
2093            &[s_byte(0xE2, 1), s_byte(0x98, 2), s_byte(0x83, 3), s_match(0)]
2094        );
2095
2096        // Check that non-UTF-8 literals work.
2097        let nfa = NFA::compiler()
2098            .configure(
2099                NFA::config()
2100                    .which_captures(WhichCaptures::None)
2101                    .unanchored_prefix(false),
2102            )
2103            .syntax(crate::util::syntax::Config::new().utf8(false))
2104            .build(r"(?-u)\xFF")
2105            .unwrap();
2106        assert_eq!(nfa.states(), &[s_byte(b'\xFF', 1), s_match(0),]);
2107    }
2108
2109    #[test]
2110    fn compile_class_ascii() {
2111        assert_eq!(
2112            build(r"[a-z]").states(),
2113            &[s_range(b'a', b'z', 1), s_match(0),]
2114        );
2115        assert_eq!(
2116            build(r"[x-za-c]").states(),
2117            &[s_sparse(&[(b'a', b'c', 1), (b'x', b'z', 1)]), s_match(0)]
2118        );
2119    }
2120
2121    #[test]
2122    #[cfg(not(miri))]
2123    fn compile_class_unicode() {
2124        assert_eq!(
2125            build(r"[\u03B1-\u03B4]").states(),
2126            &[s_range(0xB1, 0xB4, 2), s_byte(0xCE, 0), s_match(0)]
2127        );
2128        assert_eq!(
2129            build(r"[\u03B1-\u03B4\u{1F919}-\u{1F91E}]").states(),
2130            &[
2131                s_range(0xB1, 0xB4, 5),
2132                s_range(0x99, 0x9E, 5),
2133                s_byte(0xA4, 1),
2134                s_byte(0x9F, 2),
2135                s_sparse(&[(0xCE, 0xCE, 0), (0xF0, 0xF0, 3)]),
2136                s_match(0),
2137            ]
2138        );
2139        assert_eq!(
2140            build(r"[a-z☃]").states(),
2141            &[
2142                s_byte(0x83, 3),
2143                s_byte(0x98, 0),
2144                s_sparse(&[(b'a', b'z', 3), (0xE2, 0xE2, 1)]),
2145                s_match(0),
2146            ]
2147        );
2148    }
2149
2150    #[test]
2151    fn compile_repetition() {
2152        assert_eq!(
2153            build(r"a?").states(),
2154            &[s_bin_union(1, 2), s_byte(b'a', 2), s_match(0),]
2155        );
2156        assert_eq!(
2157            build(r"a??").states(),
2158            &[s_bin_union(2, 1), s_byte(b'a', 2), s_match(0),]
2159        );
2160    }
2161
2162    #[test]
2163    fn compile_group() {
2164        assert_eq!(
2165            build(r"ab+").states(),
2166            &[s_byte(b'a', 1), s_byte(b'b', 2), s_bin_union(1, 3), s_match(0)]
2167        );
2168        assert_eq!(
2169            build(r"(ab)").states(),
2170            &[s_byte(b'a', 1), s_byte(b'b', 2), s_match(0)]
2171        );
2172        assert_eq!(
2173            build(r"(ab)+").states(),
2174            &[s_byte(b'a', 1), s_byte(b'b', 2), s_bin_union(0, 3), s_match(0)]
2175        );
2176    }
2177
2178    #[test]
2179    fn compile_alternation() {
2180        assert_eq!(
2181            build(r"a|b").states(),
2182            &[s_range(b'a', b'b', 1), s_match(0)]
2183        );
2184        assert_eq!(
2185            build(r"ab|cd").states(),
2186            &[
2187                s_byte(b'b', 3),
2188                s_byte(b'd', 3),
2189                s_sparse(&[(b'a', b'a', 0), (b'c', b'c', 1)]),
2190                s_match(0)
2191            ],
2192        );
2193        assert_eq!(
2194            build(r"|b").states(),
2195            &[s_byte(b'b', 2), s_bin_union(2, 0), s_match(0)]
2196        );
2197        assert_eq!(
2198            build(r"a|").states(),
2199            &[s_byte(b'a', 2), s_bin_union(0, 2), s_match(0)]
2200        );
2201    }
2202
2203    // This tests the use of a non-binary union, i.e., a state with more than
2204    // 2 unconditional epsilon transitions. The only place they tend to appear
2205    // is in reverse NFAs when shrinking is disabled. Otherwise, 'binary-union'
2206    // and 'sparse' tend to cover all other cases of alternation.
2207    #[test]
2208    fn compile_non_binary_union() {
2209        let nfa = NFA::compiler()
2210            .configure(
2211                NFA::config()
2212                    .which_captures(WhichCaptures::None)
2213                    .reverse(true)
2214                    .shrink(false)
2215                    .unanchored_prefix(false),
2216            )
2217            .build(r"[\u1000\u2000\u3000]")
2218            .unwrap();
2219        assert_eq!(
2220            nfa.states(),
2221            &[
2222                s_union(&[3, 6, 9]),
2223                s_byte(0xE1, 10),
2224                s_byte(0x80, 1),
2225                s_byte(0x80, 2),
2226                s_byte(0xE2, 10),
2227                s_byte(0x80, 4),
2228                s_byte(0x80, 5),
2229                s_byte(0xE3, 10),
2230                s_byte(0x80, 7),
2231                s_byte(0x80, 8),
2232                s_match(0),
2233            ]
2234        );
2235    }
2236
2237    #[test]
2238    fn compile_many_start_pattern() {
2239        let nfa = NFA::compiler()
2240            .configure(
2241                NFA::config()
2242                    .which_captures(WhichCaptures::None)
2243                    .unanchored_prefix(false),
2244            )
2245            .build_many(&["a", "b"])
2246            .unwrap();
2247        assert_eq!(
2248            nfa.states(),
2249            &[
2250                s_byte(b'a', 1),
2251                s_match(0),
2252                s_byte(b'b', 3),
2253                s_match(1),
2254                s_bin_union(0, 2),
2255            ]
2256        );
2257        assert_eq!(nfa.start_anchored().as_usize(), 4);
2258        assert_eq!(nfa.start_unanchored().as_usize(), 4);
2259        // Test that the start states for each individual pattern are correct.
2260        assert_eq!(nfa.start_pattern(pid(0)).unwrap(), sid(0));
2261        assert_eq!(nfa.start_pattern(pid(1)).unwrap(), sid(2));
2262    }
2263
2264    // This tests that our compiler can handle an empty character class. At the
2265    // time of writing, the regex parser forbids it, so the only way to test it
2266    // is to provide a hand written HIR.
2267    #[test]
2268    fn empty_class_bytes() {
2269        use regex_syntax::hir::{Class, ClassBytes, Hir};
2270
2271        let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![])));
2272        let config = NFA::config()
2273            .which_captures(WhichCaptures::None)
2274            .unanchored_prefix(false);
2275        let nfa =
2276            NFA::compiler().configure(config).build_from_hir(&hir).unwrap();
2277        assert_eq!(nfa.states(), &[s_fail(), s_match(0)]);
2278    }
2279
2280    // Like empty_class_bytes, but for a Unicode class.
2281    #[test]
2282    fn empty_class_unicode() {
2283        use regex_syntax::hir::{Class, ClassUnicode, Hir};
2284
2285        let hir = Hir::class(Class::Unicode(ClassUnicode::new(vec![])));
2286        let config = NFA::config()
2287            .which_captures(WhichCaptures::None)
2288            .unanchored_prefix(false);
2289        let nfa =
2290            NFA::compiler().configure(config).build_from_hir(&hir).unwrap();
2291        assert_eq!(nfa.states(), &[s_fail(), s_match(0)]);
2292    }
2293
2294    #[test]
2295    fn compile_captures_all() {
2296        let nfa = NFA::compiler()
2297            .configure(
2298                NFA::config()
2299                    .unanchored_prefix(false)
2300                    .which_captures(WhichCaptures::All),
2301            )
2302            .build("a(b)c")
2303            .unwrap();
2304        assert_eq!(
2305            nfa.states(),
2306            &[
2307                s_cap(1, 0, 0, 0),
2308                s_byte(b'a', 2),
2309                s_cap(3, 0, 1, 2),
2310                s_byte(b'b', 4),
2311                s_cap(5, 0, 1, 3),
2312                s_byte(b'c', 6),
2313                s_cap(7, 0, 0, 1),
2314                s_match(0)
2315            ]
2316        );
2317        let ginfo = nfa.group_info();
2318        assert_eq!(2, ginfo.all_group_len());
2319    }
2320
2321    #[test]
2322    fn compile_captures_implicit() {
2323        let nfa = NFA::compiler()
2324            .configure(
2325                NFA::config()
2326                    .unanchored_prefix(false)
2327                    .which_captures(WhichCaptures::Implicit),
2328            )
2329            .build("a(b)c")
2330            .unwrap();
2331        assert_eq!(
2332            nfa.states(),
2333            &[
2334                s_cap(1, 0, 0, 0),
2335                s_byte(b'a', 2),
2336                s_byte(b'b', 3),
2337                s_byte(b'c', 4),
2338                s_cap(5, 0, 0, 1),
2339                s_match(0)
2340            ]
2341        );
2342        let ginfo = nfa.group_info();
2343        assert_eq!(1, ginfo.all_group_len());
2344    }
2345
2346    #[test]
2347    fn compile_captures_none() {
2348        let nfa = NFA::compiler()
2349            .configure(
2350                NFA::config()
2351                    .unanchored_prefix(false)
2352                    .which_captures(WhichCaptures::None),
2353            )
2354            .build("a(b)c")
2355            .unwrap();
2356        assert_eq!(
2357            nfa.states(),
2358            &[s_byte(b'a', 1), s_byte(b'b', 2), s_byte(b'c', 3), s_match(0)]
2359        );
2360        let ginfo = nfa.group_info();
2361        assert_eq!(0, ginfo.all_group_len());
2362    }
2363}