1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Complete, fast, and fully spec-compliant JSONPath query parser.
//!
//! The crate exposes the [`JsonPathQuery`] type and the [`parse`](`crate::parse`)
//! function that converts a query string into the AST representation. The parsing
//! complies with the proposed [JSONPath RFC specification](https://www.ietf.org/archive/id/draft-ietf-jsonpath-base-21.html).
//!
//! A JSONPath query is a sequence of **segments**, each containing one or more
//! **selectors**. There are two types of segments:
//! - **child** ([`Segment::Child`]), and
//! - **descendant** ([`Segment::Descendant`]);
//!
//! and five different types of selectors:
//! - **name** ([`Selector::Name`]),
//! - **wildcard** ([`Selector::Wildcard`]),
//! - **index** ([`Selector::Index`]),
//! - **slice**,
//! - and **filter**.
//!
//! Descriptions of each segment and selector can be found in the documentation of the
//! relevant type in this crate, while the formal grammar is described in the RFC.
//!
//! ## State of the crate
//!
//! This is an in-development version that supports only name, index, and wildcard selectors.
//! However, these are fully supported, tested, and fuzzed. The planned roadmap is:
//! - [x] support slices
//! - [ ] support filters (without functions)
//! - [ ] support functions (including type check)
//! - [ ] polish the API
//! - [ ] 1.0.0 stable release
//!
//! ## Examples
//! To create a query from a query string:
//! ```
//! # use rsonpath_syntax::{JsonPathQuery, Segment, Selectors, Selector, str::JsonString};
//! # use std::error::Error;
//! #
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let query_string = "$..phoneNumbers[*].number";
//! let query = rsonpath_syntax::parse(query_string)?;
//!
//! // Query structure is a linear sequence of segments:
//! // Descendant '..phoneNumbers', child wildcard, child 'number'.
//! assert_eq!(query.segments().len(), 3);
//! assert_eq!(
//!   query.segments()[0],
//!   Segment::Descendant(
//!     Selectors::one(
//!       Selector::Name(
//!         JsonString::new("phoneNumbers")
//! ))));
//! assert_eq!(
//!   query.segments()[1],
//!   Segment::Child(
//!     Selectors::one(
//!       Selector::Wildcard
//! )));
//! assert_eq!(
//!   query.segments()[2],
//!   Segment::Child(
//!     Selectors::one(
//!       Selector::Name(
//!         JsonString::new("number")
//! ))));
//! # Ok(())
//! # }
//! ```
//!
//! ## Crate features
//!
//! There are two optional features:
//! - `arbitrary`, which enables a dependency on the [`arbitrary` crate](https://docs.rs/arbitrary/latest/arbitrary/)
//!   to provide [`Arbitrary`](`arbitrary::Arbitrary`) implementations on query types; this is used e.g. for fuzzing.
//! - `color`, which enables a dependency on the [`owo_colors` crate](https://docs.rs/owo-colors/latest/owo_colors/)
//!   to provide colorful [`Display`] representations of [`ParseError`](error::ParseError);
//!   see [`ParseError::colored`](error::ParseError::colored).

#![forbid(unsafe_code)]
// Generic pedantic lints.
#![warn(
    explicit_outlives_requirements,
    semicolon_in_expressions_from_macros,
    unreachable_pub,
    unused_import_braces,
    unused_lifetimes
)]
// Clippy pedantic lints.
#![warn(
    clippy::allow_attributes_without_reason,
    clippy::cargo_common_metadata,
    clippy::cast_lossless,
    clippy::cloned_instead_of_copied,
    clippy::empty_drop,
    clippy::empty_line_after_outer_attr,
    clippy::equatable_if_let,
    clippy::expl_impl_clone_on_copy,
    clippy::explicit_deref_methods,
    clippy::explicit_into_iter_loop,
    clippy::explicit_iter_loop,
    clippy::fallible_impl_from,
    clippy::flat_map_option,
    clippy::if_then_some_else_none,
    clippy::inconsistent_struct_constructor,
    clippy::large_digit_groups,
    clippy::let_underscore_must_use,
    clippy::manual_ok_or,
    clippy::map_err_ignore,
    clippy::map_unwrap_or,
    clippy::match_same_arms,
    clippy::match_wildcard_for_single_variants,
    clippy::missing_inline_in_public_items,
    clippy::mod_module_files,
    clippy::must_use_candidate,
    clippy::needless_continue,
    clippy::needless_for_each,
    clippy::needless_pass_by_value,
    clippy::ptr_as_ptr,
    clippy::redundant_closure_for_method_calls,
    clippy::ref_binding_to_reference,
    clippy::ref_option_ref,
    clippy::rest_pat_in_fully_bound_structs,
    clippy::undocumented_unsafe_blocks,
    clippy::unneeded_field_pattern,
    clippy::unseparated_literal_suffix,
    clippy::unreadable_literal,
    clippy::unused_self,
    clippy::use_self
)]
// Panic-free lint.
#![warn(clippy::exit)]
// Panic-free lints (disabled for tests).
#![cfg_attr(not(test), warn(clippy::unwrap_used))]
// IO hygiene, only on --release.
#![cfg_attr(
    not(debug_assertions),
    warn(clippy::print_stderr, clippy::print_stdout, clippy::todo)
)]
// Documentation lints, enabled only on --release.
#![cfg_attr(
    not(debug_assertions),
    warn(missing_docs, clippy::missing_errors_doc, clippy::missing_panics_doc,)
)]
#![cfg_attr(not(debug_assertions), warn(rustdoc::missing_crate_level_docs))]
// Docs.rs config.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(html_logo_url = "https://raw.githubusercontent.com/V0ldek/rsonpath/main/img/rsonquery-logo.svg")]

