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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
// Project:   grippo
// File:      src/expr/program.rs
// Purpose:   A lowered CEL predicate and its evaluation over raw JSON
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A parsed expression lowered to field slots and leaf checks, evaluated in
//! cel's three values: true, false and error.

use std::cell::RefCell;
use std::cmp::Ordering;
use std::fmt;
use std::slice;

use memchr::memmem::Finder;

use crate::json::Slots;
use crate::record::{Json, Miss, ReadPlan, Record, Typed, object_keys};
use crate::strmatch::StrMatcher;

#[cfg(feature = "expr-cel")]
use super::fallback::CelProgram;
use super::parse::{self, Ast, Cmp, Func, Lit, Method, Path, Refusal};
use super::value::{ErrorKind, read_error};

/// The most distinct field paths, prefixes included, one program reads.
pub const MAX_FIELDS: usize = 16;

/// What an expression gives for one record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// The expression holds.
    True,
    /// The expression doesn't hold.
    False,
    /// cel would raise this error. A caller that only filters treats it as false.
    Error(ErrorKind),
}

/// How [`Program::compile_with`] lowers.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
#[allow(
    clippy::struct_excessive_bools,
    reason = "each is a separate choice a caller opts into"
)]
pub struct Options {
    /// Lower `matches()` onto strmatch. Off by default, since a regex in a
    /// filter is a policy a caller opts into.
    pub allow_regex: bool,
    /// Read `has(name)` on a bare name as "the record has this root field".
    /// Off by default, since cel refuses `has()` without a member. Lowered
    /// text only: the cel fallback refuses `has(name)` as cel does.
    pub root_presence: bool,
    /// Read `has(a.b)` as false when `a` is absent. Off by default, since cel
    /// raises an error for an absent parent. Lowered text only.
    pub missing_parent_false: bool,
    /// Read `a.b` as the root key `a.b` when the record has one, before the
    /// field `b` of `a`, as cel does. Off by default, since probing those keys
    /// costs up to 65% more instructions on a filter that reads several paths.
    /// The cel fallback honours it too, binding such a root key when the
    /// record has one.
    pub dotted_root_keys: bool,
    /// What happens to text outside the lowered subset.
    pub fallback: Fallback,
}

impl Options {
    /// The defaults, with `matches()` allowed.
    #[must_use]
    pub const fn with_regex() -> Self {
        Self {
            allow_regex: true,
            root_presence: false,
            missing_parent_false: false,
            dotted_root_keys: false,
            fallback: Fallback::Refuse,
        }
    }
}

/// What [`Program::compile_with`] does with text outside the lowered subset.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Fallback {
    /// It's a [`Refusal`].
    #[default]
    Refuse,
    /// It runs on cel-rust. Without the `expr-cel` feature it's a
    /// [`Refusal`] naming the feature. `matches()` still needs
    /// `Options::allow_regex`.
    ///
    /// Every root field the text names is read before cel runs, so a field
    /// malformed in a branch that never runs, such as the right side of a
    /// `||` whose left side holds, still makes the result
    /// `ErrorKind::Malformed`. The lowered path reads a field only when a
    /// leaf needs it.
    Cel,
}

/// Which engine runs a compiled expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Engine {
    /// grippo's own checks, with no interpreter.
    Lowered,
    /// cel-rust's interpreter, for text outside the lowered subset, under
    /// [`Fallback::Cel`].
    Cel,
}

/// The refusal for text that needs [`Fallback::Cel`] in a build without the
/// `expr-cel` feature.
#[cfg(not(feature = "expr-cel"))]
pub(super) const fn no_cel(text: &str) -> Refusal {
    Refusal {
        span: 0..text.len(),
        why: "Fallback::Cel, which runs only with the expr-cel feature",
    }
}

/// A CEL expression lowered to checks over a record's fields.
#[derive(Debug)]
pub struct Program {
    pub(super) slots: Vec<Slot>,
    root: Node,
    reads: Reads,
    /// The interpreter that runs the text in place of `root`.
    #[cfg(feature = "expr-cel")]
    cel: Option<Box<CelProgram>>,
}

