grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// Project:   grippo
// File:      src/ua/tests.rs
// Purpose:   Hand-written rule tables, ua-parser as the oracle, and uap-core's own test files
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "a test that can't load its inputs has failed"
)]

use std::borrow::Cow;
use std::path::Path;
use std::sync::LazyLock;

use proptest::prelude::*;
use serde::Deserialize;

use super::*;

fn ua_rule(regex: &str, repl: [Option<&str>; 5]) -> UserAgentRule {
    let s = |i: usize| repl[i].map(str::to_owned);
    UserAgentRule {
        regex: regex.into(),
        family_replacement: s(0),
        v1_replacement: s(1),
        v2_replacement: s(2),
        v3_replacement: s(3),
        v4_replacement: s(4),
    }
}

fn os_rule(regex: &str, repl: [Option<&str>; 5]) -> OsRule {
    let s = |i: usize| repl[i].map(str::to_owned);
    OsRule {
        regex: regex.into(),
        os_replacement: s(0),
        os_v1_replacement: s(1),
        os_v2_replacement: s(2),
        os_v3_replacement: s(3),
        os_v4_replacement: s(4),
    }
}

fn device_rule(regex: &str, folded: bool, repl: [Option<&str>; 3]) -> DeviceRule {
    let s = |i: usize| repl[i].map(str::to_owned);
    DeviceRule {
        regex: regex.into(),
        regex_flag: folded.then_some(RegexFlag::IgnoreCase),
        device_replacement: s(0),
        brand_replacement: s(1),
        model_replacement: s(2),
    }
}

/// Rules that take each resolver path: family text, `$1` and group, version
/// text and groups, OS and device templates that trim to nothing, a folded
/// device rule, a rule with no literal worth searching, and two rules that
/// both match where rule order decides.
fn hand_rules() -> Rules {
    const N: Option<&str> = None;
    Rules {
        user_agent_parsers: vec![
            ua_rule(r"(Firefox)/(\d+)\.(\d+)(?:\.(\d+))?", [N; 5]),
            ua_rule(r"Edg/(\d+)", [Some("Edge"), Some("$1"), N, N, N]),
            ua_rule(
                r"(Chrome|Chromium)/(\d+)\.(\d+)",
                [Some("$1 Browser"), N, N, Some("x"), N],
            ),
            ua_rule(r"(UC? ?Browser|U3)[ /]?(\d+)", [N; 5]),
            ua_rule(r"Chrome", [Some("Late Chrome"), N, N, N, N]),
            ua_rule(r"Bot(\d*)", [Some(""), N, N, N, N]),
            ua_rule(r"Pending", [N; 5]),
        ],
        os_parsers: vec![
            os_rule(
                r"Windows NT (\d+)\.(\d+)",
                [Some("Windows"), Some("$1"), Some("$2 "), Some(" "), N],
            ),
            os_rule(r"Android (\d+)(?:\.(\d+))?", [N, N, N, N, N]),
            os_rule(r"(Linux) ?(x86_64)?", [Some("$1 $2"), Some("$3"), N, N, N]),
        ],
        device_parsers: vec![
            device_rule(
                r"; *(SM-[A-Z]\d+)",
                true,
                [Some("Samsung $1"), Some("Samsung"), N],
            ),
            device_rule(r"(iPhone|iPad)", false, [N, Some("Apple"), Some("$1")]),
            device_rule(
                r"; ([A-Z]{2})(\d{3})\)",
                false,
                [Some("$1-$2"), Some("  "), Some("$9")],
            ),
        ],
    }
}

