asdf-yaml 0.2.1

ASDF-flavoured YAML document model, parser and emitter
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
//! The YAML Pointer path syntax used to address values in the tree.
//!
//! This is libfyaml's native lookup syntax, which libasdf inherits and which
//! is only informally specified. The rules, as libasdf's own documentation
//! sets them out:
//!
//! - Components are separated by `/`.
//! - A non-numeric component is always a mapping key.
//! - A numeric component depends on context: a mapping key when the parent is
//!   a mapping, a sequence index when the parent is a sequence. Sequence
//!   indices may be negative, counting back from the end.
//! - `[N]` is *always* a sequence index, and fails against a mapping.
//! - `'a'` or `"a"` is *always* a mapping key, so `'0'` is the string key
//!   `0` rather than an index.
//! - Escaping uses backslashes rather than JSON Pointer's `~`. The characters
//!   needing escape are ``/{}[].&*\``; inside quotes none of them do.

use crate::document::Document;
use crate::node::{Node, NodeData, NodeId};

/// One step of a path.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Component {
    /// A mapping key, stated unambiguously by quoting.
    Key(String),
    /// A sequence index, stated unambiguously by brackets. Negative values
    /// count back from the end.
    Index(i64),
    /// A bare component, resolved against whatever the parent turns out to be.
    Bare(String),
}

/// The characters that must be escaped outside quotes.
pub const ESCAPE_CHARS: &[char] = &['/', '{', '}', '[', ']', '.', '&', '*', '\\'];

/// An error in a path's syntax.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
pub enum PathError {
    /// A quoted component was never closed.
    #[error("unterminated quote in path component {0:?}")]
    UnterminatedQuote(String),
    /// A bracketed component was never closed.
    #[error("unterminated bracket in path component {0:?}")]
    UnterminatedBracket(String),
    /// The contents of `[...]` were not an integer.
    #[error("bracketed path component {0:?} is not an integer")]
    NonIntegerIndex(String),
    /// A trailing backslash with nothing to escape.
    #[error("path ends with a dangling escape")]
    DanglingEscape,
}

/// A parsed path.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Path {
    components: Vec<Component>,
}

impl Path {
    /// Parse a path string.
    ///
    /// A leading `/` is optional and ignored, so `a/b` and `/a/b` are the
    /// same path. An empty path addresses the root.
    pub fn parse(path: &str) -> Result<Self, PathError> {
        let mut components = Vec::new();
        let mut rest = path.strip_prefix('/').unwrap_or(path);

        if rest.is_empty() {
            return Ok(Path { components });
        }

        while !rest.is_empty() {
            let (component, remainder) = parse_component(rest)?;
            components.push(component);
            rest = match remainder.strip_prefix('/') {
                Some(r) => r,
                None => {
                    debug_assert!(remainder.is_empty());
                    ""
                }
            };
            // A trailing slash addresses the same node, matching how a
            // directory-style path reads.
            if rest.is_empty() {
                break;
            }
        }
        Ok(Path { components })
    }

    /// The components, in order.
    pub fn components(&self) -> &[Component] {
        &self.components
    }

    /// Whether this path addresses the root.
    pub fn is_root(&self) -> bool {
        self.components.is_empty()
    }
}

