fast-yaml-core 0.6.3

Core YAML 1.2.2 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
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
use crate::error::ParseResult;
use crate::value::Value;
use saphyr::{ScalarOwned, YamlLoader};
use saphyr_parser::{BufferedInput, Parser as SaphyrParser, ScalarStyle, Tag};

/// Parser for YAML documents.
///
/// Wraps saphyr's YAML loading to provide a consistent API.
#[derive(Debug)]
pub struct Parser;

impl Parser {
    /// Parse a single YAML document from a string.
    ///
    /// Returns the first document if multiple are present, or None if the input is empty.
    ///
    /// # Errors
    ///
    /// Returns `ParseError::Scanner` if the YAML syntax is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use fast_yaml_core::Parser;
    ///
    /// let result = Parser::parse_str("name: test\nvalue: 123")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_str(input: &str) -> ParseResult<Option<Value>> {
        let mut saphyr_parser = SaphyrParser::new(BufferedInput::new(input.chars()));
        let mut loader = YamlLoader::<Value>::default();
        loader.early_parse(false);
        saphyr_parser.load(&mut loader, true)?;
        let docs = inject_implicit_null_if_empty(loader.into_documents(), input);
        Ok(docs.into_iter().next().map(canonicalize))
    }

    /// Parse all YAML documents from a string.
    ///
    /// Returns a vector of all documents found in the input.
    ///
    /// # Errors
    ///
    /// Returns `ParseError::Scanner` if the YAML syntax is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use fast_yaml_core::Parser;
    ///
    /// let docs = Parser::parse_all("---\nfoo: 1\n---\nbar: 2")?;
    /// assert_eq!(docs.len(), 2);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse_all(input: &str) -> ParseResult<Vec<Value>> {
        let mut saphyr_parser = SaphyrParser::new(BufferedInput::new(input.chars()));
        let mut loader = YamlLoader::<Value>::default();
        loader.early_parse(false);
        saphyr_parser.load(&mut loader, true)?;
        let docs = inject_implicit_null_if_empty(loader.into_documents(), input);
        Ok(docs.into_iter().map(canonicalize).collect())
    }

    /// Parse all YAML documents preserving scalar styles (literal `|`, folded `>`).
    ///
    /// Unlike [`parse_all`], this function uses `early_parse = false` in the loader,
    /// which keeps scalars as `Value::Representation` nodes with their original style
    /// information instead of resolving them eagerly.
    ///
    /// This is used by the format pipeline to preserve block scalar styles in output.
    ///
    /// # Errors
    ///
    /// Returns `ParseError::Scanner` if the YAML syntax is invalid.
    ///
    /// [`parse_all`]: Parser::parse_all
    pub fn parse_all_preserving_styles(input: &str) -> ParseResult<Vec<Value>> {
        let mut saphyr_parser = SaphyrParser::new(BufferedInput::new(input.chars()));
        let mut loader = YamlLoader::<Value>::default();
        loader.early_parse(false);
        saphyr_parser.load(&mut loader, true)?;
        Ok(inject_implicit_null_if_empty(
            loader.into_documents(),
            input,
        ))
    }
}

/// Returns `true` when `tag` is the YAML non-specific tag `!`.
///
/// The non-specific tag forces the failsafe schema: scalars resolve to plain strings
/// regardless of their content (YAML 1.2 §6.8.1 / §10.3.2).
fn is_non_specific_tag(tag: &Tag) -> bool {
    tag.handle.is_empty() && tag.suffix == "!"
}

/// Injects one implicit null document when saphyr produces no documents for non-empty input.
///
/// Per YAML 1.2 §9.2, a stream with no explicit documents but non-empty content
/// (comments, bare markers, whitespace) represents one document with an implicit null node.
/// Empty string input stays `[]` to match `safe_load("")` → `None` behaviour.
fn inject_implicit_null_if_empty(docs: Vec<Value>, input: &str) -> Vec<Value> {
    if docs.is_empty() && !input.is_empty() {
        vec![Value::Value(ScalarOwned::Null)]
    } else {
        docs
    }
}