/// ua-parser built from the same rules.
fn oracle(rules: &Rules) -> ua_parser::Extractor<'static> {
    let c = |s: &Option<String>| s.clone().map(Cow::Owned);
    ua_parser::Extractor::try_from(ua_parser::Regexes {
        user_agent_parsers: rules
            .user_agent_parsers
            .iter()
            .map(|r| ua_parser::user_agent::Parser {
                regex: r.regex.clone().into(),
                family_replacement: c(&r.family_replacement),
                v1_replacement: c(&r.v1_replacement),
                v2_replacement: c(&r.v2_replacement),
                v3_replacement: c(&r.v3_replacement),
                v4_replacement: c(&r.v4_replacement),
            })
            .collect(),
        os_parsers: rules
            .os_parsers
            .iter()
            .map(|r| ua_parser::os::Parser {
                regex: r.regex.clone().into(),
                os_replacement: c(&r.os_replacement),
                os_v1_replacement: c(&r.os_v1_replacement),
                os_v2_replacement: c(&r.os_v2_replacement),
                os_v3_replacement: c(&r.os_v3_replacement),
                os_v4_replacement: c(&r.os_v4_replacement),
            })
            .collect(),
        device_parsers: rules
            .device_parsers
            .iter()
            .map(|r| ua_parser::device::Parser {
                regex: r.regex.clone().into(),
                regex_flag: r.regex_flag.map(|_| ua_parser::device::Flag::IgnoreCase),
                device_replacement: c(&r.device_replacement),
                brand_replacement: c(&r.brand_replacement),
                model_replacement: c(&r.model_replacement),
            })
            .collect(),
    })
    .unwrap()
}

/// Up to five fields of one domain's answer, as text.
type Fields = Vec<Option<String>>;

/// The owned text of each field.
fn owned(c: Option<Cow<'_, str>>) -> Option<String> {
    c.map(Cow::into_owned)
}

fn text(c: Option<&str>) -> Option<String> {
    c.map(str::to_owned)
}

fn ours(parser: &UaParser, domain: Domain, ua: &str, scratch: &mut UaScratch) -> Option<Fields> {
    match domain {
        Domain::UserAgent => parser.user_agent(ua, scratch).map(|v| {
            let family = Some(v.family.into_owned());
            vec![
                family,
                text(v.major),
                text(v.minor),
                text(v.patch),
                text(v.patch_minor),
            ]
        }),
        Domain::Os => parser.os(ua, scratch).map(|v| {
            let family = Some(v.family.into_owned());
            vec![
                family,
                owned(v.major),
                owned(v.minor),
                owned(v.patch),
                owned(v.patch_minor),
            ]
        }),
        Domain::Device => parser
            .device(ua, scratch)
            .map(|v| vec![Some(v.family.into_owned()), owned(v.brand), owned(v.model)]),
    }
}

fn theirs(uap: &ua_parser::Extractor<'_>, domain: Domain, ua: &str) -> Option<Fields> {
    match domain {
        Domain::UserAgent => uap.ua.extract(ua).map(|v| {
            let family = Some(v.family.into_owned());
            vec![
                family,
                text(v.major),
                text(v.minor),
                text(v.patch),
                text(v.patch_minor),
            ]
        }),
        Domain::Os => uap.os.extract(ua).map(|v| {
            let family = Some(v.os.into_owned());
            vec![
                family,
                owned(v.major),
                owned(v.minor),
                owned(v.patch),
                owned(v.patch_minor),
            ]
        }),
        Domain::Device => uap
            .dev
            .extract(ua)
            .map(|v| vec![Some(v.device.into_owned()), owned(v.brand), owned(v.model)]),
    }
}

#[allow(
    clippy::unnecessary_wraps,
    reason = "a case row's answer is Some or None"
)]
fn fields(f: &[Option<&str>]) -> Option<Fields> {
    Some(f.iter().map(|v| v.map(str::to_owned)).collect())
}