pub mod builder;
pub mod error;
pub mod num;
mod parser;
pub mod str;

use std::{
    fmt::{self, Display},
    ops::Deref,
};

/// JSONPath query parser.
#[derive(Debug, Clone, Default)]
pub struct Parser {
    options: ParserOptions,
}

/// Configurable builder for a [`Parser`] instance.
#[derive(Debug, Clone, Default)]
pub struct ParserBuilder {
    options: ParserOptions,
}

#[derive(Debug, Clone)]
struct ParserOptions {
    relaxed_whitespace: bool,
}

impl ParserBuilder {
    /// Create a new instance of the builder with the default settings.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            options: ParserOptions::default(),
        }
    }

    /// Control whether leading and trailing whitespace is allowed in a query.
    /// Defaults to false.
    ///
    /// The [RFC](https://www.ietf.org/archive/id/draft-ietf-jsonpath-base-21.html) grammar
    /// makes leading and trailing whitespace disallowed. The [`Parser`] defaults to this strict handling,
    /// but can be relaxed with this setting.
    ///
    /// ## Examples
    /// ```
    /// # use rsonpath_syntax::{JsonPathQuery, Parser, ParserBuilder};
    /// let default_parser = ParserBuilder::new().build();
    /// let relaxed_parser = ParserBuilder::new()
    ///     .allow_surrounding_whitespace(true)
    ///     .build();
    ///
    /// let query = "  $.leading_whitespace";
    /// assert!(default_parser.parse(query).is_err());
    /// assert!(relaxed_parser.parse(query).is_ok());
    /// ```
    #[inline]
    pub fn allow_surrounding_whitespace(&mut self, value: bool) -> &mut Self {
        self.options.relaxed_whitespace = value;
        self
    }

    /// Build a new instance of a [`Parser`].
    #[inline]
    #[must_use]
    pub fn build(&self) -> Parser {
        Parser {
            options: self.options.clone(),
        }
    }
}

impl ParserOptions {
    fn is_leading_whitespace_allowed(&self) -> bool {
        self.relaxed_whitespace
    }

    fn is_trailing_whitespace_allowed(&self) -> bool {
        self.relaxed_whitespace
    }
}

impl Default for ParserOptions {
    #[inline(always)]
    fn default() -> Self {
        Self {
            relaxed_whitespace: false,
        }
    }
}

impl From<ParserBuilder> for Parser {
    #[inline(always)]
    fn from(value: ParserBuilder) -> Self {
        Self { options: value.options }
    }
}

/// Convenience alias for [`Result`](std::result::Result) values returned by this crate.
pub type Result<T> = std::result::Result<T, error::ParseError>;

