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