/// The slots leaves read and the root keys `has()` probes, as one read plan
/// over raw JSON.
#[derive(Debug)]
struct Reads {
    plan: ReadPlan,
    /// Each path's place in the frame.
    at: Box<[usize]>,
    /// The probes of root keys holding a dot, which outrank the nested
    /// reads of the same names.
    joined: Box<[usize]>,
    /// Where the probes start in the frame, after the slots.
    probe_base: usize,
}

/// Frame room for a program's slots and then its root probes.
pub(super) const FRAME: usize = 2 * MAX_FIELDS;

thread_local! {
    /// Scratch for [`Reads::fill`], so the `&[u8]` entry points allocate
    /// nothing per record.
    static SCRATCH: RefCell<Slots> = const { RefCell::new(Slots::new()) };
}

impl Reads {
    /// Each slot in `read` once, in the order first read, then each probe at
    /// `probe_base` on.
    fn new(slots: &[Slot], read: &[usize], probes: &[Vec<String>], probe_base: usize) -> Self {
        let mut chosen: Vec<(usize, &[String])> = Vec::new();
        for &i in read {
            if chosen.iter().all(|&(at, _)| at != i) && !slots[i].path.0.is_empty() {
                chosen.push((i, &slots[i].path.0));
            }
        }
        for (j, key) in probes.iter().enumerate() {
            chosen.push((probe_base + j, key));
        }
        let paths: Vec<&[String]> = chosen.iter().map(|&(_, p)| p).collect();
        Self {
            plan: ReadPlan::new(&paths),
            at: chosen.iter().map(|&(at, _)| at).collect(),
            joined: slots
                .iter()
                .filter_map(|s| s.joined.as_ref().and_then(|j| j.probe))
                .collect(),
            probe_base,
        }
    }

    /// Reads every slot's value and probe into `frame` in one pass, when
    /// `record` is raw JSON.
    fn fill<'a, R: Record<'a>>(&self, record: R, frame: &mut Frame<R::At>) {
        let Some((bytes, at)) = record.raw_json() else {
            return;
        };
        if self.at.is_empty() {
            return;
        }
        let mut fill = |scratch: &mut Slots| {
            Json::new(bytes).find_all(&self.plan, scratch, |i, got| {
                frame[self.at[i]] = Some(got.map(at).map_err(read_error));
            });
            // A root key such as `a.b` changes what `a.b.c` reads, so the
            // slots resolve one by one in cel's order instead.
            if self.joined.iter().any(|&j| matches!(frame[j], Some(Ok(_)))) {
                frame[..self.probe_base].fill(None);
            }
        };
        let done = SCRATCH.try_with(|cell| {
            cell.try_borrow_mut()
                .map(|mut scratch| fill(&mut scratch))
                .is_ok()
        });
        if !matches!(done, Ok(true)) {
            fill(&mut Slots::new());
        }
    }
}

/// One field path, with the slot of its parent path when it has one.
#[derive(Debug)]
pub(super) struct Slot {
    parent: Option<usize>,
    path: Path,
    /// Read on its own because two or more read paths run through it.
    shared: bool,
    /// The root key cel reads this path as before its nested field.
    joined: Option<Joined>,
}

/// A root key holding a dot, such as `a.b` for the path `a.b`.
#[derive(Debug)]
struct Joined {
    key: String,
    /// Where the frame holds the one-pass read of the key, if it does.
    probe: Option<usize>,
}

#[derive(Debug)]
pub(super) enum Node {
    And(Vec<Self>),
    Or(Vec<Self>),
    Not(Box<Self>),
    Const(bool),
    Leaf(Leaf),
}

#[derive(Debug)]
pub(super) enum Leaf {
    Has {
        parent: usize,
        key: String,
        /// An absent parent reads as false, not an error.
        missing_parent_false: bool,
    },
    /// A root field is there, whatever its value.
    HasRoot {
        key: String,
        /// Where the frame holds the one-pass read of the key, if it does.
        probe: Option<usize>,
    },
    Cmp {
        slot: usize,
        op: Cmp,
        lit: Lit,
    },
    /// `size()` or `int()` of the slot's value, compared as an int.
    Call {
        func: Func,
        slot: usize,
        op: Cmp,
        lit: Lit,
    },
    In {
        slot: usize,
        lits: Vec<Lit>,
    },
    StartsWith {
        slot: usize,
        prefix: String,
    },
    EndsWith {
        slot: usize,
        suffix: String,
    },
    Contains {
        slot: usize,
        needle: String,
        find: Find,
    },
    /// `None` for an empty pattern, which every string matches.
    Matches {
        slot: usize,
        pattern: String,
        matcher: Option<Box<StrMatcher>>,
    },
}