/// Split one component off the front of `s`, returning it and the remainder.
fn parse_component(s: &str) -> Result<(Component, &str), PathError> {
    let mut chars = s.char_indices().peekable();

    match chars.peek() {
        // Bracketed: always a sequence index.
        Some((_, '[')) => {
            let close = s.find(']').ok_or_else(|| PathError::UnterminatedBracket(s.to_string()))?;
            let body = &s[1..close];
            let index = body
                .trim()
                .parse::<i64>()
                .map_err(|_| PathError::NonIntegerIndex(body.to_string()))?;
            Ok((Component::Index(index), &s[close + 1..]))
        }

        // Quoted: always a mapping key, with no escaping inside.
        Some((_, quote @ ('\'' | '"'))) => {
            let quote = *quote;
            let close =
                s[1..].find(quote).ok_or_else(|| PathError::UnterminatedQuote(s.to_string()))? + 1;
            let key = s[1..close].to_string();
            Ok((Component::Key(key), &s[close + 1..]))
        }

        // Bare: runs to the next unescaped separator.
        _ => {
            let mut out = String::new();
            let mut escaped = false;
            let mut end = s.len();

            for (idx, ch) in s.char_indices() {
                if escaped {
                    out.push(ch);
                    escaped = false;
                    continue;
                }
                match ch {
                    '\\' => escaped = true,
                    '/' => {
                        end = idx;
                        break;
                    }
                    _ => out.push(ch),
                }
            }
            if escaped {
                return Err(PathError::DanglingEscape);
            }
            Ok((Component::Bare(out), &s[end..]))
        }
    }
}

/// Escape a string so it survives a round trip through [`Path::parse`] as a
/// single bare component.
pub fn escape_component(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        if ESCAPE_CHARS.contains(&ch) {
            out.push('\\');
        }
        out.push(ch);
    }
    out
}

impl Document {
    /// Resolve a path against a starting node.
    ///
    /// Aliases are followed at each step, so a path may descend through a
    /// shared node.
    pub fn lookup_from(&self, start: NodeId, path: &Path) -> Option<NodeId> {
        let mut current = start;

        for component in path.components() {
            let resolved = self.resolve(current);
            current = match component {
                Component::Key(key) => self.mapping_get(resolved, key)?,
                Component::Index(index) => self.sequence_get(resolved, *index)?,
                Component::Bare(text) => match &self.node(resolved).data {
                    // A bare component is a key when the parent is a mapping,
                    // whether or not it looks numeric.
                    NodeData::Mapping { .. } => self.mapping_get(resolved, text)?,
                    NodeData::Sequence { .. } => {
                        let index = text.parse::<i64>().ok()?;
                        self.sequence_get(resolved, index)?
                    }
                    _ => return None,
                },
            };
        }
        Some(current)
    }

    /// Resolve a path against the document root.
    pub fn lookup(&self, path: &Path) -> Option<NodeId> {
        self.lookup_from(self.root()?, path)
    }

    /// Parse and resolve a path in one step.
    pub fn lookup_str(&self, path: &str) -> Option<NodeId> {
        self.lookup(&Path::parse(path).ok()?)
    }

    /// The container that holds `id`, searching down from the root.
    ///
    /// A node reachable by more than one route reports the first parent found
    /// in document order. Aliases are *not* followed: an alias node is its
    /// own child of whatever holds it, and the node it points at is reported
    /// under its defining position.
    pub fn parent_of(&self, id: NodeId) -> Option<NodeId> {
        let root = self.root()?;
        if root == id {
            return None;
        }
        let mut stack = vec![root];
        let mut seen = vec![false; self.node_count()];
        while let Some(current) = stack.pop() {
            let index = current.0 as usize;
            if index >= seen.len() || seen[index] {
                continue;
            }
            seen[index] = true;
            match &self.node(current).data {
                NodeData::Mapping { entries, .. } => {
                    for entry in entries {
                        if entry.key == id || entry.value == id {
                            return Some(current);
                        }
                    }
                    for entry in entries {
                        stack.push(entry.value);
                    }
                }
                NodeData::Sequence { items, .. } => {
                    if items.contains(&id) {
                        return Some(current);
                    }
                    stack.extend(items.iter().copied());
                }
                _ => {}
            }
        }
        None
    }

