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

Array slices #22

Merged
merged 8 commits into from
Nov 4, 2020
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ pest = "2.1.3"
pest_derive = "2.1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.57"
slyce = "0.3.0"
18 changes: 17 additions & 1 deletion DEVELOPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,25 @@ test to `true`, for example:
</pre>

When one or more tests are focussed in this way, the test suite will fail with the message
"testcase(s) still focussed" even if all the tests pass.
"testcase(s) still focussed" if and only if all the focussed tests pass.
This prevents pull requests being merged in which tests are accidentally left focussed.

To skip one or more tests, edit [cts.json](tests/cts.json) and set the `skip` property of the relevant
test to `true`, for example:
<pre>
}, {
"name": "wildcarded child",
<b>"skip": true,</b>
"selector": "$.*",
"document": {"a" : "A", "b" : "B"},
"result": ["A", "B"]
}, {
</pre>

When one or more tests are skipped in this way, the test suite will fail with the message
"testcase(s) still skipped" if and only if all the tests pass and none are focussed.
This prevents pull requests being merged in which tests are accidentally left skipped.

To see details of which tests run, use:
```
cargo test -- --show-output
Expand Down
10 changes: 10 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
*/

use serde_json::Value;
use slyce::Slice;
use std::iter;

/// A path is a tree of selector nodes.
///
Expand Down Expand Up @@ -57,6 +59,7 @@ pub enum Selector {
#[derive(Debug)]
pub enum UnionElement {
Name(String),
Slice(Slice),
Index(i64),
}

Expand Down Expand Up @@ -89,6 +92,13 @@ impl UnionElement {
pub fn get<'a>(&self, v: &'a Value) -> Iter<'a> {
match self {
UnionElement::Name(name) => Box::new(v.get(name).into_iter()),
UnionElement::Slice(slice) => {
if let Value::Array(arr) = v {
Box::new(slice.apply(arr))
} else {
Box::new(iter::empty())
}
}
UnionElement::Index(num) => Box::new(v.get(abs_index(*num, v)).into_iter()),
}
}
Expand Down
13 changes: 9 additions & 4 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 }

dotChild = _{ wildcardedDotChild | namedDotChild }
wildcardedDotChild = { ".*" }
Expand All @@ -18,9 +18,14 @@ char = {
}

union = { "[" ~ unionElement ~ ("," ~ unionElement)* ~ "]" }
unionElement = _{ unionChild | unionArrayIndex } // TODO: add unionArraySlice
unionChild = { doubleQuotedString | singleQuotedString }
unionArrayIndex = { "-" ? ~ ( "0" | ASCII_NONZERO_DIGIT ~ ASCII_DIGIT* ) }
unionElement = _{ unionChild | unionArraySlice | unionArrayIndex }
unionChild = ${ doubleQuotedString | singleQuotedString }
unionArrayIndex = @{ integer }
integer = _{ "-" ? ~ ( "0" | ASCII_NONZERO_DIGIT ~ ASCII_DIGIT* ) }
unionArraySlice = { sliceStart ? ~ ":" ~ sliceEnd ? ~ ( ":" ~ sliceStep ? ) ? }
sliceStart = @{ integer }
sliceEnd = @{ integer }
sliceStep = @{ integer }

doubleQuotedString = _{ "\"" ~ doubleInner ~ "\"" }
doubleInner = @{ doubleChar* }
Expand Down
1 change: 1 addition & 0 deletions src/jsonpath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub fn parse(selector: &str) -> Result<Path, SyntaxError> {
Ok(Path(p))
}

#[derive(Debug)]
pub struct Path(ast::Path);

impl Path {
Expand Down
69 changes: 55 additions & 14 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

pub use crate::ast::*;
use crate::pest::Parser;
use slyce::Slice;
use std::num::ParseIntError;

#[derive(Parser)]
#[grammar = "grammar.pest"]
Expand All @@ -17,23 +19,26 @@ pub fn parse(selector: &str) -> Result<Path, String> {
.nth(1)
.unwrap();

Ok(selector_rule
selector_rule
.into_inner()
.fold(Path::Root, |prev, r| match r.as_rule() {
Rule::matcher => Path::Sel(Box::new(prev), parse_selector(r)),
.fold(Ok(Path::Root), |prev, r| match r.as_rule() {
Rule::matcher => Ok(Path::Sel(
Box::new(prev?),
parse_selector(r).map_err(|e| format!("{}", e))?,
)),
_ => panic!("invalid parse tree {:?}", r),
}))
})
}

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

match r.as_rule() {
Ok(match r.as_rule() {
Rule::wildcardedDotChild => Selector::DotWildcard,
Rule::namedDotChild => Selector::DotName(parse_child_name(r)),
Rule::union => Selector::Union(parse_union_indices(r)),
Rule::union => Selector::Union(parse_union_indices(r)?),
_ => panic!("invalid parse tree {:?}", r),
}
})
}

fn parse_child_name(matcher_rule: pest::iterators::Pair<Rule>) -> String {
Expand All @@ -45,15 +50,18 @@ fn parse_child_name(matcher_rule: pest::iterators::Pair<Rule>) -> String {
}
}

fn parse_union_indices(matcher_rule: pest::iterators::Pair<Rule>) -> Vec<UnionElement> {
fn parse_union_indices(
matcher_rule: pest::iterators::Pair<Rule>,
) -> Result<Vec<UnionElement>, ParseIntError> {
matcher_rule
.into_inner()
.map(|r| match r.as_rule() {
Rule::unionChild => parse_union_child(r),
Rule::unionChild => Ok(parse_union_child(r)),
Rule::unionArraySlice => parse_union_array_slice(r),
Rule::unionArrayIndex => parse_union_array_index(r),
_ => panic!("invalid parse tree {:?}", r),
})
.collect()
.collect::<Result<Vec<UnionElement>, ParseIntError>>()
}

fn parse_union_child(matcher_rule: pest::iterators::Pair<Rule>) -> UnionElement {
Expand All @@ -66,9 +74,42 @@ fn parse_union_child(matcher_rule: pest::iterators::Pair<Rule>) -> UnionElement
})
}

fn parse_union_array_index(matcher_rule: pest::iterators::Pair<Rule>) -> UnionElement {
let i = matcher_rule.as_str().parse().unwrap();
UnionElement::Index(i)
fn parse_union_array_index(
matcher_rule: pest::iterators::Pair<Rule>,
) -> Result<UnionElement, ParseIntError> {
let i = matcher_rule.as_str().parse()?;
Ok(UnionElement::Index(i))
}

fn parse_union_array_slice(
matcher_rule: pest::iterators::Pair<Rule>,
) -> Result<UnionElement, ParseIntError> {
let mut start: Option<isize> = None;
let mut end: Option<isize> = None;
let mut step: Option<isize> = None;
for r in matcher_rule.into_inner() {
match r.as_rule() {
Rule::sliceStart => {
start = Some(r.as_str().parse()?);
}

Rule::sliceEnd => {
end = Some(r.as_str().parse()?);
}

Rule::sliceStep => {
step = Some(r.as_str().parse()?);
}

_ => panic!("invalid parse tree {:?}", r),
}
}

Ok(UnionElement::Slice(Slice {
start: start.into(),
end: end.into(),
step,
}))
}

fn unescape(contents: &str) -> String {
Expand Down
Loading