regex_automata/meta/
limited.rs

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`.
8
9In 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.
13
14These 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.
19
20Why 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.
26
27Why 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.
34
35See the 'opt/reverse-inner' and 'opt/reverse-suffix' benchmarks in rebar for a
36real demonstration of how quadratic behavior is mitigated.
37*/
38
39use crate::{
40    meta::error::{RetryError, RetryQuadraticError},
41    HalfMatch, Input, MatchError,
42};
43
44#[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> {
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                return Err(MatchError::quit(input.haystack()[at], at).into());
73            }
74        }
75        if at == input.start() {
76            break;
77        }
78        at -= 1;
79        if at < min_start {
80            trace!(
81                "reached position {at} which is before the previous literal \
82				 match, quitting to avoid quadratic behavior",
83            );
84            return Err(RetryError::Quadratic(RetryQuadraticError::new()));
85        }
86    }
87    let 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.)
111    if at == input.start()
112        && mat.map_or(false, |m| m.offset() > input.start())
113        && !was_dead
114    {
115        trace!(
116            "reached beginning of search at offset {at} without hitting \
117             a dead state, quitting to avoid potential false positive match",
118        );
119        return Err(RetryError::Quadratic(RetryQuadraticError::new()));
120    }
121    Ok(mat)
122}
123
124#[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> {
131    let mut mat = None;
132    let mut sid = dfa.start_state_reverse(cache, input)?;
133    if input.start() == input.end() {
134        hybrid_eoi_rev(dfa, cache, input, &mut sid, &mut mat)?;
135        return Ok(mat);
136    }
137    let mut at = input.end() - 1;
138    loop {
139        sid = dfa
140            .next_state(cache, sid, input.haystack()[at])
141            .map_err(|_| MatchError::gave_up(at))?;
142        if sid.is_tagged() {
143            if sid.is_match() {
144                let 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.
149                mat = Some(HalfMatch::new(pattern, at + 1));
150            } else if sid.is_dead() {
151                return Ok(mat);
152            } else if sid.is_quit() {
153                return Err(MatchError::quit(input.haystack()[at], at).into());
154            }
155        }
156        if at == input.start() {
157            break;
158        }
159        at -= 1;
160        if at < min_start {
161            trace!(
162                "reached position {at} which is before the previous literal \
163				 match, quitting to avoid quadratic behavior",
164            );
165            return Err(RetryError::Quadratic(RetryQuadraticError::new()));
166        }
167    }
168    let 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.
171    if at == input.start()
172        && mat.map_or(false, |m| m.offset() > input.start())
173        && !was_dead
174    {
175        trace!(
176            "reached beginning of search at offset {at} without hitting \
177             a dead state, quitting to avoid potential false positive match",
178        );
179        return Err(RetryError::Quadratic(RetryQuadraticError::new()));
180    }
181    Ok(mat)
182}
183
184#[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> {
192    use crate::dfa::Automaton;
193
194    let sp = input.get_span();
195    if sp.start > 0 {
196        let byte = input.haystack()[sp.start - 1];
197        *sid = dfa.next_state(*sid, byte);
198        if dfa.is_match_state(*sid) {
199            let pattern = dfa.match_pattern(*sid, 0);
200            *mat = Some(HalfMatch::new(pattern, sp.start));
201        } else if dfa.is_quit_state(*sid) {
202            return Err(MatchError::quit(byte, sp.start - 1));
203        }
204    } else {
205        *sid = dfa.next_eoi_state(*sid);
206        if dfa.is_match_state(*sid) {
207            let 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.
212        debug_assert!(!dfa.is_quit_state(*sid));
213    }
214    Ok(())
215}
216
217#[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> {
226    let sp = input.get_span();
227    if sp.start > 0 {
228        let byte = input.haystack()[sp.start - 1];
229        *sid = dfa
230            .next_state(cache, *sid, byte)
231            .map_err(|_| MatchError::gave_up(sp.start))?;
232        if sid.is_match() {
233            let pattern = dfa.match_pattern(cache, *sid, 0);
234            *mat = Some(HalfMatch::new(pattern, sp.start));
235        } else if sid.is_quit() {
236            return 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))?;
242        if sid.is_match() {
243            let 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.
248        debug_assert!(!sid.is_quit());
249    }
250    Ok(())
251}