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

Descendant selectors #33

Merged
merged 9 commits into from
Aug 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jsonpath-compliance-test-suite
31 changes: 31 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ pub enum Selector {
Union(Vec<UnionElement>),
DotName(String),
DotWildcard,
DescendantDotName(String),
DescendantDotWildcard,
DescendantUnion(Vec<UnionElement>),
}

#[derive(Debug)]
Expand Down Expand Up @@ -85,6 +88,34 @@ impl Selector {
Value::Array(a) => Box::new(a.iter()),
_ => Box::new(std::iter::empty()),
},
Selector::DescendantDotName(name) => {
Self::traverse(input, move |n: &'a Value| Box::new(n.get(name).into_iter()))
}
Selector::DescendantDotWildcard => {
Self::traverse(input, move |n: &'a Value| Box::new(iter::once(n)))
}
Selector::DescendantUnion(indices) => Self::traverse(input, move |n: &'a Value| {
Box::new(indices.iter().flat_map(move |i| i.find(n)))
}),
}
}

// traverse applies the given closure to all the descendants of the input value and
// returns a nodelist.
fn traverse<'a, F>(input: &'a Value, f: F) -> NodeList<'a>
where
F: Fn(&'a Value) -> NodeList<'a> + Copy + 'a,
{
match input {
Value::Object(m) => Box::new(
m.into_iter()
.flat_map(move |(_k, v)| f(v).chain(Self::traverse::<'a>(v, f))),
),
Value::Array(a) => Box::new(
a.iter()
.flat_map(move |v| f(v).chain(Self::traverse::<'a>(v, f))),
),
_ => Box::new(std::iter::empty()),
}
}
}
Expand Down
10 changes: 8 additions & 2 deletions src/grammar.pest
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ selector = ${ SOI ~ rootSelector ~ matchers ~ EOI }
matchers = ${ matcher* }
rootSelector = @{ "$" }

matcher = !{ dotChild | union }
matcher = !{ dotChild | union | wildcardedIndex | descendant }

dotChild = _{ wildcardedDotChild | namedDotChild }
wildcardedDotChild = { ".*" }
Expand All @@ -17,7 +17,7 @@ char = {
| '\u{80}'..'\u{10FFFF}'
}

union = { "[" ~ unionElement ~ ("," ~ unionElement)* ~ "]" }
union = !{ "[" ~ unionElement ~ ("," ~ unionElement)* ~ "]" }
unionElement = _{ unionChild | unionArraySlice | unionArrayIndex }
unionChild = ${ doubleQuotedString | singleQuotedString }
unionArrayIndex = @{ integer }
Expand All @@ -27,6 +27,12 @@ sliceStart = @{ integer }
sliceEnd = @{ integer }
sliceStep = @{ integer }

wildcardedIndex = { "[" ~ "*" ~ "]" }

descendant = ${ ".." ~ descendantVariant }
descendantVariant = _{ childName | wildcard | "[" ~ wildcard ~ "]" | union }
wildcard = { "*" }

doubleQuotedString = _{ "\"" ~ doubleInner ~ "\"" }
doubleInner = @{ doubleChar* }
doubleChar = {
Expand Down
12 changes: 12 additions & 0 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ fn parse_selector(matcher_rule: pest::iterators::Pair<Rule>) -> Result<Selector,
Rule::wildcardedDotChild => Selector::DotWildcard,
Rule::namedDotChild => Selector::DotName(parse_child_name(r)),
Rule::union => Selector::Union(parse_union_indices(r)?),
Rule::wildcardedIndex => Selector::DotWildcard,
Rule::descendant => parse_descendant(r)?,
_ => panic!("invalid parse tree {:?}", r),
})
}
Expand Down Expand Up @@ -115,6 +117,16 @@ fn parse_union_array_slice(
}))
}

fn parse_descendant(matcher_rule: pest::iterators::Pair<Rule>) -> Result<Selector, ParseIntError> {
let r = matcher_rule.into_inner().next().unwrap();

Ok(match r.as_rule() {
Rule::childName => Selector::DescendantDotName(r.as_str().to_owned()),
Rule::wildcard => Selector::DescendantDotWildcard,
_ => Selector::DescendantUnion(parse_union_indices(r)?),
})
}

fn unescape(contents: &str) -> String {
let s = format!(r#""{}""#, contents);
serde_json::from_str(&s).unwrap()
Expand Down
12 changes: 10 additions & 2 deletions tests/cts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,18 @@ mod tests {
assert!(false, "find failed") // should not happen
}
} else {
if !t.invalid_selector {
if t.invalid_selector {
// print failure message
println!(
"{}: parsing `{}` failed with: {}",
t.name,
t.selector,
path.err().expect("should be an error")
);
} else {
assert!(
path.is_ok(),
"{}: parsing {} should have succeeded but failed: {}",
"{}: parsing `{}` should have succeeded but failed: {}",
t.name,
t.selector,
path.err().expect("should be an error")
Expand Down