grippo 0.2.3

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
// Project:   grippo
// File:      src/grok/mod.rs
// Purpose:   Grok patterns: the library, expansion to a regex, and the dialect
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Grok: a regex written with named sub-patterns.
//!
//! [`expand`] turns `%{IPV4:client} %{WORD:verb}` into a regex with one
//! numbered group per capture and a map from group to field. The library is
//! grippo's own, each definition written from its format's documentation
//! under the name grok patterns use. A name with a native scanner gets its
//! field definition, so a pattern expands to exactly the regex the scanners
//! are held to.

use std::collections::HashMap;

use thiserror::Error;

use crate::field::FIELDS;
use crate::parse::Hint;
use crate::path::push_key;

#[cfg(feature = "parse-backtracking")]
mod backtrack;
mod date;
mod ends;
mod parser;
mod plan;
mod scratch;
mod shadow;
pub mod spec;
#[rustfmt::skip]
#[allow(clippy::all, clippy::pedantic, clippy::nursery, reason = "generated by grippo-macros/examples/stock.rs")]
mod stock;

pub use date::date_pattern;
pub use parser::{Grok, GrokBuildError, GrokBuilder};

/// grippo's grok definitions, each file written from its formats' own
/// documentation, in load order.
const PATTERN_FILES: [&str; 23] = [
    include_str!("patterns/base"),
    include_str!("patterns/aws"),
    include_str!("patterns/bacula"),
    include_str!("patterns/bind"),
    include_str!("patterns/bro"),
    include_str!("patterns/exim"),
    include_str!("patterns/firewalls"),
    include_str!("patterns/haproxy"),
    include_str!("patterns/httpd"),
    include_str!("patterns/java"),
    include_str!("patterns/junos"),
    include_str!("patterns/linux-syslog"),
    include_str!("patterns/maven"),
    include_str!("patterns/mcollective"),
    include_str!("patterns/mcollective-patterns"),
    include_str!("patterns/mongodb"),
    include_str!("patterns/nagios"),
    include_str!("patterns/postgresql"),
    include_str!("patterns/rails"),
    include_str!("patterns/redis"),
    include_str!("patterns/ruby"),
    include_str!("patterns/squid"),
    include_str!("patterns/formats"),
];

/// How deep one definition may nest others.
const MAX_DEPTH: usize = 64;

/// Named grok definitions.
#[derive(Debug, Clone)]
pub struct Library {
    defs: HashMap<String, String>,
}

impl Default for Library {
    /// grippo's definitions, then its field definitions.
    fn default() -> Self {
        let mut lib = Self::empty();
        for file in PATTERN_FILES {
            lib.add_file(file);
        }
        for f in FIELDS {
            lib.add(f.name, f.regex);
        }
        lib
    }
}

impl Library {
    /// A library with no definitions.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            defs: HashMap::new(),
        }
    }

    /// Define `name`, replacing any definition it had.
    pub fn add(&mut self, name: impl Into<String>, definition: impl Into<String>) {
        self.defs.insert(name.into(), definition.into());
    }

    /// Every `NAME definition` line of a pattern file. Blank lines and `#`
    /// comments are skipped.
    pub fn add_file(&mut self, text: &str) {
        for line in text.lines() {
            let line = line.trim_start();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            if let Some((name, def)) = line.split_once(char::is_whitespace) {
                self.add(name, def.trim_start());
            }
        }
    }

    /// Every `"NAME": "definition"` pair of a JSON object, as alias files
    /// hold them. A name defined twice keeps the later definition.
    ///
    /// # Errors
    ///
    /// [`GrokError::Json`] when `text` isn't an object of strings. Nothing is
    /// added then.
    pub fn add_json(&mut self, text: &str) -> Result<(), GrokError> {
        let pairs: Vec<(String, String)> =
            serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(text)
                .map_err(|e| GrokError::Json(e.to_string()))?
                .into_iter()
                .map(|(name, def)| match def {
                    serde_json::Value::String(def) => Ok((name, def)),
                    _ => Err(GrokError::Json(format!("{name:?} is not a string"))),
                })
                .collect::<Result<_, _>>()?;
        for (name, def) in pairs {
            self.add(name, def);
        }
        Ok(())
    }

    /// The definition of `name`.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        self.defs.get(name).map(String::as_str)
    }

    /// Every definition's name, in no order.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.defs.keys().map(String::as_str)
    }
}

