Debian Codegraph @

debian/rust-vendor/regex-automata/tests/hybrid/api.rs

raw
1 use std::error::Error;
2
3 use regex_automata::{
4 hybrid::dfa::{OverlappingState, DFA},
5 nfa::thompson,
6 HalfMatch, Input, MatchError,
7 };
8
9 // A tagged start state can be reached after the DFA has recorded a match. A
10 // prefilter must not skip to a new candidate while that match is pending.
11 #[test]
12 #[cfg(feature = "perf-literal-multisubstring")]
13 fn prefilter_does_not_skip_pending_match() -> Result<(), Box<dyn Error>> {
14 use regex_automata::{util::prefilter::Prefilter, Anchored, MatchKind};
15
16 let pre = Prefilter::new(MatchKind::LeftmostFirst, &["ab", "c"])
17 .expect("prefilter");
18 let dfa = DFA::builder()
19 .configure(
20 DFA::config().prefilter(Some(pre)).starts_for_each_pattern(true),
21 )
22 .build(r"(?:ab|c)*c")?;
23 let mut cache = dfa.create_cache();
24 let haystack = "cabac";
25 let expected = Some(HalfMatch::must(0, 1));
26
27 // Cache the anchored start state before the equivalent state is reached
28 // via an ordinary transition. Otherwise, that state is left untagged and
29 // the prefilter bug remains hidden.
30 let input = Input::new(haystack).anchored(Anchored::Yes);
31 assert_eq!(expected, dfa.try_search_fwd(&mut cache, &input)?);
32 assert_eq!(
33 expected,
34 dfa.try_search_fwd(&mut cache, &Input::new(haystack))?,
35 );
36 Ok(())
37 }
38
39 // Tests that too many cache resets cause the lazy DFA to quit.
40 //
41 // We only test this on 64-bit because the test is gingerly crafted based on
42 // implementation details of cache sizes. It's not a great test because of
43 // that, but it does check some interesting properties around how positions are
44 // reported when a search "gives up."
45 //
46 // NOTE: If you change something in lazy DFA implementation that causes this
47 // test to fail by reporting different "gave up" positions, then it's generally
48 // okay to update the positions in the test below as long as you're sure your
49 // changes are correct. Namely, it is expected that if there are changes in the
50 // cache size (or changes in how big things are inside the cache), then its
51 // utilization may change slightly and thus impact where a search gives up.
52 // Precisely where a search gives up is not an API guarantee, so changing the
53 // offsets here is OK.
54 #[test]
55 #[cfg(target_pointer_width = "64")]
56 #[cfg(not(miri))]
57 fn too_many_cache_resets_cause_quit() -> Result<(), Box<dyn Error>> {
58 // This is a carefully chosen regex. The idea is to pick one that requires
59 // some decent number of states (hence the bounded repetition). But we
60 // specifically choose to create a class with an ASCII letter and a
61 // non-ASCII letter so that we can check that no new states are created
62 // once the cache is full. Namely, if we fill up the cache on a haystack
63 // of 'a's, then in order to match one 'β', a new state will need to be
64 // created since a 'β' is encoded with multiple bytes.
65 //
66 // So we proceed by "filling" up the cache by searching a haystack of just
67 // 'a's. The cache won't have enough room to add enough states to find the
68 // match (because of the bounded repetition), which should result in it
69 // giving up before it finds a match.
70 //
71 // Since there's now no more room to create states, we search a haystack
72 // of 'β' and confirm that it gives up immediately.
73 let pattern = r"[aβ]{99}";
74 let dfa = DFA::builder()
75 .configure(
76 // Configure it so that we have the minimum cache capacity
77 // possible. And that if any resets occur, the search quits.
78 DFA::config()
79 .skip_cache_capacity_check(true)
80 .cache_capacity(0)
81 .minimum_cache_clear_count(Some(0)),
82 )
83 .thompson(thompson::NFA::config())
84 .build(pattern)?;
85 let mut cache = dfa.create_cache();
86
87 let haystack = "a".repeat(101).into_bytes();
88 let err = MatchError::gave_up(24);
89 // Notice that we make the same amount of progress in each search! That's
90 // because the cache is reused and already has states to handle the first
91 // N bytes.
92 assert_eq!(
93 Err(err.clone()),
94 dfa.try_search_fwd(&mut cache, &Input::new(&haystack))
95 );
96 assert_eq!(
97 Err(err.clone()),
98 dfa.try_search_overlapping_fwd(
99 &mut cache,
100 &Input::new(&haystack),
101 &mut OverlappingState::start()
102 ),
103 );
104
105 let haystack = "β".repeat(101).into_bytes();
106 let err = MatchError::gave_up(2);
107 assert_eq!(
108 Err(err),
109 dfa.try_search_fwd(&mut cache, &Input::new(&haystack))
110 );
111 // no need to test that other find routines quit, since we did that above
112
113 // OK, if we reset the cache, then we should be able to create more states
114 // and make more progress with searching for betas.
115 cache.reset(&dfa);
116 let err = MatchError::gave_up(26);
117 assert_eq!(
118 Err(err),
119 dfa.try_search_fwd(&mut cache, &Input::new(&haystack))
120 );
121
122 // ... switching back to ASCII still makes progress since it just needs to
123 // set transitions on existing states!
124 let haystack = "a".repeat(101).into_bytes();
125 let err = MatchError::gave_up(13);
126 assert_eq!(
127 Err(err),
128 dfa.try_search_fwd(&mut cache, &Input::new(&haystack))
129 );
130
131 Ok(())
132 }
133
134 // Tests that quit bytes in the forward direction work correctly.
135 #[test]
136 fn quit_fwd() -> Result<(), Box<dyn Error>> {
137 let dfa = DFA::builder()
138 .configure(DFA::config().quit(b'x', true))
139 .build("[[:word:]]+$")?;
140 let mut cache = dfa.create_cache();
141
142 assert_eq!(
143 dfa.try_search_fwd(&mut cache, &Input::new("abcxyz")),
144 Err(MatchError::quit(b'x', 3)),
145 );
146 assert_eq!(
147 dfa.try_search_overlapping_fwd(
148 &mut cache,
149 &Input::new(b"abcxyz"),
150 &mut OverlappingState::start()
151 ),
152 Err(MatchError::quit(b'x', 3)),
153 );
154
155 Ok(())
156 }
157
158 // Tests that quit bytes in the reverse direction work correctly.
159 #[test]
160 fn quit_rev() -> Result<(), Box<dyn Error>> {
161 let dfa = DFA::builder()
162 .configure(DFA::config().quit(b'x', true))
163 .thompson(thompson::Config::new().reverse(true))
164 .build("^[[:word:]]+")?;
165 let mut cache = dfa.create_cache();
166
167 assert_eq!(
168 dfa.try_search_rev(&mut cache, &Input::new("abcxyz")),
169 Err(MatchError::quit(b'x', 3)),
170 );
171
172 Ok(())
173 }
174
175 // Tests that if we heuristically enable Unicode word boundaries but then
176 // instruct that a non-ASCII byte should NOT be a quit byte, then the builder
177 // will panic.
178 #[test]
179 #[should_panic]
180 fn quit_panics() {
181 DFA::config().unicode_word_boundary(true).quit(b'\xFF', false);
182 }
183
184 // This tests an intesting case where even if the Unicode word boundary option
185 // is disabled, setting all non-ASCII bytes to be quit bytes will cause Unicode
186 // word boundaries to be enabled.
187 #[test]
188 fn unicode_word_implicitly_works() -> Result<(), Box<dyn Error>> {
189 let mut config = DFA::config();
190 for b in 0x80..=0xFF {
191 config = config.quit(b, true);
192 }
193 let dfa = DFA::builder().configure(config).build(r"\b")?;
194 let mut cache = dfa.create_cache();
195 let expected = HalfMatch::must(0, 1);
196 assert_eq!(
197 Ok(Some(expected)),
198 dfa.try_search_fwd(&mut cache, &Input::new(" a")),
199 );
200 Ok(())
201 }