Debian Codegraph @

third_party/rust/regex-automata/src/meta/stopat.rs

raw
1 /*!
2 This module defines two bespoke forward DFA search routines. One for the lazy
3 DFA and one for the fully compiled DFA. These routines differ from the normal
4 ones by reporting the position at which the search terminates when a match
5 *isn't* found.
6
7 This position at which a search terminates is useful in contexts where the meta
8 regex engine runs optimizations that could go quadratic if we aren't careful.
9 Namely, a regex search *could* scan to the end of the haystack only to report a
10 non-match. If the caller doesn't know that the search scanned to the end of the
11 haystack, it might restart the search at the next literal candidate it finds
12 and repeat the process.
13
14 Providing the caller with the position at which the search stopped provides a
15 way for the caller to determine the point at which subsequent scans should not
16 pass. This is principally used in the "reverse inner" optimization, which works
17 like this:
18
19 1. Look for a match of an inner literal. Say, 'Z' in '\w+Z\d+'.
20 2. At the spot where 'Z' matches, do a reverse anchored search from there for
21 '\w+'.
22 3. If the reverse search matches, it corresponds to the start position of a
23 (possible) match. At this point, do a forward anchored search to find the end
24 position. If an end position is found, then we have a match and we know its
25 bounds.
26
27 If the forward anchored search in (3) searches the entire rest of the haystack
28 but reports a non-match, then a naive implementation of the above will continue
29 back at step 1 looking for more candidates. There might still be a match to be
30 found! It's possible. But we already scanned the whole haystack. So if we keep
31 repeating the process, then we might wind up taking quadratic time in the size
32 of the haystack, which is not great.
33
34 So if the forward anchored search in (3) reports the position at which it
35 stops, then we can detect whether quadratic behavior might be occurring in
36 steps (1) and (2). For (1), it occurs if the literal candidate found occurs
37 *before* the end of the previous search in (3), since that means we're now
38 going to look for another match in a place where the forward search has already
39 scanned. It is *correct* to do so, but our technique has become inefficient.
40 For (2), quadratic behavior occurs similarly when its reverse search extends
41 past the point where the previous forward search in (3) terminated. Indeed, to
42 implement (2), we use the sibling 'limited' module for ensuring our reverse
43 scan doesn't go further than we want.
44
45 See the 'opt/reverse-inner' benchmarks in rebar for a real demonstration of
46 how quadratic behavior is mitigated.
47 */
48
49 use crate::{meta::error::RetryFailError, HalfMatch, Input, MatchError};
50
51 #[cfg(feature = "dfa-build")]
52 pub(crate) fn dfa_try_search_half_fwd(
53 dfa: &crate::dfa::dense::DFA<alloc::vec::Vec<u32>>,
54 input: &Input<'_>,
55 ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
56 use crate::dfa::{accel, Automaton};
57
58 let mut mat = None;
59 let mut sid = dfa.start_state_forward(input)?;
60 let mut at = input.start();
61 while at < input.end() {
62 sid = dfa.next_state(sid, input.haystack()[at]);
63 if dfa.is_special_state(sid) {
64 if dfa.is_match_state(sid) {
65 let pattern = dfa.match_pattern(sid, 0);
66 mat = Some(HalfMatch::new(pattern, at));
67 if input.get_earliest() {
68 return Ok(mat.ok_or(at));
69 }
70 if dfa.is_accel_state(sid) {
71 let needs = dfa.accelerator(sid);
72 at = accel::find_fwd(needs, input.haystack(), at)
73 .unwrap_or(input.end());
74 continue;
75 }
76 } else if dfa.is_accel_state(sid) {
77 let needs = dfa.accelerator(sid);
78 at = accel::find_fwd(needs, input.haystack(), at)
79 .unwrap_or(input.end());
80 continue;
81 } else if dfa.is_dead_state(sid) {
82 return Ok(mat.ok_or(at));
83 } else if dfa.is_quit_state(sid) {
84 if mat.is_some() {
85 return Ok(mat.ok_or(at));
86 }
87 return Err(MatchError::quit(input.haystack()[at], at).into());
88 } else {
89 // Ideally we wouldn't use a DFA that specialized start states
90 // and thus 'is_start_state()' could never be true here, but in
91 // practice we reuse the DFA created for the full regex which
92 // will specialize start states whenever there is a prefilter.
93 debug_assert!(dfa.is_start_state(sid));
94 }
95 }
96 at += 1;
97 }
98 dfa_eoi_fwd(dfa, input, &mut sid, &mut mat)?;
99 Ok(mat.ok_or(at))
100 }
101
102 #[cfg(feature = "hybrid")]
103 pub(crate) fn hybrid_try_search_half_fwd(
104 dfa: &crate::hybrid::dfa::DFA,
105 cache: &mut crate::hybrid::dfa::Cache,
106 input: &Input<'_>,
107 ) -> Result<Result<HalfMatch, usize>, RetryFailError> {
108 let mut mat = None;
109 let mut sid = dfa.start_state_forward(cache, input)?;
110 let mut at = input.start();
111 while at < input.end() {
112 sid = dfa
113 .next_state(cache, sid, input.haystack()[at])
114 .map_err(|_| MatchError::gave_up(at))?;
115 if sid.is_tagged() {
116 if sid.is_match() {
117 let pattern = dfa.match_pattern(cache, sid, 0);
118 mat = Some(HalfMatch::new(pattern, at));
119 if input.get_earliest() {
120 return Ok(mat.ok_or(at));
121 }
122 } else if sid.is_dead() {
123 return Ok(mat.ok_or(at));
124 } else if sid.is_quit() {
125 if mat.is_some() {
126 return Ok(mat.ok_or(at));
127 }
128 return Err(MatchError::quit(input.haystack()[at], at).into());
129 } else {
130 // We should NEVER get an unknown state ID back from
131 // dfa.next_state().
132 debug_assert!(!sid.is_unknown());
133 // Ideally we wouldn't use a lazy DFA that specialized start
134 // states and thus 'sid.is_start()' could never be true here,
135 // but in practice we reuse the lazy DFA created for the full
136 // regex which will specialize start states whenever there is
137 // a prefilter.
138 debug_assert!(sid.is_start());
139 }
140 }
141 at += 1;
142 }
143 hybrid_eoi_fwd(dfa, cache, input, &mut sid, &mut mat)?;
144 Ok(mat.ok_or(at))
145 }
146
147 #[cfg(feature = "dfa-build")]
148 #[cfg_attr(feature = "perf-inline", inline(always))]
149 fn dfa_eoi_fwd(
150 dfa: &crate::dfa::dense::DFA<alloc::vec::Vec<u32>>,
151 input: &Input<'_>,
152 sid: &mut crate::util::primitives::StateID,
153 mat: &mut Option<HalfMatch>,
154 ) -> Result<(), MatchError> {
155 use crate::dfa::Automaton;
156
157 let sp = input.get_span();
158 match input.haystack().get(sp.end) {
159 Some(&b) => {
160 *sid = dfa.next_state(*sid, b);
161 if dfa.is_match_state(*sid) {
162 let pattern = dfa.match_pattern(*sid, 0);
163 *mat = Some(HalfMatch::new(pattern, sp.end));
164 } else if dfa.is_quit_state(*sid) {
165 if mat.is_some() {
166 return Ok(());
167 }
168 return Err(MatchError::quit(b, sp.end));
169 }
170 }
171 None => {
172 *sid = dfa.next_eoi_state(*sid);
173 if dfa.is_match_state(*sid) {
174 let pattern = dfa.match_pattern(*sid, 0);
175 *mat = Some(HalfMatch::new(pattern, input.haystack().len()));
176 }
177 // N.B. We don't have to check 'is_quit' here because the EOI
178 // transition can never lead to a quit state.
179 debug_assert!(!dfa.is_quit_state(*sid));
180 }
181 }
182 Ok(())
183 }
184
185 #[cfg(feature = "hybrid")]
186 #[cfg_attr(feature = "perf-inline", inline(always))]
187 fn hybrid_eoi_fwd(
188 dfa: &crate::hybrid::dfa::DFA,
189 cache: &mut crate::hybrid::dfa::Cache,
190 input: &Input<'_>,
191 sid: &mut crate::hybrid::LazyStateID,
192 mat: &mut Option<HalfMatch>,
193 ) -> Result<(), MatchError> {
194 let sp = input.get_span();
195 match input.haystack().get(sp.end) {
196 Some(&b) => {
197 *sid = dfa
198 .next_state(cache, *sid, b)
199 .map_err(|_| MatchError::gave_up(sp.end))?;
200 if sid.is_match() {
201 let pattern = dfa.match_pattern(cache, *sid, 0);
202 *mat = Some(HalfMatch::new(pattern, sp.end));
203 } else if sid.is_quit() {
204 if mat.is_some() {
205 return Ok(());
206 }
207 return Err(MatchError::quit(b, sp.end));
208 }
209 }
210 None => {
211 *sid = dfa
212 .next_eoi_state(cache, *sid)
213 .map_err(|_| MatchError::gave_up(input.haystack().len()))?;
214 if sid.is_match() {
215 let pattern = dfa.match_pattern(cache, *sid, 0);
216 *mat = Some(HalfMatch::new(pattern, input.haystack().len()));
217 }
218 // N.B. We don't have to check 'is_quit' here because the EOI
219 // transition can never lead to a quit state.
220 debug_assert!(!sid.is_quit());
221 }
222 }
223 Ok(())
224 }