grippo 0.2.1

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
// Project:   grippo
// File:      src/compose.rs
// Purpose:   Typed primitives composed into a parser, with no pattern text
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Typed primitives composed into a parser, with no pattern text.
//!
//! A [`Part`] is a literal, a field scanner, a run of characters, a run up to
//! a literal, a choice of literals or an anchor, and parts join with
//! [`Part::then`], [`Part::or`] and [`Part::optional`]. [`Part::build`]
//! returns a [`Grok`] parser that answers exactly as the grok pattern the
//! parts spell, on the same native steps, with the same tier and cost.
//!
//! ```
//! use grippo::compose::{field, literal, until};
//! use grippo::parse::{Fields, Parsed, Parser};
//!
//! let parser = literal("<")
//!     .then(field("NONNEGINT").named("pri"))
//!     .then(literal(">"))
//!     .then(until(" ").named("host"))
//!     .then(field("GREEDYDATA").named("msg"))
//!     .build("compose:pri")?;
//! let mut out = Fields::new();
//! assert_eq!(parser.parse(b"<34>web01 disk full", &mut out)?, Parsed::Done);
//! assert_eq!(out.as_slice().len(), 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use regex_syntax::hir::{ClassUnicode, ClassUnicodeRange};
use thiserror::Error;

use crate::field::FIELDS;
use crate::grok::{Grok, GrokBuildError, Library};
use crate::parse::Hint;

/// A set of characters for [`run`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Chars(ClassUnicode);

impl Chars {
    /// These characters.
    #[must_use]
    pub fn of(chars: &str) -> Self {
        Self(ClassUnicode::new(
            chars.chars().map(|c| ClassUnicodeRange::new(c, c)),
        ))
    }

    /// Every character from `first` to `last`, both included.
    #[must_use]
    pub fn range(first: char, last: char) -> Self {
        Self(ClassUnicode::new([ClassUnicodeRange::new(first, last)]))
    }

    /// Every character but these, a newline included unless it's listed.
    #[must_use]
    pub fn but(chars: &str) -> Self {
        let mut set = Self::of(chars);
        set.0.negate();
        set
    }

    /// The characters in either set.
    #[must_use]
    pub fn or(mut self, other: &Self) -> Self {
        self.0.union(&other.0);
        self
    }
}

/// One primitive, or primitives joined. Build it into a parser with
/// [`Part::build`].
#[derive(Debug, Clone)]
pub struct Part {
    node: Node,
    name: Option<String>,
    hint: Hint,
    /// A method called on a part it doesn't apply to, reported at build.
    misuse: Option<&'static str>,
}

#[derive(Debug, Clone)]
enum Node {
    Literal(String),
    Field(String),
    Run {
        chars: Chars,
        min: usize,
        max: Option<usize>,
    },
    /// A lazy run, then this literal when there is one.
    Until(Option<String>),
    OneOf(Vec<String>),
    Seq(Vec<Part>),
    Or(Vec<Part>),
    Optional(Box<Part>),
    Start,
    End,
}

const fn part(node: Node) -> Part {
    Part {
        node,
        name: None,
        hint: Hint::Text,
        misuse: None,
    }
}

/// This text, exactly.
#[must_use]
pub fn literal(text: impl Into<String>) -> Part {
    part(Node::Literal(text.into()))
}

/// The field scanner `name`, such as `IPV4` or `TIMESTAMP_ISO8601`. The
/// scanners are [`crate::field::FIELDS`].
#[must_use]
pub fn field(name: impl Into<String>) -> Part {
    part(Node::Field(name.into()))
}

/// The longest run of `chars`, one or more. [`Part::at_least`] and
/// [`Part::at_most`] change the counts.
#[must_use]
pub const fn run(chars: Chars) -> Part {
    part(Node::Run {
        chars,
        min: 1,
        max: None,
    })
}

/// The shortest run of anything but a newline that ends at `literal` with
/// the rest matching after it, then `literal`. A name captures the run.
#[must_use]
pub fn until(literal: impl Into<String>) -> Part {
    part(Node::Until(Some(literal.into())))
}

/// The shortest run of anything but a newline after which the next part,
/// and the rest, match: grok's `%{DATA}`. Use it where the literal that ends
/// the run follows a choice, and [`until`] everywhere else.
#[must_use]
pub const fn until_next() -> Part {
    part(Node::Until(None))
}

/// The first of these literals that matches, in the order given.
#[must_use]
pub fn one_of<I>(literals: I) -> Part
where
    I: IntoIterator,
    I::Item: Into<String>,
{
    part(Node::OneOf(literals.into_iter().map(Into::into).collect()))
}

/// The start of the input. A part with no `start` matches anywhere in it,
/// and the earliest match wins.
#[must_use]
pub const fn start() -> Part {
    part(Node::Start)
}

/// The end of the input.
#[must_use]
pub const fn end() -> Part {
    part(Node::End)
}

impl Part {
    /// This part, then `next`.
    #[must_use]
    pub fn then(self, next: Self) -> Self {
        let mut parts = self.members(Join::Seq);
        parts.extend(next.members(Join::Seq));
        part(Node::Seq(parts))
    }

