grippo 0.1.2

Parse, match and scrub data at scale.
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
//! The lowered program against cel 0.14.5's interpreter, with the context
//! one variable per root field present, its JSON value converted by grippo's
//! number rule: int first, then uint, then double.

use std::borrow::Cow;
use std::collections::HashMap;

use proptest::prelude::*;
use serde_json::{Map, Number, Value as Json, json};

use super::{Options, Outcome, Program, ProgramSet, Value, ValueProgram};
use crate::record::{Miss, Record, Typed};

fn json_to_cel(json: &Json) -> cel::Value {
    match json {
        Json::Null => cel::Value::Null,
        Json::Bool(b) => cel::Value::Bool(*b),
        Json::Number(n) => n.as_i64().map_or_else(
            || {
                n.as_u64().map_or_else(
                    || cel::Value::Float(n.as_f64().unwrap_or(0.0)),
                    cel::Value::UInt,
                )
            },
            cel::Value::Int,
        ),
        Json::String(s) => cel::Value::String(s.clone().into()),
        Json::Array(a) => cel::Value::List(a.iter().map(json_to_cel).collect::<Vec<_>>().into()),
        Json::Object(o) => {
            let map: HashMap<cel::objects::Key, cel::Value> = o
                .iter()
                .map(|(k, v)| (k.clone().into(), json_to_cel(v)))
                .collect();
            cel::Value::Map(map.into())
        }
    }
}

/// Raw JSON read one path at a time through [`Json`]'s lookups, with no
/// one-pass read, as the reference the one-pass read must agree with.
#[derive(Debug, Clone, Copy)]
struct Lazy<'a>(crate::record::Json<'a>);

impl<'a> Record<'a> for Lazy<'a> {
    type At = &'a str;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
        self.0.find(path)
    }

    fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
        self.0.find_below(at, path)
    }

    fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
        self.0.typed(at)
    }

    fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
        self.0.text(at)
    }
}

/// cel's result: true, false, or `None` for an error.
fn cel_says(text: &str, record: &Json) -> Option<bool> {
    let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
    let mut ctx = cel::Context::default();
    if let Json::Object(roots) = record {
        for (k, v) in roots {
            ctx.add_variable_from_value(k.clone(), json_to_cel(v));
        }
    }
    match program.execute(&ctx) {
        Ok(cel::Value::Bool(b)) => Some(b),
        Ok(other) => panic!("{text} gave {other:?}, not a bool"),
        Err(_) => None,
    }
}

fn agree(text: &str, record: &Json) -> Result<(), TestCaseError> {
    let program = Program::compile_with(text, &Options::with_regex())
        .map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
    let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
    let ours = match program.eval(&bytes) {
        Outcome::True => Some(true),
        Outcome::False => Some(false),
        Outcome::Error(_) => None,
    };
    prop_assert_eq!(ours, cel_says(text, record), "{} on {}", text, record);
    prop_assert_eq!(
        program.eval_record(Lazy(crate::record::Json::new(&bytes))),
        program.eval(&bytes),
        "{} read by sonic-rs lookups on {}",
        text,
        record
    );
    let pretty =
        serde_json::to_vec_pretty(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
    prop_assert_eq!(
        program.eval(&pretty),
        program.eval(&bytes),
        "{} on pretty {}",
        text,
        record
    );
    Ok(())
}

const PATHS: &[&str] = &["a", "b", "a.x", "a.y", "b.x", "c.x.y"];

fn path() -> impl Strategy<Value = &'static str> {
    prop::sample::select(PATHS)
}

/// A literal as CEL text.
fn literal() -> impl Strategy<Value = &'static str> {
    prop::sample::select(
        &[
            r#""""#,
            r#""q""#,
            r#""query""#,
            r#""answer""#,
            r#""Qé""#,
            r#""a\nb""#,
            r"'q'",
            r#"r"q""#,
            "0",
            "1",
            "-1",
            "5158",
            "9223372036854775807",
            "1u",
            "18446744073709551615u",
            "1.0",
            "-0.0",
            "0.5",
            "5158.0",
            "9007199254740992.0",
            "1e3",
            "true",
            "false",
            "null",
        ][..],
    )
}

