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
//! Unit and property tests for frontmatter / prefix-document splitting and parsing (AY-146).

use ayaml::{
    ColumnEncoding, ErrorCode, ErrorKind, FrontmatterDelimiter, LimitKind, Limits, LineIndex,
    MAX_DEPTH_CAP, ParseOptions, PathSegment, Position, SpannedTree, Value,
};
use proptest::prelude::*;
use serde::Deserialize;

#[derive(Debug, PartialEq, Eq, Deserialize)]
struct BorrowedHeader<'a> {
    title: &'a str,
    tags: Vec<&'a str>,
}

#[test]
fn handles_no_frontmatter_and_non_delimiter_prefixes() {
    for input in [
        "",
        "\u{feff}",
        "# Plain Markdown\n\nBody text.\n",
        "----\nnot frontmatter\n----\n",
        "--- inline scalar\n---\nbody\n",
        "---#no-space-comment\n---\nbody\n",
    ] {
        assert_eq!(
            ayaml::split_frontmatter(input).expect("split"),
            None,
            "{input:?}"
        );
        assert_eq!(
            ayaml::parse_frontmatter_value(input).expect("parse value"),
            None,
            "{input:?}"
        );
    }
}

#[test]
fn handles_bom_crlf_delimiters_empty_and_block_scalars_with_dashes() {
    // Leading BOM + CRLF + block scalar containing indented `---` and `...` + `...` closer
    // + arbitrary non-YAML body (including form feed and unbalanced brackets).
    let input = "\u{feff}--- # header\r\ntitle: Hello\r\nnote: |\r\n  line 1\r\n  ---\r\n  ...\r\n  line 2\r\n...   # end\r\n# Body\r\n\x0c[unclosed\r\n";
    let split = ayaml::split_frontmatter(input)
        .expect("split")
        .expect("has frontmatter");
    assert_eq!(split.closing_delimiter(), FrontmatterDelimiter::DocumentEnd);
    assert_eq!(split.yaml_span().start(), 0);
    assert_eq!(&input[split.yaml_span().range()], split.yaml());
    assert_eq!(&input[split.delimiter_span().range()], "...");
    assert_eq!(split.body(), "# Body\r\n\x0c[unclosed\r\n");
    assert_eq!(&input[split.body_offset()..], split.body());

    // LineIndex aligns spans from parsing `split.yaml()` directly with `input`.
    let index = LineIndex::new(input);
    let tree = SpannedTree::parse(split.yaml()).expect("spanned");
    let title_span = tree
        .span_at(&[PathSegment::key("title")])
        .expect("title span");
    assert_eq!(&input[title_span.range()], "Hello");
    assert_eq!(
        index
            .to_position(title_span.start(), ColumnEncoding::Utf8)
            .expect("title pos"),
        Position::new(1, 7)
    );
    assert_eq!(
        index
            .to_position(split.body_offset(), ColumnEncoding::Utf8)
            .expect("body pos"),
        Position::new(8, 0)
    );

    let parsed = ayaml::parse_frontmatter_value(input)
        .expect("parse value")
        .expect("has frontmatter");
    assert_eq!(parsed.frontmatter["title"].as_str(), Some("Hello"));
    assert_eq!(
        parsed.frontmatter["note"].as_str(),
        Some("line 1\n---\n...\nline 2\n")
    );
    assert_eq!(parsed.body, split.body());
    assert_eq!(parsed.body_offset, split.body_offset());

    // Empty frontmatter with `---` and `...`, with and without trailing newline.
    for (doc, delim, expected_body) in [
        (
            "---\n---\nbody\n",
            FrontmatterDelimiter::DocumentStart,
            "body\n",
        ),
        (
            "---\r\n...\r\nbody",
            FrontmatterDelimiter::DocumentEnd,
            "body",
        ),
        ("---\n---", FrontmatterDelimiter::DocumentStart, ""),
        ("---\n...", FrontmatterDelimiter::DocumentEnd, ""),
    ] {
        let parsed = ayaml::parse_frontmatter_value(doc)
            .expect("empty frontmatter")
            .expect("some");
        assert_eq!(parsed.frontmatter, Value::Null);
        assert_eq!(parsed.closing_delimiter, delim);
        assert_eq!(parsed.body, expected_body);
        assert_eq!(&doc[parsed.body_offset..], parsed.body);
    }

    // Multiline double-quoted scalar containing an indented `---` line stays inside frontmatter.
    let quoted_doc = "---\nmsg: \"hello\n  ---\n  world\"\n---\nBody\n";
    let parsed = ayaml::parse_frontmatter_value(quoted_doc)
        .expect("quoted dashes")
        .expect("some");
    assert_eq!(parsed.frontmatter["msg"].as_str(), Some("hello --- world"));
    assert_eq!(parsed.body, "Body\n");

    // Syntax errors inside frontmatter preserve exact spans and locations in the original input.
    let bad_yaml = "\u{feff}---\na: 1\nb: \"\\z\"\n---\n# Body\n";
    let err = ayaml::parse_frontmatter_value(bad_yaml).expect_err("syntax error");
    let err_span = err.span().expect("error span");
    let bad_index = LineIndex::new(bad_yaml);
    let err_pos = bad_index
        .to_position(err_span.start(), ColumnEncoding::Utf8)
        .expect("error pos");
    assert_eq!(err_pos.line, 2);
    assert_eq!(err.location().map(ayaml::Location::line), Some(3));

    // Borrowed deserialization works directly from the original input.
    let typed_doc = "---\ntitle: Borrowed\ntags: [a, b]\n---\nParagraph\n";
    let parsed: ayaml::ParsedFrontmatter<'_, BorrowedHeader<'_>> =
        ayaml::parse_frontmatter(typed_doc)
            .expect("typed")
            .expect("some");
    assert_eq!(
        parsed.frontmatter,
        BorrowedHeader {
            title: "Borrowed",
            tags: vec!["a", "b"],
        }
    );
    assert_eq!(parsed.body, "Paragraph\n");
}

