ayaml 1.0.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, 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
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
use super::*;
use crate::limits::Limits;

#[test]
fn complex_keys_detect_duplicates_and_ambiguity_in_linear_time() {
    // Duplicate mapping keys make lookup return None, while unique complex keys resolve.
    let unique = "? {a: 1, b: [2, 3]}\n: ok\nother: yes\n";
    let tree = SpannedTree::parse(unique).expect("parse unique complex key");
    let mut expected_key = Mapping::new();
    expected_key.insert(Value::String("a".into()), Value::from(1_i64));
    expected_key.insert(
        Value::String("b".into()),
        Value::Sequence(vec![Value::from(2_i64), Value::from(3_i64)]),
    );
    let found = tree
        .lookup(&[PathSegment::Key(Value::Mapping(expected_key.clone()))])
        .expect("unique complex key should be found");
    assert_eq!(found.scalar_text(), Some("ok"));
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::String("other".into()))])
            .and_then(SpannedNode::scalar_text),
        Some("yes")
    );

    let dup = "? {a: 1, b: [2, 3]}\n: first\n? {b: [2, 3], a: 1}\n: second\nother: yes\n";
    let dup_tree = SpannedTree::parse(dup).expect("parse duplicate complex keys");
    assert!(
        dup_tree
            .lookup(&[PathSegment::Key(Value::Mapping(expected_key))])
            .is_none(),
        "duplicate complex keys must be marked ambiguous"
    );
    assert_eq!(
        dup_tree
            .lookup(&[PathSegment::Key(Value::String("other".into()))])
            .and_then(SpannedNode::scalar_text),
        Some("yes")
    );

    // An inner duplicate, merge key, or alias inside a complex key marks the enclosing
    // mapping ambiguous so lookups do not guess.
    for ambiguous_input in [
        "? {a: 1, a: 2}\n: v\nother: yes\n",
        "? {<<: {a: 1}}\n: v\nother: yes\n",
        "anchor: &x 1\n? {a: *x}\n: v\nother: yes\n",
        "? [*x]\n: v\nother: yes\n",
    ] {
        let t = SpannedTree::parse(ambiguous_input).expect("parse ambiguous complex key");
        assert!(
            t.lookup(&[PathSegment::Key(Value::String("other".into()))])
                .is_none(),
            "enclosing mapping must not guess for {ambiguous_input:?}"
        );
    }

    // Deeply nested complex keys stay linear.
    let mut nested = "{k0: 0, k1: 1, k2: 2}".to_owned();
    for _ in 0..48 {
        nested = format!("{{? {nested}: null}}");
    }
    nested.push('\n');
    assert!(SpannedTree::parse(&nested).is_ok());
}

