grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
// Project:   grippo
// File:      src/grok/parser.rs
// Purpose:   A grok list as a Parser, on the linear regex engine
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use regex_automata::meta::Regex;
use regex_automata::util::primitives::NonMaxUsize;
use regex_automata::{Anchored, Input, PatternID};
use regex_syntax::hir::Look;
use regex_syntax::hir::literal::{ExtractKind, Extractor};

use std::fmt::Write as _;
use std::num::NonZeroU32;
use std::ops::Range;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicI32, Ordering};

use super::Expanded;
#[cfg(feature = "parse-backtracking")]
use super::backtrack::Backtracking;
use super::backtrack::{Hit, Pattern};
use super::plan::{First, Outcome, Plan, Tail, Terms};
use super::shadow::{Clock, Shadow, agree};
use super::spec::{Steps, run_steps};
use super::{
    Capture, Dialect, GrokError, Library, Possessive, Render, Span, define_unknown, expand_as,
    has_possessive, inline_definitions, layer_aliases, unmark,
};
use crate::cost::{Cost, Line, REFERENCE_BYTES};
use crate::field::Edge;
use crate::parse::{Counter, counter};
use crate::parse::{FieldSink, FieldValue, Fields, ParseError, Parsed, Parser, SinkMark};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// Past this many prefix literals a signature isn't worth building.
const MAX_PREFIXES: usize = 64;

/// A list of grok patterns run as one: the match that starts earliest wins,
/// and a tie goes to the pattern listed first.
///
/// Over [`Span::Whole`] every match starts at the line's start, so the first
/// pattern that matches wins.
pub struct Grok {
    name: String,
    /// Write no field for a capture that matched nothing.
    drop_empty: bool,
    regex: Regex,
    /// Per pattern on `regex`, the capture behind each group index, `None`
    /// for a group that names no field.
    groups: Vec<Vec<Option<Capture>>>,
    /// Per pattern on `regex`, its place in the list and its lookarounds.
    checks: Vec<Checks>,
    /// The patterns that opted into backtracking and needed it.
    #[cfg(feature = "parse-backtracking")]
    backtracking: Option<Backtracking>,
    signature: Signature,
    /// With more than one pattern on the regex, each pattern's own regex,
    /// which takes the captures once the combined one has found the match.
    /// A `PikeVM` on the combined regex sizes slots for every pattern's
    /// groups, 316 GB at 2,418 corpus patterns.
    each: Vec<Regex>,
    /// Native steps per pattern, when every pattern lowers and the list's
    /// order can be kept: one pattern, or all anchored at the start.
    native: Option<Native>,
    /// Per pattern, what kept it on the regex.
    blocked: Vec<Option<&'static str>>,
    /// Per pattern, its expansion, for `explain`.
    regexes: Vec<String>,
    /// Generated code for a stock format, run before anything else.
    stock: Option<StepsFn>,
    /// `grok!` could compile the pattern, and nothing compiled runs it.
    compilable: bool,
    /// The opt-in check of the steps against the regex on live lines.
    shadow: Option<Shadow>,
    /// `parse_tier_total{parser, tier}`: records the steps decided, and
    /// records the regex did.
    on_field: Counter,
    on_regex: Counter,
}

struct Native {
    plans: Vec<Plan>,
    /// Every pattern can only match from the input's start.
    at_start: bool,
    captures: Vec<Vec<Capture>>,
    /// How recent lines went for a first try, from `-SCORE_MAX` to
    /// `SCORE_MAX`: up when the steps matched from the start, down otherwise.
    score: AtomicI32,
}

/// The bound of [`Native::score`], and where a parser starts: trying first.
const SCORE_MAX: i32 = 32;

/// What a match from the start adds to the score, against 1 off for any
/// other line. A first try saves a hit the DFA's pass over the whole line and
/// costs a miss a few steps, so it pays from about one hit in five.
const SCORE_HIT: i32 = 4;

/// What a first try that ran out of budget takes off the score: it cost the
/// most a first try can and decided nothing, so two in a row turn it off.
const SCORE_SPENT: i32 = 16;

/// While a stock parser's first try is off, one line in this many on each
/// thread runs its compiled code anyway, so the try comes back on once the
/// code settles the lines again.
const PROBE_EVERY: u32 = 16;

/// Whether this thread's next line runs compiled code as a probe.
fn probe_due() -> bool {
    thread_local! {
        static LINES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    }
    LINES.with(|lines| {
        let next = lines.get().wrapping_add(1);
        lines.set(next);
        next % PROBE_EVERY == 0
    })
}

/// How a line went, for the score.
#[derive(Clone, Copy)]
enum Went {
    /// The steps matched it from the start, inside a first try's budget.
    First,
    /// Any other line.
    Other,
    /// A first try ran out of budget on it.
    Spent,
    /// Compiled code run as a probe settled it: the try goes back on.
    Probed,
}

impl Native {
    /// Whether to run the steps before the regex: recent lines mostly
    /// matched from the start.
    fn tries_first(&self) -> bool {
        self.score.load(Ordering::Relaxed) > 0
    }

    /// Count a line. Lines that leave the score at its bound write nothing,
    /// so threads sharing a parser on a steady source don't contend. A lost
    /// update between threads only delays a switch.
    fn score(&self, went: Went) {
        let now = self.score.load(Ordering::Relaxed);
        let next = match went {
            Went::First => (now + SCORE_HIT).min(SCORE_MAX),
            Went::Other => (now - 1).max(-SCORE_MAX),
            Went::Spent => (now - SCORE_SPENT).max(-SCORE_MAX),
            Went::Probed => SCORE_MAX,
        };
        if next != now {
            self.score.store(next, Ordering::Relaxed);
        }
    }

    /// Whether the steps read `input` as the regex does: it is valid UTF-8,
    /// and ASCII where a class in the steps has a Unicode reading the
    /// pattern's dialect doesn't share.
    const fn reads_as_regex(plan: &Plan, input: &[u8]) -> bool {
        if plan.ascii_lines() {
            input.is_ascii()
        } else {
            std::str::from_utf8(input).is_ok()
        }
    }

    /// Write each field the steps captured for pattern `pid`.
    fn write<'a>(
        &self,
        pid: usize,
        steps: &[(usize, Range<usize>)],
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) {
        let captures = &self.captures[pid];
        for (i, span) in steps {
            let c = &captures[*i];
            if let Some(v) = c.value(&input[span.clone()]) {
                out.field(&c.field, v);
            }
        }
    }
}

/// The code generated for one pattern, as `grok!` writes it.
type StepsFn = fn(&[u8], &mut [(usize, usize)]) -> Steps;

impl std::fmt::Debug for Grok {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Grok")
            .field("name", &self.name)
            .field("patterns", &self.groups.len())
            .finish_non_exhaustive()
    }
}

/// Builds a [`Grok`].
#[derive(Debug, Clone)]
pub struct GrokBuilder {
    name: String,
    patterns: Vec<String>,
    library: Option<Library>,
    /// Definitions for these patterns alone, looked up before the library.
    aliases: Library,
    /// What a name neither defines expands to, in place of a build error.
    unknown: Option<String>,
    dialect: Dialect,
    span: Span,
    drop_empty: bool,
    strict: bool,
    /// The definitions the options read in place of the stock ones.
    readings: Readings,
    /// Every this many lines also runs the regex, to compare and time.
    shadow: Option<NonZeroU32>,
    /// The patterns that may run on the backtracking engine.
    #[cfg(feature = "parse-backtracking")]
    backtrack: Vec<usize>,
}

