jql-parser-8.1.2/.cargo_vcs_info.json0000644000000001571046102023000131510ustar { "git": { "sha1": "11f1f71192fbdbd84400df2b8d5093155f6eb5ca" }, "path_in_vcs": "crates/jql-parser" }jql-parser-8.1.2/Cargo.lock0000644000000037211046102023000111240ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "jql-parser" version = "8.1.2" dependencies = [ "thiserror", "winnow", ] [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "proc-macro2" version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" [[package]] name = "winnow" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a90e88e4667264a994d34e6d1ab2d26d398dcdca8b7f52bec8668957517fc7d8" dependencies = [ "memchr", ] jql-parser-8.1.2/Cargo.toml0000644000000023131046102023000111430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" name = "jql-parser" version = "8.1.2" authors = ["Davy Duperron "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Parser for jql - the JSON Query Language tool." readme = "README.md" keywords = [ "cli", "json", "terminal", "tool", "query", ] categories = [ "command-line-utilities", "filesystem", ] license = "MIT OR Apache-2.0" repository = "https://github.com/yamafaktory/jql" resolver = "2" [lib] name = "jql_parser" path = "src/lib.rs" [[test]] name = "integration" path = "tests/integration.rs" [dependencies.thiserror] version = "2.0.18" [dependencies.winnow] version = "1.0.0" features = ["simd"] jql-parser-8.1.2/Cargo.toml.orig000064400000000000000000000006451046102023000146100ustar 00000000000000[package] authors.workspace = true categories.workspace = true description = "Parser for jql - the JSON Query Language tool." edition.workspace = true keywords.workspace = true license.workspace = true name = "jql-parser" readme.workspace = true repository.workspace = true version.workspace = true [dependencies] thiserror.workspace = true winnow = { version = "1.0.0", features = ["simd"] } [lib] path = "src/lib.rs" jql-parser-8.1.2/LICENSE-APACHE000064400000000000000000000260721046102023000136470ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 Davy Duperron Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. jql-parser-8.1.2/LICENSE-MIT000064400000000000000000000020351046102023000133500ustar 00000000000000Copyright 2023 Davy Duperron Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jql-parser-8.1.2/README.md000064400000000000000000000004351046102023000131750ustar 00000000000000# jql-parser ## About This crate is a workspace dependency of the [jql](https://github.com/yamafaktory/jql) tool. ## Features - Parser - Errors - Group splitter - Tokens ## License For licensing information, please check the [workspace root](https://github.com/yamafaktory/jql). jql-parser-8.1.2/src/combinators.rs000064400000000000000000000316441046102023000154010ustar 00000000000000use winnow::{ Parser, Result, ascii::{ digit1, multispace0, }, combinator::{ alt, delimited, dispatch, fail, opt, peek, preceded, repeat, separated, separated_pair, }, error::ParserError, token::{ any, literal, take_until, }, }; use crate::tokens::{ Index, LensValue, Range, Token, }; /// Colon. static COLON: char = ':'; /// Comma. static COMMA: char = ','; /// Curly brace open. static CURLY_BRACKET_OPEN: char = '{'; /// Curly brace close. static CURLY_BRACKET_CLOSE: char = '}'; /// Double-quote. static DOUBLE_QUOTE: char = '"'; /// Equal. static EQUAL: char = '='; /// Square brace open. static SQUARE_BRACKET_OPEN: char = '['; /// Square brace close. static SQUARE_BRACKET_CLOSE: char = ']'; /// False. static FALSE: &str = "false"; /// True. static TRUE: &str = "true"; /// Lenses start. static LENSES_START: &str = "|={"; /// Keys operator. static KEYS: &str = "@"; /// Flatten operator. static FLATTEN: &str = ".."; /// Group separator. static GROUP_SEP: &str = ","; /// Pipe in operator. static PIPE_IN: &str = "|>"; /// Pipe out operator. static PIPE_OUT: &str = "<|"; /// Truncate operator. static TRUNCATE: &str = "!"; /// A combinator which takes an `inner` parser and produces a parser which also /// consumes both leading and trailing whitespaces, returning the output of /// `inner`. pub(crate) fn trim<'a, F, O, E>(inner: F) -> impl Parser<&'a str, O, E> where E: ParserError<&'a str>, F: Parser<&'a str, O, E>, { delimited(multispace0, inner, multispace0) } /// A combinator which parses a stringified number as an `Index`. pub(crate) fn parse_number(input: &mut &str) -> Result { digit1.parse_to().parse_next(input) } /// A combinator which parses a key surrounded by double quotes. pub(crate) fn parse_key<'a>(input: &mut &'a str) -> Result<&'a str> { trim(delimited( DOUBLE_QUOTE, take_until(0.., r#"""#), DOUBLE_QUOTE, )) .parse_next(input) } /// A combinator which parses a list of `Index`. pub(crate) fn parse_indexes(input: &mut &str) -> Result> { separated(1.., parse_number, trim(COMMA)).parse_next(input) } /// A combinator which parses a list of keys. fn parse_keys<'a>(input: &mut &'a str) -> Result> { trim(separated(1.., parse_key, trim(COMMA))).parse_next(input) } /// A combinator which parses a list of keys surrounded by curly braces. pub(crate) fn parse_multi_key<'a>(input: &mut &'a str) -> Result> { delimited(CURLY_BRACKET_OPEN, parse_keys, CURLY_BRACKET_CLOSE).parse_next(input) } /// A combinator which parses an array of `Index`. pub(crate) fn parse_array_index(input: &mut &str) -> Result> { delimited( trim(SQUARE_BRACKET_OPEN), parse_indexes, trim(SQUARE_BRACKET_CLOSE), ) .parse_next(input) } /// A combinator which parses an array range. pub(crate) fn parse_array_range(input: &mut &str) -> Result<(Option, Option)> { trim(delimited( SQUARE_BRACKET_OPEN, separated_pair(opt(parse_number), trim(COLON), opt(parse_number)), SQUARE_BRACKET_CLOSE, )) .parse_next(input) } /// A combinator which parses a list of index surrounded by curly braces. pub(crate) fn parse_object_index(input: &mut &str) -> Result> { delimited( trim(CURLY_BRACKET_OPEN), parse_indexes, trim(CURLY_BRACKET_CLOSE), ) .parse_next(input) } /// A combinator which parses an object range. pub(crate) fn parse_object_range(input: &mut &str) -> Result<(Option, Option)> { delimited( trim(CURLY_BRACKET_OPEN), separated_pair(opt(parse_number), trim(COLON), opt(parse_number)), trim(CURLY_BRACKET_CLOSE), ) .parse_next(input) } /// A combinator which parses any lens value. pub(crate) fn parse_lens_value<'a>(input: &mut &'a str) -> Result> { dispatch! {peek(any); 'f' => FALSE.value(LensValue::Bool(false)), 't' => TRUE.value(LensValue::Bool(true)), 'n' => "null".value(LensValue::Null), '0'..='9' => digit1.try_map(|s: &str| s.parse::().map(LensValue::Number)), _ => parse_key.map(LensValue::String), } .parse_next(input) } // /// A combinator which parses a lens key. fn parse_lens_key<'a>(input: &mut &'a str) -> Result> { trim( dispatch! {peek(any); '[' => { alt(( parse_array_index.map(Token::ArrayIndexSelector), parse_array_range.map(|(start, end)| Token::ArrayRangeSelector(Range(start, end))), )) }, '"' => parse_key.map(Token::KeySelector), '{' => { alt(( parse_multi_key.map(Token::MultiKeySelector), parse_object_index.map(Token::ObjectIndexSelector), parse_object_range.map(|(start, end)| Token::ObjectRangeSelector(Range(start, end))), )) }, _ => fail } ) .parse_next(input) } /// A combinator which parses multiple lens keys. fn parse_lens_keys<'a>(input: &mut &'a str) -> Result>> { repeat(1.., parse_lens_key).parse_next(input) } /// A combinator which parses a lens. pub(crate) fn parse_lens<'a>( input: &mut &'a str, ) -> Result<(Vec>, Option>)> { trim(( parse_lens_keys, opt(preceded(trim(EQUAL), parse_lens_value)), )) .parse_next(input) } /// A combinator which parses a list of lenses. pub(crate) fn parse_lenses<'a>( input: &mut &'a str, ) -> Result>, Option>)>> { delimited( trim(LENSES_START), separated(1.., parse_lens, trim(COMMA)), trim(CURLY_BRACKET_CLOSE), ) .parse_next(input) } /// A combinator which parses a keys operator. pub(crate) fn parse_keys_operator<'a>(input: &mut &'a str) -> Result<&'a str> { literal(KEYS).parse_next(input) } /// A combinator which parses a flatten operator. pub(crate) fn parse_flatten_operator<'a>(input: &mut &'a str) -> Result<&'a str> { literal(FLATTEN).parse_next(input) } /// A combinator which parses a pipe in operator. pub(crate) fn parse_pipe_in_operator<'a>(input: &mut &'a str) -> Result<&'a str> { literal(PIPE_IN).parse_next(input) } /// A combinator which parses a pipe out operator. pub(crate) fn parse_pipe_out_operator<'a>(input: &mut &'a str) -> Result<&'a str> { literal(PIPE_OUT).parse_next(input) } /// A combinator which parses a truncate operator. pub(crate) fn parse_truncate_operator<'a>(input: &mut &'a str) -> Result<&'a str> { trim(TRUNCATE).parse_next(input) } /// A combinator which parses a group separator. pub(crate) fn parse_group_separator<'a>(input: &mut &'a str) -> Result<&'a str> { literal(GROUP_SEP).parse_next(input) } #[cfg(test)] mod tests { use super::{ FLATTEN, GROUP_SEP, KEYS, PIPE_IN, PIPE_OUT, TRUNCATE, parse_array_index, parse_array_range, parse_flatten_operator, parse_group_separator, parse_indexes, parse_key, parse_keys_operator, parse_lens, parse_lenses, parse_multi_key, parse_number, parse_object_index, parse_object_range, parse_pipe_in_operator, parse_pipe_out_operator, parse_truncate_operator, }; use crate::tokens::{ Index, LensValue, Token, }; #[test] fn check_parse_number() { assert_eq!(parse_number(&mut "123"), Ok(Index(123))); assert!(parse_number(&mut "abc").is_err()); assert!(parse_number(&mut "abc123").is_err()); } #[test] fn check_parse_key() { assert_eq!(parse_key(&mut r#""abc""#), Ok("abc")); assert!(parse_key(&mut "abc").is_err()); } #[test] fn check_parse_indexes() { assert_eq!(parse_indexes(&mut "123"), Ok(vec![Index(123)])); assert_eq!( parse_indexes(&mut "123,456,789"), Ok(vec![Index(123), Index(456), Index(789)]) ); assert!(parse_indexes(&mut "abc").is_err()); } #[test] fn check_parse_multi_key() { assert_eq!(parse_multi_key(&mut r#"{"abc"}"#), Ok(vec!["abc"])); assert_eq!( parse_multi_key(&mut r#"{"abc","def"}"#), Ok(vec!["abc", "def"]) ); assert!(parse_multi_key(&mut "{}").is_err()); assert!(parse_multi_key(&mut "{123}").is_err()); } #[test] fn check_parse_array_index() { assert_eq!(parse_array_index(&mut "[1]"), Ok(vec![Index(1)])); assert_eq!( parse_array_index(&mut "[1,2,3]"), Ok(vec![Index(1), Index(2), Index(3)]) ); assert!(parse_array_index(&mut "[]").is_err()); assert!(parse_array_index(&mut r#"["1"]"#).is_err()); } #[test] fn check_parse_array_range() { assert_eq!(parse_array_range(&mut "[:]"), Ok((None, None))); assert_eq!(parse_array_range(&mut "[1:]"), Ok((Some(Index(1)), None))); assert_eq!(parse_array_range(&mut "[:1]"), Ok((None, Some(Index(1))))); assert_eq!( parse_array_range(&mut "[1:3]"), Ok((Some(Index(1)), Some(Index(3)))) ); assert!(parse_array_range(&mut "[]").is_err()); } #[test] fn check_parse_object_index() { assert_eq!(parse_object_index(&mut "{1}"), Ok(vec![Index(1)])); assert_eq!( parse_object_index(&mut "{1,2}"), Ok(vec![Index(1), Index(2)]) ); assert!(parse_object_index(&mut "{}").is_err()); } #[test] fn check_parse_object_range() { assert_eq!(parse_object_range(&mut "{:}"), Ok((None, None))); assert_eq!(parse_object_range(&mut "{1:}"), Ok((Some(Index(1)), None))); assert_eq!(parse_object_range(&mut "{:1}"), Ok((None, Some(Index(1))))); assert_eq!( parse_object_range(&mut "{1:3}"), Ok((Some(Index(1)), Some(Index(3)))) ); assert!(parse_object_range(&mut "{}").is_err()); } #[test] fn check_parse_keys_operator() { assert_eq!(parse_keys_operator(&mut "@"), Ok(KEYS)); assert!(parse_keys_operator(&mut "").is_err()); } #[test] fn check_parse_flatten_operator() { assert_eq!(parse_flatten_operator(&mut ".."), Ok(FLATTEN)); assert!(parse_flatten_operator(&mut "").is_err()); } #[test] fn check_parse_pipe_in_operator() { assert_eq!(parse_pipe_in_operator(&mut "|>"), Ok(PIPE_IN)); assert!(parse_pipe_in_operator(&mut "").is_err()); } #[test] fn check_parse_pipe_out_operator() { assert_eq!(parse_pipe_out_operator(&mut "<|"), Ok(PIPE_OUT)); assert!(parse_pipe_out_operator(&mut "").is_err()); } #[test] fn check_parse_truncate_operator() { assert_eq!(parse_truncate_operator(&mut "!"), Ok(TRUNCATE)); assert!(parse_truncate_operator(&mut "").is_err()); } #[test] fn check_parse_group_separator() { assert_eq!(parse_group_separator(&mut ","), Ok(GROUP_SEP)); assert!(parse_group_separator(&mut "").is_err()); } #[test] fn check_parse_lens() { assert_eq!( parse_lens(&mut r#""abc""#), Ok((vec![Token::KeySelector("abc")], None)) ); assert_eq!( parse_lens(&mut r#""abc"=null"#), Ok((vec![Token::KeySelector("abc")], Some(LensValue::Null))) ); assert_eq!( parse_lens(&mut r#""abc"="def""#), Ok(( vec![Token::KeySelector("abc")], Some(LensValue::String("def")) )) ); assert_eq!( parse_lens(&mut r#""abc"=123"#), Ok(( vec![Token::KeySelector("abc")], Some(LensValue::Number(123)) )) ); assert_eq!( parse_lens(&mut r#""abc""bcd"[0]=123"#), Ok(( vec![ Token::KeySelector("abc"), Token::KeySelector("bcd"), Token::ArrayIndexSelector(vec![Index(0)]) ], Some(LensValue::Number(123)) )) ); assert!(parse_lens(&mut "").is_err()); } #[test] fn check_parse_lenses() { assert_eq!( parse_lenses(&mut r#"|={"abc","bcd"=123,"efg"=null,"hij"="test"}"#), Ok(vec![ (vec![Token::KeySelector("abc")], None), ( vec![Token::KeySelector("bcd")], Some(LensValue::Number(123)) ), (vec![Token::KeySelector("efg")], Some(LensValue::Null)), ( vec![Token::KeySelector("hij")], Some(LensValue::String("test")) ), ]) ); } } jql-parser-8.1.2/src/errors.rs000064400000000000000000000020041046102023000143610ustar 00000000000000use thiserror::Error; fn display_content(content: &str) -> String { if content.is_empty() { String::new() } else { format!(" after {content}") } } /// Error type returned by the parser. #[derive(Debug, Error, PartialEq)] pub enum JqlParserError { /// Empty input error. #[error("Empty input")] EmptyInputError, /// Parsing error. #[error("Unable to parse input {unparsed}{}", display_content(tokens))] ParsingError { /// Tokens found while parsing. tokens: String, /// Unparsed content. unparsed: String, }, /// Truncate error. #[error("Truncate operator found as non last element or multiple times in {0}")] TruncateError(String), /// Unknown error. #[error("Unknown error")] UnknownError, } #[cfg(test)] mod tests { use super::display_content; #[test] fn check_display_content() { assert_eq!(display_content("some"), " after some"); assert_eq!(display_content(""), ""); } } jql-parser-8.1.2/src/group.rs000064400000000000000000000030501046102023000142030ustar 00000000000000use crate::tokens::Token; #[must_use] /// Splits a list of `Tokens` by `GroupSeparator`. /// Returns groups of `Tokens`. pub fn split<'a>(tokens: &'a [Token<'a>]) -> Vec>> { tokens .iter() .fold(vec![], |mut acc: Vec>, token| { if token == &Token::GroupSeparator { acc.push(vec![]); return acc; } if acc.is_empty() { acc.push(vec![]); } if let Some(last) = acc.last_mut() { last.push(token); } acc }) .into_iter() .filter(|group| !group.is_empty()) .collect() } #[cfg(test)] mod tests { use super::split; use crate::tokens::Token; #[test] fn check_split() { assert!(split(&[Token::GroupSeparator,]).is_empty()); assert_eq!( split(&[Token::KeySelector("abc")]), vec![vec![&Token::KeySelector("abc")]] ); assert_eq!( split(&[ Token::GroupSeparator, Token::GroupSeparator, Token::KeySelector("abc") ]), vec![vec![&Token::KeySelector("abc")]] ); assert_eq!( split(&[ Token::KeySelector("abc"), Token::GroupSeparator, Token::KeySelector("abc") ]), vec![ vec![&Token::KeySelector("abc")], vec![&Token::KeySelector("abc")], ] ); } } jql-parser-8.1.2/src/lib.rs000064400000000000000000000005311046102023000136160ustar 00000000000000#![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/yamafaktory/jql/a438ab0039faf64c3329fb09bae399ae95601000/jql.svg" )] mod combinators; /// Parser errors. pub mod errors; /// Grouping utilities. pub mod group; /// Parsing utilities. pub mod parser; /// Tokens for the parser. pub mod tokens; jql-parser-8.1.2/src/parser.rs000064400000000000000000000234121046102023000143470ustar 00000000000000use winnow::{ Parser, Result, combinator::{ alt, dispatch, fail, iterator, peek, }, token::any, }; use crate::{ combinators::{ parse_array_index, parse_array_range, parse_flatten_operator, parse_group_separator, parse_key, parse_keys_operator, parse_lenses, parse_multi_key, parse_object_index, parse_object_range, parse_pipe_in_operator, parse_pipe_out_operator, parse_truncate_operator, trim, }, errors::JqlParserError, tokens::{ Lens, Range, Token, View, }, }; /// Parses the provided input and map it to the first matching token. fn parse_fragment<'a>(input: &mut &'a str) -> Result> { trim( dispatch! {peek(any); '[' => { alt(( parse_array_index.map(Token::ArrayIndexSelector), parse_array_range.map(|(start, end)| Token::ArrayRangeSelector(Range(start, end))), )) }, '"' => parse_key.map(Token::KeySelector), '{' => { alt(( parse_multi_key.map(Token::MultiKeySelector), parse_object_index.map(Token::ObjectIndexSelector), parse_object_range.map(|(start, end)| Token::ObjectRangeSelector(Range(start, end))), )) }, '|' => { alt(( parse_lenses.map(|lenses| { Token::LensSelector( lenses .into_iter() .map(|(tokens, value)| Lens(tokens, value)) .collect(), ) }), parse_pipe_in_operator.value(Token::PipeInOperator), )) }, '@' => parse_keys_operator.value(Token::KeyOperator), '.' => parse_flatten_operator.value(Token::FlattenOperator), '<' => parse_pipe_out_operator.value(Token::PipeOutOperator), ',' => parse_group_separator.value(Token::GroupSeparator), '!' => parse_truncate_operator.value(Token::TruncateOperator), _ => fail } ) .parse_next(input) } /// Parses the provided input and returns a vector of `Tokens`. /// /// # Errors /// /// Returns a `JqlParserError` on failure. pub fn parse(input: &str) -> Result>, JqlParserError> { let mut input = input; let mut parser_iterator = iterator(&mut input, parse_fragment); let tokens = parser_iterator.collect::>(); let result: Result<_, _> = parser_iterator.finish(); match result { Ok(()) => { if !input.is_empty() { return Err(JqlParserError::ParsingError { tokens: tokens.stringify(), unparsed: input.to_string(), }); } let truncate_count = tokens .iter() .filter(|&token| *token == Token::TruncateOperator) .count(); if truncate_count > 1 || (truncate_count == 1 && tokens.last() != Some(&Token::TruncateOperator)) { return Err(JqlParserError::TruncateError(tokens.stringify())); } Ok(tokens) } Err(_) => Err(JqlParserError::UnknownError), } } #[cfg(test)] mod tests { use super::{ parse, parse_fragment, }; use crate::{ errors::JqlParserError, tokens::{ Index, Lens, LensValue, Range, Token, View, }, }; #[test] fn check_array_index_selector() { assert_eq!( parse_fragment(&mut "[0,1,2]"), Ok(Token::ArrayIndexSelector(vec![ Index(0), Index(1), Index(2) ])) ); assert_eq!( parse_fragment(&mut " [ 0 , 1 , 2 ] "), Ok(Token::ArrayIndexSelector(vec![ Index(0), Index(1), Index(2) ])) ); } #[test] fn check_array_range_selector() { assert_eq!( parse_fragment(&mut "[0:2]"), Ok(Token::ArrayRangeSelector(Range( Some(Index(0)), Some(Index(2)) ))) ); assert_eq!( parse_fragment(&mut "[:2]"), Ok(Token::ArrayRangeSelector(Range(None, Some(Index(2))))) ); assert_eq!( parse_fragment(&mut "[0:]"), Ok(Token::ArrayRangeSelector(Range(Some(Index(0)), None))) ); assert_eq!( parse_fragment(&mut "[:]"), Ok(Token::ArrayRangeSelector(Range(None, None))) ); } #[test] fn check_key_selector() { assert_eq!( parse_fragment(&mut r#""one""#), Ok(Token::KeySelector("one")) ); assert_eq!( parse_fragment(&mut r#" "one" "#), Ok(Token::KeySelector("one")) ); } #[test] fn check_multi_key_selector() { assert_eq!( parse_fragment(&mut r#"{"one","two","three"}"#), Ok(Token::MultiKeySelector(vec!["one", "two", "three"])) ); assert_eq!( parse_fragment(&mut r#" { "one", "two" , "three" } "#), Ok(Token::MultiKeySelector(vec!["one", "two", "three"])) ); } #[test] fn check_object_index_selector() { assert_eq!( parse_fragment(&mut "{0,1,2}"), Ok(Token::ObjectIndexSelector(vec![ Index(0), Index(1), Index(2) ])) ); assert_eq!( parse_fragment(&mut " { 0 , 1 , 2 } "), Ok(Token::ObjectIndexSelector(vec![ Index(0), Index(1), Index(2) ])) ); } #[test] fn check_object_range_selector() { assert_eq!( parse_fragment(&mut "{0:2}"), Ok(Token::ObjectRangeSelector(Range( Some(Index(0)), Some(Index(2)) ))) ); assert_eq!( parse_fragment(&mut "{:2}"), Ok(Token::ObjectRangeSelector(Range(None, Some(Index(2))))) ); assert_eq!( parse_fragment(&mut "{0:}"), Ok(Token::ObjectRangeSelector(Range(Some(Index(0)), None))) ); assert_eq!( parse_fragment(&mut "{:}"), Ok(Token::ObjectRangeSelector(Range(None, None))) ); } #[test] fn check_lens_selector() { assert_eq!( parse_fragment(&mut r#"|={"abc""c","bcd""d"=123,"efg"=null,"hij"="test"}"#), Ok(Token::LensSelector(vec![ Lens( vec![Token::KeySelector("abc"), Token::KeySelector("c")], None ), Lens( vec![Token::KeySelector("bcd"), Token::KeySelector("d")], Some(LensValue::Number(123)) ), Lens(vec![Token::KeySelector("efg")], Some(LensValue::Null)), Lens( vec![Token::KeySelector("hij")], Some(LensValue::String("test")) ), ])) ); } #[test] fn check_flatten_operator() { assert_eq!(parse_fragment(&mut ".."), Ok(Token::FlattenOperator)); assert_eq!(parse_fragment(&mut " .. "), Ok(Token::FlattenOperator)); } #[test] fn check_pipe_in_operator() { assert_eq!(parse_fragment(&mut "|>"), Ok(Token::PipeInOperator)); assert_eq!(parse_fragment(&mut " |> "), Ok(Token::PipeInOperator)); } #[test] fn check_pipe_out_operator() { assert_eq!(parse_fragment(&mut "<|"), Ok(Token::PipeOutOperator)); assert_eq!(parse_fragment(&mut " <| "), Ok(Token::PipeOutOperator)); } #[test] fn check_truncate_operator() { assert_eq!(parse_fragment(&mut "!"), Ok(Token::TruncateOperator)); assert_eq!(parse_fragment(&mut " ! "), Ok(Token::TruncateOperator)); } #[test] fn check_group_separator() { assert_eq!(parse_fragment(&mut ","), Ok(Token::GroupSeparator)); assert_eq!(parse_fragment(&mut " , "), Ok(Token::GroupSeparator)); } #[test] fn check_full_parser() { assert_eq!( parse(r#""this"[9,0]"#), Ok(vec![ Token::KeySelector("this"), Token::ArrayIndexSelector(vec![Index(9), Index(0)]) ]), ); assert_eq!( parse("[9,0]nope"), Err(JqlParserError::ParsingError { tokens: [Token::ArrayIndexSelector(vec![Index(9), Index(0)])].stringify(), unparsed: "nope".to_string(), }) ); assert_eq!( parse(r#""this"[9,0]|>"some"<|"ok"..!"#), Ok(vec![ Token::KeySelector("this"), Token::ArrayIndexSelector(vec![Index(9), Index(0)]), Token::PipeInOperator, Token::KeySelector("some"), Token::PipeOutOperator, Token::KeySelector("ok"), Token::FlattenOperator, Token::TruncateOperator ]), ); assert_eq!( parse(r#""a"!"b""#), Err(JqlParserError::TruncateError( [ Token::KeySelector("a"), Token::TruncateOperator, Token::KeySelector("b") ] .stringify() )) ); } } jql-parser-8.1.2/src/tokens.rs000064400000000000000000000166311046102023000143630ustar 00000000000000use std::{ fmt, num::{ NonZeroUsize, ParseIntError, }, str::FromStr, string::ToString, }; /// `Index` used for arrays and objects. /// Internally mapped to a `usize` with the newtype pattern. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Index(pub(crate) usize); impl Index { #[must_use] /// Creates a new `Index`. pub fn new(index: usize) -> Index { Index(index) } } impl From for usize { fn from(index: Index) -> usize { index.0 } } impl fmt::Display for Index { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Index ({})", self.0) } } impl FromStr for Index { type Err = ParseIntError; fn from_str(s: &str) -> Result { Ok(Index(s.parse::()?)) } } /// `Range` used for arrays and objects. /// Internally mapped to a tuple of `Option` of `Index`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Range(pub(crate) Option, pub(crate) Option); impl Range { #[must_use] /// Creates a new `Range`. pub fn new(start: Option, end: Option) -> Range { Range(start, end) } #[must_use] /// Maps a `Range` to a tuple of boundaries as `usize`. /// `start` defaults to 0 if `None`. /// `end` is injected based on `len` if `None`. pub fn to_boundaries(&self, len: NonZeroUsize) -> (usize, usize) { let start = self.0.unwrap_or(Index(0)); let end = self.1.unwrap_or(Index(len.get() - 1)); (start.0, end.0) } } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let format_bound = |bound: &Option| match bound { Some(index) => index.to_string(), None => String::new(), }; write!( f, "Range [{}:{}]", format_bound(&self.0), format_bound(&self.1) ) } } /// `Lens` used for `LensSelector`. /// Internally mapped to a tuple of a slice of `Token` and `Option` of /// `LensValue`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Lens<'a>(pub(crate) Vec>, pub(crate) Option>); impl<'a> Lens<'a> { #[must_use] /// Creates a new `Lens`. pub fn new(tokens: &[Token<'a>], value: Option>) -> Lens<'a> { Lens(tokens.to_vec(), value) } #[must_use] /// Gets the content of a `Lens`. pub fn get(&self) -> (Vec>, Option>) { (self.0.clone(), self.1.clone()) } #[must_use] /// Gets references to the content of a `Lens` without cloning. pub fn get_ref(&self) -> (&[Token<'a>], Option<&LensValue<'a>>) { (&self.0, self.1.as_ref()) } } impl fmt::Display for Lens<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}{}", self.0.stringify(), match &self.1 { Some(lens_value) => { lens_value.to_string() } None => String::new(), } ) } } /// Lens value type. #[derive(Debug, Clone, PartialEq, Eq)] pub enum LensValue<'a> { /// Variant for a JSON boolean. Bool(bool), /// Variant for JSON null. Null, /// Variant for a JSON number. Number(usize), /// Variant for a JSON string. String(&'a str), } impl fmt::Display for LensValue<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LensValue::Bool(boolean) => { write!(f, "{boolean}") } LensValue::Null => { write!(f, "null") } LensValue::Number(number) => { write!(f, "{number}") } LensValue::String(string) => write!(f, "{string}"), } } } /// Parser tokens type. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Token<'a> { /// Array index selector. ArrayIndexSelector(Vec), /// Array range selector. ArrayRangeSelector(Range), /// Flatten operator. FlattenOperator, /// Key operator. KeyOperator, /// Group separator. GroupSeparator, /// Key selector. KeySelector(&'a str), /// Lens selector. LensSelector(Vec>), /// Multi key selector. MultiKeySelector(Vec<&'a str>), /// Object index selector. ObjectIndexSelector(Vec), /// Object range selector. ObjectRangeSelector(Range), /// Pipe in operator. PipeInOperator, /// Pipe out operator. PipeOutOperator, /// Truncate operator. TruncateOperator, } impl<'a> Token<'a> { fn get_name(&self) -> &'a str { match self { Token::ArrayIndexSelector(_) => "Array Index Selector", Token::ArrayRangeSelector(_) => "Array Range Selector", Token::FlattenOperator => "Flatten Operator", Token::KeyOperator => "Key Operator", Token::GroupSeparator => "Group Separator", Token::KeySelector(_) => "Key Selector", Token::LensSelector(_) => "Lens Selector", Token::MultiKeySelector(_) => "Multi Key Selector", Token::ObjectIndexSelector(_) => "Object Index Selector", Token::ObjectRangeSelector(_) => "Object Range Selector", Token::PipeInOperator => "Pipe In Operator", Token::PipeOutOperator => "Pipe Out Operator", Token::TruncateOperator => "Truncate Operator", } } } impl fmt::Display for Token<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Token::ArrayIndexSelector(indexes) | Token::ObjectIndexSelector(indexes) => { let formatted_indexes = indexes .iter() .map(ToString::to_string) .collect::>() .join(", "); write!(f, "{} [{formatted_indexes}]", self.get_name()) } Token::ArrayRangeSelector(range) | Token::ObjectRangeSelector(range) => { write!(f, "{} {}", self.get_name(), range) } Token::KeySelector(key) => { write!(f, r#"{} "{key}""#, self.get_name()) } Token::LensSelector(lenses) => { let formatted_indexes = lenses .iter() .map(ToString::to_string) .collect::>() .join(", "); write!(f, "{} [{formatted_indexes}]", self.get_name()) } Token::MultiKeySelector(multi_key) => { let formatted_keys = multi_key.join(", "); write!(f, "{} {formatted_keys}", self.get_name()) } Token::FlattenOperator | Token::KeyOperator | Token::GroupSeparator | Token::PipeInOperator | Token::PipeOutOperator | Token::TruncateOperator => { write!(f, "{}", self.get_name()) } } } } /// Trait used to expose custom display methods. pub trait View { /// Returns a stringified version of `self`. fn stringify(&self) -> String; } impl<'a, T: AsRef<[Token<'a>]>> View for T { fn stringify(&self) -> String { self.as_ref() .iter() .map(ToString::to_string) .collect::>() .join(", ") } } jql-parser-8.1.2/tests/integration.rs000064400000000000000000000010731046102023000157500ustar 00000000000000use jql_parser::{ parser::parse, tokens::{ Index, Token, }, }; #[test] fn check_parse_integration() { assert_eq!( parse(r#""this"[9,0]|>"some"<|"ok"..!"#), Ok(vec![ Token::KeySelector("this"), Token::ArrayIndexSelector(vec![Index::new(9), Index::new(0)]), Token::PipeInOperator, Token::KeySelector("some"), Token::PipeOutOperator, Token::KeySelector("ok"), Token::FlattenOperator, Token::TruncateOperator ]), ); }