Coverage Report

Created: 2025-12-31 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/regex-automata-0.4.13/src/meta/limited.rs
Line
Count
Source
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
                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")]
125
0
pub(crate) fn hybrid_try_search_half_rev(
126
0
    dfa: &crate::hybrid::dfa::DFA,
127
0
    cache: &mut crate::hybrid::dfa::Cache,
128
0
    input: &Input<'_>,
129
0
    min_start: usize,
130
0
) -> Result<Option<HalfMatch>, RetryError> {
131
0
    let mut mat = None;
132
0
    let mut sid = dfa.start_state_reverse(cache, input)?;
133
0
    if input.start() == input.end() {
134
0
        hybrid_eoi_rev(dfa, cache, input, &mut sid, &mut mat)?;
135
0
        return Ok(mat);
136
0
    }
137
0
    let mut at = input.end() - 1;
138
    loop {
139
0
        sid = dfa
140
0
            .next_state(cache, sid, input.haystack()[at])
141
0
            .map_err(|_| MatchError::gave_up(at))?;
142
0
        if sid.is_tagged() {
143
0
            if sid.is_match() {
144
0
                let pattern = dfa.match_pattern(cache, sid, 0);
145
0
                // Since reverse searches report the beginning of a
146
0
                // match and the beginning is inclusive (not exclusive
147
0
                // like the end of a match), we add 1 to make it
148
0
                // inclusive.
149
0
                mat = Some(HalfMatch::new(pattern, at + 1));
150
0
            } else if sid.is_dead() {
151
0
                return Ok(mat);
152
0
            } else if sid.is_quit() {
153
0
                return Err(MatchError::quit(input.haystack()[at], at).into());
154
0
            }
155
0
        }
156
0
        if at == input.start() {
157
0
            break;
158
0
        }
159
0
        at -= 1;
160
0
        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
0
            return Err(RetryError::Quadratic(RetryQuadraticError::new()));
166
0
        }
167
    }
168
0
    let was_dead = sid.is_dead();
169
0
    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
0
    if at == input.start()
172
0
        && mat.map_or(false, |m| m.offset() > input.start())
173
0
        && !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
0
        return Err(RetryError::Quadratic(RetryQuadraticError::new()));
180
0
    }
181
0
    Ok(mat)
182
0
}
183
184
#[cfg(feature = "dfa-build")]
185
#[cfg_attr(feature = "perf-inline", inline(always))]
186
fn 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))]
219
0
fn hybrid_eoi_rev(
220
0
    dfa: &crate::hybrid::dfa::DFA,
221
0
    cache: &mut crate::hybrid::dfa::Cache,
222
0
    input: &Input<'_>,
223
0
    sid: &mut crate::hybrid::LazyStateID,
224
0
    mat: &mut Option<HalfMatch>,
225
0
) -> Result<(), MatchError> {
226
0
    let sp = input.get_span();
227
0
    if sp.start > 0 {
228
0
        let byte = input.haystack()[sp.start - 1];
229
0
        *sid = dfa
230
0
            .next_state(cache, *sid, byte)
231
0
            .map_err(|_| MatchError::gave_up(sp.start))?;
232
0
        if sid.is_match() {
233
0
            let pattern = dfa.match_pattern(cache, *sid, 0);
234
0
            *mat = Some(HalfMatch::new(pattern, sp.start));
235
0
        } else if sid.is_quit() {
236
0
            return Err(MatchError::quit(byte, sp.start - 1));
237
0
        }
238
    } else {
239
0
        *sid = dfa
240
0
            .next_eoi_state(cache, *sid)
241
0
            .map_err(|_| MatchError::gave_up(sp.start))?;
242
0
        if sid.is_match() {
243
0
            let pattern = dfa.match_pattern(cache, *sid, 0);
244
0
            *mat = Some(HalfMatch::new(pattern, 0));
245
0
        }
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
0
        debug_assert!(!sid.is_quit());
249
    }
250
0
    Ok(())
251
0
}