noyalib 0.0.55

A pure Rust YAML library with zero unsafe code and full serde integration
Documentation
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
//! Path tracking for YAML structure locations.
//!
//! This module provides the [`Path`] type for tracking the location within a
//! YAML document structure. It's primarily used for providing meaningful error
//! messages that indicate exactly where in the YAML structure an error
//! occurred.
//!
//! # Examples
//!
//! ```rust
//! use noyalib::Path;
//!
//! // Represent the path: root -> "dependencies" -> "serde" -> "version"
//! let root = Path::Root;
//! let deps = Path::Map {
//!     parent: &root,
//!     key: "dependencies",
//! };
//! let serde = Path::Map {
//!     parent: &deps,
//!     key: "serde",
//! };
//! let version = Path::Map {
//!     parent: &serde,
//!     key: "version",
//! };
//!
//! assert_eq!(version.to_string(), "dependencies.serde.version");
//! ```
//!
//! # Query paths
//!
//! The path strings read by [`Value::get_path`](crate::Value::get_path),
//! [`Value::query`](crate::Value::query), the borrowed reads, and every
//! path-taking `cst::Document` method share one grammar: `.` separates
//! mapping keys, `[n]` indexes a sequence, `*` and `[*]` match every
//! child, and `..` descends recursively. A key that itself contains one
//! of those characters is written as a bracket-quoted segment, `["a.b"]`
//! or `['a[0]']`, inside which `\` escapes the next character.
//! [`quote_key`] spells one such segment, [`push_key`] appends a key to
//! a path in whichever form reads back as that key, and [`join_keys`]
//! builds a whole path from literal keys:
//!
//! ```rust
//! use noyalib::path::{join_keys, quote_key};
//!
//! assert_eq!(quote_key("app.kubernetes.io/name"), r#"["app.kubernetes.io/name"]"#);
//! assert_eq!(
//!     join_keys(["labels", "app.kubernetes.io/name"]),
//!     r#"labels["app.kubernetes.io/name"]"#,
//! );
//! assert_eq!(join_keys(["server", "port"]), "server.port");
//! ```

// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

use crate::prelude::*;
use core::{fmt, fmt::Display, str::FromStr};

/// Represents a path to a location within a YAML document structure.
///
/// `Path` is a recursive data structure that tracks the navigation path from
/// the root of a YAML document to a specific value. It's used to provide
/// context in error messages, helping users understand exactly where in their
/// YAML an issue occurred.
///
/// # Variants
///
/// - [`Root`](Path::Root): The root of the document
/// - [`Seq`](Path::Seq): An index into a sequence (array)
/// - [`Map`](Path::Map): A key in a mapping (object)
/// - [`Alias`](Path::Alias): Following an alias reference
/// - [`Unknown`](Path::Unknown): Unknown or unspecified location
///
/// # Examples
///
/// ```rust
/// use noyalib::Path;
///
/// // Building a path: servers[0].host
/// let root = Path::Root;
/// let servers = Path::Map {
///     parent: &root,
///     key: "servers",
/// };
/// let first = Path::Seq {
///     parent: &servers,
///     index: 0,
/// };
/// let host = Path::Map {
///     parent: &first,
///     key: "host",
/// };
///
/// assert_eq!(host.to_string(), "servers[0].host");
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum Path<'a> {
    /// The root of the document.
    ///
    /// This is the starting point for all paths. When displayed, it shows as
    /// `.`.
    #[default]
    Root,

    /// An index into a sequence (array).
    ///
    /// # Fields
    ///
    /// - `parent`: The path to the sequence containing this element
    /// - `index`: The zero-based index into the sequence
    Seq {
        /// The parent path (the sequence itself).
        parent: &'a Self,
        /// The index within the sequence (zero-based).
        index: usize,
    },

    /// A key in a mapping (object).
    ///
    /// # Fields
    ///
    /// - `parent`: The path to the mapping containing this key
    /// - `key`: The key name
    Map {
        /// The parent path (the mapping itself).
        parent: &'a Self,
        /// The key within the mapping.
        key: &'a str,
    },

    /// Following an alias reference.
    ///
    /// This variant is used when traversing through a YAML alias (`*anchor`)
    /// to indicate the path continues through an alias.
    Alias {
        /// The parent path before the alias.
        parent: &'a Self,
    },

    /// Unknown or unspecified location.
    ///
    /// This variant is used when the exact location cannot be determined
    /// but we still want to track that we're somewhere nested.
    Unknown {
        /// The parent path.
        parent: &'a Self,
    },
}