#[test]
fn spanned_tree_line_scans_stay_linear_deterministically() {
    use std::fmt::Write as _;

    fn build_and_count(input: &str, merge_keys: bool) -> (SpannedTree<'_>, usize) {
        let options = ParseOptions::new().with_merge_keys(merge_keys);
        let events = crate::parse_events_with(input, &options).expect("events");
        let mut builder = Builder::new(input, merge_keys);
        for event in events {
            builder.event(event.expect("event")).expect("build");
        }
        let scanned = builder.scan_cache.blank_run_lines_scanned;
        (builder.finish(), scanned)
    }

    // Scale iteration counts under Miri while keeping every linearity assertion active.
    let (flow_keys, block_depth, compact_depth, anc_depth, blanks) = if cfg!(miri) {
        (64, 16, 12, 8, 64)
    } else {
        (2_000, 80, 40, 40, 1_000)
    };

    // 1. Dense single-line empty-value flow mapping scans zero blank-run lines.
    let mut flow = String::from("{");
    for i in 0..flow_keys {
        if i > 0 {
            flow.push(',');
        }
        let _ = write!(flow, "k{i}:");
    }
    flow.push_str("}\n");
    let (_, scanned) = build_and_count(&flow, false);
    assert_eq!(scanned, 0, "single-line flow map must scan 0 blank lines");

    // 2. Deep block mapping followed by trailing blank/comment lines scans each line at most once.
    let mut block = String::from("hdr: |\n  keep\n");
    for level in 0..block_depth {
        for _ in 0..level {
            block.push_str("  ");
        }
        let _ = writeln!(block, "k{level}:");
    }
    for _ in 0..block_depth {
        block.push_str("  ");
    }
    block.push_str("leaf:\n");
    for i in 0..blanks {
        if i % 2 == 0 {
            block.push('\n');
        } else {
            block.push_str("# comment\n");
        }
    }
    block.push_str("tail: 1\n");
    let (_, scanned) = build_and_count(&block, false);
    let block_budget = blanks + 200;
    assert!(
        scanned >= blanks && scanned <= block_budget,
        "{block_depth}-deep block + {blanks} trailing blanks scanned {scanned} lines (expected {blanks}..={block_budget})"
    );

    // 3. Deep nested compact mappings + trailing blanks do not evict blank-run cache.
    let mut compact = String::new();
    for level in 0..compact_depth {
        let pad = "    ".repeat(level);
        let _ = writeln!(compact, "{pad}- a{level}: 1\n\n{pad}  b{level}:");
    }
    let leaf_pad = "    ".repeat(compact_depth);
    let _ = writeln!(compact, "{leaf_pad}end: 1");
    for i in 0..blanks {
        if i % 2 == 0 {
            compact.push('\n');
        } else {
            compact.push_str("# trailing\n");
        }
    }
    compact.push_str("- after: 2\n");
    let (_, scanned) = build_and_count(&compact, false);
    let compact_budget = blanks + 300;
    assert!(
        scanned <= compact_budget,
        "{compact_depth}-deep compact + {blanks} trailing blanks scanned {scanned} lines (expected <= {compact_budget})"
    );

    // 4. Ancestor + sibling merge replays over blanks scan the blank run once and
    //    preserve the exact originating missing-value span.
    let mut anc = String::new();
    for level in 0..anc_depth {
        let pad = "  ".repeat(level);
        let _ = writeln!(anc, "{pad}m{level}:");
    }
    let base_pad = "  ".repeat(anc_depth);
    let _ = writeln!(anc, "{base_pad}base: &b");
    let _ = writeln!(anc, "{base_pad}  k0:");
    for _ in 0..blanks {
        anc.push('\n');
    }
    let _ = writeln!(anc, "{base_pad}  k1: 1");
    for level in (0..anc_depth).rev() {
        let pad = "  ".repeat(level + 1);
        let _ = writeln!(anc, "{pad}<<: *b");
        let _ = writeln!(anc, "{pad}x{level}:");
    }
    for i in 0..anc_depth {
        let _ = writeln!(anc, "s{i}: {{ <<: *b }}");
    }
    let (tree, scanned) = build_and_count(&anc, true);
    let anc_budget = blanks + 200;
    assert!(
        scanned <= anc_budget,
        "ancestor + sibling merge replays scanned {scanned} lines (expected <= {anc_budget})"
    );
    let mut base_path: Vec<PathSegment> = (0..anc_depth)
        .map(|l| PathSegment::Key(Value::from(format!("m{l}"))))
        .collect();
    base_path.push(PathSegment::Key(Value::from("base")));
    base_path.push(PathSegment::Key(Value::from("k0")));
    let base_k0 = tree.span_at(&base_path).expect("base k0");
    let outer_k0 = tree
        .span_at(&[
            PathSegment::Key(Value::from("m0")),
            PathSegment::Key(Value::from("k0")),
        ])
        .expect("outer merged k0");
    let sibling_k0 = tree
        .span_at(&[
            PathSegment::Key(Value::from("s0")),
            PathSegment::Key(Value::from("k0")),
        ])
        .expect("sibling merged k0");
    assert_eq!(outer_k0, base_k0);
    assert_eq!(sibling_k0, base_k0);
}

#[test]
fn compact_first_entry_span_refuses_intervening_comments_and_merge_suppresses_entries() {
    let with_comment = "- a: 1\n  # comment about b\n  b: 2\n";
    let tree = SpannedTree::parse(with_comment).expect("tree");
    assert_eq!(
        tree.entry_span_at(&[PathSegment::Index(0), PathSegment::Key(Value::from("a"))]),
        None,
        "compact first entry followed by comment must not produce an entry_span"
    );
    let without_comment = "- a: 1\n  b: 2\n";
    let clean_tree = SpannedTree::parse(without_comment).expect("clean tree");
    assert_eq!(
        clean_tree
            .entry_span_at(&[PathSegment::Index(0), PathSegment::Key(Value::from("a"))])
            .and_then(|s| s.slice(without_comment)),
        Some("a: 1\n  ")
    );

    let merged = "base: &b\n  k: 1\nout:\n  <<: *b\n  own: 2\n";
    let opts = ParseOptions::new().with_merge_keys(true);
    let merged_tree = SpannedTree::parse_with(merged, &opts).expect("merged tree");
    assert!(
        merged_tree
            .span_at(&[
                PathSegment::Key(Value::from("out")),
                PathSegment::Key(Value::from("k")),
            ])
            .is_some()
    );
    assert_eq!(
        merged_tree.entry_span_at(&[
            PathSegment::Key(Value::from("out")),
            PathSegment::Key(Value::from("own")),
        ]),
        None,
        "merge_keys=true must suppress entry_span conservatively"
    );
}

#[test]
fn spanned_node_and_entry_layout_stay_compact() {
    assert!(
        size_of::<SpannedNode<'_>>() <= 64,
        "SpannedNode grew to {} bytes",
        size_of::<SpannedNode<'_>>()
    );
    assert!(
        size_of::<Entry<'_>>() <= 128,
        "Entry grew to {} bytes",
        size_of::<Entry<'_>>()
    );
}