fn ordered_literal() -> impl Strategy<Value = &'static str> {
    literal().prop_filter("no ordering on bool or null", |l| {
        !matches!(*l, "true" | "false" | "null")
    })
}

fn string_arg() -> impl Strategy<Value = &'static str> {
    prop::sample::select(
        &[
            r#""""#, r#""q""#, r#""que""#, r#""ery""#, r#""é""#, r#""x""#, r#""\n""#,
        ][..],
    )
}

fn leaf() -> impl Strategy<Value = String> {
    prop_oneof![
        (path(), prop::sample::select(&["x", "y"][..])).prop_map(|(p, k)| format!("has({p}.{k})")),
        (path(), prop::sample::select(&["==", "!="][..]), literal())
            .prop_map(|(p, op, l)| format!("{p} {op} {l}")),
        (
            path(),
            prop::sample::select(&["<", "<=", ">", ">="][..]),
            ordered_literal()
        )
            .prop_map(|(p, op, l)| format!("{p} {op} {l}")),
        (literal(), path()).prop_map(|(l, p)| format!("{l} == {p}")),
        (
            path(),
            prop::sample::select(&["startsWith", "endsWith", "contains"][..]),
            string_arg()
        )
            .prop_map(|(p, m, s)| format!("{p}.{m}({s})")),
        (path(), literal(), literal()).prop_map(|(p, l1, l2)| format!("{p} in [{l1}, {l2}]")),
        (path(), pattern()).prop_map(|(p, re)| format!("{p}.matches({re})")),
    ]
}

/// A regex as a CEL string literal.
fn pattern() -> impl Strategy<Value = &'static str> {
    prop::sample::select(
        &[
            r#""""#,
            r#""q""#,
            r#""^q""#,
            r#""y$""#,
            r#""^qu.*y$""#,
            r#""(?i)QUERY""#,
            r#""\\d+""#,
            r#""é""#,
            r#"".""#,
            r#""an|qu""#,
            r#""^$""#,
            r#""^a\nb$""#,
            r#""[a-z]{5}""#,
        ][..],
    )
}

fn expr() -> impl Strategy<Value = String> {
    leaf().prop_recursive(3, 12, 3, |inner| {
        prop_oneof![
            (inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} && {b})")),
            (inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} || {b})")),
            inner.prop_map(|a| format!("!({a})")),
        ]
    })
}

fn scalar() -> impl Strategy<Value = Json> {
    prop_oneof![
        prop::sample::select(
            &[
                "", "q", "query", "answer", "Q\u{e9}", "a\nb", "xqueryx", "é"
            ][..]
        )
        .prop_map(|s| Json::String(s.to_owned())),
        prop::sample::select(&[0_i64, 1, -1, 5158, i64::MAX, i64::MIN, 3][..])
            .prop_map(|n| json!(n)),
        prop::sample::select(&[9_223_372_036_854_775_808_u64, u64::MAX][..]).prop_map(|n| json!(n)),
        prop::sample::select(&[1.0_f64, -0.0, 0.5, 5158.0, 9_007_199_254_740_992.0, 1e3][..])
            .prop_map(|f| Number::from_f64(f).map_or(Json::Null, Json::Number)),
        any::<bool>().prop_map(Json::Bool),
        Just(Json::Null),
        prop::collection::vec(prop::sample::select(&["q", "x", "query"][..]), 0..3)
            .prop_map(|v| json!(v)),
    ]
}

fn object(depth: u32) -> BoxedStrategy<Json> {
    let value = if depth == 0 {
        scalar().boxed()
    } else {
        prop_oneof![3 => scalar(), 2 => object(depth - 1)].boxed()
    };
    prop::collection::vec((prop::sample::select(&["x", "y", "q"][..]), value), 0..3)
        .prop_map(|kvs| {
            Json::Object(
                kvs.into_iter()
                    .map(|(k, v)| (k.to_owned(), v))
                    .collect::<Map<_, _>>(),
            )
        })
        .boxed()
}