/// Canonicalize mixed-case YAML 1.2.2 bool/null variants that saphyr leaves as strings.
///
/// saphyr handles lowercase `true`, `false`, `null`, `~` natively.
/// This function post-processes the tree to:
/// - Resolve `Value::Representation` nodes (produced by `early_parse = false`) to typed scalars,
///   applying explicit YAML core schema tags (`!!int`, `!!float`, `!!bool`, `!!null`, `!!str`)
///   when present (#203).
/// - Handle `True`, `TRUE`, `False`, `FALSE`, `Null` mixed-case variants.
/// - Resolve YAML 1.1 merge keys (`<<: *anchor`) into parent mappings (#204).
pub fn canonicalize(value: Value) -> Value {
    match value {
        Value::Representation(ref s, style, ref tag) => {
            coerce_representation(s, style, tag.as_ref())
        }
        Value::Value(ScalarOwned::String(ref s)) => match s.as_str() {
            "True" | "TRUE" => Value::Value(ScalarOwned::Boolean(true)),
            "False" | "FALSE" => Value::Value(ScalarOwned::Boolean(false)),
            "Null" | "NULL" => Value::Value(ScalarOwned::Null),
            _ => value,
        },
        Value::Tagged(ref tag, ref inner) => coerce_tagged(tag, inner),
        Value::Sequence(seq) => Value::Sequence(seq.into_iter().map(canonicalize).collect()),
        Value::Mapping(map) => {
            let canonicalized: crate::value::Map = map
                .into_iter()
                .map(|(k, v)| (canonicalize(k), canonicalize(v)))
                .collect();
            resolve_merge_keys(canonicalized)
        }
        other => other,
    }
}

/// Parse a YAML core schema integer: decimal, hex (`0x`), or octal (`0o`).
///
/// Returns `None` for values that overflow `i64` or don't match integer syntax.
fn parse_core_schema_int(s: &str) -> Option<i64> {
    let (neg, digits) = s.strip_prefix('-').map_or_else(
        || (false, s.strip_prefix('+').unwrap_or(s)),
        |rest| (true, rest),
    );
    let raw: i64 = if let Some(hex) = digits
        .strip_prefix("0x")
        .or_else(|| digits.strip_prefix("0X"))
    {
        i64::from_str_radix(hex, 16).ok()?
    } else if let Some(oct) = digits
        .strip_prefix("0o")
        .or_else(|| digits.strip_prefix("0O"))
    {
        i64::from_str_radix(oct, 8).ok()?
    } else {
        digits.parse::<i64>().ok()?
    };
    if neg { raw.checked_neg() } else { Some(raw) }
}

/// Returns `true` if `s` is an integer literal (decimal, hex, or octal) that may exceed `i64` range.
///
/// Matches optional `+`/`-` sign followed by `0x`/`0X` + hex digits, `0o`/`0O` + octal digits,
/// or plain ASCII decimal digits.
fn is_integer_literal(s: &str) -> bool {
    let s = s.strip_prefix(['+', '-']).unwrap_or(s);
    if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        return !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit());
    }
    if let Some(oct) = s.strip_prefix("0o").or_else(|| s.strip_prefix("0O")) {
        return !oct.is_empty() && oct.bytes().all(|b| matches!(b, b'0'..=b'7'));
    }
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}

/// Attempt to coerce a float string to `i64` via truncation toward zero (`PyYAML` convention).
///
/// Returns `None` for non-finite values (.nan, .inf) and values outside the `i64` range.
/// Values very close to `i64::MAX` may saturate due to `f64` precision limits — this is a
/// known, benign edge case at the representable boundary.
#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
fn float_str_to_int(s: &str) -> Option<i64> {
    parse_core_schema_float(s)
        .filter(|f| f.is_finite() && *f >= i64::MIN as f64 && *f <= i64::MAX as f64)
        .map(|f| f as i64)
}

/// Parse a YAML core schema float, handling special values (.inf, .nan, etc.).
fn parse_core_schema_float(s: &str) -> Option<f64> {
    match s {
        ".inf" | ".Inf" | ".INF" => Some(f64::INFINITY),
        "-.inf" | "-.Inf" | "-.INF" => Some(f64::NEG_INFINITY),
        ".nan" | ".NaN" | ".NAN" => Some(f64::NAN),
        // YAML 1.2 Core Schema float: optional sign, digits, optional fraction, optional exponent.
        // Reject bare words like "infinity" or "nan" that Rust's f64::parse() accepts.
        other => {
            let s = other.strip_prefix(['+', '-']).unwrap_or(other);
            let has_digit_start = s.starts_with(|c: char| c.is_ascii_digit());
            let looks_like_float = has_digit_start
                && s.chars().all(|c| {
                    c.is_ascii_digit() || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-'
                });
            looks_like_float
                .then(|| other.parse::<f64>().ok())
                .flatten()
        }
    }
}