/// The regex dialect a pattern was written in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Dialect {
    /// Rust's regex syntax, as written.
    #[default]
    Rust,
    /// Oniguruma, as Oniguruma-based grok engines run it: `^` and `$` match
    /// at lines, `(?m)` lets `.` cross a newline, `\<` and `\>` are the
    /// brackets themselves, and a final `$` allows one line terminator.
    Oniguruma,
    /// PCRE, for a pattern written for a PCRE engine: `\<` and `\>` are the
    /// brackets themselves, a `{` that opens no interval is the brace, and a
    /// `[` inside a class is the bracket unless it opens `[:name:]`. A
    /// branch-reset group `(?|` is a plain group, since fields go by name.
    /// A possessive repeat of one class, such as `[^"]*+`, builds where
    /// what follows can never use a character it gave back, which makes it
    /// the greedy repeat. Library definitions stay as written.
    Pcre,
}

/// How much of a line a pattern has to match.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Span {
    /// Any part of it. In a list the match that starts earliest wins, and a
    /// tie goes to the pattern listed first.
    #[default]
    Part,
    /// All of it, with `.` matching a newline. Every match starts where the
    /// line does, so in a list the first pattern that matches wins.
    Whole,
}

/// One capture: the field it writes and how its value is typed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Capture {
    /// The field name, with a `[a][b]` reference written `a.b` and
    /// `[a.b][c]` written `["a.b"].c`.
    pub field: String,
    /// `Int` for a `:int`, `:long` or `:integer` suffix, `Float` for
    /// `:float`, `:double` or `:number`, `Bool` for `:boolean`, `Timestamp`
    /// for `:date(FORMAT)`, else `Text`.
    pub hint: Hint,
    /// A `:lowercase`, `:uppercase` or `:nullif(value)` suffix.
    pub filter: Option<Filter>,
}

/// What a suffix does to a captured value before it's written.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Filter {
    /// ASCII letters to lower case.
    Lowercase,
    /// ASCII letters to upper case.
    Uppercase,
    /// No field at all when the value is exactly this, such as `-`.
    NullIf(String),
}

impl Capture {
    /// The value to write for `bytes`, after the filter. `None` when the
    /// filter drops it.
    #[must_use]
    pub fn value<'a>(&self, bytes: &'a [u8]) -> Option<crate::parse::FieldValue<'a>> {
        use crate::parse::FieldValue;
        Some(match &self.filter {
            Some(Filter::NullIf(v)) if bytes == v.as_bytes() => return None,
            None | Some(Filter::NullIf(_)) => FieldValue::borrowed(bytes, self.hint),
            Some(Filter::Lowercase) => FieldValue::owned(bytes.to_ascii_lowercase(), self.hint),
            Some(Filter::Uppercase) => FieldValue::owned(bytes.to_ascii_uppercase(), self.hint),
        })
    }
}

/// A grok pattern as a regex: capture `i` is the group named `g{i}`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Expanded {
    /// The regex.
    pub regex: String,
    /// The captures, by group number.
    pub captures: Vec<Capture>,
}

/// Why a pattern didn't expand.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum GrokError {
    /// `%{NAME}` with no definition.
    #[error("no grok definition named {0:?}")]
    Unknown(String),
    /// A definition that reaches itself.
    #[error("grok definition {0:?} refers to itself")]
    Cycle(String),
    /// Definitions nested deeper than 64.
    #[error("grok definitions nest deeper than 64 at {0:?}")]
    TooDeep(String),
    /// A `%{` with no closing `}`, or a type suffix grok doesn't have.
    #[error("malformed grok reference {0:?}")]
    Malformed(String),
    /// A `date(FORMAT)` with a directive [`date_pattern`] can't match.
    #[error("date format {0}")]
    Date(String),
    /// Definitions given as JSON that aren't an object of strings.
    #[error("grok definitions as JSON: {0}")]
    Json(String),
}

/// Expand `pattern` against `library`, then apply `dialect`.
///
/// # Errors
///
/// [`GrokError`] for an unknown or self-referring name, or a broken `%{...}`.
pub fn expand(pattern: &str, library: &Library, dialect: Dialect) -> Result<Expanded, GrokError> {
    expand_as(pattern, library, dialect, Span::Part, Possessive::Greedy)
}