fn record() -> impl Strategy<Value = Json> {
    let root = prop_oneof![2 => scalar(), 3 => object(2)];
    prop::collection::vec((prop::sample::select(&["a", "b", "c"][..]), root), 0..4).prop_map(
        |kvs| {
            Json::Object(
                kvs.into_iter()
                    .map(|(k, v)| (k.to_owned(), v))
                    .collect::<Map<_, _>>(),
            )
        },
    )
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(4096))]

    #[test]
    fn a_lowered_program_gives_what_cel_gives(text in expr(), rec in record()) {
        agree(&text, &rec)?;
    }
}

/// The pilot's headline filters and the review's edge tables, each against cel.
#[test]
fn named_cases_agree_with_cel() {
    let dns = r#"event.network.direction == "outbound" && event.dns.type == "query""#;
    let either = r#"event.dns.type == "query" || event.dns.type == "answer""#;
    let neither = r#"!(event.network.direction == "outbound" && event.dns.type == "answer")"#;
    let records = [
        json!({}),
        json!({"event": {}}),
        json!({"event": {"network": {"direction": "outbound"}, "dns": {"type": "query"}}}),
        json!({"event": {"network": {"direction": "inbound"}, "dns": {"type": "answer"}}}),
        json!({"event": {"dns": {"type": "answer"}}}),
        json!({"event": null}),
        json!({"event": 3}),
        json!({"event": {"dns": {"type": 7}}}),
        json!({"f": 123}),
        json!({"f": "123"}),
        json!({"f": null}),
        json!({"f": 9_007_199_254_740_993_u64}),
        json!({"f": "a\u{0061}"}),
        json!({"a": {}}),
        json!({"a": {"b": null}}),
        json!({"a": []}),
        json!({"a": ["x", "q"]}),
        json!({"a": {"x": 1}}),
    ];
    let exprs = [
        dns,
        either,
        neither,
        r#"f == "123""#,
        r#"f != "123""#,
        r#"!(f == "x")"#,
        r#"!f.startsWith("1")"#,
        r#"f.contains("2")"#,
        "f == 9007199254740992.0",
        "f > 3",
        "f >= 1u",
        r#"f == "aa""#,
        "has(a.b)",
        "!has(a.b)",
        r#"a.contains("x")"#,
        r#"a.contains("q") || f == null"#,
        r#"f in ["123", 123]"#,
        "true && f == 1",
    ];
    for text in exprs {
        for rec in &records {
            if let Err(e) = agree(text, rec) {
                panic!("{e}");
            }
        }
    }
}

/// cel's value, or `None` for an error.
fn cel_value(text: &str, record: &Json) -> Option<cel::Value> {
    let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
    let mut ctx = cel::Context::default();
    if let Json::Object(roots) = record {
        for (k, v) in roots {
            ctx.add_variable_from_value(k.clone(), json_to_cel(v));
        }
    }
    program.execute(&ctx).ok()
}

fn as_cel(v: &Value<'_>) -> cel::Value {
    match v {
        Value::Str(s) => cel::Value::String(s.to_string().into()),
        Value::Int(n) => cel::Value::Int(*n),
        Value::Uint(n) => cel::Value::UInt(*n),
        Value::Double(n) => cel::Value::Float(*n),
        Value::Bool(b) => cel::Value::Bool(*b),
        Value::Null => cel::Value::Null,
        Value::Json(text) => json_to_cel(&serde_json::from_str(text).unwrap_or(Json::Null)),
    }
}

