grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/expr/names.rs
// Purpose:   The field paths a CEL expression reads and the functions it calls
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`names`]: the field paths and calls in any CEL text cel's lexer reads,
//! including forms [`super::Program`] refuses.

use std::ops::Range;

use super::lex::{self, Mode, Tok, Token};
use super::parse::{RESERVED, Refusal};
use crate::path::Path;

/// Methods whose first argument names a variable bound inside the call.
const BINDERS: &[&str] = &[
    "all",
    "exists",
    "exists_one",
    "existsOne",
    "map",
    "filter",
    "transformList",
    "transformMap",
    "transformMapEntry",
];

/// What a CEL expression reads and calls.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Names<'a> {
    /// Each field path read, once, in the order first read. A method's
    /// receiver counts, so `msg.contains("x")` reads `msg`.
    pub fields: Vec<Path>,
    /// Each call in text order, repeats included.
    pub calls: Vec<Call<'a>>,
}

/// A function or method call.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Call<'a> {
    /// The name called, such as `size` or `matches`.
    pub name: &'a str,
    /// Byte range of the name in the expression.
    pub span: Range<usize>,
    /// Called on a value, `x.name(...)`, rather than as `name(...)`.
    pub method: bool,
}

/// The field paths `text` reads and the functions and methods it calls.
///
/// They're read from its tokens alone, so a form [`super::Program`] refuses
/// reads as well. Literals and comments hold no names. A variable a
/// comprehension binds, the `t` of `tags.exists(t, t == "x")`, is no field,
/// and neither is a member of a call's result.
///
/// ```
/// use grippo::expr::names;
///
/// let n = names(r#"has(a.b) && msg.matches("^x") && size(tags["k"]) > 1"#).unwrap();
/// let fields: Vec<String> = n.fields.iter().map(ToString::to_string).collect();
/// assert_eq!(fields, ["a.b", "msg", "tags.k"]);
/// let calls: Vec<&str> = n.calls.iter().map(|c| c.name).collect();
/// assert_eq!(calls, ["has", "matches", "size"]);
/// ```
///
/// Text cel's lexer rejects is still read: a one-line literal ends at its
/// line break, an unclosed `"""` is an empty literal then a new one, and a
/// lone backtick is one byte, as cel 0.14.5 reads them.
///
/// # Errors
///
/// None: any text reads. The `Result` is kept for a later refusal.
pub fn names(text: &str) -> Result<Names<'_>, Refusal> {
    let tokens = lex::tokens_with(text, Mode::Lenient).map_err(|e| Refusal {
        span: e.span,
        why: e.why,
    })?;
    let mut out = Names {
        fields: Vec::new(),
        calls: Vec::new(),
    };
    // Each bound variable, with the bracket depth inside its call.
    let mut bound: Vec<(&str, usize)> = Vec::new();
    let mut depth = 0;
    let mut i = 0;
    while let Some(token) = tokens.get(i) {
        match &token.tok {
            Tok::LParen => depth += 1,
            Tok::RParen => {
                bound.retain(|&(_, d)| d != depth);
                depth = depth.saturating_sub(1);
            }
            Tok::Ident(w) if !RESERVED.contains(w) => {
                let method = i > 0 && tokens[i - 1].tok == Tok::Dot;
                if is_tok(&tokens, i + 1, &Tok::LParen) {
                    out.calls.push(Call {
                        name: w,
                        span: token.span.clone(),
                        method,
                    });
                    if method
                        && BINDERS.contains(w)
                        && let Some(Tok::Ident(v)) = tokens.get(i + 2).map(|t| &t.tok)
                        && is_tok(&tokens, i + 3, &Tok::Comma)
                    {
                        bound.push((v, depth + 1));
                    }
                } else if !method {
                    i = field(&tokens, i, &bound, &mut out.fields);
                    continue;
                }
            }
            _ => {}
        }
        i += 1;
    }
    Ok(out)
}

