ayaml 0.2.3

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
//! Property tests for emitter, parser, and Serde round trips.

#![allow(
    let_underscore_drop,
    clippy::redundant_clone,
    reason = "test fixtures favor compact setup, generated inputs, and literal YAML braces"
)]

use ayaml::Value;
use proptest::prelude::*;

proptest! {
    #[test]
    fn emitted_strings_round_trip(text in any::<String>()) {
        let value = Value::from(text.as_str());
        let output = ayaml::to_string_value(&value).expect("emit");
        let decoded = ayaml::parse_value(&output).expect("reparse");
        prop_assert_eq!(decoded, value, "output={:?}", output);
    }

    #[test]
    fn parser_does_not_panic(input in any::<String>()) {
        let _ = ayaml::parse_value(&input);
    }

    #[test]
    fn emitted_string_sequences_round_trip(values in prop::collection::vec(any::<String>(), 0..8)) {
        let value = Value::Sequence(values.into_iter().map(Value::from).collect());
        let output = ayaml::to_string_value(&value).expect("emit");
        let decoded = ayaml::parse_value(&output).expect("reparse");
        prop_assert_eq!(decoded, value, "output={:?}", output);
    }
}

proptest! {
    #[test]
    fn borrowed_value_matches_composed_value(input in any::<String>()) {
        let composed = ayaml::parse_value(&input);
        let borrowed = ayaml::from_str_borrowed::<Value>(&input);
        match (composed, borrowed) {
            (Ok(composed), Ok(borrowed)) => {
                // Both paths keep tags, so they compare exactly, as the
                // `borrowed` fuzz target does.
                prop_assert_eq!(composed, borrowed);
            }
            (Err(_), Err(_)) => {}
            (Ok(value), Err(error)) => {
                prop_assert!(false, "composed {value:?}, borrowed error {error:?}");
            }
            (Err(error), Ok(value)) => {
                prop_assert!(false, "composed error {error:?}, borrowed {value:?}");
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Emitter oracles over generated values
// ---------------------------------------------------------------------------

/// Text that exercises YAML syntax: indicators, spaces, line breaks, quotes,
/// escapes, and look-alikes of other types.
fn yamlish_text() -> impl Strategy<Value = String> {
    prop_oneof![
        any::<String>(),
        "[-?:,#&*!|>'\"%@`\\[\\]{} a0.~\\n\\t]{0,10}",
        prop::sample::select(vec![
            "",
            "~",
            "null",
            "true",
            "no",
            "-1",
            "+1",
            "0x1F",
            "0o17",
            "1e3",
            ".inf",
            "-.inf",
            ".nan",
            "18446744073709551616",
            "-9223372036854775809",
            "...",
            "--- a",
            "- a",
            "? a",
            ": a",
            "a: b",
            "a #b",
            "#a",
            "a\n",
            "\n",
            "\n\n",
            " a",
            "a ",
            " \n",
            "a\n\nb\n\n",
            "\u{a0}",
            "\u{feff}a",
            "\u{85}",
            "\u{2028}",
            "\u{fffe}",
            "\t",
        ])
        .prop_map(str::to_owned),
    ]
}

fn scalar_value() -> impl Strategy<Value = Value> {
    prop_oneof![
        Just(Value::Null),
        any::<bool>().prop_map(Value::from),
        any::<i64>().prop_map(Value::from),
        any::<u64>().prop_map(Value::from),
        any::<f64>().prop_map(Value::from),
        yamlish_text().prop_map(Value::from),
    ]
}

fn tag_suffix() -> impl Strategy<Value = String> {
    prop_oneof![
        "[A-Za-z][A-Za-z0-9]{0,6}",
        "[a-z %!:/#,\\[\\]{}\u{e9}]{1,6}",
    ]
}

/// Nested values: sequences, mappings with any keys, and single-tagged
/// values, because YAML cannot hold a tag on a tagged value.
fn nested_value() -> impl Strategy<Value = Value> {
    scalar_value().prop_recursive(4, 48, 5, |inner| {
        prop_oneof![
            prop::collection::vec(inner.clone(), 0..5).prop_map(Value::Sequence),
            prop::collection::vec((inner.clone(), inner.clone()), 0..5).prop_map(|entries| {
                let mut mapping = ayaml::Mapping::new();
                for (key, value) in entries {
                    mapping.insert(key, value);
                }
                Value::Mapping(mapping)
            }),
            (tag_suffix(), inner).prop_map(|(suffix, value)| {
                if value.is_tagged() {
                    value
                } else {
                    Value::from(ayaml::TaggedValue::new(ayaml::Tag::local(suffix), value))
                }
            }),
        ]
    })
}

/// The first alias in `events` that has no node with its anchor earlier in its own document.
fn first_dangling_alias<'e>(events: &'e [ayaml::Event<'_>]) -> Option<&'e str> {
    use ayaml::Event;

    let mut anchors = std::collections::HashSet::new();
    for event in events {
        match event {
            Event::DocumentStart { .. } => anchors.clear(),
            Event::Alias { anchor, .. } => {
                if !anchors.contains(anchor.as_str()) {
                    return Some(anchor.as_str());
                }
            }
            Event::Scalar {
                anchor: Some(anchor),
                ..
            }
            | Event::SequenceStart {
                anchor: Some(anchor),
                ..
            }
            | Event::MappingStart {
                anchor: Some(anchor),
                ..
            } => {
                anchors.insert(anchor.as_str());
            }
            _ => {}
        }
    }
    None
}

fn reparse(output: &str) -> Value {
    ayaml::parse_value(output).unwrap_or_else(|error| panic!("{error}; output={output:?}"))
}

// The default 256 cases keep `cargo test` fast; set PROPTEST_CASES for
// deeper runs.
proptest! {
    #[test]
    fn nested_values_round_trip(value in nested_value()) {
        let output = ayaml::to_string_value(&value).expect("emit");
        prop_assert_eq!(reparse(&output), value, "output={:?}", output);
    }

    #[test]
    fn nested_values_round_trip_with_options(
        value in nested_value(),
        flow in any::<bool>(),
        indent in 2_usize..=9,
        indent_sequences in any::<bool>(),
        style in prop::option::of(prop::sample::select(vec![
            ayaml::ScalarStyle::Plain,
            ayaml::ScalarStyle::SingleQuoted,
            ayaml::ScalarStyle::DoubleQuoted,
            ayaml::ScalarStyle::Literal,
            ayaml::ScalarStyle::Folded,
        ])),
    ) {
        let options = ayaml::EmitOptions::new()
            .with_flow(flow)
            .with_explicit_start(true)
            .with_explicit_end(true)
            .with_scalar_style(style)
            .with_indent(indent)
            .with_indent_sequences(indent_sequences);
        let output = ayaml::to_string_value_with(&value, &options).expect("emit");
        prop_assert_eq!(reparse(&output), value, "output={:?}", output);
    }

    /// Event emission of the parsed text keeps the documents, and the lazy
    /// writer writes exactly what the collected writer writes.
    #[test]
    fn event_emission_round_trips_generated_documents(value in nested_value()) {
        let text = ayaml::to_string_value(&value).expect("emit");
        let events = ayaml::parse_events(&text)
            .and_then(Iterator::collect::<Result<Vec<_>, _>>)
            .expect("events");
        let output = ayaml::to_string_events(&events).expect("emit events");
        prop_assert_eq!(reparse(&output), value, "text={:?} output={:?}", text, output);
        let mut lazy = Vec::new();
        ayaml::to_writer_event_stream(&mut lazy, ayaml::parse_events(&text).expect("stream"))
            .expect("lazy emit");
        prop_assert_eq!(String::from_utf8(lazy).expect("utf8"), output);
    }

    /// Whatever parses, both emitters write as text that parses back. The one exception is an
    /// alias with no anchor before it in its document, which the event readers report as it is
    /// written and the event writer refuses, since no value reader loads it (D97).
    #[test]
    fn emitters_accept_whatever_parses(input in yamlish_text()) {
        let Ok(events) = ayaml::parse_events(&input).and_then(Iterator::collect::<Result<Vec<_>, _>>)
        else {
            return Ok(());
        };
        let dangling = first_dangling_alias(&events);
        let output = match ayaml::to_string_events(&events) {
            Ok(output) => output,
            Err(error) => {
                // The refusal is of the first such alias, and no reader of values loads the
                // stream that holds it.
                let name = dangling.unwrap_or_else(|| panic!("{error}; input={input:?}"));
                prop_assert_eq!(
                    error.to_string(),
                    format!(
                        "cannot write the alias {name:?}: no node before it in its document has that anchor"
                    ),
                    "input={:?}",
                    input
                );
                prop_assert!(ayaml::parse_documents(&input).is_err(), "input={:?}", input);
                return Ok(());
            }
        };
        prop_assert!(dangling.is_none(), "input={:?} output={:?}", input, output);
        let reparsed = ayaml::parse_events(&output)
            .and_then(Iterator::collect::<Result<Vec<_>, _>>)
            .unwrap_or_else(|error| panic!("{error}; input={input:?} output={output:?}"));
        prop_assert_eq!(reparsed.len(), events.len(), "output={:?}", output);
        if let Ok(value) = ayaml::parse_value(&input) {
            prop_assert_eq!(reparse(&output), value.clone());
            let output = ayaml::to_string_value(&value).expect("emit value");
            prop_assert_eq!(reparse(&output), value, "output={:?}", output);
        }
    }
}

// ---------------------------------------------------------------------------
// Serde round trips
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
enum Shape {
    Unit,
    Newtype(i64),
    Flag(bool),
    Tuple(i32, String),
    Struct {
        name: Option<String>,
        sizes: Vec<u16>,
    },
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Document {
    names: Vec<Vec<String>>,
    pairs: Vec<(i32, i32)>,
    maybe: Option<String>,
    nothing: Option<u8>,
    shape: Shape,
    shapes: Vec<Shape>,
    table: std::collections::BTreeMap<String, Vec<i64>>,
    ratio: f64,
    small: f32,
    letter: char,
    unit: (),
}

fn shape() -> impl Strategy<Value = Shape> {
    prop_oneof![
        Just(Shape::Unit),
        any::<i64>().prop_map(Shape::Newtype),
        any::<bool>().prop_map(Shape::Flag),
        (any::<i32>(), yamlish_text()).prop_map(|(a, b)| Shape::Tuple(a, b)),
        (
            prop::option::of(yamlish_text()),
            prop::collection::vec(any::<u16>(), 0..4)
        )
            .prop_map(|(name, sizes)| Shape::Struct { name, sizes }),
    ]
}

prop_compose! {
    fn document()(
        names in prop::collection::vec(prop::collection::vec(yamlish_text(), 0..3), 0..3),
        pairs in prop::collection::vec((any::<i32>(), any::<i32>()), 0..3),
        maybe in prop::option::of(yamlish_text()),
        nothing in prop::option::of(any::<u8>()),
        shape in shape(),
        shapes in prop::collection::vec(shape(), 0..3),
        table in prop::collection::btree_map(yamlish_text(), prop::collection::vec(any::<i64>(), 0..3), 0..3),
        ratio in any::<f64>().prop_filter("NaN is never equal", |value| !value.is_nan()),
        small in any::<f32>().prop_filter("NaN is never equal", |value| !value.is_nan()),
        letter in any::<char>(),
    ) -> Document {
        Document { names, pairs, maybe, nothing, shape, shapes, table, ratio, small, letter, unit: () }
    }
}

/// The round trip below can't notice a matching mistake in the emitter and the
/// reader, so this pins both sides to literal text.
#[test]
fn serde_types_match_literal_yaml() {
    let document = Document {
        names: vec![vec!["a".to_owned(), "b c".to_owned()], Vec::new()],
        pairs: vec![(1, -2)],
        maybe: Some("kept".to_owned()),
        nothing: None,
        shape: Shape::Newtype(7),
        shapes: vec![
            Shape::Unit,
            Shape::Flag(true),
            Shape::Tuple(3, "t".to_owned()),
            Shape::Struct {
                name: None,
                sizes: vec![4, 5],
            },
        ],
        table: std::collections::BTreeMap::from([("k".to_owned(), vec![6])]),
        ratio: 1.5,
        small: 0.25,
        letter: 'z',
        unit: (),
    };
    let text = "\
names:
- - a
  - b c
- []
pairs:
- - 1
  - -2
maybe: kept
nothing: null
shape: !Newtype 7
shapes:
- Unit
- !Flag true
-
  !Tuple
  - 3
  - t
-
  !Struct
  name: null
  sizes:
  - 4
  - 5
table:
  k:
  - 6
ratio: 1.5
small: 0.25
letter: z
unit: null
";
    assert_eq!(ayaml::to_string(&document).expect("emit"), text);
    assert_eq!(ayaml::from_str::<Document>(text).expect("read"), document);
}

proptest! {
    #[test]
    fn serde_types_round_trip(document in document()) {
        let output = ayaml::to_string(&document).expect("emit");
        let decoded: Document = ayaml::from_str(&output)
            .unwrap_or_else(|error| panic!("{error}; output={output:?}"));
        prop_assert_eq!(decoded, document, "output={:?}", output);
    }
}

proptest! {
    /// Equal tags hash alike whatever form wrote them: a local tag with its own handle, a verbatim
    /// tag, an expanded handle, or a core tag. The hasher is deterministic, and the test checks
    /// every pair in each spelling group.
    #[test]
    fn equal_tag_spellings_hash_alike(suffix in tag_suffix()) {
        use std::cmp::Ordering;
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        fn hash(tag: &ayaml::Tag) -> u64 {
            let mut hasher = DefaultHasher::new();
            tag.hash(&mut hasher);
            hasher.finish()
        }

        let groups = [
            vec![
                ayaml::Tag::local(suffix.as_str()),
                ayaml::Tag::new("!", suffix.as_str()),
                ayaml::Tag::new("", format!("!{suffix}")),
            ],
            vec![
                ayaml::Tag::new("tag:x:", suffix.as_str()),
                ayaml::Tag::new("", format!("tag:x:{suffix}")),
            ],
            vec![
                ayaml::Tag::core(suffix.as_str()),
                ayaml::Tag::new("tag:yaml.org,2002:", suffix.as_str()),
                ayaml::Tag::new("", format!("tag:yaml.org,2002:{suffix}")),
            ],
        ];
        for tags in groups {
            for left in &tags {
                for right in &tags {
                    prop_assert_eq!(left, right);
                    prop_assert_eq!(hash(left), hash(right));
                    prop_assert_eq!(left.cmp(right), Ordering::Equal);
                }
            }
        }
    }
}