Debian Codegraph @

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

raw
1 /*!
2 This module defines two bespoke reverse DFA searching routines. (One for the
3 lazy DFA and one for the fully compiled DFA.) These routines differ from the
4 usual ones by permitting the caller to specify a minimum starting position.
5 That is, the search will begin at `input.end()` and will usually stop at
6 `input.start()`, unless `min_start > input.start()`, in which case, the search
7 will stop at `min_start`.
8
9 In other words, this lets you say, "no, the search must not extend past this
10 point, even if it's within the bounds of the given `Input`." And if the search
11 *does* want to go past that point, it stops and returns a "may be quadratic"
12 error, which indicates that the caller should retry using some other technique.
13
14 These routines specifically exist to protect against quadratic behavior when
15 employing the "reverse suffix" and "reverse inner" optimizations. Without the
16 backstop these routines provide, it is possible for parts of the haystack to
17 get re-scanned over and over again. The backstop not only prevents this, but
18 *tells you when it is happening* so that you can change the strategy.
19
20 Why can't we just use the normal search routines? We could use the normal
21 search routines and just set the start bound on the provided `Input` to our
22 `min_start` position. The problem here is that it's impossible to distinguish
23 between "no match because we reached the end of input" and "determined there
24 was no match well before the end of input." The former case is what we care
25 about with respect to quadratic behavior. The latter case is totally fine.
26
27 Why don't we modify the normal search routines to report the position at which
28 the search stops? I considered this, and I still wonder if it is indeed the
29 right thing to do. However, I think the straight-forward thing to do there
30 would be to complicate the return type signature of almost every search routine
31 in this crate, which I really do not want to do. It therefore might make more
32 sense to provide a richer way for search routines to report meta data, but that
33 was beyond my bandwidth to work on at the time of writing.
34
35 See the 'opt/reverse-inner' and 'opt/reverse-suffix' benchmarks in rebar for a
36 real demonstration of how quadratic behavior is mitigated.
37 */
38
39 use crate::{
40 meta::error::{RetryError, RetryQuadraticError},
41 HalfMatch, Input, MatchError,
42 };
43
44 #[cfg(feature = "dfa-build")]
45 pub(crate) fn dfa_try_search_half_rev(
46 dfa: &crate::dfa::dense::DFA<alloc::vec::Vec<u32>>,
47 input: &Input<'_>,
48 min_start: usize,
49 ) -> Result<Option<HalfMatch>, RetryError> {
50 use crate::dfa::Automaton;
51
52 let mut mat = None;
53 let mut sid = dfa.start_state_reverse(input)?;
54 if input.start() == input.end() {
55 dfa_eoi_rev(dfa, input, &mut sid, &mut mat)?;
56 return Ok(mat);
57 }
58 let mut at = input.end() - 1;
59 loop {
60 sid = dfa.next_state(sid, input.haystack()[at]);
61 if dfa.is_special_state(sid) {
62 if dfa.is_match_state(sid) {
63 let pattern = dfa.match_pattern(sid, 0);
64 // Since reverse searches report the beginning of a
65 // match and the beginning is inclusive (not exclusive
66 // like the end of a match), we add 1 to make it
67 // inclusive.
68 mat = Some(HalfMatch::new(pattern, at + 1));
69 } else if dfa.is_dead_state(sid) {
70 return Ok(mat);
71 } else if dfa.is_quit_state(sid) {
72 if mat.is_some() {
73 return Ok(mat);
74 }
75 return Err(MatchError::quit(input.haystack()[at], at).into());
76 }
77 }
78 if at == input.start() {
79 break;
80 }
81 at -= 1;
82 if at < min_start {
83 trace!(
84 "reached position {} which is before the previous literal \
85 match, quitting to avoid quadratic behavior",
86 at,
87 );
88 return Err(RetryError::Quadratic(RetryQuadraticError::new()));
89 }
90 }
91 let was_dead = dfa.is_dead_state(sid);
92 dfa_eoi_rev(dfa, input, &mut sid, &mut mat)?;
93 // If we reach the beginning of the search and we could otherwise still
94 // potentially keep matching if there was more to match, then we actually
95 // return an error to indicate giving up on this optimization. Why? Because
96 // we can't prove that the real match begins at where we would report it.
97 //
98 // This only happens when all of the following are true:
99 //
100 // 1) We reach the starting point of our search span.
101 // 2) The match we found is before the starting point.
102 // 3) The FSM reports we could possibly find a longer match.
103 //
104 // We need (1) because otherwise the search stopped before the starting
105 // point and there is no possible way to find a more leftmost position.
106 //
107 // We need (2) because if the match found has an offset equal to the minimum
108 // possible offset, then there is no possible more leftmost match.
109 //
110 // We need (3) because if the FSM couldn't continue anyway (i.e., it's in
111 // a dead state), then we know we couldn't find anything more leftmost
112 // than what we have. (We have to check the state we were in prior to the
113 // EOI transition since the EOI transition will usually bring us to a dead
114 // state by virtue of it represents the end-of-input.)
115 if at == input.start()
116 && mat.map_or(false, |m| m.offset() > input.start())
117 && !was_dead
118 {
119 trace!(
120 "reached beginning of search at offset {} without hitting \
121 a dead state, quitting to avoid potential false positive match",
122 at,
123 );
124 return Err(RetryError::Quadratic(RetryQuadraticError::new()));
125 }
126 Ok(mat)
127 }
128
129 #[cfg(feature = "hybrid")]
130 pub(crate) fn hybrid_try_search_half_rev(
131 dfa: &crate::hybrid::dfa::DFA,
132 cache: &mut crate::hybrid::dfa::Cache,
133 input: &Input<'_>,
134 min_start: usize,
135 ) -> Result<Option<HalfMatch>, RetryError> {
136 let mut mat = None;
137 let mut sid = dfa.start_state_reverse(cache, input)?;
138 if input.start() == input.end() {
139 hybrid_eoi_rev(dfa, cache, input, &mut sid, &mut mat)?;
140 return Ok(mat);
141 }
142 let mut at = input.end() - 1;
143 loop {
144 sid = dfa
145 .next_state(cache, sid, input.haystack()[at])
146 .map_err(|_| MatchError::gave_up(at))?;
147 if sid.is_tagged() {
148 if sid.is_match() {
149 let pattern = dfa.match_pattern(cache, sid, 0);
150 // Since reverse searches report the beginning of a
151 // match and the beginning is inclusive (not exclusive
152 // like the end of a match), we add 1 to make it
153 // inclusive.
154 mat = Some(HalfMatch::new(pattern, at + 1));
155 } else if sid.is_dead() {
156 return Ok(mat);
157 } else if sid.is_quit() {
158 if mat.is_some() {
159 return Ok(mat);
160 }
161 return Err(MatchError::quit(input.haystack()[at], at).into());
162 }
163 }
164 if at == input.start() {
165 break;
166 }
167 at -= 1;
168 if at < min_start {
169 trace!(
170 "reached position {} which is before the previous literal \
171 match, quitting to avoid quadratic behavior",
172 at,
173 );
174 return Err(RetryError::Quadratic(RetryQuadraticError::new()));
175 }
176 }
177 let was_dead = sid.is_dead();
178 hybrid_eoi_rev(dfa, cache, input, &mut sid, &mut mat)?;
179 // See the comments in the full DFA routine above for why we need this.
180 if at == input.start()
181 && mat.map_or(false, |m| m.offset() > input.start())
182 && !was_dead
183 {
184 trace!(
185 "reached beginning of search at offset {} without hitting \
186 a dead state, quitting to avoid potential false positive match",
187 at,
188 );
189 return Err(RetryError::Quadratic(RetryQuadraticError::new()));
190 }
191 Ok(mat)
192 }
193
194 #[cfg(feature = "dfa-build")]
195 #[cfg_attr(feature = "perf-inline", inline(always))]
196 fn dfa_eoi_rev(
197 dfa: &crate::dfa::dense::DFA<alloc::vec::Vec<u32>>,
198 input: &Input<'_>,
199 sid: &mut crate::util::primitives::StateID,
200 mat: &mut Option<HalfMatch>,
201 ) -> Result<(), MatchError> {
202 use crate::dfa::Automaton;
203
204 let sp = input.get_span();
205 if sp.start > 0 {
206 let byte = input.haystack()[sp.start - 1];
207 *sid = dfa.next_state(*sid, byte);
208 if dfa.is_match_state(*sid) {
209 let pattern = dfa.match_pattern(*sid, 0);
210 *mat = Some(HalfMatch::new(pattern, sp.start));
211 } else if dfa.is_quit_state(*sid) {
212 if mat.is_some() {
213 return Ok(());
214 }
215 return Err(MatchError::quit(byte, sp.start - 1));
216 }
217 } else {
218 *sid = dfa.next_eoi_state(*sid);
219 if dfa.is_match_state(*sid) {
220 let pattern = dfa.match_pattern(*sid, 0);
221 *mat = Some(HalfMatch::new(pattern, 0));
222 }
223 // N.B. We don't have to check 'is_quit' here because the EOI
224 // transition can never lead to a quit state.
225 debug_assert!(!dfa.is_quit_state(*sid));
226 }
227 Ok(())
228 }
229
230 #[cfg(feature = "hybrid")]
231 #[cfg_attr(feature = "perf-inline", inline(always))]
232 fn hybrid_eoi_rev(
233 dfa: &crate::hybrid::dfa::DFA,
234 cache: &mut crate::hybrid::dfa::Cache,
235 input: &Input<'_>,
236 sid: &mut crate::hybrid::LazyStateID,
237 mat: &mut Option<HalfMatch>,
238 ) -> Result<(), MatchError> {
239 let sp = input.get_span();
240 if sp.start > 0 {
241 let byte = input.haystack()[sp.start - 1];
242 *sid = dfa
243 .next_state(cache, *sid, byte)
244 .map_err(|_| MatchError::gave_up(sp.start))?;
245 if sid.is_match() {
246 let pattern = dfa.match_pattern(cache, *sid, 0);
247 *mat = Some(HalfMatch::new(pattern, sp.start));
248 } else if sid.is_quit() {
249 if mat.is_some() {
250 return Ok(());
251 }
252 return Err(MatchError::quit(byte, sp.start - 1));
253 }
254 } else {
255 *sid = dfa
256 .next_eoi_state(cache, *sid)
257 .map_err(|_| MatchError::gave_up(sp.start))?;
258 if sid.is_match() {
259 let pattern = dfa.match_pattern(cache, *sid, 0);
260 *mat = Some(HalfMatch::new(pattern, 0));
261 }
262 // N.B. We don't have to check 'is_quit' here because the EOI
263 // transition can never lead to a quit state.
264 debug_assert!(!sid.is_quit());
265 }
266 Ok(())
267 }