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/expr/valued.rs
// Purpose:   CEL value expressions lowered: ternaries, sums, fields and literals
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A CEL expression that gives a value rather than a filter's answer, such as
//! `risk_score > 80 ? "high" : "low"` or `bytes_in + bytes_out`.

use std::borrow::Cow;

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

#[cfg(feature = "expr-cel")]
use super::fallback::CelProgram;
use super::parse::{self, Lit, Refusal};
#[cfg(not(feature = "expr-cel"))]
use super::program::no_cel;
use super::program::{
    Engine, FRAME, Fallback, Frame, Lower, MAX_FIELDS, Options, Outcome, Program,
};
use super::value::{ErrorKind, read_error};

/// What a value expression gives for one record.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Value<'a> {
    /// A string, borrowed from the record or the expression where it can be.
    Str(Cow<'a, str>),
    /// An int.
    Int(i64),
    /// A uint.
    Uint(u64),
    /// A double.
    Double(f64),
    /// A bool.
    Bool(bool),
    /// A null.
    Null,
    /// A JSON array or object, its text.
    Json(Cow<'a, str>),
}

/// A CEL value expression lowered to the checks and reads a filter uses.
#[derive(Debug)]
pub struct ValueProgram {
    filter: Program,
    root: Node,
    /// The interpreter that runs the text in place of `root`.
    #[cfg(feature = "expr-cel")]
    cel: Option<Box<CelProgram>>,
}

#[derive(Debug)]
enum Node {
    Pred(super::program::Node),
    Cond(super::program::Node, Box<Self>, Box<Self>),
    Add(Vec<Self>),
    Lit(Lit),
    Field(usize),
}

impl ValueProgram {
    /// Lowers `text`, or returns the first form outside the lowered subset:
    /// a ternary over a filter, `+` over fields and literals, a field, or a
    /// literal.
    ///
    /// # Errors
    ///
    /// A [`Refusal`] naming the form, so the caller can run its interpreter.
    pub fn compile(text: &str) -> Result<Self, Refusal> {
        Self::compile_with(text, &Options::default())
    }

    /// [`ValueProgram::compile`] with `options`. Under [`Fallback::Cel`],
    /// text outside the lowered subset runs on cel.
    ///
    /// # Errors
    ///
    /// A [`Refusal`] naming the form, so the caller can run its interpreter.
    /// Under [`Fallback::Cel`] it means cel can't compile the text either, it
    /// calls `matches()` without `Options::allow_regex`, or the `expr-cel`
    /// feature is off.
    pub fn compile_with(text: &str, options: &Options) -> Result<Self, Refusal> {
        let lowered = Self::lower(text, options);
        match options.fallback {
            Fallback::Cel if lowered.is_err() => Self::cel(text, options),
            _ => lowered,
        }
    }

    #[cfg(feature = "expr-cel")]
    fn cel(text: &str, options: &Options) -> Result<Self, Refusal> {
        CelProgram::compile(text, options).map(Self::from_cel)
    }

    #[cfg(not(feature = "expr-cel"))]
    const fn cel(text: &str, _: &Options) -> Result<Self, Refusal> {
        Err(no_cel(text))
    }

    fn lower(text: &str, options: &Options) -> Result<Self, Refusal> {
        let ast = parse::parse_value(text)?;
        let mut lower = Lower::new(options, text.len(), MAX_FIELDS);
        let root = node(&mut lower, ast)?;
        Ok(Self {
            filter: Program::from_lower(lower),
            root,
            #[cfg(feature = "expr-cel")]
            cel: None,
        })
    }

    #[cfg(feature = "expr-cel")]
    fn from_cel(cel: CelProgram) -> Self {
        Self {
            filter: Program::from_lower(Lower::new(&Options::default(), 0, MAX_FIELDS)),
            root: Node::Lit(Lit::Null),
            cel: Some(Box::new(cel)),
        }
    }

    /// Text cel runs whole, never lowered, so a test holds both engines to
    /// one answer.
    #[cfg(all(test, feature = "expr-cel"))]
    pub(super) fn compile_cel(text: &str, options: &Options) -> Result<Self, Refusal> {
        Self::cel(text, options)
    }

    /// Which engine runs this expression.
    #[must_use]
    pub const fn engine(&self) -> Engine {
        #[cfg(feature = "expr-cel")]
        if self.cel.is_some() {
            return Engine::Cel;
        }
        Engine::Lowered
    }

    /// The expression's value on the JSON record `json`, or the error cel
    /// would raise.
    ///
    /// # Errors
    ///
    /// The [`ErrorKind`] of the first error the evaluation meets.
    pub fn eval<'a>(&'a self, json: &'a [u8]) -> Result<Value<'a>, ErrorKind> {
        self.eval_record(Json::new(json))
    }

    /// [`ValueProgram::eval`] over `record`: raw JSON, a raw line or the
    /// fields a parser chain wrote.
    ///
    /// # Errors
    ///
    /// The [`ErrorKind`] of the first error the evaluation meets.
    pub fn eval_record<'a, R: Record<'a>>(&'a self, record: R) -> Result<Value<'a>, ErrorKind> {
        #[cfg(feature = "expr-cel")]
        if let Some(cel) = &self.cel {
            return cel.value(record);
        }
        let mut frame = [None; FRAME];
        self.filter.prefill(record, &mut frame);
        self.value(&self.root, record, &mut frame)
    }

    fn value<'a, R: Record<'a>>(
        &'a self,
        n: &'a Node,
        record: R,
        frame: &mut Frame<R::At>,
    ) -> Result<Value<'a>, ErrorKind> {
        match n {
            Node::Pred(p) => match self.filter.node(p, record, frame) {
                Outcome::True => Ok(Value::Bool(true)),
                Outcome::False => Ok(Value::Bool(false)),
                Outcome::Error(kind) => Err(kind),
            },
            Node::Cond(c, then, other) => match self.filter.node(c, record, frame) {
                Outcome::True => self.value(then, record, frame),
                Outcome::False => self.value(other, record, frame),
                Outcome::Error(kind) => Err(kind),
            },
            Node::Lit(lit) => Ok(literal(lit)),
            Node::Field(slot) => {
                let at = self.filter.resolve(*slot, record, frame)?;
                Ok(match record.typed(at).map_err(read_error)? {
                    Typed::Str(s) => Value::Str(s),
                    Typed::Int(n) => Value::Int(n),
                    Typed::Uint(n) => Value::Uint(n),
                    Typed::Double(n) => Value::Double(n),
                    Typed::Bool(b) => Value::Bool(b),
                    Typed::Null => Value::Null,
                    Typed::List | Typed::Map => Value::Json(record.text(at).map_err(read_error)?),
                })
            }
            Node::Add(terms) => {
                let mut terms = terms.iter();
                let Some(first) = terms.next() else {
                    return Err(ErrorKind::TypeMismatch);
                };
                let mut sum = self.value(first, record, frame)?;
                for t in terms {
                    sum = add(sum, self.value(t, record, frame)?)?;
                }
                Ok(sum)
            }
        }
    }
}

fn literal(lit: &Lit) -> Value<'_> {
    match lit {
        Lit::Str(s) => Value::Str(Cow::Borrowed(s)),
        Lit::Int(n) => Value::Int(*n),
        Lit::Uint(n) => Value::Uint(*n),
        Lit::Double(n) => Value::Double(*n),
        Lit::Bool(b) => Value::Bool(*b),
        Lit::Null => Value::Null,
    }
}