    /// The path from the root to `id`, in the syntax [`Path::parse`] accepts.
    ///
    /// Absolute, so `/history/extensions/0` rather than
    /// `history/extensions/0`, and a sequence index is written plainly
    /// rather than bracketed -- that is the form libasdf reports and the one
    /// its own tests expect. A bare numeric component is unambiguous on the
    /// way back in, since it is read as an index only when the container it
    /// addresses is a sequence.
    ///
    /// The root itself is `/`. Returns `None` when `id` is not reachable from
    /// the root, which is the case for a node built but not yet attached.
    pub fn path_of(&self, id: NodeId) -> Option<String> {
        let root = self.root()?;
        let mut components = Vec::new();
        if !self.walk_to(root, id, &mut components, &mut vec![false; self.node_count()]) {
            return None;
        }
        Some(format!("/{}", components.join("/")))
    }

    /// Depth-first search for `target`, recording the route taken.
    fn walk_to(
        &self,
        current: NodeId,
        target: NodeId,
        route: &mut Vec<String>,
        seen: &mut Vec<bool>,
    ) -> bool {
        if current == target {
            return true;
        }
        let index = current.0 as usize;
        if index >= seen.len() || seen[index] {
            return false;
        }
        seen[index] = true;
        match &self.node(current).data {
            NodeData::Mapping { entries, .. } => {
                for entry in entries {
                    let Some(key) = self.resolved(entry.key).as_str() else {
                        continue;
                    };
                    route.push(escape_component(key));
                    if self.walk_to(entry.value, target, route, seen) {
                        return true;
                    }
                    route.pop();
                }
            }
            NodeData::Sequence { items, .. } => {
                for (position, item) in items.iter().enumerate() {
                    route.push(position.to_string());
                    if self.walk_to(*item, target, route, seen) {
                        return true;
                    }
                    route.pop();
                }
            }
            _ => {}
        }
        false
    }
}

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

    fn doc() -> Document {
        parse_document(
            "a:\n  b: 1\n  '0': zero-as-key\nseq: [x, y, z]\nnested:\n  - k: v\n  - k: w\n",
        )
        .unwrap()
    }

    #[test]
    fn nodes_report_their_path_from_the_root() {
        let d = doc();
        let root = d.root().unwrap();
        assert_eq!(d.path_of(root).as_deref(), Some("/"));

        let inner = d.lookup_str("a/b").unwrap();
        assert_eq!(d.path_of(inner).as_deref(), Some("/a/b"));

        // A sequence element's index is written plainly; it reads back as an
        // index because the container it addresses is a sequence.
        let item = d.lookup_str("seq/1").unwrap();
        assert_eq!(d.path_of(item).as_deref(), Some("/seq/1"));
        assert_eq!(d.lookup_str(&d.path_of(item).unwrap()), Some(item));

        let nested = d.lookup_str("nested/1/k").unwrap();
        assert_eq!(d.path_of(nested).as_deref(), Some("/nested/1/k"));
        assert_eq!(d.lookup_str("/nested/1/k"), Some(nested));
    }

    #[test]
    fn a_detached_node_has_no_path() {
        let mut d = doc();
        let orphan = d.add_scalar("nowhere");
        assert_eq!(d.path_of(orphan), None);
        assert_eq!(d.parent_of(orphan), None);
    }

    #[test]
    fn nodes_report_their_parent() {
        let d = doc();
        let root = d.root().unwrap();
        assert_eq!(d.parent_of(root), None, "the root has no parent");

        let inner = d.lookup_str("a/b").unwrap();
        let a = d.lookup_str("a").unwrap();
        assert_eq!(d.parent_of(inner), Some(a));
        assert_eq!(d.parent_of(a), Some(root));

        let item = d.lookup_str("seq/2").unwrap();
        assert_eq!(d.parent_of(item), Some(d.lookup_str("seq").unwrap()));
    }

    fn get<'a>(d: &'a Document, path: &str) -> Option<&'a str> {
        d.lookup_str(path).map(|id| d.resolved(id).as_str().unwrap_or("<container>"))
    }

    #[test]
    fn parses_simple_paths() {
        let p = Path::parse("a/b").unwrap();
        assert_eq!(p.components(), [Component::Bare("a".into()), Component::Bare("b".into())]);
        // A leading slash is optional.
        assert_eq!(Path::parse("/a/b").unwrap(), p);
    }

    #[test]
    fn empty_path_is_the_root() {
        assert!(Path::parse("").unwrap().is_root());
        assert!(Path::parse("/").unwrap().is_root());
    }

    #[test]
    fn looks_up_nested_mappings() {
        let d = doc();
        assert_eq!(get(&d, "a/b"), Some("1"));
        assert_eq!(get(&d, "/a/b"), Some("1"));
        assert!(get(&d, "a/missing").is_none());
    }

    #[test]
    fn numeric_component_indexes_a_sequence() {
        let d = doc();
        assert_eq!(get(&d, "seq/0"), Some("x"));
        assert_eq!(get(&d, "seq/2"), Some("z"));
        assert!(get(&d, "seq/3").is_none());
    }

    #[test]
    fn negative_indices_count_from_the_end() {
        let d = doc();
        assert_eq!(get(&d, "seq/-1"), Some("z"));
        assert_eq!(get(&d, "seq/-3"), Some("x"));
        assert!(get(&d, "seq/-4").is_none());
    }

    #[test]
    fn numeric_component_is_a_key_under_a_mapping() {
        // The context rule: '0' addresses the *key* "0", not an index.
        let d = doc();
        assert_eq!(get(&d, "a/0"), Some("zero-as-key"));
    }

    #[test]
    fn brackets_force_a_sequence_index() {
        let d = doc();
        assert_eq!(get(&d, "seq/[1]"), Some("y"));
        assert_eq!(get(&d, "seq/[-1]"), Some("z"));
        // Against a mapping it must fail, even though the key "0" exists.
        assert!(get(&d, "a/[0]").is_none());
    }

    #[test]
    fn quotes_force_a_mapping_key() {
        let d = doc();
        assert_eq!(get(&d, "a/'0'"), Some("zero-as-key"));
        assert_eq!(get(&d, "a/\"0\""), Some("zero-as-key"));
        // Against a sequence a quoted component must fail: it is a string key.
        assert!(get(&d, "seq/'0'").is_none());
    }

    #[test]
    fn descends_through_sequences_of_mappings() {
        let d = doc();
        assert_eq!(get(&d, "nested/0/k"), Some("v"));
        assert_eq!(get(&d, "nested/1/k"), Some("w"));
        assert_eq!(get(&d, "nested/-1/k"), Some("w"));
    }

    #[test]
    fn backslash_escapes_a_separator() {
        let d = parse_document("a/b: slashed\n").unwrap();
        assert_eq!(get(&d, "a\\/b"), Some("slashed"));
        // Without the escape it is two components and finds nothing.
        assert!(get(&d, "a/b").is_none());
    }

    #[test]
    fn quotes_avoid_the_need_to_escape() {
        let d = parse_document("a.b: dotted\n").unwrap();
        assert_eq!(get(&d, "'a.b'"), Some("dotted"));
        assert_eq!(get(&d, "a\\.b"), Some("dotted"));
    }

    #[test]
    fn escape_round_trips() {
        for raw in ["a/b", "a.b", "a[0]", "a&b", "plain"] {
            let escaped = escape_component(raw);
            let parsed = Path::parse(&escaped).unwrap();
            assert_eq!(
                parsed.components(),
                [Component::Bare(raw.to_string())],
                "{raw:?} escaped to {escaped:?}"
            );
        }
    }

    #[test]
    fn paths_follow_aliases() {
        let d = parse_document("target: &a {x: 1}\nalias: *a\n").unwrap();
        assert_eq!(get(&d, "alias/x"), Some("1"));
        assert_eq!(get(&d, "target/x"), Some("1"));
    }

    #[test]
    fn descending_into_a_scalar_fails() {
        let d = doc();
        assert!(get(&d, "a/b/c").is_none());
    }

    #[test]
    fn syntax_errors_are_reported() {
        assert_eq!(
            Path::parse("'unterminated"),
            Err(PathError::UnterminatedQuote("'unterminated".into()))
        );
        assert_eq!(Path::parse("[1"), Err(PathError::UnterminatedBracket("[1".into())));
        assert_eq!(Path::parse("[abc]"), Err(PathError::NonIntegerIndex("abc".into())));
        assert_eq!(Path::parse("a\\"), Err(PathError::DanglingEscape));
    }

    #[test]
    fn trailing_slash_is_ignored() {
        let d = doc();
        assert_eq!(get(&d, "a/b/"), Some("1"));
    }
}

