grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Project:   grippo
// File:      src/expr/fallback.rs
// Purpose:   CEL text outside the lowered subset run on cel-rust over a record
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The `expr-cel` fallback: text the lowering refuses, compiled and run by
//! cel-rust, with each root field the text reads bound from the record.

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::slice;
use std::sync::{Arc, OnceLock};

use cel::ExecutionError;
use cel::common::ast::{EntryExpr, Expr, IdedEntryExpr, IdedExpr, LiteralValue, operators};
use cel::objects::{Key, Map};
use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};

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

use super::names::names;
use super::parse::Refusal;
use super::program::{Options, Outcome};
use super::value::{ErrorKind, read_error};
use super::valued::Value;

/// The standard environment every fallback program runs in, built once.
fn env() -> &'static Arc<cel::Env> {
    static ENV: OnceLock<Arc<cel::Env>> = OnceLock::new();
    ENV.get_or_init(|| Arc::new(cel::Env::stdlib()))
}

/// CEL text cel-rust compiled, and what it reads from a record.
#[derive(Debug)]
pub(super) struct CelProgram {
    program: cel::Program,
    /// Each root field the text reads, and how much of it.
    roots: Vec<(String, Wanted)>,
    /// Root keys holding a dot that cel reads a qualified name as, bound
    /// under `Options::dotted_root_keys` when the record has them.
    dotted: Vec<String>,
    text: Box<str>,
}

/// How much of a value the text reads: all of it, or some of its keys.
#[derive(Debug, Default)]
struct Wanted {
    whole: bool,
    keys: Vec<(String, Self)>,
}

impl Wanted {
    fn add(&mut self, path: &[&str]) {
        if self.whole {
            return;
        }
        let Some((first, rest)) = path.split_first() else {
            self.whole = true;
            self.keys.clear();
            return;
        };
        let at = self
            .keys
            .iter()
            .position(|(k, _)| k == first)
            .unwrap_or_else(|| {
                self.keys.push(((*first).to_owned(), Self::default()));
                self.keys.len() - 1
            });
        self.keys[at].1.add(rest);
    }
}

impl CelProgram {
    /// Compiles `text` on cel-rust.
    ///
    /// # Errors
    ///
    /// A [`Refusal`] for text cel doesn't compile, or for a `matches()` call
    /// without `Options::allow_regex`.
    pub(super) fn compile(text: &str, options: &Options) -> Result<Self, Refusal> {
        let program = cel::Program::compile(text).map_err(|e| Refusal {
            span: e
                .errors
                .first()
                .map_or(0, |e| offset(text, e.pos))
                .min(text.len())..text.len(),
            why: "text cel doesn't compile",
        })?;
        let mut reads = Scan {
            roots: Vec::new(),
            dotted: Vec::new(),
            bound: Vec::new(),
            regex: false,
            dotted_root_keys: options.dotted_root_keys,
        };
        reads.expr(program.expression());
        if reads.regex && !options.allow_regex {
            let span = names(text)
                .ok()
                .and_then(|n| n.calls.into_iter().find(|c| c.name == "matches"))
                .map_or(0..text.len(), |c| c.span);
            return Err(Refusal {
                span,
                why: "matches(), which runs only with Options::allow_regex",
            });
        }
        let Scan { roots, dotted, .. } = reads;
        Ok(Self {
            program,
            roots,
            dotted,
            text: text.into(),
        })
    }

    /// The text's result on `record` as a filter: a value that isn't a bool
    /// is a type mismatch.
    pub(super) fn outcome<'a, R: Record<'a>>(&self, record: R) -> Outcome {
        match self.run(record) {
            Ok(cel::Value::Bool(true)) => Outcome::True,
            Ok(cel::Value::Bool(false)) => Outcome::False,
            Ok(_) => Outcome::Error(ErrorKind::TypeMismatch),
            Err(kind) => Outcome::Error(kind),
        }
    }