/// How `contains` searches a string value.
#[derive(Debug)]
pub(super) enum Find {
    Byte(u8),
    Bytes(Box<Finder<'static>>),
}

/// Each slot's read for one record, filled as leaves first need it.
pub(super) type Frame<A> = [Option<Result<A, ErrorKind>>];

impl Program {
    /// Lowers `text`, or returns the first form outside the lowered subset.
    ///
    /// # 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())
    }

    /// [`Program::compile`] with `options`. Under [`Fallback::Cel`], text
    /// outside the lowered subset runs on cel, and [`Program::engine`] says so.
    ///
    /// # 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(text)?;
        let mut lower = Lower::new(options, text.len(), MAX_FIELDS);
        let root = lower.node(ast)?;
        let mut program = Self::from_lower(lower);
        program.root = root;
        Ok(program)
    }

    /// A program that only reads what `lower` gathered, for a value
    /// expression's or a set's filters.
    pub(super) fn from_lower(lower: Lower) -> Self {
        let Lower {
            mut slots,
            read,
            probes,
            max_fields,
            ..
        } = lower;
        mark_shared(&mut slots, &read);
        Self {
            reads: Reads::new(&slots, &read, &probes, max_fields),
            slots,
            root: Node::Const(true),
            #[cfg(feature = "expr-cel")]
            cel: None,
        }
    }

    /// A program cel runs whole.
    #[cfg(feature = "expr-cel")]
    fn from_cel(cel: CelProgram) -> Self {
        let mut program = Self::from_lower(Lower::new(&Options::default(), 0, MAX_FIELDS));
        program.cel = Some(Box::new(cel));
        program
    }

    /// 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 program.
    #[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 result on the JSON record `json`, every field it
    /// reads found in one pass.
    #[must_use]
    pub fn eval(&self, json: &[u8]) -> Outcome {
        self.eval_record(Json::new(json))
    }

    /// Fills `frame` with every field the program reads, in one pass, when
    /// `record` is raw JSON.
    pub(super) fn prefill<'a, R: Record<'a>>(&self, record: R, frame: &mut Frame<R::At>) {
        self.reads.fill(record, frame);
    }

    /// Whether the expression is true on `json`. An error counts as false.
    #[must_use]
    pub fn matches(&self, json: &[u8]) -> bool {
        self.eval(json) == Outcome::True
    }

    /// The expression's result on `record`: raw JSON, a raw line or the
    /// fields a parser chain wrote.
    #[must_use]
    pub fn eval_record<'a, R: Record<'a>>(&self, record: R) -> Outcome {
        #[cfg(feature = "expr-cel")]
        if let Some(cel) = &self.cel {
            return cel.outcome(record);
        }
        let mut frame = [None; FRAME];
        self.prefill(record, &mut frame);
        self.node(&self.root, record, &mut frame)
    }

    /// Whether the expression is true on `record`. An error counts as false.
    #[must_use]
    pub fn matches_record<'a, R: Record<'a>>(&self, record: R) -> bool {
        self.eval_record(record) == Outcome::True
    }

    pub(super) fn node<'a, R: Record<'a>>(
        &self,
        node: &Node,
        record: R,
        frame: &mut Frame<R::At>,
    ) -> Outcome {
        // Of two errors cel raises the right-hand one, so the last one wins.
        match node {
            Node::And(children) => {
                let mut error = None;
                for child in children {
                    match self.node(child, record, frame) {
                        Outcome::False => return Outcome::False,
                        Outcome::Error(kind) => error = Some(kind),
                        Outcome::True => {}
                    }
                }
                error.map_or(Outcome::True, Outcome::Error)
            }
            Node::Or(children) => {
                let mut error = None;
                for child in children {
                    match self.node(child, record, frame) {
                        Outcome::True => return Outcome::True,
                        Outcome::Error(kind) => error = Some(kind),
                        Outcome::False => {}
                    }
                }
                error.map_or(Outcome::False, Outcome::Error)
            }
            Node::Not(inner) => match self.node(inner, record, frame) {
                Outcome::True => Outcome::False,
                Outcome::False => Outcome::True,
                error @ Outcome::Error(_) => error,
            },
            Node::Const(v) => outcome(*v),
            Node::Leaf(leaf) => self
                .leaf(leaf, record, frame)
                .map_or_else(Outcome::Error, outcome),
        }
    }

    fn leaf<'a, R: Record<'a>>(
        &self,
        leaf: &Leaf,
        record: R,
        frame: &mut Frame<R::At>,
    ) -> Result<bool, ErrorKind> {
        match leaf {
            Leaf::Has {
                parent,
                key,
                missing_parent_false,
            } => {
                let obj = match self.resolve(*parent, record, frame) {
                    Ok(obj) => obj,
                    Err(ErrorKind::MissingRoot | ErrorKind::MissingField)
                        if *missing_parent_false =>
                    {
                        return Ok(false);
                    }
                    Err(e) => return Err(e),
                };
                match record.find_below(obj, slice::from_ref(key)) {
                    Ok(_) => Ok(true),
                    Err(Miss::MissingField | Miss::MissingRoot) => Ok(false),
                    Err(Miss::WrongParentType) => Err(ErrorKind::TypeMismatch),
                    Err(Miss::Malformed) => Err(ErrorKind::Malformed),
                }
            }
            Leaf::HasRoot { key, probe } => {
                let read = probe.and_then(|i| frame.get(i).copied().flatten());
                match read.unwrap_or_else(|| record.find(slice::from_ref(key)).map_err(read_error))
                {
                    Ok(_) => Ok(true),
                    Err(ErrorKind::MissingRoot) => Ok(false),
                    Err(e) => Err(e),
                }
            }
            Leaf::Cmp { slot, op, lit } => compare(&self.typed(*slot, record, frame)?, *op, lit),
            Leaf::Call {
                func,
                slot,
                op,
                lit,
            } => {
                let at = self.resolve(*slot, record, frame)?;
                let n = match func {
                    Func::Size => size(record, at)?,
                    Func::Int => int(record.typed(at).map_err(read_error)?)?,
                };
                compare(&Typed::Int(n), *op, lit)
            }
            Leaf::In { slot, lits } => {
                let v = self.typed(*slot, record, frame)?;
                Ok(lits.iter().any(|lit| equal(&v, lit)))
            }
            Leaf::StartsWith { slot, prefix } => match self.typed(*slot, record, frame)? {
                Typed::Str(s) => Ok(s.starts_with(prefix.as_str())),
                _ => Err(ErrorKind::TypeMismatch),
            },
            Leaf::EndsWith { slot, suffix } => match self.typed(*slot, record, frame)? {
                Typed::Str(s) => Ok(s.ends_with(suffix.as_str())),
                _ => Err(ErrorKind::TypeMismatch),
            },
            Leaf::Matches { slot, matcher, .. } => match self.typed(*slot, record, frame)? {
                Typed::Str(s) => Ok(matcher.as_ref().is_none_or(|m| m.is_match(s.as_bytes()))),
                _ => Err(ErrorKind::TypeMismatch),
            },
            Leaf::Contains { slot, find, .. } => match self.typed(*slot, record, frame)? {
                Typed::Str(s) => Ok(match find {
                    Find::Byte(b) => memchr::memchr(*b, s.as_bytes()).is_some(),
                    Find::Bytes(f) => f.find(s.as_bytes()).is_some(),
                }),
                _ => Err(ErrorKind::TypeMismatch),
            },
        }
    }

    /// The value in slot `i`, typed.
    pub(super) fn typed<'a, R: Record<'a>>(
        &self,
        i: usize,
        record: R,
        frame: &mut Frame<R::At>,
    ) -> Result<Typed<'a>, ErrorKind> {
        record
            .typed(self.resolve(i, record, frame)?)
            .map_err(read_error)
    }

    /// Where slot `i` sits in the record, found once per record.
    pub(super) fn resolve<'a, R: Record<'a>>(
        &self,
        i: usize,
        record: R,
        frame: &mut Frame<R::At>,
    ) -> Result<R::At, ErrorKind> {
        if let Some(done) = frame[i] {
            return done;
        }
        let slot = &self.slots[i];
        if let Some(joined) = &slot.joined {
            let read = joined.probe.and_then(|j| frame.get(j).copied().flatten());
            let read = read.unwrap_or_else(|| {
                record
                    .find(slice::from_ref(&joined.key))
                    .map_err(read_error)
            });
            if let Ok(at) = read {
                frame[i] = Some(Ok(at));
                return Ok(at);
            }
        }
        let mut base = slot.parent;
        while let Some(p) = base {
            if self.slots[p].shared || self.slots[p].joined.is_some() {
                break;
            }
            base = self.slots[p].parent;
        }
        let got = match base {
            Some(p) => {
                let obj = self.resolve(p, record, frame)?;
                record.find_below(obj, &slot.path.0[self.slots[p].path.0.len()..])
            }
            None => record.find(&slot.path.0),
        }
        .map_err(read_error);
        frame[i] = Some(got);
        got
    }
}

