Skip to main content

sokf_core/query/
expr.rs

1//! `Expr` is a compiled JMESPath expression over `serde_json::Value`. The
2//! `jmespath` crate parses the expression, and the `eval` module walks its
3//! syntax tree, so an object read from the input keeps its key order.
4
5use std::fmt;
6
7use serde_json::Value;
8
9use super::eval;
10use crate::{Error, Result};
11
12/// `Expr` is a compiled JMESPath expression, kept with the source text it
13/// was compiled from.
14#[derive(Clone)]
15pub struct Expr {
16    source: String,
17    compiled: jmespath::Expression<'static>,
18}
19
20impl Expr {
21    /// `compile` compiles `source`. A parse failure is an [`Error::Query`]
22    /// that carries the `jmespath` crate's message.
23    // sokf-implements: CLI-4_AC-17
24    // sokf-implements: CLI-7_AC-21
25    pub fn compile(source: &str) -> Result<Expr> {
26        let compiled = jmespath::compile(source)
27            .map_err(|e| Error::Query(e.to_string().trim_end().to_string()))?;
28        Ok(Expr {
29            source: source.to_string(),
30            compiled,
31        })
32    }
33
34    /// `source` returns the expression as written.
35    pub fn source(&self) -> &str {
36        &self.source
37    }
38
39    /// `eval` evaluates the expression against `value`. An object in the
40    /// result keeps the key order that it was read with. An object literal in
41    /// the expression is the exception: its keys come out sorted, because the
42    /// `jmespath` crate parses it into a sorted map. A runtime
43    /// failure is an [`Error::Query`].
44    // sokf-implements: CLI-4_AC-14
45    // sokf-implements: CLI-4_AC-17
46    // sokf-implements: CLI-7_AC-22
47    pub fn eval(&self, value: &Value) -> Result<Value> {
48        eval::eval(self.compiled.as_ast(), value).map_err(|e| Error::Query(e.to_string()))
49    }
50
51    /// `truthy` evaluates the expression against `value` and returns whether
52    /// the result is true by JMESPath's rules, as `graph` filters require
53    /// (CLI-7_AC-44). It returns `false` when the evaluation fails at
54    /// runtime.
55    // sokf-implements: CLI-7_AC-43
56    // sokf-implements: CLI-7_AC-44
57    // sokf-implements: CLI-7_AC-11
58    pub fn truthy(&self, value: &Value) -> bool {
59        eval::eval(self.compiled.as_ast(), value).is_ok_and(|v| eval::truthy(&v))
60    }
61}
62
63impl fmt::Debug for Expr {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_tuple("Expr").field(&self.source).finish()
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use serde_json::json;
72
73    use super::*;
74
75    #[test]
76    fn compiles_or_refuses_with_the_crate_message() {
77        let e = Expr::compile("type=='Decision'").unwrap();
78        assert_eq!(e.source(), "type=='Decision'");
79        assert!(format!("{e:?}").contains("type=='Decision'"));
80        let err = Expr::compile("nodes[?").unwrap_err();
81        assert!(matches!(err, Error::Query(_)));
82        assert!(err.to_string().starts_with("query: "), "{err}");
83    }
84
85    #[test]
86    fn eval_projects_and_reports_runtime_failures() {
87        let e = Expr::compile("nodes[?kind=='document'].id").unwrap();
88        let value = json!({"nodes": [
89            {"kind": "document", "id": "a"},
90            {"kind": "file"},
91            {"kind": "document", "id": "b"}
92        ]});
93        assert_eq!(e.eval(&value).unwrap(), json!(["a", "b"]));
94        assert_eq!(
95            Expr::compile("nope").unwrap().eval(&value).unwrap(),
96            Value::Null
97        );
98        let bad = Expr::compile("contains(tags, 'core')").unwrap();
99        assert!(matches!(bad.eval(&json!({})), Err(Error::Query(_))));
100    }
101
102    // sokf-tests: CLI-7_AC-44
103    // sokf-tests: CLI-7_AC-11
104    #[test]
105    fn truthy_follows_jmespath_and_treats_failure_as_false() {
106        let doc = json!({"type": "Decision", "tags": ["core"], "title": "", "n": 0, "list": [], "map": {}});
107        let cases = [
108            ("type=='Decision'", true),
109            ("type=='Issue'", false),
110            ("contains(tags, 'core')", true),
111            ("title", false),
112            ("n", true),
113            ("list", false),
114            ("map", false),
115            ("missing", false),
116            ("!missing", true),
117            ("tags", true),
118        ];
119        for (src, expected) in cases {
120            assert_eq!(Expr::compile(src).unwrap().truthy(&doc), expected, "{src}");
121        }
122        // `tags` is absent, so `contains` fails with a type error, which
123        // `truthy` treats as false.
124        let no_tags = json!({"type": "Decision"});
125        assert!(
126            !Expr::compile("contains(tags, 'core')")
127                .unwrap()
128                .truthy(&no_tags)
129        );
130        assert!(Expr::compile("!resource").unwrap().truthy(&no_tags));
131    }
132}