Skip to content
This repository was archived by the owner on Feb 22, 2024. It is now read-only.

Commit 4491566

Browse files
author
Marko Mikulicic
committed
Simplify parser
1 parent 2ad8241 commit 4491566

File tree

2 files changed

+13
-17
lines changed

2 files changed

+13
-17
lines changed

src/grammar.pest

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
selector = _{ SOI ~ jsonPath ~ EOI }
1+
selector = _{ SOI ~ rootSelector ~ jsonPath ~ EOI }
22

3-
jsonPath = ${ rootSelector ~ matcher* }
3+
jsonPath = ${ matcher* }
44
rootSelector = { "$" }
55

66
matcher = { dotChild | union }

src/parser.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,15 @@ struct PathParser;
1414
pub fn parse(selector: &str) -> Result<Path, String> {
1515
let selector_rule = PathParser::parse(Rule::selector, selector)
1616
.map_err(|e| format!("{}", e))?
17-
.next()
17+
.nth(1)
1818
.unwrap();
1919

20-
let mut res = Path::Root;
21-
for r in selector_rule.into_inner() {
22-
res = match r.as_rule() {
23-
Rule::rootSelector => res, // TODO: fix grammar so that this is a silent rule since we don't need it
24-
Rule::matcher => Path::Sel(Box::new(res), parse_selector(r)),
20+
Ok(selector_rule
21+
.into_inner()
22+
.fold(Path::Root, |prev, r| match r.as_rule() {
23+
Rule::matcher => Path::Sel(Box::new(prev), parse_selector(r)),
2524
_ => panic!("invalid parse tree {:?}", r),
26-
}
27-
}
28-
Ok(res)
25+
}))
2926
}
3027

3128
fn parse_selector(matcher_rule: pest::iterators::Pair<Rule>) -> Selector {
@@ -41,6 +38,7 @@ fn parse_selector(matcher_rule: pest::iterators::Pair<Rule>) -> Selector {
4138

4239
fn parse_child_name(matcher_rule: pest::iterators::Pair<Rule>) -> String {
4340
let r = matcher_rule.into_inner().next().unwrap();
41+
4442
match r.as_rule() {
4543
Rule::childName => r.as_str().to_owned(),
4644
_ => panic!("invalid parse tree {:?}", r),
@@ -61,15 +59,13 @@ fn parse_union_indices(matcher_rule: pest::iterators::Pair<Rule>) -> Vec<Index>
6159
}
6260

6361
fn parse_union_child(matcher_rule: pest::iterators::Pair<Rule>) -> Vec<Index> {
64-
let mut res = Vec::new();
65-
for r in matcher_rule.into_inner() {
62+
matcher_rule.into_inner().map(|r|
6663
match r.as_rule() {
67-
Rule::doubleInner => res.push(Index::Field(unescape(r.as_str()))),
68-
Rule::singleInner => res.push(Index::Field(unescape_single(r.as_str()))),
64+
Rule::doubleInner => Index::Field(unescape(r.as_str())),
65+
Rule::singleInner => Index::Field(unescape_single(r.as_str())),
6966
_ => panic!("invalid parse tree {:?}", r),
7067
}
71-
}
72-
res
68+
).collect()
7369
}
7470

7571
fn parse_union_array_index(matcher_rule: pest::iterators::Pair<Rule>) -> Index {

0 commit comments

Comments
 (0)