const fn outcome(v: bool) -> Outcome {
    if v { Outcome::True } else { Outcome::False }
}

fn compare(v: &Typed<'_>, op: Cmp, lit: &Lit) -> Result<bool, ErrorKind> {
    Ok(match op {
        Cmp::Eq => equal(v, lit),
        Cmp::Ne => !equal(v, lit),
        Cmp::Lt => order(v, lit)? == Some(Ordering::Less),
        Cmp::Le => matches!(order(v, lit)?, Some(Ordering::Less | Ordering::Equal)),
        Cmp::Gt => order(v, lit)? == Some(Ordering::Greater),
        Cmp::Ge => matches!(order(v, lit)?, Some(Ordering::Greater | Ordering::Equal)),
    })
}

/// cel's `size()`: a string's code points, a list's elements, a map's distinct
/// keys.
fn size<'a, R: Record<'a>>(record: R, at: R::At) -> Result<i64, ErrorKind> {
    let n = match record.typed(at).map_err(read_error)? {
        Typed::Str(s) => s.chars().count(),
        Typed::List => list_len(&record.text(at).map_err(read_error)?)?,
        Typed::Map => {
            let mut keys =
                object_keys(&record.text(at).map_err(read_error)?).map_err(read_error)?;
            keys.sort_unstable();
            keys.dedup();
            keys.len()
        }
        _ => return Err(ErrorKind::TypeMismatch),
    };
    i64::try_from(n).map_err(|_| ErrorKind::Overflow)
}