    /// The text's value on `record`. A list or map is compact JSON with its
    /// keys sorted.
    pub(super) fn value<'a, R: Record<'a>>(&self, record: R) -> Result<Value<'a>, ErrorKind> {
        Ok(match self.run(record)? {
            cel::Value::String(s) => Value::Str(Cow::Owned(Arc::unwrap_or_clone(s))),
            cel::Value::Int(n) => Value::Int(n),
            cel::Value::UInt(n) => Value::Uint(n),
            cel::Value::Float(n) => Value::Double(n),
            cel::Value::Bool(b) => Value::Bool(b),
            cel::Value::Null => Value::Null,
            v @ (cel::Value::List(_) | cel::Value::Map(_)) => {
                let mut out = String::new();
                write_json(&v, &mut out)?;
                Value::Json(Cow::Owned(out))
            }
            _ => return Err(ErrorKind::Other),
        })
    }

    fn run<'a, R: Record<'a>>(&self, record: R) -> Result<cel::Value, ErrorKind> {
        // A root scope, since cel looks an absolute name such as `.a` up there only.
        let mut ctx = cel::Context::with_env(Arc::clone(env()));
        for name in &self.dotted {
            if let Some(at) = root(record, name)? {
                ctx.add_variable_from_value(name.as_str(), whole(record, at)?);
            }
        }
        for (name, wanted) in &self.roots {
            if let Some(at) = root(record, name)? {
                ctx.add_variable_from_value(name.as_str(), part(record, at, wanted)?);
            }
        }
        self.program.execute(&ctx).map_err(|e| self.kind(&e))
    }

    /// The [`ErrorKind`] the lowering gives for the same failure.
    fn kind(&self, error: &ExecutionError) -> ErrorKind {
        match error {
            ExecutionError::UndeclaredReference(name) => {
                let name = name.strip_prefix('.').unwrap_or(name);
                if self.roots.iter().any(|(root, _)| root == name) {
                    ErrorKind::MissingRoot
                } else {
                    ErrorKind::Other
                }
            }
            ExecutionError::NoSuchKey(_) => ErrorKind::MissingField,
            // A field selected, or a string key indexed, below a value that isn't a map.
            ExecutionError::NoSuchOverload(o)
                if o.function() == "_._"
                    || (o.function() == "_[_]"
                        && o.argument_types().get(1).is_some_and(|t| t == "string")) =>
            {
                ErrorKind::MissingField
            }
            ExecutionError::Overflow(..) => ErrorKind::Overflow,
            ExecutionError::FunctionError { message, .. } if message.ends_with("overflow") => {
                ErrorKind::Overflow
            }
            ExecutionError::FunctionError { function, message }
                if matches!(function.as_str(), "int" | "uint" | "double")
                    && message.contains("parse error") =>
            {
                ErrorKind::Conversion
            }
            ExecutionError::NoSuchOverload(_)
            | ExecutionError::UnsupportedTargetType { .. }
            | ExecutionError::NotSupportedAsMethod { .. }
            | ExecutionError::UnexpectedType { .. }
            | ExecutionError::ValuesNotComparable(..)
            | ExecutionError::UnsupportedBinaryOperator(..)
            | ExecutionError::UnsupportedIndex(..)
            | ExecutionError::UnsupportedKeyType(_)
            | ExecutionError::InvalidArgumentCount { .. }
            | ExecutionError::MissingArgumentOrTarget => ErrorKind::TypeMismatch,
            _ => ErrorKind::Other,
        }
    }
}

impl fmt::Display for CelProgram {
    /// The text cel runs, as `cel(...)`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "cel({})", self.text)
    }
}

/// The byte offset of cel's 1-based line and column, columns in characters.
fn offset(text: &str, (line, column): (isize, isize)) -> usize {
    let (Ok(line), Ok(column)) = (usize::try_from(line), usize::try_from(column)) else {
        return 0;
    };
    let start: usize = text
        .split_inclusive('\n')
        .take(line.saturating_sub(1))
        .map(str::len)
        .sum();
    let rest = &text[start.min(text.len())..];
    start
        + rest
            .char_indices()
            .nth(column.saturating_sub(1))
            .map_or(rest.len(), |(i, _)| i)
}

/// Gathers the roots a compiled text reads, scoped as cel's own reference
/// walk scopes them.
struct Scan<'e> {
    roots: Vec<(String, Wanted)>,
    dotted: Vec<String>,
    /// The names the enclosing comprehensions bind.
    bound: Vec<&'e str>,
    regex: bool,
    dotted_root_keys: bool,
}