/// Why a grok parser didn't build.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GrokBuildError {
    /// A pattern didn't expand.
    #[error("pattern {index}: {source}")]
    Expand {
        /// The pattern's place in the list.
        index: usize,
        /// Why.
        source: GrokError,
    },
    /// The expanded regex doesn't compile on the linear engine. Lookaround
    /// and backreferences end here, unless the pattern opted into
    /// backtracking.
    #[error("the expanded patterns don't compile: {0}")]
    Regex(Box<regex_automata::meta::BuildError>),
    /// A pattern that opted into backtracking doesn't compile there either.
    #[cfg(feature = "parse-backtracking")]
    #[error("a backtracking pattern doesn't compile: {0}")]
    Backtracking(Box<fancy_regex::Error>),
    /// `atomic_number` was set and a pattern holds a `NUMBER` that the steps
    /// can't show gives back no digit: read as the greedy number it would
    /// match lines the atomic group doesn't.
    #[error(
        "pattern {index}: {reason}. Leave atomic_number off, or opt the pattern into backtracking"
    )]
    Atomic {
        /// The pattern's place in the list.
        index: usize,
        /// What kept the number from being the greedy one.
        reason: &'static str,
    },
    /// No pattern was given.
    #[error("a grok parser needs at least one pattern")]
    Empty,
    /// `strict` was set and a pattern runs on the regex.
    #[error("pattern {index} runs on the regex: {reason}. {hint}")]
    NotNative {
        /// The pattern's place in the list.
        index: usize,
        /// What kept it on the regex.
        reason: &'static str,
        /// A rewrite that would lower it.
        hint: &'static str,
    },
    /// A PCRE pattern's possessive repeat that the linear engine can't keep:
    /// as a greedy repeat it would match lines PCRE doesn't.
    #[error(
        "pattern {index}: {reason}. Write the greedy repeat if that's meant, or opt the pattern into backtracking"
    )]
    Possessive {
        /// The pattern's place in the list.
        index: usize,
        /// What kept the repeat from being the greedy one.
        reason: &'static str,
    },
}

impl Grok {
    /// Start a builder for the parser registered as `name`, such as
    /// `grok:firewall`.
    #[must_use]
    pub fn builder(name: impl Into<String>) -> GrokBuilder {
        GrokBuilder {
            name: name.into(),
            patterns: Vec::new(),
            library: None,
            aliases: Library::empty(),
            unknown: None,
            dialect: Dialect::Rust,
            span: Span::Part,
            drop_empty: false,
            strict: false,
            readings: Readings::default(),
            shadow: None,
            #[cfg(feature = "parse-backtracking")]
            backtrack: Vec::new(),
        }
    }
}

impl GrokBuilder {
    /// Add a pattern to the list.
    #[must_use]
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.patterns.push(pattern.into());
        self
    }

    /// Add a pattern that runs on fancy-regex when the linear engine refuses
    /// it, for lookaround or a backreference. A backtracking search has no
    /// worst-case bound, so each such pattern opts in on its own.
    #[cfg(feature = "parse-backtracking")]
    #[must_use]
    pub fn backtracking_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.backtrack.push(self.patterns.len());
        self.patterns.push(pattern.into());
        self
    }

    /// Use `library` in place of the default one.
    #[must_use]
    pub fn library(mut self, library: Library) -> Self {
        self.library = Some(library);
        self
    }

    /// Refuse to build when a pattern can't run on native steps, rather than
    /// run it on the regex.
    #[must_use]
    pub const fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Read `IPV6`, and the IPv6 half of `IP` and `IPORHOST`, as a whole
    /// address: the longest form of each shape, with no word character beside
    /// it and nothing beside it that would extend it. Off by default, where
    /// the upstream alternation can stop inside an address. `IPV4` range-checks
    /// its octets either way.
    #[must_use]
    pub const fn validate(mut self, validate: bool) -> Self {
        self.readings.validate = validate;
        self
    }

    /// Read the zone id of `IPV6`, of the IPv6 half of `IP`, and of `IPORHOST`
    /// as a `%` and every character to the end of the line, as the upstream
    /// grok library does. Off by default, where a zone is a `%` and the
    /// characters RFC 6874 leaves unreserved, so `fe80::1%eth0 up` ends before
    /// the space. The zone is part of the pattern, so what follows it can still
    /// take back the end of the line to start where it needs to.
    #[must_use]
    pub const fn wide_ipv6_zone(mut self, wide: bool) -> Self {
        self.readings.wide_zone = wide;
        self
    }

    /// Read `NUMBER` and `BASE10NUM` as atomic groups, as the upstream grok
    /// library does: a number that has taken its longest match gives no digit
    /// back to what follows, so `%{NUMBER:a}%{INT:b}` never matches. Off by
    /// default, where a number gives digits back. A pattern builds when its
    /// steps show that what follows can't start with a character the number
    /// holds. Any other fails with [`GrokBuildError::Atomic`], unless it opts
    /// into backtracking, which keeps the atomic group.
    #[must_use]
    pub const fn atomic_number(mut self, atomic: bool) -> Self {
        self.readings.atomic_number = atomic;
        self
    }

    /// Every `every`th line also runs on the regex. A disagreement counts in
    /// `parse_shadow_disagree_total`, and while the steps take more than twice
    /// the regex's time the parser runs the regex first. Off by default.
    #[must_use]
    pub const fn shadow(mut self, every: NonZeroU32) -> Self {
        self.shadow = Some(every);
        self
    }

    /// Read the patterns in `dialect`.
    #[must_use]
    pub const fn dialect(mut self, dialect: Dialect) -> Self {
        self.dialect = dialect;
        self
    }

    /// Match `span` of the line: any part of it by default, or all of it.
    #[must_use]
    pub const fn span(mut self, span: Span) -> Self {
        self.span = span;
        self
    }

    /// Definitions for this parser's patterns alone. A name in the patterns,
    /// or in another alias, finds its alias before the library. A library
    /// definition's own references still find the library.
    #[must_use]
    pub fn aliases(mut self, aliases: Library) -> Self {
        self.aliases = aliases;
        self
    }

    /// Expand a name nothing defines to `definition`, such as `.+?`, rather
    /// than fail the build.
    #[must_use]
    pub fn unknown(mut self, definition: impl Into<String>) -> Self {
        self.unknown = Some(definition.into());
        self
    }

    /// Write no field for a capture that matched nothing. A group that took
    /// no part writes none either way.
    #[must_use]
    pub const fn drop_empty(mut self, drop: bool) -> Self {
        self.drop_empty = drop;
        self
    }

    /// Build the parser.
    ///
    /// # Errors
    ///
    /// [`GrokBuildError`] for no pattern, one that doesn't expand, or an
    /// expansion the linear engine can't run.
    pub fn build(self) -> Result<Grok, GrokBuildError> {
        if self.patterns.is_empty() {
            return Err(GrokBuildError::Empty);
        }
        // A lone stock format on the stock library has code generated for it.
        let lone_on_stock = self.library.is_none()
            && !self.readings.any()
            && self.aliases.defs.is_empty()
            && self.dialect == Dialect::Rust
            && self.span == Span::Part
            && self.patterns.len() == 1;
        let stock = lone_on_stock
            .then(|| {
                super::stock::STOCK
                    .iter()
                    .find(|(p, _)| *p == self.patterns[0])
            })
            .flatten()
            .map(|&(_, steps)| steps);
        let mut library = self.library.unwrap_or_default();
        option_fields(&mut library, self.readings);
        let patterns: Vec<String> = layer_aliases(&self.patterns, &self.aliases, &mut library)
            .iter()
            .map(|p| inline_definitions(p, &mut library))
            .collect();
        if let Some(definition) = &self.unknown {
            define_unknown(&patterns, &mut library, definition);
        }
        let span = self.span;
        let lowered: Vec<Result<Plan, &'static str>> = patterns
            .iter()
            .map(|p| Plan::lower_with(p, &library, self.dialect, span, self.readings.atomic_number))
            .collect();
        let atomic = reads_atomic(
            self.readings.atomic_number,
            self.dialect,
            &patterns,
            &library,
            span,
        )?;
        // A possessive repeat or an atomic number is the greedy one only
        // where the steps proved it. Elsewhere the backtracking engine alone
        // reads it as the original does.
        let unproven = |index: usize| {
            lowered[index].is_err()
                && (atomic[index] || has_possessive(&patterns[index], self.dialect))
        };
        let expansion = Expansion {
            patterns: &patterns,
            library: &library,
            dialect: self.dialect,
            span,
            atomic: &atomic,
            unproven: &unproven,
        };
        #[cfg(feature = "parse-backtracking")]
        let opted = |i: usize| self.backtrack.contains(&i);
        #[cfg(not(feature = "parse-backtracking"))]
        let opted = |_: usize| false;
        let (expanded, rendered) = expansion.all(&opted)?;
        let (linear, slow) = split(&expanded, &opted, &unproven);
        if let Some(&index) = linear.iter().find(|&&i| unproven(i)) {
            let reason = lowered[index].as_ref().err().copied().unwrap_or_default();
            return Err(if has_possessive(&patterns[index], self.dialect) {
                GrokBuildError::Possessive { index, reason }
            } else {
                GrokBuildError::Atomic { index, reason }
            });
        }
        let regexes: Vec<&str> = linear.iter().map(|&i| expanded[i].regex.as_str()).collect();
        let (regex, each) = list_regexes(&regexes)?;
        let groups = capture_groups(&regex, &linear, &expanded);
        let limit = share(&linear, &expanded, slow.len());
        #[cfg(feature = "parse-backtracking")]
        let backtracking =
            Backtracking::new(&slow, &rendered, limit).map_err(GrokBuildError::Backtracking)?;
        let checks = Checks::each(&regex, &linear, &expanded, rendered, limit);
        let all: Vec<&str> = expanded.iter().map(|e| e.regex.as_str()).collect();
        let signature = signature(&all);
        let blocked: Vec<Option<&'static str>> =
            lowered.iter().map(|l| l.as_ref().err().copied()).collect();
        report_blocked(&self.name, self.strict, &blocked)?;
        let ordered = lowered.len() == 1
            || span == Span::Whole
            || self.patterns.iter().all(|p| p.starts_with('^'));
        let regexes_owned = expanded.iter().map(|e| e.regex.clone()).collect();
        let labels = |tier: &str| [("parser", self.name.clone()), ("tier", tier.to_owned())];
        let on_field = counter("parse_tier_total", &labels("field"));
        #[cfg(feature = "parse-backtracking")]
        let slow = backtracking.is_some();
        #[cfg(not(feature = "parse-backtracking"))]
        let slow = false;
        let on_regex = counter(
            "parse_tier_total",
            &labels(if slow { "backtracking" } else { "regex" }),
        );
        // What `grok!` accepts: the plan's ops, and few enough fields, with
        // no option it has no form for.
        let compilable = lone_on_stock
            && !self.drop_empty
            && self.unknown.is_none()
            && stock.is_none()
            && expanded[0].captures.len() <= super::spec::MAX_CAPTURES
            && lowered[0].as_ref().is_ok_and(|p| p.ops().is_ok());
        let native = (ordered && !slow && lowered.iter().all(Result::is_ok)).then(|| Native {
            at_start: lowered.iter().flatten().all(Plan::starts_at_zero),
            plans: lowered.into_iter().flatten().collect(),
            captures: expanded.into_iter().map(|e| e.captures).collect(),
            score: AtomicI32::new(SCORE_MAX),
        });
        let stock = stock.filter(|_| native.is_some());
        let compilable = compilable && native.is_some();
        if compilable {
            suggest_compiling(&self.name);
        }
        let shadow = self.shadow.filter(|_| native.is_some()).map(|every| {
            Shadow::new(
                every,
                counter(
                    "parse_shadow_disagree_total",
                    &[("parser", self.name.clone())],
                ),
            )
        });
        Ok(Grok {
            name: self.name,
            drop_empty: self.drop_empty,
            regex,
            groups,
            checks,
            #[cfg(feature = "parse-backtracking")]
            backtracking,
            signature,
            each,
            native,
            blocked,
            regexes: regexes_owned,
            stock,
            compilable,
            shadow,
            on_field,
            on_regex,
        })
    }
}

