grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
use super::lex::{self, Tok};
use super::parse::{Ast, Cmp, Lit, Method, Path, parse};

fn path(p: &str) -> Path {
    Path(p.split('.').map(str::to_owned).collect())
}

fn eq(p: &str, v: &str) -> Ast {
    Ast::Cmp(path(p), Cmp::Eq, Lit::Str(v.to_owned()))
}

#[test]
fn the_subset_parses_to_its_tree() {
    let cases: Vec<(&str, Ast)> = vec![
        ("has(r._table)", Ast::Has(path("r._table"), 0..3)),
        ("has(_table)", Ast::Has(path("_table"), 0..3)),
        (
            "!has(_table)",
            Ast::Not(Box::new(Ast::Has(path("_table"), 1..4))),
        ),
        ("!has(a.b)", Ast::Not(Box::new(Ast::Has(path("a.b"), 1..4)))),
        (r#"status == "poison""#, eq("status", "poison")),
        (r#""poison" == status"#, eq("status", "poison")),
        (
            "3 < severity",
            Ast::Cmp(path("severity"), Cmp::Gt, Lit::Int(3)),
        ),
        (
            "event.system.event_id == 5158",
            Ast::Cmp(path("event.system.event_id"), Cmp::Eq, Lit::Int(5158)),
        ),
        (
            "x >= -1.5e2",
            Ast::Cmp(path("x"), Cmp::Ge, Lit::Double(-150.0)),
        ),
        ("x != 7u", Ast::Cmp(path("x"), Cmp::Ne, Lit::Uint(7))),
        ("x == null", Ast::Cmp(path("x"), Cmp::Eq, Lit::Null)),
        ("x == true", Ast::Cmp(path("x"), Cmp::Eq, Lit::Bool(true))),
        ("true", Ast::Const(true)),
        (
            r#"event.network.direction == "outbound" && event.dns.type == "query""#,
            Ast::And(vec![
                eq("event.network.direction", "outbound"),
                eq("event.dns.type", "query"),
            ]),
        ),
        (
            r#"event.dns.type == "query" || event.dns.type == "answer""#,
            Ast::Or(vec![
                eq("event.dns.type", "query"),
                eq("event.dns.type", "answer"),
            ]),
        ),
        (
            r#"!(a == "x" && b == "y") || c == "z""#,
            Ast::Or(vec![
                Ast::Not(Box::new(Ast::And(vec![eq("a", "x"), eq("b", "y")]))),
                eq("c", "z"),
            ]),
        ),
        (
            r#"host.matches("^prod-.*$")"#,
            Ast::Method(path("host"), Method::Matches, "^prod-.*$".to_owned()),
        ),
        (
            r#"a["b-c"].contains('x')"#,
            Ast::Method(
                Path(vec!["a".to_owned(), "b-c".to_owned()]),
                Method::Contains,
                "x".to_owned(),
            ),
        ),
        (
            r#"t in ["query", "answer",]"#,
            Ast::In(
                path("t"),
                vec![Lit::Str("query".to_owned()), Lit::Str("answer".to_owned())],
            ),
        ),
        (
            "a.`b-c` == 'x' // trailing comment",
            Ast::Cmp(
                Path(vec!["a".to_owned(), "b-c".to_owned()]),
                Cmp::Eq,
                Lit::Str("x".to_owned()),
            ),
        ),
        (
            r#"m.startsWith(r"\d")"#,
            Ast::Method(path("m"), Method::StartsWith, r"\d".to_owned()),
        ),
        (
            r#"m.endsWith("a\x41é\101\n")"#,
            Ast::Method(path("m"), Method::EndsWith, "aA\u{e9}A\n".to_owned()),
        ),
        (
            "m == '''two\nlines'''",
            Ast::Cmp(path("m"), Cmp::Eq, Lit::Str("two\nlines".to_owned())),
        ),
    ];
    for (text, want) in cases {
        assert_eq!(parse(text).as_ref(), Ok(&want), "{text}");
    }
}

#[test]
fn forms_outside_the_subset_are_refused_where_they_start() {
    let cases: &[(&str, &str)] = &[
        ("a.size() > 3", "size"),
        ("size(a) > 3", "size"),
        ("a + 1 == 3", "+"),
        ("a == b", "b"),
        ("a ? b : c", "?"),
        ("a.exists(x, x == 1)", "exists"),
        ("a == b'x'", "b'x'"),
        ("a", "a"),
        ("(a == 'x'", ""),
        (r#""x".contains(a)"#, "\"x\""),
        ("a.contains(b)", "b"),
        ("a == 'x' b", "b"),
        ("in == 'x'", "in"),
        ("has(a[\"b\"])", "has"),
    ];
    for &(text, at) in cases {
        let refusal = parse(text).expect_err(text);
        assert_eq!(&text[refusal.span.clone()], at, "{text}: {refusal}");
    }
}

#[test]
fn text_cel_rejects_is_a_lexing_refusal() {
    for text in [
        "a == 'open",
        "a == 'line\nbreak'",
        r"a == '\q'",
        "a == `",
        "a == 99999999999999999999",
    ] {
        assert!(lex::tokens(text).is_err(), "{text}");
    }
    // A bad escape's span ends after the escaped character, whatever its width.
    for (text, escape) in [(r"a == '\q'", r"\q"), ("a == 'x\\\u{e9}'", "\\\u{e9}")] {
        let refusal = parse(text).expect_err(text);
        assert_eq!(
            text.get(refusal.span.clone()),
            Some(escape),
            "{text}: {refusal}"
        );
    }
    let toks: Vec<Tok<'_>> = lex::tokens("1 0x1F 2u 0x2u .5 1e3 1.5")
        .expect("numbers")
        .into_iter()
        .map(|t| t.tok)
        .collect();
    assert_eq!(
        toks,
        [
            Tok::Int(1),
            Tok::Int(31),
            Tok::Uint(2),
            Tok::Uint(2),
            Tok::Double(0.5),
            Tok::Double(1000.0),
            Tok::Double(1.5)
        ]
    );
}

#[test]
fn raw_json_spellings_read_as_their_values() {
    use super::{ErrorKind, Options, Outcome, Program};
    let presence = Options {
        root_presence: true,
        ..Options::default()
    };
    let cases: &[(&str, &[u8], Outcome)] = &[
        (r#"f == "aa""#, br#"{"f":"aa"}"#, Outcome::True),
        (r#"f == "aa""#, br#"{"f":"\u0061a"}"#, Outcome::True),
        (r#"f == "x""#, br#"{"\u0066":"x"}"#, Outcome::True),
        (r#"a.b == "x""#, br#"{"a":{"\u0062":"x"}}"#, Outcome::True),
        (r#"f == "a\"b""#, br#"{"f":"a\"b"}"#, Outcome::True),
        (
            r#"f.startsWith("a")"#,
            br#"{ "f" : "abc" , "g" : 1 }"#,
            Outcome::True,
        ),
        ("has(a.b)", br#"{"a" : { "b" : null } }"#, Outcome::True),
        ("has(_table)", br#"{"_table":null}"#, Outcome::True),
        ("has(_table)", br#"{"_tables":1}"#, Outcome::False),
        ("!has(_table)", br#"{"a":1}"#, Outcome::True),
        (
            "has(_table) && t == 1",
            br#"{"_table":"x","t":1}"#,
            Outcome::True,
        ),
        ("has(_table)", b"[1]", Outcome::False),
        (
            "has(_table)",
            br#"{"_table":}"#,
            Outcome::Error(ErrorKind::Malformed),
        ),
        ("f == 1", b"[1]", Outcome::Error(ErrorKind::MissingRoot)),
        ("f == 1", b"", Outcome::Error(ErrorKind::MissingRoot)),
        ("f == 1", br#"{"f":}"#, Outcome::Error(ErrorKind::Malformed)),
        (
            "a.b == 1",
            br#"{"a":{"c":1}}"#,
            Outcome::Error(ErrorKind::MissingField),
        ),
        (
            r#"a.startsWith("x")"#,
            br#"{"a":1}"#,
            Outcome::Error(ErrorKind::TypeMismatch),
        ),
        ("f == 1 || g == 2", br#"{"g":2}"#, Outcome::True),
        ("f == 1 && g == 2", br#"{"g":3}"#, Outcome::False),
    ];
    for (text, json, want) in cases {
        let p = Program::compile_with(text, &presence).expect(text);
        assert_eq!(
            p.eval(json),
            *want,
            "{text} on {}",
            String::from_utf8_lossy(json)
        );
    }
}

#[test]
fn lowering_refuses_what_it_cant_run() {
    use super::{MAX_FIELDS, Program};
    let wide = (0..=MAX_FIELDS)
        .map(|i| format!("f{i} == 1"))
        .collect::<Vec<_>>()
        .join(" && ");
    for text in [
        r#"host.matches("^prod-")"#,
        "a < true",
        "a >= null",
        "has(_table)",
        "!has(a.b) || has(c)",
        wide.as_str(),
    ] {
        assert!(Program::compile(text).is_err(), "{text}");
    }
    for text in ["has(_table)", "! has(  _table  )", "!has(a.b) || has(c)"] {
        let refusal = Program::compile(text).expect_err(text);
        assert_eq!(&text[refusal.span.clone()], "has", "{text}: {refusal:?}");
    }
    let p = Program::compile(r#"!(a.b == "x" && c.contains("yz")) || d.startsWith("q")"#)
        .expect("compiles");
    assert_eq!(
        p.to_string(),
        r#"or(not(and(Eq(a.b, Str("x")), memmem(c, "yz"))), prefix(d, "q"))"#
    );
}