grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/grok/spec.rs
// Purpose:   A lowered pattern as ops for generated code, and the parser around it
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The build-time back end: `grippo_macros::grok!` turns a pattern into Rust
//! from the [`Op`] list here, and [`Compiled`] runs that code with the
//! regex behind it.
//!
//! Every op leaves at most one place the regex could end it, so the generated
//! code makes no choice the regex might make differently. A pattern outside
//! that subset isn't compiled: [`ops`] says why.

use std::ops::Range;

use super::{Capture, Dialect, Grok, GrokBuildError, Library, expand};
use crate::parse::{FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

#[doc(hidden)]
pub use memchr::{memchr, memmem};

/// The most fields a compiled pattern writes.
pub const MAX_CAPTURES: usize = 64;

/// A capture no op wrote.
#[doc(hidden)]
pub const UNSET: (usize, usize) = (usize::MAX, usize::MAX);

/// A character class, for a byte test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Class {
    /// Its ASCII members, a bit each.
    pub ascii: u128,
    /// It holds characters past ASCII.
    pub other: bool,
    /// It's every character but a newline.
    pub line: bool,
}

/// One step of a compiled pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Op {
    /// These bytes.
    Literal(Vec<u8>),
    /// One of these literals, none a prefix of another.
    Alt {
        /// The capture it writes.
        capture: Option<usize>,
        /// The literals, in the pattern's order.
        literals: Vec<Vec<u8>>,
    },
    /// A native field scanner.
    Field {
        /// Its place in [`crate::field::FIELDS`].
        index: usize,
        /// The capture it writes.
        capture: Option<usize>,
        /// Every character the field can hold.
        alphabet: Class,
        /// What follows is the end of the input.
        then_end: bool,
        /// What follows may match nothing.
        rest_nullable: bool,
    },
    /// A field whose characters overlap what follows, settled per line: of
    /// the ends its regex allows, the one where what follows can start.
    Settle {
        /// Its place in [`crate::field::FIELDS`].
        index: usize,
        /// The capture it writes.
        capture: Option<usize>,
        /// Characters what follows can start with.
        follow: Class,
        /// What follows can match once the input has ended.
        eoi: bool,
        /// What follows may match nothing, so every end will do.
        open: bool,
    },
    /// A greedy run of one class that what follows can't start with.
    Span {
        /// The capture it writes.
        capture: Option<usize>,
        /// The class.
        class: Class,
        /// Fewest characters.
        min: usize,
        /// Most characters.
        max: Option<usize>,
    },
    /// A run of one class that what follows can start with: the longest end
    /// where the rest of its sequence matches, or the shortest when lazy.
    GiveBack {
        /// The capture it writes.
        capture: Option<usize>,
        /// The class.
        class: Class,
        /// Fewest characters.
        min: usize,
        /// Most characters.
        max: Option<usize>,
        /// The shortest end first.
        lazy: bool,
    },
    /// A lazy run of one class up to the first `literal`, which the next op
    /// reads.
    Until {
        /// The capture it writes.
        capture: Option<usize>,
        /// The class.
        class: Class,
        /// Fewest characters, 0 or 1.
        min: usize,
        /// The literal that ends it.
        literal: Vec<u8>,
    },
    /// An optional group: these ops when they match, else nothing. After a
    /// taken group a miss is the regex's to settle.
    Optional(Vec<Self>),
    /// Branches tried in order: the first that matches is kept, and after it
    /// a miss is the regex's to settle. An empty branch always matches.
    Choice(Vec<Vec<Self>>),
    /// A group of ops repeated `min` to `max` times, the most first unless
    /// lazy, each count tried with the rest of the sequence after it.
    Loop {
        /// The ops repeated, with no choice, group or run that gives back.
        body: Vec<Self>,
        /// Fewest passes.
        min: usize,
        /// Most passes.
        max: Option<usize>,
        /// The fewest passes first.
        lazy: bool,
    },
    /// Where this capture starts, for a group of several ops.
    Open(usize),
    /// Where this capture ends.
    Close(usize),
    /// The end of the input.
    End,
}

/// What generated code made of a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Steps {
    /// The regex's answer: the captures were written.
    Matched,
    /// The regex can't match either.
    NoMatch,
    /// Only the regex can say.
    Unsure,
}

/// The ops for `pattern`, and the fields its captures write, or why it
/// doesn't compile. The pattern is in the Rust dialect, against the stock
/// library.
///
/// # Errors
///
/// What kept the pattern from compiling.
pub fn ops(pattern: &str) -> Result<(Vec<Op>, Vec<Capture>), String> {
    let library = Library::default();
    let expanded = expand(pattern, &library, Dialect::Rust).map_err(|e| e.to_string())?;
    if expanded.captures.len() > MAX_CAPTURES {
        return Err(format!("more than {MAX_CAPTURES} captures"));
    }
    let plan = super::plan::Plan::lower(pattern, &library, Dialect::Rust, super::Span::Part)?;
    let ops = plan.ops()?;
    Ok((ops, expanded.captures))
}