/// The builder options that read a definition in place of the stock one.
#[derive(Debug, Clone, Copy, Default)]
struct Readings {
    /// Read an IPv6 address whole.
    validate: bool,
    /// Read an `IPV6` zone as `%` and the rest of the line.
    wide_zone: bool,
    /// Read `NUMBER` as an atomic group.
    atomic_number: bool,
}

impl Readings {
    /// Whether any option is on.
    const fn any(self) -> bool {
        self.validate || self.wide_zone || self.atomic_number
    }
}

/// Put the fields `readings` asks for in `library`, in place of the stock ones.
fn option_fields(library: &mut Library, readings: Readings) {
    use crate::field::{CHECKED, Field, WIDE_ZONE, WIDE_ZONE_CHECKED};
    let (validate, wide_zone) = (readings.validate, readings.wide_zone);
    let tables: [(bool, &[Field]); 3] = [
        (validate, &CHECKED),
        (wide_zone, &WIDE_ZONE),
        (validate && wide_zone, &WIDE_ZONE_CHECKED),
    ];
    for (on, table) in tables {
        if on {
            for f in table {
                library.add(f.name, f.regex);
            }
        }
    }
}

/// What expands a list's patterns.
struct Expansion<'e> {
    patterns: &'e [String],
    library: &'e Library,
    dialect: Dialect,
    span: Span,
    /// Per pattern, whether it holds a number read as an atomic group.
    atomic: &'e [bool],
    /// Whether the steps didn't prove pattern `i`'s possessive repeat or
    /// atomic number the greedy one.
    unproven: &'e dyn Fn(usize) -> bool,
}

impl Expansion<'_> {
    /// Every pattern's expansion for the linear engine, and with its
    /// lookarounds as written for fancy-regex where it holds one or `opted`
    /// says it may run on the backtracking engine.
    fn all(
        &self,
        opted: &dyn Fn(usize) -> bool,
    ) -> Result<(Vec<Expanded>, Vec<Option<Expanded>>), GrokBuildError> {
        let expanded = (0..self.patterns.len())
            .map(|i| self.of(i, Render::Groups))
            .collect::<Result<Vec<Expanded>, GrokBuildError>>()?;
        let rendered = (0..self.patterns.len())
            .map(|i| {
                (!expanded[i].edges.is_empty() || opted(i))
                    .then(|| self.of(i, Render::Lookarounds))
                    .transpose()
            })
            .collect::<Result<Vec<Option<Expanded>>, GrokBuildError>>()?;
        Ok((expanded, rendered))
    }

    /// Pattern `index`'s expansion written as `render` says, with a
    /// possessive repeat or an atomic number the steps didn't prove kept as
    /// written, for the backtracking engine.
    fn of(&self, index: usize, render: Render) -> Result<Expanded, GrokBuildError> {
        let unproven = (self.unproven)(index);
        let possessive = if unproven {
            Possessive::Kept
        } else {
            Possessive::Greedy
        };
        let kept = self.atomic[index] && unproven;
        expand_as(
            &self.patterns[index],
            self.library,
            self.dialect,
            self.span,
            possessive,
            kept,
            render,
        )
        .map_err(|source| GrokBuildError::Expand {
            index,
            source: unmark(source),
        })
    }
}