#[test]
fn rejects_missing_closing_delimiter_and_enforces_limits() {
    for unclosed in [
        "---",
        "\u{feff}---",
        "---\n",
        "---\ntitle: hi\n",
        "---\na: 1\n--- extra text\n",
    ] {
        let error = ayaml::split_frontmatter(unclosed).expect_err(unclosed);
        assert_eq!(error.kind(), ErrorKind::Parser, "{unclosed:?}: {error}");
        assert_eq!(
            error.code(),
            ErrorCode::UnexpectedToken,
            "{unclosed:?}: {error}"
        );
        assert_eq!(
            error.location().map(|loc| (loc.line(), loc.column())),
            Some((1, 1)),
            "{unclosed:?}: {error}"
        );
    }

    // Invalid limits fail fast even when the input has no frontmatter.
    for bad in [
        Limits::new().with_max_depth(MAX_DEPTH_CAP + 1),
        Limits::new().with_node_cost_bytes(0),
    ] {
        let opts = ParseOptions::new().with_limits(bad);
        for error in [
            ayaml::split_frontmatter_with("# plain\n", &opts).unwrap_err(),
            ayaml::parse_frontmatter_with::<Value>("# plain\n", &opts).unwrap_err(),
            ayaml::parse_frontmatter_value_with("# plain\n", &opts).unwrap_err(),
        ] {
            assert_eq!(error.kind(), ErrorKind::Limit);
            assert_eq!(error.limit(), None);
        }
    }

    // Oversized body after a small frontmatter is accepted even when total input > max_input_bytes.
    let small_opts = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(32));
    let mut big_body = String::from("---\na: 1\n---\n");
    big_body.push_str(&"x".repeat(4096));
    let parsed = ayaml::parse_frontmatter_value_with(&big_body, &small_opts)
        .expect("small header with large body")
        .expect("some");
    assert_eq!(parsed.frontmatter["a"].as_u64(), Some(1));
    assert_eq!(parsed.body.len(), 4096);

    // Oversized frontmatter (closed or unclosed single long line) fails with LimitKind::InputBytes.
    let big_header = format!("---\nk: {}\n---\nbody\n", "v".repeat(64));
    let error = ayaml::split_frontmatter_with(&big_header, &small_opts).expect_err("big header");
    assert_eq!(error.kind(), ErrorKind::Limit);
    assert_eq!(
        error.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );

    let unclosed_long_line = format!("---\n{}", "z".repeat(4096));
    let error = ayaml::split_frontmatter_with(&unclosed_long_line, &small_opts)
        .expect_err("unclosed long line");
    assert_eq!(error.kind(), ErrorKind::Limit);
    assert_eq!(
        error.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );

    // Oversized comment on the opening `---` line fails boundedly with LimitKind::InputBytes.
    let long_open_comment = format!("--- #{}\na: 1\n---\nbody\n", "c".repeat(4096));
    let error = ayaml::split_frontmatter_with(&long_open_comment, &small_opts)
        .expect_err("long opening comment");
    assert_eq!(error.kind(), ErrorKind::Limit);
    assert_eq!(
        error.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );

    // Oversized comment on the closing delimiter line also fails boundedly with InputBytes.
    let long_close_comment = format!("---\na: 1\n--- #{}\nbody\n", "c".repeat(4096));
    let error = ayaml::split_frontmatter_with(&long_close_comment, &small_opts)
        .expect_err("long closing comment");
    assert_eq!(error.kind(), ErrorKind::Limit);
    assert_eq!(
        error.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );

    // Bare CR (`\r`) line breaks work consistently with YAML 1.2.2 and LineIndex.
    for (doc, expected_body) in [
        ("---\ra: 1\r---\rbody", "body"),
        ("---\na: 1\r---\nbody\n", "body\n"),
        ("---\na: 1\n---\rbody", "body"),
    ] {
        let parsed = ayaml::parse_frontmatter_value(doc)
            .expect("cr frontmatter")
            .expect("some");
        assert_eq!(parsed.frontmatter["a"].as_u64(), Some(1));
        assert_eq!(parsed.body, expected_body);
        assert_eq!(&doc[parsed.body_offset..], parsed.body);
    }

    // Depth and other parser limits are enforced when parsing frontmatter.
    let depth_opts = ParseOptions::new().with_limits(Limits::new().with_max_depth(1));
    let error = ayaml::parse_frontmatter_value_with("---\na: [1, 2]\n---\nbody\n", &depth_opts)
        .expect_err("depth limit");
    assert_eq!(error.kind(), ErrorKind::Limit);
    assert_eq!(
        error.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::Depth)
    );
}