/// Parse a JSONPath query string using default [`Parser`] configuration.
///
/// ## Errors
/// Fails if the string does not represent a valid JSONPath query
/// as governed by the [JSONPath RFC specification](https://www.ietf.org/archive/id/draft-ietf-jsonpath-base-21.html).
///
/// Note that leading and trailing whitespace is explicitly disallowed by the spec.
/// This can be relaxed with a custom [`Parser`] configured with [`ParserBuilder::allow_surrounding_whitespace`].
///
/// # Examples
/// ```
/// # use rsonpath_syntax::parse;
/// let x = "  $.a  ";
/// let err = rsonpath_syntax::parse(x).expect_err("should fail");
/// assert_eq!(err.to_string(),
/// "error: query starting with whitespace
///
///     $.a  
///   ^^ leading whitespace is disallowed
///   (bytes 0-1)
///
///
///error: query ending with whitespace
///
///     $.a  
///        ^^ trailing whitespace is disallowed
///   (bytes 5-6)
///
///
///suggestion: did you mean `$.a` ?
///");
/// ```
#[inline]
pub fn parse(str: &str) -> Result<JsonPathQuery> {
    Parser::default().parse(str)
}

impl Parser {
    /// Parse a JSONPath query string.
    ///
    /// ## Errors
    /// Fails if the string does not represent a valid JSONPath query
    /// as governed by the [JSONPath RFC specification](https://www.ietf.org/archive/id/draft-ietf-jsonpath-base-21.html).
    ///
    /// Note that leading and trailing whitespace is explicitly disallowed by the spec.
    /// The parser defaults to this strict behavior unless configured with
    /// [`ParserBuilder::allow_surrounding_whitespace`].
    #[inline]
    pub fn parse(&self, str: &str) -> Result<JsonPathQuery> {
        crate::parser::parse_json_path_query(str, &self.options)
    }
}

/// JSONPath query segment.
///
/// Every query is a sequence of zero or more of segments,
/// each applying one or more selectors to a node and passing it along to the
/// subsequent segments.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum Segment {
    /// A child segment contains a sequence of selectors,
    /// each of which selects zero or more children of a node.
    Child(Selectors),
    /// A child segment contains a sequence of selectors,
    /// each of which selects zero or more descendants of a node.
    Descendant(Selectors),
}

// We don't derive this because an empty Vec of Selectors is not a valid representation.
#[cfg(feature = "arbitrary")]
#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
impl<'a> arbitrary::Arbitrary<'a> for Selectors {
    #[inline]
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let first = u.arbitrary::<Selector>()?;
        let mut rest = u.arbitrary::<Vec<Selector>>()?;
        rest.push(first);

        Ok(Self::many(rest))
    }
}

/// Collection of one or more [`Selector`] instances.
///
/// Guaranteed to be non-empty.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct Selectors {
    inner: Vec<Selector>,
}

/// Each [`Segment`] defines one or more selectors.
/// A selector produces one or more children/descendants of the node it is applied to.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum Selector {
    /// A name selector selects at most one object member value under the key equal to the
    /// selector's [`JsonString`](str::JsonString).
    Name(str::JsonString),
    /// A wildcard selector selects the nodes of all children of an object or array.
    Wildcard,
    /// An index selector matches at most one array element value,
    /// depending on the selector's [`Index`].
    Index(Index),
    /// A slice selector matches elements from arrays starting at a given index,
    /// ending at a given index, and incrementing with a specified step.
    Slice(Slice),
}

/// Directional index into a JSON array.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum Index {
    /// Zero-based index from the start of the array.
    FromStart(num::JsonUInt),
    /// Index from the end of the array.
    ///
    /// `-1` is the last element, `-2` is the second last, etc.
    FromEnd(num::JsonNonZeroUInt),
}

// We don't derive this because FromEnd(0) is not a valid index.
#[cfg(feature = "arbitrary")]
#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
impl<'a> arbitrary::Arbitrary<'a> for Index {
    #[inline]
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let num = u.arbitrary::<num::JsonInt>()?;
        Ok(Self::from(num))
    }
}

impl From<num::JsonInt> for Index {
    #[inline]
    fn from(value: num::JsonInt) -> Self {
        if value.as_i64() >= 0 {
            Self::FromStart(value.abs())
        } else {
            Self::FromEnd(value.abs().try_into().expect("checked for zero already"))
        }
    }
}

/// Directional step offset within a JSON array.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum Step {
    /// Step forward by a given offset amount.
    Forward(num::JsonUInt),
    /// Step backward by a given offset amount.
    Backward(num::JsonNonZeroUInt),
}

// We don't derive this because Backward(0) is not a valid step.
#[cfg(feature = "arbitrary")]
#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
impl<'a> arbitrary::Arbitrary<'a> for Step {
    #[inline]
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let num = u.arbitrary::<num::JsonInt>()?;
        Ok(Self::from(num))
    }
}

