grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/expr/parse.rs
// Purpose:   The lowerable CEL subset parsed to a tree, or why it can't be
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The CEL subset grippo lowers, parsed to [`Ast`]. Text outside the subset
//! is a [`Refusal`] naming the first form that left it.

use std::ops::Range;

use super::lex::{self, Tok, Token};

/// A field path, one segment a name: `a.b["c-d"]` is `["a", "b", "c-d"]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct Path(pub(super) Vec<String>);

/// A literal operand.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Lit {
    Str(String),
    Int(i64),
    Uint(u64),
    Double(f64),
    Bool(bool),
    Null,
}

/// A comparison, written field first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Cmp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
}

impl Cmp {
    /// The comparison with its operands swapped: `3 < f` is `f > 3`.
    const fn flipped(self) -> Self {
        match self {
            Self::Eq => Self::Eq,
            Self::Ne => Self::Ne,
            Self::Lt => Self::Gt,
            Self::Le => Self::Ge,
            Self::Gt => Self::Lt,
            Self::Ge => Self::Le,
        }
    }
}

/// A string method taking one string literal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Method {
    StartsWith,
    EndsWith,
    Contains,
    Matches,
}

/// A function cel applies to a field before a comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Func {
    /// `size(x)` or `x.size()`.
    Size,
    /// `int(x)`.
    Int,
}

/// The parsed subset.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Ast {
    Or(Vec<Self>),
    And(Vec<Self>),
    Not(Box<Self>),
    Const(bool),
    /// The path, and the span of the `has` token for a refusal.
    Has(Path, Range<usize>),
    Cmp(Path, Cmp, Lit),
    /// `size()` or `int()` of a field, compared with a literal.
    Call(Func, Path, Cmp, Lit),
    Method(Path, Method, String),
    In(Path, Vec<Lit>),
}

/// The first form outside the subset, or text cel itself rejects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    /// Byte range of the form in the expression text.
    pub span: Range<usize>,
    /// What the form is.
    pub why: &'static str,
}

impl std::fmt::Display for Refusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} at bytes {}..{}",
            self.why, self.span.start, self.span.end
        )
    }
}

impl std::error::Error for Refusal {}

/// CEL's reserved words, which can't name a field.
pub(super) const RESERVED: &[&str] = &[
    "as",
    "break",
    "const",
    "continue",
    "else",
    "false",
    "for",
    "function",
    "if",
    "import",
    "in",
    "let",
    "loop",
    "package",
    "namespace",
    "null",
    "return",
    "true",
    "var",
    "void",
    "while",
];

/// Parses `text`, the whole of it, as the subset.
pub(super) fn parse(text: &str) -> Result<Ast, Refusal> {
    let tokens = lex::tokens(text).map_err(|e| Refusal {
        span: e.span,
        why: e.why,
    })?;
    let mut p = Parser {
        tokens: &tokens,
        at: 0,
        len: text.len(),
    };
    let ast = p.or()?;
    p.peek().map_or(Ok(ast), |t| {
        Err(refuse(t.span.clone(), "a form outside the lowered subset"))
    })
}

/// A value expression: a predicate, a ternary, a sum, a literal or a field.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Value {
    Pred(Ast),
    Cond(Ast, Box<Self>, Box<Self>),
    Add(Vec<Self>),
    Lit(Lit),
    Field(Path),
}

/// Parses `text`, the whole of it, as a value expression.
pub(super) fn parse_value(text: &str) -> Result<Value, Refusal> {
    let tokens = lex::tokens(text).map_err(|e| Refusal {
        span: e.span,
        why: e.why,
    })?;
    let mut p = Parser {
        tokens: &tokens,
        at: 0,
        len: text.len(),
    };
    let v = p.value()?;
    p.peek().map_or(Ok(v), |t| {
        Err(refuse(t.span.clone(), "a form outside the lowered subset"))
    })
}