/// [`expand`] over `span`, with a PCRE pattern's possessive repeats written
/// as asked.
pub(super) fn expand_as(
    pattern: &str,
    library: &Library,
    dialect: Dialect,
    span: Span,
    possessive: Possessive,
) -> Result<Expanded, GrokError> {
    let pattern = &*as_rust(pattern, dialect, possessive);
    let new = |keep_groups| Expander {
        library,
        out: String::with_capacity(pattern.len() * 4),
        captures: Vec::new(),
        stack: Vec::new(),
        onig: dialect == Dialect::Oniguruma,
        names: Vec::new(),
        keep_groups,
        numbered: false,
    };
    let mut e = new(false);
    e.text(pattern)?;
    // A numbered backreference counts groups as they were written.
    if e.numbered {
        e = new(true);
        e.text(pattern)?;
    }
    // Wrapped before the dialect's rewrites, so a final `$` stays a line end.
    let out = match span {
        Span::Part => e.out,
        Span::Whole => format!("(?s)\\A(?:{})\\z", e.out),
    };
    let regex = match dialect {
        Dialect::Rust | Dialect::Pcre => out,
        Dialect::Oniguruma => oniguruma(&out),
    };
    Ok(Expanded {
        regex,
        captures: e.captures,
    })
}

struct Expander<'l> {
    library: &'l Library,
    out: String,
    captures: Vec<Capture>,
    stack: Vec<String>,
    /// Read type suffixes and group names in the Oniguruma dialect's form.
    onig: bool,
    /// Each named group as written, with the capture it became.
    names: Vec<(String, usize)>,
    /// Leave an unnamed group a capture, not `(?:`.
    keep_groups: bool,
    /// The text holds a numbered backreference, `\1` to `\9`.
    numbered: bool,
}