/// Coerce a `Value::Representation` scalar, applying the tag if present.
///
/// When `early_parse = false`, saphyr preserves the raw string, style, and tag in a
/// `Representation` node. This function resolves that node to a typed `Value::Value`.
fn coerce_representation(s: &str, style: ScalarStyle, tag: Option<&Tag>) -> Value {
    // 1. Core-schema explicit tag (!!str, !!int, !!float, !!bool, !!null).
    if let Some(tag) = tag.filter(|t| t.is_yaml_core_schema()) {
        let coerced: Option<ScalarOwned> = match tag.suffix.as_str() {
            "int" => parse_core_schema_int(s)
                .or_else(|| float_str_to_int(s))
                .map(ScalarOwned::Integer),
            "float" => parse_core_schema_float(s).map(|f| ScalarOwned::FloatingPoint(f.into())),
            "bool" => s.parse::<bool>().ok().map(ScalarOwned::Boolean),
            "null" => matches!(s, "~" | "null" | "").then_some(ScalarOwned::Null),
            "str" => Some(ScalarOwned::String(s.into())),
            _ => None,
        };
        if let Some(scalar) = coerced {
            return Value::Value(scalar);
        }
    }
    // 2. Non-specific tag `!`: failsafe schema forces string (YAML 1.2 §6.8.1 / §10.3.2).
    if tag.is_some_and(is_non_specific_tag) {
        return Value::Value(ScalarOwned::String(s.into()));
    }
    // 3. No tag or unknown tag: non-plain scalars are always strings.
    if style != ScalarStyle::Plain {
        return Value::Value(ScalarOwned::String(s.into()));
    }
    // 4. Empty plain scalar with no tag: implicit null (YAML 1.2 §10.3.2, bare `---`).
    if s.is_empty() {
        return Value::Value(ScalarOwned::Null);
    }
    // 5. Plain scalar: apply saphyr's implicit resolution rules.
    let scalar = match s {
        "~" | "null" | "NULL" | "Null" => ScalarOwned::Null,
        "true" | "True" | "TRUE" => ScalarOwned::Boolean(true),
        "false" | "False" | "FALSE" => ScalarOwned::Boolean(false),
        other => parse_core_schema_int(other).map_or_else(
            || {
                if is_integer_literal(other) {
                    ScalarOwned::String(other.into())
                } else {
                    parse_core_schema_float(other).map_or_else(
                        || ScalarOwned::String(other.into()),
                        |f| ScalarOwned::FloatingPoint(f.into()),
                    )
                }
            },
            ScalarOwned::Integer,
        ),
    };
    Value::Value(scalar)
}

/// Coerce a tagged value to the appropriate scalar type based on the YAML core schema tag suffix.
fn coerce_tagged(tag: &Tag, inner: &Value) -> Value {
    if tag.is_yaml_core_schema()
        && let Value::Value(ScalarOwned::String(ref s)) = *inner
    {
        let coerced: Option<ScalarOwned> = match tag.suffix.as_str() {
            "int" => parse_core_schema_int(s)
                .or_else(|| float_str_to_int(s))
                .map(ScalarOwned::Integer),
            "float" => parse_core_schema_float(s).map(|f| ScalarOwned::FloatingPoint(f.into())),
            "bool" => s.parse::<bool>().ok().map(ScalarOwned::Boolean),
            "null" => matches!(s.as_str(), "~" | "null" | "").then_some(ScalarOwned::Null),
            "str" => Some(ScalarOwned::String(s.clone())),
            _ => None,
        };
        if let Some(scalar) = coerced {
            return Value::Value(scalar);
        }
    }
    canonicalize(inner.clone())
}