/// A JSON array's element count.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn list_len(text: &str) -> Result<usize, ErrorKind> {
    sonic_rs::to_array_iter(text).try_fold(0, |n, item| {
        item.map(|_| n + 1).map_err(|_| ErrorKind::Malformed)
    })
}

/// A JSON array's element count.
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn list_len(text: &str) -> Result<usize, ErrorKind> {
    serde_json::from_str::<Vec<&serde_json::value::RawValue>>(text)
        .map(|items| items.len())
        .map_err(|_| ErrorKind::Malformed)
}

/// cel's `int()`: a double inside i64's range, bounds excluded,
/// truncated toward zero, and a string as Rust's `i64` parse reads it.
#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    reason = "cel bounds a double by i64's range through f64, then truncates"
)]
fn int(v: Typed<'_>) -> Result<i64, ErrorKind> {
    match v {
        Typed::Int(n) => Ok(n),
        Typed::Uint(n) => i64::try_from(n).map_err(|_| ErrorKind::Overflow),
        Typed::Double(d) if d > i64::MIN as f64 && d < i64::MAX as f64 => Ok(d as i64),
        Typed::Double(_) => Err(ErrorKind::Overflow),
        Typed::Str(s) => s.parse::<i64>().map_err(|_| ErrorKind::Conversion),
        _ => Err(ErrorKind::TypeMismatch),
    }
}