/// Each string and what each domain gives for it, `None` for no match.
#[test]
fn hand_rules_fill_fields_as_ua_parser_does() {
    use Domain::{Device, Os, UserAgent};
    let n: Option<&str> = None;
    let cases: &[(Domain, &str, Option<Fields>)] = &[
        (
            UserAgent,
            "Mozilla/5.0 Firefox/133.0",
            fields(&[Some("Firefox"), Some("133"), Some("0"), n, n]),
        ),
        (
            UserAgent,
            "Firefox/133.0.2",
            fields(&[Some("Firefox"), Some("133"), Some("0"), Some("2"), n]),
        ),
        (
            UserAgent,
            "Chrome/120.0 Edg/120",
            fields(&[Some("Edge"), Some("$1"), n, n, n]),
        ),
        (
            UserAgent,
            "Chromium/99.1",
            fields(&[
                Some("Chromium Browser"),
                Some("99"),
                Some("1"),
                Some("x"),
                n,
            ]),
        ),
        (
            UserAgent,
            "UCBrowser/11",
            fields(&[Some("UCBrowser"), Some("11"), n, n, n]),
        ),
        (
            UserAgent,
            "U3/2 always tried",
            fields(&[Some("U3"), Some("2"), n, n, n]),
        ),
        (
            UserAgent,
            "Chrome only",
            fields(&[Some("Late Chrome"), n, n, n, n]),
        ),
        (UserAgent, "Bot", fields(&[Some(""), n, n, n, n])),
        (UserAgent, "Bot42", fields(&[Some("42"), n, n, n, n])),
        (UserAgent, "Pending", fields(&[Some(""), n, n, n, n])),
        (UserAgent, "", None),
        (UserAgent, "Safari/605", None),
        (UserAgent, "firefox/133.0", None),
        (
            Os,
            "Windows NT 10.0",
            fields(&[Some("Windows"), Some("10"), Some("0"), n, n]),
        ),
        (Os, "Android 14", fields(&[Some("14"), n, n, n, n])),
        (
            Os,
            "Android 14.1",
            fields(&[Some("14"), Some("1"), n, n, n]),
        ),
        (Os, "Linux", fields(&[Some("Linux"), n, n, n, n])),
        (
            Os,
            "Linux x86_64",
            fields(&[Some("Linux x86_64"), n, n, n, n]),
        ),
        (Os, "Mac OS X", None),
        (
            Device,
            "Android; sm-g991b",
            fields(&[Some("Samsung sm-g991"), Some("Samsung"), Some("sm-g991")]),
        ),
        (
            Device,
            "Android; SM-G991B",
            fields(&[Some("Samsung SM-G991"), Some("Samsung"), Some("SM-G991")]),
        ),
        (
            Device,
            "iPhone OS 17",
            fields(&[Some("iPhone"), Some("Apple"), Some("iPhone")]),
        ),
        (Device, "iphone", None),
        (Device, "(X; AB123)", fields(&[Some("AB-123"), n, n])),
        (Device, "Mozilla/5.0", None),
    ];
    let rules = hand_rules();
    let p = UaParser::new(&rules).unwrap();
    let x = oracle(&rules);
    let mut s = p.scratch();
    for (d, ua, want) in cases {
        assert_eq!(&ours(&p, *d, ua, &mut s), want, "{d} {ua:?}");
        assert_eq!(&theirs(&x, *d, ua), want, "ua-parser {d} {ua:?}");
    }
}

#[test]
fn parse_gives_all_three_and_borrows_where_it_can() {
    let p = UaParser::new(&hand_rules()).unwrap();
    let mut s = p.scratch();
    let ua = "Mozilla/5.0 (Linux; Android 14; SM-A515F) Firefox/133.0";
    let c = p.parse(ua, &mut s);
    let agent = c.user_agent.unwrap();
    assert!(matches!(agent.family, Cow::Borrowed("Firefox")));
    let os = c.os.unwrap();
    assert!(matches!(os.family, Cow::Borrowed("14")));
    assert_eq!(os.major, None);
    let device = c.device.unwrap();
    assert!(matches!(device.family, Cow::Owned(ref f) if f == "Samsung SM-A515"));
    assert!(matches!(device.brand, Some(Cow::Borrowed("Samsung"))));
    assert_eq!(
        p.parse("curl/8.0", &mut s),
        Client {
            user_agent: None,
            os: None,
            device: None
        }
    );
}

#[test]
fn empty_table_matches_nothing() {
    let p = UaParser::new(&Rules::default()).unwrap();
    let mut s = p.scratch();
    for ua in ["", "Mozilla/5.0 Firefox/133.0"] {
        assert!(p.user_agent(ua, &mut s).is_none());
        assert!(p.os(ua, &mut s).is_none());
        assert!(p.device(ua, &mut s).is_none());
    }
    for d in Domain::ALL {
        assert_eq!(p.tier_counts(d).iter().sum::<usize>(), 0);
    }
}