impl Document {
    /// Insert `value` at `path`, creating intermediate mappings as needed.
    ///
    /// This mirrors libasdf's `asdf_node_insert_at` with materialisation on:
    /// setting `powers/squares` in an empty tree creates the `powers` mapping
    /// on the way. Returns the node that was replaced, if any.
    ///
    /// Intermediate steps are only ever created as mappings, since a bare
    /// path component gives no way to say "make a sequence here". A component
    /// that names an existing sequence still indexes into it.
    pub fn insert_at(&mut self, path: &Path, value: NodeId) -> Result<Option<NodeId>, PathError> {
        let Some((last, leading)) = path.components().split_last() else {
            // An empty path replaces the root outright.
            let previous = self.root();
            self.set_root(value);
            return Ok(previous);
        };

        // Walk to the parent, materialising mappings that are not there yet.
        let mut current = match self.root() {
            Some(root) => root,
            None => {
                let root = self.add(Node::mapping());
                self.set_root(root);
                root
            }
        };

        for component in leading {
            let resolved = self.resolve(current);
            let existing = match component {
                Component::Key(key) => self.mapping_get(resolved, key),
                Component::Index(index) => self.sequence_get(resolved, *index),
                Component::Bare(text) => match &self.node(resolved).data {
                    NodeData::Sequence { .. } => {
                        text.parse::<i64>().ok().and_then(|i| self.sequence_get(resolved, i))
                    }
                    _ => self.mapping_get(resolved, text),
                },
            };

            current = match existing {
                // Descend through anything that can hold children.
                Some(node) if self.node(self.resolve(node)).is_mapping() => node,
                Some(node) if self.node(self.resolve(node)).is_sequence() => node,
                // A scalar in the way is replaced by a mapping, since the
                // caller has asked for a path through it.
                _ => {
                    let fresh = self.add(Node::mapping());
                    self.set_component(resolved, component, fresh)?;
                    fresh
                }
            };
        }

        let parent = self.resolve(current);
        self.set_component(parent, last, value)
    }