fn is_tok(tokens: &[Token<'_>], i: usize, tok: &Tok<'_>) -> bool {
    tokens.get(i).is_some_and(|t| t.tok == *tok)
}

/// Reads the field path whose root is the identifier at `i`, as the subset
/// parser reads one, and adds it unless its root is bound. Returns the index
/// after the path: a method name that ends it is read next, as a call.
fn field(tokens: &[Token<'_>], i: usize, bound: &[(&str, usize)], fields: &mut Vec<Path>) -> usize {
    let tok = |j: usize| tokens.get(j).map(|t| &t.tok);
    let Some(Tok::Ident(root)) = tok(i) else {
        return i + 1;
    };
    let mut keys: Vec<String> = vec![(*root).to_owned()];
    let mut j = i + 1;
    loop {
        match (tok(j), tok(j + 1), tok(j + 2)) {
            (Some(Tok::Dot), Some(Tok::Ident(_)), Some(Tok::LParen)) => break,
            (Some(Tok::Dot), Some(Tok::Ident(w)), _) if !RESERVED.contains(w) => {
                keys.push((*w).to_owned());
                j += 2;
            }
            (Some(Tok::LBracket), Some(Tok::Str(s)), Some(Tok::RBracket)) => {
                keys.push(s.to_string());
                j += 3;
            }
            _ => break,
        }
    }
    if !bound.iter().any(|&(v, _)| v == *root)
        && let Ok(path) = Path::from_keys(keys)
        && !fields.contains(&path)
    {
        fields.push(path);
    }
    j
}

#[cfg(test)]
mod tests {
    use super::*;

    type Read<'a> = (Vec<String>, Vec<(&'a str, bool)>);

    fn read(text: &str) -> Read<'_> {
        let n = names(text).unwrap();
        let fields = n.fields.iter().map(ToString::to_string).collect();
        let calls = n.calls.iter().map(|c| (c.name, c.method)).collect();
        (fields, calls)
    }

    #[test]
    fn fields_and_calls_read_from_tokens() {
        let rows: &[(&str, &[&str], &[(&str, bool)])] = &[
            (
                r#"tags == owner && source != "internal""#,
                &["tags", "owner", "source"],
                &[],
            ),
            (r#"'"' == host || port > 1"#, &["host", "port"], &[]),
            (
                r#"r"severity" == name && b'x' != tag"#,
                &["name", "tag"],
                &[],
            ),
            (
                "level > 1 // and source\n || other",
                &["level", "other"],
                &[],
            ),
            (
                r#"msg.contains("x") && a.b.startsWith("y")"#,
                &["msg", "a.b"],
                &[("contains", true), ("startsWith", true)],
            ),
            (
                "has(a.b) && size(c) > 1",
                &["a.b", "c"],
                &[("has", false), ("size", false)],
            ),
            (
                r#"labels["app.kind"] == "x""#,
                &[r#"labels["app.kind"]"#],
                &[],
            ),
            (
                r#"tags.exists(t, t == "x") && t > 1"#,
                &["tags", "t"],
                &[("exists", true)],
            ),
            ("xs.map(v, v.n + k)", &["xs", "k"], &[("map", true)]),
            ("f(x).y == z", &["x", "z"], &[("f", false)]),
            ("x in [1, 2] && true != null", &["x"], &[]),
            ("x ? `a.b` : c", &["x", r#"["a.b"]"#, "c"], &[]),
            ("a == a && a.b == a", &["a", "a.b"], &[]),
        ];
        for &(text, fields, calls) in rows {
            let (got_fields, got_calls) = read(text);
            assert_eq!(got_fields, fields, "{text}");
            assert_eq!(got_calls, calls, "{text}");
        }
    }

    /// A call written past a literal or with a gap before its bracket is
    /// found, and a name inside a literal or comment is not.
    #[test]
    fn calls_past_literals_and_gaps() {
        for text in [
            "x.matches (\"a\")",
            "x.matches\t(\"a\")",
            "x.matches // note\n(\"a\")",
            r#"r"\" == "x" || x.matches("a")"#,
            r#"'"' == x || y.matches("a")"#,
            r#""""a"b""" == x || [1].map(v, v) == [1]"#,
        ] {
            let calls = read(text).1;
            assert!(
                calls.contains(&("matches", true)) || calls.contains(&("map", true)),
                "{text}"
            );
        }
        for text in [
            r#"r"x.matches(" == y || z > 1"#,
            "'''map(v, v)''' == y || z > 1",
            "x > 1 // y.matches(\"a\")",
        ] {
            assert_eq!(read(text).1, [], "{text}");
        }
    }

    /// Text cel's lexer rejects reads as cel 0.14.5 reads it, so a call past
    /// a broken literal is still found.
    #[test]
    fn text_the_lexer_rejects_still_reads_as_cel_reads_it() {
        let rows: &[(&str, &[&str], &[(&str, bool)])] = &[
            // A vertical tab or form feed before the bracket is whitespace.
            ("x.matches\x0b(\"a\")", &["x"], &[("matches", true)]),
            ("x.matches\x0c(\"a\")", &["x"], &[("matches", true)]),
            // An unclosed triple quote is an empty literal, then a new one.
            (r#""""a" || x.matches("a")"#, &["x"], &[("matches", true)]),
            // A prefix opens a literal only as a whole name before the quote.
            (r#"rb"\" == "x" || x.matches("a")"#, &["rb", "x", "a"], &[]),
            (r#"xr"\" == "x" || x.matches("a")"#, &["xr", "x", "a"], &[]),
            (r#"r "\" == "x" || x.matches("a")"#, &["r", "x", "a"], &[]),
            (
                r#"br"\" == "x" || x.matches("a")"#,
                &["x"],
                &[("matches", true)],
            ),
            // A one-line literal ends at its line break.
            ("\"abc\nx.matches(\"a\")", &["x"], &[("matches", true)]),
            ("x == \"open", &["x"], &[]),
            // A backtick name is opaque, and a lone backtick one byte.
            (
                "x.`a//b` == 1 || x.matches(\"a\")",
                &["x.a//b", "x"],
                &[("matches", true)],
            ),
            ("` x.matches(\"a\")", &["x"], &[("matches", true)]),
        ];
        for &(text, fields, calls) in rows {
            let (got_fields, got_calls) = read(text);
            assert_eq!(got_fields, fields, "{text:?}");
            assert_eq!(got_calls, calls, "{text:?}");
        }
    }
}