#[test]
fn spanned_key_small_to_large_promotion_and_zero_alloc_lookup() {
    use std::fmt::Write as _;

    // 1. Small mapping (8 keys) stays in linear KeyTracker::Small and distinguishes string vs typed keys.
    let small_yaml = "1: int_one\n\"1\": str_one\n!!str 2: str_two\ntrue: bool_true\n\"true\": str_true\nnull: null_val\n\"null\": str_null\n01: str_01\n";
    let tree = SpannedTree::parse(small_yaml).expect("parse small disjoint keys");
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from(1_i64))])
            .and_then(SpannedNode::scalar_text),
        Some("int_one")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from("1"))])
            .and_then(SpannedNode::scalar_text),
        Some("str_one")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from("2"))])
            .and_then(SpannedNode::scalar_text),
        Some("str_two")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::Bool(true))])
            .and_then(SpannedNode::scalar_text),
        Some("bool_true")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from("true"))])
            .and_then(SpannedNode::scalar_text),
        Some("str_true")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::Null)])
            .and_then(SpannedNode::scalar_text),
        Some("null_val")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from("null"))])
            .and_then(SpannedNode::scalar_text),
        Some("str_null")
    );
    assert_eq!(
        tree.lookup(&[PathSegment::Key(Value::from("01"))])
            .and_then(SpannedNode::scalar_text),
        Some("str_01")
    );

    // 2. Duplicate detection before promotion (<= 8 keys) and across plain/quoted/!!str spellings.
    let dup_small = "a: 1\nb: 2\n\"a\": 3\n!!str b: 4\nc: 5\n";
    let dup_small_tree = SpannedTree::parse(dup_small).expect("parse small duplicate");
    assert!(
        dup_small_tree
            .lookup(&[PathSegment::Key(Value::from("a"))])
            .is_none()
    );
    assert!(
        dup_small_tree
            .lookup(&[PathSegment::Key(Value::from("b"))])
            .is_none()
    );
    assert_eq!(
        dup_small_tree
            .lookup(&[PathSegment::Key(Value::from("c"))])
            .and_then(SpannedNode::scalar_text),
        Some("5")
    );

    // 3. Promotion past SMALL_LIMIT (8) into KeyTracker::Large with duplicates before/after spill.
    let mut large = String::new();
    for i in 0..20 {
        let _ = writeln!(large, "k{i}: v{i}");
    }
    let _ = writeln!(large, "\"k0\": dup0");
    let _ = writeln!(large, "k15: dup15");
    let _ = writeln!(large, "1: int1");
    let _ = writeln!(large, "\"1\": str1");
    let _ = writeln!(large, "1: int1_dup");
    let large_tree = SpannedTree::parse(&large).expect("parse promoted mapping");
    assert!(
        large_tree
            .lookup(&[PathSegment::Key(Value::from("k0"))])
            .is_none()
    );
    assert!(
        large_tree
            .lookup(&[PathSegment::Key(Value::from("k15"))])
            .is_none()
    );
    assert!(
        large_tree
            .lookup(&[PathSegment::Key(Value::from(1_i64))])
            .is_none()
    );
    assert_eq!(
        large_tree
            .lookup(&[PathSegment::Key(Value::from("1"))])
            .and_then(SpannedNode::scalar_text),
        Some("str1")
    );
    assert_eq!(
        large_tree
            .lookup(&[PathSegment::Key(Value::from("k19"))])
            .and_then(SpannedNode::scalar_text),
        Some("v19")
    );
}

#[test]
fn builder_scratch_spill_preserves_spans_and_anchors() {
    use std::fmt::Write as _;

    // 1. Sequence exceeding SCRATCH_LIMIT (64) with nested empty/anchored items.
    let mut seq = String::new();
    for i in 0..72 {
        if i == 10 {
            let _ = writeln!(seq, "- &a item{i}");
        } else if i == 20 {
            seq.push_str("- []\n");
        } else if i == 30 {
            seq.push_str("- {}\n");
        } else {
            let _ = writeln!(seq, "- item{i}");
        }
    }
    let seq_tree = SpannedTree::parse(&seq).expect("parse spilled seq");
    assert_eq!(
        seq_tree
            .lookup(&[PathSegment::Index(0)])
            .and_then(SpannedNode::scalar_text),
        Some("item0")
    );
    assert_eq!(
        seq_tree
            .lookup(&[PathSegment::Index(71)])
            .and_then(SpannedNode::scalar_text),
        Some("item71")
    );
    assert_eq!(
        seq_tree.entry_span_at(&[PathSegment::Index(10)]),
        None,
        "anchored item in spilled sequence must suppress entry_span"
    );
    assert_eq!(
        seq_tree
            .entry_span_at(&[PathSegment::Index(70)])
            .and_then(|s| s.slice(&seq)),
        Some("- item70\n")
    );

    // 2. Compact block mapping exceeding SCRATCH_LIMIT (64) preserves compact first entry_span.
    let mut map = String::from("- k0: v0\n");
    for i in 1..72 {
        let _ = writeln!(map, "  k{i}: v{i}");
    }
    let map_tree = SpannedTree::parse(&map).expect("parse spilled compact map");
    assert_eq!(
        map_tree
            .entry_span_at(&[PathSegment::Index(0), PathSegment::Key(Value::from("k0"))])
            .and_then(|s| s.slice(&map)),
        Some("k0: v0\n  ")
    );
    assert_eq!(
        map_tree
            .entry_span_at(&[PathSegment::Index(0), PathSegment::Key(Value::from("k70"))])
            .and_then(|s| s.slice(&map)),
        Some("  k70: v70\n")
    );
    assert_eq!(
        map_tree
            .lookup(&[PathSegment::Index(0), PathSegment::Key(Value::from("k71"))])
            .and_then(SpannedNode::scalar_text),
        Some("v71")
    );
}