impl From<num::JsonInt> for Step {
    #[inline]
    fn from(value: num::JsonInt) -> Self {
        if value.as_i64() >= 0 {
            Self::Forward(value.abs())
        } else {
            Self::Backward(value.abs().try_into().expect("checked for zero already"))
        }
    }
}

/// Slice selector defining the start and end bounds, as well as the step value and direction.
///
/// The start index is inclusive defaults to `Index::FromStart(0)`.
///
/// The end index is exclusive and optional.
/// If `None`, the end of the slice depends on the step direction:
/// - if going forward, the end is `len` of the array;
/// - if going backward, the end is 0.
///
/// The step defaults to `Step::Forward(1)`. Note that `Step::Forward(0)` is a valid
/// value and is specified to result in an empty slice, regardless of `start` and `end`.
///
/// # Examples
/// ```
/// # use rsonpath_syntax::{Slice, Index, Step, num::JsonUInt};
/// let slice = Slice::default();
/// assert_eq!(slice.start(), Index::FromStart(JsonUInt::ZERO));
/// assert_eq!(slice.end(), None);
/// assert_eq!(slice.step(), Step::Forward(JsonUInt::ONE));
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Slice {
    start: Index,
    end: Option<Index>,
    step: Step,
}

/// Helper API for programmatically constructing [`Slice`] instances.
///
/// # Examples
/// ```
/// # use rsonpath_syntax::{Slice, SliceBuilder, Index, Step, num::JsonUInt};
/// let mut builder = SliceBuilder::new();
///
/// builder.with_start(-3).with_end(1).with_step(-7);
///
/// let slice: Slice = builder.into();
/// assert_eq!(slice.to_string(), "-3:1:-7");
/// ```
pub struct SliceBuilder {
    inner: Slice,
}

impl Slice {
    const DEFAULT_START: Index = Index::FromStart(num::JsonUInt::ZERO);
    const DEFAULT_STEP: Step = Step::Forward(num::JsonUInt::ONE);

    /// Create a new [`Slice`] from given bounds and step.
    #[inline(always)]
    #[must_use]
    pub fn new(start: Index, end: Option<Index>, step: Step) -> Self {
        Self { start, end, step }
    }

    /// Get the start index of the [`Slice`].
    #[inline(always)]
    #[must_use]
    pub fn start(&self) -> Index {
        self.start
    }

    /// Get the end index of the [`Slice`].
    #[inline(always)]
    #[must_use]
    pub fn end(&self) -> Option<Index> {
        self.end
    }

    /// Get the step of the [`Slice`].
    #[inline(always)]
    #[must_use]
    pub fn step(&self) -> Step {
        self.step
    }
}

impl Default for Slice {
    #[inline]
    fn default() -> Self {
        Self {
            start: Index::FromStart(0.into()),
            end: None,
            step: Step::Forward(1.into()),
        }
    }
}

impl SliceBuilder {
    /// Create a new [`Slice`] configuration with default values.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Slice::default(),
        }
    }

    /// Set the start of the [`Slice`].
    #[inline]
    pub fn with_start<N: Into<num::JsonInt>>(&mut self, start: N) -> &mut Self {
        self.inner.start = start.into().into();
        self
    }

    /// Set the end of the [`Slice`].
    #[inline]
    pub fn with_end<N: Into<num::JsonInt>>(&mut self, end: N) -> &mut Self {
        self.inner.end = Some(end.into().into());
        self
    }

    /// Set the step of the [`Slice`].
    #[inline]
    pub fn with_step<N: Into<num::JsonInt>>(&mut self, step: N) -> &mut Self {
        self.inner.step = step.into().into();
        self
    }

    /// Get the configured [`Slice`] instance.
    ///
    /// This does not consume the builder. For a consuming variant use the `Into<Slice>` impl.
    #[inline]
    #[must_use]
    pub fn to_slice(&mut self) -> Slice {
        self.inner.clone()
    }
}

impl From<SliceBuilder> for Slice {
    #[inline]
    #[must_use]
    fn from(value: SliceBuilder) -> Self {
        value.inner
    }
}

impl Default for SliceBuilder {
    #[inline(always)]
    #[must_use]
    fn default() -> Self {
        Self::new()
    }
}

/// JSONPath query structure represented by a sequence of [`Segments`](Segment).
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct JsonPathQuery {
    segments: Vec<Segment>,
}