/// Resolve YAML 1.1 merge keys (`<<`) in a canonicalized mapping.
///
/// Explicit keys always win over merged keys.
fn resolve_merge_keys(map: crate::value::Map) -> Value {
    let merge_key = Value::Value(ScalarOwned::String("<<".into()));
    if !map.contains_key(&merge_key) {
        return Value::Mapping(map);
    }

    let mut result: crate::value::Map = crate::value::Map::new();
    let mut merges: Vec<Value> = Vec::new();

    for (k, v) in map {
        if k == merge_key {
            merges.push(v);
        } else {
            result.insert(k, v);
        }
    }

    for merge_val in merges {
        match merge_val {
            Value::Mapping(merge_map) => {
                for (mk, mv) in merge_map {
                    result.entry(mk).or_insert(mv);
                }
            }
            Value::Sequence(seq) => {
                for item in seq {
                    if let Value::Mapping(merge_map) = item {
                        for (mk, mv) in merge_map {
                            result.entry(mk).or_insert(mv);
                        }
                    }
                }
            }
            _ => {}
        }
    }

    Value::Mapping(result)
}

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

    #[test]
    fn test_parse_str_simple() {
        let result = Parser::parse_str("name: test\nvalue: 123").unwrap();
        assert!(result.is_some());
    }

    #[test]
    fn test_parse_str_empty() {
        let result = Parser::parse_str("").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_all_multiple_docs() {
        let docs = Parser::parse_all("---\nfoo: 1\n---\nbar: 2").unwrap();
        assert_eq!(docs.len(), 2);
    }

    #[test]
    fn test_yaml12_bool_true_variants() {
        for variant in &["True", "TRUE"] {
            let result = Parser::parse_str(&format!("val: {variant}"))
                .unwrap()
                .unwrap();
            if let Value::Mapping(map) = result {
                let v = map.values().next().unwrap();
                assert!(
                    matches!(v, Value::Value(ScalarOwned::Boolean(true))),
                    "{variant} should be Bool(true)"
                );
            } else {
                panic!("expected mapping");
            }
        }
    }

    #[test]
    fn test_yaml12_bool_false_variants() {
        for variant in &["False", "FALSE"] {
            let result = Parser::parse_str(&format!("val: {variant}"))
                .unwrap()
                .unwrap();
            if let Value::Mapping(map) = result {
                let v = map.values().next().unwrap();
                assert!(
                    matches!(v, Value::Value(ScalarOwned::Boolean(false))),
                    "{variant} should be Bool(false)"
                );
            } else {
                panic!("expected mapping");
            }
        }
    }

    #[test]
    fn test_yaml12_null_variant() {
        let result = Parser::parse_str("val: Null").unwrap().unwrap();
        if let Value::Mapping(map) = result {
            let v = map.values().next().unwrap();
            assert!(
                matches!(v, Value::Value(ScalarOwned::Null)),
                "Null should be Null"
            );
        } else {
            panic!("expected mapping");
        }
    }

    #[test]
    fn test_parse_str_invalid() {
        let result = Parser::parse_str("invalid: [\n  missing: bracket");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_nested() {
        let yaml = r"
person:
  name: John
  age: 30
  hobbies:
    - reading
    - coding
";
        let result = Parser::parse_str(yaml).unwrap();
        assert!(result.is_some());
    }

    #[test]
    fn test_parse_anchors() {
        let yaml = r"
defaults: &defaults
  adapter: postgres
  host: localhost

development:
  <<: *defaults
  database: dev_db
";
        let result = Parser::parse_str(yaml).unwrap();
        assert!(result.is_some());
    }

    fn get_mapping_val(yaml: &str, key: &str) -> Value {
        let result = Parser::parse_str(yaml).unwrap().unwrap();
        let Value::Mapping(map) = result else {
            panic!("expected mapping");
        };
        let k = Value::Value(ScalarOwned::String(key.into()));
        map[&k].clone()
    }

    #[test]
    fn test_explicit_tag_int_quoted() {
        let v = get_mapping_val("val: !!int '42'", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(42))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_float() {
        let v = get_mapping_val("val: !!float '3.14'", "val");
        if let Value::Value(ScalarOwned::FloatingPoint(f)) = v {
            #[allow(clippy::approx_constant)]
            let expected = 3.14_f64;
            assert!((f64::from(f) - expected).abs() < 1e-9);
        } else {
            panic!("expected FloatingPoint, got {v:?}");
        }
    }

    #[test]
    fn test_explicit_tag_bool() {
        let v = get_mapping_val("val: !!bool 'true'", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Boolean(true))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_null() {
        let v = get_mapping_val("val: !!null ''", "val");
        assert!(matches!(v, Value::Value(ScalarOwned::Null)), "got {v:?}");
    }

    #[test]
    fn test_explicit_tag_str_int() {
        let v = get_mapping_val("val: !!str 42", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == "42"),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_float_truncation() {
        let v = get_mapping_val("val: !!int 3.14", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(3))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_negative_float() {
        let v = get_mapping_val("val: !!int -2.7", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(-2))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_scientific() {
        let v = get_mapping_val("val: !!int 1.0e2", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(100))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_exact_float() {
        let v = get_mapping_val("val: !!int 3.0", "val");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(3))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_nan_rejected() {
        let v = get_mapping_val("val: !!int .nan", "val");
        assert!(
            !matches!(v, Value::Value(ScalarOwned::Integer(_))),
            "!!int .nan should not produce an integer, got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_inf_rejected() {
        let v = get_mapping_val("val: !!int .inf", "val");
        assert!(
            !matches!(v, Value::Value(ScalarOwned::Integer(_))),
            "!!int .inf should not produce an integer, got {v:?}"
        );
    }

    #[test]
    fn test_explicit_tag_int_overflow_rejected() {
        let v = get_mapping_val("val: !!int 1.0e20", "val");
        assert!(
            !matches!(v, Value::Value(ScalarOwned::Integer(_))),
            "!!int 1.0e20 should not produce a saturated integer, got {v:?}"
        );
    }

    #[test]
    fn test_merge_key_basic() {
        let yaml = r"
defaults: &defaults
  adapter: postgres
  host: localhost
development:
  <<: *defaults
  database: dev_db
";
        let result = Parser::parse_str(yaml).unwrap().unwrap();
        let Value::Mapping(root) = result else {
            panic!("expected mapping")
        };
        let dev_key = Value::Value(ScalarOwned::String("development".into()));
        let Value::Mapping(dev) = root[&dev_key].clone() else {
            panic!("expected mapping")
        };

        let adapter_key = Value::Value(ScalarOwned::String("adapter".into()));
        let host_key = Value::Value(ScalarOwned::String("host".into()));
        let db_key = Value::Value(ScalarOwned::String("database".into()));

        assert!(dev.contains_key(&adapter_key), "adapter should be merged");
        assert!(dev.contains_key(&host_key), "host should be merged");
        assert!(dev.contains_key(&db_key), "database should be present");
        assert!(
            !dev.contains_key(&Value::Value(ScalarOwned::String("<<".into()))),
            "<< should be removed"
        );
    }

    #[test]
    fn test_merge_key_explicit_wins() {
        let yaml = r"
base: &base
  host: localhost
  port: 5432
override:
  <<: *base
  host: remotehost
";
        let result = Parser::parse_str(yaml).unwrap().unwrap();
        let Value::Mapping(root) = result else {
            panic!("expected mapping")
        };
        let ov_key = Value::Value(ScalarOwned::String("override".into()));
        let Value::Mapping(ov) = root[&ov_key].clone() else {
            panic!("expected mapping")
        };
        let host_key = Value::Value(ScalarOwned::String("host".into()));
        assert!(
            matches!(&ov[&host_key], Value::Value(ScalarOwned::String(s)) if s == "remotehost"),
            "explicit host should win over merged"
        );
    }

    #[test]
    fn test_merge_key_sequence() {
        let yaml = r"
a: &a
  x: 1
b: &b
  y: 2
merged:
  <<: [*a, *b]
  z: 3
";
        let result = Parser::parse_str(yaml).unwrap().unwrap();
        let Value::Mapping(root) = result else {
            panic!("expected mapping")
        };
        let m_key = Value::Value(ScalarOwned::String("merged".into()));
        let Value::Mapping(m) = root[&m_key].clone() else {
            panic!("expected mapping")
        };

        let x = Value::Value(ScalarOwned::String("x".into()));
        let y = Value::Value(ScalarOwned::String("y".into()));
        let z = Value::Value(ScalarOwned::String("z".into()));
        assert!(m.contains_key(&x), "x should be merged from *a");
        assert!(m.contains_key(&y), "y should be merged from *b");
        assert!(m.contains_key(&z), "z should be present");
    }

    #[test]
    fn test_i64_max_boundary() {
        let v = get_mapping_val("x: 9223372036854775807", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(i64::MAX))),
            "i64::MAX should stay Integer, got {v:?}"
        );

        let v = get_mapping_val("x: 9223372036854775808", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "i64::MAX+1 should become String, got {v:?}"
        );
    }

    #[test]
    fn test_leading_plus_large_integer() {
        let v = get_mapping_val("x: +42", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(42))),
            "+42 should be Integer(42), got {v:?}"
        );

        let v = get_mapping_val("x: +99999999999999999999", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "+overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_large_integer_preserved_as_string() {
        let big =
            "99999999999999999999999999999999999999999999999999999999999999999999999999999999";
        let v = get_mapping_val(&format!("x: {big}"), "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == big),
            "got {v:?}"
        );
    }

    #[test]
    fn test_normal_integer_unaffected() {
        let v = get_mapping_val("x: 42", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(42))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_float_unaffected() {
        let v = get_mapping_val("x: 1.5e10", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::FloatingPoint(_))),
            "got {v:?}"
        );
    }

    #[test]
    fn test_negative_large_integer() {
        let big = "-99999999999999999999999999999999";
        let v = get_mapping_val(&format!("x: {big}"), "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == big),
            "got {v:?}"
        );
    }

    #[test]
    fn test_hex_overflow_preserved_as_string() {
        let v = get_mapping_val("x: 0x8000000000000000", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "hex overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_hex_max_i64_preserved_as_integer() {
        // 0x7FFFFFFFFFFFFFFF == i64::MAX == 9223372036854775807
        let v = get_mapping_val("x: 0x7FFFFFFFFFFFFFFF", "x");
        assert!(
            matches!(
                v,
                Value::Value(ScalarOwned::Integer(9_223_372_036_854_775_807))
            ),
            "0x7FFFFFFFFFFFFFFF should be Integer(i64::MAX), got {v:?}"
        );
    }

    #[test]
    fn test_octal_overflow_preserved_as_string() {
        let v = get_mapping_val("x: 0o1000000000000000000000", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "octal overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_octal_max_fitting_preserved_as_integer() {
        // 0o777777777777777777777 == i64::MAX == 9223372036854775807
        let v = get_mapping_val("x: 0o777777777777777777777", "x");
        assert!(
            matches!(
                v,
                Value::Value(ScalarOwned::Integer(9_223_372_036_854_775_807))
            ),
            "0o777777777777777777777 should be Integer(i64::MAX), got {v:?}"
        );
    }

    #[test]
    fn test_tagged_int_hex_fits_i64() {
        let v = get_mapping_val("x: !!int 0xFF", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::Integer(255))),
            "!!int 0xFF should be Integer(255), got {v:?}"
        );
    }

    #[test]
    fn test_tagged_int_hex_overflow_preserved_as_string() {
        let v = get_mapping_val("x: !!int 0x8000000000000000", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "!!int hex overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_negative_hex_overflow_preserved_as_string() {
        // -0x8000000000000000 == i64::MIN, which fits; -0x8000000000000001 overflows.
        // Both produce String because parse_core_schema_int does not handle sign + 0x prefix —
        // consistent with the decimal path where signed hex is not a YAML 1.2 core schema form.
        let v = get_mapping_val("x: -0x8000000000000001", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "negative hex overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_tagged_int_octal_overflow_preserved_as_string() {
        let v = get_mapping_val("x: !!int 0o1000000000000000000000", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "!!int octal overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_uppercase_prefix_hex_overflow_preserved_as_string() {
        let v = get_mapping_val("x: 0XDEADBEEFDEADBEEF", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "0X uppercase prefix overflow should be String, got {v:?}"
        );
    }

    #[test]
    fn test_uppercase_prefix_octal_overflow_preserved_as_string() {
        let v = get_mapping_val("x: 0O1000000000000000000000", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(_))),
            "0O uppercase prefix overflow should be String, got {v:?}"
        );
    }

    // --- #235: empty/comment-only/bare-marker streams yield one null doc ---

    #[test]
    fn test_empty_string_yields_empty_vec() {
        let docs = Parser::parse_all("").unwrap();
        assert!(docs.is_empty(), "empty string must stay []");
    }

    #[test]
    fn test_whitespace_only_yields_null_doc() {
        let docs = Parser::parse_all("   ").unwrap();
        assert_eq!(docs.len(), 1);
        assert!(matches!(docs[0], Value::Value(ScalarOwned::Null)));
    }

    #[test]
    fn test_comment_only_yields_null_doc() {
        let docs = Parser::parse_all("# comment").unwrap();
        assert_eq!(docs.len(), 1);
        assert!(matches!(docs[0], Value::Value(ScalarOwned::Null)));
    }

    #[test]
    fn test_bare_doc_end_yields_null_doc() {
        let docs = Parser::parse_all("...").unwrap();
        assert_eq!(docs.len(), 1);
        assert!(matches!(docs[0], Value::Value(ScalarOwned::Null)));
    }

    #[test]
    fn test_comment_then_doc_end_yields_null_doc() {
        let docs = Parser::parse_all("# c\n...").unwrap();
        assert_eq!(docs.len(), 1);
        assert!(matches!(docs[0], Value::Value(ScalarOwned::Null)));
    }

    #[test]
    fn test_bare_doc_start_yields_null_doc() {
        let docs = Parser::parse_all("---").unwrap();
        assert_eq!(docs.len(), 1);
        assert!(matches!(docs[0], Value::Value(ScalarOwned::Null)));
    }

    #[test]
    fn test_parse_str_comment_only_returns_null() {
        let result = Parser::parse_str("# comment").unwrap();
        assert!(matches!(result, Some(Value::Value(ScalarOwned::Null))));
    }

    #[test]
    fn test_parse_str_empty_unchanged() {
        let result = Parser::parse_str("").unwrap();
        assert!(result.is_none(), "empty string must still return None");
    }

    #[test]
    fn test_bom_only_yields_one_doc() {
        // BOM-only: saphyr processes the BOM and returns one document (empty Null scalar).
        // inject_implicit_null_if_empty is not needed here — saphyr handles it.
        // Document: BOM-only → 1 doc (saphyr behaviour, not injected).
        let docs = Parser::parse_all("\u{FEFF}").unwrap();
        assert_eq!(docs.len(), 1, "BOM-only should yield exactly one document");
    }

    // --- #238: non-specific tag `!` forces string (failsafe schema) ---

    #[test]
    fn test_non_specific_tag_plain_integer_is_string() {
        let v = get_mapping_val("x: ! 99", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == "99"),
            "! 99 should be String(\"99\"), got {v:?}"
        );
    }

    #[test]
    fn test_non_specific_tag_quoted_is_string() {
        let v = get_mapping_val("x: ! \"99\"", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == "99"),
            "! \"99\" should be String(\"99\"), got {v:?}"
        );
    }

    #[test]
    fn test_non_specific_tag_true_is_string() {
        let v = get_mapping_val("x: ! true", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == "true"),
            "! true should be String(\"true\"), got {v:?}"
        );
    }

    #[test]
    fn test_non_specific_tag_null_keyword_is_string() {
        let v = get_mapping_val("x: ! null", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s == "null"),
            "! null should be String(\"null\"), got {v:?}"
        );
    }

    #[test]
    fn test_non_specific_tag_empty_is_string_not_null() {
        // `! ''` must be String(""), NOT Null. Order of branches is load-bearing.
        let v = get_mapping_val("x: ! ''", "x");
        assert!(
            matches!(v, Value::Value(ScalarOwned::String(ref s)) if s.is_empty()),
            "! '' should be String(\"\") not Null, got {v:?}"
        );
    }

    #[test]
    fn test_non_specific_tag_on_sequence_is_noop() {
        // Non-specific tag on collection: failsafe seq = plain seq.
        let yaml = "x: ! [1, 2]";
        let result = Parser::parse_str(yaml).unwrap().unwrap();
        let Value::Mapping(map) = result else {
            panic!("expected mapping")
        };
        let k = Value::Value(ScalarOwned::String("x".into()));
        let val = &map[&k];
        assert!(
            matches!(val, Value::Sequence(_)),
            "! on sequence must stay Sequence, got {val:?}"
        );
    }

    // --- #235 round-trip: format(parse("# c")) freezes new expected output ---

    #[test]
    fn test_round_trip_comment_only() {
        use crate::emitter::Emitter;
        let docs = Parser::parse_all_preserving_styles("# comment").unwrap();
        assert_eq!(docs.len(), 1, "should have one null doc");
        // The null doc formats to "null\n" or "~\n" — freeze whatever the emitter produces.
        let formatted = Emitter::emit_all(&docs).unwrap();
        assert!(
            !formatted.is_empty(),
            "formatted output must be non-empty, got: {formatted:?}"
        );
        // Null should not format as empty string.
        assert_ne!(formatted.trim(), "", "null doc must not format to empty");
    }
}