#[test]
fn parse_spanned_matches_event_stream_in_default_and_compat_modes() {
    let cases = [
        "",
        "\u{feff}a: 1\r\nb: |\r\n  hello\r\n",
        "a: 1\n---\nb: [2, {c: 3}]\n",
        "base: &b\n  k: 1\nuse: *b\n",
        "? {x: [1, 2]}\n: complex\nplain: ok\n",
        "- first: 1\n  second: \"escaped\\nval\"\n  third: 'single''quote'\n",
        "bad: [1, 2\n",
    ];
    let opts = ParseOptions::new();
    for input in cases {
        let direct = SpannedTree::parse_with(input, &opts);
        let via_events = crate::parse_events_with(input, &opts).and_then(|events| {
            let mut builder = Builder::new(input, false);
            for event in events {
                builder.event(event?)?;
            }
            Ok(builder.finish())
        });
        match (direct, via_events) {
            (Ok(d), Ok(e)) => {
                assert_eq!(format!("{d:?}"), format!("{e:?}"), "{input:?}");
            }
            (Err(de), Err(ee)) => {
                assert_eq!(de.code(), ee.code(), "{input:?}");
                assert_eq!(de.span(), ee.span(), "{input:?}");
                assert_eq!(de.location(), ee.location(), "{input:?}");
            }
            (d, e) => panic!("mismatch on {input:?}: direct={d:?} vs events={e:?}"),
        }

        #[cfg(feature = "libyaml-compat")]
        {
            let compat_opts = crate::compat::ParseOptions::new();
            let direct_c = SpannedTree::parse_compat_with(input, &compat_opts);
            let via_events_c =
                crate::compat::parse_events_with(input, &compat_opts).and_then(|events| {
                    let mut builder = Builder::new(input, false);
                    for event in events {
                        builder.event(event?)?;
                    }
                    Ok(builder.finish())
                });
            match (direct_c, via_events_c) {
                (Ok(d), Ok(e)) => {
                    assert_eq!(format!("{d:?}"), format!("{e:?}"), "compat {input:?}");
                }
                (Err(de), Err(ee)) => {
                    assert_eq!(de.code(), ee.code(), "compat {input:?}");
                    assert_eq!(de.span(), ee.span(), "compat {input:?}");
                    assert_eq!(de.location(), ee.location(), "compat {input:?}");
                }
                (d, e) => panic!("compat mismatch on {input:?}: direct={d:?} vs events={e:?}"),
            }
        }
    }

    // Tight `max_events` error matches between direct `EventSink::Spanned` and event-stream path.
    let tight = ParseOptions::new().with_limits(Limits::new().with_max_events(5));
    let tight_input = "a: 1\nb: 2\nc: 3\n";
    let direct_err = SpannedTree::parse_with(tight_input, &tight).expect_err("direct max_events");
    let events_err = crate::parse_events_with(tight_input, &tight)
        .and_then(|events| {
            let mut builder = Builder::new(tight_input, false);
            for event in events {
                builder.event(event?)?;
            }
            Ok(builder.finish())
        })
        .expect_err("events max_events");
    assert_eq!(direct_err.code(), events_err.code());
    assert_eq!(direct_err.span(), events_err.span());
    assert_eq!(direct_err.location(), events_err.location());
}