/// cel's `==`: numbers across int, uint and double by value, an int
/// against a double through `f64`, any other mix false.
#[allow(
    clippy::cast_precision_loss,
    clippy::float_cmp,
    reason = "cel compares an int with a double through f64, exactly"
)]
fn equal(v: &Typed<'_>, lit: &Lit) -> bool {
    match (v, lit) {
        (Typed::Str(a), Lit::Str(b)) => a == b,
        (Typed::Int(a), Lit::Int(b)) => a == b,
        (Typed::Uint(a), Lit::Uint(b)) => a == b,
        (Typed::Double(a), Lit::Double(b)) => a == b,
        (Typed::Int(a), Lit::Uint(b)) => u64::try_from(*a).is_ok_and(|a| a == *b),
        (Typed::Uint(a), Lit::Int(b)) => i64::try_from(*a).is_ok_and(|a| a == *b),
        (Typed::Int(a), Lit::Double(b)) => *a as f64 == *b,
        (Typed::Uint(a), Lit::Double(b)) => *a as f64 == *b,
        (Typed::Double(a), Lit::Int(b)) => *a == *b as f64,
        (Typed::Double(a), Lit::Uint(b)) => *a == *b as f64,
        (Typed::Bool(a), Lit::Bool(b)) => a == b,
        (Typed::Null, Lit::Null) => true,
        _ => false,
    }
}

/// cel's ordering: an error where the types don't compare, and `None` where
/// a NaN meets a number, which makes every ordering false.
#[allow(
    clippy::cast_precision_loss,
    reason = "cel orders an int against a double through f64"
)]
fn order(v: &Typed<'_>, lit: &Lit) -> Result<Option<Ordering>, ErrorKind> {
    Ok(match (v, lit) {
        (Typed::Int(a), Lit::Int(b)) => Some(a.cmp(b)),
        (Typed::Uint(a), Lit::Uint(b)) => Some(a.cmp(b)),
        (Typed::Int(a), Lit::Uint(b)) => {
            Some(u64::try_from(*a).map_or(Ordering::Less, |a| a.cmp(b)))
        }
        (Typed::Uint(a), Lit::Int(b)) => {
            Some(i64::try_from(*a).map_or(Ordering::Greater, |a| a.cmp(b)))
        }
        (Typed::Int(a), Lit::Double(b)) => (*a as f64).partial_cmp(b),
        (Typed::Uint(a), Lit::Double(b)) => (*a as f64).partial_cmp(b),
        (Typed::Double(a), Lit::Int(b)) => a.partial_cmp(&(*b as f64)),
        (Typed::Double(a), Lit::Uint(b)) => a.partial_cmp(&(*b as f64)),
        (Typed::Double(a), Lit::Double(b)) => a.partial_cmp(b),
        (Typed::Str(a), Lit::Str(b)) => Some(a.as_ref().cmp(b.as_str())),
        _ => return Err(ErrorKind::TypeMismatch),
    })
}

/// Builds slots and leaves from the parsed tree.
pub(super) struct Lower {
    pub(super) slots: Vec<Slot>,
    /// The slots leaves read directly, one entry per leaf.
    pub(super) read: Vec<usize>,
    /// The root keys `has()` reads, each one key long, in probe order.
    pub(super) probes: Vec<Vec<String>>,
    pub(super) len: usize,
    options: Options,
    /// The most slots this lowering may add.
    max_fields: usize,
}

/// Marks each slot that two or more leaf reads pass through or stop at.
fn mark_shared(slots: &mut [Slot], read: &[usize]) {
    let mut through = vec![0_u32; slots.len()];
    let mut seen = Vec::new();
    for &leaf in read {
        if seen.contains(&leaf) {
            continue;
        }
        seen.push(leaf);
        let mut at = Some(leaf);
        while let Some(i) = at {
            through[i] += 1;
            at = slots[i].parent;
        }
    }
    for (slot, n) in slots.iter_mut().zip(through) {
        slot.shared = n > 1;
    }
}

impl Lower {
    pub(super) fn new(options: &Options, len: usize, max_fields: usize) -> Self {
        Self {
            slots: Vec::new(),
            read: Vec::new(),
            len,
            options: options.clone(),
            max_fields,
            probes: Vec::new(),
        }
    }

