forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

ast.rs458 lines, 13.6 KiBHistoryRawDownload
1use crate::jsonpath::errors::JSONPathError;
2use crate::jsonpath::JSONPathParser;
3use std::fmt::{self, Write};
4
5#[derive(Debug, Clone)]
6pub struct Query {
7 pub segments: Segment,
8}
9
10#[derive(Debug, Clone)]
11pub enum Segment {
12 Root {},
13 Child {
14 left: Box<Segment>,
15 selectors: Vec<Selector>,
16 },
17 Recursive {
18 left: Box<Segment>,
19 selectors: Vec<Selector>,
20 },
21}
22
23#[derive(Debug, Clone)]
24pub enum Selector {
25 Name {
26 name: String,
27 },
28 Index {
29 index: i64,
30 },
31 Slice {
32 start: Option<i64>,
33 stop: Option<i64>,
34 step: Option<i64>,
35 },
36 Wild {},
37 Filter {
38 expression: Box<FilterExpression>,
39 },
40}
41
42#[derive(Debug, Clone)]
43pub enum FilterExpression {
44 True_ {},
45 False_ {},
46 Null {},
47 Array {
48 values: Vec<FilterExpression>,
49 },
50 StringLiteral {
51 value: String,
52 },
53 Int {
54 value: i64,
55 },
56 Float {
57 value: f64,
58 },
59 Not {
60 expression: Box<FilterExpression>,
61 },
62 Logical {
63 left: Box<FilterExpression>,
64 operator: LogicalOperator,
65 right: Box<FilterExpression>,
66 },
67 Comparison {
68 left: Box<FilterExpression>,
69 operator: ComparisonOperator,
70 right: Box<FilterExpression>,
71 },
72 RelativeQuery {
73 query: Box<Query>,
74 },
75 RootQuery {
76 query: Box<Query>,
77 },
78 Function {
79 name: String,
80 args: Vec<FilterExpression>,
81 },
82}
83
84#[derive(Debug, Clone)]
85pub enum LogicalOperator {
86 And,
87 Or,
88}
89
90#[derive(Debug, Clone)]
91pub enum ComparisonOperator {
92 Eq,
93 Ne,
94 Ge,
95 Gt,
96 Le,
97 Lt,
98 Contains,
99 In,
100}
101
102impl Query {
103 pub fn standard(expr: &str) -> Result<Self, JSONPathError> {
104 JSONPathParser::new().parse(expr)
105 }
106
107 pub fn is_singular(&self) -> bool {
108 self.segments.is_singular()
109 }
110}
111
112impl Segment {
113 // Returns `true` if this query can resolve to at most one node, or `false` otherwise.
114 pub fn is_singular(&self) -> bool {
115 match self {
116 Segment::Child { left, selectors } => {
117 selectors.len() == 1
118 && selectors.first().is_some_and(|selector| {
119 matches!(selector, Selector::Name { .. } | Selector::Index { .. })
120 })
121 && left.is_singular()
122 }
123 Segment::Recursive { .. } => false,
124 Segment::Root {} => true,
125 }
126 }
127}
128
129impl FilterExpression {
130 pub fn is_literal(&self) -> bool {
131 matches!(
132 self,
133 FilterExpression::True_ { .. }
134 | FilterExpression::False_ { .. }
135 | FilterExpression::Null { .. }
136 | FilterExpression::StringLiteral { .. }
137 | FilterExpression::Int { .. }
138 | FilterExpression::Float { .. }
139 | FilterExpression::Array { .. }
140 )
141 }
142}
143
144impl fmt::Display for Query {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 write!(f, "${}", self.segments)
147 }
148}
149
150impl fmt::Display for Segment {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 match self {
153 Segment::Child { left, selectors } => write!(
154 f,
155 "{}[{}]",
156 left,
157 selectors
158 .iter()
159 .map(|s| s.to_string())
160 .collect::<Vec<String>>()
161 .join(", ")
162 ),
163 Segment::Recursive { left, selectors } => write!(
164 f,
165 "{}..[{}]",
166 left,
167 selectors
168 .iter()
169 .map(|s| s.to_string())
170 .collect::<Vec<String>>()
171 .join(", ")
172 ),
173 Segment::Root {} => Ok(()),
174 }
175 }
176}
177
178impl fmt::Display for Selector {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 match self {
181 Selector::Name { name, .. } => write!(f, "'{name}'"),
182 Selector::Index {
183 index: array_index, ..
184 } => write!(f, "{array_index}"),
185 Selector::Slice {
186 start, stop, step, ..
187 } => {
188 write!(
189 f,
190 "{}:{}:{}",
191 start
192 .and_then(|i| Some(i.to_string()))
193 .unwrap_or(String::from("")),
194 stop.and_then(|i| Some(i.to_string()))
195 .unwrap_or(String::from("")),
196 step.and_then(|i| Some(i.to_string()))
197 .unwrap_or(String::from("1")),
198 )
199 }
200 Selector::Wild { .. } => f.write_char('*'),
201 Selector::Filter { expression, .. } => write!(f, "?{expression}"),
202 }
203 }
204}
205
206impl fmt::Display for FilterExpression {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 match self {
209 FilterExpression::True_ { .. } => f.write_str("true"),
210 FilterExpression::False_ { .. } => f.write_str("false"),
211 FilterExpression::Null { .. } => f.write_str("null"),
212 FilterExpression::StringLiteral { value, .. } => write!(f, "'{value}'"),
213 FilterExpression::Array { values, .. } => {
214 write!(
215 f,
216 "[{}]",
217 values
218 .iter()
219 .map(|e| e.to_string())
220 .collect::<Vec<String>>()
221 .join(", ")
222 )
223 }
224 FilterExpression::Int { value, .. } => write!(f, "{value}"),
225 FilterExpression::Float { value, .. } => write!(f, "{value}"),
226 FilterExpression::Not { expression, .. } => write!(f, "!{expression}"),
227 FilterExpression::Logical {
228 left,
229 operator,
230 right,
231 ..
232 } => write!(f, "({left} {operator} {right})"),
233 FilterExpression::Comparison {
234 left,
235 operator,
236 right,
237 ..
238 } => write!(f, "{left} {operator} {right}"),
239 FilterExpression::RelativeQuery { query, .. } => {
240 write!(f, "@{}", query.segments)
241 }
242 FilterExpression::RootQuery { query, .. } => {
243 write!(f, "${}", query.segments)
244 }
245 FilterExpression::Function { name, args, .. } => {
246 write!(
247 f,
248 "{}({})",
249 name,
250 args.iter()
251 .map(|a| a.to_string())
252 .collect::<Vec<String>>()
253 .join(", ")
254 )
255 }
256 }
257 }
258}
259
260impl fmt::Display for LogicalOperator {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 match self {
263 LogicalOperator::And => f.write_str("&&"),
264 LogicalOperator::Or => f.write_str("||"),
265 }
266 }
267}
268
269impl fmt::Display for ComparisonOperator {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 match self {
272 ComparisonOperator::Eq => f.write_str("=="),
273 ComparisonOperator::Ne => f.write_str("!="),
274 ComparisonOperator::Ge => f.write_str(">="),
275 ComparisonOperator::Gt => f.write_str(">"),
276 ComparisonOperator::Le => f.write_str("<="),
277 ComparisonOperator::Lt => f.write_str("<"),
278 ComparisonOperator::Contains => f.write_str("contains"),
279 ComparisonOperator::In => f.write_str("in"),
280 }
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 fn parse(expr: &str) -> Query {
289 Query::standard(expr).unwrap()
290 }
291
292 fn relative_query(selector: Selector) -> Query {
293 Query {
294 segments: Segment::Child {
295 left: Box::new(Segment::Root {}),
296 selectors: vec![selector],
297 },
298 }
299 }
300
301 #[test]
302 fn query_standard_reports_singular_queries_correctly() {
303 let cases = [
304 ("$", true),
305 ("$.store", true),
306 ("$['store']", true),
307 ("$.store.books[0]", true),
308 ("$.store.books[0][1]", true),
309 ("$.store.books[0, 1]", false),
310 ("$.store.books[*]", false),
311 ("$.store.books[?(@.available == true)]", false),
312 ("$.store..title", false),
313 ];
314
315 for (expr, expected) in cases {
316 assert_eq!(
317 parse(expr).is_singular(),
318 expected,
319 "{expr} should have singular={expected}"
320 );
321 }
322 }
323
324 #[test]
325 fn filter_expression_is_literal_matches_jsonpath_contract() {
326 let literal_cases = [
327 FilterExpression::True_ {},
328 FilterExpression::False_ {},
329 FilterExpression::Null {},
330 FilterExpression::StringLiteral {
331 value: "hello".to_owned(),
332 },
333 FilterExpression::Int { value: 42 },
334 FilterExpression::Float { value: 3.5 },
335 FilterExpression::Array {
336 values: vec![
337 FilterExpression::Int { value: 1 },
338 FilterExpression::StringLiteral {
339 value: "two".to_owned(),
340 },
341 FilterExpression::Array {
342 values: vec![FilterExpression::Null {}],
343 },
344 ],
345 },
346 ];
347
348 for expr in literal_cases {
349 assert!(expr.is_literal(), "{expr:?} should be literal");
350 }
351
352 let non_literal_cases = [
353 FilterExpression::RelativeQuery {
354 query: Box::new(relative_query(Selector::Name {
355 name: "title".to_owned(),
356 })),
357 },
358 FilterExpression::RootQuery {
359 query: Box::new(parse("$.store.books[0]")),
360 },
361 FilterExpression::Function {
362 name: "count".to_owned(),
363 args: vec![FilterExpression::RelativeQuery {
364 query: Box::new(relative_query(Selector::Name {
365 name: "title".to_owned(),
366 })),
367 }],
368 },
369 FilterExpression::Not {
370 expression: Box::new(FilterExpression::True_ {}),
371 },
372 FilterExpression::Logical {
373 left: Box::new(FilterExpression::True_ {}),
374 operator: LogicalOperator::And,
375 right: Box::new(FilterExpression::False_ {}),
376 },
377 FilterExpression::Comparison {
378 left: Box::new(FilterExpression::Int { value: 1 }),
379 operator: ComparisonOperator::Eq,
380 right: Box::new(FilterExpression::Int { value: 2 }),
381 },
382 ];
383
384 for expr in non_literal_cases {
385 assert!(!expr.is_literal(), "{expr:?} should not be literal");
386 }
387 }
388
389 #[test]
390 fn query_and_ast_display_are_stable() {
391 let query = parse("$.store.books[0]");
392 assert_eq!(query.to_string(), "$['store']['books'][0]");
393 assert_eq!(
394 parse("$.store.books[0, 1]").to_string(),
395 "$['store']['books'][0, 1]"
396 );
397 assert_eq!(parse("$.store..title").to_string(), "$['store']..['title']");
398
399 let selector_display = [
400 (
401 Selector::Name {
402 name: "field".into(),
403 },
404 "'field'",
405 ),
406 (Selector::Index { index: -2 }, "-2"),
407 (
408 Selector::Slice {
409 start: Some(1),
410 stop: Some(3),
411 step: None,
412 },
413 "1:3:1",
414 ),
415 (Selector::Wild {}, "*"),
416 ];
417
418 for (selector, expected) in selector_display {
419 assert_eq!(selector.to_string(), expected);
420 }
421
422 let filter_display = FilterExpression::Logical {
423 left: Box::new(FilterExpression::Comparison {
424 left: Box::new(FilterExpression::RelativeQuery {
425 query: Box::new(relative_query(Selector::Name {
426 name: "available".to_owned(),
427 })),
428 }),
429 operator: ComparisonOperator::Eq,
430 right: Box::new(FilterExpression::True_ {}),
431 }),
432 operator: LogicalOperator::And,
433 right: Box::new(FilterExpression::Not {
434 expression: Box::new(FilterExpression::Function {
435 name: "count".to_owned(),
436 args: vec![FilterExpression::RootQuery {
437 query: Box::new(parse("$.store.books[*]")),
438 }],
439 }),
440 }),
441 };
442 assert_eq!(
443 filter_display.to_string(),
444 "(@['available'] == true && !count($['store']['books'][*]))"
445 );
446
447 assert_eq!(LogicalOperator::And.to_string(), "&&");
448 assert_eq!(LogicalOperator::Or.to_string(), "||");
449 assert_eq!(ComparisonOperator::Eq.to_string(), "==");
450 assert_eq!(ComparisonOperator::Ne.to_string(), "!=");
451 assert_eq!(ComparisonOperator::Ge.to_string(), ">=");
452 assert_eq!(ComparisonOperator::Gt.to_string(), ">");
453 assert_eq!(ComparisonOperator::Le.to_string(), "<=");
454 assert_eq!(ComparisonOperator::Lt.to_string(), "<");
455 assert_eq!(ComparisonOperator::Contains.to_string(), "contains");
456 assert_eq!(ComparisonOperator::In.to_string(), "in");
457 }
458}