#[test]
fn builder_cache_storage_block_scalar_and_anchored_depth_invariants() {
    use std::borrow::Cow;

    // 1. `AfterBlockScalar::from_raw`: leading whitespace-only line (`spaces == line.len()`) must
    //    not be treated as content, and keep chomping `+` preserves `(indent, true)`.
    assert_eq!(
        AfterBlockScalar::from_raw("|\n  \n    hi\n").known(),
        Some((4, false))
    );
    assert_eq!(
        AfterBlockScalar::from_raw("|+\n  hi\n").known(),
        Some((2, true))
    );
    assert_eq!(
        AfterBlockScalar::from_raw("|-\n  hi\n").known(),
        Some((2, false))
    );

    // 2. `split_first_line`: leading CRLF at index 0 (`i * 1` vs `i + 1`).
    assert_eq!(split_first_line("\r\nabc"), ("", "abc"));
    assert_eq!(split_first_line("\rabc"), ("", "abc"));
    assert_eq!(split_first_line("ab\r\ncd"), ("ab", "cd"));

    // 3. `LineScanCache` monotonic caching (`entry_end` backward lookback preserves newer cache,
    //    `value_indicator_follows` checks `from >= cached.from`).
    let sample = "a: 1\nb:\n  \n: val\nc: 3\n";
    let mut cache = LineScanCache::new(sample);
    let later = sample.find("c: 3").unwrap();
    let earlier = sample.find("a: 1").unwrap();
    let _ = cache.entry_end(later);
    let _ = cache.entry_end(earlier);
    assert_eq!(cache.last_entry_end.map(|(at, _)| at), Some(later));
    let colon_line = sample.find("  \n: val").unwrap();
    let _ = cache.blank_run(colon_line);
    assert!(cache.value_indicator_follows(colon_line));
    assert!(!cache.value_indicator_follows(0));

    // 4. `EntryStorage::get_mut` rejects `index >= len` even when backing scratch has more slots.
    let dummy_entry = || Entry {
        key: SpannedNode {
            span: Span::empty(0),
            entry_span: PackedOptionSpan::NONE,
            kind: Kind::PlainScalar("k"),
        },
        value: SpannedNode {
            span: Span::empty(0),
            entry_span: PackedOptionSpan::NONE,
            kind: Kind::PlainScalar("v"),
        },
        ambiguous: false,
    };
    let mut scratch = vec![dummy_entry(), dummy_entry()];
    let mut storage = EntryStorage::Scratch { start: 0, len: 1 };
    assert!(storage.get_mut(&mut scratch, 0).is_some());
    assert!(storage.get_mut(&mut scratch, 1).is_none());

    // 5. `SpannedNode::spanned_scalar_key` resolves `Kind::Scalar` with `Plain` style and no tag
    //    (e.g. `Cow::Owned` or `v != r`) as a typed key, while `Builder::push_scalar_inner` keeps
    //    `Kind::Scalar` whenever `v != r`.
    let mut b_owned = Builder::new("1: v\n\"1\": q\n", false);
    b_owned
        .event(Event::MappingStart {
            style: crate::event::CollectionStyle::Block,
            tag: None,
            anchor: None,
            span: Span::new(0, 0),
        })
        .expect("map");
    b_owned
        .event(Event::Scalar {
            value: Cow::Owned("1".to_owned()),
            raw: Cow::Borrowed("1"),
            style: ScalarStyle::Plain,
            tag: None,
            anchor: None,
            span: Span::new(0, 1),
        })
        .expect("owned plain key");
    b_owned.push_plain_scalar("v", Span::new(3, 4));
    // Add a quoted `"1"` sibling key: unmutated, owned plain `1` resolves to `Other(1)` while
    // quoted `"1"` stays `Str("1")` (distinct, non-ambiguous). Mutating `spanned_scalar_key`'s
    // `data.style != ScalarStyle::Plain` guard causes a false collision marking both ambiguous.
    b_owned
        .event(Event::Scalar {
            value: Cow::Borrowed("1"),
            raw: Cow::Borrowed("\"1\""),
            style: ScalarStyle::DoubleQuoted,
            tag: None,
            anchor: None,
            span: Span::new(5, 8),
        })
        .expect("quoted key 1");
    b_owned.push_plain_scalar("q", Span::new(10, 11));
    b_owned
        .event(Event::MappingEnd {
            span: Span::new(12, 12),
        })
        .expect("end");
    b_owned
        .event(Event::DocumentEnd {
            explicit: false,
            span: Span::new(12, 12),
        })
        .expect("doc end");
    let tree_owned = b_owned.finish();
    assert_eq!(
        tree_owned
            .lookup(&[PathSegment::Key(Value::from(1_u64))])
            .and_then(SpannedNode::scalar_text),
        Some("v")
    );
    assert_eq!(
        tree_owned
            .lookup(&[PathSegment::Key(Value::from("1"))])
            .and_then(SpannedNode::scalar_text),
        Some("q")
    );

    // When `v != r` (e.g. multiline plain scalar), `push_scalar_inner` preserves `raw` (`Kind::Scalar`).
    let mut b_raw = Builder::new("a\n  b", false);
    b_raw
        .event(Event::Scalar {
            value: Cow::Borrowed("a b"),
            raw: Cow::Borrowed("a\n  b"),
            style: ScalarStyle::Plain,
            tag: None,
            anchor: None,
            span: Span::new(0, 5),
        })
        .expect("scalar");
    b_raw
        .event(Event::DocumentEnd {
            explicit: false,
            span: Span::new(5, 5),
        })
        .expect("end");
    let raw_tree = b_raw.finish();
    assert_eq!(raw_tree.scalar_text_at(&[]), Some("a\n  b"));
    assert_eq!(raw_tree.scalar_encoding_at(&[]), Some("a\n  b"));
}