impl JsonPathQuery {
    /// Returns all [`Segments`](Segment) of the query as a slice.
    #[inline(always)]
    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }
}

impl Segment {
    /// Returns all [`Selector`] instances of the segment.
    #[inline(always)]
    #[must_use]
    pub fn selectors(&self) -> &Selectors {
        match self {
            Self::Child(s) | Self::Descendant(s) => s,
        }
    }

    /// Check if this is a child segment.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selectors, Segment, Selector};
    /// let segment = Segment::Child(Selectors::one(Selector::Wildcard));
    /// assert!(segment.is_child());
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn is_child(&self) -> bool {
        matches!(self, Self::Child(_))
    }

    /// Check if this is a descendant segment.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selectors, Segment, Selector};
    /// let segment = Segment::Descendant(Selectors::one(Selector::Wildcard));
    /// assert!(segment.is_descendant());
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn is_descendant(&self) -> bool {
        matches!(self, Self::Descendant(_))
    }
}

impl Selectors {
    /// Create a singleton [`Selectors`] instance.
    #[inline(always)]
    #[must_use]
    pub fn one(selector: Selector) -> Self {
        Self { inner: vec![selector] }
    }

    /// Create a [`Selectors`] instance taking ownership of the `vec`.
    ///
    /// ## Panics
    /// If the `vec` is empty.
    ///
    /// ```should_panic
    /// # use rsonpath_syntax::Selectors;
    /// Selectors::many(vec![]);
    /// ```
    #[inline]
    #[must_use]
    pub fn many(vec: Vec<Selector>) -> Self {
        assert!(!vec.is_empty(), "cannot create an empty Selectors collection");
        Self { inner: vec }
    }

    /// Get a reference to the first [`Selector`] in the collection.
    #[inline]
    #[must_use]
    pub fn first(&self) -> &Selector {
        &self.inner[0]
    }

    /// Get the selectors as a non-empty slice.
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[Selector] {
        // Deref magic.
        self
    }
}

impl Selector {
    /// Check if this is a name selector.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selector, str::JsonString};
    /// let selector = Selector::Name(JsonString::new("abc"));
    /// assert!(selector.is_name());
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_name(&self) -> bool {
        matches!(self, Self::Name(_))
    }

    /// Check if this is a wildcard selector.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::Selector;
    /// let selector = Selector::Wildcard;
    /// assert!(selector.is_wildcard());
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_wildcard(&self) -> bool {
        matches!(self, Self::Wildcard)
    }

    /// Check if this is an index selector.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selector, Index};
    /// let selector = Selector::Index(Index::FromStart(0.into()));
    /// assert!(selector.is_index());
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_index(&self) -> bool {
        matches!(self, Self::Index(_))
    }
}

impl Index {
    /// Check if this is an index counting from the start of an array.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selector, Index};
    /// let index = Index::FromStart(0.into());
    /// assert!(index.is_start_based());
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_start_based(&self) -> bool {
        matches!(self, Self::FromStart(_))
    }

    /// Check if this is an index counting from the end of an array.
    ///
    /// # Examples
    /// ```
    /// # use rsonpath_syntax::{Selector, Index};
    /// let index = Index::FromEnd(1.try_into().unwrap());
    /// assert!(index.is_end_based());
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_end_based(&self) -> bool {
        matches!(self, Self::FromEnd(_))
    }
}

impl Deref for Selectors {
    type Target = [Selector];

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl Display for JsonPathQuery {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "$")?;
        for s in &self.segments {
            write!(f, "{s}")?;
        }
        Ok(())
    }
}

impl Display for Segment {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Child(s) => write!(f, "{s}"),
            Self::Descendant(s) => write!(f, "..{s}"),
        }
    }
}

impl Display for Selectors {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}", self.first())?;
        for s in self.inner.iter().skip(1) {
            write!(f, ", {s}")?;
        }
        write!(f, "]")?;
        Ok(())
    }
}

impl Display for Selector {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Name(n) => write!(f, "'{}'", str::escape(n.unquoted(), str::EscapeMode::SingleQuoted)),
            Self::Wildcard => write!(f, "*"),
            Self::Index(idx) => write!(f, "{idx}"),
            Self::Slice(slice) => write!(f, "{slice}"),
        }
    }
}

impl Display for Index {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FromStart(idx) => write!(f, "{idx}"),
            Self::FromEnd(idx) => write!(f, "-{idx}"),
        }
    }
}