    /// Parse and insert in one step.
    pub fn insert_at_str(
        &mut self,
        path: &str,
        value: NodeId,
    ) -> Result<Option<NodeId>, PathError> {
        let parsed = Path::parse(path)?;
        self.insert_at(&parsed, value)
    }

    /// Set one component of a container, replacing whatever was there.
    fn set_component(
        &mut self,
        parent: NodeId,
        component: &Component,
        value: NodeId,
    ) -> Result<Option<NodeId>, PathError> {
        let is_sequence = self.node(parent).is_sequence();

        match component {
            Component::Key(key) => Ok(self.mapping_set(parent, key, value)),
            Component::Index(index) => Ok(self.sequence_set(parent, *index, value)),
            Component::Bare(text) => {
                if is_sequence && let Ok(index) = text.parse::<i64>() {
                    return Ok(self.sequence_set(parent, index, value));
                }
                Ok(self.mapping_set(parent, text, value))
            }
        }
    }

    /// Replace a sequence element, or append when the index is one past the
    /// end. Returns the element that was replaced.
    pub fn sequence_set(&mut self, id: NodeId, index: i64, value: NodeId) -> Option<NodeId> {
        let target = self.resolve(id);
        let len = self.container_len(target)? as i64;
        let idx = if index < 0 { len + index } else { index };

        let NodeData::Sequence { items, .. } = &mut self.node_mut(target).data else {
            return None;
        };
        if idx == len {
            items.push(value);
            return None;
        }
        if idx < 0 || idx > len {
            return None;
        }
        Some(core::mem::replace(&mut items[idx as usize], value))
    }

