Debian Codegraph @

debian/rust-vendor/fancy-regex/benches/bench.rs

raw
1 // Copyright 2016 The Fancy Regex Authors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 #[macro_use]
22 extern crate criterion;
23
24 use criterion::Criterion;
25 use std::time::Duration;
26
27 use fancy_regex::internal::{
28 analyze, compile, optimize, run_default, AnalyzeContext, CompileOptions,
29 };
30 use fancy_regex::seek_pattern_is_useful;
31 use fancy_regex::Expr;
32 use fancy_regex::Regex as FancyRegex;
33 use regex::Regex;
34
35 fn parse_lifetime_re(c: &mut Criterion) {
36 c.bench_function("parse_lifetime_re", |b| {
37 b.iter(|| Expr::parse_tree("\\'[a-zA-Z_][a-zA-Z0-9_]*(?!\\')\\b").unwrap())
38 });
39 }
40
41 fn parse_literal_re(c: &mut Criterion) {
42 c.bench_function("parse_literal_re", |b| {
43 b.iter(|| Expr::parse_tree("^\\\\([!-/:-@\\[-`\\{-~aftnrv]|[0-7]{1,3}|x[0-9a-fA-F]{2}|x\\{[0-9a-fA-F]{1,6}\\})").unwrap())
44 });
45 }
46
47 fn parse_literal_re_regex(c: &mut Criterion) {
48 c.bench_function("parse_literal_re_regex", |b| {
49 b.iter(|| Regex::new("^\\\\([!-/:-@\\[-`\\{-~aftnrv]|[0-7]{1,3}|x[0-9a-fA-F]{2}|x\\{[0-9a-fA-F]{1,6}\\})").unwrap())
50 });
51 }
52
53 fn parse_misc(c: &mut Criterion) {
54 c.bench_function("parse_misc", |b| {
55 b.iter(|| Expr::parse_tree("^\\p{L}|\\p{N}|\\s|.|\\d").unwrap())
56 });
57 }
58
59 fn analyze_literal_re(c: &mut Criterion) {
60 let re = "^\\\\([!-/:-@\\[-`\\{-~aftnrv]|[0-7]{1,3}|x[0-9a-fA-F]{2}|x\\{[0-9a-fA-F]{1,6}\\})";
61 let tree = Expr::parse_tree(re).unwrap();
62 c.bench_function("analyze_literal_re", |b| {
63 b.iter(|| analyze(&tree, AnalyzeContext::default()).unwrap())
64 });
65 }
66
67 fn run_backtrack(c: &mut Criterion) {
68 let tree = Expr::parse_tree("^.*?(([ab]+)\\1b)").unwrap();
69 let a = analyze(
70 &tree,
71 AnalyzeContext {
72 explicit_capture_group_0: true,
73 ..Default::default()
74 },
75 )
76 .unwrap();
77 let p = compile(
78 &a,
79 CompileOptions {
80 anchored: true,
81 contains_subroutines: tree.contains_subroutines,
82 ..CompileOptions::default()
83 },
84 )
85 .unwrap();
86 c.bench_function("run_backtrack", |b| {
87 b.iter(|| {
88 let result = run_default(&p, "babab", 0).unwrap();
89 assert_eq!(result, Some(vec![0, 5, 0, 2]));
90 return result;
91 })
92 });
93 }
94
95 // The following regex is a pathological case for backtracking
96 // implementations, see README.md:
97 fn run_tricky(c: &mut Criterion) {
98 let tree = Expr::parse_tree("(a|b|ab)*bc").unwrap();
99 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
100 let p = compile(
101 &a,
102 CompileOptions {
103 contains_subroutines: tree.contains_subroutines,
104 ..CompileOptions::default()
105 },
106 )
107 .unwrap();
108 let mut s = String::new();
109 for _ in 0..28 {
110 s.push_str("ab");
111 }
112 s.push_str("ac");
113 c.bench_function("run_tricky", |b| b.iter(|| run_default(&p, &s, 0).unwrap()));
114 }
115
116 fn run_backtrack_limit(c: &mut Criterion) {
117 let tree = Expr::parse_tree("(?i)(a|b|ab)*(?>c)").unwrap();
118 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
119 let p = compile(
120 &a,
121 CompileOptions {
122 contains_subroutines: tree.contains_subroutines,
123 ..CompileOptions::default()
124 },
125 )
126 .unwrap();
127 let s = "abababababababababababababababababababababababababababab";
128 c.bench_function("run_backtrack_limit", |b| {
129 b.iter(|| run_default(&p, &s, 0).unwrap_err())
130 });
131 }
132
133 #[cfg(feature = "variable-lookbehinds")]
134 fn const_size_lookbehind(c: &mut Criterion) {
135 // Benchmark const-size lookbehind (should use simple GoBack)
136 let tree = Expr::parse_tree(r"(?<=ab)x").unwrap();
137 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
138 let p = compile(
139 &a,
140 CompileOptions {
141 contains_subroutines: tree.contains_subroutines,
142 ..CompileOptions::default()
143 },
144 )
145 .unwrap();
146 let input = "abx";
147 c.bench_function("const_size_lookbehind", |b| {
148 b.iter(|| run_default(&p, input, 0).unwrap())
149 });
150 }
151
152 #[cfg(feature = "variable-lookbehinds")]
153 fn variable_size_lookbehind(c: &mut Criterion) {
154 // Benchmark variable-size lookbehind (uses reverse DFA)
155 let tree = Expr::parse_tree(r"(?<=a+b+)x").unwrap();
156 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
157 let p = compile(
158 &a,
159 CompileOptions {
160 contains_subroutines: tree.contains_subroutines,
161 ..CompileOptions::default()
162 },
163 )
164 .unwrap();
165 let input = "aaabbbbx";
166 c.bench_function("variable_size_lookbehind", |b| {
167 b.iter(|| run_default(&p, input, 0).unwrap())
168 });
169 }
170
171 #[cfg(feature = "variable-lookbehinds")]
172 fn variable_size_alt_lookbehind(c: &mut Criterion) {
173 // Benchmark variable-size lookbehind with alternation
174 let tree = Expr::parse_tree(r"(?<=a|bc)x").unwrap();
175 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
176 let p = compile(
177 &a,
178 CompileOptions {
179 contains_subroutines: tree.contains_subroutines,
180 ..CompileOptions::default()
181 },
182 )
183 .unwrap();
184 let input = "bcx";
185 c.bench_function("variable_size_alt_lookbehind", |b| {
186 b.iter(|| run_default(&p, input, 0).unwrap())
187 });
188 }
189
190 #[cfg(feature = "variable-lookbehinds")]
191 criterion_group!(
192 name = lookbehind_benches;
193 config = Criterion::default();
194 targets = const_size_lookbehind,
195 variable_size_lookbehind,
196 variable_size_alt_lookbehind,
197 );
198
199 criterion_group!(
200 name = benches;
201 config = Criterion::default().warm_up_time(Duration::from_secs(10));
202 targets = parse_lifetime_re,
203 parse_literal_re,
204 parse_literal_re_regex,
205 parse_misc,
206 analyze_literal_re,
207 run_backtrack,
208 run_tricky,
209 );
210 criterion_group!(
211 name = slow_benches;
212 config = Criterion::default().sample_size(10);
213 targets = run_backtrack_limit,
214 );
215
216 fn continue_from_end_of_prev_match_short_haystack(c: &mut Criterion) {
217 // Benchmark \G with a short haystack that doesn't match
218 let tree = Expr::parse_tree(r"\Gfoo").unwrap();
219 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
220 let p = compile(
221 &a,
222 CompileOptions {
223 contains_subroutines: tree.contains_subroutines,
224 ..CompileOptions::default()
225 },
226 )
227 .unwrap();
228 let input = "bar"; // 3 bytes, doesn't match
229 c.bench_function("continue_from_end_of_prev_match_short_haystack", |b| {
230 b.iter(|| run_default(&p, input, 0).unwrap())
231 });
232 }
233
234 fn continue_from_end_of_prev_match_long_haystack(c: &mut Criterion) {
235 // Benchmark \G with a long haystack that doesn't match
236 let tree = Expr::parse_tree(r"\Gfoo").unwrap();
237 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
238 let p = compile(
239 &a,
240 CompileOptions {
241 contains_subroutines: tree.contains_subroutines,
242 ..CompileOptions::default()
243 },
244 )
245 .unwrap();
246 let mut input = String::new();
247 for _ in 0..10000 {
248 input.push('x');
249 }
250 c.bench_function("continue_from_end_of_prev_match_long_haystack", |b| {
251 b.iter(|| run_default(&p, &input, 0).unwrap())
252 });
253 }
254
255 criterion_group!(
256 name = continue_from_end_of_prev_match_benches;
257 config = Criterion::default();
258 targets = continue_from_end_of_prev_match_short_haystack,
259 continue_from_end_of_prev_match_long_haystack,
260 );
261
262 /// Shared logic for the backref-in-long-haystack seek benchmarks.
263 ///
264 /// Compiles `(abc)\1` with the given `seek` setting, builds a 10,000-`x` haystack
265 /// (optionally with `"abcabc"` appended), and registers a criterion benchmark under
266 /// `name`.
267 fn bench_backref_in_long_haystack(c: &mut Criterion, name: &str, seek: bool, with_match: bool) {
268 // Pattern with a backref — when seek is true the approximation inlines the group
269 // body ("abc"), so the engine jumps directly to "abc" occurrences and skips the rest.
270 let tree = Expr::parse_tree(r"(abc)\1").unwrap();
271 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
272 let p = compile(
273 &a,
274 CompileOptions {
275 contains_subroutines: tree.contains_subroutines,
276 seek_filter: if seek {
277 Some(seek_pattern_is_useful)
278 } else {
279 None
280 },
281 ..CompileOptions::default()
282 },
283 )
284 .unwrap();
285 let mut haystack = String::new();
286 for _ in 0..10_000 {
287 haystack.push('x');
288 }
289 if with_match {
290 // Place the match target at the very end so the seek pre-filter must scan
291 // the entire haystack before finding the single candidate position.
292 haystack.push_str("abcabc");
293 }
294 c.bench_function(name, |b| b.iter(|| run_default(&p, &haystack, 0).unwrap()));
295 }
296
297 fn seek_backref_in_long_haystack(c: &mut Criterion) {
298 bench_backref_in_long_haystack(c, "seek_backref_in_long_haystack", true, true);
299 }
300
301 fn seek_backref_in_long_haystack_no_match(c: &mut Criterion) {
302 bench_backref_in_long_haystack(c, "seek_backref_in_long_haystack_no_match", true, false);
303 }
304
305 fn no_seek_backref_in_long_haystack(c: &mut Criterion) {
306 bench_backref_in_long_haystack(c, "no_seek_backref_in_long_haystack", false, true);
307 }
308
309 fn no_seek_backref_in_long_haystack_no_match(c: &mut Criterion) {
310 bench_backref_in_long_haystack(c, "no_seek_backref_in_long_haystack_no_match", false, false);
311 }
312
313 criterion_group!(
314 name = seek_benches;
315 config = Criterion::default();
316 targets = seek_backref_in_long_haystack,
317 seek_backref_in_long_haystack_no_match,
318 no_seek_backref_in_long_haystack,
319 no_seek_backref_in_long_haystack_no_match,
320 );
321
322 /// Shared logic for the worst-case seek benchmarks.
323 ///
324 /// Compiles `(\d{3})\1` with the given `seek` setting and builds a haystack of
325 /// `"1234567890"` repeated 100 times (optionally followed by `"00000"` to place a
326 /// match at the very end). Because every position in the all-digits haystack is
327 /// a candidate for `\d{3}`, the seek pre-filter cannot skip any positions — it
328 /// becomes pure overhead compared to running without seek.
329 fn bench_digit_backref_worst_case(c: &mut Criterion, name: &str, seek: bool, with_match: bool) {
330 let tree = Expr::parse_tree(r"(\d{3})\1").unwrap();
331 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
332 let p = compile(
333 &a,
334 CompileOptions {
335 contains_subroutines: tree.contains_subroutines,
336 seek_filter: if seek {
337 Some(seek_pattern_is_useful)
338 } else {
339 None
340 },
341 ..CompileOptions::default()
342 },
343 )
344 .unwrap();
345 let mut haystack = "1234567890".repeat(100);
346 if with_match {
347 // Append 5 zeros so the string ends with 6 zeros giving a match ("000" + "000")
348 // near the very end, forcing the seek pre-filter to traverse the whole haystack.
349 haystack.push_str("00000");
350 }
351 c.bench_function(name, |b| b.iter(|| run_default(&p, &haystack, 0).unwrap()));
352 }
353
354 fn seek_digit_backref_worst_case(c: &mut Criterion) {
355 bench_digit_backref_worst_case(c, "seek_digit_backref_worst_case", true, true);
356 }
357
358 fn seek_digit_backref_worst_case_no_match(c: &mut Criterion) {
359 bench_digit_backref_worst_case(c, "seek_digit_backref_worst_case_no_match", true, false);
360 }
361
362 fn no_seek_digit_backref_worst_case(c: &mut Criterion) {
363 bench_digit_backref_worst_case(c, "no_seek_digit_backref_worst_case", false, true);
364 }
365
366 fn no_seek_digit_backref_worst_case_no_match(c: &mut Criterion) {
367 bench_digit_backref_worst_case(c, "no_seek_digit_backref_worst_case_no_match", false, false);
368 }
369
370 criterion_group!(
371 name = seek_worst_case_benches;
372 config = Criterion::default();
373 targets = seek_digit_backref_worst_case,
374 seek_digit_backref_worst_case_no_match,
375 no_seek_digit_backref_worst_case,
376 no_seek_digit_backref_worst_case_no_match,
377 );
378
379 /// Shared logic for the case-insensitive Unicode backref benchmarks.
380 ///
381 /// `(?i)(\p{Greek}+) \1` forces every backref comparison to go through the
382 /// non-ASCII case-folding path (`matches_literal_casei_unicode`). The haystack
383 /// is a run of Greek word pairs that never match the backref, optionally
384 /// followed by one case-folded pair at the very end, so the VM performs many
385 /// folded comparisons per iteration.
386 fn bench_casei_unicode_backref(c: &mut Criterion, name: &str, with_match: bool) {
387 let re = FancyRegex::new(r"(?i)(\p{Greek}+) \1").unwrap();
388 // The two words share no letters, so no suffix-of-one / prefix-of-the-next
389 // can satisfy the backref and the pattern never matches within the run.
390 let mut haystack = "αβγδ εζηθ ".repeat(20);
391 if with_match {
392 haystack.push_str("ωμεγα ΩΜΕΓΑ");
393 }
394 c.bench_function(name, |b| {
395 b.iter(|| {
396 let found = re.find(&haystack).unwrap();
397 assert_eq!(found.is_some(), with_match);
398 found
399 })
400 });
401 }
402
403 fn casei_unicode_backref(c: &mut Criterion) {
404 bench_casei_unicode_backref(c, "casei_unicode_backref", true);
405 }
406
407 fn casei_unicode_backref_no_match(c: &mut Criterion) {
408 bench_casei_unicode_backref(c, "casei_unicode_backref_no_match", false);
409 }
410
411 /// `find_iter` over a hard (VM-executed) pattern with many matches, to expose
412 /// the per-`run` scratch allocation overhead paid on every iteration step.
413 fn find_iter_fancy_many_matches(c: &mut Criterion) {
414 let re = FancyRegex::new(r"(?<=@)\w+").unwrap();
415 let haystack = "user@alpha beta@gamma ".repeat(500);
416 c.bench_function("find_iter_fancy_many_matches", |b| {
417 b.iter(|| {
418 let count = re.find_iter(&haystack).filter_map(Result::ok).count();
419 assert_eq!(count, 1000);
420 count
421 })
422 });
423 }
424
425 /// `find_iter` over an easy pattern that `optimize()` rewrites with an explicit
426 /// capture group 0 (trailing lookahead). The Wrap fast path currently allocates
427 /// full captures per step just to read group 1's span.
428 fn find_iter_wrap_explicit_group0(c: &mut Criterion) {
429 let re = FancyRegex::new(r"\w+(?=!)").unwrap();
430 let haystack = "hello! world? foo! bar ".repeat(500);
431 c.bench_function("find_iter_wrap_explicit_group0", |b| {
432 b.iter(|| {
433 let count = re.find_iter(&haystack).filter_map(Result::ok).count();
434 assert_eq!(count, 1000);
435 count
436 })
437 });
438 }
439
440 /// `is_match` on a hard pattern; the VM allocates and discards its saves
441 /// vector on every call.
442 fn is_match_fancy(c: &mut Criterion) {
443 let re = FancyRegex::new(r"\b(\w{3})\1\b").unwrap();
444 let haystack = "one two three four five six seven abcabc";
445 c.bench_function("is_match_fancy", |b| {
446 b.iter(|| {
447 let matched = re.is_match(haystack).unwrap();
448 assert!(matched);
449 matched
450 })
451 });
452 }
453
454 criterion_group!(
455 name = api_benches;
456 config = Criterion::default().sample_size(30);
457 targets = casei_unicode_backref,
458 casei_unicode_backref_no_match,
459 find_iter_fancy_many_matches,
460 find_iter_wrap_explicit_group0,
461 is_match_fancy,
462 );
463
464 /// Shared logic for the optimized-vs-unoptimized concat-repeat benchmarks.
465 ///
466 /// Compiles `(\w)(?:\s*\w?\s*)+\1` with or without calling `optimize()` on
467 /// the parsed tree. The backreference makes the whole pattern hard, so the
468 /// VM executes the ambiguous `(?:\s*\w?\s*)+` middle section. With
469 /// optimization, that section is rewritten to the unambiguous `\s*(?:\w\s*)*`,
470 /// reducing the number of backtracking paths the VM must explore.
471 fn bench_concat_repeat_optimization(c: &mut Criterion, name: &str, with_optimize: bool) {
472 let pattern = r"(\w)(?:\s*\w?\s*)+\1";
473 let mut tree = Expr::parse_tree(pattern).unwrap();
474 if with_optimize {
475 optimize(&mut tree);
476 }
477 let a = analyze(
478 &tree,
479 AnalyzeContext {
480 explicit_capture_group_0: false,
481 ..Default::default()
482 },
483 )
484 .unwrap();
485 let p = compile(
486 &a,
487 CompileOptions {
488 contains_subroutines: tree.contains_subroutines,
489 ..CompileOptions::default()
490 },
491 )
492 .unwrap();
493 // Haystack: 20 repetitions of "x " then a final "x" — the whole string
494 // matches because the captured 'x' equals the final \1.
495 let mut haystack = "x ".repeat(20);
496 haystack.push('x');
497 c.bench_function(name, |b| b.iter(|| run_default(&p, &haystack, 0).unwrap()));
498 }
499
500 fn run_concat_repeat_optimized(c: &mut Criterion) {
501 bench_concat_repeat_optimization(c, "run_concat_repeat_optimized", true);
502 }
503
504 fn run_concat_repeat_unoptimized(c: &mut Criterion) {
505 bench_concat_repeat_optimization(c, "run_concat_repeat_unoptimized", false);
506 }
507
508 criterion_group!(
509 name = optimize_benches;
510 config = Criterion::default();
511 targets = run_concat_repeat_optimized,
512 run_concat_repeat_unoptimized,
513 );
514
515 #[cfg(feature = "variable-lookbehinds")]
516 criterion_main!(
517 benches,
518 slow_benches,
519 lookbehind_benches,
520 continue_from_end_of_prev_match_benches,
521 seek_benches,
522 seek_worst_case_benches,
523 api_benches,
524 optimize_benches
525 );
526
527 #[cfg(not(feature = "variable-lookbehinds"))]
528 criterion_main!(
529 benches,
530 slow_benches,
531 continue_from_end_of_prev_match_benches,
532 seek_benches,
533 seek_worst_case_benches,
534 api_benches,
535 optimize_benches
536 );