grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/expr/set.rs
// Purpose:   Many CEL filters over one record, sharing field reads
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Many lowered filters run over one record at once: each field the set reads
//! is read once, and every `field == "literal"` on one field is one hash
//! lookup.

use std::collections::HashMap;

use crate::record::{Json, Record, Typed};

use super::parse::{self, Cmp, Lit, Refusal};
use super::program::{Frame, Leaf, Lower, Node, Options, Outcome, Program};

/// The most distinct field paths, prefixes included, one set reads.
pub const MAX_SET_FIELDS: usize = 64;

/// Many CEL filters lowered together over one table of field reads.
#[derive(Debug)]
pub struct ProgramSet {
    filter: Program,
    /// Each filter's tree, `None` where it is answered by an index.
    roots: Vec<Option<Node>>,
    /// Per field, each literal to the filters that are `field == literal`.
    index: Vec<(usize, HashMap<String, Vec<usize>>)>,
    /// The filters that refused, by position, and why.
    refused: Vec<(usize, Refusal)>,
}

impl ProgramSet {
    /// Lowers each of `texts` into one set. A text that refuses is left out
    /// and listed by [`ProgramSet::refused`], so the caller runs its
    /// interpreter for that one.
    ///
    /// # Errors
    ///
    /// A [`Refusal`] when the set reads more than [`MAX_SET_FIELDS`] paths.
    pub fn compile<S: AsRef<str>>(texts: &[S], options: &Options) -> Result<Self, Refusal> {
        let mut lower = Lower::new(options, 0, MAX_SET_FIELDS);
        let mut roots = Vec::with_capacity(texts.len());
        let mut refused = Vec::new();
        for (i, text) in texts.iter().enumerate() {
            let text = text.as_ref();
            lower.len = text.len();
            let slots_before = lower.slots.len();
            let reads_before = lower.read.len();
            let probes_before = lower.probes.len();
            match parse::parse(text).and_then(|ast| lower.node(ast)) {
                Ok(node) => roots.push(Some(node)),
                Err(r) if lower.slots.len() >= MAX_SET_FIELDS => return Err(r),
                Err(r) => {
                    lower.slots.truncate(slots_before);
                    lower.read.truncate(reads_before);
                    lower.probes.truncate(probes_before);
                    roots.push(None);
                    refused.push((i, r));
                }
            }
        }
        let mut index: Vec<(usize, HashMap<String, Vec<usize>>)> = Vec::new();
        for (id, root) in roots.iter_mut().enumerate() {
            let Some(Node::Leaf(Leaf::Cmp {
                slot,
                op: Cmp::Eq,
                lit: Lit::Str(want),
            })) = root.as_ref()
            else {
                continue;
            };
            let (slot, want) = (*slot, want.clone());
            let at = index
                .iter()
                .position(|(s, _)| *s == slot)
                .unwrap_or_else(|| {
                    index.push((slot, HashMap::new()));
                    index.len() - 1
                });
            index[at].1.entry(want).or_default().push(id);
            *root = None;
        }
        Ok(Self {
            filter: Program::from_lower(lower),
            roots,
            index,
            refused,
        })
    }

    /// The filters that refused, by their position in the texts, and why.
    #[must_use]
    pub fn refused(&self) -> &[(usize, Refusal)] {
        &self.refused
    }

    /// Every filter true on `json`, by position, in order, into `out`.
    /// `out` is cleared first. A refused filter is never listed. Every field
    /// the set reads is found in one pass.
    pub fn matching(&self, json: &[u8], out: &mut Vec<usize>) {
        self.matching_record(Json::new(json), out);
    }

    /// [`ProgramSet::matching`] over `record`: raw JSON, a raw line or the
    /// fields a parser chain wrote.
    pub fn matching_record<'a, R: Record<'a>>(&self, record: R, out: &mut Vec<usize>) {
        let mut frame = [None; 2 * MAX_SET_FIELDS];
        self.filter.prefill(record, &mut frame);
        self.matching_in(record, &mut frame, out);
    }

    fn matching_in<'a, R: Record<'a>>(
        &self,
        record: R,
        frame: &mut Frame<R::At>,
        out: &mut Vec<usize>,
    ) {
        out.clear();
        for (slot, by_literal) in &self.index {
            if let Ok(Typed::Str(s)) = self.filter.typed(*slot, record, frame)
                && let Some(ids) = by_literal.get(s.as_ref())
            {
                out.extend_from_slice(ids);
            }
        }
        for (id, root) in self.roots.iter().enumerate() {
            if let Some(node) = root
                && self.filter.node(node, record, frame) == Outcome::True
            {
                out.push(id);
            }
        }
        out.sort_unstable();
    }
}