    /// Remove whatever is at `path`, returning it.
    pub fn remove_at_str(&mut self, path: &str) -> Option<NodeId> {
        let parsed = Path::parse(path).ok()?;
        let (last, leading) = parsed.components().split_last()?;

        let mut current = self.root()?;
        for component in leading {
            let resolved = self.resolve(current);
            current = match component {
                Component::Key(key) => self.mapping_get(resolved, key)?,
                Component::Index(index) => self.sequence_get(resolved, *index)?,
                Component::Bare(text) => match &self.node(resolved).data {
                    NodeData::Sequence { .. } => {
                        self.sequence_get(resolved, text.parse::<i64>().ok()?)?
                    }
                    _ => self.mapping_get(resolved, text)?,
                },
            };
        }

        let parent = self.resolve(current);
        match last {
            Component::Key(key) => self.mapping_remove(parent, key),
            Component::Index(index) => self.sequence_remove(parent, *index),
            Component::Bare(text) => {
                if self.node(parent).is_sequence()
                    && let Ok(index) = text.parse::<i64>()
                {
                    return self.sequence_remove(parent, index);
                }
                self.mapping_remove(parent, text)
            }
        }
    }

    /// Remove a sequence element, returning it.
    pub fn sequence_remove(&mut self, id: NodeId, index: i64) -> Option<NodeId> {
        let target = self.resolve(id);
        let len = self.container_len(target)? as i64;
        let idx = if index < 0 { len + index } else { index };
        if idx < 0 || idx >= len {
            return None;
        }
        let NodeData::Sequence { items, .. } = &mut self.node_mut(target).data else {
            return None;
        };
        Some(items.remove(idx as usize))
    }
}

#[cfg(test)]
mod insert_tests {
    use super::*;
    use crate::node::ScalarStyle;
    use crate::parse::parse_document;