fn proptest_config() -> ProptestConfig {
    let default_cases = if cfg!(miri) { 2 } else { 128 };
    let cases = std::env::var("PROPTEST_CASES")
        .ok()
        .and_then(|value| value.parse().ok())
        .unwrap_or(default_cases);
    ProptestConfig {
        cases,
        ..ProptestConfig::default()
    }
}

#[test]
fn split_frontmatter_rejects_four_hyphens_even_under_tiny_input_limit() {
    let opts = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(2));
    assert_eq!(
        ayaml::split_frontmatter_with("----\nbody\n", &opts),
        Ok(None)
    );
    let bom_opts = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(5));
    assert_eq!(
        ayaml::split_frontmatter_with("\u{feff}----\nbody\n", &bom_opts),
        Ok(None)
    );
}

#[test]
fn over_limit_multibyte_utf8_delimiter_comments_never_panic() {
    // Opening delimiter comment with 2-byte (`é`) and 4-byte (`🦀`) UTF-8 sequences where
    // `max_input_bytes` lands on interior continuation bytes.
    for (doc, limits) in [
        ("--- #é\na: 1\n---\nbody\n", &[5_usize, 6][..]),
        ("--- #🦀\na: 1\n---\nbody\n", &[5, 6, 7][..]),
        ("---\na: 1\n--- #🦀\nbody\n", &[14, 15, 16][..]),
    ] {
        for &max_bytes in limits {
            let opts =
                ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(max_bytes));
            let split_err = ayaml::split_frontmatter_with(doc, &opts)
                .expect_err("over-limit utf8 comment split");
            assert_eq!(split_err.kind(), ErrorKind::Limit, "max={max_bytes}");
            assert_eq!(
                split_err.limit().map(ayaml::LimitExceeded::kind),
                Some(LimitKind::InputBytes)
            );
            assert!(split_err.location().is_some());
            if let Some(span) = split_err.span() {
                assert!(doc.is_char_boundary(span.start()));
                assert!(doc.is_char_boundary(span.end()));
            }
            let parse_err = ayaml::parse_frontmatter_value_with(doc, &opts)
                .expect_err("over-limit utf8 comment parse");
            assert_eq!(parse_err.kind(), ErrorKind::Limit, "max={max_bytes}");
        }
    }
}