/// Run `f` on `n` capture slots, all unset. Most patterns fit in 8, which
/// saves filling all 64 on every line.
fn with_caps<R>(n: usize, f: impl FnOnce(&mut [(usize, usize)]) -> R) -> R {
    if n <= 8 {
        f(&mut [UNSET; 8][..n])
    } else if n <= 32 {
        f(&mut [UNSET; 32][..n])
    } else {
        f(&mut [UNSET; MAX_CAPTURES][..n])
    }
}

/// What generated code `steps` makes of `input`, with each capture written
/// to `out` on a match. `None` when only the regex can say.
pub(super) fn run_steps<'a>(
    steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
    captures: &[Capture],
    input: &'a [u8],
    out: &mut dyn FieldSink<'a>,
) -> Option<Parsed> {
    with_caps(captures.len(), |caps| match steps(input, caps) {
        Steps::Matched => {
            for (c, &(start, end)) in captures.iter().zip(caps.iter()) {
                // A capture in an optional group that wasn't taken.
                if start != usize::MAX
                    && let Some(v) = c.value(&input[start..end])
                {
                    out.field(&c.field, v);
                }
            }
            Some(Parsed::Done)
        }
        Steps::NoMatch => Some(Parsed::NoMatch),
        Steps::Unsure => None,
    })
}

/// Generated code for one pattern, with the regex behind it for a line the
/// code can't settle.
pub struct Compiled {
    grok: Grok,
    captures: Vec<Capture>,
    steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
}

impl std::fmt::Debug for Compiled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Compiled")
            .field("grok", &self.grok)
            .finish_non_exhaustive()
    }
}

impl Compiled {
    /// Wrap `steps`, the code `grippo_macros::grok!` wrote for `pattern`.
    ///
    /// # Errors
    ///
    /// [`GrokBuildError`] when the pattern doesn't build as a [`Grok`].
    #[doc(hidden)]
    pub fn new(
        name: &str,
        pattern: &str,
        steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
    ) -> Result<Self, GrokBuildError> {
        let grok = Grok::builder(name).pattern(pattern).build()?;
        let library = Library::default();
        let expanded = expand(pattern, &library, Dialect::Rust)
            .map_err(|source| GrokBuildError::Expand { index: 0, source })?;
        Ok(Self {
            grok,
            captures: expanded.captures,
            steps,
        })
    }

    /// What the generated code alone makes of `input`, with no regex.
    #[must_use]
    pub fn steps(&self, input: &[u8]) -> Steps {
        with_caps(self.captures.len(), |caps| (self.steps)(input, caps))
    }

    /// The parser behind the generated code.
    #[must_use]
    pub const fn grok(&self) -> &Grok {
        &self.grok
    }
}

impl Parser for Compiled {
    fn name(&self) -> &str {
        self.grok.name()
    }

    fn tier(&self) -> MatcherTier {
        self.grok.tier()
    }

    fn signature(&self) -> &Signature {
        self.grok.signature()
    }

    fn hands_on_body(&self) -> bool {
        false
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        if let Some(parsed) = run_steps(self.steps, &self.captures, input, out) {
            return Ok(parsed);
        }
        self.grok.parse(input, out)
    }
}

/// The one end of field `index` from `at` where what follows can start:
/// `Some(Ok(end))`, `Some(Err(()))` when there's none, `None` when only the
/// regex can say.
#[doc(hidden)]
#[must_use]
pub fn settle(
    index: usize,
    h: &[u8],
    at: usize,
    follow: Class,
    eoi: bool,
    open: bool,
) -> Option<Result<usize, ()>> {
    let field = crate::field::FIELDS.get(index)?;
    // The scanner is exact to the field's regex, so a field it can't start
    // has no end to settle, and a miss skips the DFA walk.
    if matches!((field.scan)(h, at), crate::field::Scan::NoMatch) {
        return Some(Err(()));
    }
    let ends = super::ends::of(field)?;
    let unsure = std::cell::Cell::new(false);
    let viable = |p: usize| {
        if open {
            return true;
        }
        match h.get(p) {
            None => eoi,
            Some(&b) if b < 0x80 => (follow.ascii >> b) & 1 == 1,
            Some(_) => {
                unsure.set(unsure.get() || follow.other);
                false
            }
        }
    };
    let mut budget = h.len().saturating_add(1).saturating_mul(64);
    let end = ends.only(h, at, &mut budget, viable);
    if unsure.get() {
        return None;
    }
    match end {
        super::ends::End::At(end) => Some(Ok(end)),
        super::ends::End::Nowhere => Some(Err(())),
        super::ends::End::Unsure | super::ends::End::Spent => None,
    }
}

/// Where `literal` first starts in `h` from `from`, no further than `last`.
#[doc(hidden)]
#[must_use]
pub fn find(h: &[u8], from: usize, last: usize, literal: &[u8]) -> Option<usize> {
    let p = from + memmem::find(h.get(from..)?, literal)?;
    (p <= last).then_some(p)
}

/// `range` as the pair the generated code writes.
#[doc(hidden)]
#[must_use]
pub const fn pair(range: Range<usize>) -> (usize, usize) {
    (range.start, range.end)
}