    /// This part, or else `other` where this one doesn't match.
    #[must_use]
    pub fn or(self, other: Self) -> Self {
        let mut parts = self.members(Join::Or);
        parts.extend(other.members(Join::Or));
        part(Node::Or(parts))
    }

    /// This part where it matches, else nothing. A field inside one that
    /// didn't match isn't written.
    #[must_use]
    pub fn optional(self) -> Self {
        part(Node::Optional(Box::new(self)))
    }

    /// Write what this part matched as the field `name`. `a.b` is a nested
    /// name, as grok's `[a][b]` is.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Hint the named field's value as `hint`: `Text`, `Int`, `Float` or
    /// `Bool`, as grok's `:int`, `:float` and `:boolean` suffixes do.
    #[must_use]
    pub const fn typed(mut self, hint: Hint) -> Self {
        self.hint = hint;
        self
    }

    /// A [`run`] of at least `count` characters.
    #[must_use]
    pub const fn at_least(mut self, count: usize) -> Self {
        match &mut self.node {
            Node::Run { min, .. } => *min = count,
            _ => self.misuse = Some("at_least on a part that isn't a run"),
        }
        self
    }

    /// A [`run`] of at most `count` characters.
    #[must_use]
    pub const fn at_most(mut self, count: usize) -> Self {
        match &mut self.node {
            Node::Run { max, .. } => *max = Some(count),
            _ => self.misuse = Some("at_most on a part that isn't a run"),
        }
        self
    }

    /// The parser for these parts, registered as `name`, such as
    /// `compose:access`.
    ///
    /// # Errors
    ///
    /// [`ComposeError`] for an unknown field scanner, a field name grok can't
    /// write, a part that matches nothing, or a method on a part it doesn't
    /// apply to.
    pub fn build(&self, name: impl Into<String>) -> Result<Grok, ComposeError> {
        let mut speller = Speller {
            aliases: Library::empty(),
            count: 0,
        };
        let mut pattern = String::new();
        speller.part(self, &mut pattern)?;
        if pattern.is_empty() {
            return Err(ComposeError::Shape("a part that matches nothing"));
        }
        Ok(Grok::builder(name)
            .pattern(pattern)
            .aliases(speller.aliases)
            .build()?)
    }

    /// A part with no name, no hint and no misuse adds nothing of its own
    /// when it joins another of its kind.
    fn plain(&self) -> bool {
        self.name.is_none() && self.hint == Hint::Text && self.misuse.is_none()
    }

    /// The parts this one adds to a join of `kind`.
    fn members(mut self, kind: Join) -> Vec<Self> {
        if self.plain() {
            match (&mut self.node, kind) {
                (Node::Seq(parts), Join::Seq) | (Node::Or(parts), Join::Or) => {
                    return std::mem::take(parts);
                }
                _ => {}
            }
        }
        vec![self]
    }
}

#[derive(Debug, Clone, Copy)]
enum Join {
    Seq,
    Or,
}