impl<'a> Path<'a> {
    /// Creates a new sequence index path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// let items = Path::Map {
    ///     parent: &root,
    ///     key: "items",
    /// };
    /// let first = items.index(0);
    ///
    /// assert_eq!(first.to_string(), "items[0]");
    /// ```
    #[must_use]
    pub fn index(&'a self, index: usize) -> Self {
        Path::Seq {
            parent: self,
            index,
        }
    }

    /// Creates a new map key path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// let config = root.key("config");
    /// let host = config.key("host");
    ///
    /// assert_eq!(host.to_string(), "config.host");
    /// ```
    #[must_use]
    pub fn key(&'a self, key: &'a str) -> Self {
        Path::Map { parent: self, key }
    }

    /// Creates a new alias path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// let alias_path = root.alias();
    /// ```
    #[must_use]
    pub fn alias(&'a self) -> Self {
        Path::Alias { parent: self }
    }

    /// Creates a new unknown path.
    #[must_use]
    pub fn unknown(&'a self) -> Self {
        Path::Unknown { parent: self }
    }

    /// Returns `true` if this is the root path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// assert!(root.is_root());
    ///
    /// let child = root.key("test");
    /// assert!(!child.is_root());
    /// ```
    #[must_use]
    pub fn is_root(&self) -> bool {
        matches!(self, Path::Root)
    }

    /// Returns the parent path, if any.
    ///
    /// Returns `None` if this is the root path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// let child = root.key("test");
    ///
    /// assert!(root.parent().is_none());
    /// assert!(child.parent().is_some());
    /// ```
    #[must_use]
    pub fn parent(&self) -> Option<&Self> {
        match self {
            Path::Root => None,
            Path::Seq { parent, .. }
            | Path::Map { parent, .. }
            | Path::Alias { parent }
            | Path::Unknown { parent } => Some(parent),
        }
    }

    /// Returns the depth of this path (number of segments from root).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use noyalib::Path;
    ///
    /// let root = Path::Root;
    /// assert_eq!(root.depth(), 0);
    ///
    /// let child = root.key("a").key("b");
    /// // Note: each key() creates a new path on the stack
    /// ```
    #[must_use]
    pub fn depth(&self) -> usize {
        match self {
            Path::Root => 0,
            Path::Seq { parent, .. }
            | Path::Map { parent, .. }
            | Path::Alias { parent }
            | Path::Unknown { parent } => 1 + parent.depth(),
        }
    }
}

impl Display for Path<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        /// Helper struct to format the parent path with a trailing dot if
        /// needed.
        struct Parent<'a>(&'a Path<'a>);

        impl Display for Parent<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self.0 {
                    Path::Root => Ok(()),
                    path => write!(f, "{path}."),
                }
            }
        }

        /// Helper struct to format the parent path without trailing dot for
        /// sequences.
        struct ParentNoDot<'a>(&'a Path<'a>);

        impl Display for ParentNoDot<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self.0 {
                    Path::Root => Ok(()),
                    path => write!(f, "{path}"),
                }
            }
        }

        match self {
            Path::Root => f.write_str("."),
            Path::Seq { parent, index } => {
                write!(f, "{}[{}]", ParentNoDot(parent), index)
            }
            Path::Map { parent, key } => {
                write!(f, "{}{}", Parent(parent), key)
            }
            Path::Alias { parent } => {
                write!(f, "{}", Parent(parent))
            }
            Path::Unknown { parent } => {
                write!(f, "{}?", Parent(parent))
            }
        }
    }
}