#[test]
fn spanned_tree_document_predicates_and_matches_key() {
    use std::borrow::Cow;

    // 5b. `SpannedTree::document`, `SpannedNode::is_*` predicates, and `matches_key` across
    //     plain, owned-plain, quoted, and tagged scalar keys.
    let pred_tree = SpannedTree::parse("s: &a [1]\n\"1\": q\n!!str 2: t\nr: *a\n").expect("pred");
    let root_doc = pred_tree.document(0).expect("doc 0");
    assert!(pred_tree.document(1).is_none());
    assert!(
        root_doc.is_mapping()
            && !root_doc.is_sequence()
            && !root_doc.is_scalar()
            && !root_doc.is_alias()
    );
    let seq_node = pred_tree
        .lookup(&[PathSegment::Key(Value::from("s"))])
        .expect("seq");
    assert!(
        seq_node.is_sequence()
            && !seq_node.is_mapping()
            && !seq_node.is_scalar()
            && !seq_node.is_alias()
    );
    let sc_node = pred_tree
        .lookup(&[PathSegment::Key(Value::from("1"))])
        .expect("quoted 1");
    assert!(
        sc_node.is_scalar()
            && !sc_node.is_sequence()
            && !sc_node.is_mapping()
            && !sc_node.is_alias()
    );
    assert_eq!(sc_node.scalar_text(), Some("q"));
    assert!(
        pred_tree
            .lookup(&[PathSegment::Key(Value::from(1_u64))])
            .is_none()
    );
    assert_eq!(
        pred_tree.scalar_encoding_at(&[PathSegment::Key(Value::from("2"))]),
        Some("t")
    );
    let alias_node = pred_tree
        .lookup(&[PathSegment::Key(Value::from("r"))])
        .expect("alias");
    assert!(
        alias_node.is_alias()
            && !alias_node.is_scalar()
            && !alias_node.is_sequence()
            && !alias_node.is_mapping()
    );

    // Owned plain `Kind::Scalar` keys (`"1"` and `"foo"`): verify exact typed and string lookup.
    let mut b_mk = Builder::new("1: a\nfoo: b\n", false);
    b_mk.event(Event::MappingStart {
        style: crate::event::CollectionStyle::Block,
        tag: None,
        anchor: None,
        span: Span::new(0, 0),
    })
    .expect("map");
    for (k, v) in [("1", "a"), ("foo", "b")] {
        b_mk.event(Event::Scalar {
            value: Cow::Owned(k.to_owned()),
            raw: Cow::Borrowed(k),
            style: ScalarStyle::Plain,
            tag: None,
            anchor: None,
            span: Span::new(0, k.len()),
        })
        .expect("k");
        b_mk.push_plain_scalar(v, Span::new(0, v.len()));
    }
    b_mk.event(Event::MappingEnd {
        span: Span::new(12, 12),
    })
    .expect("end");
    b_mk.event(Event::DocumentEnd {
        explicit: false,
        span: Span::new(12, 12),
    })
    .expect("doc end");
    let mk_tree = b_mk.finish();
    assert_eq!(
        mk_tree.scalar_text_at(&[PathSegment::Key(Value::from(1_u64))]),
        Some("a")
    );
    assert!(
        mk_tree
            .lookup(&[PathSegment::Key(Value::from(2_u64))])
            .is_none()
    );
    assert!(
        mk_tree
            .lookup(&[PathSegment::Key(Value::from("1"))])
            .is_none()
    );
    assert_eq!(
        mk_tree.scalar_text_at(&[PathSegment::Key(Value::from("foo"))]),
        Some("b")
    );
    assert!(
        mk_tree
            .lookup(&[PathSegment::Key(Value::from("bar"))])
            .is_none()
    );
}