impl Expander<'_> {
    /// Copy `text` to the output, expanding references and renaming groups.
    fn text(&mut self, text: &str) -> Result<(), GrokError> {
        let mut rest = text;
        let mut class = 0_usize;
        while let Some(c) = rest.chars().next() {
            let w = c.len_utf8();
            // A backreference by name follows the group's new name.
            if let Some(name) = backreference(rest)
                && let Some(&(_, i)) = self.names.iter().rev().find(|(n, _)| n == name)
            {
                self.out.push_str("\\k<g");
                self.out.push_str(&i.to_string());
                self.out.push('>');
                rest = &rest[name.len() + 4..];
                continue;
            }
            if c == '\\' {
                self.numbered |= matches!(rest.as_bytes().get(1), Some(b'1'..=b'9'));
                let n = rest[1..].chars().next().map_or(0, char::len_utf8);
                self.out.push_str(&rest[..w + n]);
                rest = &rest[w + n..];
                continue;
            }
            if class > 0 {
                match c {
                    '[' => class += 1,
                    ']' => class -= 1,
                    _ => {}
                }
                self.out.push(c);
                rest = &rest[w..];
                continue;
            }
            if c == '[' {
                class = 1;
                self.out.push('[');
                rest = &rest[1..];
                // A `]` first in a class, or after `^`, is the bracket itself.
                for lead in ["^]", "^", "]"] {
                    if let Some(after) = rest.strip_prefix(lead) {
                        self.out.push_str(lead);
                        rest = after;
                        break;
                    }
                }
                continue;
            }
            if let Some(after) = rest.strip_prefix("%{") {
                let end = after
                    .find('}')
                    .ok_or_else(|| GrokError::Malformed(rest.to_owned()))?;
                self.reference(&after[..end])?;
                rest = &after[end + 1..];
                continue;
            }
            let group = if self.onig {
                onig_group(rest).map(|(raw, after)| (raw, capture_name(raw), after))
            } else {
                named_group(rest).map(|(raw, after)| (raw, (raw, Hint::Text), after))
            };
            if let Some((raw, (name, hint), after)) = group {
                let i = self.capture(field_path(name), hint);
                self.names.push((raw.to_owned(), i));
                self.group(i);
                rest = after;
                continue;
            }
            // An unnamed group writes no field, so it needs no capture slot.
            if c == '(' && !self.keep_groups && !rest[1..].starts_with(['?', '*']) {
                self.out.push_str("(?:");
                rest = &rest[1..];
                continue;
            }
            self.out.push(c);
            rest = &rest[w..];
        }
        Ok(())
    }

    /// `NAME`, `NAME:field` or `NAME:field:type`. With a `date(FORMAT)` type
    /// the name may be left out, and the format is the matcher.
    fn reference(&mut self, inner: &str) -> Result<(), GrokError> {
        let mut parts = inner.splitn(3, ':');
        let name = parts.next().unwrap_or_default();
        let field = parts.next().filter(|f| !f.is_empty());
        // The Oniguruma dialect reads a suffix it doesn't know as text.
        let suffix = parts.next();
        let filter = suffix.and_then(filter_of);
        let date = suffix.and_then(date_format);
        let hint = match suffix.map(hint_of) {
            None => Hint::Text,
            Some(Some(hint)) => hint,
            Some(None) if date.is_some() => Hint::Timestamp,
            Some(None) if self.onig || filter.is_some() => Hint::Text,
            Some(None) => return Err(GrokError::Malformed(format!("%{{{inner}}}"))),
        };
        let generated;
        let def = match date {
            Some(format) if name.is_empty() => {
                generated = date_pattern(format)?;
                generated.as_str()
            }
            _ => self
                .library
                .get(name)
                .ok_or_else(|| GrokError::Unknown(name.to_owned()))?,
        };
        if self.stack.iter().any(|s| s == name) {
            return Err(GrokError::Cycle(name.to_owned()));
        }
        if self.stack.len() == MAX_DEPTH {
            return Err(GrokError::TooDeep(name.to_owned()));
        }
        match field {
            Some(field) => {
                let i = self.capture(field_path(field), hint);
                self.captures[i].filter = filter;
                self.group(i);
            }
            None => self.out.push_str("(?:"),
        }
        self.stack.push(name.to_owned());
        self.text(def)?;
        self.stack.pop();
        self.out.push(')');
        Ok(())
    }

    fn group(&mut self, i: usize) {
        self.out.push_str("(?P<g");
        self.out.push_str(&i.to_string());
        self.out.push('>');
    }

    fn capture(&mut self, field: String, hint: Hint) -> usize {
        self.captures.push(Capture {
            field,
            hint,
            filter: None,
        });
        self.captures.len() - 1
    }
}

/// A `(?<name>` or `(?P<name>` group at the start of `rest`: the name and the
/// text after `>`. Lookbehinds `(?<=` and `(?<!` aren't groups.
fn named_group(rest: &str) -> Option<(&str, &str)> {
    let body = rest
        .strip_prefix("(?P<")
        .or_else(|| rest.strip_prefix("(?<"))?;
    let end = body.find('>')?;
    let name = &body[..end];
    let valid = !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'[' | b']'));
    valid.then(|| (name, &body[end + 1..]))
}

/// `FORMAT` in a `date(FORMAT)` suffix.
fn date_format(suffix: &str) -> Option<&str> {
    suffix.strip_prefix("date(")?.strip_suffix(')')
}

/// The filter a grok suffix names.
fn filter_of(suffix: &str) -> Option<Filter> {
    match suffix {
        "lowercase" => Some(Filter::Lowercase),
        "uppercase" => Some(Filter::Uppercase),
        _ => suffix
            .strip_prefix("nullif(")
            .and_then(|v| v.strip_suffix(')'))
            .map(|v| Filter::NullIf(v.to_owned())),
    }
}

/// The value type a grok suffix names.
fn hint_of(suffix: &str) -> Option<Hint> {
    match suffix {
        "string" => Some(Hint::Text),
        "int" | "long" | "integer" => Some(Hint::Int),
        "float" | "double" | "number" => Some(Hint::Float),
        "boolean" => Some(Hint::Bool),
        _ => None,
    }
}

/// As [`named_group`], plus `(?'name'` and the `NAME:field:type` names
/// the Oniguruma dialect writes its references as.
fn onig_group(rest: &str) -> Option<(&str, &str)> {
    let (name, after) = if let Some(name) = quoted_name(rest) {
        (name, &rest[name.len() + 4..])
    } else {
        let body = rest
            .strip_prefix("(?P<")
            .or_else(|| rest.strip_prefix("(?<"))?;
        let end = body.find('>')?;
        (&body[..end], &body[end + 1..])
    };
    let valid = !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'[' | b']' | b':'));
    valid.then_some((name, after))
}