/// Whether each pattern holds a reference [`GrokBuilder::atomic_number`] reads
/// as an atomic group, when `on`.
fn reads_atomic(
    on: bool,
    dialect: Dialect,
    patterns: &[String],
    library: &Library,
    span: Span,
) -> Result<Vec<bool>, GrokBuildError> {
    if !on {
        return Ok(vec![false; patterns.len()]);
    }
    patterns
        .iter()
        .enumerate()
        .map(|(index, p)| {
            let expand = |atomic| {
                expand_as(
                    p,
                    library,
                    dialect,
                    span,
                    Possessive::Greedy,
                    atomic,
                    Render::Groups,
                )
                .map_err(|source| GrokBuildError::Expand {
                    index,
                    source: unmark(source),
                })
            };
            Ok(expand(true)?.regex != expand(false)?.regex)
        })
        .collect()
}

/// The combined regex for `regexes`, sized to the list, and with more than
/// one pattern each pattern's own regex for its captures.
fn list_regexes(regexes: &[&str]) -> Result<(Regex, Vec<Regex>), GrokBuildError> {
    let each = if regexes.len() > 1 {
        regexes
            .iter()
            .map(|r| Regex::new(r).map_err(|e| GrokBuildError::Regex(Box::new(e))))
            .collect::<Result<Vec<_>, GrokBuildError>>()?
    } else {
        Vec::new()
    };
    // A long list's lazy DFA outgrows the default 2 MiB cache and falls
    // to the PikeVM, about 3,000 times slower at 100 patterns. The cache
    // grows only as a thread needs it, up to this bound.
    let cache = (2 << 20_usize).max(regexes.len() * (64 << 10));
    // A list's NFA grows with its patterns, about 89 MiB at 1,000 corpus
    // patterns. Past 256 MiB the build fails instead.
    let nfa = (10 << 20_usize)
        .max(regexes.len() * (128 << 10))
        .min(256 << 20);
    let regex = regex_automata::meta::Builder::new()
        .configure(
            regex_automata::meta::Config::new()
                .hybrid_cache_capacity(cache)
                .nfa_size_limit(Some(nfa)),
        )
        .build_many(regexes)
        .map_err(|e| GrokBuildError::Regex(Box::new(e)))?;
    Ok((regex, each))
}

/// Each fancy-regex search's share of [`RECORD_BACKTRACKS`]: a record runs
/// at most one search a pattern that holds a lookaround on the linear engine,
/// and one a pattern on the backtracking engine, `slow` of them.
fn share(linear: &[usize], expanded: &[Expanded], slow: usize) -> usize {
    let edged = linear
        .iter()
        .filter(|&&i| !expanded[i].edges.is_empty())
        .count();
    RECORD_BACKTRACKS / (edged + slow).max(1)
}

/// The patterns that stay on the linear engine, by place in the list, and
/// the ones that opted into backtracking and need it.
fn split(
    expanded: &[Expanded],
    opted: &dyn Fn(usize) -> bool,
    unproven: &dyn Fn(usize) -> bool,
) -> (Vec<usize>, Vec<usize>) {
    let (slow, linear): (Vec<usize>, Vec<usize>) = (0..expanded.len())
        .partition(|&i| opted(i) && (unproven(i) || Regex::new(&expanded[i].regex).is_err()));
    (linear, slow)
}

/// Per linear pattern on `regex`, the capture behind each group index.
fn capture_groups(
    regex: &Regex,
    linear: &[usize],
    expanded: &[Expanded],
) -> Vec<Vec<Option<Capture>>> {
    linear
        .iter()
        .map(|&i| &expanded[i])
        .enumerate()
        .map(|(pid, e)| {
            regex
                .group_info()
                .pattern_names(PatternID::new_unchecked(pid))
                .map(|name| {
                    let i: usize = name?.strip_prefix('g')?.parse().ok()?;
                    e.captures.get(i).cloned()
                })
                .collect()
        })
        .collect()
}

/// Literals one of which starts every match, when the patterns have a small
/// finite set, else a signature that rules nothing out. When every pattern
/// can only match from the start of the input, the literals are anchored
/// there, so a set tests them without searching the line.
fn signature(regexes: &[&str]) -> Signature {
    let mut literals: Vec<Vec<u8>> = Vec::new();
    let mut from_start = true;
    let mut extractor = Extractor::new();
    extractor.kind(ExtractKind::Prefix);
    for re in regexes {
        let Ok(hir) = regex_syntax::parse(re) else {
            return Signature::builder()
                .build()
                .unwrap_or_else(|_| unreachable!("invariant: no literal"));
        };
        from_start &= hir.properties().look_set_prefix().contains(Look::Start);
        let seq = extractor.extract(&hir);
        match seq.literals() {
            Some(lits) if !lits.is_empty() && lits.iter().all(|l| !l.is_empty()) => {
                literals.extend(lits.iter().map(|l| l.as_bytes().to_vec()));
            }
            _ => literals.clear(),
        }
        if literals.is_empty() || literals.len() > MAX_PREFIXES {
            literals.clear();
            break;
        }
    }
    let builder = Signature::builder();
    let builder = if literals.is_empty() {
        builder
    } else if from_start {
        builder.anchored(literals)
    } else {
        builder.any_of(literals)
    };
    builder
        .build()
        .unwrap_or_else(|_| unreachable!("invariant: literals are non-empty"))
}

impl Parser for Grok {
    fn name(&self) -> &str {
        &self.name
    }

    fn tier(&self) -> MatcherTier {
        #[cfg(feature = "parse-backtracking")]
        if self.backtracking.is_some() {
            return MatcherTier::Backtracking;
        }
        if self.native.is_some() {
            MatcherTier::Field
        } else {
            MatcherTier::Regex
        }
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn hands_on_body(&self) -> bool {
        false
    }

    /// One pattern's price: from its plan's steps, or from its capture groups
    /// on the regex. `None` for a list or the backtracking engine.
    fn cost(&self) -> Option<Cost> {
        let Some(native) = self.native.as_ref() else {
            #[cfg(feature = "parse-backtracking")]
            if self.backtracking.is_some() {
                return None;
            }
            let [groups] = self.groups.as_slice() else {
                return None;
            };
            return regex_priced(groups.len());
        };
        let [plan] = native.plans.as_slice() else {
            return None;
        };
        priced(&plan.terms(), native.at_start)
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        self.run(input, out, &mut Tally::Now).map(parsed)
    }

    fn parse_counted<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        counts: &mut crate::parse::ParserCounts,
    ) -> Result<Parsed, ParseError> {
        self.run(input, out, &mut Tally::Held(counts)).map(parsed)
    }
}

/// The pattern that matched, by place in the list, as a parser's answer.
const fn parsed(won: Option<usize>) -> Parsed {
    match won {
        Some(_) => Parsed::Done,
        None => Parsed::NoMatch,
    }
}

/// A sink that skips an empty value, for [`GrokBuilder::drop_empty`].
struct NonEmpty<'s, 'a>(&'s mut dyn FieldSink<'a>);

