Debian Codegraph @

third_party/rust/regex-automata/src/util/determinize/mod.rs

raw
1 /*!
2 This module contains types and routines for implementing determinization.
3
4 In this crate, there are at least two places where we implement
5 determinization: fully ahead-of-time compiled DFAs in the `dfa` module and
6 lazily compiled DFAs in the `hybrid` module. The stuff in this module
7 corresponds to the things that are in common between these implementations.
8
9 There are three broad things that our implementations of determinization have
10 in common, as defined by this module:
11
12 * The classification of start states. That is, whether we're dealing with
13 word boundaries, line boundaries, etc., is all the same. This also includes
14 the look-behind assertions that are satisfied by each starting state
15 classification.
16 * The representation of DFA states as sets of NFA states, including
17 convenience types for building these DFA states that are amenable to reusing
18 allocations.
19 * Routines for the "classical" parts of determinization: computing the
20 epsilon closure, tracking match states (with corresponding pattern IDs, since
21 we support multi-pattern finite automata) and, of course, computing the
22 transition function between states for units of input.
23
24 I did consider a couple of alternatives to this particular form of code reuse:
25
26 1. Don't do any code reuse. The problem here is that we *really* want both
27 forms of determinization to do exactly identical things when it comes to
28 their handling of NFA states. While our tests generally ensure this, the code
29 is tricky and large enough where not reusing code is a pretty big bummer.
30
31 2. Implement all of determinization once and make it generic over fully
32 compiled DFAs and lazily compiled DFAs. While I didn't actually try this
33 approach, my instinct is that it would be more complex than is needed here.
34 And the interface required would be pretty hairy. Instead, I think splitting
35 it into logical sub-components works better.
36 */
37
38 use alloc::vec::Vec;
39
40 pub(crate) use self::state::{
41 State, StateBuilderEmpty, StateBuilderMatches, StateBuilderNFA,
42 };
43
44 use crate::{
45 nfa::thompson,
46 util::{
47 alphabet,
48 look::{Look, LookSet},
49 primitives::StateID,
50 search::MatchKind,
51 sparse_set::{SparseSet, SparseSets},
52 start::Start,
53 utf8,
54 },
55 };
56
57 mod state;
58
59 /// Compute the set of all reachable NFA states, including the full epsilon
60 /// closure, from a DFA state for a single unit of input. The set of reachable
61 /// states is returned as a `StateBuilderNFA`. The `StateBuilderNFA` returned
62 /// also includes any look-behind assertions satisfied by `unit`, in addition
63 /// to whether it is a match state. For multi-pattern DFAs, the builder will
64 /// also include the pattern IDs that match (in the order seen).
65 ///
66 /// `nfa` must be able to resolve any NFA state in `state` and any NFA state
67 /// reachable via the epsilon closure of any NFA state in `state`. `sparses`
68 /// must have capacity equivalent to `nfa.len()`.
69 ///
70 /// `match_kind` should correspond to the match semantics implemented by the
71 /// DFA being built. Generally speaking, for leftmost-first match semantics,
72 /// states that appear after the first NFA match state will not be included in
73 /// the `StateBuilderNFA` returned since they are impossible to visit.
74 ///
75 /// `sparses` is used as scratch space for NFA traversal. Other than their
76 /// capacity requirements (detailed above), there are no requirements on what's
77 /// contained within them (if anything). Similarly, what's inside of them once
78 /// this routine returns is unspecified.
79 ///
80 /// `stack` must have length 0. It is used as scratch space for depth first
81 /// traversal. After returning, it is guaranteed that `stack` will have length
82 /// 0.
83 ///
84 /// `state` corresponds to the current DFA state on which one wants to compute
85 /// the transition for the input `unit`.
86 ///
87 /// `empty_builder` corresponds to the builder allocation to use to produce a
88 /// complete `StateBuilderNFA` state. If the state is not needed (or is already
89 /// cached), then it can be cleared and reused without needing to create a new
90 /// `State`. The `StateBuilderNFA` state returned is final and ready to be
91 /// turned into a `State` if necessary.
92 pub(crate) fn next(
93 nfa: &thompson::NFA,
94 match_kind: MatchKind,
95 sparses: &mut SparseSets,
96 stack: &mut Vec<StateID>,
97 state: &State,
98 unit: alphabet::Unit,
99 empty_builder: StateBuilderEmpty,
100 ) -> StateBuilderNFA {
101 sparses.clear();
102
103 // Whether the NFA is matched in reverse or not. We use this in some
104 // conditional logic for dealing with the exceptionally annoying CRLF-aware
105 // line anchors.
106 let rev = nfa.is_reverse();
107 // The look-around matcher that our NFA is configured with. We don't
108 // actually use it to match look-around assertions, but we do need its
109 // configuration for constructing states consistent with how it matches.
110 let lookm = nfa.look_matcher();
111
112 // Put the NFA state IDs into a sparse set in case we need to
113 // re-compute their epsilon closure.
114 //
115 // Doing this state shuffling is technically not necessary unless some
116 // kind of look-around is used in the DFA. Some ad hoc experiments
117 // suggested that avoiding this didn't lead to much of an improvement,
118 // but perhaps more rigorous experimentation should be done. And in
119 // particular, avoiding this check requires some light refactoring of
120 // the code below.
121 state.iter_nfa_state_ids(|nfa_id| {
122 sparses.set1.insert(nfa_id);
123 });
124
125 // Compute look-ahead assertions originating from the current state. Based
126 // on the input unit we're transitioning over, some additional set of
127 // assertions may be true. Thus, we re-compute this state's epsilon closure
128 // (but only if necessary). Notably, when we build a DFA state initially,
129 // we don't enable any look-ahead assertions because we don't know whether
130 // they're true or not at that point.
131 if !state.look_need().is_empty() {
132 // Add look-ahead assertions that are now true based on the current
133 // input unit.
134 let mut look_have = state.look_have().clone();
135 match unit.as_u8() {
136 Some(b'\r') => {
137 if !rev || !state.is_half_crlf() {
138 look_have = look_have.insert(Look::EndCRLF);
139 }
140 }
141 Some(b'\n') => {
142 if rev || !state.is_half_crlf() {
143 look_have = look_have.insert(Look::EndCRLF);
144 }
145 }
146 Some(_) => {}
147 None => {
148 look_have = look_have.insert(Look::End);
149 look_have = look_have.insert(Look::EndLF);
150 look_have = look_have.insert(Look::EndCRLF);
151 }
152 }
153 if unit.is_byte(lookm.get_line_terminator()) {
154 look_have = look_have.insert(Look::EndLF);
155 }
156 if state.is_half_crlf()
157 && ((rev && !unit.is_byte(b'\r'))
158 || (!rev && !unit.is_byte(b'\n')))
159 {
160 look_have = look_have.insert(Look::StartCRLF);
161 }
162 if state.is_from_word() == unit.is_word_byte() {
163 look_have = look_have.insert(Look::WordUnicodeNegate);
164 look_have = look_have.insert(Look::WordAsciiNegate);
165 } else {
166 look_have = look_have.insert(Look::WordUnicode);
167 look_have = look_have.insert(Look::WordAscii);
168 }
169 // If we have new assertions satisfied that are among the set of
170 // assertions that exist in this state (that is, just because we added
171 // an EndLF assertion above doesn't mean there is an EndLF conditional
172 // epsilon transition in this state), then we re-compute this state's
173 // epsilon closure using the updated set of assertions.
174 //
175 // Note that since our DFA states omit unconditional epsilon
176 // transitions, this check is necessary for correctness. If we re-did
177 // the epsilon closure below needlessly, it could change based on the
178 // fact that we omitted epsilon states originally.
179 if !look_have
180 .subtract(state.look_have())
181 .intersect(state.look_need())
182 .is_empty()
183 {
184 for nfa_id in sparses.set1.iter() {
185 epsilon_closure(
186 nfa,
187 nfa_id,
188 look_have,
189 stack,
190 &mut sparses.set2,
191 );
192 }
193 sparses.swap();
194 sparses.set2.clear();
195 }
196 }
197
198 // Convert our empty builder into one that can record assertions and match
199 // pattern IDs.
200 let mut builder = empty_builder.into_matches();
201 // Set whether the StartLF look-behind assertion is true for this
202 // transition or not. The look-behind assertion for ASCII word boundaries
203 // is handled below.
204 if nfa.look_set_any().contains_anchor_line()
205 && unit.is_byte(lookm.get_line_terminator())
206 {
207 // Why only handle StartLF here and not Start? That's because Start
208 // can only impact the starting state, which is special cased in
209 // start state handling.
210 builder.set_look_have(|have| have.insert(Look::StartLF));
211 }
212 // We also need to add StartCRLF to our assertions too, if we can. This
213 // is unfortunately a bit more complicated, because it depends on the
214 // direction of the search. In the forward direction, ^ matches after a
215 // \n, but in the reverse direction, ^ only matches after a \r. (This is
216 // further complicated by the fact that reverse a regex means changing a ^
217 // to a $ and vice versa.)
218 if nfa.look_set_any().contains_anchor_crlf()
219 && ((rev && unit.is_byte(b'\r')) || (!rev && unit.is_byte(b'\n')))
220 {
221 builder.set_look_have(|have| have.insert(Look::StartCRLF));
222 }
223 for nfa_id in sparses.set1.iter() {
224 match *nfa.state(nfa_id) {
225 thompson::State::Union { .. }
226 | thompson::State::BinaryUnion { .. }
227 | thompson::State::Fail
228 | thompson::State::Look { .. }
229 | thompson::State::Capture { .. } => {}
230 thompson::State::Match { pattern_id } => {
231 // Notice here that we are calling the NEW state a match
232 // state if the OLD state we are transitioning from
233 // contains an NFA match state. This is precisely how we
234 // delay all matches by one byte and also what therefore
235 // guarantees that starting states cannot be match states.
236 //
237 // If we didn't delay matches by one byte, then whether
238 // a DFA is a matching state or not would be determined
239 // by whether one of its own constituent NFA states
240 // was a match state. (And that would be done in
241 // 'add_nfa_states'.)
242 //
243 // Also, 'add_match_pattern_id' requires that callers never
244 // pass duplicative pattern IDs. We do in fact uphold that
245 // guarantee here, but it's subtle. In particular, a Thompson
246 // NFA guarantees that each pattern has exactly one match
247 // state. Moreover, since we're iterating over the NFA state
248 // IDs in a set, we are guarateed not to have any duplicative
249 // match states. Thus, it is impossible to add the same pattern
250 // ID more than once.
251 //
252 // N.B. We delay matches by 1 byte as a way to hack 1-byte
253 // look-around into DFA searches. This lets us support ^, $
254 // and ASCII-only \b. The delay is also why we need a special
255 // "end-of-input" (EOI) sentinel and why we need to follow the
256 // EOI sentinel at the end of every search. This final EOI
257 // transition is necessary to report matches found at the end
258 // of a haystack.
259 builder.add_match_pattern_id(pattern_id);
260 if !match_kind.continue_past_first_match() {
261 break;
262 }
263 }
264 thompson::State::ByteRange { ref trans } => {
265 if trans.matches_unit(unit) {
266 epsilon_closure(
267 nfa,
268 trans.next,
269 builder.look_have(),
270 stack,
271 &mut sparses.set2,
272 );
273 }
274 }
275 thompson::State::Sparse(ref sparse) => {
276 if let Some(next) = sparse.matches_unit(unit) {
277 epsilon_closure(
278 nfa,
279 next,
280 builder.look_have(),
281 stack,
282 &mut sparses.set2,
283 );
284 }
285 }
286 thompson::State::Dense(ref dense) => {
287 if let Some(next) = dense.matches_unit(unit) {
288 epsilon_closure(
289 nfa,
290 next,
291 builder.look_have(),
292 stack,
293 &mut sparses.set2,
294 );
295 }
296 }
297 }
298 }
299 // We only set the word byte if there's a word boundary look-around
300 // anywhere in this regex. Otherwise, there's no point in bloating the
301 // number of states if we don't have one.
302 //
303 // We also only set it when the state has a non-zero number of NFA states.
304 // Otherwise, we could wind up with states that *should* be DEAD states
305 // but are otherwise distinct from DEAD states because of this look-behind
306 // assertion being set. While this can't technically impact correctness *in
307 // theory*, it can create pathological DFAs that consume input until EOI or
308 // a quit byte is seen. Consuming until EOI isn't a correctness problem,
309 // but a (serious) perf problem. Hitting a quit byte, however, could be a
310 // correctness problem since it could cause search routines to report an
311 // error instead of a detected match once the quit state is entered. (The
312 // search routine could be made to be a bit smarter by reporting a match
313 // if one was detected once it enters a quit state (and indeed, the search
314 // routines in this crate do just that), but it seems better to prevent
315 // these things by construction if possible.)
316 if !sparses.set2.is_empty() {
317 if nfa.look_set_any().contains_word() && unit.is_word_byte() {
318 builder.set_is_from_word();
319 }
320 if nfa.look_set_any().contains_anchor_crlf()
321 && ((rev && unit.is_byte(b'\n')) || (!rev && unit.is_byte(b'\r')))
322 {
323 builder.set_is_half_crlf();
324 }
325 }
326 let mut builder_nfa = builder.into_nfa();
327 add_nfa_states(nfa, &sparses.set2, &mut builder_nfa);
328 builder_nfa
329 }
330
331 /// Compute the epsilon closure for the given NFA state. The epsilon closure
332 /// consists of all NFA state IDs, including `start_nfa_id`, that can be
333 /// reached from `start_nfa_id` without consuming any input. These state IDs
334 /// are written to `set` in the order they are visited, but only if they are
335 /// not already in `set`. `start_nfa_id` must be a valid state ID for the NFA
336 /// given.
337 ///
338 /// `look_have` consists of the satisfied assertions at the current
339 /// position. For conditional look-around epsilon transitions, these are
340 /// only followed if they are satisfied by `look_have`.
341 ///
342 /// `stack` must have length 0. It is used as scratch space for depth first
343 /// traversal. After returning, it is guaranteed that `stack` will have length
344 /// 0.
345 pub(crate) fn epsilon_closure(
346 nfa: &thompson::NFA,
347 start_nfa_id: StateID,
348 look_have: LookSet,
349 stack: &mut Vec<StateID>,
350 set: &mut SparseSet,
351 ) {
352 assert!(stack.is_empty());
353 // If this isn't an epsilon state, then the epsilon closure is always just
354 // itself, so there's no need to spin up the machinery below to handle it.
355 if !nfa.state(start_nfa_id).is_epsilon() {
356 set.insert(start_nfa_id);
357 return;
358 }
359
360 stack.push(start_nfa_id);
361 while let Some(mut id) = stack.pop() {
362 // In many cases, we can avoid stack operations when an NFA state only
363 // adds one new state to visit. In that case, we just set our ID to
364 // that state and mush on. We only use the stack when an NFA state
365 // introduces multiple new states to visit.
366 loop {
367 // Insert this NFA state, and if it's already in the set and thus
368 // already visited, then we can move on to the next one.
369 if !set.insert(id) {
370 break;
371 }
372 match *nfa.state(id) {
373 thompson::State::ByteRange { .. }
374 | thompson::State::Sparse { .. }
375 | thompson::State::Dense { .. }
376 | thompson::State::Fail
377 | thompson::State::Match { .. } => break,
378 thompson::State::Look { look, next } => {
379 if !look_have.contains(look) {
380 break;
381 }
382 id = next;
383 }
384 thompson::State::Union { ref alternates } => {
385 id = match alternates.get(0) {
386 None => break,
387 Some(&id) => id,
388 };
389 // We need to process our alternates in order to preserve
390 // match preferences, so put the earliest alternates closer
391 // to the top of the stack.
392 stack.extend(alternates[1..].iter().rev());
393 }
394 thompson::State::BinaryUnion { alt1, alt2 } => {
395 id = alt1;
396 stack.push(alt2);
397 }
398 thompson::State::Capture { next, .. } => {
399 id = next;
400 }
401 }
402 }
403 }
404 }
405
406 /// Add the NFA state IDs in the given `set` to the given DFA builder state.
407 /// The order in which states are added corresponds to the order in which they
408 /// were added to `set`.
409 ///
410 /// The DFA builder state given should already have its complete set of match
411 /// pattern IDs added (if any) and any look-behind assertions (StartLF, Start
412 /// and whether this state is being generated for a transition over a word byte
413 /// when applicable) that are true immediately prior to transitioning into this
414 /// state (via `builder.look_have()`). The match pattern IDs should correspond
415 /// to matches that occurred on the previous transition, since all matches are
416 /// delayed by one byte. The things that should _not_ be set are look-ahead
417 /// assertions (EndLF, End and whether the next byte is a word byte or not).
418 /// The builder state should also not have anything in `look_need` set, as this
419 /// routine will compute that for you.
420 ///
421 /// The given NFA should be able to resolve all identifiers in `set` to a
422 /// particular NFA state. Additionally, `set` must have capacity equivalent
423 /// to `nfa.len()`.
424 pub(crate) fn add_nfa_states(
425 nfa: &thompson::NFA,
426 set: &SparseSet,
427 builder: &mut StateBuilderNFA,
428 ) {
429 for nfa_id in set.iter() {
430 match *nfa.state(nfa_id) {
431 thompson::State::ByteRange { .. } => {
432 builder.add_nfa_state_id(nfa_id);
433 }
434 thompson::State::Sparse { .. } => {
435 builder.add_nfa_state_id(nfa_id);
436 }
437 thompson::State::Dense { .. } => {
438 builder.add_nfa_state_id(nfa_id);
439 }
440 thompson::State::Look { look, .. } => {
441 builder.add_nfa_state_id(nfa_id);
442 builder.set_look_need(|need| need.insert(look));
443 }
444 thompson::State::Union { .. }
445 | thompson::State::BinaryUnion { .. } => {
446 // Pure epsilon transitions don't need to be tracked as part
447 // of the DFA state. Tracking them is actually superfluous;
448 // they won't cause any harm other than making determinization
449 // slower.
450 //
451 // Why aren't these needed? Well, in an NFA, epsilon
452 // transitions are really just jumping points to other states.
453 // So once you hit an epsilon transition, the same set of
454 // resulting states always appears. Therefore, putting them in
455 // a DFA's set of ordered NFA states is strictly redundant.
456 //
457 // Look-around states are also epsilon transitions, but
458 // they are *conditional*. So their presence could be
459 // discriminatory, and thus, they are tracked above.
460 //
461 // But wait... why are epsilon states in our `set` in the first
462 // place? Why not just leave them out? They're in our `set`
463 // because it was generated by computing an epsilon closure,
464 // and we want to keep track of all states we visited to avoid
465 // re-visiting them. In exchange, we have to do this second
466 // iteration over our collected states to finalize our DFA
467 // state. In theory, we could avoid this second iteration if
468 // we maintained two sets during epsilon closure: the set of
469 // visited states (to avoid cycles) and the set of states that
470 // will actually be used to construct the next DFA state.
471 //
472 // Note that this optimization requires that we re-compute the
473 // epsilon closure to account for look-ahead in 'next' *only
474 // when necessary*. Namely, only when the set of look-around
475 // assertions changes and only when those changes are within
476 // the set of assertions that are needed in order to step
477 // through the closure correctly. Otherwise, if we re-do the
478 // epsilon closure needlessly, it could change based on the
479 // fact that we are omitting epsilon states here.
480 //
481 // -----
482 //
483 // Welp, scratch the above. It turns out that recording these
484 // is in fact necessary to seemingly handle one particularly
485 // annoying case: when a conditional epsilon transition is
486 // put inside of a repetition operator. One specific case I
487 // ran into was the regex `(?:\b|%)+` on the haystack `z%`.
488 // The correct leftmost first matches are: [0, 0] and [1, 1].
489 // But the DFA was reporting [0, 0] and [1, 2]. To understand
490 // why this happens, consider the NFA for the aforementioned
491 // regex:
492 //
493 // >000000: binary-union(4, 1)
494 // 000001: \x00-\xFF => 0
495 // 000002: WordAscii => 5
496 // 000003: % => 5
497 // ^000004: binary-union(2, 3)
498 // 000005: binary-union(4, 6)
499 // 000006: MATCH(0)
500 //
501 // The problem here is that one of the DFA start states is
502 // going to consist of the NFA states [2, 3] by computing the
503 // epsilon closure of state 4. State 4 isn't included because
504 // we previously were not keeping track of union states. But
505 // only a subset of transitions out of this state will be able
506 // to follow WordAscii, and in those cases, the epsilon closure
507 // is redone. The only problem is that computing the epsilon
508 // closure from [2, 3] is different than computing the epsilon
509 // closure from [4]. In the former case, assuming the WordAscii
510 // assertion is satisfied, you get: [2, 3, 6]. In the latter
511 // case, you get: [2, 6, 3]. Notice that '6' is the match state
512 // and appears AFTER '3' in the former case. This leads to a
513 // preferential but incorrect match of '%' before returning
514 // a match. In the latter case, the match is preferred over
515 // continuing to accept the '%'.
516 //
517 // It almost feels like we might be able to fix the NFA states
518 // to avoid this, or to at least only keep track of union
519 // states where this actually matters, since in the vast
520 // majority of cases, this doesn't matter.
521 //
522 // Another alternative would be to define a new HIR property
523 // called "assertion is repeated anywhere" and compute it
524 // inductively over the entire pattern. If it happens anywhere,
525 // which is probably pretty rare, then we record union states.
526 // Otherwise we don't.
527 builder.add_nfa_state_id(nfa_id);
528 }
529 // Capture states we definitely do not need to record, since they
530 // are unconditional epsilon transitions with no branching.
531 thompson::State::Capture { .. } => {}
532 // It's not totally clear whether we need to record fail states or
533 // not, but we do so out of an abundance of caution. Since they are
534 // quite rare in practice, there isn't much cost to recording them.
535 thompson::State::Fail => {
536 builder.add_nfa_state_id(nfa_id);
537 }
538 thompson::State::Match { .. } => {
539 // Normally, the NFA match state doesn't actually need to
540 // be inside the DFA state. But since we delay matches by
541 // one byte, the matching DFA state corresponds to states
542 // that transition from the one we're building here. And
543 // the way we detect those cases is by looking for an NFA
544 // match state. See 'next' for how this is handled.
545 builder.add_nfa_state_id(nfa_id);
546 }
547 }
548 }
549 // If we know this state contains no look-around assertions, then
550 // there's no reason to track which look-around assertions were
551 // satisfied when this state was created.
552 if builder.look_need().is_empty() {
553 builder.set_look_have(|_| LookSet::empty());
554 }
555 }
556
557 /// Sets the appropriate look-behind assertions on the given state based on
558 /// this starting configuration.
559 pub(crate) fn set_lookbehind_from_start(
560 nfa: &thompson::NFA,
561 start: &Start,
562 builder: &mut StateBuilderMatches,
563 ) {
564 let rev = nfa.is_reverse();
565 let lineterm = nfa.look_matcher().get_line_terminator();
566 match *start {
567 Start::NonWordByte => {}
568 Start::WordByte => {
569 builder.set_is_from_word();
570 }
571 Start::Text => {
572 builder.set_look_have(|have| {
573 have.insert(Look::Start)
574 .insert(Look::StartLF)
575 .insert(Look::StartCRLF)
576 });
577 }
578 Start::LineLF => {
579 if rev {
580 builder.set_is_half_crlf();
581 builder.set_look_have(|have| have.insert(Look::StartLF));
582 } else {
583 builder.set_look_have(|have| have.insert(Look::StartCRLF));
584 }
585 if lineterm == b'\n' {
586 builder.set_look_have(|have| have.insert(Look::StartLF));
587 }
588 }
589 Start::LineCR => {
590 if rev {
591 builder.set_look_have(|have| have.insert(Look::StartCRLF));
592 } else {
593 builder.set_is_half_crlf();
594 }
595 if lineterm == b'\r' {
596 builder.set_look_have(|have| have.insert(Look::StartLF));
597 }
598 }
599 Start::CustomLineTerminator => {
600 builder.set_look_have(|have| have.insert(Look::StartLF));
601 // This is a bit of a tricky case, but if the line terminator was
602 // set to a word byte, then we also need to behave as if the start
603 // configuration is Start::WordByte. That is, we need to mark our
604 // state as having come from a word byte.
605 if utf8::is_word_byte(lineterm) {
606 builder.set_is_from_word();
607 }
608 }
609 }
610 }