grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/parse/both_paths.rs
// Purpose:   Check a parser against the regex it replaces, input by input
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A native parser is an optimisation over a regex, never a replacement for it.
//!
//! [`check`] runs both over the same inputs and reports the first input where
//! they disagree, so a corpus gate can hold a parser to its regex.

use regex_automata::meta::Regex;

use super::{Fields, Parsed, Parser};

/// Why the check could not start.
#[derive(Debug, thiserror::Error)]
#[error("both-paths: the regex does not compile: {0}")]
pub struct CheckError(#[from] Box<regex_automata::meta::BuildError>);

/// What the two paths wrote: `(name, bytes)` pairs, sorted.
pub type Written = Vec<(String, Vec<u8>)>;

/// The first input where the paths disagree.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Disagreement {
    /// The paths disagree on whether the input matches, or on its fields.
    Fields {
        /// The input.
        input: Vec<u8>,
        /// The parser's fields, `None` when it didn't match.
        native: Option<Written>,
        /// The regex's named groups that took part, `None` when it didn't match.
        regex: Option<Written>,
    },
    /// The parser accepted an input its own signature rules out.
    Signature {
        /// The input.
        input: Vec<u8>,
    },
}

impl std::fmt::Display for Disagreement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fields {
                input,
                native,
                regex,
            } => write!(
                f,
                "paths disagree on {:?}: native {native:?}, regex {regex:?}",
                String::from_utf8_lossy(input)
            ),
            Self::Signature { input } => write!(
                f,
                "the parser accepts {:?} but its signature rules it out",
                String::from_utf8_lossy(input)
            ),
        }
    }
}

impl std::error::Error for Disagreement {}

/// Run `parser` and `pattern` over every input. Field names must equal the
/// regex's group names. A group that took no part writes nothing, on both
/// paths. A parser error counts as no match.
///
/// Returns how many inputs agreed.
///
/// # Errors
///
/// [`CheckError`] when `pattern` doesn't compile. A [`Disagreement`] is
/// returned inside `Ok` so the caller can print it in its own gate.
pub fn check<'i, I>(
    parser: &dyn Parser,
    pattern: &str,
    inputs: I,
) -> Result<Result<usize, Disagreement>, CheckError>
where
    I: IntoIterator<Item = &'i [u8]>,
{
    let re = Regex::new(pattern).map_err(|e| CheckError(Box::new(e)))?;
    let mut caps = re.create_captures();
    let mut agreed = 0;
    for input in inputs {
        let mut out = Fields::new();
        let native = match parser.parse(input, &mut out) {
            Ok(Parsed::Done | Parsed::Body { .. } | Parsed::Decoded(_)) => Some(sorted(
                out.as_slice()
                    .iter()
                    .map(|(n, v)| (n.clone(), v.bytes.to_vec())),
            )),
            Ok(Parsed::NoMatch) | Err(_) => None,
        };
        if native.is_some() && !parser.signature().may_match(input) {
            return Ok(Err(Disagreement::Signature {
                input: input.to_vec(),
            }));
        }
        re.captures(input, &mut caps);
        let regex = caps.is_match().then(|| {
            let names = re
                .group_info()
                .pattern_names(regex_automata::PatternID::ZERO);
            sorted(names.enumerate().filter_map(|(i, name)| {
                let span = caps.get_group(i)?;
                Some((name?.to_owned(), input[span.range()].to_vec()))
            }))
        });
        if native != regex {
            return Ok(Err(Disagreement::Fields {
                input: input.to_vec(),
                native,
                regex,
            }));
        }
        agreed += 1;
    }
    Ok(Ok(agreed))
}

fn sorted(pairs: impl Iterator<Item = (String, Vec<u8>)>) -> Written {
    let mut v: Written = pairs.collect();
    v.sort();
    v
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::{FieldSink, FieldValue, Hint, ParseError};
    use crate::strmatch::Signature;
    use crate::tier::MatcherTier;

    /// `<digits>:<digits>`, as `^(?P<a>[0-9]+):(?P<b>[0-9]+)$` matches.
    struct Pair {
        sig: Signature,
        loose: bool,
    }

    impl Parser for Pair {
        fn name(&self) -> &'static str {
            "pair"
        }
        fn tier(&self) -> MatcherTier {
            MatcherTier::Field
        }
        fn signature(&self) -> &Signature {
            &self.sig
        }
        fn parse<'a>(
            &self,
            input: &'a [u8],
            out: &mut dyn FieldSink<'a>,
        ) -> Result<Parsed, ParseError> {
            let Some(colon) = memchr::memchr(b':', input) else {
                return Ok(Parsed::NoMatch);
            };
            let (a, b) = (&input[..colon], &input[colon + 1..]);
            let digits = |s: &[u8]| !s.is_empty() && s.iter().all(u8::is_ascii_digit);
            if !digits(a) || !(self.loose || digits(b)) {
                return Ok(Parsed::NoMatch);
            }
            out.field("a", FieldValue::borrowed(a, Hint::Int));
            out.field("b", FieldValue::borrowed(b, Hint::Int));
            Ok(Parsed::Done)
        }
    }

    const RE: &str = r"^(?P<a>[0-9]+):(?P<b>[0-9]+)$";
    const INPUTS: [&[u8]; 6] = [b"1:2", b"10:20", b":2", b"1:", b"a:1", b"1:x"];

    fn pair(loose: bool, sig: &str) -> Pair {
        Pair {
            sig: Signature::builder().all_of([sig]).build().unwrap(),
            loose,
        }
    }

    #[test]
    fn an_exact_parser_agrees_on_every_input() {
        assert_eq!(check(&pair(false, ":"), RE, INPUTS).unwrap(), Ok(6));
    }

    #[test]
    fn a_loose_parser_is_caught_on_the_first_input_it_gets_wrong() {
        let got = check(&pair(true, ":"), RE, INPUTS).unwrap().unwrap_err();
        assert!(
            matches!(&got, Disagreement::Fields { input, native: Some(_), regex: None } if input == b"1:")
        );
    }

    #[test]
    fn a_signature_that_rules_out_an_accepted_input_is_caught() {
        let got = check(&pair(false, "::"), RE, INPUTS).unwrap().unwrap_err();
        assert!(matches!(got, Disagreement::Signature { .. }));
    }

    #[test]
    fn a_bad_regex_is_an_error() {
        assert!(check(&pair(false, ":"), "(", INPUTS).is_err());
    }
}