Debian Codegraph @

third_party/rust/regex-automata/tests/dfa/suite.rs

raw
1 use {
2 anyhow::Result,
3 regex_automata::{
4 dfa::{
5 self, dense, regex::Regex, sparse, Automaton, OverlappingState,
6 StartKind,
7 },
8 nfa::thompson,
9 util::{prefilter::Prefilter, syntax},
10 Anchored, Input, PatternSet,
11 },
12 regex_syntax::hir,
13 regex_test::{
14 CompiledRegex, Match, RegexTest, SearchKind, Span, TestResult,
15 TestRunner,
16 },
17 };
18
19 use crate::{create_input, suite, untestify_kind};
20
21 const EXPANSIONS: &[&str] = &["is_match", "find", "which"];
22
23 /// Runs the test suite with the default configuration.
24 #[test]
25 fn unminimized_default() -> Result<()> {
26 let builder = Regex::builder();
27 TestRunner::new()?
28 .expand(EXPANSIONS, |t| t.compiles())
29 .blacklist("expensive")
30 .test_iter(suite()?.iter(), dense_compiler(builder))
31 .assert();
32 Ok(())
33 }
34
35 /// Runs the test suite with the default configuration and a prefilter enabled,
36 /// if one can be built.
37 #[test]
38 fn unminimized_prefilter() -> Result<()> {
39 let my_compiler = |test: &RegexTest, regexes: &[String]| {
40 // Parse regexes as HIRs so we can get literals to build a prefilter.
41 let mut hirs = vec![];
42 for pattern in regexes.iter() {
43 hirs.push(syntax::parse_with(pattern, &config_syntax(test))?);
44 }
45 let kind = match untestify_kind(test.match_kind()) {
46 None => return Ok(CompiledRegex::skip()),
47 Some(kind) => kind,
48 };
49 let pre = Prefilter::from_hirs_prefix(kind, &hirs);
50 let mut builder = Regex::builder();
51 builder.dense(dense::DFA::config().prefilter(pre));
52 compiler(builder, |_, _, re| {
53 Ok(CompiledRegex::compiled(move |test| -> TestResult {
54 run_test(&re, test)
55 }))
56 })(test, regexes)
57 };
58 TestRunner::new()?
59 .expand(EXPANSIONS, |t| t.compiles())
60 .blacklist("expensive")
61 .test_iter(suite()?.iter(), my_compiler)
62 .assert();
63 Ok(())
64 }
65
66 /// Runs the test suite with start states specialized.
67 #[test]
68 fn unminimized_specialized_start_states() -> Result<()> {
69 let mut builder = Regex::builder();
70 builder.dense(dense::Config::new().specialize_start_states(true));
71
72 TestRunner::new()?
73 .expand(EXPANSIONS, |t| t.compiles())
74 .blacklist("expensive")
75 .test_iter(suite()?.iter(), dense_compiler(builder))
76 .assert();
77 Ok(())
78 }
79
80 /// Runs the test suite with byte classes disabled.
81 #[test]
82 fn unminimized_no_byte_class() -> Result<()> {
83 let mut builder = Regex::builder();
84 builder.dense(dense::Config::new().byte_classes(false));
85
86 TestRunner::new()?
87 .expand(EXPANSIONS, |t| t.compiles())
88 .blacklist("expensive")
89 .test_iter(suite()?.iter(), dense_compiler(builder))
90 .assert();
91 Ok(())
92 }
93
94 /// Runs the test suite with NFA shrinking enabled.
95 #[test]
96 fn unminimized_nfa_shrink() -> Result<()> {
97 let mut builder = Regex::builder();
98 builder.thompson(thompson::Config::new().shrink(true));
99
100 TestRunner::new()?
101 .expand(EXPANSIONS, |t| t.compiles())
102 .blacklist("expensive")
103 .test_iter(suite()?.iter(), dense_compiler(builder))
104 .assert();
105 Ok(())
106 }
107
108 /// Runs the test suite on a minimized DFA with an otherwise default
109 /// configuration.
110 #[test]
111 fn minimized_default() -> Result<()> {
112 let mut builder = Regex::builder();
113 builder.dense(dense::Config::new().minimize(true));
114 TestRunner::new()?
115 .expand(EXPANSIONS, |t| t.compiles())
116 .blacklist("expensive")
117 .test_iter(suite()?.iter(), dense_compiler(builder))
118 .assert();
119 Ok(())
120 }
121
122 /// Runs the test suite on a minimized DFA with byte classes disabled.
123 #[test]
124 fn minimized_no_byte_class() -> Result<()> {
125 let mut builder = Regex::builder();
126 builder.dense(dense::Config::new().minimize(true).byte_classes(false));
127
128 TestRunner::new()?
129 .expand(EXPANSIONS, |t| t.compiles())
130 .blacklist("expensive")
131 .test_iter(suite()?.iter(), dense_compiler(builder))
132 .assert();
133 Ok(())
134 }
135
136 /// Runs the test suite on a sparse unminimized DFA.
137 #[test]
138 fn sparse_unminimized_default() -> Result<()> {
139 let builder = Regex::builder();
140 TestRunner::new()?
141 .expand(EXPANSIONS, |t| t.compiles())
142 .blacklist("expensive")
143 .test_iter(suite()?.iter(), sparse_compiler(builder))
144 .assert();
145 Ok(())
146 }
147
148 /// Runs the test suite on a sparse unminimized DFA with prefilters enabled.
149 #[test]
150 fn sparse_unminimized_prefilter() -> Result<()> {
151 let my_compiler = |test: &RegexTest, regexes: &[String]| {
152 // Parse regexes as HIRs so we can get literals to build a prefilter.
153 let mut hirs = vec![];
154 for pattern in regexes.iter() {
155 hirs.push(syntax::parse_with(pattern, &config_syntax(test))?);
156 }
157 let kind = match untestify_kind(test.match_kind()) {
158 None => return Ok(CompiledRegex::skip()),
159 Some(kind) => kind,
160 };
161 let pre = Prefilter::from_hirs_prefix(kind, &hirs);
162 let mut builder = Regex::builder();
163 builder.dense(dense::DFA::config().prefilter(pre));
164 compiler(builder, |builder, _, re| {
165 let fwd = re.forward().to_sparse()?;
166 let rev = re.reverse().to_sparse()?;
167 let re = builder.build_from_dfas(fwd, rev);
168 Ok(CompiledRegex::compiled(move |test| -> TestResult {
169 run_test(&re, test)
170 }))
171 })(test, regexes)
172 };
173 TestRunner::new()?
174 .expand(EXPANSIONS, |t| t.compiles())
175 .blacklist("expensive")
176 .test_iter(suite()?.iter(), my_compiler)
177 .assert();
178 Ok(())
179 }
180
181 /// Another basic sanity test that checks we can serialize and then deserialize
182 /// a regex, and that the resulting regex can be used for searching correctly.
183 #[test]
184 fn serialization_unminimized_default() -> Result<()> {
185 let builder = Regex::builder();
186 let my_compiler = |builder| {
187 compiler(builder, |builder, _, re| {
188 let builder = builder.clone();
189 let (fwd_bytes, _) = re.forward().to_bytes_native_endian();
190 let (rev_bytes, _) = re.reverse().to_bytes_native_endian();
191 Ok(CompiledRegex::compiled(move |test| -> TestResult {
192 let fwd: dense::DFA<&[u32]> =
193 dense::DFA::from_bytes(&fwd_bytes).unwrap().0;
194 let rev: dense::DFA<&[u32]> =
195 dense::DFA::from_bytes(&rev_bytes).unwrap().0;
196 let re = builder.build_from_dfas(fwd, rev);
197
198 run_test(&re, test)
199 }))
200 })
201 };
202 TestRunner::new()?
203 .expand(EXPANSIONS, |t| t.compiles())
204 .blacklist("expensive")
205 .test_iter(suite()?.iter(), my_compiler(builder))
206 .assert();
207 Ok(())
208 }
209
210 /// A basic sanity test that checks we can serialize and then deserialize a
211 /// regex using sparse DFAs, and that the resulting regex can be used for
212 /// searching correctly.
213 #[test]
214 fn sparse_serialization_unminimized_default() -> Result<()> {
215 let builder = Regex::builder();
216 let my_compiler = |builder| {
217 compiler(builder, |builder, _, re| {
218 let builder = builder.clone();
219 let fwd_bytes = re.forward().to_sparse()?.to_bytes_native_endian();
220 let rev_bytes = re.reverse().to_sparse()?.to_bytes_native_endian();
221 Ok(CompiledRegex::compiled(move |test| -> TestResult {
222 let fwd: sparse::DFA<&[u8]> =
223 sparse::DFA::from_bytes(&fwd_bytes).unwrap().0;
224 let rev: sparse::DFA<&[u8]> =
225 sparse::DFA::from_bytes(&rev_bytes).unwrap().0;
226 let re = builder.build_from_dfas(fwd, rev);
227 run_test(&re, test)
228 }))
229 })
230 };
231 TestRunner::new()?
232 .expand(EXPANSIONS, |t| t.compiles())
233 .blacklist("expensive")
234 .test_iter(suite()?.iter(), my_compiler(builder))
235 .assert();
236 Ok(())
237 }
238
239 fn dense_compiler(
240 builder: dfa::regex::Builder,
241 ) -> impl FnMut(&RegexTest, &[String]) -> Result<CompiledRegex> {
242 compiler(builder, |_, _, re| {
243 Ok(CompiledRegex::compiled(move |test| -> TestResult {
244 run_test(&re, test)
245 }))
246 })
247 }
248
249 fn sparse_compiler(
250 builder: dfa::regex::Builder,
251 ) -> impl FnMut(&RegexTest, &[String]) -> Result<CompiledRegex> {
252 compiler(builder, |builder, _, re| {
253 let fwd = re.forward().to_sparse()?;
254 let rev = re.reverse().to_sparse()?;
255 let re = builder.build_from_dfas(fwd, rev);
256 Ok(CompiledRegex::compiled(move |test| -> TestResult {
257 run_test(&re, test)
258 }))
259 })
260 }
261
262 fn compiler(
263 mut builder: dfa::regex::Builder,
264 mut create_matcher: impl FnMut(
265 &dfa::regex::Builder,
266 Option<Prefilter>,
267 Regex,
268 ) -> Result<CompiledRegex>,
269 ) -> impl FnMut(&RegexTest, &[String]) -> Result<CompiledRegex> {
270 move |test, regexes| {
271 // Parse regexes as HIRs for some analysis below.
272 let mut hirs = vec![];
273 for pattern in regexes.iter() {
274 hirs.push(syntax::parse_with(pattern, &config_syntax(test))?);
275 }
276
277 // Get a prefilter in case the test wants it.
278 let kind = match untestify_kind(test.match_kind()) {
279 None => return Ok(CompiledRegex::skip()),
280 Some(kind) => kind,
281 };
282 let pre = Prefilter::from_hirs_prefix(kind, &hirs);
283
284 // Check if our regex contains things that aren't supported by DFAs.
285 // That is, Unicode word boundaries when searching non-ASCII text.
286 if !test.haystack().is_ascii() {
287 for hir in hirs.iter() {
288 let looks = hir.properties().look_set();
289 if looks.contains(hir::Look::WordUnicode)
290 || looks.contains(hir::Look::WordUnicodeNegate)
291 {
292 return Ok(CompiledRegex::skip());
293 }
294 }
295 }
296 if !configure_regex_builder(test, &mut builder) {
297 return Ok(CompiledRegex::skip());
298 }
299 create_matcher(&builder, pre, builder.build_many(&regexes)?)
300 }
301 }
302
303 fn run_test<A: Automaton>(re: &Regex<A>, test: &RegexTest) -> TestResult {
304 let input = create_input(test);
305 match test.additional_name() {
306 "is_match" => TestResult::matched(re.is_match(input.earliest(true))),
307 "find" => match test.search_kind() {
308 SearchKind::Earliest | SearchKind::Leftmost => {
309 let input =
310 input.earliest(test.search_kind() == SearchKind::Earliest);
311 TestResult::matches(
312 re.find_iter(input)
313 .take(test.match_limit().unwrap_or(std::usize::MAX))
314 .map(|m| Match {
315 id: m.pattern().as_usize(),
316 span: Span { start: m.start(), end: m.end() },
317 }),
318 )
319 }
320 SearchKind::Overlapping => {
321 try_search_overlapping(re, &input).unwrap()
322 }
323 },
324 "which" => match test.search_kind() {
325 SearchKind::Earliest | SearchKind::Leftmost => {
326 // There are no "which" APIs for standard searches.
327 TestResult::skip()
328 }
329 SearchKind::Overlapping => {
330 let dfa = re.forward();
331 let mut patset = PatternSet::new(dfa.pattern_len());
332 dfa.try_which_overlapping_matches(&input, &mut patset)
333 .unwrap();
334 TestResult::which(patset.iter().map(|p| p.as_usize()))
335 }
336 },
337 name => TestResult::fail(&format!("unrecognized test name: {}", name)),
338 }
339 }
340
341 /// Configures the given regex builder with all relevant settings on the given
342 /// regex test.
343 ///
344 /// If the regex test has a setting that is unsupported, then this returns
345 /// false (implying the test should be skipped).
346 fn configure_regex_builder(
347 test: &RegexTest,
348 builder: &mut dfa::regex::Builder,
349 ) -> bool {
350 let match_kind = match untestify_kind(test.match_kind()) {
351 None => return false,
352 Some(k) => k,
353 };
354
355 let starts = if test.anchored() {
356 StartKind::Anchored
357 } else {
358 StartKind::Unanchored
359 };
360 let mut dense_config = dense::Config::new()
361 .start_kind(starts)
362 .match_kind(match_kind)
363 .unicode_word_boundary(true);
364 // When doing an overlapping search, we might try to find the start of each
365 // match with a custom search routine. In that case, we need to tell the
366 // reverse search (for the start offset) which pattern to look for. The
367 // only way that API works is when anchored starting states are compiled
368 // for each pattern. This does technically also enable it for the forward
369 // DFA, but we're okay with that.
370 if test.search_kind() == SearchKind::Overlapping {
371 dense_config = dense_config.starts_for_each_pattern(true);
372 }
373
374 builder
375 .syntax(config_syntax(test))
376 .thompson(config_thompson(test))
377 .dense(dense_config);
378 true
379 }
380
381 /// Configuration of a Thompson NFA compiler from a regex test.
382 fn config_thompson(test: &RegexTest) -> thompson::Config {
383 let mut lookm = regex_automata::util::look::LookMatcher::new();
384 lookm.set_line_terminator(test.line_terminator());
385 thompson::Config::new().utf8(test.utf8()).look_matcher(lookm)
386 }
387
388 /// Configuration of the regex syntax from a regex test.
389 fn config_syntax(test: &RegexTest) -> syntax::Config {
390 syntax::Config::new()
391 .case_insensitive(test.case_insensitive())
392 .unicode(test.unicode())
393 .utf8(test.utf8())
394 .line_terminator(test.line_terminator())
395 }
396
397 /// Execute an overlapping search, and for each match found, also find its
398 /// overlapping starting positions.
399 ///
400 /// N.B. This routine used to be part of the crate API, but 1) it wasn't clear
401 /// to me how useful it was and 2) it wasn't clear to me what its semantics
402 /// should be. In particular, a potentially surprising footgun of this routine
403 /// that it is worst case *quadratic* in the size of the haystack. Namely, it's
404 /// possible to report a match at every position, and for every such position,
405 /// scan all the way to the beginning of the haystack to find the starting
406 /// position. Typical leftmost non-overlapping searches don't suffer from this
407 /// because, well, matches can't overlap. So subsequent searches after a match
408 /// is found don't revisit previously scanned parts of the haystack.
409 ///
410 /// Its semantics can be strange for other reasons too. For example, given
411 /// the regex '.*' and the haystack 'zz', the full set of overlapping matches
412 /// is: [0, 0], [1, 1], [0, 1], [2, 2], [1, 2], [0, 2]. The ordering of
413 /// those matches is quite strange, but makes sense when you think about the
414 /// implementation: an end offset is found left-to-right, and then one or more
415 /// starting offsets are found right-to-left.
416 ///
417 /// Nevertheless, we provide this routine in our test suite because it's
418 /// useful to test the low level DFA overlapping search and our test suite
419 /// is written in a way that requires starting offsets.
420 fn try_search_overlapping<A: Automaton>(
421 re: &Regex<A>,
422 input: &Input<'_>,
423 ) -> Result<TestResult> {
424 let mut matches = vec![];
425 let mut fwd_state = OverlappingState::start();
426 let (fwd_dfa, rev_dfa) = (re.forward(), re.reverse());
427 while let Some(end) = {
428 fwd_dfa.try_search_overlapping_fwd(input, &mut fwd_state)?;
429 fwd_state.get_match()
430 } {
431 let revsearch = input
432 .clone()
433 .range(input.start()..end.offset())
434 .anchored(Anchored::Pattern(end.pattern()))
435 .earliest(false);
436 let mut rev_state = OverlappingState::start();
437 while let Some(start) = {
438 rev_dfa.try_search_overlapping_rev(&revsearch, &mut rev_state)?;
439 rev_state.get_match()
440 } {
441 let span = Span { start: start.offset(), end: end.offset() };
442 let mat = Match { id: end.pattern().as_usize(), span };
443 matches.push(mat);
444 }
445 }
446 Ok(TestResult::matches(matches))
447 }