#[test]
fn frontmatter_bounded_line_scan_exact_limit_and_crlf_edges() {
    // Non-delimiter line whose `\n` sits at byte `remaining` exceeds `max_input_bytes`.
    let opts_8 = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(8));
    let over_nl = ayaml::split_frontmatter_with("---\nabcd\n---", &opts_8)
        .expect_err("newline past remaining budget must fail with InputBytes");
    assert_eq!(over_nl.kind(), ErrorKind::Limit);
    assert_eq!(
        over_nl.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );

    // Unterminated final line whose length equals `remaining` exactly hits EOF cleanly and
    // reports missing closing delimiter (`Parser`), not `InputBytes` or a slice panic.
    let eof_exact = ayaml::split_frontmatter_with("---\nabcd", &opts_8)
        .expect_err("exact-limit unterminated frontmatter reports missing delimiter");
    assert_eq!(eof_exact.kind(), ErrorKind::Parser);

    // CRLF line where `i + 2 == remaining < i * 2` (`i = 4`, `remaining = 6`) must succeed the
    // line scan and reach missing closing delimiter (`Parser`) rather than `InputBytes`.
    let opts_10 = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(10));
    let crlf_exact = ayaml::split_frontmatter_with("---\na: 1\r\n", &opts_10)
        .expect_err("exact-limit CRLF line reaches missing closing delimiter");
    assert_eq!(crlf_exact.kind(), ErrorKind::Parser);

    // Same CRLF line with 1 byte less (`remaining = 5 < 6`) must fail with `InputBytes`.
    let opts_9 = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(9));
    let crlf_over = ayaml::split_frontmatter_with("---\na: 1\r\n", &opts_9)
        .expect_err("CRLF split across remaining budget must fail with InputBytes");
    assert_eq!(crlf_over.kind(), ErrorKind::Limit);
    assert_eq!(
        crlf_over.limit().map(ayaml::LimitExceeded::kind),
        Some(LimitKind::InputBytes)
    );
}

proptest! {
    #![proptest_config(proptest_config())]

    #[test]
    fn round_trips_frontmatter_and_aligns_line_index_spans(
        bom in any::<bool>(),
        crlf in any::<bool>(),
        use_doc_end in any::<bool>(),
        title in "[a-zA-Z0-9 _.-]{1,24}",
        block_mid in "[a-zA-Z0-9 _.-]{0,16}",
        body in "[\\PC\n]{0,64}",
    ) {
        let nl = if crlf { "\r\n" } else { "\n" };
        let close = if use_doc_end { "..." } else { "---" };
        let expected_delim = if use_doc_end {
            FrontmatterDelimiter::DocumentEnd
        } else {
            FrontmatterDelimiter::DocumentStart
        };

        let mut doc = String::new();
        if bom {
            doc.push('\u{feff}');
        }
        doc.push_str("---");
        doc.push_str(nl);
        doc.push_str("title: '");
        doc.push_str(&title.replace('\'', "''"));
        doc.push('\'');
        doc.push_str(nl);
        doc.push_str("note: |2");
        doc.push_str(nl);
        doc.push_str("  ");
        doc.push_str(&block_mid);
        doc.push_str(nl);
        doc.push_str("  ---");
        doc.push_str(nl);
        doc.push_str("  ...");
        doc.push_str(nl);
        let expected_yaml_end = doc.len();
        doc.push_str(close);
        doc.push_str(nl);
        let expected_body_offset = doc.len();
        doc.push_str(&body);

        let split = ayaml::split_frontmatter(&doc)
            .expect("valid split")
            .expect("has frontmatter");
        prop_assert_eq!(split.closing_delimiter(), expected_delim);
        prop_assert_eq!(split.yaml_span().start(), 0);
        prop_assert_eq!(split.yaml_span().end(), expected_yaml_end);
        prop_assert_eq!(split.body_offset(), expected_body_offset);
        prop_assert_eq!(split.body(), body.as_str());
        prop_assert_eq!(&doc[split.body_offset()..], split.body());

        // SpannedTree spans over split.yaml() align identically with LineIndex::new(&doc).
        let index = LineIndex::new(&doc);
        let tree = SpannedTree::parse(split.yaml()).expect("spanned");
        let title_span = tree
            .span_at(&[PathSegment::key("title")])
            .expect("title span");
        prop_assert_eq!(&doc[title_span.range()], &split.yaml()[title_span.range()]);
        prop_assert_eq!(
            index
                .to_position(title_span.start(), ColumnEncoding::Utf8)
                .expect("title pos")
                .line,
            1
        );
        prop_assert_eq!(
            index
                .to_position(split.body_offset(), ColumnEncoding::Utf8)
                .expect("body pos")
                .line,
            7
        );

        // Decoded Value matches expected fields.
        let parsed = ayaml::parse_frontmatter_value(&doc)
            .expect("parse value")
            .expect("has frontmatter");
        prop_assert_eq!(parsed.frontmatter["title"].as_str(), Some(title.as_str()));
        let expected_note = format!("{block_mid}\n---\n...\n");
        prop_assert_eq!(
            parsed.frontmatter["note"].as_str(),
            Some(expected_note.as_str())
        );
        prop_assert_eq!(parsed.body, body.as_str());
        prop_assert_eq!(parsed.body_offset, expected_body_offset);
    }
}