// ── Query path parsing ──────────────────────────────────────────────────
// Shared path parsing for value.rs and borrowed.rs query methods.

/// A parsed segment in a [`QueryPath`].
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum QuerySegment {
    /// A key in a mapping.
    Key(String),
    /// An index in a sequence.
    Index(usize),
    /// Wildcard: matches all keys or all indices.
    Wildcard,
    /// Recursive descent: matches at any depth.
    RecursiveDescent,
}

/// A validated query path.
///
/// Parsing is atomic: malformed input returns [`PathError`] and never
/// exposes a successfully parsed prefix. Use this type when a path comes
/// from an untrusted configuration, command line, or network request and
/// the caller must distinguish an invalid path from a path that is valid
/// but does not match a value.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct QueryPath(Vec<QuerySegment>);

impl QueryPath {
    /// Parse and validate a query path.
    ///
    /// The empty string is the root path. Empty segments, incomplete
    /// brackets, invalid indices, and trailing separators are rejected.
    pub fn parse(input: &str) -> Result<Self, PathError> {
        parse_query_path_checked(input).map(Self)
    }

    /// Return the validated path segments.
    #[must_use]
    pub fn segments(&self) -> &[QuerySegment] {
        &self.0
    }

    /// Return whether this path addresses the root value.
    #[must_use]
    pub fn is_root(&self) -> bool {
        self.0.is_empty()
    }
}

impl FromStr for QueryPath {
    type Err = PathError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::parse(input)
    }
}

impl Display for QueryPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut rendered = String::new();
        let mut after_descent = false;
        for segment in &self.0 {
            match segment {
                QuerySegment::Key(key) if is_plain_key(key) => {
                    if !rendered.is_empty() && !after_descent {
                        rendered.push('.');
                    }
                    rendered.push_str(key);
                }
                QuerySegment::Key(key) => rendered.push_str(&quote_key(key)),
                QuerySegment::Index(index) => {
                    use core::fmt::Write as _;
                    write!(rendered, "[{index}]")?;
                }
                QuerySegment::Wildcard => rendered.push_str("[*]"),
                QuerySegment::RecursiveDescent => rendered.push_str(".."),
            }
            after_descent = matches!(segment, QuerySegment::RecursiveDescent);
        }
        f.write_str(&rendered)
    }
}

/// The category of a query-path syntax error.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum PathErrorKind {
    /// A dot would create an empty mapping-key segment.
    EmptySegment,
    /// A dot appeared immediately before a bracket segment.
    SeparatorBeforeBracket,
    /// A bracket segment has no closing bracket.
    UnterminatedBracket,
    /// A quoted mapping key has no closing quote.
    UnterminatedQuotedKey,
    /// A quoted mapping key ends with an incomplete escape.
    DanglingEscape,
    /// A quoted mapping key is not followed by `]`.
    ExpectedClosingBracket,
    /// Bracket content is neither an index nor `*`.
    InvalidBracketSegment,
    /// A numeric sequence index does not fit in [`usize`].
    IndexOverflow,
    /// A closing bracket appeared outside a bracket segment.
    StrayClosingBracket,
    /// The path ends with a dot separator.
    DanglingSeparator,
}

/// An error returned when a query path is syntactically invalid.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct PathError {
    kind: PathErrorKind,
}

impl PathError {
    const fn new(kind: PathErrorKind) -> Self {
        Self { kind }
    }

    /// Return the stable error category.
    #[must_use]
    pub const fn kind(self) -> PathErrorKind {
        self.kind
    }
}