    fn nodes(&mut self, terms: Vec<Ast>) -> Result<Vec<Node>, Refusal> {
        terms.into_iter().map(|t| self.node(t)).collect()
    }

    pub(super) fn node(&mut self, ast: Ast) -> Result<Node, Refusal> {
        Ok(match ast {
            Ast::Or(terms) => Node::Or(self.nodes(terms)?),
            Ast::And(terms) => Node::And(self.nodes(terms)?),
            Ast::Not(inner) => Node::Not(Box::new(self.node(*inner)?)),
            Ast::Const(v) => Node::Const(v),
            Ast::Has(path, at) => {
                let Some((key, parent)) = path.0.split_last() else {
                    return Err(self.refuse("has() with no field"));
                };
                if parent.is_empty() {
                    if !self.options.root_presence {
                        return Err(Refusal {
                            span: at,
                            why: "has() on a bare name, which runs only with Options::root_presence",
                        });
                    }
                    let probe = self.probe(key);
                    return Ok(Node::Leaf(Leaf::HasRoot {
                        key: key.clone(),
                        probe,
                    }));
                }
                let parent = self.read(&path.prefix(parent.len()))?;
                Node::Leaf(Leaf::Has {
                    parent,
                    key: key.clone(),
                    missing_parent_false: self.options.missing_parent_false,
                })
            }
            Ast::Cmp(path, op, lit) => {
                if !matches!(op, Cmp::Eq | Cmp::Ne) && matches!(lit, Lit::Bool(_) | Lit::Null) {
                    return Err(self.refuse("an ordering against a bool or null"));
                }
                Node::Leaf(Leaf::Cmp {
                    slot: self.read(&path)?,
                    op,
                    lit,
                })
            }
            Ast::Call(func, path, op, lit) => {
                if !matches!(op, Cmp::Eq | Cmp::Ne) && matches!(lit, Lit::Bool(_) | Lit::Null) {
                    return Err(self.refuse("an ordering against a bool or null"));
                }
                Node::Leaf(Leaf::Call {
                    func,
                    slot: self.read(&path)?,
                    op,
                    lit,
                })
            }
            Ast::In(path, lits) => Node::Leaf(Leaf::In {
                slot: self.read(&path)?,
                lits,
            }),
            Ast::Method(path, method, arg) => {
                let slot = self.read(&path)?;
                Node::Leaf(match method {
                    Method::StartsWith => Leaf::StartsWith { slot, prefix: arg },
                    Method::EndsWith => Leaf::EndsWith { slot, suffix: arg },
                    Method::Contains => {
                        let find = match arg.as_bytes() {
                            [b] => Find::Byte(*b),
                            bytes => Find::Bytes(Box::new(Finder::new(bytes).into_owned())),
                        };
                        Leaf::Contains {
                            slot,
                            needle: arg,
                            find,
                        }
                    }
                    Method::Matches => self.matches(slot, arg)?,
                })
            }
        })
    }

    /// A `matches()` leaf: refused unless the caller allows regex, or when
    /// cel's string regex wouldn't compile the pattern.
    fn matches(&self, slot: usize, pattern: String) -> Result<Leaf, Refusal> {
        if !self.options.allow_regex {
            return Err(self.refuse("matches(), which runs only with Options::allow_regex"));
        }
        if regex_syntax::Parser::new().parse(&pattern).is_err() {
            return Err(self.refuse("a matches() pattern cel's regex refuses"));
        }
        let matcher = if pattern.is_empty() {
            None
        } else {
            let m = StrMatcher::new(&pattern)
                .map_err(|_| self.refuse("a matches() pattern strmatch can't build"))?;
            Some(Box::new(m))
        };
        Ok(Leaf::Matches {
            slot,
            pattern,
            matcher,
        })
    }