    fn get<'a>(d: &'a Document, path: &str) -> Option<&'a str> {
        d.lookup_str(path).map(|id| d.resolved(id).as_str().unwrap_or("<container>"))
    }

    #[test]
    fn sets_a_top_level_key() {
        let mut doc = parse_document("a: 1\n").unwrap();
        let v = doc.add_scalar("2");
        let previous = doc.insert_at_str("b", v).unwrap();
        assert!(previous.is_none());
        assert_eq!(get(&doc, "b"), Some("2"));
        assert_eq!(get(&doc, "a"), Some("1"));
    }

    #[test]
    fn replaces_an_existing_value() {
        let mut doc = parse_document("a: 1\n").unwrap();
        let v = doc.add_scalar("9");
        let previous = doc.insert_at_str("a", v).unwrap();
        assert!(previous.is_some());
        assert_eq!(get(&doc, "a"), Some("9"));
        assert_eq!(doc.container_len(doc.root().unwrap()), Some(1));
    }

    #[test]
    fn materialises_intermediate_mappings() {
        // The README's case: setting `powers/squares` in a tree that has
        // neither must create `powers` on the way.
        let mut doc = parse_document("a: 1\n").unwrap();
        let v = doc.add_scalar("squared");
        doc.insert_at_str("powers/squares", v).unwrap();

        assert_eq!(get(&doc, "powers/squares"), Some("squared"));
        assert!(doc.node(doc.lookup_str("powers").unwrap()).is_mapping());
    }

    #[test]
    fn materialises_several_levels() {
        let mut doc = Document::new();
        let v = doc.add_scalar("deep");
        doc.insert_at_str("a/b/c/d", v).unwrap();
        assert_eq!(get(&doc, "a/b/c/d"), Some("deep"));
    }

    #[test]
    fn creates_a_root_when_there_is_none() {
        let mut doc = Document::new();
        let v = doc.add_scalar("hello");
        doc.insert_at_str("greeting", v).unwrap();
        assert!(doc.root().is_some());
        assert_eq!(get(&doc, "greeting"), Some("hello"));
    }

    #[test]
    fn an_empty_path_replaces_the_root() {
        let mut doc = parse_document("a: 1\n").unwrap();
        let v = doc.add_scalar("replaced");
        doc.insert_at_str("", v).unwrap();
        assert_eq!(doc.root(), Some(v));
    }

    #[test]
    fn a_scalar_in_the_way_becomes_a_mapping() {
        let mut doc = parse_document("a: scalar\n").unwrap();
        let v = doc.add_scalar("1");
        doc.insert_at_str("a/b", v).unwrap();
        assert_eq!(get(&doc, "a/b"), Some("1"));
        assert!(doc.node(doc.lookup_str("a").unwrap()).is_mapping());
    }

    #[test]
    fn writes_through_a_sequence_index() {
        let mut doc = parse_document("s: [x, y, z]\n").unwrap();
        let v = doc.add_scalar("Y");
        doc.insert_at_str("s/1", v).unwrap();
        assert_eq!(get(&doc, "s/1"), Some("Y"));
        assert_eq!(doc.container_len(doc.lookup_str("s").unwrap()), Some(3));
    }

    #[test]
    fn appending_one_past_the_end_extends_a_sequence() {
        let mut doc = parse_document("s: [x]\n").unwrap();
        let v = doc.add_scalar("y");
        doc.insert_at_str("s/1", v).unwrap();
        assert_eq!(doc.container_len(doc.lookup_str("s").unwrap()), Some(2));
        assert_eq!(get(&doc, "s/1"), Some("y"));
    }

    #[test]
    fn a_quoted_component_makes_a_string_key_even_over_a_sequence() {
        let mut doc = parse_document("a: {}\n").unwrap();
        let v = doc.add_scalar("1");
        doc.insert_at_str("a/'0'", v).unwrap();
        assert_eq!(get(&doc, "a/'0'"), Some("1"));
    }

    #[test]
    fn removes_values() {
        let mut doc = parse_document("a: 1\nb:\n  c: 2\ns: [x, y]\n").unwrap();

        assert!(doc.remove_at_str("a").is_some());
        assert!(doc.lookup_str("a").is_none());

        assert!(doc.remove_at_str("b/c").is_some());
        assert!(doc.lookup_str("b/c").is_none());
        // The parent survives.
        assert!(doc.lookup_str("b").is_some());

        assert!(doc.remove_at_str("s/0").is_some());
        assert_eq!(doc.container_len(doc.lookup_str("s").unwrap()), Some(1));
        assert_eq!(get(&doc, "s/0"), Some("y"));

        assert!(doc.remove_at_str("missing").is_none());
    }

    #[test]
    fn inserted_trees_emit_and_re_read() {
        use crate::emit::emit;
        use crate::parse::parse_document as reparse;

        let mut doc = Document::new_asdf();
        let name = doc.add_scalar_styled("Dennis Richie", ScalarStyle::Plain);
        doc.insert_at_str("name", name).unwrap();
        let foo = doc.add_scalar("42");
        doc.insert_at_str("foo", foo).unwrap();
        let sq = doc.add_scalar("1764");
        doc.insert_at_str("powers/squares", sq).unwrap();

        let text = emit(&doc).unwrap();
        let back = reparse(&text).unwrap();
        assert_eq!(
            back.lookup_str("powers/squares").map(|id| back
                .resolved(id)
                .as_str()
                .unwrap()
                .to_string()),
            Some("1764".to_string())
        );
    }
}