/// A group name in the Oniguruma dialect's form: `NAME:field:type`, `field:type`
/// where the type is one grok has, else the whole name as the field.
fn capture_name(name: &str) -> (&str, Hint) {
    let parts: Vec<&str> = name.split(':').collect();
    match parts.as_slice() {
        [_, field, suffix] => (field, hint_of(suffix).unwrap_or(Hint::Text)),
        [field, suffix] => hint_of(suffix).map_or((name, Hint::Text), |hint| (field, hint)),
        _ => (name, Hint::Text),
    }
}

/// A field reference `[a][b]` as the name `a.b`. A key holding `.` or `"` is
/// quoted, so `[a.b][c]` is `["a.b"].c`.
fn field_path(field: &str) -> String {
    if !field.starts_with('[') {
        return field.to_owned();
    }
    let mut name = String::with_capacity(field.len());
    for key in field.split(['[', ']']).filter(|s| !s.is_empty()) {
        push_key(&mut name, key);
    }
    name
}

/// Oniguruma's reading of a pattern, in Rust's syntax: the four rewrites in
/// [`Dialect::Oniguruma`], and `\h` as a hex digit.
fn oniguruma(expanded: &str) -> String {
    let mut out = String::with_capacity(expanded.len() + 24);
    out.push_str("(?m)");
    let mut rest = expanded;
    let mut class = false;
    while let Some(c) = rest.chars().next() {
        let w = c.len_utf8();
        match c {
            '\\' => {
                let next = rest[1..].chars().next();
                match next {
                    // Oniguruma has no word-boundary escape: the bracket itself.
                    Some(angle @ ('<' | '>')) => out.push(angle),
                    // `\h` is a hex digit, which Rust has no escape for.
                    Some('h') => out.push_str(if class { "0-9A-Fa-f" } else { "[0-9A-Fa-f]" }),
                    Some('H') if !class => out.push_str("[^0-9A-Fa-f]"),
                    Some(n) => {
                        out.push('\\');
                        out.push(n);
                    }
                    None => out.push('\\'),
                }
                rest = &rest[w + next.map_or(0, char::len_utf8)..];
                continue;
            }
            '[' if !class => class = true,
            ']' if class => class = false,
            // A `{` that opens no interval is the brace itself.
            '{' if !class => {
                let len = match interval(rest) {
                    Some((len, true)) => {
                        out.push_str("{0");
                        out.push_str(&rest[1..len]);
                        len
                    }
                    Some((len, false)) => {
                        out.push_str(&rest[..len]);
                        len
                    }
                    None => {
                        out.push_str("\\{");
                        1
                    }
                };
                rest = &rest[len..];
                continue;
            }
            // Oniguruma's `m` flag is Rust's `s`: `.` crosses a newline.
            '(' if !class && rest.starts_with("(?m)") => {
                out.push_str("(?s)");
                rest = &rest[4..];
                continue;
            }
            _ => {}
        }
        out.push(c);
        rest = &rest[w..];
    }
    if out.ends_with('$') && !out.ends_with("\\$") {
        out.pop();
        out.push_str("(?:\\r\\n|\\n|\\r)?$");
    }
    out
}

/// How a PCRE pattern's possessive repeats, such as `x*+`, are written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Possessive {
    /// As written, for the planner and the backtracking engine.
    Kept,
    /// As the greedy repeat, for the linear regex.
    Greedy,
}

/// `pattern` in the syntax the expander and the planner read: a PCRE pattern
/// rewritten, any other as written.
fn as_rust(pattern: &str, dialect: Dialect, possessive: Possessive) -> std::borrow::Cow<'_, str> {
    match dialect {
        Dialect::Pcre => pcre(pattern, possessive).into(),
        Dialect::Rust | Dialect::Oniguruma => pattern.into(),
    }
}

/// `true` when a PCRE pattern holds a possessive repeat.
pub(super) fn has_possessive(pattern: &str, dialect: Dialect) -> bool {
    dialect == Dialect::Pcre && pcre(pattern, Possessive::Kept) != pcre(pattern, Possessive::Greedy)
}