impl<'e> Scan<'e> {
    fn expr(&mut self, e: &'e IdedExpr) {
        if let Some((name, keys, named)) = chain(e) {
            self.path(name, &keys, named);
            return;
        }
        match &e.expr {
            Expr::Call(call) => {
                self.regex |= call.func_name == "matches";
                if let Some(target) = &call.target {
                    self.expr(target);
                }
                for arg in &call.args {
                    self.expr(arg);
                }
            }
            Expr::Comprehension(c) => {
                self.expr(&c.iter_range);
                self.expr(&c.accu_init);
                let outer = self.bound.len();
                self.bound.push(&c.accu_var);
                self.expr(&c.result);
                self.bound.push(&c.iter_var);
                if let Some(second) = &c.iter_var2 {
                    self.bound.push(second);
                }
                self.expr(&c.loop_cond);
                self.expr(&c.loop_step);
                self.bound.truncate(outer);
            }
            Expr::List(list) => {
                for item in &list.elements {
                    self.expr(item);
                }
            }
            Expr::Map(map) => self.entries(&map.entries),
            Expr::Struct(s) => self.entries(&s.entries),
            Expr::Select(select) => self.expr(&select.operand),
            Expr::Ident(_) | Expr::Literal(_) | Expr::Unspecified => {}
        }
    }

    fn entries(&mut self, entries: &'e [IdedEntryExpr]) {
        for entry in entries {
            match &entry.expr {
                EntryExpr::StructField(field) => self.expr(&field.value),
                EntryExpr::MapEntry(pair) => {
                    self.expr(&pair.key);
                    self.expr(&pair.value);
                }
            }
        }
    }

    /// Records the read of `keys` below the identifier `name`, of which the
    /// first `named` segments, the name included, spell a qualified name.
    fn path(&mut self, name: &'e str, keys: &[&str], named: usize) {
        // `@` can't be written in source, and an absolute name skips the
        // comprehensions' scopes.
        if name.starts_with('@') || self.bound.contains(&name) {
            return;
        }
        let root = name.strip_prefix('.').unwrap_or(name);
        let at = self
            .roots
            .iter()
            .position(|(r, _)| r == root)
            .unwrap_or_else(|| {
                self.roots.push((root.to_owned(), Wanted::default()));
                self.roots.len() - 1
            });
        self.roots[at].1.add(keys);
        if self.dotted_root_keys {
            let mut joined = root.to_owned();
            for key in keys.iter().take(named.saturating_sub(1)) {
                joined.push('.');
                joined.push_str(key);
                if !self.dotted.contains(&joined) {
                    self.dotted.push(joined.clone());
                }
            }
        }
    }
}

/// An identifier with the fields selected and string keys indexed below it:
/// the identifier, the keys, and how many leading segments are names joined
/// by dots, which cel also reads as one qualified name.
fn chain(e: &IdedExpr) -> Option<(&str, Vec<&str>, usize)> {
    let mut steps: Vec<(&str, bool)> = Vec::new();
    let mut at = e;
    loop {
        match &at.expr {
            Expr::Ident(name) => {
                steps.reverse();
                let named = 1 + steps.iter().take_while(|&&(_, n)| n).count();
                return Some((name, steps.into_iter().map(|(k, _)| k).collect(), named));
            }
            // `has(a.b)` tests `b` on the name `a`, so `b` isn't part of it.
            Expr::Select(s) => {
                steps.push((&s.field, !s.test));
                at = &s.operand;
            }
            Expr::Call(c) if c.func_name == operators::INDEX && c.target.is_none() => {
                let [operand, key] = c.args.as_slice() else {
                    return None;
                };
                let Expr::Literal(LiteralValue::String(key)) = &key.expr else {
                    return None;
                };
                steps.push((key.inner(), false));
                at = operand;
            }
            _ => return None,
        }
    }
}

/// The record's root field `name`, or `None` when it has none.
fn root<'a, R: Record<'a>>(record: R, name: &str) -> Result<Option<R::At>, ErrorKind> {
    match record.find(slice::from_ref(&name)) {
        Ok(at) => Ok(Some(at)),
        Err(Miss::Malformed) => Err(ErrorKind::Malformed),
        Err(_) => Ok(None),
    }
}

/// The value at `at`, holding only the keys `wanted` names where it's a map.
fn part<'a, R: Record<'a>>(record: R, at: R::At, wanted: &Wanted) -> Result<cel::Value, ErrorKind> {
    if wanted.whole || !matches!(record.typed(at).map_err(read_error)?, Typed::Map) {
        return whole(record, at);
    }
    let mut map: HashMap<Key, cel::Value> = HashMap::with_capacity(wanted.keys.len());
    for (key, below) in &wanted.keys {
        match record.find_below(at, slice::from_ref(key)) {
            Ok(child) => {
                map.insert(Key::from(key.as_str()), part(record, child, below)?);
            }
            Err(Miss::Malformed) => return Err(ErrorKind::Malformed),
            Err(_) => {}
        }
    }
    Ok(cel::Value::Map(Map { map: Arc::new(map) }))
}