impl<'a> FieldSink<'a> for NonEmpty<'_, 'a> {
    fn field(&mut self, name: &str, value: FieldValue<'a>) {
        if !value.bytes.is_empty() {
            self.0.field(name, value);
        }
    }

    fn body_field(&mut self, name: &str, value: FieldValue<'a>) {
        if !value.bytes.is_empty() {
            self.0.body_field(name, value);
        }
    }

    fn push_prefix(&mut self, prefix: &str) {
        self.0.push_prefix(prefix);
    }

    fn pop_prefix(&mut self) {
        self.0.pop_prefix();
    }

    fn mark(&self) -> SinkMark {
        self.0.mark()
    }

    fn rollback(&mut self, mark: SinkMark) {
        self.0.rollback(mark);
    }
}

/// Which of a parser's two tier counters a record adds to.
#[derive(Clone, Copy)]
enum Tier {
    /// The steps decided it.
    Field,
    /// The regex did.
    Regex,
}

/// Where a record's tier count goes.
enum Tally<'c> {
    /// To the shared counter, at once.
    Now,
    /// To a batch, which adds it when it publishes.
    Held(&'c mut crate::parse::ParserCounts),
}

impl Grok {
    /// Count one record against a tier.
    #[cfg_attr(
        not(feature = "metrics"),
        allow(clippy::missing_const_for_fn, reason = "the body is the counter add")
    )]
    fn tier(&self, tally: &mut Tally<'_>, tier: Tier) {
        let counter = match tier {
            Tier::Field => &self.on_field,
            Tier::Regex => &self.on_regex,
        };
        match tally {
            Tally::Now => counter.increment(1),
            #[cfg(feature = "metrics")]
            Tally::Held(counts) => counts.add(tier as usize, counter, 1),
            // No recorder can be there, so there is nothing to hold.
            #[cfg(not(feature = "metrics"))]
            Tally::Held(counts) => {
                let _ = counts;
            }
        }
    }

    /// One record, by the shadow check when it is this record's turn: the
    /// pattern that matched, by place in the list.
    fn run<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        tally: &mut Tally<'_>,
    ) -> Result<Option<usize>, ParseError> {
        if self.drop_empty {
            return self.run_into(input, &mut NonEmpty(out), tally);
        }
        self.run_into(input, out, tally)
    }

    fn run_into<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        tally: &mut Tally<'_>,
    ) -> Result<Option<usize>, ParseError> {
        if let Some(shadow) = &self.shadow {
            if shadow.sample() {
                return self.parse_shadowed(shadow, input, out, tally);
            }
            if shadow.regex_first() {
                #[cfg(test)]
                REGEX_FIRST.with(|n| n.set(n.get() + 1));
                self.tier(tally, Tier::Regex);
                return self.regex_won(input, out);
            }
        }
        self.parse_fast(input, out, tally, false)
            .map(|(won, _)| won)
    }

    /// The steps, or the regex where they can't say: the pattern that
    /// matched, and where the regex decided, how long it took when `timed`.
    fn parse_fast<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        tally: &mut Tally<'_>,
        timed: bool,
    ) -> Result<(Option<usize>, Option<f32>), ParseError> {
        if let Some(native) = &self.native {
            // Compiled code is a first try too, under the same score. A late
            // miss walks most of the line, so every miss counts against it.
            // One it can't settle is counted once, below.
            let mut tried = false;
            let on = native.tries_first();
            if let Some(code) = self.stock
                && (on || probe_due())
            {
                match run_steps(code, &native.captures[0], input, out) {
                    Some(Parsed::NoMatch) => {
                        native.score(Went::Other);
                        self.tier(tally, Tier::Field);
                        return Ok((None, None));
                    }
                    Some(_) => {
                        native.score(if on { Went::First } else { Went::Probed });
                        self.tier(tally, Tier::Field);
                        return Ok((Some(0), None));
                    }
                    None => tried = true,
                }
            }
            let mut steps = super::scratch::steps();
            // One pattern tries its steps from the start before any regex
            // pass: the DFA reads the whole line, and a match at the start is
            // the leftmost. The steps read characters as the regex does only
            // on input they are known to read alike, so a match counts then.
            let first = !tried && native.plans.len() == 1 && native.tries_first();
            let mut spent = false;
            if first {
                match native.plans[0].first_try(input, &mut steps) {
                    First::Matched if Native::reads_as_regex(&native.plans[0], input) => {
                        native.score(Went::First);
                        self.tier(tally, Tier::Field);
                        native.write(0, &steps, input, out);
                        return Ok((Some(0), None));
                    }
                    First::Spent => spent = true,
                    First::Matched | First::Open => {}
                }
            }
            let missed = if spent { Went::Spent } else { Went::Other };
            // The DFA rejects a miss in one pass, faster than the signature's
            // literal scans, and gives a hit's leftmost start and pattern.
            // A pattern that starts with `^` needs no scan back for its start.
            let found = if native.at_start {
                let anchored = Input::new(input).anchored(Anchored::Yes);
                let half = self.regex.search_half(&anchored);
                half.map(|h| (h.pattern().as_usize(), 0))
            } else {
                let m = self.regex.search(&Input::new(input));
                m.map(|m| (m.pattern().as_usize(), m.start()))
            };
            let Some((pid, start)) = found else {
                native.score(missed);
                self.tier(tally, Tier::Field);
                return Ok((None, None));
            };
            // The steps run once a record: after a first try that ran out,
            // the regex reads the captures.
            if !spent && Native::reads_as_regex(&native.plans[pid], input) {
                let located = native.plans[pid].run_at(input, start, &mut steps);
                if located.outcome == Outcome::Matched {
                    // Whether a first try would have won this line. Compiled
                    // code takes a stock parser's first try, so only that
                    // code's own answer, above, can say it would have.
                    if self.stock.is_none() && located.first_fits {
                        native.score(Went::First);
                    } else if tried || !located.first_fits {
                        native.score(Went::Other);
                    }
                    self.tier(tally, Tier::Field);
                    native.write(pid, &steps, input, out);
                    return Ok((Some(pid), None));
                }
            }
            native.score(missed);
            self.tier(tally, Tier::Regex);
            return self.regex_timed(input, out, timed);
        }
        // Every match holds the signature's literals. Its scans cost more
        // than the linear regex's own reject, less than a backtracking search.
        #[cfg(feature = "parse-backtracking")]
        if self.backtracking.is_some() && !self.signature.may_match(input) {
            self.tier(tally, Tier::Regex);
            return Ok((None, Some(0.0)));
        }
        self.tier(tally, Tier::Regex);
        self.regex_timed(input, out, timed)
    }

    /// The regex's answer, and how long it took when `timed`.
    fn regex_timed<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        timed: bool,
    ) -> Result<(Option<usize>, Option<f32>), ParseError> {
        let clock = timed.then(Clock::now);
        let won = self.regex_won(input, out)?;
        Ok((won, Some(clock.map_or(0.0, |c| c.ns()))))
    }

    /// A sampled line on both paths, timed and compared, with the steps'
    /// answer written to `out`.
    fn parse_shadowed<'a>(
        &self,
        shadow: &Shadow,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        tally: &mut Tally<'_>,
    ) -> Result<Option<usize>, ParseError> {
        let mut by_steps = Fields::new();
        let clock = Clock::now();
        let (won, by_regex) = self.parse_fast(input, &mut by_steps, tally, true)?;
        let steps_ns = clock.ns();
        // A record the regex decided has its answer and its time: a second
        // run would spend the record's backtrack budget again.
        let (regex_ns, agreed) = if let Some(regex_ns) = by_regex {
            (regex_ns, true)
        } else {
            let mut by_regex = Fields::new();
            let clock = Clock::now();
            let regex = self.regex_won(input, &mut by_regex)?;
            let regex_ns = clock.ns();
            let agreed = agree(&parsed(won), &by_steps, &parsed(regex), &by_regex);
            (regex_ns, agreed)
        };
        shadow.record(steps_ns, regex_ns, agreed);
        for (name, value) in by_steps.as_slice() {
            out.field(name, value.clone());
        }
        Ok(won)
    }

    /// Parse `input` as [`Parser::parse`] does, and say which pattern
    /// matched: its place in the list, `None` for no match.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] when a backtracking search passes its budget.
    pub fn parse_indexed<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Option<usize>, ParseError> {
        self.run(input, out, &mut Tally::Now)
    }
}