/// What the last character [`pcre`] read was, for telling a repeat's suffix
/// from a repeat.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Last {
    /// The start, `(` or `|`: nothing to repeat.
    Open,
    /// Something a repeat can follow.
    Atom,
    /// A repeat: `?` after it is lazy, `+` possessive.
    Repeat,
}

/// PCRE's reading of a pattern, in Rust's syntax: the rewrites in
/// [`Dialect::Pcre`]. A `%{...}` reference is copied whole.
fn pcre(pattern: &str, possessive: Possessive) -> String {
    let mut out = String::with_capacity(pattern.len() + 8);
    let mut rest = pattern;
    let mut class = false;
    let mut last = Last::Open;
    while let Some(c) = rest.chars().next() {
        let mut len = c.len_utf8();
        let before = std::mem::replace(&mut last, Last::Atom);
        match c {
            '\\' => {
                let next = rest[1..].chars().next();
                len += next.map_or(0, char::len_utf8);
                match next {
                    // PCRE has no word-boundary escape: the bracket itself.
                    Some(angle @ ('<' | '>')) => out.push(angle),
                    _ => out.push_str(&rest[..len]),
                }
            }
            '[' if class => match rest[2..].find(":]").filter(|_| rest.starts_with("[:")) {
                Some(end) => {
                    len = end + 4;
                    out.push_str(&rest[..len]);
                }
                None => out.push_str("\\["),
            },
            '[' => {
                class = true;
                // A `]` first in a class, or after `^`, is the bracket itself.
                let lead = ["^]", "^", "]"]
                    .into_iter()
                    .find(|lead| rest[1..].starts_with(lead));
                len += lead.map_or(0, str::len);
                out.push_str(&rest[..len]);
            }
            ']' if class => {
                class = false;
                out.push(']');
            }
            '%' if !class && rest.starts_with("%{") => {
                len = rest.find('}').map_or(rest.len(), |end| end + 1);
                out.push_str(&rest[..len]);
            }
            // Branch reset renumbers groups, and a field goes by its name.
            '(' if !class && rest.starts_with("(?|") => {
                len = 3;
                out.push_str("(?:");
                last = Last::Open;
            }
            '{' if !class => match interval(rest) {
                Some((end, low_left_out)) => {
                    out.push_str(if low_left_out { "{0" } else { "{" });
                    out.push_str(&rest[1..end]);
                    len = end;
                    last = Last::Repeat;
                }
                None => out.push_str("\\{"),
            },
            '+' | '?' if !class && before == Last::Repeat => {
                if c == '?' || possessive == Possessive::Kept {
                    out.push(c);
                }
            }
            '*' | '+' | '?' if !class => {
                out.push(c);
                last = match before {
                    Last::Open => Last::Open,
                    Last::Atom | Last::Repeat => Last::Repeat,
                };
            }
            '(' | '|' if !class => {
                out.push(c);
                last = Last::Open;
            }
            _ => out.push(c),
        }
        rest = &rest[len..];
    }
    out
}

/// `pattern` with each inline definition, `%{NAME:field:type=regex}`, moved
/// into `library` under its name, and the reference left as `%{NAME:field:type}`.
pub(super) fn inline_definitions(pattern: &str, library: &mut Library) -> String {
    let mut out = String::with_capacity(pattern.len());
    let mut rest = pattern;
    while let Some(at) = rest.find("%{") {
        out.push_str(&rest[..at]);
        let body = &rest[at + 2..];
        // A definition may hold intervals such as `{3}`, so braces nest.
        let mut depth = 0_usize;
        let end = body.char_indices().find_map(|(k, c)| match c {
            '{' => {
                depth += 1;
                None
            }
            '}' if depth == 0 => Some(k),
            '}' => {
                depth -= 1;
                None
            }
            _ => None,
        });
        let Some(end) = end else {
            out.push_str(&rest[at..]);
            return out;
        };
        let inner = &body[..end];
        let head = if let Some((head, definition)) = inner.split_once('=') {
            library.add(head.split(':').next().unwrap_or(head), definition);
            head.trim_end_matches(':')
        } else {
            inner
        };
        out.push_str("%{");
        out.push_str(head);
        out.push('}');
        rest = &body[end + 1..];
    }
    out.push_str(rest);
    out
}

