Debian Codegraph @

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

raw
1 use crate::{
2 dfa::{
3 accel,
4 automaton::{Automaton, OverlappingState},
5 },
6 util::{
7 prefilter::Prefilter,
8 primitives::StateID,
9 search::{Anchored, HalfMatch, Input, Span},
10 },
11 MatchError,
12 };
13
14 #[inline(never)]
15 pub fn find_fwd<A: Automaton + ?Sized>(
16 dfa: &A,
17 input: &Input<'_>,
18 ) -> Result<Option<HalfMatch>, MatchError> {
19 if input.is_done() {
20 return Ok(None);
21 }
22 let pre = if input.get_anchored().is_anchored() {
23 None
24 } else {
25 dfa.get_prefilter()
26 };
27 // Searching with a pattern ID is always anchored, so we should never use
28 // a prefilter.
29 if pre.is_some() {
30 if input.get_earliest() {
31 find_fwd_imp(dfa, input, pre, true)
32 } else {
33 find_fwd_imp(dfa, input, pre, false)
34 }
35 } else {
36 if input.get_earliest() {
37 find_fwd_imp(dfa, input, None, true)
38 } else {
39 find_fwd_imp(dfa, input, None, false)
40 }
41 }
42 }
43
44 #[cfg_attr(feature = "perf-inline", inline(always))]
45 fn find_fwd_imp<A: Automaton + ?Sized>(
46 dfa: &A,
47 input: &Input<'_>,
48 pre: Option<&'_ Prefilter>,
49 earliest: bool,
50 ) -> Result<Option<HalfMatch>, MatchError> {
51 // See 'prefilter_restart' docs for explanation.
52 let universal_start = dfa.universal_start_state(Anchored::No).is_some();
53 let mut mat = None;
54 let mut sid = init_fwd(dfa, input)?;
55 let mut at = input.start();
56 // This could just be a closure, but then I think it would be unsound
57 // because it would need to be safe to invoke. This way, the lack of safety
58 // is clearer in the code below.
59 macro_rules! next_unchecked {
60 ($sid:expr, $at:expr) => {{
61 let byte = *input.haystack().get_unchecked($at);
62 dfa.next_state_unchecked($sid, byte)
63 }};
64 }
65
66 if let Some(ref pre) = pre {
67 let span = Span::from(at..input.end());
68 // If a prefilter doesn't report false positives, then we don't need to
69 // touch the DFA at all. However, since all matches include the pattern
70 // ID, and the prefilter infrastructure doesn't report pattern IDs, we
71 // limit this optimization to cases where there is exactly one pattern.
72 // In that case, any match must be the 0th pattern.
73 match pre.find(input.haystack(), span) {
74 None => return Ok(mat),
75 Some(ref span) => {
76 at = span.start;
77 if !universal_start {
78 sid = prefilter_restart(dfa, &input, at)?;
79 }
80 }
81 }
82 }
83 while at < input.end() {
84 // SAFETY: There are two safety invariants we need to uphold here in
85 // the loops below: that 'sid' and 'prev_sid' are valid state IDs
86 // for this DFA, and that 'at' is a valid index into 'haystack'.
87 // For the former, we rely on the invariant that next_state* and
88 // start_state_forward always returns a valid state ID (given a valid
89 // state ID in the former case). For the latter safety invariant, we
90 // always guard unchecked access with a check that 'at' is less than
91 // 'end', where 'end <= haystack.len()'. In the unrolled loop below, we
92 // ensure that 'at' is always in bounds.
93 //
94 // PERF: See a similar comment in src/hybrid/search.rs that justifies
95 // this extra work to make the search loop fast. The same reasoning and
96 // benchmarks apply here.
97 let mut prev_sid;
98 while at < input.end() {
99 prev_sid = unsafe { next_unchecked!(sid, at) };
100 if dfa.is_special_state(prev_sid) || at + 3 >= input.end() {
101 core::mem::swap(&mut prev_sid, &mut sid);
102 break;
103 }
104 at += 1;
105
106 sid = unsafe { next_unchecked!(prev_sid, at) };
107 if dfa.is_special_state(sid) {
108 break;
109 }
110 at += 1;
111
112 prev_sid = unsafe { next_unchecked!(sid, at) };
113 if dfa.is_special_state(prev_sid) {
114 core::mem::swap(&mut prev_sid, &mut sid);
115 break;
116 }
117 at += 1;
118
119 sid = unsafe { next_unchecked!(prev_sid, at) };
120 if dfa.is_special_state(sid) {
121 break;
122 }
123 at += 1;
124 }
125 if dfa.is_special_state(sid) {
126 if dfa.is_start_state(sid) {
127 if let Some(ref pre) = pre {
128 let span = Span::from(at..input.end());
129 match pre.find(input.haystack(), span) {
130 None => return Ok(mat),
131 Some(ref span) => {
132 // We want to skip any update to 'at' below
133 // at the end of this iteration and just
134 // jump immediately back to the next state
135 // transition at the leading position of the
136 // candidate match.
137 //
138 // ... but only if we actually made progress
139 // with our prefilter, otherwise if the start
140 // state has a self-loop, we can get stuck.
141 if span.start > at {
142 at = span.start;
143 if !universal_start {
144 sid = prefilter_restart(dfa, &input, at)?;
145 }
146 continue;
147 }
148 }
149 }
150 } else if dfa.is_accel_state(sid) {
151 let needles = dfa.accelerator(sid);
152 at = accel::find_fwd(needles, input.haystack(), at + 1)
153 .unwrap_or(input.end());
154 continue;
155 }
156 } else if dfa.is_match_state(sid) {
157 let pattern = dfa.match_pattern(sid, 0);
158 mat = Some(HalfMatch::new(pattern, at));
159 if earliest {
160 return Ok(mat);
161 }
162 if dfa.is_accel_state(sid) {
163 let needles = dfa.accelerator(sid);
164 at = accel::find_fwd(needles, input.haystack(), at + 1)
165 .unwrap_or(input.end());
166 continue;
167 }
168 } else if dfa.is_accel_state(sid) {
169 let needs = dfa.accelerator(sid);
170 at = accel::find_fwd(needs, input.haystack(), at + 1)
171 .unwrap_or(input.end());
172 continue;
173 } else if dfa.is_dead_state(sid) {
174 return Ok(mat);
175 } else {
176 // It's important that this is a debug_assert, since this can
177 // actually be tripped even if DFA::from_bytes succeeds and
178 // returns a supposedly valid DFA.
179 debug_assert!(dfa.is_quit_state(sid));
180 return Err(MatchError::quit(input.haystack()[at], at));
181 }
182 }
183 at += 1;
184 }
185 eoi_fwd(dfa, input, &mut sid, &mut mat)?;
186 Ok(mat)
187 }
188
189 #[inline(never)]
190 pub fn find_rev<A: Automaton + ?Sized>(
191 dfa: &A,
192 input: &Input<'_>,
193 ) -> Result<Option<HalfMatch>, MatchError> {
194 if input.is_done() {
195 return Ok(None);
196 }
197 if input.get_earliest() {
198 find_rev_imp(dfa, input, true)
199 } else {
200 find_rev_imp(dfa, input, false)
201 }
202 }
203
204 #[cfg_attr(feature = "perf-inline", inline(always))]
205 fn find_rev_imp<A: Automaton + ?Sized>(
206 dfa: &A,
207 input: &Input<'_>,
208 earliest: bool,
209 ) -> Result<Option<HalfMatch>, MatchError> {
210 let mut mat = None;
211 let mut sid = init_rev(dfa, input)?;
212 // In reverse search, the loop below can't handle the case of searching an
213 // empty slice. Ideally we could write something congruent to the forward
214 // search, i.e., 'while at >= start', but 'start' might be 0. Since we use
215 // an unsigned offset, 'at >= 0' is trivially always true. We could avoid
216 // this extra case handling by using a signed offset, but Rust makes it
217 // annoying to do. So... We just handle the empty case separately.
218 if input.start() == input.end() {
219 eoi_rev(dfa, input, &mut sid, &mut mat)?;
220 return Ok(mat);
221 }
222
223 let mut at = input.end() - 1;
224 macro_rules! next_unchecked {
225 ($sid:expr, $at:expr) => {{
226 let byte = *input.haystack().get_unchecked($at);
227 dfa.next_state_unchecked($sid, byte)
228 }};
229 }
230 loop {
231 // SAFETY: See comments in 'find_fwd' for a safety argument.
232 let mut prev_sid;
233 while at >= input.start() {
234 prev_sid = unsafe { next_unchecked!(sid, at) };
235 if dfa.is_special_state(prev_sid)
236 || at <= input.start().saturating_add(3)
237 {
238 core::mem::swap(&mut prev_sid, &mut sid);
239 break;
240 }
241 at -= 1;
242
243 sid = unsafe { next_unchecked!(prev_sid, at) };
244 if dfa.is_special_state(sid) {
245 break;
246 }
247 at -= 1;
248
249 prev_sid = unsafe { next_unchecked!(sid, at) };
250 if dfa.is_special_state(prev_sid) {
251 core::mem::swap(&mut prev_sid, &mut sid);
252 break;
253 }
254 at -= 1;
255
256 sid = unsafe { next_unchecked!(prev_sid, at) };
257 if dfa.is_special_state(sid) {
258 break;
259 }
260 at -= 1;
261 }
262 if dfa.is_special_state(sid) {
263 if dfa.is_start_state(sid) {
264 if dfa.is_accel_state(sid) {
265 let needles = dfa.accelerator(sid);
266 at = accel::find_rev(needles, input.haystack(), at)
267 .map(|i| i + 1)
268 .unwrap_or(input.start());
269 }
270 } else if dfa.is_match_state(sid) {
271 let pattern = dfa.match_pattern(sid, 0);
272 // Since reverse searches report the beginning of a match
273 // and the beginning is inclusive (not exclusive like the
274 // end of a match), we add 1 to make it inclusive.
275 mat = Some(HalfMatch::new(pattern, at + 1));
276 if earliest {
277 return Ok(mat);
278 }
279 if dfa.is_accel_state(sid) {
280 let needles = dfa.accelerator(sid);
281 at = accel::find_rev(needles, input.haystack(), at)
282 .map(|i| i + 1)
283 .unwrap_or(input.start());
284 }
285 } else if dfa.is_accel_state(sid) {
286 let needles = dfa.accelerator(sid);
287 // If the accelerator returns nothing, why don't we quit the
288 // search? Well, if the accelerator doesn't find anything, that
289 // doesn't mean we don't have a match. It just means that we
290 // can't leave the current state given one of the 255 possible
291 // byte values. However, there might be an EOI transition. So
292 // we set 'at' to the end of the haystack, which will cause
293 // this loop to stop and fall down into the EOI transition.
294 at = accel::find_rev(needles, input.haystack(), at)
295 .map(|i| i + 1)
296 .unwrap_or(input.start());
297 } else if dfa.is_dead_state(sid) {
298 return Ok(mat);
299 } else {
300 debug_assert!(dfa.is_quit_state(sid));
301 return Err(MatchError::quit(input.haystack()[at], at));
302 }
303 }
304 if at == input.start() {
305 break;
306 }
307 at -= 1;
308 }
309 eoi_rev(dfa, input, &mut sid, &mut mat)?;
310 Ok(mat)
311 }
312
313 #[inline(never)]
314 pub fn find_overlapping_fwd<A: Automaton + ?Sized>(
315 dfa: &A,
316 input: &Input<'_>,
317 state: &mut OverlappingState,
318 ) -> Result<(), MatchError> {
319 state.mat = None;
320 if input.is_done() {
321 return Ok(());
322 }
323 let pre = if input.get_anchored().is_anchored() {
324 None
325 } else {
326 dfa.get_prefilter()
327 };
328 if pre.is_some() {
329 find_overlapping_fwd_imp(dfa, input, pre, state)
330 } else {
331 find_overlapping_fwd_imp(dfa, input, None, state)
332 }
333 }
334
335 #[cfg_attr(feature = "perf-inline", inline(always))]
336 fn find_overlapping_fwd_imp<A: Automaton + ?Sized>(
337 dfa: &A,
338 input: &Input<'_>,
339 pre: Option<&'_ Prefilter>,
340 state: &mut OverlappingState,
341 ) -> Result<(), MatchError> {
342 // See 'prefilter_restart' docs for explanation.
343 let universal_start = dfa.universal_start_state(Anchored::No).is_some();
344 let mut sid = match state.id {
345 None => {
346 state.at = input.start();
347 init_fwd(dfa, input)?
348 }
349 Some(sid) => {
350 if let Some(match_index) = state.next_match_index {
351 let match_len = dfa.match_len(sid);
352 if match_index < match_len {
353 state.next_match_index = Some(match_index + 1);
354 let pattern = dfa.match_pattern(sid, match_index);
355 state.mat = Some(HalfMatch::new(pattern, state.at));
356 return Ok(());
357 }
358 }
359 // Once we've reported all matches at a given position, we need to
360 // advance the search to the next position.
361 state.at += 1;
362 if state.at > input.end() {
363 return Ok(());
364 }
365 sid
366 }
367 };
368
369 // NOTE: We don't optimize the crap out of this routine primarily because
370 // it seems like most find_overlapping searches will have higher match
371 // counts, and thus, throughput is perhaps not as important. But if you
372 // have a use case for something faster, feel free to file an issue.
373 while state.at < input.end() {
374 sid = dfa.next_state(sid, input.haystack()[state.at]);
375 if dfa.is_special_state(sid) {
376 state.id = Some(sid);
377 if dfa.is_start_state(sid) {
378 if let Some(ref pre) = pre {
379 let span = Span::from(state.at..input.end());
380 match pre.find(input.haystack(), span) {
381 None => return Ok(()),
382 Some(ref span) => {
383 if span.start > state.at {
384 state.at = span.start;
385 if !universal_start {
386 sid = prefilter_restart(
387 dfa, &input, state.at,
388 )?;
389 }
390 continue;
391 }
392 }
393 }
394 } else if dfa.is_accel_state(sid) {
395 let needles = dfa.accelerator(sid);
396 state.at = accel::find_fwd(
397 needles,
398 input.haystack(),
399 state.at + 1,
400 )
401 .unwrap_or(input.end());
402 continue;
403 }
404 } else if dfa.is_match_state(sid) {
405 state.next_match_index = Some(1);
406 let pattern = dfa.match_pattern(sid, 0);
407 state.mat = Some(HalfMatch::new(pattern, state.at));
408 return Ok(());
409 } else if dfa.is_accel_state(sid) {
410 let needs = dfa.accelerator(sid);
411 // If the accelerator returns nothing, why don't we quit the
412 // search? Well, if the accelerator doesn't find anything, that
413 // doesn't mean we don't have a match. It just means that we
414 // can't leave the current state given one of the 255 possible
415 // byte values. However, there might be an EOI transition. So
416 // we set 'at' to the end of the haystack, which will cause
417 // this loop to stop and fall down into the EOI transition.
418 state.at =
419 accel::find_fwd(needs, input.haystack(), state.at + 1)
420 .unwrap_or(input.end());
421 continue;
422 } else if dfa.is_dead_state(sid) {
423 return Ok(());
424 } else {
425 debug_assert!(dfa.is_quit_state(sid));
426 return Err(MatchError::quit(
427 input.haystack()[state.at],
428 state.at,
429 ));
430 }
431 }
432 state.at += 1;
433 }
434
435 let result = eoi_fwd(dfa, input, &mut sid, &mut state.mat);
436 state.id = Some(sid);
437 if state.mat.is_some() {
438 // '1' is always correct here since if we get to this point, this
439 // always corresponds to the first (index '0') match discovered at
440 // this position. So the next match to report at this position (if
441 // it exists) is at index '1'.
442 state.next_match_index = Some(1);
443 }
444 result
445 }
446
447 #[inline(never)]
448 pub(crate) fn find_overlapping_rev<A: Automaton + ?Sized>(
449 dfa: &A,
450 input: &Input<'_>,
451 state: &mut OverlappingState,
452 ) -> Result<(), MatchError> {
453 state.mat = None;
454 if input.is_done() {
455 return Ok(());
456 }
457 let mut sid = match state.id {
458 None => {
459 let sid = init_rev(dfa, input)?;
460 state.id = Some(sid);
461 if input.start() == input.end() {
462 state.rev_eoi = true;
463 } else {
464 state.at = input.end() - 1;
465 }
466 sid
467 }
468 Some(sid) => {
469 if let Some(match_index) = state.next_match_index {
470 let match_len = dfa.match_len(sid);
471 if match_index < match_len {
472 state.next_match_index = Some(match_index + 1);
473 let pattern = dfa.match_pattern(sid, match_index);
474 state.mat = Some(HalfMatch::new(pattern, state.at));
475 return Ok(());
476 }
477 }
478 // Once we've reported all matches at a given position, we need
479 // to advance the search to the next position. However, if we've
480 // already followed the EOI transition, then we know we're done
481 // with the search and there cannot be any more matches to report.
482 if state.rev_eoi {
483 return Ok(());
484 } else if state.at == input.start() {
485 // At this point, we should follow the EOI transition. This
486 // will cause us the skip the main loop below and fall through
487 // to the final 'eoi_rev' transition.
488 state.rev_eoi = true;
489 } else {
490 // We haven't hit the end of the search yet, so move on.
491 state.at -= 1;
492 }
493 sid
494 }
495 };
496 while !state.rev_eoi {
497 sid = dfa.next_state(sid, input.haystack()[state.at]);
498 if dfa.is_special_state(sid) {
499 state.id = Some(sid);
500 if dfa.is_start_state(sid) {
501 if dfa.is_accel_state(sid) {
502 let needles = dfa.accelerator(sid);
503 state.at =
504 accel::find_rev(needles, input.haystack(), state.at)
505 .map(|i| i + 1)
506 .unwrap_or(input.start());
507 }
508 } else if dfa.is_match_state(sid) {
509 state.next_match_index = Some(1);
510 let pattern = dfa.match_pattern(sid, 0);
511 state.mat = Some(HalfMatch::new(pattern, state.at + 1));
512 return Ok(());
513 } else if dfa.is_accel_state(sid) {
514 let needles = dfa.accelerator(sid);
515 // If the accelerator returns nothing, why don't we quit the
516 // search? Well, if the accelerator doesn't find anything, that
517 // doesn't mean we don't have a match. It just means that we
518 // can't leave the current state given one of the 255 possible
519 // byte values. However, there might be an EOI transition. So
520 // we set 'at' to the end of the haystack, which will cause
521 // this loop to stop and fall down into the EOI transition.
522 state.at =
523 accel::find_rev(needles, input.haystack(), state.at)
524 .map(|i| i + 1)
525 .unwrap_or(input.start());
526 } else if dfa.is_dead_state(sid) {
527 return Ok(());
528 } else {
529 debug_assert!(dfa.is_quit_state(sid));
530 return Err(MatchError::quit(
531 input.haystack()[state.at],
532 state.at,
533 ));
534 }
535 }
536 if state.at == input.start() {
537 break;
538 }
539 state.at -= 1;
540 }
541
542 let result = eoi_rev(dfa, input, &mut sid, &mut state.mat);
543 state.rev_eoi = true;
544 state.id = Some(sid);
545 if state.mat.is_some() {
546 // '1' is always correct here since if we get to this point, this
547 // always corresponds to the first (index '0') match discovered at
548 // this position. So the next match to report at this position (if
549 // it exists) is at index '1'.
550 state.next_match_index = Some(1);
551 }
552 result
553 }
554
555 #[cfg_attr(feature = "perf-inline", inline(always))]
556 fn init_fwd<A: Automaton + ?Sized>(
557 dfa: &A,
558 input: &Input<'_>,
559 ) -> Result<StateID, MatchError> {
560 let sid = dfa.start_state_forward(input)?;
561 // Start states can never be match states, since all matches are delayed
562 // by 1 byte.
563 debug_assert!(!dfa.is_match_state(sid));
564 Ok(sid)
565 }
566
567 #[cfg_attr(feature = "perf-inline", inline(always))]
568 fn init_rev<A: Automaton + ?Sized>(
569 dfa: &A,
570 input: &Input<'_>,
571 ) -> Result<StateID, MatchError> {
572 let sid = dfa.start_state_reverse(input)?;
573 // Start states can never be match states, since all matches are delayed
574 // by 1 byte.
575 debug_assert!(!dfa.is_match_state(sid));
576 Ok(sid)
577 }
578
579 #[cfg_attr(feature = "perf-inline", inline(always))]
580 fn eoi_fwd<A: Automaton + ?Sized>(
581 dfa: &A,
582 input: &Input<'_>,
583 sid: &mut StateID,
584 mat: &mut Option<HalfMatch>,
585 ) -> Result<(), MatchError> {
586 let sp = input.get_span();
587 match input.haystack().get(sp.end) {
588 Some(&b) => {
589 *sid = dfa.next_state(*sid, b);
590 if dfa.is_match_state(*sid) {
591 let pattern = dfa.match_pattern(*sid, 0);
592 *mat = Some(HalfMatch::new(pattern, sp.end));
593 } else if dfa.is_quit_state(*sid) {
594 return Err(MatchError::quit(b, sp.end));
595 }
596 }
597 None => {
598 *sid = dfa.next_eoi_state(*sid);
599 if dfa.is_match_state(*sid) {
600 let pattern = dfa.match_pattern(*sid, 0);
601 *mat = Some(HalfMatch::new(pattern, input.haystack().len()));
602 }
603 // N.B. We don't have to check 'is_quit' here because the EOI
604 // transition can never lead to a quit state.
605 debug_assert!(!dfa.is_quit_state(*sid));
606 }
607 }
608 Ok(())
609 }
610
611 #[cfg_attr(feature = "perf-inline", inline(always))]
612 fn eoi_rev<A: Automaton + ?Sized>(
613 dfa: &A,
614 input: &Input<'_>,
615 sid: &mut StateID,
616 mat: &mut Option<HalfMatch>,
617 ) -> Result<(), MatchError> {
618 let sp = input.get_span();
619 if sp.start > 0 {
620 let byte = input.haystack()[sp.start - 1];
621 *sid = dfa.next_state(*sid, byte);
622 if dfa.is_match_state(*sid) {
623 let pattern = dfa.match_pattern(*sid, 0);
624 *mat = Some(HalfMatch::new(pattern, sp.start));
625 } else if dfa.is_quit_state(*sid) {
626 return Err(MatchError::quit(byte, sp.start - 1));
627 }
628 } else {
629 *sid = dfa.next_eoi_state(*sid);
630 if dfa.is_match_state(*sid) {
631 let pattern = dfa.match_pattern(*sid, 0);
632 *mat = Some(HalfMatch::new(pattern, 0));
633 }
634 // N.B. We don't have to check 'is_quit' here because the EOI
635 // transition can never lead to a quit state.
636 debug_assert!(!dfa.is_quit_state(*sid));
637 }
638 Ok(())
639 }
640
641 /// Re-compute the starting state that a DFA should be in after finding a
642 /// prefilter candidate match at the position `at`.
643 ///
644 /// The function with the same name has a bit more docs in hybrid/search.rs.
645 #[cfg_attr(feature = "perf-inline", inline(always))]
646 fn prefilter_restart<A: Automaton + ?Sized>(
647 dfa: &A,
648 input: &Input<'_>,
649 at: usize,
650 ) -> Result<StateID, MatchError> {
651 let mut input = input.clone();
652 input.set_start(at);
653 init_fwd(dfa, &input)
654 }