impl Display for PathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self.kind {
            PathErrorKind::EmptySegment => "query path contains an empty segment",
            PathErrorKind::SeparatorBeforeBracket => {
                "query path has a separator before a bracket segment"
            }
            PathErrorKind::UnterminatedBracket => "query path has an unterminated bracket",
            PathErrorKind::UnterminatedQuotedKey => "query path has an unterminated quoted key",
            PathErrorKind::DanglingEscape => "query path has a dangling quoted-key escape",
            PathErrorKind::ExpectedClosingBracket => {
                "a quoted query-path key must be followed by a closing bracket"
            }
            PathErrorKind::InvalidBracketSegment => {
                "query-path bracket content must be an index or wildcard"
            }
            PathErrorKind::IndexOverflow => "query-path sequence index overflows usize",
            PathErrorKind::StrayClosingBracket => "query path contains a stray closing bracket",
            PathErrorKind::DanglingSeparator => "query path ends with a separator",
        };
        f.write_str(message)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PathError {}

/// Parse a query path string into segments.
///
/// Supports:
/// - Dot notation: `"foo.bar.baz"`
/// - Bracket notation: `"items[0]"`
/// - Quoted keys: `"labels[\"app.kubernetes.io/name\"]"` — the text
///   between the quotes is one mapping key, whatever it contains, so a
///   key holding `.`, `[`, `]`, or `*` is addressable. Either quote
///   style works (`['a[0]']`, `["*"]`); inside both, `\` escapes the
///   next character, so `["say \"hi\""]` is the key `say "hi"`.
///   [`quote_key`] spells such a segment.
/// - Mixed: `"items[0].name"`, `"items[0][\"a.b\"].c"`
/// - Wildcard: `"items[*]"` or `"items.*"`
/// - Recursive descent: `"..name"` (find `name` at any depth)
///
/// Malformed paths never produce a partial prefix. Invalid bracket
/// content, unterminated quoted keys, stray closing brackets, and
/// dangling separators resolve to an impossible sentinel segment so a
/// read returns no match and a mutator reports its existing path error
/// without touching an ancestor node.
pub(crate) fn parse_query_path(path: &str) -> Vec<QuerySegment> {
    parse_query_path_checked(path).unwrap_or_else(|_| {
        // NUL is forbidden in YAML scalar content, so no parsed mapping
        // can contain this key. Keeping the public callers' existing
        // `Option` / `Result` shapes avoids a breaking API change while
        // guaranteeing malformed input cannot resolve to the root or a
        // successfully parsed prefix.
        vec![QuerySegment::Key("\0noyalib::invalid-query-path\0".into())]
    })
}

fn parse_query_path_checked(path: &str) -> Result<Vec<QuerySegment>, PathError> {
    let mut segments = Vec::new();
    let mut current = String::new();
    let mut chars = path.chars().peekable();
    let mut separator_pending = false;

    while let Some(c) = chars.next() {
        match c {
            '.' => {
                let had_current = !current.is_empty();
                if had_current {
                    segments.push(QuerySegment::Key(core::mem::take(&mut current)));
                }
                if chars.peek() == Some(&'.') {
                    if separator_pending {
                        return Err(PathError::new(PathErrorKind::EmptySegment));
                    }
                    let _ = chars.next();
                    segments.push(QuerySegment::RecursiveDescent);
                    separator_pending = false;
                } else if (!had_current && segments.is_empty()) || separator_pending {
                    return Err(PathError::new(PathErrorKind::EmptySegment));
                } else {
                    separator_pending = true;
                }
            }
            '[' => {
                if separator_pending {
                    return Err(PathError::new(PathErrorKind::SeparatorBeforeBracket));
                }
                if !current.is_empty() {
                    segments.push(QuerySegment::Key(core::mem::take(&mut current)));
                }
                if let Some(&quote @ ('"' | '\'')) = chars.peek() {
                    let _ = chars.next();
                    let key = read_quoted_key(&mut chars, quote)?;
                    if chars.next() != Some(']') {
                        return Err(PathError::new(PathErrorKind::ExpectedClosingBracket));
                    }
                    segments.push(QuerySegment::Key(key));
                    separator_pending = false;
                    continue;
                }
                let mut index_str = String::new();
                let mut closed = false;
                while let Some(&c) = chars.peek() {
                    if c == ']' {
                        let _ = chars.next();
                        closed = true;
                        break;
                    }
                    index_str.push(c);
                    let _ = chars.next();
                }
                if !closed {
                    return Err(PathError::new(PathErrorKind::UnterminatedBracket));
                }
                if index_str == "*" {
                    segments.push(QuerySegment::Wildcard);
                } else if index_str.bytes().all(|byte| byte.is_ascii_digit())
                    && !index_str.is_empty()
                {
                    let idx = index_str
                        .parse::<usize>()
                        .map_err(|_| PathError::new(PathErrorKind::IndexOverflow))?;
                    segments.push(QuerySegment::Index(idx));
                } else {
                    return Err(PathError::new(PathErrorKind::InvalidBracketSegment));
                }
                separator_pending = false;
            }
            ']' => return Err(PathError::new(PathErrorKind::StrayClosingBracket)),
            '*' => {
                if !current.is_empty() {
                    segments.push(QuerySegment::Key(core::mem::take(&mut current)));
                }
                segments.push(QuerySegment::Wildcard);
                separator_pending = false;
            }
            _ => {
                current.push(c);
                separator_pending = false;
            }
        }
    }

    if separator_pending {
        return Err(PathError::new(PathErrorKind::DanglingSeparator));
    }
    if !current.is_empty() {
        segments.push(QuerySegment::Key(current));
    }

    Ok(segments)
}

