grippo 0.1.2

Parse, match and scrub data at scale.
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, object_keys};

use super::parse::{self, Lit, Refusal};
use super::program::{FRAME, 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,
}

#[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`.
    ///
    /// # Errors
    ///
    /// A [`Refusal`] naming the form, so the caller can run its interpreter.
    pub fn compile_with(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,
        })
    }

    /// 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> {
        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 0.14.5'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))))
        }
        // cel appends anything iterable to a list, and a map iterates its keys.
        (Value::Json(x), Value::Json(y)) if x.starts_with('[') && y.starts_with('{') => {
            Ok(Value::Json(Cow::Owned(concat_arrays(&x, &map_keys(&y)?))))
        }
        _ => Err(ErrorKind::TypeMismatch),
    }
}

/// A JSON object's keys as a JSON array.
fn map_keys(obj: &str) -> Result<String, ErrorKind> {
    let keys = object_keys(obj).map_err(read_error)?;
    serde_json::to_string(&keys).map_err(|_| ErrorKind::Malformed)
}

/// 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)?),
    })
}