struct Parser<'t, 'a> {
    tokens: &'t [Token<'a>],
    at: usize,
    len: usize,
}

impl<'a> Parser<'_, 'a> {
    fn peek(&self) -> Option<&Token<'a>> {
        self.tokens.get(self.at)
    }

    fn peek_tok(&self, ahead: usize) -> Option<&Tok<'a>> {
        self.tokens.get(self.at + ahead).map(|t| &t.tok)
    }

    fn here(&self) -> Range<usize> {
        self.peek().map_or(self.len..self.len, |t| t.span.clone())
    }

    fn eat(&mut self, tok: &Tok<'_>) -> bool {
        if self.peek_tok(0) == Some(tok) {
            self.at += 1;
            true
        } else {
            false
        }
    }

    fn expect(&mut self, tok: &Tok<'_>, why: &'static str) -> Result<(), Refusal> {
        if self.eat(tok) {
            Ok(())
        } else {
            Err(refuse(self.here(), why))
        }
    }

    /// A ternary when a predicate is followed by `?`, a predicate alone, or a
    /// sum of fields and literals.
    fn value(&mut self) -> Result<Value, Refusal> {
        let start = self.at;
        if let Ok(cond) = self.or() {
            if self.eat(&Tok::Question) {
                let then = self.value()?;
                self.expect(&Tok::Colon, "a ternary with no `:`")?;
                let other = self.value()?;
                return Ok(Value::Cond(cond, Box::new(then), Box::new(other)));
            }
            if matches!(self.peek_tok(0), None | Some(Tok::Colon | Tok::RParen)) {
                return Ok(Value::Pred(cond));
            }
        }
        self.at = start;
        let mut terms = vec![self.atom()?];
        while self.eat(&Tok::Plus) {
            terms.push(self.atom()?);
        }
        Ok(if terms.len() == 1 {
            terms.remove(0)
        } else {
            Value::Add(terms)
        })
    }

    fn atom(&mut self) -> Result<Value, Refusal> {
        if self.eat(&Tok::LParen) {
            let inner = self.value()?;
            self.expect(&Tok::RParen, "an unclosed parenthesis")?;
            return Ok(inner);
        }
        match self.peek_tok(0) {
            Some(Tok::Ident(w)) if !RESERVED.contains(w) => {
                let path = self.path()?;
                if self.peek_tok(0) == Some(&Tok::Dot) {
                    return Err(refuse(
                        self.here(),
                        "a method in a value outside the subset",
                    ));
                }
                Ok(Value::Field(path))
            }
            _ => self.lit().map(Value::Lit),
        }
    }

    fn or(&mut self) -> Result<Ast, Refusal> {
        let mut terms = vec![self.and()?];
        while self.eat(&Tok::OrOr) {
            terms.push(self.and()?);
        }
        Ok(if terms.len() == 1 {
            terms.remove(0)
        } else {
            Ast::Or(terms)
        })
    }

    fn and(&mut self) -> Result<Ast, Refusal> {
        let mut terms = vec![self.unary()?];
        while self.eat(&Tok::AndAnd) {
            terms.push(self.unary()?);
        }
        Ok(if terms.len() == 1 {
            terms.remove(0)
        } else {
            Ast::And(terms)
        })
    }

    fn unary(&mut self) -> Result<Ast, Refusal> {
        if self.eat(&Tok::Not) {
            return Ok(Ast::Not(Box::new(self.unary()?)));
        }
        if self.eat(&Tok::LParen) {
            let inner = self.or()?;
            self.expect(&Tok::RParen, "an unclosed parenthesis")?;
            return Ok(inner);
        }
        self.leaf()
    }

    fn leaf(&mut self) -> Result<Ast, Refusal> {
        let start = self.here();
        match self.peek_tok(0) {
            Some(Tok::Ident("has")) if self.peek_tok(1) == Some(&Tok::LParen) => {
                self.at += 2;
                let path = self.path()?;
                let named_last = matches!(self.tokens[self.at - 1].tok, Tok::Ident(_));
                let before = &self.tokens[self.at - 2].tok;
                // A bare name is a root field, lowered only with `Options::root_presence`.
                let bare = path.0.len() == 1 && *before == Tok::LParen;
                if !named_last || !(bare || *before == Tok::Dot) {
                    return Err(refuse(start, "has() on an index, which cel refuses"));
                }
                self.expect(&Tok::RParen, "has() takes one field path")?;
                return Ok(Ast::Has(path, start));
            }
            Some(Tok::Ident("true" | "false")) if !matches!(self.peek_tok(1), Some(t) if cmp_of(t).is_some()) =>
            {
                let v = self.peek_tok(0) == Some(&Tok::Ident("true"));
                self.at += 1;
                return Ok(Ast::Const(v));
            }
            Some(Tok::Ident(w)) if !RESERVED.contains(w) => {}
            _ => {
                let lit = self.lit()?;
                let Some(cmp) = self.peek_tok(0).and_then(cmp_of) else {
                    return Err(refuse(start, "a literal with no comparison"));
                };
                self.at += 1;
                let (func, path) = self.operand()?;
                return Ok(match func {
                    Some(func) => Ast::Call(func, path, cmp.flipped(), lit),
                    None => Ast::Cmp(path, cmp.flipped(), lit),
                });
            }
        }
        let (func, path) = self.operand()?;
        if let Some(func) = func {
            let Some(cmp) = self.peek_tok(0).and_then(cmp_of) else {
                return Err(refuse(start, "size() or int() with no comparison"));
            };
            self.at += 1;
            return Ok(Ast::Call(func, path, cmp, self.lit()?));
        }
        if self.peek_tok(0) == Some(&Tok::Dot) {
            return self.method(path);
        }
        if self.peek_tok(0) == Some(&Tok::Ident("in")) {
            self.at += 1;
            self.expect(&Tok::LBracket, "`in` over anything but a list literal")?;
            let mut lits = Vec::new();
            if !self.eat(&Tok::RBracket) {
                loop {
                    lits.push(self.lit()?);
                    if self.eat(&Tok::RBracket) {
                        break;
                    }
                    self.expect(&Tok::Comma, "a malformed list literal")?;
                    if self.eat(&Tok::RBracket) {
                        break;
                    }
                }
            }
            return Ok(Ast::In(path, lits));
        }
        let Some(cmp) = self.peek_tok(0).and_then(cmp_of) else {
            if self.peek_tok(0) == Some(&Tok::LParen) {
                return Err(refuse(start, "a function call outside the subset"));
            }
            let span = if self.peek().is_some() {
                self.here()
            } else {
                start
            };
            return Err(refuse(
                span,
                "a bare field, or a field in a form outside the subset",
            ));
        };
        self.at += 1;
        if matches!(self.peek_tok(0), Some(Tok::Ident(w)) if !matches!(*w, "true" | "false" | "null"))
        {
            return Err(refuse(self.here(), "a comparison between two fields"));
        }
        let lit = self.lit()?;
        Ok(Ast::Cmp(path, cmp, lit))
    }

    fn method(&mut self, path: Path) -> Result<Ast, Refusal> {
        self.at += 1;
        let span = self.here();
        let method = match self.peek_tok(0) {
            Some(Tok::Ident("startsWith")) => Method::StartsWith,
            Some(Tok::Ident("endsWith")) => Method::EndsWith,
            Some(Tok::Ident("contains")) => Method::Contains,
            Some(Tok::Ident("matches")) => Method::Matches,
            _ => return Err(refuse(span, "a method outside the lowered subset")),
        };
        self.at += 1;
        self.expect(&Tok::LParen, "a method name with no call")?;
        let Some(Tok::Str(arg)) = self.peek_tok(0).cloned() else {
            return Err(refuse(
                self.here(),
                "a string method takes one string literal",
            ));
        };
        self.at += 1;
        self.expect(&Tok::RParen, "a string method takes one string literal")?;
        Ok(Ast::Method(path, method, arg.into_owned()))
    }

    /// A field, `size(field)`, `field.size()` or `int(field)`.
    fn operand(&mut self) -> Result<(Option<Func>, Path), Refusal> {
        let func = match (self.peek_tok(0), self.peek_tok(1)) {
            (Some(Tok::Ident("size")), Some(Tok::LParen)) => Some(Func::Size),
            (Some(Tok::Ident("int")), Some(Tok::LParen)) => Some(Func::Int),
            _ => None,
        };
        if func.is_some() {
            self.at += 2;
            let path = self.path()?;
            self.expect(&Tok::RParen, "size() and int() take one field path")?;
            return Ok((func, path));
        }
        let path = self.path()?;
        let size = [Tok::Dot, Tok::Ident("size"), Tok::LParen, Tok::RParen];
        if (0..size.len()).all(|i| self.peek_tok(i) == Some(&size[i])) {
            self.at += size.len();
            return Ok((Some(Func::Size), path));
        }
        Ok((None, path))
    }

    fn path(&mut self) -> Result<Path, Refusal> {
        let mut segs = Vec::new();
        match self.peek_tok(0) {
            Some(Tok::Ident(w)) if !RESERVED.contains(w) => {
                segs.push((*w).to_owned());
                self.at += 1;
            }
            _ => return Err(refuse(self.here(), "a field path")),
        }
        loop {
            match (self.peek_tok(0), self.peek_tok(1), self.peek_tok(2)) {
                (Some(Tok::Dot), Some(Tok::Ident(_)), Some(Tok::LParen)) => break,
                (Some(Tok::Dot), Some(Tok::Ident(w)), _) if !RESERVED.contains(w) => {
                    segs.push((*w).to_owned());
                    self.at += 2;
                }
                (Some(Tok::LBracket), Some(Tok::Str(s)), Some(Tok::RBracket)) => {
                    segs.push(s.to_string());
                    self.at += 3;
                }
                (Some(Tok::Dot | Tok::LBracket), _, _) => {
                    return Err(refuse(self.here(), "a path step outside the subset"));
                }
                _ => break,
            }
        }
        Ok(Path(segs))
    }

    fn lit(&mut self) -> Result<Lit, Refusal> {
        let span = self.here();
        let negative = self.eat(&Tok::Minus);
        let lit = match (self.peek_tok(0).cloned(), negative) {
            (Some(Tok::Int(n)), _) => Lit::Int(if negative { -n } else { n }),
            (Some(Tok::Double(d)), _) => Lit::Double(if negative { -d } else { d }),
            (Some(Tok::Uint(u)), false) => Lit::Uint(u),
            (Some(Tok::Str(s)), false) => Lit::Str(s.into_owned()),
            (Some(Tok::Ident("true")), false) => Lit::Bool(true),
            (Some(Tok::Ident("false")), false) => Lit::Bool(false),
            (Some(Tok::Ident("null")), false) => Lit::Null,
            (Some(Tok::Bytes), false) => {
                return Err(refuse(span, "a bytes literal"));
            }
            _ => return Err(refuse(span, "a literal")),
        };
        self.at += 1;
        Ok(lit)
    }
}

const fn cmp_of(tok: &Tok<'_>) -> Option<Cmp> {
    Some(match tok {
        Tok::EqEq => Cmp::Eq,
        Tok::Ne => Cmp::Ne,
        Tok::Lt => Cmp::Lt,
        Tok::Le => Cmp::Le,
        Tok::Gt => Cmp::Gt,
        Tok::Ge => Cmp::Ge,
        _ => return None,
    })
}

const fn refuse(span: Range<usize>, why: &'static str) -> Refusal {
    Refusal { span, why }
}