grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/grok/cover_tests.rs
// Purpose:   Inputs that take every DFA transition of a lowered pattern
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::collections::{HashMap, VecDeque};

use regex_automata::dfa::{Automaton, StartKind, dense};
use regex_automata::util::primitives::StateID;
use regex_automata::{Anchored, Input};

use super::plan::Outcome;
use super::{Dialect, Grok, Library, expand};
use crate::parse::{Fields, Parsed, Parser};

/// How far one run goes: a pattern whose DFA passes `dfa_bytes` or `states`
/// is skipped, and each pattern keeps at most `inputs`, thinned evenly.
#[derive(Clone, Copy)]
struct Reach {
    dfa_bytes: usize,
    states: usize,
    inputs: usize,
}

type Found = Option<Vec<(String, Vec<u8>)>>;

/// One matching input per DFA transition of `regex`: the shortest way to the
/// transition's state, its byte, then a way on to a match. `None` when the
/// DFA doesn't build inside the size limits.
fn covering_inputs(regex: &str, reach: Reach) -> Option<Vec<Vec<u8>>> {
    let config = dense::Config::new()
        .start_kind(StartKind::Anchored)
        .unicode_word_boundary(true)
        .dfa_size_limit(Some(reach.dfa_bytes))
        .determinize_size_limit(Some(reach.dfa_bytes * 2));
    let dfa = dense::Builder::new().configure(config).build(regex).ok()?;
    let start = dfa
        .start_state_forward(&Input::new(b"").anchored(Anchored::Yes))
        .ok()?;
    let bytes: Vec<u8> = dfa
        .byte_classes()
        .representatives(..)
        .filter_map(regex_automata::util::alphabet::Unit::as_u8)
        .collect();
    let mut to: HashMap<StateID, Vec<u8>> = HashMap::from([(start, Vec::new())]);
    let mut edges: Vec<(StateID, u8, StateID)> = Vec::new();
    let mut queue = VecDeque::from([start]);
    while let Some(s) = queue.pop_front() {
        for &b in &bytes {
            let t = dfa.next_state(s, b);
            if dfa.is_dead_state(t) || dfa.is_quit_state(t) {
                continue;
            }
            edges.push((s, b, t));
            if !to.contains_key(&t) {
                if to.len() == reach.states {
                    return None;
                }
                let mut path = to[&s].clone();
                path.push(b);
                to.insert(t, path);
                queue.push_back(t);
            }
        }
    }
    let mut onward: HashMap<StateID, Vec<u8>> = to
        .keys()
        .filter(|&&s| dfa.is_match_state(dfa.next_eoi_state(s)))
        .map(|&s| (s, Vec::new()))
        .collect();
    loop {
        let mut grew = false;
        for &(s, b, t) in &edges {
            if !onward.contains_key(&s)
                && let Some(rest) = onward.get(&t)
            {
                let path = [&[b], rest.as_slice()].concat();
                onward.insert(s, path);
                grew = true;
            }
        }
        if !grew {
            break;
        }
    }
    let mut inputs: Vec<Vec<u8>> = edges
        .iter()
        .filter_map(|&(s, b, t)| Some([to[&s].as_slice(), &[b], onward.get(&t)?].concat()))
        .collect();
    inputs.sort_unstable();
    inputs.dedup();
    let step = inputs.len().div_ceil(reach.inputs).max(1);
    Some(inputs.into_iter().step_by(step).collect())
}

fn fields(parsed: &Parsed, out: &Fields<'_>) -> Found {
    (*parsed != Parsed::NoMatch).then(|| {
        out.as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), v.bytes.to_vec()))
            .collect()
    })
}

/// `parse` and, on UTF-8, the steps' own answer, each against the regex.
/// Returns whether the steps decided the line.
fn agrees(g: &Grok, pattern: &str, line: &[u8]) -> bool {
    let mut out = Fields::new();
    let regex = fields(&g.parse_regex(line, &mut out).unwrap(), &out);
    let mut out = Fields::new();
    let parsed = fields(&g.parse(line, &mut out).unwrap(), &out);
    let shown = String::from_utf8_lossy(line);
    assert_eq!(parsed, regex, "{pattern} parses {shown:?}");
    if std::str::from_utf8(line).is_err() {
        return false;
    }
    let (outcome, native) = g.native_outcome(line).unwrap();
    match outcome {
        Outcome::Matched => assert_eq!(Some(native), regex, "{pattern} on {shown:?}"),
        Outcome::NoMatch => assert_eq!(None, regex, "{pattern} on {shown:?}"),
        Outcome::Unsure => return false,
    }
    true
}

/// Walk every lowered library definition in `dialect` and return (patterns,
/// lines, lines the steps decided).
fn walk(reach: Reach, dialect: Dialect) -> (usize, usize, usize) {
    let lib = Library::default();
    let mut names: Vec<&String> = lib.defs.keys().collect();
    names.sort();
    let (mut patterns, mut lines, mut decided) = (0, 0, 0);
    for name in names {
        let p = format!("%{{{name}:f}}");
        let Ok(g) = Grok::builder("grok:c").pattern(&p).dialect(dialect).build() else {
            continue;
        };
        if g.blocked()[0].is_some() {
            continue;
        }
        let regex = expand(&p, &lib, dialect).unwrap().regex;
        let Some(inputs) = covering_inputs(&regex, reach) else {
            continue;
        };
        patterns += 1;
        for input in &inputs {
            let half = &input[..input.len() / 2];
            let framed = [b"x ", input.as_slice(), b" y"].concat();
            for line in [input.as_slice(), half, framed.as_slice()] {
                lines += 1;
                decided += usize::from(agrees(&g, &p, line));
            }
        }
    }
    eprintln!("{patterns} patterns, {lines} lines, {decided} decided by the steps");
    (patterns, lines, decided)
}

#[test]
fn dfa_transitions_of_lowered_definitions_agree_with_the_regex() {
    let reach = Reach {
        dfa_bytes: 128 << 10,
        states: 300,
        inputs: 40,
    };
    let (patterns, lines, decided) = walk(reach, Dialect::Rust);
    assert!(
        patterns >= 150,
        "only {patterns} patterns had a DFA to walk"
    );
    assert!(
        decided * 2 > lines,
        "the steps decided {decided} of {lines}"
    );
}

/// Every transition of every definition. Run with `--run-ignored only`.
#[test]
#[ignore = "minutes unoptimised: the full walk"]
fn every_dfa_transition_of_a_lowered_definition_agrees_with_the_regex() {
    let reach = Reach {
        dfa_bytes: 8 << 20,
        states: 4_000,
        inputs: 1_000,
    };
    let onig = walk(reach, Dialect::Oniguruma);
    assert!(
        onig.0 >= 250,
        "only {} Oniguruma patterns had a DFA",
        onig.0
    );
    let (patterns, lines, decided) = walk(reach, Dialect::Rust);
    assert!(
        patterns >= 250,
        "only {patterns} patterns had a DFA to walk"
    );
    assert!(
        decided * 2 > lines,
        "the steps decided {decided} of {lines}"
    );
}

/// A field repeated a fixed number of times: the regex moves its end on the
/// early passes and takes its longest end on the last.
#[test]
fn a_field_in_a_counted_loop_ends_where_the_regex_ends_it() {
    let p = "%{BACULA_CAPACITY:f}";
    let g = Grok::builder("grok:c").pattern(p).build().unwrap();
    assert!(g.blocked()[0].is_none());
    for line in ["0,0+0+0,000", "x 0,0+0+0\u{660} y", "12,345,678", "1,2"] {
        agrees(&g, p, line.as_bytes());
    }
}