#[test]
fn builder_reserve_block_scalar_and_anchored_depth_invariants() {
    use std::borrow::Cow;

    // 6. `Builder::reserve_collection`, `in_key_position`, `tracking_resolved`, `SCRATCH_LIMIT`
    //    pre-allocation boundary, and `suppress_entry_spans`/`marked` `after_block_scalar` guards.
    let mut b = Builder::new("a: 1\n", false);
    assert!(!b.in_key_position());
    assert!(!b.tracking_resolved());
    b.reserve_collection(SCRATCH_LIMIT);
    assert_eq!(b.pending_capacity, Some(SCRATCH_LIMIT));
    b.event(Event::SequenceStart {
        style: crate::event::CollectionStyle::Flow,
        tag: None,
        anchor: None,
        span: Span::empty(0),
    })
    .expect("seq at limit");
    assert!(matches!(
        b.stack.last().map(|f| &f.kind),
        Some(FrameKind::Sequence {
            items: SeqStorage::Scratch { .. },
            ..
        })
    ));
    b.reserve_collection(SCRATCH_LIMIT + 1);
    b.event(Event::SequenceStart {
        style: crate::event::CollectionStyle::Flow,
        tag: None,
        anchor: None,
        span: Span::empty(0),
    })
    .expect("seq above limit");
    assert!(matches!(
        b.stack.last().map(|f| &f.kind),
        Some(FrameKind::Sequence {
            items: SeqStorage::Owned(_),
            ..
        })
    ));
    b.reserve_collection(SCRATCH_LIMIT);
    b.event(Event::MappingStart {
        style: crate::event::CollectionStyle::Flow,
        tag: None,
        anchor: None,
        span: Span::empty(0),
    })
    .expect("map at limit");
    assert!(matches!(
        b.stack.last().map(|f| &f.kind),
        Some(FrameKind::Mapping {
            entries: EntryStorage::Scratch { .. },
            ..
        })
    ));
    assert!(b.in_key_position());
    b.reserve_collection(SCRATCH_LIMIT + 1);
    b.event(Event::MappingStart {
        style: crate::event::CollectionStyle::Flow,
        tag: None,
        anchor: None,
        span: Span::empty(0),
    })
    .expect("map above limit");
    assert!(matches!(
        b.stack.last().map(|f| &f.kind),
        Some(FrameKind::Mapping {
            entries: EntryStorage::Owned(_),
            ..
        })
    ));
    assert!(b.tracking_resolved());

    // `suppress_entry_spans` and `marked` skip updating `after_block_scalar`.
    for (input, suppress) in [("k: |\n  hi\n", true), ("a\n\u{feff}k: |\n  hi\n", false)] {
        let mut bs = Builder::new(input, suppress);
        bs.after_block_scalar = AfterBlockScalar::UNKNOWN;
        bs.push_plain_scalar("x", Span::new(0, 1));
        assert!(bs.after_block_scalar.is_some());
        bs.after_block_scalar = AfterBlockScalar::NONE;
        bs.push_scalar(
            Cow::Borrowed("hi\n"),
            "|\n  hi\n",
            ScalarStyle::Literal,
            None,
            false,
            Span::new(0, 7),
        );
        assert!(!bs.after_block_scalar.is_some());
    }

    // 7. Closing an anchored sequence or anchored mapping decrements `anchored_depth` back to 0 so
    //    following sibling entries keep their exact `entry_span`.
    let after_anchored_seq = "a: &s\n  - 1\n  - 2\nb: 3\n";
    let seq_tree = SpannedTree::parse(after_anchored_seq).expect("parse after anchored seq");
    assert_eq!(
        seq_tree
            .entry_span_at(&[PathSegment::Key(Value::from("b"))])
            .and_then(|s| s.slice(after_anchored_seq)),
        Some("b: 3\n")
    );
    let after_anchored_map = "a: &m\n  x: 1\nb: 2\n";
    let map_tree = SpannedTree::parse(after_anchored_map).expect("parse after anchored map");
    assert_eq!(
        map_tree
            .entry_span_at(&[PathSegment::Key(Value::from("b"))])
            .and_then(|s| s.slice(after_anchored_map)),
        Some("b: 2\n")
    );

    // 8. Anchor propagation suppresses `entry_span` on enclosing entries when either the collection
    //    itself OR any nested key/value/item inside it carries an anchor (`frame.anchored || any_anchored`).
    for (label, doc, path) in [
        (
            "anchored_seq_self",
            "items: &s\n  - 1\n  - 2\nother: 3\n",
            vec![PathSegment::Key(Value::from("items"))],
        ),
        (
            "anchored_seq_child",
            "items:\n  - &a 1\n  - 2\nother: 3\n",
            vec![PathSegment::Key(Value::from("items"))],
        ),
        (
            "anchored_map_self",
            "cfg: &m\n  x: 1\nother: 3\n",
            vec![PathSegment::Key(Value::from("cfg"))],
        ),
        (
            "anchored_map_val_child",
            "cfg:\n  x: &v 1\n  y: 2\nother: 3\n",
            vec![PathSegment::Key(Value::from("cfg"))],
        ),
        (
            "anchored_map_key_child",
            "cfg:\n  &k x: 1\n  y: 2\nother: 3\n",
            vec![PathSegment::Key(Value::from("cfg"))],
        ),
        (
            "compact_first_anchored_key",
            "- &k a: 1\n  b: 2\n",
            vec![PathSegment::Index(0), PathSegment::Key(Value::from("a"))],
        ),
        (
            "compact_first_anchored_val",
            "- a: &v 1\n  b: 2\n",
            vec![PathSegment::Index(0), PathSegment::Key(Value::from("a"))],
        ),
        (
            "seq_item_anchored_in_unanchored_seq",
            "- &a 1\n- 2\n",
            vec![PathSegment::Index(0)],
        ),
    ] {
        let t = SpannedTree::parse(doc).expect(label);
        assert_eq!(
            t.entry_span_at(&path),
            None,
            "{label}: must suppress entry_span"
        );
    }
}