impl Grok {
    /// Each pattern's plan, one line apiece: lowered, or what kept it on the
    /// regex with a rewrite that would lower it, then its expanded regex.
    #[must_use]
    pub fn explain(&self) -> String {
        let mut out = String::new();
        for (i, (blocked, regex)) in self.blocked.iter().zip(&self.regexes).enumerate() {
            #[cfg(feature = "parse-backtracking")]
            if self.backtracking.as_ref().is_some_and(|b| b.holds(i)) {
                let _ = writeln!(
                    out,
                    "{i}: backtracking: the linear engine refuses it\n   {regex}"
                );
                continue;
            }
            let plan = match blocked {
                None if self.native.is_some() => {
                    let first = if self.stock.is_some() { "compiled code, then " } else { "" };
                    let steps = self.cost().map_or_else(
                    || "native steps".to_owned(),
                    |c| {
                        format!(
                            "native steps, tier Field, about {:.0} ns a hit and {:.0} ns a miss at {REFERENCE_BYTES} B",
                            c.label(),
                            c.miss.ns(REFERENCE_BYTES)
                        )
                    },
                );
                    let up = if self.compilable { "; grok! compiles it to code" } else { "" };
                    format!("{first}{steps}{up}")
                }
                None => "lowers, but the list runs on the regex: a list lowers when it is one pattern, all start with ^, or each matches the whole line".to_owned(),
                Some(reason) => {
                    let price = self.cost().map_or_else(String::new, |c| {
                        format!(". About {:.0} ns a hit at {REFERENCE_BYTES} B", c.label())
                    });
                    format!("regex: {reason}. {}{price}", hint(reason))
                }
            };
            // Writing to a String can't fail.
            let _ = writeln!(out, "{i}: {plan}\n   {regex}");
        }
        out
    }

    /// What kept each pattern on the regex, `None` for one that lowered.
    #[must_use]
    pub fn blocked(&self) -> &[Option<&'static str>] {
        &self.blocked
    }

    /// Lines the shadow sampled and whether it runs the regex first, `None`
    /// with no shadow.
    #[cfg(test)]
    pub(super) fn shadow_state(&self) -> Option<(u32, bool)> {
        self.shadow.as_ref().map(|s| (s.samples(), s.regex_first()))
    }

    /// Whether the next line tries the steps before the regex.
    #[cfg(test)]
    pub(super) fn tries_first(&self) -> bool {
        self.native.as_ref().is_some_and(Native::tries_first)
    }

    /// The native steps' own answer for the first pattern, without the
    /// regex to fall back on: the outcome and the fields it would write.
    #[cfg(test)]
    pub(super) fn native_outcome(&self, input: &[u8]) -> Option<(Outcome, Vec<(String, Vec<u8>)>)> {
        let native = self.native.as_ref()?;
        let mut steps = Vec::new();
        if !Native::reads_as_regex(&native.plans[0], input) {
            return Some((Outcome::Unsure, Vec::new()));
        }
        let outcome = native.plans[0].run(input, &mut steps);
        let fields = steps
            .iter()
            .map(|(i, span)| {
                (
                    native.captures[0][*i].field.clone(),
                    input[span.clone()].to_vec(),
                )
            })
            .collect();
        Some((outcome, fields))
    }

    /// What the compiled stock code makes of `input`: `None` with no such
    /// code, `Some(None)` where the code can't say.
    #[cfg(test)]
    #[allow(
        clippy::option_option,
        reason = "no stock code and code that can't say are both answers"
    )]
    pub(super) fn stock_says(&self, input: &[u8]) -> Option<Option<Parsed>> {
        let native = self.native.as_ref()?;
        let code = self.stock?;
        Some(run_steps(
            code,
            &native.captures[0],
            input,
            &mut crate::parse::Fields::new(),
        ))
    }

    /// What the first pattern's native steps spend on `input` from every
    /// start: the outcome, the units spent, and the located budget.
    #[cfg(test)]
    pub(super) fn native_units(&self, input: &[u8]) -> Option<(Outcome, usize, usize)> {
        Some(self.native.as_ref()?.plans[0].run_units(input))
    }

    /// What a first try makes of `input`, and a run from its start on the
    /// located budget, for the first pattern.
    #[cfg(test)]
    pub(super) fn first_and_located(&self, input: &[u8]) -> Option<(First, super::plan::Located)> {
        let plan = &self.native.as_ref()?.plans[0];
        let mut caps = Vec::new();
        Some((
            plan.first_try(input, &mut caps),
            plan.run_at(input, 0, &mut caps),
        ))
    }

    /// What the first pattern's steps spend on `input` from its start with
    /// no budget to stop them: the outcome, the units, and a first try's budget.
    #[cfg(test)]
    pub(super) fn first_try_units(&self, input: &[u8]) -> Option<(Outcome, usize, usize)> {
        Some(self.native.as_ref()?.plans[0].first_try_units(input))
    }

    /// Each pattern's expanded regex, by place in the list.
    #[cfg(test)]
    pub(super) fn regexes(&self) -> &[String] {
        &self.regexes
    }

    /// The regex's answer, the one the native steps are held to.
    #[cfg(test)]
    pub(super) fn parse_regex<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        self.regex_won(input, out).map(parsed)
    }

    /// The regex's answer, with the pattern that matched by place in the list.
    fn regex_won<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Option<usize>, ParseError> {
        let answer = self.linear_answer(input)?;
        #[cfg(feature = "parse-backtracking")]
        if let Some(hit) = self
            .backtracking
            .as_ref()
            .map(|b| b.search(input, answer.as_ref().map(|a| a.place(self))))
            .transpose()?
            .flatten()
        {
            let linear = answer.as_ref().map(|a| a.place(self));
            if linear.is_none_or(|first| (hit.start, hit.index) < first) {
                hit.write(input, out);
                return Ok(Some(hit.index));
            }
        }
        match answer {
            None => Ok(None),
            Some(Answer::Fancy(hit)) => {
                hit.write(input, out);
                Ok(Some(hit.index))
            }
            Some(Answer::Slots { pid, shape, slots }) => {
                for (i, capture) in self.groups[pid.as_usize()].iter().enumerate() {
                    if let (Some(c), Some(span)) = (capture, group_span(Some(shape), &slots, i))
                        && let Some(v) = c.value(&input[span])
                    {
                        out.field(&c.field, v);
                    }
                }
                Ok(Some(self.checks[pid.as_usize()].index))
            }
        }
    }

    /// The linear patterns' answer. A match that fails an edge check hands
    /// the record, from that match's start, to fancy-regex.
    fn linear_answer<'g, 'a>(
        &'g self,
        input: &'a [u8],
    ) -> Result<Option<Answer<'g, 'a>>, ParseError> {
        let search = Input::new(input);
        // `shape` is the regex whose slots were filled and the pattern's id
        // on it, which is 0 on a pattern's own regex whatever its place in
        // the list.
        let (pid, shape, slots) = if self.each.is_empty() {
            let mut slots = super::scratch::slots(self.regex.group_info().slot_len());
            let pid = self.regex.search_slots(&search, &mut slots);
            (pid, pid.map(|pid| (&self.regex, pid)), slots)
        } else if let Some(m) = self.regex.search(&search) {
            let one = &self.each[m.pattern().as_usize()];
            let mut slots = super::scratch::slots(one.group_info().slot_len());
            let at = Input::new(input).range(m.start()..).anchored(Anchored::Yes);
            let own = one.search_slots(&at, &mut slots);
            (Some(m.pattern()), own.map(|own| (one, own)), slots)
        } else {
            (None, None, super::scratch::slots(0))
        };
        let (Some(pid), Some(shape)) = (pid, shape) else {
            return Ok(None);
        };
        if self.keeps(pid.as_usize(), Some(shape), &slots, input) {
            return Ok(Some(Answer::Slots { pid, shape, slots }));
        }
        let start = group_span(Some(shape), &slots, 0).map_or(0, |m| m.start);
        self.refused(input, start)
    }

    /// Whether the regex's answer for pattern `pid`, in `slots`, keeps every
    /// edge check its path made.
    fn keeps(
        &self,
        pid: usize,
        shape: Option<(&Regex, PatternID)>,
        slots: &[Option<NonMaxUsize>],
        input: &[u8],
    ) -> bool {
        let c = &self.checks[pid];
        c.groups.is_empty()
            || (!c.repeated
                && c.groups.iter().all(|&(g, edge)| {
                    group_span(shape, slots, g).is_none_or(|s| edge.holds(input, s.start))
                }))
    }

    /// The leftmost match from `from` on, a tie going to the pattern listed
    /// first: fancy-regex's for a pattern with a lookaround, the linear
    /// engine's for one without. Each pattern searches once, so the record's
    /// backtracks stay within [`RECORD_BACKTRACKS`].
    fn refused<'g, 'a>(
        &'g self,
        input: &'a [u8],
        from: usize,
    ) -> Result<Option<Answer<'g, 'a>>, ParseError> {
        let mut best: Option<Answer<'g, 'a>> = None;
        for (q, c) in self.checks.iter().enumerate() {
            let found = if c.groups.is_empty() {
                let one = self.each.get(q).unwrap_or(&self.regex);
                let mut slots = super::scratch::slots(one.group_info().slot_len());
                let at = Input::new(input).range(from..);
                one.search_slots(&at, &mut slots).map(|own| Answer::Slots {
                    pid: PatternID::new_unchecked(q),
                    shape: (one, own),
                    slots,
                })
            } else {
                c.fancy()?.search_from(input, from)?.map(Answer::Fancy)
            };
            let Some(found) = found else { continue };
            if best.as_ref().is_none_or(|b| found.start() < b.start()) {
                let first = found.start() == from;
                best = Some(found);
                // No later pattern can start sooner, and a tie is this one's.
                if first {
                    break;
                }
            }
        }
        Ok(best)
    }
}