/// Why parts didn't build into a parser.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ComposeError {
    /// [`field`] named no field scanner.
    #[error("no field scanner is named {0:?}")]
    UnknownField(String),
    /// A field name that's empty, or holds `:`, `{`, `}`, `=`, `%` or a
    /// control character, which grok can't write.
    #[error("{0:?} can't be a field name")]
    Name(String),
    /// Parts that can't make a parser, and why.
    #[error("{0}")]
    Shape(&'static str),
    /// The pattern the parts spell didn't build.
    #[error(transparent)]
    Build(#[from] GrokBuildError),
}

/// Writes parts as the grok pattern they mean, each named part with no
/// scanner of its own as an alias.
struct Speller {
    aliases: Library,
    count: usize,
}

impl Speller {
    fn part(&mut self, p: &Part, out: &mut String) -> Result<(), ComposeError> {
        if let Some(misuse) = p.misuse {
            return Err(ComposeError::Shape(misuse));
        }
        let capture = match &p.name {
            Some(name) => Some((checked(name)?, suffix(p.hint)?)),
            None if p.hint == Hint::Text => None,
            None => return Err(ComposeError::Shape("a hint with no name")),
        };
        match (&p.node, capture) {
            (Node::Field(name), capture) => scanner(name, capture, out),
            (Node::Until(literal), capture) => lazy_until(literal.as_deref(), capture, out),
            (Node::Start | Node::End, Some(_)) => Err(ComposeError::Shape("a name on an anchor")),
            (node, None) => self.node(node, out),
            (node, Some(capture)) => {
                let mut definition = String::new();
                self.node(node, &mut definition)?;
                let alias = format!("_{}", self.count);
                self.count += 1;
                reference(&alias, Some(capture), out);
                self.aliases.add(alias, definition);
                Ok(())
            }
        }
    }

    fn node(&mut self, node: &Node, out: &mut String) -> Result<(), ComposeError> {
        match node {
            Node::Field(name) => scanner(name, None, out)?,
            Node::Until(literal) => lazy_until(literal.as_deref(), None, out)?,
            Node::Literal(text) => out.push_str(&regex_syntax::escape(text)),
            Node::Run { chars, min, max } => {
                class(chars, out)?;
                quantifier(*min, *max, out)?;
            }
            Node::OneOf(literals) => {
                if literals.is_empty() {
                    return Err(ComposeError::Shape("one_of with no literals"));
                }
                out.push_str("(?:");
                for (i, literal) in literals.iter().enumerate() {
                    if i > 0 {
                        out.push('|');
                    }
                    out.push_str(&regex_syntax::escape(literal));
                }
                out.push(')');
            }
            Node::Seq(parts) => {
                for p in parts {
                    self.part(p, out)?;
                }
            }
            Node::Or(parts) => {
                out.push_str("(?:");
                for (i, p) in parts.iter().enumerate() {
                    if i > 0 {
                        out.push('|');
                    }
                    self.part(p, out)?;
                }
                out.push(')');
            }
            Node::Optional(inner) => {
                out.push_str("(?:");
                self.part(inner, out)?;
                out.push_str(")?");
            }
            Node::Start => out.push('^'),
            Node::End => out.push('$'),
        }
        Ok(())
    }
}

/// A field name and the grok suffix of its hint.
type Capture<'p> = (&'p str, Option<&'static str>);

/// The field scanner `name`, as a reference.
fn scanner(name: &str, capture: Option<Capture<'_>>, out: &mut String) -> Result<(), ComposeError> {
    if !FIELDS.iter().any(|f| f.name == name) {
        return Err(ComposeError::UnknownField(name.to_owned()));
    }
    reference(name, capture, out);
    Ok(())
}

/// `%{DATA}`, then `literal` when there is one, which grok lowers to a lazy
/// run up to it.
fn lazy_until(
    literal: Option<&str>,
    capture: Option<Capture<'_>>,
    out: &mut String,
) -> Result<(), ComposeError> {
    if literal == Some("") {
        return Err(ComposeError::Shape("an until with an empty literal"));
    }
    reference("DATA", capture, out);
    if let Some(literal) = literal {
        out.push_str(&regex_syntax::escape(literal));
    }
    Ok(())
}

/// `%{NAME}`, or `%{NAME:field}` with the hint's suffix.
fn reference(name: &str, capture: Option<Capture<'_>>, out: &mut String) {
    out.push_str("%{");
    out.push_str(name);
    if let Some((field, suffix)) = capture {
        out.push(':');
        out.push_str(field);
        if let Some(suffix) = suffix {
            out.push(':');
            out.push_str(suffix);
        }
    }
    out.push('}');
}

/// `name`, when grok can write it as a field name.
fn checked(name: &str) -> Result<&str, ComposeError> {
    let bad = |c: char| c.is_control() || matches!(c, ':' | '{' | '}' | '=' | '%');
    if name.is_empty() || name.contains(bad) {
        return Err(ComposeError::Name(name.to_owned()));
    }
    Ok(name)
}

/// The grok suffix for `hint`, `None` for text.
const fn suffix(hint: Hint) -> Result<Option<&'static str>, ComposeError> {
    match hint {
        Hint::Text => Ok(None),
        Hint::Int => Ok(Some("int")),
        Hint::Float => Ok(Some("float")),
        Hint::Bool => Ok(Some("boolean")),
        _ => Err(ComposeError::Shape(
            "a hint grok can't write: only Text, Int, Float and Bool",
        )),
    }
}

/// `chars` as a bracket class, every character as a hex escape.
fn class(chars: &Chars, out: &mut String) -> Result<(), ComposeError> {
    use std::fmt::Write as _;
    let ranges = chars.0.ranges();
    if ranges.is_empty() {
        return Err(ComposeError::Shape("a run of an empty set"));
    }
    out.push('[');
    for r in ranges {
        let (first, last) = (u32::from(r.start()), u32::from(r.end()));
        // Writing to a String can't fail.
        let _ = if first == last {
            write!(out, "\\x{{{first:X}}}")
        } else {
            write!(out, "\\x{{{first:X}}}-\\x{{{last:X}}}")
        };
    }
    out.push(']');
    Ok(())
}

/// The repetition a run of `min` to `max` characters is written with.
fn quantifier(min: usize, max: Option<usize>, out: &mut String) -> Result<(), ComposeError> {
    use std::fmt::Write as _;
    // Writing to a String can't fail.
    let _ = match (min, max) {
        (_, Some(0)) => return Err(ComposeError::Shape("a run of at most 0")),
        (min, Some(max)) if max < min => {
            return Err(ComposeError::Shape(
                "a run whose at_most is below its at_least",
            ));
        }
        (1, Some(1)) => Ok(()),
        (0, Some(1)) => out.write_char('?'),
        (0, None) => out.write_char('*'),
        (1, None) => out.write_char('+'),
        (min, None) => write!(out, "{{{min},}}"),
        (min, Some(max)) if min == max => write!(out, "{{{min}}}"),
        (min, Some(max)) => write!(out, "{{{min},{max}}}"),
    };
    Ok(())
}

#[cfg(test)]
mod tests;