/// Read the body of a quoted key segment up to its closing `quote`,
/// consuming the quote. `\` escapes the next character.
fn read_quoted_key(
    chars: &mut core::iter::Peekable<core::str::Chars<'_>>,
    quote: char,
) -> Result<String, PathError> {
    let mut key = String::new();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                let escaped = chars
                    .next()
                    .ok_or_else(|| PathError::new(PathErrorKind::DanglingEscape))?;
                key.push(escaped);
            }
            c if c == quote => return Ok(key),
            c => key.push(c),
        }
    }
    Err(PathError::new(PathErrorKind::UnterminatedQuotedKey))
}

/// Whether the query grammar reads `key` back as itself when it is
/// written plain: it is not empty and holds none of `.`, `[`, `]`, `*`.
fn is_plain_key(key: &str) -> bool {
    !key.is_empty() && !key.contains(['.', '[', ']', '*'])
}

/// Spell `key` as one bracket-quoted path segment, `["key"]`, that
/// [`Value::get_path`](crate::Value::get_path) and every path-taking
/// `cst::Document` method read back as exactly that mapping key. `"`
/// and `\` inside the key are escaped.
///
/// # Examples
///
/// ```rust
/// use noyalib::path::quote_key;
///
/// assert_eq!(quote_key("app.kubernetes.io/name"), r#"["app.kubernetes.io/name"]"#);
/// assert_eq!(quote_key("*"), r#"["*"]"#);
/// assert_eq!(quote_key(r#"say "hi""#), r#"["say \"hi\""]"#);
/// ```
#[must_use]
pub fn quote_key(key: &str) -> String {
    let mut out = String::with_capacity(key.len() + 4);
    out.push_str("[\"");
    for c in key.chars() {
        if matches!(c, '"' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out.push_str("\"]");
    out
}

/// Append the mapping key `key` to `path`: in dot notation when the
/// grammar reads the plain spelling back as that key, otherwise as the
/// segment [`quote_key`] spells. A quoted segment needs no separator.
///
/// # Examples
///
/// ```rust
/// use noyalib::path::push_key;
///
/// let mut path = String::from("items[0]");
/// push_key(&mut path, "labels");
/// push_key(&mut path, "app.kubernetes.io/name");
/// assert_eq!(path, r#"items[0].labels["app.kubernetes.io/name"]"#);
/// ```
pub fn push_key(path: &mut String, key: &str) {
    if is_plain_key(key) {
        if !path.is_empty() {
            path.push('.');
        }
        path.push_str(key);
    } else {
        path.push_str(&quote_key(key));
    }
}

/// Build a path from literal mapping keys, one [`push_key`] per key, so
/// every key reads back as itself whatever it contains.
///
/// # Examples
///
/// ```rust
/// use noyalib::path::join_keys;
///
/// assert_eq!(join_keys(["server", "port"]), "server.port");
/// assert_eq!(join_keys(["a", "b.c", "*"]), r#"a["b.c"]["*"]"#);
/// assert_eq!(join_keys(Vec::<&str>::new()), "");
/// ```
#[must_use]
pub fn join_keys<K: AsRef<str>>(keys: impl IntoIterator<Item = K>) -> String {
    let mut path = String::new();
    for key in keys {
        push_key(&mut path, key.as_ref());
    }
    path
}

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

    #[test]
    fn test_path_root_display() {
        let root = Path::Root;
        assert_eq!(root.to_string(), ".");
    }

    #[test]
    fn test_path_map_display() {
        let root = Path::Root;
        let key1 = Path::Map {
            parent: &root,
            key: "config",
        };
        assert_eq!(key1.to_string(), "config");

        let key2 = Path::Map {
            parent: &key1,
            key: "server",
        };
        assert_eq!(key2.to_string(), "config.server");

        let key3 = Path::Map {
            parent: &key2,
            key: "host",
        };
        assert_eq!(key3.to_string(), "config.server.host");
    }

    #[test]
    fn test_path_seq_display() {
        let root = Path::Root;
        let items = Path::Map {
            parent: &root,
            key: "items",
        };
        let first = Path::Seq {
            parent: &items,
            index: 0,
        };
        assert_eq!(first.to_string(), "items[0]");

        let second = Path::Seq {
            parent: &items,
            index: 1,
        };
        assert_eq!(second.to_string(), "items[1]");
    }

    #[test]
    fn test_path_mixed_display() {
        let root = Path::Root;
        let servers = Path::Map {
            parent: &root,
            key: "servers",
        };
        let first = Path::Seq {
            parent: &servers,
            index: 0,
        };
        let host = Path::Map {
            parent: &first,
            key: "host",
        };
        assert_eq!(host.to_string(), "servers[0].host");
    }

    #[test]
    fn test_path_unknown_display() {
        let root = Path::Root;
        let unknown = Path::Unknown { parent: &root };
        assert_eq!(unknown.to_string(), "?"); // Root doesn't add a dot

        let key = Path::Map {
            parent: &root,
            key: "test",
        };
        let unknown2 = Path::Unknown { parent: &key };
        assert_eq!(unknown2.to_string(), "test.?");
    }

    #[test]
    fn test_path_builder_methods() {
        let root = Path::Root;
        let config = root.key("config");
        let items = config.key("items");
        let first = items.index(0);
        let name = first.key("name");

        assert_eq!(name.to_string(), "config.items[0].name");
    }

    #[test]
    fn test_path_is_root() {
        let root = Path::Root;
        assert!(root.is_root());

        let child = root.key("test");
        assert!(!child.is_root());
    }

    #[test]
    fn test_path_parent() {
        let root = Path::Root;
        assert!(root.parent().is_none());

        let child = Path::Map {
            parent: &root,
            key: "test",
        };
        assert_eq!(child.parent(), Some(&root));
    }

    #[test]
    fn test_path_depth() {
        let root = Path::Root;
        assert_eq!(root.depth(), 0);

        let d1 = Path::Map {
            parent: &root,
            key: "a",
        };
        assert_eq!(d1.depth(), 1);

        let d2 = Path::Map {
            parent: &d1,
            key: "b",
        };
        assert_eq!(d2.depth(), 2);

        let d3 = Path::Seq {
            parent: &d2,
            index: 0,
        };
        assert_eq!(d3.depth(), 3);
    }

    #[test]
    fn test_path_default() {
        let path: Path = Path::default();
        assert!(path.is_root());
    }

    #[test]
    fn test_path_equality() {
        let root1 = Path::Root;
        let root2 = Path::Root;
        assert_eq!(root1, root2);

        let key1 = Path::Map {
            parent: &root1,
            key: "test",
        };
        let key2 = Path::Map {
            parent: &root2,
            key: "test",
        };
        assert_eq!(key1, key2);

        let key3 = Path::Map {
            parent: &root1,
            key: "other",
        };
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_path_alias() {
        let root = Path::Root;
        let alias = root.alias();
        assert!(matches!(alias, Path::Alias { .. }));
    }

    #[test]
    fn test_path_complex_real_world() {
        // Simulate a real-world path like: dependencies.serde.features[0]
        let root = Path::Root;
        let deps = root.key("dependencies");
        let serde = deps.key("serde");
        let features = serde.key("features");
        let first_feature = features.index(0);

        assert_eq!(first_feature.to_string(), "dependencies.serde.features[0]");
    }

    #[test]
    fn test_path_deeply_nested() {
        let root = Path::Root;
        let a = root.key("a");
        let b = a.key("b");
        let c = b.key("c");
        let d = c.key("d");
        let e = d.key("e");

        assert_eq!(e.to_string(), "a.b.c.d.e");
        assert_eq!(e.depth(), 5);
    }

    #[test]
    fn parse_query_path_handles_inline_star_after_key() {
        // `field*` — the `*` glyph mid-path with a non-empty
        // accumulated key. The parser must flush the key first,
        // then push a Wildcard segment.
        let segments = parse_query_path("field*");
        assert_eq!(segments.len(), 2);
        assert!(matches!(&segments[0], QuerySegment::Key(s) if s == "field"));
        assert!(matches!(&segments[1], QuerySegment::Wildcard));
    }

    #[test]
    fn parse_query_path_rejects_unparseable_bracket_content() {
        let segments = parse_query_path("items[abc]");
        assert_eq!(segments.len(), 1);
        assert!(matches!(&segments[0], QuerySegment::Key(s) if s.contains("invalid-query-path")));
        assert!(parse_query_path_checked("items[abc]").is_err());
    }

    #[test]
    fn parse_query_path_handles_standalone_star_segment() {
        // `*` on its own — recursive descent's "match anything at
        // this level" form.
        let segments = parse_query_path("*");
        assert_eq!(segments.len(), 1);
        assert!(matches!(&segments[0], QuerySegment::Wildcard));
    }

    #[test]
    fn parse_query_path_handles_recursive_descent() {
        // `..name` — descend recursively, then look up `name`.
        let segments = parse_query_path("..name");
        assert_eq!(segments.len(), 2);
        assert!(matches!(&segments[0], QuerySegment::RecursiveDescent));
        assert!(matches!(&segments[1], QuerySegment::Key(s) if s == "name"));
    }

    fn keys(segments: &[QuerySegment]) -> Vec<&str> {
        segments
            .iter()
            .map(|s| match s {
                QuerySegment::Key(k) => k.as_str(),
                QuerySegment::Index(_) => "<index>",
                QuerySegment::Wildcard => "<wildcard>",
                QuerySegment::RecursiveDescent => "<descent>",
            })
            .collect()
    }

    #[test]
    fn parse_query_path_reads_a_quoted_bracket_segment_as_one_key() {
        let segments = parse_query_path(r#"labels["app.kubernetes.io/name"]"#);
        assert_eq!(keys(&segments), ["labels", "app.kubernetes.io/name"]);
    }

    #[test]
    fn parse_query_path_quoted_key_may_hold_any_grammar_character() {
        for (path, key) in [
            (r#"["*"]"#, "*"),
            (r#"["a[0]"]"#, "a[0]"),
            ("['a]b']", "a]b"),
            (r#"[""]"#, ""),
            (r#"["say \"hi\""]"#, "say \"hi\""),
            (r#"["back\\slash"]"#, "back\\slash"),
            (r"['it\'s']", "it's"),
            (r#"['double "quotes"']"#, "double \"quotes\""),
            (r#"["..x"]"#, "..x"),
        ] {
            let segments = parse_query_path(path);
            assert_eq!(keys(&segments), [key], "{path}");
        }
    }

    #[test]
    fn parse_query_path_mixes_quoted_keys_with_the_other_segments() {
        let segments = parse_query_path(r#"items[0]["a.b"].c[*]['d']"#);
        assert_eq!(
            keys(&segments),
            ["items", "<index>", "a.b", "c", "<wildcard>", "d"]
        );
        assert!(matches!(segments[1], QuerySegment::Index(0)));
    }

    #[test]
    fn parse_query_path_rejects_unterminated_quoted_key() {
        assert!(parse_query_path_checked(r#"a["bc"#).is_err());
        assert!(parse_query_path_checked("a['bc").is_err());
    }

    #[test]
    fn parse_query_path_rejects_other_partial_grammars() {
        for path in ["a.", ".a", "a[0", "a]", "a.[0]", r#"a["b"x]"#] {
            assert!(parse_query_path_checked(path).is_err(), "{path}");
        }
    }

    #[test]
    fn quote_key_round_trips_every_key_through_the_parser() {
        for key in [
            "plain",
            "a.b",
            "*",
            "a[0]",
            "]",
            "[",
            "",
            "say \"hi\"",
            "back\\slash",
            "'",
            "\\\"",
            "app.kubernetes.io/name",
            "..",
            "[*]",
            "trailing\\",
        ] {
            let segments = parse_query_path(&quote_key(key));
            assert_eq!(keys(&segments), [key], "{key:?} -> {:?}", quote_key(key));
        }
    }

    #[test]
    fn join_keys_quotes_only_the_keys_the_grammar_would_misread() {
        assert_eq!(join_keys(["server", "port"]), "server.port");
        assert_eq!(join_keys(["only"]), "only");
        assert_eq!(join_keys(Vec::<&str>::new()), "");
        let path = join_keys(["labels", "app.io/name", "tier", "", "x*", "y"]);
        assert_eq!(path, r#"labels["app.io/name"].tier[""]["x*"].y"#);
        assert_eq!(
            keys(&parse_query_path(&path)),
            ["labels", "app.io/name", "tier", "", "x*", "y"]
        );
    }

    #[test]
    fn push_key_after_an_index_or_a_quoted_segment_needs_no_separator() {
        let mut path = String::from("items[0]");
        push_key(&mut path, "name");
        assert_eq!(path, "items[0].name");
        let mut path = quote_key("a.b");
        push_key(&mut path, "c");
        push_key(&mut path, "d]");
        assert_eq!(path, r#"["a.b"].c["d]"]"#);
        assert_eq!(keys(&parse_query_path(&path)), ["a.b", "c", "d]"]);
    }

    #[test]
    fn query_path_reports_stable_error_categories() {
        for (input, kind) in [
            (".a", PathErrorKind::EmptySegment),
            ("a.[0]", PathErrorKind::SeparatorBeforeBracket),
            ("a[0", PathErrorKind::UnterminatedBracket),
            (r#"a["b"#, PathErrorKind::UnterminatedQuotedKey),
            (r#"a["b"x]"#, PathErrorKind::ExpectedClosingBracket),
            ("a[no]", PathErrorKind::InvalidBracketSegment),
            ("a]", PathErrorKind::StrayClosingBracket),
            ("a.", PathErrorKind::DanglingSeparator),
        ] {
            assert_eq!(QueryPath::parse(input).unwrap_err().kind(), kind, "{input}");
        }

        let overflow = format!("items[{}]", "9".repeat(usize::BITS as usize));
        assert_eq!(
            QueryPath::parse(&overflow).unwrap_err().kind(),
            PathErrorKind::IndexOverflow
        );
    }

    #[test]
    fn query_path_display_is_canonical_and_round_trips() {
        for input in [
            "",
            "server.port",
            "items[12].name",
            r#"labels["app.example/name"]"#,
            "items[*].name",
            "..name",
            "root..name",
        ] {
            let path = QueryPath::parse(input).unwrap();
            let rendered = path.to_string();
            assert_eq!(
                QueryPath::parse(&rendered).unwrap(),
                path,
                "{input} -> {rendered}"
            );
        }
    }
}