/// Marks the library entry an alias is filed under. No reference in a library
/// definition is written with it, so those references never reach an alias.
const ALIAS_MARK: char = '\u{1}';

/// The name of each `%{...}` reference in `text`, with where it starts.
fn reference_names(text: &str) -> impl Iterator<Item = (usize, &str)> {
    text.match_indices("%{").filter_map(move |(at, _)| {
        let body = &text[at + 2..];
        let end = body.find([':', '}', '='])?;
        Some((at + 2, &body[..end]))
    })
}

/// `patterns` with each reference to a name in `aliases` pointed at that
/// alias, and the aliases added to `library` under [`ALIAS_MARK`]. An alias's
/// own references are pointed the same way, so an alias shadows the library
/// in the patterns and the aliases, and nowhere else.
pub(super) fn layer_aliases(
    patterns: &[String],
    aliases: &Library,
    library: &mut Library,
) -> Vec<String> {
    let point = |text: &str| {
        let mut out = String::with_capacity(text.len() + 4);
        let mut from = 0;
        for (at, name) in reference_names(text) {
            if aliases.get(name).is_some() {
                out.push_str(&text[from..at]);
                out.push(ALIAS_MARK);
                from = at;
            }
        }
        out.push_str(&text[from..]);
        out
    };
    for (name, def) in &aliases.defs {
        library.add(format!("{ALIAS_MARK}{name}"), point(def));
    }
    patterns.iter().map(|p| point(p)).collect()
}

/// Define each name the patterns reach that `library` lacks as `definition`.
pub(super) fn define_unknown(patterns: &[String], library: &mut Library, definition: &str) {
    let mut todo: Vec<String> = patterns.to_vec();
    let mut seen = std::collections::HashSet::new();
    let mut missing = Vec::new();
    while let Some(text) = todo.pop() {
        for (_, name) in reference_names(&text) {
            if name.is_empty() || !seen.insert(name.to_owned()) {
                continue;
            }
            match library.get(name) {
                Some(def) => todo.push(def.to_owned()),
                None => missing.push(name.to_owned()),
            }
        }
    }
    for name in missing {
        library.add(name, definition);
    }
}

/// `error` with an alias named as it was written.
pub(super) fn unmark(error: GrokError) -> GrokError {
    let named = |name: String| name.trim_start_matches(ALIAS_MARK).to_owned();
    match error {
        GrokError::Unknown(name) => GrokError::Unknown(named(name)),
        GrokError::Cycle(name) => GrokError::Cycle(named(name)),
        GrokError::TooDeep(name) => GrokError::TooDeep(named(name)),
        other => other,
    }
}

/// The length of the `{n}`, `{n,}`, `{n,m}` or `{,m}` at the start of `rest`,
/// and whether it leaves out the low count, which Oniguruma reads as 0.
fn interval(rest: &str) -> Option<(usize, bool)> {
    let b = rest.as_bytes();
    let digits = |from: usize| b[from..].iter().take_while(|c| c.is_ascii_digit()).count();
    let lo = digits(1);
    let mut end = 1 + lo;
    if b.get(end) == Some(&b',') {
        let hi = digits(end + 1);
        end += 1 + hi;
        if lo == 0 && hi == 0 {
            return None;
        }
    } else if lo == 0 {
        return None;
    }
    (b.get(end) == Some(&b'}')).then_some((end + 1, lo == 0))
}

/// The name in a `\k<name>` or `\k'name'` backreference at the start of
/// `rest`.
fn backreference(rest: &str) -> Option<&str> {
    let (tail, close) = rest
        .strip_prefix("\\k<")
        .map(|t| (t, '>'))
        .or_else(|| rest.strip_prefix("\\k'").map(|t| (t, '\'')))?;
    tail.find(close).map(|end| &tail[..end])
}

/// The name in a `(?'name'` group at the start of `rest`.
fn quoted_name(rest: &str) -> Option<&str> {
    let tail = rest.strip_prefix("(?'")?;
    let end = tail.find('\'')?;
    Some(&tail[..end])
}

#[cfg(test)]
mod cover_tests;
#[cfg(test)]
mod plan_tests;
#[cfg(test)]
mod tests;