fn agree_value(text: &str, record: &Json) -> Result<(), TestCaseError> {
    let program = ValueProgram::compile_with(text, &Options::with_regex())
        .map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
    let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
    let ours = program.eval(&bytes).ok().map(|v| as_cel(&v));
    let lazy = program
        .eval_record(Lazy(crate::record::Json::new(&bytes)))
        .ok()
        .map(|v| as_cel(&v));
    prop_assert_eq!(
        &lazy,
        &ours,
        "{} read by sonic-rs lookups on {}",
        text,
        record
    );
    let theirs = cel_value(text, record);
    if ours != theirs {
        // cel appends a map's keys to a list in its hash map's order.
        let sorted = |v: Option<cel::Value>| match v {
            Some(cel::Value::List(items)) => {
                let mut items: Vec<String> = items.iter().map(|i| format!("{i:?}")).collect();
                items.sort();
                Some(items)
            }
            _ => None,
        };
        prop_assert!(
            sorted(ours.clone()).is_some() && sorted(ours) == sorted(theirs),
            "{} on {}",
            text,
            record
        );
    }
    Ok(())
}

fn value_atom() -> impl Strategy<Value = String> {
    prop_oneof![
        path().prop_map(str::to_owned),
        literal().prop_map(str::to_owned)
    ]
}

fn value_expr() -> impl Strategy<Value = String> {
    prop_oneof![
        value_atom(),
        (value_atom(), value_atom()).prop_map(|(a, b)| format!("{a} + {b}")),
        (expr(), value_atom(), value_atom()).prop_map(|(c, a, b)| format!("{c} ? {a} : {b}")),
        (expr(), value_atom(), expr(), value_atom(), value_atom())
            .prop_map(|(c1, a, c2, b, d)| format!("{c1} ? {a} : {c2} ? {b} : {d}")),
    ]
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(2048))]

    #[test]
    fn a_lowered_value_gives_what_cel_gives(text in value_expr(), rec in record()) {
        agree_value(&text, &rec)?;
    }
}

/// The loader's computed columns, each against cel.
#[test]
fn computed_columns_agree_with_cel() {
    let exprs = [
        r#"risk_score > 80 ? "high" : risk_score > 40 ? "medium" : "low""#,
        r#"src_ip.startsWith("10.") || src_ip.startsWith("192.168.")"#,
        "bytes_in + bytes_out",
        r#"value + "_enriched""#,
        r#"risk_score > 90 ? "critical" : "ok""#,
    ];
    let records = [
        json!({}),
        json!({"risk_score": 95, "src_ip": "10.0.0.1", "bytes_in": 10, "bytes_out": 20, "value": "v"}),
        json!({"risk_score": 50.5, "src_ip": "8.8.8.8", "bytes_in": 10, "bytes_out": 2.5, "value": 3}),
        json!({"risk_score": "high", "bytes_in": i64::MAX, "bytes_out": 1}),
        json!({"bytes_in": [1], "bytes_out": [2, 3]}),
    ];
    for text in exprs {
        for rec in &records {
            if let Err(e) = agree_value(text, rec) {
                panic!("{e}");
            }
        }
    }
}

/// A set's matches are exactly the filters that are true alone.
fn agree_set(texts: &[String], record: &Json) -> Result<(), TestCaseError> {
    let options = Options::with_regex();
    let set =
        ProgramSet::compile(texts, &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
    prop_assert!(set.refused().is_empty(), "{:?}", set.refused());
    let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
    let alone: Vec<usize> = texts
        .iter()
        .enumerate()
        .filter(|(_, t)| {
            Program::compile_with(t, &options).is_ok_and(|p| p.eval(&bytes) == Outcome::True)
        })
        .map(|(i, _)| i)
        .collect();
    let (mut got, mut lazy) = (Vec::new(), Vec::new());
    set.matching(&bytes, &mut got);
    set.matching_record(Lazy(crate::record::Json::new(&bytes)), &mut lazy);
    prop_assert_eq!(
        &got,
        &lazy,
        "{:?} read by sonic-rs lookups on {}",
        texts,
        record
    );
    prop_assert_eq!(got, alone, "{:?} on {}", texts, record);
    Ok(())
}

fn equals() -> impl Strategy<Value = String> {
    (
        path(),
        prop::sample::select(&[r#""q""#, r#""query""#, r#""answer""#, r#""""#][..]),
    )
        .prop_map(|(p, l)| format!("{p} == {l}"))
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1024))]

    #[test]
    fn a_set_matches_what_each_filter_matches_alone(
        texts in prop::collection::vec(prop_oneof![3 => equals(), 1 => expr()], 1..30),
        rec in record(),
    ) {
        agree_set(&texts, &rec)?;
    }
}

