Skip to main content

jsonpath_rust/query/
test_function.rs

1use crate::parser::model::{FnArg, TestFunction};
2use crate::query::context::JsonPathEvalContext;
3use crate::query::queryable::Queryable;
4use crate::query::state::{Data, Pointer, State};
5use crate::query::Query;
6use regex::Regex;
7use std::borrow::Cow;
8
9impl TestFunction {
10    pub fn apply<'a, T: Queryable>(&self, state: State<'a, T>) -> State<'a, T> {
11        self.process(state)
12    }
13}
14
15impl Query for FnArg {
16    fn process_with_context<'a, T: Queryable>(
17        &self,
18        step: State<'a, T>,
19        ctx: &mut JsonPathEvalContext,
20    ) -> State<'a, T> {
21        match self {
22            FnArg::Literal(lit) => lit.process_with_context(step, ctx),
23            FnArg::Test(test) => test.process_with_context(step, ctx),
24            FnArg::Filter(filter) => filter.process_with_context(step, ctx),
25        }
26    }
27}
28
29impl Query for TestFunction {
30    fn process_with_context<'a, T: Queryable>(
31        &self,
32        state: State<'a, T>,
33        ctx: &mut JsonPathEvalContext,
34    ) -> State<'a, T> {
35        match self {
36            TestFunction::Length(arg) => length(arg.process_with_context(state, ctx)),
37            TestFunction::Count(arg) => count(arg.process_with_context(state, ctx)),
38            TestFunction::Match(lhs, rhs) => regex(
39                lhs.process_with_context(state.clone(), ctx),
40                rhs.process_with_context(state, ctx),
41                false,
42                ctx,
43            ),
44            TestFunction::Search(lhs, rhs) => regex(
45                lhs.process_with_context(state.clone(), ctx),
46                rhs.process_with_context(state, ctx),
47                true,
48                ctx,
49            ),
50            TestFunction::Custom(name, args) => custom(name, args, state, ctx),
51            TestFunction::Value(arg) => value(arg.process_with_context(state, ctx)),
52            _ => State::nothing(state.root),
53        }
54    }
55}
56
57fn custom<'a, T: Queryable>(
58    name: &str,
59    args: &Vec<FnArg>,
60    state: State<'a, T>,
61    ctx: &mut JsonPathEvalContext,
62) -> State<'a, T> {
63    let args = args
64        .into_iter()
65        .map(|v| v.process_with_context(state.clone(), ctx))
66        .flat_map(|v| match v.data {
67            Data::Value(v) => vec![Cow::Owned(v)],
68            Data::Ref(Pointer { inner, .. }) => vec![Cow::Borrowed(inner)],
69            Data::Refs(v) => v.into_iter().map(|v| Cow::Borrowed(v.inner)).collect(),
70            _ => vec![],
71        })
72        .collect::<Vec<_>>();
73
74    State::data(
75        state.root,
76        Data::Value(Queryable::extension_custom(name, args)),
77    )
78}
79
80/// Returns the length/size of the object.
81///
82/// # Returns
83///
84/// Returns a `Progress` enum containing either:
85/// - `Progress::Data` with a vector of references to self and the query path for strings/arrays/objects
86/// - `Progress::Nothing` for other types
87///
88/// The returned length follows JSON path length() function semantics based on the type:
89/// - String type: Number of Unicode scalar values
90/// - Array type: Number of elements
91/// - Object type: Number of members
92/// - Other types: Nothing
93fn length<T: Queryable>(state: State<T>) -> State<T> {
94    let from_item = |item: &T| {
95        if let Some(v) = item.as_str() {
96            State::i64(v.chars().count() as i64, state.root)
97        } else if let Some(items) = item.as_array() {
98            State::i64(items.len() as i64, state.root)
99        } else if let Some(items) = item.as_object() {
100            State::i64(items.len() as i64, state.root)
101        } else {
102            State::nothing(state.root)
103        }
104    };
105
106    match state.data {
107        Data::Ref(Pointer { inner, .. }) => from_item(inner),
108        Data::Refs(items) => State::i64(items.len() as i64, state.root),
109        Data::Value(item) => from_item(&item),
110        Data::Nothing => State::nothing(state.root),
111    }
112}
113
114/// The count() function extension provides a way
115/// to obtain the number of nodes in a nodelist
116/// and make that available for further processing in the filter expression
117fn count<T: Queryable>(state: State<T>) -> State<T> {
118    let to_state = |count: i64| State::i64(count, state.root);
119
120    match state.data {
121        Data::Ref(..) | Data::Value(..) => to_state(1),
122        Data::Refs(items) => to_state(items.len() as i64),
123        Data::Nothing => State::nothing(state.root),
124    }
125}
126/// The match() function extension provides
127/// a way to check whether (the entirety of; see Section 2.4.7)
128/// a given string matches a given regular expression,
129/// which is in the form described in [RFC9485].
130///
131/// Its arguments are instances of ValueType
132/// (possibly taken from a singular query,
133/// as for the first argument in the example above).
134/// If the first argument is not a string
135/// or the second argument is not a string conforming to [RFC9485],
136/// the result is LogicalFalse. Otherwise, the string that is the first argument is matched against
137/// the I-Regexp contained in the string that is the second argument; the result is LogicalTrue
138/// if the string matches the I-Regexp and is LogicalFalse otherwise.
139fn regex<'a, T: Queryable>(
140    lhs: State<'a, T>,
141    rhs: State<'a, T>,
142    substr: bool,
143    ctx: &mut JsonPathEvalContext,
144) -> State<'a, T> {
145    let to_state = |b| State::bool(b, lhs.root);
146    let regex = |v: &str, r: &Regex| {
147        if substr {
148            r.find(v).is_some()
149        } else {
150            r.is_match(v)
151        }
152    };
153    let to_str = |s: State<'a, T>| match s.data {
154        Data::Value(v) => v.as_str().map(|s| s.to_string()),
155        Data::Ref(Pointer { inner, .. }) => inner.as_str().map(|s| s.to_string()),
156        _ => None,
157    };
158
159    match (to_str(lhs), to_str(rhs)) {
160        (Some(lhs), Some(rhs)) => ctx
161            .regex(&prepare_regex(rhs, substr))
162            .map(|re| to_state(regex(&lhs, &re)))
163            .unwrap_or(to_state(false)),
164        _ => to_state(false),
165    }
166}
167
168/// Translates an I-Regexp ([RFC9485]) into the syntax of the `regex` crate.
169///
170/// An I-Regexp `.` matches any character except `\n` and `\r` (RFC9485, section 5.3),
171/// but the crate's `.` matches `\r`, so `.` outside a character class becomes `[^\n\r]`.
172/// For match() the whole pattern is anchored, so `a|b` does not match "ab".
173fn prepare_regex(pattern: String, substring: bool) -> String {
174    let mut translated = String::with_capacity(pattern.len());
175    let mut chars = pattern.chars();
176    let mut in_class = false;
177    while let Some(c) = chars.next() {
178        match c {
179            '\\' => {
180                translated.push(c);
181                if let Some(escaped) = chars.next() {
182                    translated.push(escaped);
183                }
184            }
185            '[' if !in_class => {
186                in_class = true;
187                translated.push(c);
188            }
189            ']' if in_class => {
190                in_class = false;
191                translated.push(c);
192            }
193            '.' if !in_class => translated.push_str(r"[^\n\r]"),
194            _ => translated.push(c),
195        }
196    }
197
198    if substring {
199        translated
200    } else {
201        format!("^(?:{translated})$")
202    }
203}
204
205fn value<T: Queryable>(state: State<T>) -> State<T> {
206    match state.data {
207        Data::Ref(..) | Data::Value(..) => state,
208        Data::Refs(items) if items.len() == 1 => {
209            State::data(state.root, Data::Ref(items[0].clone()))
210        }
211        _ => State::nothing(state.root),
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use crate::parser::model::Segment;
218    use crate::parser::model::Selector;
219    use crate::parser::model::Test;
220    use crate::parser::model::TestFunction;
221    use crate::query::context::JsonPathEvalContext;
222    use crate::query::state::{Data, Pointer, State};
223    use crate::query::test_function::{regex, FnArg};
224    use crate::query::Query;
225    use crate::{arg, q_segment, segment, selector, test, test_fn};
226    use serde_json::json;
227
228    #[test]
229    fn test_len() {
230        let json = json!({"array": [1,2,3]});
231        let state = State::root(&json);
232
233        let query = test_fn!(length arg!(t test!(@ segment!(selector!(array)))));
234        let res = query.process(state);
235
236        assert_eq!(res.ok_val(), Some(json!(3)));
237    }
238
239    #[test]
240    fn test_match_1() {
241        let json = json!({"a": "abc sdgfudsf","b": "abc.*"});
242        let state = State::root(&json);
243
244        let query = test_fn!(match
245            arg!(t test!(@ segment!(selector!(a)))),
246            arg!(t test!(@ segment!(selector!(b))))
247        );
248        let res = query.process(state);
249
250        assert_eq!(res.ok_val(), Some(json!(true)));
251    }
252
253    #[test]
254    fn test_count_1() {
255        let json = json!({"array": [1,2,3]});
256        let state = State::root(&json);
257
258        let query = test_fn!(count arg!(t test!(@ segment!(selector!(array)))));
259        let res = query.process(state);
260
261        assert_eq!(res.ok_val(), Some(json!(1)));
262    }
263
264    #[test]
265    fn test_search() {
266        let json = json!("123");
267        let state = State::root(&json);
268        let reg = State::str("[a-z]+", &json);
269
270        let res = regex(state, reg, true, &mut JsonPathEvalContext::default());
271
272        assert_eq!(res.ok_val(), Some(json!(false)));
273    }
274
275    #[test]
276    fn test_match() {
277        let json = json!("bbab");
278        let state = State::root(&json);
279        let reg = State::str("^b.?b$", &json);
280
281        let res = regex(state, reg, false, &mut JsonPathEvalContext::default());
282
283        assert_eq!(res.ok_val(), Some(json!(false)));
284    }
285}