/// The value at `at`, typed as grippo types it: an int, then a uint, then a
/// double.
fn whole<'a, R: Record<'a>>(record: R, at: R::At) -> Result<cel::Value, ErrorKind> {
    Ok(match record.typed(at).map_err(read_error)? {
        Typed::Str(s) => cel::Value::String(Arc::new(s.into_owned())),
        Typed::Int(n) => cel::Value::Int(n),
        Typed::Uint(n) => cel::Value::UInt(n),
        Typed::Double(n) => cel::Value::Float(n),
        Typed::Bool(b) => cel::Value::Bool(b),
        Typed::Null => cel::Value::Null,
        Typed::List | Typed::Map => {
            let text = record.text(at).map_err(read_error)?;
            let mut json = serde_json::Deserializer::from_str(&text);
            let value = Seed.deserialize(&mut json);
            value
                .and_then(|v| json.end().map(|()| v))
                .map_err(|_| ErrorKind::Malformed)?
        }
    })
}

/// JSON read straight into a cel value, numbers by grippo's rule and the
/// first of two equal keys kept, as the record's own reads keep it.
struct CelVisitor;

impl<'de> Visitor<'de> for CelVisitor {
    type Value = cel::Value;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a JSON value")
    }

    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Self::Value, E> {
        Ok(cel::Value::Bool(v))
    }

    fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
        Ok(cel::Value::Int(v))
    }

    fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
        Ok(i64::try_from(v).map_or(cel::Value::UInt(v), cel::Value::Int))
    }

    fn visit_f64<E: de::Error>(self, v: f64) -> Result<Self::Value, E> {
        Ok(cel::Value::Float(v))
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
        Ok(cel::Value::String(Arc::new(v.to_owned())))
    }

    fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
        Ok(cel::Value::String(Arc::new(v)))
    }

    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
        Ok(cel::Value::Null)
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0));
        while let Some(item) = seq.next_element_seed(Seed)? {
            items.push(item);
        }
        Ok(cel::Value::List(Arc::new(items)))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
        let mut map: HashMap<Key, cel::Value> = HashMap::new();
        while let Some(key) = access.next_key::<String>()? {
            let value = access.next_value_seed(Seed)?;
            map.entry(Key::from(key)).or_insert(value);
        }
        Ok(cel::Value::Map(Map { map: Arc::new(map) }))
    }
}

/// [`CelVisitor`] for one value.
struct Seed;

impl<'de> DeserializeSeed<'de> for Seed {
    type Value = cel::Value;

    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
        d.deserialize_any(CelVisitor)
    }
}

/// `v` as compact JSON, a map's keys sorted, or [`ErrorKind::Other`] for a
/// value JSON can't hold, two map keys that spell the same JSON key included.
fn write_json(v: &cel::Value, out: &mut String) -> Result<(), ErrorKind> {
    match v {
        cel::Value::Null => out.push_str("null"),
        cel::Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        cel::Value::Int(n) => out.push_str(&n.to_string()),
        cel::Value::UInt(n) => out.push_str(&n.to_string()),
        cel::Value::Float(n) => {
            let n = serde_json::Number::from_f64(*n).ok_or(ErrorKind::Other)?;
            out.push_str(&n.to_string());
        }
        cel::Value::String(s) => out.push_str(&quoted(s)?),
        cel::Value::List(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_json(item, out)?;
            }
            out.push(']');
        }
        cel::Value::Map(map) => {
            let mut members: Vec<(String, &cel::Value)> = map
                .map
                .iter()
                .map(|(k, v)| {
                    let key = match k {
                        Key::String(s) => s.as_str().to_owned(),
                        Key::Int(n) => n.to_string(),
                        Key::Uint(n) => n.to_string(),
                        Key::Bool(b) => b.to_string(),
                    };
                    (key, v)
                })
                .collect();
            members.sort_by(|a, b| a.0.cmp(&b.0));
            // Keys `1`, `1u`, `"1"` all spell `"1"`: one JSON member would lose the other.
            if members.windows(2).any(|pair| pair[0].0 == pair[1].0) {
                return Err(ErrorKind::Other);
            }
            out.push('{');
            for (i, (key, value)) in members.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&quoted(key)?);
                out.push(':');
                write_json(value, out)?;
            }
            out.push('}');
        }
        _ => return Err(ErrorKind::Other),
    }
    Ok(())
}

/// `s` as a JSON string.
fn quoted(s: &str) -> Result<String, ErrorKind> {
    serde_json::to_string(s).map_err(|_| ErrorKind::Other)
}