#[test]
fn bad_rules_name_the_rule() {
    let bad = |rules: Rules| UaParser::new(&rules).unwrap_err();
    let one_ua = |r| Rules {
        user_agent_parsers: vec![ua_rule("ok", [None; 5]), r],
        ..Rules::default()
    };
    let e = bad(one_ua(ua_rule("(unclosed", [None; 5])));
    assert!(
        matches!(
            e,
            UaError::Pattern {
                domain: Domain::UserAgent,
                index: 1,
                ..
            }
        ),
        "{e}"
    );
    let e = bad(one_ua(ua_rule("", [None; 5])));
    assert!(matches!(e, UaError::Pattern { index: 1, .. }), "{e}");
    let e = bad(one_ua(ua_rule(
        "NoGroup",
        [Some("$1 x"), None, None, None, None],
    )));
    assert!(matches!(e, UaError::MissingGroup { index: 1 }), "{e}");
    let e = bad(Rules {
        device_parsers: vec![device_rule("a(?=b)", false, [None; 3])],
        ..Rules::default()
    });
    assert!(
        matches!(
            e,
            UaError::Pattern {
                domain: Domain::Device,
                index: 0,
                ..
            }
        ),
        "{e}"
    );
    assert_eq!(e.to_string().split(':').next(), Some("ua"));
}

#[test]
fn a_scratch_from_another_parser_is_rebuilt() {
    let small = UaParser::new(&Rules {
        user_agent_parsers: vec![ua_rule("(Other)", [None; 5])],
        ..Rules::default()
    })
    .unwrap();
    let p = UaParser::new(&hand_rules()).unwrap();
    let mut s = small.scratch();
    let agent = p.user_agent("Firefox/1.2", &mut s).unwrap();
    assert_eq!((&*agent.family, agent.major), ("Firefox", Some("1")));
    assert!(small.user_agent("Firefox/1.2", &mut s).is_none());
}

#[test]
fn parser_is_send_and_sync() {
    fn check<T: Send + Sync>() {}
    check::<UaParser>();
    check::<UaScratch>();
}

#[test]
fn rules_deserialise_in_regexes_yaml_shape() {
    let text = r#"{
        "user_agent_parsers": [{"regex": "(Foo)/(\\d+)", "v1_replacement": "1", "other": 3}],
        "device_parsers": [{"regex": "bar", "regex_flag": "i", "model_replacement": null}]
    }"#;
    let rules: Rules = serde_json::from_str(text).unwrap();
    assert!(rules.os_parsers.is_empty());
    assert_eq!(
        rules.user_agent_parsers[0].v1_replacement.as_deref(),
        Some("1")
    );
    assert_eq!(
        rules.device_parsers[0].regex_flag,
        Some(RegexFlag::IgnoreCase)
    );
    let bad = r#"{"device_parsers": [{"regex": "x", "regex_flag": "g"}]}"#;
    assert!(serde_json::from_str::<Rules>(bad).is_err());
}

#[test]
fn rewrite_reads_patterns_as_ua_parser_does() {
    let cases = [
        (r".{0,2}x", r".{0,2}x"),
        (r"a{0,100}b{1,1000}", "a*b+"),
        (r"a{2,100}", r"a{2,100}"),
        (r"a{0,99}", r"a{0,99}"),
        (r"a{0,}", r"a{0,}"),
        (r"[{0,100}]", r"[{0,100}]"),
        (r"\{0,100}", r"\{0,100}"),
        (r"{0,100}", r"{0,100}"),
        (r"\d\D\w\W", "[0-9][^0-9][A-Za-z0-9_][^A-Za-z0-9_]"),
        (r"[\d.]", "[[0-9].]"),
        (r"\\d", r"\\d"),
        (r"\s\b\.", r"\s\b\."),
        (r"[]a]{0,100}", r"[]a]{0,100}"),
        ("tail\\", "tail\\"),
        ("", ""),
    ];
    for (re, want) in cases {
        assert_eq!(literals::rewrite(re), want, "{re}");
    }
}