/// The backtracks one record's fancy-regex searches share, on both tiers:
/// fancy-regex's default for one search. It counts backtracks, not every
/// step a search takes, so a search's time is bounded by its length too.
const RECORD_BACKTRACKS: usize = 1_000_000;

#[cfg(test)]
thread_local! {
    /// Records this thread ran regex-first because the shadow switched.
    pub(super) static REGEX_FIRST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// A linear pattern's answer.
enum Answer<'g, 'a> {
    /// The linear engine's: pattern `pid` on the combined regex, its slots
    /// laid out as `shape`'s.
    Slots {
        pid: PatternID,
        shape: (&'g Regex, PatternID),
        slots: super::scratch::Lease<Option<NonMaxUsize>>,
    },
    /// Fancy-regex's, for a pattern with a lookaround.
    Fancy(Hit<'g, 'a>),
}

impl Answer<'_, '_> {
    fn start(&self) -> usize {
        match self {
            Self::Slots { shape, slots, .. } => {
                group_span(Some(*shape), slots, 0).map_or(0, |m| m.start)
            }
            Self::Fancy(hit) => hit.start,
        }
    }

    /// Its start and its pattern's place in the list.
    #[cfg(feature = "parse-backtracking")]
    fn place(&self, grok: &Grok) -> (usize, usize) {
        match self {
            Self::Slots { pid, .. } => (self.start(), grok.checks[pid.as_usize()].index),
            Self::Fancy(hit) => (hit.start, hit.index),
        }
    }
}

/// One linear pattern's lookarounds, which the linear engine reads as empty
/// groups.
struct Checks {
    /// Its place in the list.
    index: usize,
    /// Each lookaround's group, by index, with the check it stands for.
    groups: Vec<(usize, Edge)>,
    /// A group sits inside a repeat, where the slots keep only the last pass,
    /// so no answer of the regex's can be shown to keep the checks.
    repeated: bool,
    /// The pattern expanded with its lookarounds as written.
    rendered: Option<Expanded>,
    /// The backtracks one search may take.
    limit: usize,
    /// The pattern on fancy-regex, built on the first answer that fails a
    /// check.
    fancy: OnceLock<Result<Pattern, String>>,
}

impl Checks {
    /// Each linear pattern's, `linear` their places in the list, a search
    /// taking `limit` backtracks.
    fn each(
        regex: &Regex,
        linear: &[usize],
        expanded: &[Expanded],
        mut rendered: Vec<Option<Expanded>>,
        limit: usize,
    ) -> Vec<Self> {
        linear
            .iter()
            .enumerate()
            .map(|(pid, &i)| Self::new(regex, pid, i, &expanded[i], rendered[i].take(), limit))
            .collect()
    }

    /// Linear pattern `pid` on `regex`, pattern `index` in the list.
    fn new(
        regex: &Regex,
        pid: usize,
        index: usize,
        expanded: &Expanded,
        rendered: Option<Expanded>,
        limit: usize,
    ) -> Self {
        let names: Vec<Option<&str>> = regex
            .group_info()
            .pattern_names(PatternID::new_unchecked(pid))
            .collect();
        let groups: Vec<(usize, Edge)> = expanded
            .edges
            .iter()
            .enumerate()
            .filter_map(|(k, &edge)| {
                let name = format!("e{k}");
                let g = names.iter().position(|n| *n == Some(name.as_str()))?;
                Some((g, edge))
            })
            .collect();
        let repeated = !groups.is_empty()
            && regex_syntax::parse(&expanded.regex).is_ok_and(|hir| {
                let at: Vec<usize> = groups.iter().map(|&(g, _)| g).collect();
                repeats_an_edge(&hir, &at, false)
            });
        Self {
            index,
            groups,
            repeated,
            rendered,
            limit,
            fancy: OnceLock::new(),
        }
    }

    /// The pattern on fancy-regex.
    fn fancy(&self) -> Result<&Pattern, ParseError> {
        let built = self.fancy.get_or_init(|| {
            let e = self
                .rendered
                .as_ref()
                .ok_or_else(|| "a pattern with no lookaround reading".to_owned())?;
            Pattern::new(self.index, &e.regex, &e.captures, self.limit).map_err(|e| e.to_string())
        });
        built
            .as_ref()
            .map_err(|e| ParseError::Other(e.clone().into()))
    }
}

/// Whether an edge group, a capture whose index is in `edges`, sits inside a
/// repeat of more than one pass in `hir`.
fn repeats_an_edge(hir: &regex_syntax::hir::Hir, edges: &[usize], inside: bool) -> bool {
    use regex_syntax::hir::HirKind;
    match hir.kind() {
        HirKind::Capture(c) => {
            (inside && usize::try_from(c.index).is_ok_and(|i| edges.contains(&i)))
                || repeats_an_edge(&c.sub, edges, inside)
        }
        HirKind::Repetition(r) => repeats_an_edge(&r.sub, edges, inside || r.max != Some(1)),
        HirKind::Concat(subs) | HirKind::Alternation(subs) => {
            subs.iter().any(|h| repeats_an_edge(h, edges, inside))
        }
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
    }
}

/// Group `i`'s span, where the search that filled `slots` matched it.
fn group_span(
    shape: Option<(&Regex, PatternID)>,
    slots: &[Option<regex_automata::util::primitives::NonMaxUsize>],
    i: usize,
) -> Option<Range<usize>> {
    let (regex, pid) = shape?;
    let (start, end) = regex.group_info().slots(pid, i)?;
    Some(slots.get(start).copied()??.get()..slots.get(end).copied()??.get())
}

/// Fail on a pattern kept off native steps when `strict`, else log it.
fn report_blocked(
    name: &str,
    strict: bool,
    blocked: &[Option<&'static str>],
) -> Result<(), GrokBuildError> {
    for (index, reason) in blocked.iter().enumerate() {
        if let Some(reason) = *reason {
            if strict {
                return Err(GrokBuildError::NotNative {
                    index,
                    reason,
                    hint: hint(reason),
                });
            }
            summarise(name, index, reason);
        }
    }
    Ok(())
}

/// A rewrite that would lower a pattern blocked for `reason`.
fn hint(reason: &str) -> &'static str {
    match reason {
        "a field that can end where the next step starts" => {
            "Put a literal between them that the first field can't hold, or use a field that stops there"
        }
        "regex syntax outside a reference" | "an escape that isn't a literal" => {
            "Write the class or repetition as a grok field such as %{NOTSPACE} or %{DATA}"
        }
        "a number the next step could make give back digits" => {
            "Put a literal between them that a number can't hold, or opt the pattern into backtracking"
        }
        "a repeated group" => "Repeat a field instead of a group, or keep it on the regex",
        "an unanchored pattern that starts with a run" => {
            "Anchor it with ^, or start it with a literal or a field"
        }
        _ => "Keep it on the regex, or split the pattern",
    }
}

/// Say once per process, for the first ten patterns, that one runs on the
/// regex. Past ten it's a debug line.
#[cfg_attr(
    not(feature = "tracing"),
    allow(
        unused_variables,
        clippy::missing_const_for_fn,
        reason = "the body is the tracing call"
    )
)]
fn summarise(parser: &str, index: usize, reason: &'static str) {
    #[cfg(feature = "tracing")]
    {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static TOLD: AtomicUsize = AtomicUsize::new(0);
        if TOLD.fetch_add(1, Ordering::Relaxed) < 10 {
            tracing::warn!(
                parser,
                pattern = index,
                blocked = reason,
                hint = hint(reason),
                "grok pattern runs on the regex"
            );
        } else {
            tracing::debug!(
                parser,
                pattern = index,
                blocked = reason,
                "grok pattern runs on the regex"
            );
        }
    }
}