/// cel's `+`: each type adds only its own, ints and uints checked.
fn add<'a>(a: Value<'a>, b: Value<'a>) -> Result<Value<'a>, ErrorKind> {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => {
            x.checked_add(y).map(Value::Int).ok_or(ErrorKind::Overflow)
        }
        (Value::Uint(x), Value::Uint(y)) => {
            x.checked_add(y).map(Value::Uint).ok_or(ErrorKind::Overflow)
        }
        (Value::Double(x), Value::Double(y)) => Ok(Value::Double(x + y)),
        (Value::Str(x), Value::Str(y)) => Ok(Value::Str(Cow::Owned(x.into_owned() + &y))),
        (Value::Json(x), Value::Json(y)) if x.starts_with('[') && y.starts_with('[') => {
            Ok(Value::Json(Cow::Owned(concat_arrays(&x, &y))))
        }
        _ => Err(ErrorKind::TypeMismatch),
    }
}

/// Two JSON arrays' text as one array.
fn concat_arrays(a: &str, b: &str) -> String {
    let inner = |s: &str| {
        s.trim()
            .strip_prefix('[')
            .and_then(|s| s.strip_suffix(']'))
            .unwrap_or_default()
            .trim()
            .to_owned()
    };
    let (x, y) = (inner(a), inner(b));
    match (x.is_empty(), y.is_empty()) {
        (true, _) => format!("[{y}]"),
        (_, true) => format!("[{x}]"),
        _ => format!("[{x},{y}]"),
    }
}

fn node(lower: &mut Lower, v: parse::Value) -> Result<Node, Refusal> {
    Ok(match v {
        parse::Value::Pred(ast) => Node::Pred(lower.node(ast)?),
        parse::Value::Cond(c, then, other) => Node::Cond(
            lower.node(c)?,
            Box::new(node(lower, *then)?),
            Box::new(node(lower, *other)?),
        ),
        parse::Value::Add(terms) => Node::Add(
            terms
                .into_iter()
                .map(|t| node(lower, t))
                .collect::<Result<_, _>>()?,
        ),
        parse::Value::Lit(lit) => Node::Lit(lit),
        parse::Value::Field(path) => Node::Field(lower.read(&path)?),
    })
}