#[test]
fn required_literals_follow_the_pattern() {
    use literals::{Required, required};
    let lits = |s: &[&str]| s.iter().map(|l| l.as_bytes().to_vec()).collect::<Vec<_>>();
    let cases: Vec<(&str, usize, Required)> = vec![
        (
            r"Firefox/[0-9]+",
            3,
            Required::Clauses(vec![lits(&["Firefox/"])]),
        ),
        (
            r"(Chrome|Chromium)/",
            3,
            Required::Clauses(vec![lits(&["Chrome/"]), lits(&["Chromium/"])]),
        ),
        (
            r"Edg/[0-9]+ Mobile",
            3,
            Required::Clauses(vec![lits(&[" Mobile", "Edg/"])]),
        ),
        (
            r"(?:IE|U3) ",
            3,
            Required::Clauses(vec![lits(&["IE "]), lits(&["U3 "])]),
        ),
        (r"(?:IE|U3)[0-9]", 3, Required::Nothing),
        (
            r"(?:IE|U3)[0-9]",
            2,
            Required::Clauses(vec![lits(&["IE"]), lits(&["U3"])]),
        ),
        (r"[0-9]+", 2, Required::Nothing),
        (r"x?", 2, Required::Nothing),
    ];
    for (re, min, want) in cases {
        let hir = regex_syntax::parse(re).unwrap();
        assert_eq!(required(&hir, min), want, "{re}");
    }
}

/// The hand rules built once for every proptest case.
static HAND: LazyLock<(UaParser, ua_parser::Extractor<'static>)> = LazyLock::new(|| {
    let rules = hand_rules();
    (UaParser::new(&rules).unwrap(), oracle(&rules))
});

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1024))]

    /// Strings built from the hand rules' pieces give ua-parser's answer in
    /// every domain.
    #[test]
    fn hand_rules_agree_with_ua_parser(parts in proptest::collection::vec(
        prop_oneof![
            Just("Firefox/"), Just("Chrome/"), Just("chromium/"), Just("Edg/"), Just("UC Browser"),
            Just("U3"), Just("Bot"), Just("Windows NT "), Just("Android "), Just("Linux"),
            Just(" x86_64"), Just("; SM-"), Just("; sm-"), Just("iPhone"), Just("; AB"), Just(")"),
            Just("1"), Just("23"), Just("."), Just(" "), Just("/"), Just("G"), Just("\u{e9}"),
        ],
        0..10,
    )) {
        let (p, x) = &*HAND;
        let mut s = p.scratch();
        let ua: String = parts.concat();
        for d in Domain::ALL {
            prop_assert_eq!(ours(p, d, &ua, &mut s), theirs(x, d, &ua), "{} {:?}", d, ua);
        }
    }
}

// ---------------------------------------------------------------------------
// uap-core's own test files, from the directory GRIPPO_UAP_CORE names
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
struct TestFile {
    test_cases: Vec<TestCase>,
}

#[derive(Deserialize)]
struct TestCase {
    user_agent_string: String,
    family: Option<String>,
    major: Option<String>,
    minor: Option<String>,
    patch: Option<String>,
    patch_minor: Option<String>,
    brand: Option<String>,
    model: Option<String>,
}

impl TestCase {
    /// The expected fields, the browser's empty versions read as none.
    fn expected(self, d: Domain) -> Fields {
        let blank = |v: Option<String>| v.filter(|s| !s.is_empty());
        match d {
            Domain::UserAgent => vec![
                self.family,
                blank(self.major),
                blank(self.minor),
                blank(self.patch),
                blank(self.patch_minor),
            ],
            Domain::Os => vec![
                self.family,
                self.major,
                self.minor,
                self.patch,
                self.patch_minor,
            ],
            Domain::Device => vec![self.family, self.brand, self.model],
        }
    }
}

const TEST_FILES: [(Domain, &str); 8] = [
    (Domain::UserAgent, "tests/test_ua.yaml"),
    (
        Domain::UserAgent,
        "test_resources/firefox_user_agent_strings.yaml",
    ),
    (Domain::UserAgent, "test_resources/pgts_browser_list.yaml"),
    (
        Domain::UserAgent,
        "test_resources/opera_mini_user_agent_strings.yaml",
    ),
    (
        Domain::UserAgent,
        "test_resources/podcasting_user_agent_strings.yaml",
    ),
    (Domain::Os, "tests/test_os.yaml"),
    (Domain::Os, "test_resources/additional_os_tests.yaml"),
    (Domain::Device, "tests/test_device.yaml"),
];