#[test]
fn builder_scratch_spill_key_promotion_alias_ambiguity_and_merge_missing_value() {
    // 9. `SeqStorage` / `EntryStorage` scratch-spill boundary (`SCRATCH_LIMIT = 64`) and
    //    `KeyTracker::Small` -> `Large` promotion boundary (`SMALL_LIMIT = 8`).
    let mut b_spill = Builder::new("", false);
    b_spill
        .event(Event::SequenceStart {
            style: crate::event::CollectionStyle::Flow,
            tag: None,
            anchor: None,
            span: Span::empty(0),
        })
        .expect("seq start");
    for _ in 0..SCRATCH_LIMIT {
        b_spill.push_plain_scalar("1", Span::empty(0));
    }
    assert!(matches!(
        b_spill.stack.last().map(|f| &f.kind),
        Some(FrameKind::Sequence {
            items: SeqStorage::Scratch { len, .. },
            ..
        }) if *len == SCRATCH_LIMIT
    ));
    b_spill.push_plain_scalar("1", Span::empty(0));
    assert!(matches!(
        b_spill.stack.last().map(|f| &f.kind),
        Some(FrameKind::Sequence {
            items: SeqStorage::Owned(v),
            ..
        }) if v.len() == SCRATCH_LIMIT + 1
    ));

    let mut b_map = Builder::new("", false);
    b_map
        .event(Event::MappingStart {
            style: crate::event::CollectionStyle::Flow,
            tag: None,
            anchor: None,
            span: Span::empty(0),
        })
        .expect("map start");
    let keys: Vec<String> = (0..=SCRATCH_LIMIT).map(|i| format!("k{i}")).collect();
    for (idx, k) in keys.iter().enumerate() {
        b_map.push_plain_scalar(k, Span::empty(0));
        b_map.push_plain_scalar("v", Span::empty(0));
        if idx + 1 == SMALL_LIMIT {
            assert!(matches!(
                b_map.stack.last().map(|f| &f.kind),
                Some(FrameKind::Mapping {
                    keys: KeyTracker::Small { .. },
                    ..
                })
            ));
        } else if idx + 1 == SMALL_LIMIT + 1 {
            assert!(matches!(
                b_map.stack.last().map(|f| &f.kind),
                Some(FrameKind::Mapping {
                    keys: KeyTracker::Large(m),
                    ..
                }) if m.capacity() >= SMALL_LIMIT * 2
            ));
        }
        if idx + 1 == SCRATCH_LIMIT {
            assert!(matches!(
                b_map.stack.last().map(|f| &f.kind),
                Some(FrameKind::Mapping {
                    entries: EntryStorage::Scratch { len, .. },
                    ..
                }) if *len == SCRATCH_LIMIT
            ));
        }
    }
    assert!(matches!(
        b_map.stack.last().map(|f| &f.kind),
        Some(FrameKind::Mapping {
            entries: EntryStorage::Owned(v),
            ..
        }) if v.len() == SCRATCH_LIMIT + 1
    ));

    // 10. Alias key inside a LARGE (> SMALL_LIMIT) mapping and inside a complex key mapping both
    //     set `guess = true` so lookups refuse to guess (`KeyTracker::Large` & `KeyTracker::Resolved`).
    let mut large_alias = String::from("a: &a 1\n");
    for i in 0..10 {
        use std::fmt::Write as _;
        let _ = writeln!(large_alias, "k{i}: {i}");
    }
    large_alias.push_str("*a : alias_val\n");
    let large_alias_tree = SpannedTree::parse(&large_alias).expect("large map with alias key");
    assert!(
        large_alias_tree
            .lookup(&[PathSegment::Key(Value::from("k0"))])
            .is_none(),
        "large mapping with an alias key must mark all entries ambiguous"
    );
    let complex_alias_key = "a: &a 1\n? {k: 1, *a : 2}\n: v\nother: ok\n";
    let complex_alias_tree =
        SpannedTree::parse(complex_alias_key).expect("complex key with alias key");
    assert!(
        complex_alias_tree
            .lookup(&[PathSegment::Key(Value::from("other"))])
            .is_none(),
        "mapping containing a complex key with an alias key must not guess"
    );

    // 11. Under `merge_keys = true`, an unmerged own key with a missing value still places its
    //     empty value span immediately after its own `:` (`key_end >= frame.open.start()`).
    let merge_own_missing = "base: &b\n  k: 1\nout:\n  <<: *b\n  own:\n  next: 2\n";
    let merge_opts = ParseOptions::new().with_merge_keys(true);
    let merge_tree = SpannedTree::parse_with(merge_own_missing, &merge_opts).expect("merge");
    let own_span = merge_tree
        .span_at(&[
            PathSegment::Key(Value::from("out")),
            PathSegment::Key(Value::from("own")),
        ])
        .expect("own span");
    let own_colon_end = merge_own_missing.find("own:").unwrap() + "own:".len();
    assert_eq!(own_span, Span::empty(own_colon_end));

    // 12. Direct `record_mapping_key` (`KeyTracker::Resolved` sets `*guess |= true` on unresolved
    //     key) and `SpannedNode::is_missing_value` exact guard matrix.
    let mut resolved_keys = KeyTracker::Resolved(Box::new(Mapping::new()));
    let mut entry_store = EntryStorage::Owned(Vec::new());
    let mut seen_keys = Vec::new();
    let mut guess = false;
    let alias_key = SpannedNode {
        span: Span::empty(0),
        entry_span: PackedOptionSpan::NONE,
        kind: Kind::Alias,
    };
    let _ = record_mapping_key(
        &mut resolved_keys,
        &mut entry_store,
        &mut seen_keys,
        &mut [],
        &mut guess,
        MappingKeyInput {
            in_key: true,
            key_node: &alias_key,
            key_resolved: None,
            node_resolved: None,
            entry_index: 0,
        },
    );
    assert!(
        guess,
        "unresolved key in KeyTracker::Resolved must set guess=true"
    );

    let empty_plain = SpannedNode {
        span: Span::empty(0),
        entry_span: PackedOptionSpan::NONE,
        kind: Kind::PlainScalar(""),
    };
    assert!(empty_plain.is_missing_value(false));
    assert!(!empty_plain.is_missing_value(true));
    let non_empty_plain = SpannedNode {
        span: Span::new(0, 1),
        entry_span: PackedOptionSpan::NONE,
        kind: Kind::PlainScalar(""),
    };
    assert!(!non_empty_plain.is_missing_value(false));
    assert!(!alias_key.is_missing_value(false));
    let empty_scalar = SpannedNode {
        span: Span::empty(0),
        entry_span: PackedOptionSpan::NONE,
        kind: Kind::Scalar(Box::new(ScalarData {
            value: Cow::Borrowed(""),
            raw: Cow::Borrowed(""),
            style: ScalarStyle::Plain,
            tag: None,
        })),
    };
    assert!(empty_scalar.is_missing_value(false));
}