fast-yaml-core 0.6.1

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
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)?;
        Ok(loader.into_documents().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)?;
        Ok(loader
            .into_documents()
            .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(loader.into_documents())
    }
}

/// 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,
    }
}

/// 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 {
    if let Some(tag) = tag.filter(|t| t.is_yaml_core_schema()) {
        let coerced: Option<ScalarOwned> = match tag.suffix.as_str() {
            "int" => s
                .parse::<i64>()
                .ok()
                .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);
        }
    }
    // No tag or unknown tag: non-plain scalars are always strings.
    if style != ScalarStyle::Plain {
        return Value::Value(ScalarOwned::String(s.into()));
    }
    // 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 => other.parse::<i64>().map_or_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" => s
                .parse::<i64>()
                .ok()
                .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");
    }
}