fn read(dir: &Path, name: &str) -> String {
    std::fs::read_to_string(dir.join(name)).unwrap_or_else(|e| panic!("{name}: {e}"))
}

/// Every string in uap-core's test files gets the file's expected answer,
/// and ua-parser's answer on the string, its upper-cased and its
/// lower-cased forms. Skipped when `GRIPPO_UAP_CORE` is unset: uap-core stays
/// out of this repository.
#[test]
fn uap_core_test_files_agree() {
    let Some(dir) = std::env::var_os("GRIPPO_UAP_CORE") else {
        return;
    };
    let dir = Path::new(&dir);
    let yaml = read(dir, "regexes.yaml");
    let rules: Rules = serde_saphyr::from_str(&yaml).unwrap();
    let parser = UaParser::new(&rules).unwrap();
    let uap_rules: ua_parser::Regexes<'static> = serde_saphyr::from_str(&yaml).unwrap();
    let uap = ua_parser::Extractor::try_from(uap_rules).unwrap();
    let mut scratch = parser.scratch();
    let other = |domain: Domain| -> Fields {
        let mut f = vec![Some("Other".to_owned())];
        f.resize(if domain == Domain::Device { 3 } else { 5 }, None);
        f
    };
    let mut wrong: Vec<String> = Vec::new();
    // Per file: domain, strings, candidates and regex runs.
    let mut totals: Vec<(Domain, usize, usize, usize)> = Vec::new();
    for (domain, name) in TEST_FILES {
        let file: TestFile = serde_saphyr::from_str(&read(dir, name)).unwrap();
        let strings = file.test_cases.len();
        assert!(strings > 0, "{name} has no cases");
        let (mut candidates, mut runs) = (0, 0);
        for case in file.test_cases {
            let ua = case.user_agent_string.clone();
            let table = &mut scratch.tables[domain as usize];
            let won = parser.table(domain).first(ua.as_bytes(), table);
            candidates += table.candidates.len();
            runs += won.map_or(table.candidates.len(), |rule| {
                let at = table.candidates.iter().position(|&r| r as usize == rule);
                at.map_or(0, |k| k + 1)
            });
            let got = ours(&parser, domain, &ua, &mut scratch);
            let want = case.expected(domain);
            if got.clone().unwrap_or_else(|| other(domain)) != want {
                wrong.push(format!("{name}: {ua:?} got {got:?} want {want:?}"));
            }
            for variant in [ua.clone(), ua.to_uppercase(), ua.to_lowercase()] {
                let mine = ours(&parser, domain, &variant, &mut scratch);
                let oracle = theirs(&uap, domain, &variant);
                if mine != oracle {
                    wrong.push(format!(
                        "{name}: {variant:?} ours {mine:?} ua-parser {oracle:?}"
                    ));
                }
            }
        }
        totals.push((domain, strings, candidates, runs));
    }
    for domain in Domain::ALL {
        let (strings, candidates, runs) = totals
            .iter()
            .filter(|t| t.0 == domain)
            .fold((0, 0, 0), |a, t| (a.0 + t.1, a.1 + t.2, a.2 + t.3));
        let table = parser.table(domain);
        #[allow(clippy::cast_precision_loss, reason = "counts far below 2^52")]
        let per = |v: usize| v as f64 / strings.max(1) as f64;
        println!(
            "uap-core {domain}: rules {} regex-tier {} always-tried {} signatures {} | strings {strings} candidates/string {:.2} runs/string {:.2}",
            table.rules.len(),
            parser.tier_counts(domain)[MatcherTier::Regex.index()],
            table.always.len(),
            table.set.len(),
            per(candidates),
            per(runs),
        );
    }
    let total: usize = totals.iter().map(|t| t.1).sum();
    assert_eq!(total, 31_166, "uap-core's test files changed size");
    let shown = &wrong[..wrong.len().min(20)];
    assert!(wrong.is_empty(), "{} of {total}: {shown:#?}", wrong.len());
}