/// Once per process, that a pattern built at run time could be compiled in.
#[cfg_attr(
    not(feature = "tracing"),
    allow(
        unused_variables,
        clippy::missing_const_for_fn,
        reason = "the body is the tracing call"
    )
)]
fn suggest_compiling(parser: &str) {
    #[cfg(feature = "tracing")]
    {
        use std::sync::atomic::{AtomicBool, Ordering};
        static TOLD: AtomicBool = AtomicBool::new(false);
        if TOLD.swap(true, Ordering::Relaxed) {
            tracing::debug!(parser, "grok pattern could be compiled with grok!");
        } else {
            tracing::warn!(
                parser,
                "grok pattern could be compiled with grok!, which skips the step interpreter"
            );
        }
    }
}

/// Per capture group plus one, the share of the `meta_captures` row's byte rate
/// a grok regex pays: fitted over 2,224 corpus patterns, 91% within 2x.
const REGEX_RATE_PER_GROUP: f32 = 0.8;

/// A pattern on the regex with `groups` capture groups, group 0 included:
/// the `meta_captures` row's fixed cost, its byte rate scaled by the groups,
/// and the DFA's reject for a miss.
fn regex_priced(groups: usize) -> Option<Cost> {
    use crate::cost::of;
    let (meta, dfa) = (of("meta_captures")?, of("lazy_dfa_find")?);
    #[allow(clippy::cast_precision_loss, reason = "a group count far below 2^24")]
    let scale = REGEX_RATE_PER_GROUP * (groups as f32 + 1.0);
    Some(Cost {
        hit: Line {
            fixed_ns: meta.hit.fixed_ns,
            ns_per_byte: meta.hit.ns_per_byte * scale,
        },
        miss: dfa.miss,
    })
}

/// Steps `grok.base`'s pattern runs, and how many more `grok.steps`'s does.
const BASE_STEPS: usize = 1;
const STEPS_ROW_EXTRA: f32 = 31.0;

/// A plan's cost from the table's `grok.*` and `field.*` rows: the base, each
/// step past it, each field and each settled end, and per byte the last
/// open-ended step's rate. A miss on a plan that starts at zero fails at its
/// first step. Any other runs the DFA over the line.
fn priced(t: &Terms, at_start: bool) -> Option<Cost> {
    use crate::cost::of;
    let (base, steps) = (of("grok.base")?, of("grok.steps")?);
    let (settled, unsettled, run) = (of("grok.settled")?, of("grok.unsettled")?, of("grok.run")?);
    let per_step = ((steps.hit.fixed_ns - base.hit.fixed_ns) / STEPS_ROW_EXTRA).max(0.0);
    let settle = (settled.hit.fixed_ns - unsettled.hit.fixed_ns).max(0.0);
    #[allow(
        clippy::cast_precision_loss,
        reason = "step and field counts are far below 2^24"
    )]
    let mut fixed = (t.steps.saturating_sub(BASE_STEPS) as f32).mul_add(
        per_step,
        (t.settled as f32).mul_add(settle, base.hit.fixed_ns),
    );
    for c in t.fields.iter().filter_map(|f| of(&format!("field.{f}"))) {
        fixed += c.hit.fixed_ns;
    }
    let tail = match t.tail {
        None => 0.0,
        Some(Tail::Line) => of("memchr")?.hit.ns_per_byte,
        Some(Tail::Class) => run.hit.ns_per_byte,
        Some(Tail::Field(f)) => of(&format!("field.{f}")).map_or(0.0, |c| c.hit.ns_per_byte),
    };
    let per_byte = base.hit.ns_per_byte + tail;
    let miss = if at_start {
        base.miss
    } else {
        let dfa = of("lazy_dfa_find")?.miss;
        Line {
            fixed_ns: base.miss.fixed_ns + dfa.fixed_ns,
            ns_per_byte: dfa.ns_per_byte,
        }
    };
    Some(Cost {
        hit: Line {
            fixed_ns: fixed,
            ns_per_byte: per_byte,
        },
        miss,
    })
}