forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

parser.rs708 lines, 24.3 KiBHistoryRawDownload
1//! A JSONPath parser using [pest].
2//!
3//! Refer to `jsonpath.pest` and the [pest book].
4//!
5//! [pest]: https://pest.rs/
6//! [pest book]: https://pest.rs/book/
7
8use std::{collections::HashMap, ops::RangeInclusive};
9
10use pest::{iterators::Pair, Parser};
11use pest_derive::Parser;
12
13use crate::jsonpath::ast::{
14 ComparisonOperator, FilterExpression, LogicalOperator, Segment, Selector,
15};
16use crate::jsonpath::errors::JSONPathError;
17use crate::jsonpath::Query;
18
19#[derive(Parser)]
20#[grammar = "jsonpath/jsonpath.pest"]
21struct JSONPath;
22
23#[derive(Debug)]
24pub enum ExpressionType {
25 Logical,
26 Nodes,
27 Value,
28}
29
30#[derive(Debug)]
31pub struct FunctionSignature {
32 pub param_types: Vec<ExpressionType>,
33 pub return_type: ExpressionType,
34}
35
36pub fn standard_functions() -> HashMap<String, FunctionSignature> {
37 let mut functions = HashMap::new();
38
39 functions.insert(
40 "count".to_owned(),
41 FunctionSignature {
42 param_types: vec![ExpressionType::Nodes],
43 return_type: ExpressionType::Value,
44 },
45 );
46
47 functions.insert(
48 "length".to_owned(),
49 FunctionSignature {
50 param_types: vec![ExpressionType::Value],
51 return_type: ExpressionType::Value,
52 },
53 );
54
55 functions.insert(
56 "match".to_owned(),
57 FunctionSignature {
58 param_types: vec![ExpressionType::Value, ExpressionType::Value],
59 return_type: ExpressionType::Logical,
60 },
61 );
62
63 functions.insert(
64 "search".to_owned(),
65 FunctionSignature {
66 param_types: vec![ExpressionType::Value, ExpressionType::Value],
67 return_type: ExpressionType::Logical,
68 },
69 );
70
71 functions.insert(
72 "value".to_owned(),
73 FunctionSignature {
74 param_types: vec![ExpressionType::Nodes],
75 return_type: ExpressionType::Value,
76 },
77 );
78
79 functions
80}
81
82#[derive(Debug)]
83pub struct JSONPathParser {
84 pub index_range: RangeInclusive<i64>,
85 pub function_signatures: HashMap<String, FunctionSignature>,
86}
87
88impl Default for JSONPathParser {
89 fn default() -> Self {
90 Self::new()
91 }
92}
93
94impl JSONPathParser {
95 pub fn new() -> Self {
96 JSONPathParser {
97 index_range: ((-2_i64).pow(53) + 1..=2_i64.pow(53) - 1),
98 function_signatures: standard_functions(),
99 }
100 }
101
102 pub fn add_function(
103 &mut self,
104 name: &str,
105 params: Vec<ExpressionType>,
106 returns: ExpressionType,
107 ) {
108 self.function_signatures.insert(
109 name.to_owned(),
110 FunctionSignature {
111 param_types: params,
112 return_type: returns,
113 },
114 );
115 }
116
117 pub fn parse(&self, query: &str) -> Result<Query, JSONPathError> {
118 let segments = JSONPath::parse(Rule::jsonpath, query)
119 .map_err(|err| JSONPathError::syntax(err.to_string()))?
120 .try_fold(Segment::Root {}, |acc, segment| {
121 self.parse_segment(acc, segment)
122 })?;
123 Ok(Query { segments })
124 }
125
126 fn parse_segment(&self, acc: Segment, segment: Pair<Rule>) -> Result<Segment, JSONPathError> {
127 Ok(match segment.as_rule() {
128 Rule::child_segment => Segment::Child {
129 left: Box::new(acc),
130 selectors: self.parse_segment_inner(segment.into_inner().next().unwrap())?,
131 },
132 Rule::descendant_segment => Segment::Recursive {
133 left: Box::new(acc),
134 selectors: self.parse_segment_inner(segment.into_inner().next().unwrap())?,
135 },
136 Rule::name_segment | Rule::index_segment => Segment::Child {
137 left: Box::new(acc),
138 selectors: vec![self.parse_selector(segment.into_inner().next().unwrap())?],
139 },
140 Rule::EOI => acc,
141 _ => unreachable!(),
142 })
143 }
144
145 fn parse_segment_inner(&self, segment: Pair<Rule>) -> Result<Vec<Selector>, JSONPathError> {
146 Ok(match segment.as_rule() {
147 Rule::bracketed_selection => {
148 let seg: Result<Vec<_>, _> = segment
149 .into_inner()
150 .map(|selector| self.parse_selector(selector))
151 .collect();
152 seg?
153 }
154 Rule::wildcard_selector => vec![Selector::Wild {}],
155 Rule::member_name_shorthand => vec![Selector::Name {
156 // for child_segment name:
157 name: segment.as_str().to_owned(),
158 }],
159 _ => unreachable!(),
160 })
161 }
162
163 fn parse_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> {
164 Ok(match selector.as_rule() {
165 Rule::double_quoted => Selector::Name {
166 name: unescape_string(selector.as_str()),
167 },
168 Rule::single_quoted => Selector::Name {
169 name: unescape_string(&selector.as_str().replace("\\'", "'")),
170 },
171 Rule::wildcard_selector => Selector::Wild {},
172 Rule::slice_selector => self.parse_slice_selector(selector)?,
173 Rule::index_selector => Selector::Index {
174 index: self.parse_i_json_int(selector.as_str())?,
175 },
176 Rule::filter_selector => self.parse_filter_selector(selector)?,
177 Rule::member_name_shorthand => Selector::Name {
178 // for name_segment name:
179 name: selector.as_str().to_owned(),
180 },
181 _ => unreachable!(),
182 })
183 }
184
185 fn parse_slice_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> {
186 let mut start: Option<i64> = None;
187 let mut stop: Option<i64> = None;
188 let mut step: Option<i64> = None;
189
190 for i in selector.into_inner() {
191 match i.as_rule() {
192 Rule::start => start = Some(self.parse_i_json_int(i.as_str())?),
193 Rule::stop => stop = Some(self.parse_i_json_int(i.as_str())?),
194 Rule::step => step = Some(self.parse_i_json_int(i.as_str())?),
195 _ => unreachable!(),
196 }
197 }
198
199 Ok(Selector::Slice { start, stop, step })
200 }
201
202 fn parse_filter_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> {
203 Ok(Selector::Filter {
204 expression: Box::new(
205 self.parse_logical_or_expression(selector.into_inner().next().unwrap(), true)?,
206 ),
207 })
208 }
209
210 fn parse_logical_or_expression(
211 &self,
212 expr: Pair<Rule>,
213 assert_compared: bool,
214 ) -> Result<FilterExpression, JSONPathError> {
215 let mut it = expr.into_inner();
216 let mut or_expr = self.parse_logical_and_expression(it.next().unwrap(), assert_compared)?;
217 if assert_compared {
218 self.assert_compared(&or_expr)?;
219 }
220 for and_expr in it {
221 let right = self.parse_logical_and_expression(and_expr, assert_compared)?;
222 if assert_compared {
223 self.assert_compared(&right)?;
224 }
225 or_expr = FilterExpression::Logical {
226 left: Box::new(or_expr),
227 operator: LogicalOperator::Or,
228 right: Box::new(right),
229 };
230 }
231 Ok(or_expr)
232 }
233
234 fn parse_logical_and_expression(
235 &self,
236 expr: Pair<Rule>,
237 assert_compared: bool,
238 ) -> Result<FilterExpression, JSONPathError> {
239 let mut it = expr.into_inner();
240 let mut and_expr = self.parse_basic_expression(it.next().unwrap())?;
241 if assert_compared {
242 self.assert_compared(&and_expr)?;
243 }
244 for basic_expr in it {
245 let right = self.parse_basic_expression(basic_expr)?;
246 if assert_compared {
247 self.assert_compared(&right)?;
248 }
249 and_expr = FilterExpression::Logical {
250 left: Box::new(and_expr),
251 operator: LogicalOperator::And,
252 right: Box::new(right),
253 };
254 }
255 Ok(and_expr)
256 }
257
258 fn parse_basic_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
259 match expr.as_rule() {
260 Rule::paren_expr => self.parse_paren_expression(expr),
261 Rule::comparison_expr => self.parse_comparison_expression(expr),
262 Rule::test_expr => self.parse_test_expression(expr),
263 _ => unreachable!(),
264 }
265 }
266
267 fn parse_paren_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
268 let mut it = expr.into_inner();
269 let p = it.next().unwrap();
270 match p.as_rule() {
271 Rule::logical_not_op => Ok(FilterExpression::Not {
272 expression: Box::new(self.parse_logical_or_expression(it.next().unwrap(), true)?),
273 }),
274 Rule::logical_or_expr => self.parse_logical_or_expression(p, true),
275 _ => unreachable!(),
276 }
277 }
278
279 fn parse_comparison_expression(
280 &self,
281 expr: Pair<Rule>,
282 ) -> Result<FilterExpression, JSONPathError> {
283 let mut it = expr.into_inner();
284 let left = self.parse_comparable(it.next().unwrap())?;
285 let operator = match it.next().unwrap().as_str() {
286 "==" => ComparisonOperator::Eq,
287 "!=" => ComparisonOperator::Ne,
288 "<=" => ComparisonOperator::Le,
289 ">=" => ComparisonOperator::Ge,
290 "<" => ComparisonOperator::Lt,
291 ">" => ComparisonOperator::Gt,
292 "contains" => ComparisonOperator::Contains,
293 "in" => ComparisonOperator::In,
294 _ => unreachable!(),
295 };
296 let right = self.parse_comparable(it.next().unwrap())?;
297 self.assert_comparable(&left)?;
298 self.assert_comparable(&right)?;
299 Ok(FilterExpression::Comparison {
300 left: Box::new(left),
301 operator,
302 right: Box::new(right),
303 })
304 }
305
306 fn parse_comparable(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
307 Ok(match expr.as_rule() {
308 Rule::number => self.parse_number(expr)?,
309 Rule::double_quoted => FilterExpression::StringLiteral {
310 value: unescape_string(expr.as_str()),
311 },
312 Rule::single_quoted => FilterExpression::StringLiteral {
313 value: unescape_string(&expr.as_str().replace("\\'", "'")),
314 },
315 Rule::true_literal => FilterExpression::True_ {},
316 Rule::false_literal => FilterExpression::False_ {},
317 Rule::null => FilterExpression::Null {},
318 Rule::array_literal => self.parse_array_literal(expr)?,
319 Rule::rel_singular_query => {
320 let segments = expr
321 .into_inner()
322 .try_fold(Segment::Root {}, |acc, segment| {
323 self.parse_segment(acc, segment)
324 });
325 FilterExpression::RelativeQuery {
326 query: Box::new(Query {
327 segments: segments?,
328 }),
329 }
330 }
331 Rule::abs_singular_query => {
332 let segments = expr
333 .into_inner()
334 .try_fold(Segment::Root {}, |acc, segment| {
335 self.parse_segment(acc, segment)
336 });
337 FilterExpression::RootQuery {
338 query: Box::new(Query {
339 segments: segments?,
340 }),
341 }
342 }
343 Rule::function_expr => self.parse_function_expression(expr)?,
344 _ => unreachable!(),
345 })
346 }
347
348 fn parse_number(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
349 let raw = expr.as_str();
350 if raw == "-0" {
351 return Ok(FilterExpression::Int { value: 0 });
352 }
353 let is_float = raw.contains('.') || raw.contains('e') || raw.contains('E');
354 if !is_float {
355 if let Ok(value) = raw.parse::<i64>() {
356 return Ok(FilterExpression::Int { value });
357 }
358 }
359 Ok(FilterExpression::Float {
360 value: raw
361 .parse::<f64>()
362 .map_err(|_| JSONPathError::syntax(String::from("invalid float literal")))?,
363 })
364 }
365
366 fn parse_array_literal(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
367 let values: Result<Vec<_>, _> = expr
368 .into_inner()
369 .map(|p| self.parse_comparable(p))
370 .collect();
371 Ok(FilterExpression::Array { values: values? })
372 }
373
374 fn parse_test_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
375 let mut it = expr.into_inner();
376 let pair = it.next().unwrap();
377 Ok(match pair.as_rule() {
378 Rule::logical_not_op => FilterExpression::Not {
379 expression: Box::new(self.parse_test_expression_inner(it.next().unwrap())?),
380 },
381 _ => self.parse_test_expression_inner(pair)?,
382 })
383 }
384
385 fn parse_test_expression_inner(
386 &self,
387 expr: Pair<Rule>,
388 ) -> Result<FilterExpression, JSONPathError> {
389 Ok(match expr.as_rule() {
390 Rule::rel_query => {
391 let segments = expr
392 .into_inner()
393 .try_fold(Segment::Root {}, |acc, segment| {
394 self.parse_segment(acc, segment)
395 });
396 FilterExpression::RelativeQuery {
397 query: Box::new(Query {
398 segments: segments?,
399 }),
400 }
401 }
402 Rule::root_query => {
403 let segments = expr
404 .into_inner()
405 .try_fold(Segment::Root {}, |acc, segment| {
406 self.parse_segment(acc, segment)
407 });
408 FilterExpression::RootQuery {
409 query: Box::new(Query {
410 segments: segments?,
411 }),
412 }
413 }
414 Rule::function_expr => self.parse_function_expression(expr)?,
415 _ => unreachable!(),
416 })
417 }
418
419 fn parse_function_expression(
420 &self,
421 expr: Pair<Rule>,
422 ) -> Result<FilterExpression, JSONPathError> {
423 let mut it = expr.into_inner();
424 let name = it.next().unwrap().as_str();
425 let args: Result<Vec<_>, _> = it.map(|ex| self.parse_function_argument(ex)).collect();
426 Ok(FilterExpression::Function {
427 name: name.to_string(),
428 args: self.assert_well_typed(name, args?)?,
429 })
430 }
431
432 fn parse_function_argument(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> {
433 Ok(match expr.as_rule() {
434 Rule::number => self.parse_number(expr)?,
435 Rule::double_quoted => FilterExpression::StringLiteral {
436 value: unescape_string(expr.as_str()),
437 },
438 Rule::single_quoted => FilterExpression::StringLiteral {
439 value: unescape_string(&expr.as_str().replace("\\'", "'")),
440 },
441 Rule::true_literal => FilterExpression::True_ {},
442 Rule::false_literal => FilterExpression::False_ {},
443 Rule::null => FilterExpression::Null {},
444 Rule::array_literal => self.parse_array_literal(expr)?,
445 Rule::rel_query => {
446 let segments = expr
447 .into_inner()
448 .try_fold(Segment::Root {}, |acc, segment| {
449 self.parse_segment(acc, segment)
450 });
451 FilterExpression::RelativeQuery {
452 query: Box::new(Query {
453 segments: segments?,
454 }),
455 }
456 }
457 Rule::root_query => {
458 let segments = expr
459 .into_inner()
460 .try_fold(Segment::Root {}, |acc, segment| {
461 self.parse_segment(acc, segment)
462 });
463 FilterExpression::RootQuery {
464 query: Box::new(Query {
465 segments: segments?,
466 }),
467 }
468 }
469 Rule::logical_or_expr => self.parse_logical_or_expression(expr, false)?,
470 Rule::function_expr => self.parse_function_expression(expr)?,
471 _ => unreachable!(),
472 })
473 }
474
475 fn parse_i_json_int(&self, value: &str) -> Result<i64, JSONPathError> {
476 let i = value
477 .parse::<i64>()
478 .map_err(|_| JSONPathError::syntax(format!("index out of range `{}`", value)))?;
479 if !self.index_range.contains(&i) {
480 return Err(JSONPathError::syntax(format!(
481 "index out of range `{}`",
482 value
483 )));
484 }
485 Ok(i)
486 }
487
488 fn assert_comparable(&self, expr: &FilterExpression) -> Result<(), JSONPathError> {
489 // TODO: accept span/position for better errors
490 match expr {
491 FilterExpression::RelativeQuery { query, .. }
492 | FilterExpression::RootQuery { query, .. } => {
493 if !query.is_singular() {
494 Err(JSONPathError::typ(String::from(
495 "non-singular query is not comparable",
496 )))
497 } else {
498 Ok(())
499 }
500 }
501 FilterExpression::Function { name, .. } => {
502 if let Some(FunctionSignature {
503 return_type: ExpressionType::Value,
504 ..
505 }) = self.function_signatures.get(name)
506 {
507 Ok(())
508 } else {
509 Err(JSONPathError::typ(format!(
510 "result of {}() is not comparable",
511 name
512 )))
513 }
514 }
515 _ => Ok(()),
516 }
517 }
518
519 fn assert_compared(&self, expr: &FilterExpression) -> Result<(), JSONPathError> {
520 match expr {
521 FilterExpression::Function { name, .. } => {
522 if let Some(FunctionSignature {
523 return_type: ExpressionType::Value,
524 ..
525 }) = self.function_signatures.get(name)
526 {
527 Err(JSONPathError::typ(format!(
528 "result of {}() must be compared",
529 name
530 )))
531 } else {
532 Ok(())
533 }
534 }
535 _ => Ok(()),
536 }
537 }
538
539 fn assert_well_typed(
540 &self,
541 func_name: &str,
542 args: Vec<FilterExpression>,
543 ) -> Result<Vec<FilterExpression>, JSONPathError> {
544 // TODO: accept span/position for better errors
545 let signature = self
546 .function_signatures
547 .get(func_name)
548 .ok_or_else(|| JSONPathError::name(format!("unknown function `{}`", func_name)))?;
549
550 // correct number of arguments?
551 if args.len() != signature.param_types.len() {
552 return Err(JSONPathError::typ(format!(
553 "{}() takes {} argument{} but {} were given",
554 func_name,
555 signature.param_types.len(),
556 if signature.param_types.len() > 1 {
557 "s"
558 } else {
559 ""
560 },
561 args.len()
562 )));
563 }
564
565 // correct argument types?
566 for (idx, typ) in signature.param_types.iter().enumerate() {
567 let arg = &args[idx];
568 match typ {
569 ExpressionType::Value => {
570 if !self.is_value_type(arg) {
571 return Err(JSONPathError::typ(format!(
572 "argument {} of {}() must be of a 'Value' type",
573 idx + 1,
574 func_name
575 )));
576 }
577 }
578 ExpressionType::Logical => {
579 if !matches!(
580 arg,
581 FilterExpression::RelativeQuery { .. }
582 | FilterExpression::RootQuery { .. }
583 | FilterExpression::Logical { .. }
584 | FilterExpression::Comparison { .. },
585 ) {
586 return Err(JSONPathError::typ(format!(
587 "argument {} of {}() must be of a 'Logical' type",
588 idx + 1,
589 func_name
590 )));
591 }
592 }
593 ExpressionType::Nodes => {
594 if !self.is_nodes_type(arg) {
595 return Err(JSONPathError::typ(format!(
596 "argument {} of {}() must be of a 'Nodes' type",
597 idx + 1,
598 func_name
599 )));
600 }
601 }
602 }
603 }
604
605 Ok(args)
606 }
607
608 fn is_value_type(&self, expr: &FilterExpression) -> bool {
609 // literals are values
610 if expr.is_literal() {
611 return true;
612 }
613
614 match expr {
615 FilterExpression::RelativeQuery { query, .. }
616 | FilterExpression::RootQuery { query, .. } => {
617 // singular queries will be coerced to a value
618 query.is_singular()
619 }
620 FilterExpression::Function { name, .. } => {
621 // some functions return a value
622 matches!(
623 self.function_signatures.get(name),
624 Some(FunctionSignature {
625 return_type: ExpressionType::Value,
626 ..
627 })
628 )
629 }
630 FilterExpression::Array { .. } => true,
631 _ => false,
632 }
633 }
634
635 fn is_nodes_type(&self, expr: &FilterExpression) -> bool {
636 match expr {
637 FilterExpression::RelativeQuery { .. } | FilterExpression::RootQuery { .. } => true,
638 FilterExpression::Function { name, .. } => {
639 matches!(
640 self.function_signatures.get(name),
641 Some(FunctionSignature {
642 return_type: ExpressionType::Nodes,
643 ..
644 })
645 )
646 }
647 _ => false,
648 }
649 }
650}
651
652fn unescape_string(value: &str) -> String {
653 let chars = value.chars().collect::<Vec<char>>();
654 let length = chars.len();
655 let mut rv = String::new();
656 let mut index: usize = 0;
657
658 while index < length {
659 match chars[index] {
660 '\\' => {
661 index += 1;
662 match chars[index] {
663 '"' => rv.push('"'),
664 '\\' => rv.push('\\'),
665 '/' => rv.push('/'),
666 'b' => rv.push('\x08'),
667 'f' => rv.push('\x0C'),
668 'n' => rv.push('\n'),
669 'r' => rv.push('\r'),
670 't' => rv.push('\t'),
671 'u' => {
672 index += 1;
673 let digits = chars
674 .get(index..index + 4)
675 .unwrap()
676 .iter()
677 .collect::<String>();
678 let mut codepoint = u32::from_str_radix(&digits, 16).unwrap();
679
680 if index + 5 < length && chars[index + 4] == '\\' && chars[index + 5] == 'u'
681 {
682 let digits = &chars
683 .get(index + 6..index + 10)
684 .unwrap()
685 .iter()
686 .collect::<String>();
687 let low_surrogate = u32::from_str_radix(digits, 16).unwrap();
688 codepoint =
689 0x10000 + (((codepoint & 0x03FF) << 10) | (low_surrogate & 0x03FF));
690 index += 6;
691 }
692
693 let unescaped = char::from_u32(codepoint).unwrap();
694 rv.push(unescaped);
695 index += 3;
696 }
697 _ => unreachable!(),
698 }
699 }
700 c => {
701 rv.push(c);
702 }
703 }
704 index += 1;
705 }
706
707 rv
708}