impl Display for Step {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Forward(idx) => write!(f, "{idx}"),
            Self::Backward(idx) => write!(f, "-{idx}"),
        }
    }
}

impl Display for Slice {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.start != Self::DEFAULT_START {
            write!(f, "{}", self.start)?;
        }
        write!(f, ":")?;
        if let Some(end) = self.end {
            write!(f, "{end}")?;
        }
        if self.step != Self::DEFAULT_STEP {
            write!(f, ":{}", self.step)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn leading_whitespace_is_disallowed() {
        let err = parse("  $").expect_err("should fail");
        let display = format!("{err}");
        let expected = r"error: query starting with whitespace

    $
  ^^ leading whitespace is disallowed
  (bytes 0-1)


suggestion: did you mean `$` ?
";
        assert_eq!(display, expected);
    }

    #[test]
    fn trailing_whitespace_is_disallowed() {
        let err = parse("$  ").expect_err("should fail");
        let display = format!("{err}");
        let expected = r"error: query ending with whitespace

  $  
   ^^ trailing whitespace is disallowed
  (bytes 1-2)


suggestion: did you mean `$` ?
";
        assert_eq!(display, expected);
    }

    mod name_selector {
        use super::*;
        use pretty_assertions::assert_eq;
        use test_case::test_case;

        fn parse_single_quoted_name_selector(src: &str) -> Result<JsonPathQuery> {
            let query_string = format!("$['{src}']");
            parse(&query_string)
        }

        #[test_case("", ""; "empty")]
        #[test_case("dog", "dog"; "ascii")]
        #[test_case(r"\\", r"\"; "backslash")]
        #[test_case("unescaped 🔥 fire emoji", "unescaped 🔥 fire emoji"; "unescaped emoji")]
        #[test_case(r"escape \b backspace", "escape \u{0008} backspace"; "BS escape")]
        #[test_case(r"escape \t tab", "escape \t tab"; "HT escape")]
        #[test_case(r"escape \n endln", "escape \n endln"; "LF escape")]
        #[test_case(r"escape \f formfeed", "escape \u{000C} formfeed"; "FF escape")]
        #[test_case(r"escape \r carriage", "escape \r carriage"; "CR escape")]
        #[test_case(r#"escape \' apost"#, r"escape ' apost"; "apostrophe escape")]
        #[test_case(r"escape \/ slash", r"escape / slash"; "slash escape")]
        #[test_case(r"escape \\ backslash", r"escape \ backslash"; "backslash escape")]
        #[test_case(r"escape \u2112 script L", "escape ℒ script L"; "U+2112 Script Capital L escape")]
        #[test_case(r"escape \u211269 script L", "escape ℒ69 script L"; "U+2112 Script Capital L escape followed by digits")]
        #[test_case(r"escape \u21a7 bar down arrow", "escape ↧ bar down arrow"; "U+21a7 Downwards Arrow From Bar (lowercase hex)")]
        #[test_case(r"escape \u21A7 bar down arrow", "escape ↧ bar down arrow"; "U+21A7 Downwards Arrow From Bar (uppercase hex)")]
        #[test_case(r"escape \ud83d\udd25 fire emoji", "escape 🔥 fire emoji"; "U+1F525 fire emoji escape (lowercase hex)")]
        #[test_case(r"escape \uD83D\uDD25 fire emoji", "escape 🔥 fire emoji"; "U+1F525 fire emoji escape (uppercase hex)")]
        fn parse_correct_single_quoted_name(src: &str, expected: &str) {
            let res = parse_single_quoted_name_selector(src).expect("should successfully parse");
            match res.segments().first() {
                Some(Segment::Child(selectors)) => match selectors.first() {
                    Selector::Name(name) => assert_eq!(name.unquoted(), expected),
                    _ => panic!("expected to parse a single name selector, got {res:?}"),
                },
                _ => panic!("expected to parse a single name selector, got {res:?}"),
            }
        }

        #[test]
        fn parse_double_quoted_name_with_escaped_double_quote() {
            let query_string = r#"$["escape \" quote"]"#;
            let res = parse(query_string).expect("should successfully parse");
            match res.segments().first() {
                Some(Segment::Child(selectors)) => match selectors.first() {
                    Selector::Name(name) => assert_eq!(name.unquoted(), "escape \" quote"),
                    _ => panic!("expected to parse a single name selector, got {res:?}"),
                },
                _ => panic!("expected to parse a single name selector, got {res:?}"),
            }
        }
    }
}