/// The record's fields as a parser writes them: one dotted name per scalar,
/// an array, null or empty object as its JSON text.
#[cfg(feature = "parse")]
fn flatten(record: &Json) -> crate::parse::Fields<'static> {
    use crate::parse::{FieldSink, FieldValue, Fields, Hint};

    fn put(name: &str, value: &Json, out: &mut Fields<'static>) {
        let (bytes, hint) = match value {
            Json::Object(map) if !map.is_empty() => {
                for (k, v) in map {
                    put(&format!("{name}.{k}"), v, out);
                }
                return;
            }
            Json::String(s) => (s.clone().into_bytes(), Hint::Text),
            Json::Number(n) if n.is_f64() => (n.to_string().into_bytes(), Hint::Float),
            Json::Number(n) => (n.to_string().into_bytes(), Hint::Int),
            Json::Bool(b) => (b.to_string().into_bytes(), Hint::Bool),
            other => (other.to_string().into_bytes(), Hint::Json),
        };
        out.field(name, FieldValue::owned(bytes, hint));
    }
    let mut out = Fields::new();
    if let Json::Object(map) = record {
        for (k, v) in map {
            put(k, v, &mut out);
        }
    }
    out
}

/// Every filter, value and set gives the same answer, errors included, over
/// the record's JSON and over its fields as a parser writes them.
#[cfg(feature = "parse")]
fn agree_on_fields(text: &str, value: &str, record: &Json) -> Result<(), TestCaseError> {
    let options = Options::with_regex();
    let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
    let fields = flatten(record);
    let program = Program::compile_with(text, &options)
        .map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
    prop_assert_eq!(
        program.eval_record(&fields),
        program.eval(&bytes),
        "{} on {:?}",
        text,
        fields.as_slice()
    );
    let set =
        ProgramSet::compile(&[text], &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
    let (mut ours, mut theirs) = (Vec::new(), Vec::new());
    set.matching_record(&fields, &mut ours);
    set.matching(&bytes, &mut theirs);
    prop_assert_eq!(ours, theirs, "set of {} on {:?}", text, fields.as_slice());
    let program = ValueProgram::compile_with(value, &options)
        .map_err(|r| TestCaseError::fail(format!("{value}: {r}")))?;
    let ours = program.eval_record(&fields).map(|v| as_cel(&v));
    let theirs = program.eval(&bytes).map(|v| as_cel(&v));
    prop_assert_eq!(ours, theirs, "{} on {:?}", value, fields.as_slice());
    Ok(())
}

#[cfg(feature = "parse")]
proptest! {
    #![proptest_config(ProptestConfig::with_cases(2048))]

    #[test]
    fn fields_give_what_their_json_gives(
        text in expr(),
        value in value_expr(),
        rec in record(),
    ) {
        agree_on_fields(&text, &value, &rec)?;
    }
}

/// The JSON record a parser chain's fields stand for, built by splitting each
/// name at its dots: a name written twice is an array.
#[cfg(feature = "parse")]
fn nest(fields: &crate::parse::Fields<'_>) -> Json {
    use crate::parse::Hint;

    let mut root = Map::new();
    for (name, value) in fields.as_slice() {
        let text = String::from_utf8(value.bytes.to_vec()).unwrap_or_default();
        let leaf = match value.hint {
            Hint::Json => serde_json::from_str(&text).unwrap_or(Json::Null),
            Hint::Int | Hint::Float => serde_json::from_str::<Number>(&text)
                .map_or_else(|_| Json::String(text.clone()), Json::Number),
            Hint::Bool if text == "true" || text == "false" => Json::Bool(text == "true"),
            _ => Json::String(text),
        };
        let keys: Vec<&str> = name.split('.').collect();
        let Some((last, parents)) = keys.split_last() else {
            continue;
        };
        let mut at = &mut root;
        for key in parents {
            let next = at
                .entry((*key).to_owned())
                .or_insert_with(|| Json::Object(Map::new()));
            let Json::Object(map) = next else {
                panic!("{name} runs below a value");
            };
            at = map;
        }
        match at.get_mut(*last) {
            Some(Json::Array(items)) => items.push(leaf),
            Some(first) => *first = Json::Array(vec![first.take(), leaf]),
            None => {
                at.insert((*last).to_owned(), leaf);
            }
        }
    }
    Json::Object(root)
}

/// Filters over the fields of a `syslog > cef` chain give what they give over
/// the equal JSON record, errors included, and what cel gives there.
#[cfg(all(feature = "parse-syslog", feature = "parse-cef"))]
#[test]
fn a_syslog_cef_chain_reads_as_its_json_record() {
    use crate::format;
    use crate::parse::{Fields, ParsePlan, Parsers};

    use super::ErrorKind;

    let mut registry = Parsers::new();
    format::register_stock(&mut registry).expect("stock parsers register");
    let plan = ParsePlan::chain("syslog > cef", &registry).expect("the chain compiles");
    let line =
        b"<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 suser=bob";
    let mut fields = Fields::new();
    plan.parse_stateless(line, &mut fields);
    let record = nest(&fields);
    assert_eq!(record["cef"]["src"], json!("10.0.0.1"), "{record}");
    assert_eq!(record["severity"], json!(6), "{record}");
    let bytes = serde_json::to_vec(&record).expect("serialises");
    let error = Outcome::Error;
    let cases: &[(&str, Outcome)] = &[
        (r#"cef.name == "login ok""#, Outcome::True),
        (
            r#"cef.src.startsWith("10.") && hostname == "fw01""#,
            Outcome::True,
        ),
        (r#"cef.suser in ["alice", "bob"]"#, Outcome::True),
        (
            r#"cef.device_vendor == "Acme" || cef.dst == "x""#,
            Outcome::True,
        ),
        (r#"cef.src.matches("^10\\.0\\.")"#, Outcome::True),
        ("severity == 6 && pri > 100", Outcome::True),
        (r#"cef.severity == "5""#, Outcome::True),
        ("cef.severity == 5", Outcome::False),
        (r#"cef == "x""#, Outcome::False),
        ("has(cef.suser) && !has(cef.dst)", Outcome::True),
        ("has(cef.dst)", Outcome::False),
        ("cef.severity > 3", error(ErrorKind::TypeMismatch)),
        (r#"cef.contains("x")"#, error(ErrorKind::TypeMismatch)),
        ("has(cef.name.x)", error(ErrorKind::TypeMismatch)),
        (r#"cef.dst == "x""#, error(ErrorKind::MissingField)),
        ("cef.name.x == 1", error(ErrorKind::MissingField)),
        (r#"leef.src == "x""#, error(ErrorKind::MissingRoot)),
        (r#"!has(cef.dst) || cef.dst == "x""#, Outcome::True),
    ];
    let options = Options::with_regex();
    for &(text, want) in cases {
        let program = Program::compile_with(text, &options).expect(text);
        assert_eq!(program.eval_record(&fields), want, "{text} on {record}");
        assert_eq!(program.eval(&bytes), want, "{text} on the JSON {record}");
        assert_eq!(
            cel_says(text, &record),
            want_cel(want),
            "cel: {text} on {record}"
        );
    }
    let presence = Options {
        root_presence: true,
        ..Options::default()
    };
    for (text, want) in [("has(cef)", true), ("has(leef)", false)] {
        let program = Program::compile_with(text, &presence).expect(text);
        assert_eq!(program.matches_record(&fields), want, "{text}");
        assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
    }
    let texts: Vec<&str> = cases.iter().map(|(t, _)| *t).collect();
    let set = ProgramSet::compile(&texts, &options).expect("the set compiles");
    let (mut ours, mut theirs) = (Vec::new(), Vec::new());
    set.matching_record(&fields, &mut ours);
    set.matching(&bytes, &mut theirs);
    assert_eq!(ours, theirs);
    for value in [
        r#"cef.src + ":" + cef.suser"#,
        r#"severity > 3 ? "high" : "low""#,
        "cef",
        "pri + facility",
    ] {
        let program = ValueProgram::compile(value).expect(value);
        let ours = program.eval_record(&fields).map(|v| as_cel(&v));
        assert_eq!(ours, program.eval(&bytes).map(|v| as_cel(&v)), "{value}");
        assert_eq!(ours.ok(), cel_value(value, &record), "cel: {value}");
    }
}

/// A raw line reads as the record `{"message": line}`, and a field it lacks
/// is cel's error for that record.
#[test]
fn a_raw_line_reads_as_its_message_field() {
    use crate::record::Line;

    use super::ErrorKind;

    let line = "login denied for bob from 10.0.0.1";
    let record = json!({ "message": line });
    let bytes = serde_json::to_vec(&record).expect("serialises");
    let error = Outcome::Error;
    let cases: &[(&str, Outcome)] = &[
        (r#"message.contains("denied")"#, Outcome::True),
        (
            r#"message.startsWith("login") && !message.endsWith("x")"#,
            Outcome::True,
        ),
        (r#"message.matches("from [0-9.]+$")"#, Outcome::True),
        (r#"message == "login""#, Outcome::False),
        ("message > 3", error(ErrorKind::TypeMismatch)),
        ("has(message.x)", error(ErrorKind::TypeMismatch)),
        (r#"msg.contains("denied")"#, error(ErrorKind::MissingRoot)),
        (r#"message.x == "y""#, error(ErrorKind::MissingField)),
        (r#"msg == "x" || message.contains("bob")"#, Outcome::True),
    ];
    let options = Options::with_regex();
    for &(text, want) in cases {
        let program = Program::compile_with(text, &options).expect(text);
        assert_eq!(
            program.eval_record(Line::new(line.as_bytes())),
            want,
            "{text}"
        );
        assert_eq!(program.eval(&bytes), want, "{text} on the JSON");
        assert_eq!(cel_says(text, &record), want_cel(want), "cel: {text}");
        let renamed = Program::compile_with(&text.replace("message", "raw"), &options).expect(text);
        assert_eq!(
            renamed.eval_record(Line::named(line.as_bytes(), "raw")),
            want,
            "{text} on a line named raw"
        );
    }
    let presence = Options {
        root_presence: true,
        ..Options::default()
    };
    for (text, want) in [("has(message)", true), ("has(msg)", false)] {
        let program = Program::compile_with(text, &presence).expect(text);
        assert_eq!(
            program.matches_record(Line::new(line.as_bytes())),
            want,
            "{text}"
        );
        assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
    }
    let bad = Line::new(b"bad \xff byte");
    let program = Program::compile(r#"message.contains("bad")"#).expect("compiles");
    assert_eq!(program.eval_record(bad), error(ErrorKind::Malformed));
    let value = ValueProgram::compile(r#"message + "!""#).expect("compiles");
    assert_eq!(
        value.eval_record(Line::new(b"up")),
        Ok(Value::Str("up!".into()))
    );
}

/// cel's answer for an outcome: `None` for any error.
fn want_cel(outcome: Outcome) -> Option<bool> {
    match outcome {
        Outcome::True => Some(true),
        Outcome::False => Some(false),
        Outcome::Error(_) => None,
    }
}