grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/grok/backtrack.rs
// Purpose:   Grok patterns on fancy-regex: those the linear engine refuses, and lookaround reads
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use fancy_regex::{Captures, Regex, RegexBuilder};

use super::Capture;
#[cfg(feature = "parse-backtracking")]
use super::Expanded;
use crate::parse::{FieldSink, ParseError};

#[cfg(test)]
thread_local! {
    /// fancy-regex searches this thread has run.
    pub(super) static SEARCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The patterns a list opted into backtracking, each searched on its own.
#[cfg(feature = "parse-backtracking")]
pub(super) struct Backtracking {
    patterns: Vec<Pattern>,
}

/// One pattern on fancy-regex, expanded with its lookarounds as written.
pub(super) struct Pattern {
    /// Its place in the list, which breaks a tie between equal starts.
    index: usize,
    regex: Regex,
    /// The capture behind each group index, `None` for one that names no field.
    groups: Vec<Option<Capture>>,
}

/// The earliest match of a pattern, or of the backtracking patterns.
pub(super) struct Hit<'p, 'a> {
    pub(super) start: usize,
    pub(super) index: usize,
    captures: Captures<'a, [u8]>,
    groups: &'p [Option<Capture>],
}

impl Pattern {
    /// Compile `regex`, pattern `index`'s expansion, with `limit` backtracks a
    /// search.
    pub(super) fn new(
        index: usize,
        regex: &str,
        captures: &[Capture],
        limit: usize,
    ) -> Result<Self, Box<fancy_regex::Error>> {
        let regex = RegexBuilder::new(regex)
            .backtrack_limit(limit)
            .build()
            .map_err(Box::new)?;
        let groups = regex
            .capture_names()
            .map(|name| {
                let i: usize = name?.strip_prefix('g')?.parse().ok()?;
                captures.get(i).cloned()
            })
            .collect();
        Ok(Self {
            index,
            regex,
            groups,
        })
    }

    /// The leftmost match that starts at `from` or later, in one search, so
    /// the backtrack limit covers every start it tries.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] when the search passes the limit.
    pub(super) fn search_from<'p, 'a>(
        &'p self,
        input: &'a [u8],
        from: usize,
    ) -> Result<Option<Hit<'p, 'a>>, ParseError> {
        #[cfg(test)]
        SEARCHES.with(|n| n.set(n.get() + 1));
        let found = self
            .regex
            .captures_from_pos(input, from)
            .map_err(|_| ParseError::Limit {
                what: "the backtracking budget",
            })?;
        Ok(found.map(|captures| Hit {
            start: captures.get(0).map_or(from, |m| m.start()),
            index: self.index,
            captures,
            groups: &self.groups,
        }))
    }
}

#[cfg(feature = "parse-backtracking")]
impl Backtracking {
    /// The patterns at places `slow` in the list, from their expansions with
    /// the lookarounds as written, `limit` backtracks a search. `None` for
    /// no pattern.
    pub(super) fn new(
        slow: &[usize],
        rendered: &[Option<Expanded>],
        limit: usize,
    ) -> Result<Option<Self>, Box<fancy_regex::Error>> {
        let patterns = slow
            .iter()
            .filter_map(|&i| Some((i, rendered.get(i)?.as_ref()?)))
            .map(|(i, e)| Pattern::new(i, &e.regex, &e.captures, limit))
            .collect::<Result<Vec<Pattern>, Box<fancy_regex::Error>>>()?;
        Ok((!patterns.is_empty()).then_some(Self { patterns }))
    }

    /// Whether the pattern at `index` in the list runs here.
    pub(super) fn holds(&self, index: usize) -> bool {
        self.patterns.iter().any(|p| p.index == index)
    }

    /// The match that starts earliest, a tie going to the pattern listed
    /// first, where it beats `rival`, the other tier's start and place in the
    /// list. A pattern that can't beat it isn't searched.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] when a search passes its backtrack limit.
    pub(super) fn search<'p, 'a>(
        &'p self,
        input: &'a [u8],
        rival: Option<(usize, usize)>,
    ) -> Result<Option<Hit<'p, 'a>>, ParseError> {
        let mut best: Option<Hit<'p, 'a>> = None;
        for p in &self.patterns {
            // Nothing starts before 0, and a tie goes to the earlier pattern.
            let bound = best.as_ref().map(|b| (b.start, b.index)).or(rival);
            if bound.is_some_and(|(start, index)| start == 0 && index < p.index) {
                continue;
            }
            let Some(hit) = p.search_from(input, 0)? else {
                continue;
            };
            if bound.is_none_or(|first| (hit.start, hit.index) < first) {
                best = Some(hit);
            }
        }
        Ok(best)
    }
}

impl<'a> Hit<'_, 'a> {
    /// Write the match's fields to `out`.
    pub(super) fn write(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>) {
        for (i, capture) in self.groups.iter().enumerate() {
            if let (Some(c), Some(m)) = (capture, self.captures.get(i))
                && let Some(v) = c.value(&input[m.range()])
            {
                out.field(&c.field, v);
            }
        }
    }
}