grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
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
// 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::{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::atomic::{AtomicI32, Ordering};

#[cfg(feature = "parse-backtracking")]
use super::Expanded;
#[cfg(feature = "parse-backtracking")]
use super::backtrack::Backtracking;
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, Span, define_unknown, expand_as,
    has_possessive, inline_definitions, layer_aliases, unmark,
};
use crate::cost::{Cost, Line, REFERENCE_BYTES};
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.
    #[cfg(feature = "parse-backtracking")]
    linear: Vec<usize>,
    /// 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);
        }
    }

    /// 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,
    /// 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>),
    /// 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,
            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
    }

    /// 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.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();
        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(p, &library, self.dialect, span))
            .collect();
        // A possessive repeat is the greedy one only where the steps proved
        // it. Elsewhere the backtracking engine alone reads it as PCRE does.
        let unproven = |index: usize| {
            lowered[index].is_err() && has_possessive(&patterns[index], self.dialect)
        };
        let expanded = patterns
            .iter()
            .enumerate()
            .map(|(index, p)| {
                let possessive = if unproven(index) {
                    Possessive::Kept
                } else {
                    Possessive::Greedy
                };
                expand_as(p, &library, self.dialect, span, possessive).map_err(|source| {
                    GrokBuildError::Expand {
                        index,
                        source: unmark(source),
                    }
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        #[cfg(feature = "parse-backtracking")]
        let (linear, backtracking) = split(&expanded, &self.backtrack, &unproven)?;
        #[cfg(not(feature = "parse-backtracking"))]
        let linear: Vec<usize> = (0..expanded.len()).collect();
        if let Some(&index) = linear.iter().find(|&&i| unproven(i)) {
            let reason = lowered[index].as_ref().err().copied().unwrap_or_default();
            return Err(GrokBuildError::Possessive { index, reason });
        }
        let regexes: Vec<&str> = linear.iter().map(|&i| expanded[i].regex.as_str()).collect();
        let (regex, each) = list_regexes(&regexes)?;
        let groups = 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();
        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();
        for (index, reason) in blocked.iter().enumerate() {
            if let Some(reason) = *reason {
                if self.strict {
                    return Err(GrokBuildError::NotNative {
                        index,
                        reason,
                        hint: hint(reason),
                    });
                }
                summarise(&self.name, index, reason);
            }
        }
        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,
            #[cfg(feature = "parse-backtracking")]
            linear,
            #[cfg(feature = "parse-backtracking")]
            backtracking,
            signature,
            each,
            native,
            blocked,
            regexes: regexes_owned,
            stock,
            compilable,
            shadow,
            on_field,
            on_regex,
        })
    }
}

/// 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))
}

/// The patterns that stay on the linear engine, by place in the list, and
/// the ones that opted into backtracking and need it.
#[cfg(feature = "parse-backtracking")]
fn split(
    expanded: &[Expanded],
    opted: &[usize],
    unproven: &dyn Fn(usize) -> bool,
) -> Result<(Vec<usize>, Option<Backtracking>), GrokBuildError> {
    let (slow, linear): (Vec<usize>, Vec<usize>) = (0..expanded.len()).partition(|i| {
        opted.contains(i) && (unproven(*i) || Regex::new(&expanded[*i].regex).is_err())
    });
    if slow.is_empty() {
        return Ok((linear, None));
    }
    let patterns = slow
        .iter()
        .map(|&i| {
            (
                i,
                expanded[i].regex.as_str(),
                expanded[i].captures.as_slice(),
            )
        })
        .collect();
    let backtracking = Backtracking::new(patterns).map_err(GrokBuildError::Backtracking)?;
    Ok((linear, Some(backtracking)))
}

/// 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() {
                self.tier(tally, Tier::Regex);
                return self.regex_won(input, out);
            }
        }
        self.parse_fast(input, out, tally)
    }

    /// The steps, or the regex where they can't say.
    fn parse_fast<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        tally: &mut Tally<'_>,
    ) -> Result<Option<usize>, 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);
                    }
                    Some(_) => {
                        native.score(if on { Went::First } else { Went::Probed });
                        self.tier(tally, Tier::Field);
                        return Ok(Some(0));
                    }
                    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 UTF-8, so a match counts once the input is known to be.
            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 std::str::from_utf8(input).is_ok() => {
                        native.score(Went::First);
                        self.tier(tally, Tier::Field);
                        native.write(0, &steps, input, out);
                        return Ok(Some(0));
                    }
                    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);
            };
            // The steps run once a record: after a first try that ran out,
            // the regex reads the captures.
            if !spent && std::str::from_utf8(input).is_ok() {
                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));
                }
            }
            native.score(missed);
            self.tier(tally, Tier::Regex);
            return self.regex_won(input, out);
        }
        // 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);
        }
        self.tier(tally, Tier::Regex);
        self.regex_won(input, out)
    }

    /// 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 = self.parse_fast(input, &mut by_steps, tally)?;
        let steps_ns = clock.ns();
        let mut by_regex = Fields::new();
        let clock = Clock::now();
        let regex = self.regex_won(input, &mut by_regex)?;
        shadow.record(
            steps_ns,
            clock.ns(),
            agree(&parsed(won), &by_steps, &parsed(regex), &by_regex),
        );
        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
    }

    /// 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();
        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 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.
    #[cfg_attr(
        not(feature = "parse-backtracking"),
        allow(
            clippy::unnecessary_wraps,
            reason = "only a backtracking search can fail"
        )
    )]
    fn regex_won<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Option<usize>, ParseError> {
        // `pid_of` is the pattern's place on the combined regex. `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_of, 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(&Input::new(input), &mut slots);
            (pid, pid.map(|pid| (&self.regex, pid)), slots)
        } else if let Some(m) = self.regex.search(&Input::new(input)) {
            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))
        };
        // A group's span, where the search that filled the slots matched it.
        let group = |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())
        };
        #[cfg(feature = "parse-backtracking")]
        if let Some(hit) = self
            .backtracking
            .as_ref()
            .map(|b| b.search(input))
            .transpose()?
            .flatten()
        {
            let linear = group(0)
                .zip(pid_of)
                .map(|(m, pid)| (m.start, self.linear[pid.as_usize()]));
            if linear.is_none_or(|first| (hit.start, hit.index) < first) {
                hit.write(input, out);
                return Ok(Some(hit.index));
            }
        }
        let Some(pid) = pid_of else {
            return Ok(None);
        };
        for (i, capture) in self.groups[pid.as_usize()].iter().enumerate() {
            if let (Some(c), Some(span)) = (capture, group(i))
                && let Some(v) = c.value(&input[span])
            {
                out.field(&c.field, v);
            }
        }
        #[cfg(feature = "parse-backtracking")]
        let pid = self.linear[pid.as_usize()];
        #[cfg(not(feature = "parse-backtracking"))]
        let pid = pid.as_usize();
        Ok(Some(pid))
    }
}

/// 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 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,
    })
}