    /// The slot for `path`, adding it and its prefixes when new.
    fn slot(&mut self, path: &Path) -> Result<usize, Refusal> {
        // Each prefix takes a slot, so this bounds the recursion below.
        if path.0.len() > self.max_fields {
            return Err(self.refuse("more field paths than one program holds"));
        }
        // Without dotted root keys, `a.b` and `a["b"]` read the same field.
        let unnamed;
        let path = if self.options.dotted_root_keys {
            path
        } else {
            unnamed = Path(path.0.clone(), 0);
            &unnamed
        };
        if let Some(i) = self.slots.iter().position(|s| &s.path == path) {
            return Ok(i);
        }
        let Some((_, prefix)) = path.0.split_last() else {
            return Err(self.refuse("an empty field path"));
        };
        let parent = if prefix.is_empty() {
            None
        } else {
            Some(self.slot(&path.prefix(prefix.len()))?)
        };
        if self.slots.len() == self.max_fields {
            return Err(self.refuse("more field paths than one program holds"));
        }
        let joined = path.joined().map(|key| Joined {
            probe: self.probe(&key),
            key,
        });
        self.slots.push(Slot {
            parent,
            path: path.clone(),
            shared: false,
            joined,
        });
        Ok(self.slots.len() - 1)
    }

    /// The frame place for a `has()` of the root key `key`, `None` once
    /// `max_fields` probes are taken.
    fn probe(&mut self, key: &str) -> Option<usize> {
        let j = match self.probes.iter().position(|p| p[0] == key) {
            Some(j) => j,
            None if self.probes.len() < self.max_fields => {
                self.probes.push(vec![key.to_owned()]);
                self.probes.len() - 1
            }
            None => return None,
        };
        Some(self.max_fields + j)
    }

    /// The slot for `path`, recorded as read by one leaf.
    pub(super) fn read(&mut self, path: &Path) -> Result<usize, Refusal> {
        let i = self.slot(path)?;
        self.read.push(i);
        Ok(i)
    }

    pub(super) const fn refuse(&self, why: &'static str) -> Refusal {
        Refusal {
            span: 0..self.len,
            why,
        }
    }
}

impl fmt::Display for Program {
    /// One line: the tree, each leaf named by the check it runs, or `cel(...)`
    /// around the text the fallback runs.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(feature = "expr-cel")]
        if let Some(cel) = &self.cel {
            return write!(f, "{cel}");
        }
        self.write_node(&self.root, f)
    }
}

impl Program {
    fn write_node(&self, node: &Node, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match node {
            Node::And(c) => self.write_list("and", c, f),
            Node::Or(c) => self.write_list("or", c, f),
            Node::Not(inner) => {
                f.write_str("not(")?;
                self.write_node(inner, f)?;
                f.write_str(")")
            }
            Node::Const(v) => write!(f, "{v}"),
            Node::Leaf(leaf) => self.write_leaf(leaf, f),
        }
    }

    fn write_list(&self, name: &str, children: &[Node], f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{name}(")?;
        for (i, c) in children.iter().enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            self.write_node(c, f)?;
        }
        f.write_str(")")
    }

    fn write_leaf(&self, leaf: &Leaf, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let path = |i: usize| self.slots[i].path.0.join(".");
        match leaf {
            Leaf::Has { parent, key, .. } => write!(f, "has({}.{key})", path(*parent)),
            Leaf::HasRoot { key, .. } => write!(f, "has({key})"),
            Leaf::Cmp { slot, op, lit } => write!(f, "{op:?}({}, {lit:?})", path(*slot)),
            Leaf::Call {
                func,
                slot,
                op,
                lit,
            } => {
                let name = match func {
                    Func::Size => "size",
                    Func::Int => "int",
                };
                write!(f, "{op:?}({name}({}), {lit:?})", path(*slot))
            }
            Leaf::In { slot, lits } => write!(f, "in({}, {} values)", path(*slot), lits.len()),
            Leaf::StartsWith { slot, prefix } => write!(f, "prefix({}, {prefix:?})", path(*slot)),
            Leaf::EndsWith { slot, suffix } => write!(f, "suffix({}, {suffix:?})", path(*slot)),
            Leaf::Matches { slot, pattern, .. } => {
                write!(f, "matches({}, {pattern:?})", path(*slot))
            }
            Leaf::Contains { slot, needle, find } => {
                let how = match find {
                    Find::Byte(_) => "memchr",
                    Find::Bytes(_) => "memmem",
                };
                write!(f, "{how}({}, {needle:?})", path(*slot))
            }
        }
    }
}