ayaml 1.0.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#![allow(
    clippy::format_collect,
    reason = "test fixtures favor compact setup, generated inputs, and literal YAML braces"
)]

use std::collections::HashMap;

use super::line::*;
use super::scalars::*;
use super::{Scanner, Token, TokenKind};
use crate::event::ScalarStyle;
use crate::limits::Limits;
use crate::tag::Tag;
use proptest::prelude::*;

fn tokens(input: &str) -> Vec<TokenKind> {
    let limits = Limits::default();
    let mut scanner = Scanner::new(input, &limits).expect("scanner");
    let mut tokens = Vec::new();
    while let Some(token) = scanner.next_token(&limits).expect("token") {
        tokens.push(token.kind);
    }
    tokens
}

fn scalar(input: &str) -> (String, ScalarStyle, String) {
    let limits = Limits::default();
    let mut scanner = Scanner::new(input, &limits).expect("scanner");
    while let Some(token) = scanner.next_token(&limits).expect("token") {
        let raw = input[token.span.start()..token.span.end()].to_owned();
        match token.kind {
            TokenKind::PlainScalar => return (raw.clone(), ScalarStyle::Plain, raw),
            TokenKind::SingleQuotedScalar => {
                return (
                    input[token.span.start() + 1..token.span.end() - 1].to_owned(),
                    ScalarStyle::SingleQuoted,
                    raw,
                );
            }
            TokenKind::DoubleQuotedScalar => {
                return (
                    input[token.span.start() + 1..token.span.end() - 1].to_owned(),
                    ScalarStyle::DoubleQuoted,
                    raw,
                );
            }
            TokenKind::Scalar(scalar) => {
                return (scalar.value.into_owned(input), scalar.style, raw);
            }
            _ => {}
        }
    }
    panic!("no scalar in {input:?}");
}

/// The anchor names `input` leaves for its aliases to match, sorted.
fn colon_anchors(input: &str, compat: bool) -> Option<Vec<String>> {
    let limits = Limits::default();
    let mut scanner = Scanner::with_compat(input, &limits, compat).expect("scanner");
    while scanner.next_token(&limits).expect("token").is_some() {}
    let mut names: Vec<String> = scanner
        .colon_anchors?
        .into_keys()
        .map(str::to_owned)
        .collect();
    names.sort();
    Some(names)
}

fn rules(compat: bool) -> NameRules<'static, 'static> {
    NameRules {
        compat,
        colon_anchors: None,
        input: "",
    }
}

#[test]
fn a_line_ends_an_alias_name_as_the_scanner_does() {
    // The anchor `a:` is defined on the second line, after the first.
    let input = "*a:\n&a: 1\n*a:\n*b:";
    let mut known = HashMap::with_hasher(crate::limits::GlobalHasher);
    known.insert("a:", 4);
    let none = NameRules {
        compat: true,
        colon_anchors: None,
        input,
    };
    let anchored = NameRules {
        compat: true,
        colon_anchors: Some(&known),
        input,
    };
    let default = NameRules {
        compat: false,
        colon_anchors: None,
        input,
    };
    let (before, after, other) = (&input[..3], &input[10..13], &input[14..]);
    let owner = LineShape::Owner(Owner::Block(0));
    // The colon is this line's indicator, unless an anchor before it has the whole name.
    assert_eq!(line_shape(after, none), owner);
    assert_eq!(line_shape(after, anchored), LineShape::Content);
    assert_eq!(line_shape(before, anchored), owner);
    assert_eq!(line_shape(other, anchored), owner);
    assert_eq!(line_shape(after, default), LineShape::Content);
    // No colon to give up, or none but the name.
    assert_eq!(line_shape("*ab", none), LineShape::Content);
    assert_eq!(line_shape("*:", none), LineShape::Content);
    // Only an alias gives one up, and a flow key's alias is inside its key.
    assert_eq!(line_shape("&a:", none), LineShape::Open);
    assert_eq!(line_shape("!a:", none), LineShape::Open);
    assert_eq!(line_shape("{*a: 1}:", none), owner);
}

#[test]
fn only_compat_keeps_anchor_names_and_only_those_ending_in_a_colon() {
    assert_eq!(
        colon_anchors("x: &a: 1\ny: &b 2\nz: &c:d: 3\n", true),
        Some(vec!["a:".to_owned()])
    );
    assert_eq!(colon_anchors("x: &a 1\ny: &b 2\n", true), None);
    assert_eq!(colon_anchors("x: &a: 1\ny: &b 2\n", false), None);
    assert_eq!(colon_anchors("x: &a: 1\n---\ny: 2\n", true), None);
    assert_eq!(colon_anchors("x: &a: 1\n...\n", true), None);
}

#[test]
fn a_line_walk_stops_where_the_scanner_would() {
    // A key that ends at the last `:` on the line, in both modes.
    for text in [
        "a: c",
        "a:",
        "a:\tc",
        "a#b: c",
        "a \"b: c",
        "a [b: c",
        "&a !t k: c",
        "&a\tk: c",
        "\"a: b\": c",
        "\"a\\\": b\": c",
        "\"a\\\\\": c",
        "'a: b': c",
        "'\\': c",
        "'a'': b': c",
        "[a]: c",
        "{a: b}: c",
        "[a#b]: c",
        "[\"]: \"]: c",
        "[']: ']: c",
        "['a'']: ']: c",
        "[\"\\\"]: \"]: c",
        "['\\']: c",
        "{\"a\":\"]: \"}: c",
        "{\"a\" :\"]: \"}: c",
        "{\"a\"\t:\"]: \"}: c",
        "{[a] :\"]: \"}: c",
        "['a' :\"]: \"]: c",
        "{\"a\"::\"b}: c",
        "[x &a: \"]: \"]: c",
        "[x !a: \"]: \"]: c",
        "{x *a: \"]: \"}: c",
        "{a:\t\"]: \"}: c",
        "{a:\"b: c}: d",
        "[&a,\"]: \"]: c",
        "[&a\t\"]: \"]: c",
        "{&a}: c",
        "[!t,\"]: \"]: c",
        "[&a:b \"]: \"]: c",
        "[!<t:]> \"]: \"]: c",
        "{!<t:]> : }: c",
        "[a[b]]: c",
    ] {
        for compat in [false, true] {
            assert_eq!(
                walk_line(text, rules(compat)),
                LineStop::Value(text.rfind(':').unwrap()),
                "{text:?} compat={compat}"
            );
        }
    }
    // A comment, which no later `:` or bracket changes.
    for text in [
        "# a: b",
        "a # b: c",
        "a\t# b: c",
        "'a' # b: c",
        "[a] # b: c",
        "&a # b: c",
    ] {
        for compat in [false, true] {
            assert_eq!(
                walk_line(text, rules(compat)),
                LineStop::Comment(text.find('#').unwrap()),
                "{text:?} compat={compat}"
            );
        }
    }
    // Nothing that ends a key on this line.
    for text in [
        "",
        "a",
        "a:b",
        "a#b",
        "!t",
        "&a b",
        "[",
        "[a",
        "\"a: b",
        "'a",
        "[\"a: b]: c",
        "[a, # b]: c",
        "[a # b]: c",
        "[a\t# b]: c",
        "&:b: c",
        "[a[b]: c",
        "[a{b}: c",
        "{a: [b}: c",
        "[!<t:]: c",
        "!a:b: c",
    ] {
        for compat in [false, true] {
            assert_eq!(
                walk_line(text, rules(compat)),
                LineStop::End,
                "{text:?} compat={compat}"
            );
        }
    }
}

#[test]
fn a_line_walk_reads_names_and_a_flow_question_mark_by_mode() {
    let walk = |text: &str| (walk_line(text, rules(false)), walk_line(text, rules(true)));
    let last = |text: &str| LineStop::Value(text.rfind(':').unwrap());
    for text in ["&a:b: c", "*a:b: c", "&a?b: c", "&a?b \"c: d"] {
        assert_eq!(
            walk(text),
            (LineStop::End, LineStop::Value(text.find(": ").unwrap())),
            "{text:?}"
        );
    }
    let text = "[?\"]: \"]: c";
    assert_eq!(
        walk(text),
        (LineStop::Value(text.find(':').unwrap()), last(text))
    );
    let text = "{?\"a: b}: c";
    assert_eq!(walk(text), (last(text), LineStop::End));
    let text = "[?\t\"]: \"]: c";
    assert_eq!(walk(text), (last(text), last(text)));
}

#[test]
fn a_closing_quote_is_the_one_the_scanner_stops_at() {
    for (text, close) in [
        ("\"a\"", 2),
        ("'a'", 2),
        ("\"a\"\"b\"", 2),
        ("'a''b'", 5),
        ("'a\\'", 3),
        ("\"a\\\"b\"", 5),
        ("\"a\\\\\"", 4),
        ("\"a", 2),
        ("'a''", 4),
    ] {
        assert_eq!(closing_quote(text.as_bytes(), 0), close, "{text:?}");
    }
}

#[test]
fn a_comment_comes_off_the_line_it_ends() {
    for compat in [false, true] {
        for (line, code) in [
            ("a: b", "a: b"),
            ("a: b # c: d", "a: b "),
            ("a: # c", "a: "),
            ("a: b: c # d", "a: b: c "),
            ("# c", ""),
            ("- # c", "- "),
            ("- [' # ']: # c", "- [' # ']: "),
            ("- [\"]: \"]: # c \"", "- [\"]: \"]: "),
            ("? {\", \"}: # c \"", "? {\", \"}: "),
            ("- a#b: # c", "- a#b: "),
            ("\u{feff}a: # c", "\u{feff}a: "),
            ("[a, # b", "[a, # b"),
        ] {
            assert_eq!(
                strip_comment(line, rules(compat)),
                code,
                "{line:?} compat={compat}"
            );
        }
    }
}

#[test]
fn block_tokens_and_indicators() {
    let kinds = tokens("a: 1\n- b\n");
    assert!(matches!(kinds[0], TokenKind::StreamStart));
    assert!(kinds.iter().any(|kind| matches!(kind, TokenKind::Value)));
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::BlockEntry))
    );
    assert!(matches!(kinds.last(), Some(TokenKind::StreamEnd)));
}

#[test]
fn flow_tokens_are_nested_and_comma_separated() {
    let kinds = tokens("[1, {a: 2}]");
    assert!(matches!(kinds[1], TokenKind::FlowSequenceStart { .. }));
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::FlowEntry))
    );
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::FlowMappingStart { .. }))
    );
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::FlowMappingEnd))
    );
}

#[test]
fn block_scalars_support_literal_folding_and_chomping() {
    let (value, style, raw) = scalar("|\n  a\n  b\n");
    assert_eq!(value, "a\nb\n");
    assert_eq!(style, ScalarStyle::Literal);
    assert_eq!(raw, "|\n  a\n  b\n");

    let (value, style, _) = scalar(">\n  a\n  b\n");
    assert_eq!(value, "a b\n");
    assert_eq!(style, ScalarStyle::Folded);

    let (value, _, _) = scalar("|-\n  a\n  b\n");
    assert_eq!(value, "a\nb");

    let (value, _, _) = scalar("|+\n  a\n\n");
    assert_eq!(value, "a\n\n");
}

/// How a block scalar's value was built from a list of its lines, before the scanner built
/// one string as it read them.
fn block_scalar_from_lines(lines: &[(String, bool)], literal: bool, chomping: Chomping) -> String {
    let mut raw = String::new();
    for (text, had_break) in lines {
        raw.push_str(text);
        if *had_break {
            raw.push('\n');
        }
    }
    let mut value = if literal {
        raw
    } else {
        let lines: Vec<&str> = raw.split('\n').collect();
        let mut value = String::new();
        let mut index = 0;
        while index < lines.len() {
            let line = lines[index];
            value.push_str(line);
            if index + 1 == lines.len() {
                break;
            }
            let mut next = index + 1;
            while next < lines.len() && lines[next].is_empty() {
                next += 1;
            }
            if next == lines.len() {
                for _ in index + 1..lines.len() {
                    value.push('\n');
                }
                break;
            }
            let breaks = next - index;
            let more_indented =
                line.starts_with([' ', '\t']) || lines[next].starts_with([' ', '\t']);
            if line.is_empty() || more_indented {
                for _ in 0..breaks {
                    value.push('\n');
                }
            } else if breaks == 1 {
                value.push(' ');
            } else {
                for _ in 0..breaks - 1 {
                    value.push('\n');
                }
            }
            index = next;
        }
        value
    };
    let final_break = lines
        .iter()
        .rev()
        .find(|(text, _)| !text.is_empty())
        .is_some_and(|(_, had_break)| *had_break);
    match chomping {
        Chomping::Strip => {
            while value.ends_with('\n') {
                value.pop();
            }
        }
        Chomping::Clip => {
            while value.ends_with('\n') {
                value.pop();
            }
            if final_break && !value.is_empty() {
                value.push('\n');
            }
        }
        Chomping::Keep => {}
    }
    value
}

/// Building one string as the lines are read gives what the list of lines gave, for every
/// sequence of up to five lines of these kinds, with or without a last line break.
#[test]
fn block_scalars_built_as_read_match_the_list_of_lines() {
    let kinds = ["", "a", "b c", " a", "\ta", "  "];
    let mut sequences: Vec<Vec<&str>> = vec![Vec::new()];
    let mut checked = 0;
    for _ in 0..5 {
        sequences = sequences
            .iter()
            .flat_map(|sequence| {
                kinds.iter().map(move |kind| {
                    let mut longer = sequence.clone();
                    longer.push(kind);
                    longer
                })
            })
            .collect();
        for sequence in &sequences {
            for last_break in [true, false] {
                let lines: Vec<(String, bool)> = sequence
                    .iter()
                    .enumerate()
                    .map(|(at, text)| ((*text).to_owned(), last_break || at + 1 < sequence.len()))
                    .collect();
                let text: String = lines
                    .iter()
                    .map(|(text, had_break)| {
                        format!("{text}{}", if *had_break { "\n" } else { "" })
                    })
                    .collect();
                let final_break = lines
                    .iter()
                    .rev()
                    .find(|(text, _)| !text.is_empty())
                    .is_some_and(|(_, had_break)| *had_break);
                for literal in [true, false] {
                    for chomping in [Chomping::Strip, Chomping::Clip, Chomping::Keep] {
                        assert_eq!(
                            build_block_scalar(text.clone(), final_break, literal, chomping),
                            block_scalar_from_lines(&lines, literal, chomping),
                            "{lines:?}, literal {literal}"
                        );
                        checked += 1;
                    }
                }
            }
        }
    }
    assert_eq!(
        checked,
        (1..=5).map(|n| 6_usize.pow(n) * 2 * 6).sum::<usize>()
    );
}

#[test]
fn block_scalar_indent_indicator_is_relative_to_the_header() {
    // A root node's indentation is -1, so |2 takes one space off a four-space line.
    let (value, _, _) = scalar("|2\n    a\n");
    assert_eq!(value, "   a\n");
}

#[test]
fn single_quotes_decode_doubled_quote() {
    let (value, style, raw) = scalar("'it''s'");
    assert_eq!(value, "it's");
    assert_eq!(style, ScalarStyle::SingleQuoted);
    assert_eq!(raw, "'it''s'");
}

#[test]
fn double_quotes_decode_escapes() {
    let (value, style, _) = scalar("\"a\\n\\u00e9\"");
    assert_eq!(value, "a\né");
    assert_eq!(style, ScalarStyle::DoubleQuoted);
}

#[test]
fn multiline_quoted_scalars_fold_line_breaks() {
    let (value, style, _) = scalar("'a\n  b'");
    assert_eq!(value, "a b");
    assert_eq!(style, ScalarStyle::SingleQuoted);

    let (value, style, _) = scalar("\"a\n  b\"");
    assert_eq!(value, "a b");
    assert_eq!(style, ScalarStyle::DoubleQuoted);

    let (value, _, _) = scalar("'a\n\n  b'");
    assert_eq!(value, "a\nb");
}

#[test]
fn escaped_line_break_in_double_quotes_is_a_continuation() {
    let (value, _, _) = scalar("\"a\\\n  b\"");
    assert_eq!(value, "ab");
}

#[test]
fn anchors_aliases_tags_and_directives() {
    let input = "%YAML 1.2\n---\na: &b !Custom {x: 1}\nc: *b\n";
    let kinds = tokens(input);
    assert!(kinds.iter().any(|kind| matches!(
        kind,
        TokenKind::Directive(directive) if directive.name.slice(input) == Some("YAML")
    )));
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::DocumentStart { explicit: true }))
    );
    assert!(kinds.iter().any(|kind| matches!(kind, TokenKind::Anchor)));
    assert!(kinds.iter().any(|kind| matches!(kind, TokenKind::Alias)));
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::Tag(tag) if *tag == Tag::local("Custom")))
    );
}

#[test]
fn comments_are_skipped_and_line_breaks_are_tokens() {
    let input = "a: 1 # comment\nb: 2\n";
    let limits = Limits::default();
    let mut scanner = Scanner::new(input, &limits).expect("scanner");
    let mut values = Vec::new();
    while let Some(token) = scanner.next_token(&limits).expect("token") {
        match token.kind {
            TokenKind::PlainScalar => {
                values.push(input[token.span.start()..token.span.end()].to_owned());
            }
            TokenKind::Scalar(scalar) => values.push(scalar.value.into_owned(input)),
            _ => {}
        }
    }
    assert!(values.iter().any(|value| value == "1"));
    assert!(!values.iter().any(|value| value.contains("comment")));
}

#[test]
fn crlf_and_bom_are_handled() {
    let kinds = tokens("\u{feff}a: 1\r\nb: 2\r\n");
    assert!(matches!(kinds[0], TokenKind::StreamStart));
    assert!(
        kinds
            .iter()
            .any(|kind| matches!(kind, TokenKind::LineBreak))
    );
}

#[test]
fn unicode_span_is_byte_based() {
    let limits = Limits::default();
    let mut scanner = Scanner::new("é: 1", &limits).expect("scanner");
    let mut spans = Vec::new();
    while let Some(token) = scanner.next_token(&limits).expect("token") {
        let value = match &token.kind {
            TokenKind::PlainScalar => Some(&"é: 1"[token.span.start()..token.span.end()]),
            TokenKind::Scalar(scalar) => Some(scalar.value.as_str("é: 1")),
            _ => None,
        };
        if value == Some("é") {
            spans.push(token.span);
        }
    }
    assert_eq!(spans.len(), 1);
    assert_eq!((spans[0].start(), spans[0].end()), (0, 2));
}

#[test]
fn unterminated_quotes_and_unknown_escapes_error() {
    let limits = Limits::default();
    let mut scanner = Scanner::new("\"unterminated", &limits).expect("scanner");
    let error = loop {
        match scanner.next_token(&limits) {
            Ok(Some(_)) => {}
            Ok(None) => panic!("expected an error"),
            Err(error) => break error,
        }
    };
    assert_eq!(error.kind(), crate::error::ErrorKind::Scanner);

    let mut scanner = Scanner::new("\"\\q\"", &limits).expect("scanner");
    let error = loop {
        match scanner.next_token(&limits) {
            Ok(Some(_)) => {}
            Ok(None) => panic!("expected an error"),
            Err(error) => break error,
        }
    };
    assert_eq!(error.kind(), crate::error::ErrorKind::Scanner);
}

#[test]
fn input_limit_is_enforced_before_scanning() {
    let limits = Limits {
        max_input_bytes: 0,
        ..Limits::default()
    };
    let error = Scanner::new("x", &limits).expect_err("input limit");
    assert_eq!(error.kind(), crate::error::ErrorKind::Limit);
}

#[test]
fn quoted_scalars_borrow_without_escapes_and_decode_escapes_and_breaks() {
    let input = "s1: 'plain café'\ns2: 'it''s\n  fine'\nd1: \"plain café\"\nd2: \"a\\nb\\u0041\"\n";
    let limits = Limits::default();
    let mut scanner = Scanner::new(input, &limits).expect("scanner");
    let mut scalars = Vec::new();
    while let Some(token) = scanner.next_token(&limits).expect("token") {
        match token.kind {
            TokenKind::SingleQuotedScalar => scalars.push((
                ScalarStyle::SingleQuoted,
                true,
                input[token.span.start() + 1..token.span.end() - 1].to_owned(),
            )),
            TokenKind::DoubleQuotedScalar => scalars.push((
                ScalarStyle::DoubleQuoted,
                true,
                input[token.span.start() + 1..token.span.end() - 1].to_owned(),
            )),
            TokenKind::Scalar(scalar) => {
                scalars.push((
                    scalar.style,
                    matches!(scalar.value, super::TokenText::Slice(_)),
                    scalar.value.into_owned(input),
                ));
            }
            _ => {}
        }
    }
    assert_eq!(
        scalars,
        vec![
            (ScalarStyle::SingleQuoted, true, "plain café".to_owned()),
            (ScalarStyle::SingleQuoted, false, "it's fine".to_owned()),
            (ScalarStyle::DoubleQuoted, true, "plain café".to_owned()),
            (ScalarStyle::DoubleQuoted, false, "a\nbA".to_owned()),
        ]
    );
    for bad in ["'unterminated", "\"unterminated", "\"unterminated\\"] {
        let mut scanner = Scanner::new(bad, &limits).expect("scanner");
        let mut err = None;
        while let Ok(Some(_)) = scanner.next_token(&limits).map_err(|e| err = Some(e)) {}
        assert!(err.is_some(), "expected error for {bad:?}");
    }
}

fn scan_all(input: &str, fast: bool) -> Result<Vec<Token>, String> {
    let limits = Limits::default();
    let mut scanner = Scanner::new(input, &limits).map_err(|error| error.to_string())?;
    scanner.fast_continuation = fast;
    let mut tokens = Vec::new();
    while let Some(token) = scanner
        .next_token(&limits)
        .map_err(|error| error.to_string())?
    {
        tokens.push(token);
    }
    Ok(tokens)
}

#[test]
fn swar_scanners_handle_every_alignment_and_stop_byte() {
    for prefix_len in 1..=24 {
        let prefix = "a".repeat(prefix_len);
        // Plain block scalar across warmup + SWAR + tail with `:` / `#` / UTF-8 / newline stops.
        for suffix in [
            "",
            ": x",
            " # comment",
            "é_tail",
            ":not_a_value",
            "#not_a_comment",
        ] {
            let input = format!("{prefix}{suffix}\n");
            let expected = match suffix {
                ": x" | " # comment" => prefix.clone(),
                other => format!("{prefix}{other}"),
            };
            let (value, style, _) = scalar(&input);
            assert_eq!(style, ScalarStyle::Plain);
            assert_eq!(value, expected, "input={input:?}");
        }
        // Single-quoted and double-quoted scalars across warmup + SWAR + tail.
        let single_input = format!("'{prefix}''{prefix}'\n");
        let (value, style, _) = scalar(&single_input);
        assert_eq!(style, ScalarStyle::SingleQuoted);
        assert_eq!(value, format!("{prefix}'{prefix}"));

        let double_input = format!("\"{prefix}\\n{prefix}\"\n");
        let (value, style, _) = scalar(&double_input);
        assert_eq!(style, ScalarStyle::DoubleQuoted);
        assert_eq!(value, format!("{prefix}\n{prefix}"));

        // Borrowed single/double quoted over SWAR lengths.
        let borrowed_single = format!("'{prefix}café{prefix}'\n");
        let (value, _, _) = scalar(&borrowed_single);
        assert_eq!(value, format!("{prefix}café{prefix}"));

        let borrowed_double = format!("\"{prefix}café{prefix}\"\n");
        let (value, _, _) = scalar(&borrowed_double);
        assert_eq!(value, format!("{prefix}café{prefix}"));

        // Flow plain scalar stopping on flow indicators.
        for indicator in [",", "]", "}"] {
            let flow = format!("[{prefix}{indicator}1]");
            let limits = Limits::default();
            let mut scanner = Scanner::new(&flow, &limits).expect("scanner");
            let mut found = None;
            while let Some(tok) = scanner.next_token(&limits).expect("tok") {
                if matches!(tok.kind, TokenKind::PlainScalar) {
                    found = Some(&flow[tok.span.start()..tok.span.end()]);
                    break;
                }
            }
            assert_eq!(found, Some(prefix.as_str()), "flow={flow:?}");
        }

        // Comment SWAR skip across alignment.
        let commented = format!("k: v # {prefix}comment\nnext: 1\n");
        let kinds = tokens(&commented);
        assert_eq!(
            kinds
                .iter()
                .filter(|k| matches!(k, TokenKind::PlainScalar))
                .count(),
            4
        );
    }
}

#[test]
fn inline_non_printable_validation_rejects_every_forbidden_context() {
    let scan_err = |input: &str| {
        let limits = Limits::default();
        let mut scanner = Scanner::new(input, &limits).expect("scanner");
        loop {
            match scanner.next_token(&limits) {
                Ok(Some(_)) => {}
                Ok(None) => return None,
                Err(error) => return Some(error),
            }
        }
    };
    // C0 controls (other than \t, \n, \r) are forbidden everywhere, even inside quotes.
    for ctrl in [0x00_u8, 0x01, 0x07, 0x08, 0x0b, 0x0c, 0x1b, 0x1f] {
        let ch = ctrl as char;
        for input in [
            format!("plain{ch}text"),
            format!("'single{ch}text'"),
            format!("\"double{ch}text\""),
            format!("a: 1 # comment{ch}text\n"),
            format!("|\n  block{ch}text\n"),
            format!("| # header{ch}text\n  ok\n"),
            format!("&anc{ch}hor 1"),
            format!("!tag{ch}x 1"),
            format!("%TAG !e! {ch}\n---\n1\n"),
            format!("{}plain{ch}after_swar", "x".repeat(32)),
            format!("\"{}double{ch}after_swar\"", "x".repeat(32)),
            format!("'{}single{ch}after_swar'", "x".repeat(32)),
        ] {
            let err = scan_err(&input).unwrap_or_else(|| panic!("expected error for {input:?}"));
            assert_eq!(err.kind(), crate::error::ErrorKind::Scanner, "{input:?}");
        }
    }
    // DEL, C1 (excluding NEL U+0085), U+FFFE, U+FFFF are forbidden outside quotes, allowed inside.
    for ch in [
        '\u{7f}', '\u{80}', '\u{84}', '\u{86}', '\u{9f}', '\u{fffe}', '\u{ffff}',
    ] {
        for bad in [
            format!("plain{ch}text"),
            format!("{}plain{ch}after_swar", "x".repeat(32)),
            format!("a: 1 # comment{ch}text\n"),
            format!("a: 1 # {}comment{ch}after_swar\n", "x".repeat(32)),
            format!("|\n  block{ch}text\n"),
            format!("|\n  {}block{ch}after_swar\n", "x".repeat(32)),
            format!("&anc{ch} 1"),
            format!("!tag{ch} 1"),
        ] {
            let err = scan_err(&bad).unwrap_or_else(|| panic!("expected error for {bad:?}"));
            assert_eq!(err.kind(), crate::error::ErrorKind::Scanner, "{bad:?}");
        }
        // Allowed inside single and double quotes (including past SWAR warmup).
        for good in [
            format!("'quoted{ch}text'"),
            format!("\"quoted{ch}text\""),
            format!("'{}quoted{ch}after_swar'", "x".repeat(32)),
            format!("\"{}quoted{ch}after_swar\"", "x".repeat(32)),
        ] {
            assert!(scan_err(&good).is_none(), "unexpected error for {good:?}");
        }
    }
    // NEL U+0085 is printable everywhere in YAML 1.2.
    assert!(scan_err("plain\u{85}text").is_none());
    assert!(scan_err("a: 1 # comment\u{85}text\n").is_none());
}

#[test]
fn compat_question_stops_name_handles_all_separators_and_unicode_breaks() {
    use super::line::compat_question_stops_name;

    // `?` stays inside the name before EOF, blanks, or flow indicators.
    for keep in [
        None,
        Some(' '),
        Some('\t'),
        Some('\n'),
        Some('\r'),
        Some(','),
        Some('['),
        Some(']'),
        Some('{'),
        Some('}'),
    ] {
        assert!(!compat_question_stops_name(keep, false), "block {keep:?}");
        assert!(!compat_question_stops_name(keep, true), "flow {keep:?}");
    }
    // Outside flow, Unicode line breaks (NEL/LS/PS) keep `?` in the name; inside flow they stop it.
    for unicode_nl in [Some('\u{85}'), Some('\u{2028}'), Some('\u{2029}')] {
        assert!(
            !compat_question_stops_name(unicode_nl, false),
            "block {unicode_nl:?}"
        );
        assert!(
            compat_question_stops_name(unicode_nl, true),
            "flow {unicode_nl:?}"
        );
    }
    // Ordinary non-blank text after `?` stops the compat anchor/alias name in both modes.
    assert!(compat_question_stops_name(Some('a'), false));
    assert!(compat_question_stops_name(Some('a'), true));

    // Verify `Scanner::with_compat` tokenizes trailing `?` anchors/aliases before Unicode line
    // breaks and in flow context cleanly.
    let limits = Limits::default();
    for input in [
        "&a?\n1\n",
        "&a?\u{85}1\n",
        "&a?\u{2028}1\n",
        "&a?\u{2029}1\n",
        "[&a? ]\n",
        "[&a?\u{85}]\n",
        "&? 1\n",
        "*?\n",
    ] {
        let mut scanner = Scanner::with_compat(input, &limits, true).expect(input);
        let mut count = 0_usize;
        while scanner.next_token(&limits).expect(input).is_some() {
            count += 1;
        }
        assert!(count >= 3, "{input:?}: count={count}");
    }
}

const PLAIN_PIECES: &[&str] = &[
    "a", "b", "c", "first", "second", " ", "  ", "\n", "\n\n", "\t", "k: ", "- ", "? ", ": ",
    "!t ", "&a ", " # ", "#",
];

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1024))]

    #[test]
    fn the_plain_scalar_fast_path_agrees_with_the_full_path(
        input in prop::collection::vec(prop::sample::select(PLAIN_PIECES), 0..40)
            .prop_map(|pieces| pieces.concat())
    ) {
        let fast = scan_all(&input, true);
        let full = scan_all(&input, false);
        prop_assert_eq!(fast, full, "input={:?}", input);
    }
}

#[test]
fn incremental_scalar_limit_rejects_quoted_block_and_plain_scalars_with_exact_boundaries() {
    use crate::error::ErrorCode;
    use crate::limits::LimitKind;

    let scan_err = |input: &str, limits: &Limits| -> crate::Error {
        let mut scanner = Scanner::new(input, limits).expect("scanner");
        loop {
            match scanner.next_token(limits) {
                Ok(Some(_)) => {}
                Ok(None) => panic!("expected error for {input:?} under {limits:?}"),
                Err(err) => return *err,
            }
        }
    };

    let scan_ok = |input: &str, limits: &Limits| {
        let mut scanner = Scanner::new(input, limits).expect("scanner");
        while scanner.next_token(limits).expect(input).is_some() {}
    };

    // 1. Double-quoted `\L` expansion followed by trailing spaces before a folded line break:
    //    10 `\L`s (20 raw -> 30 decoded) + 5 spaces (temporarily 35 decoded) + `\n` + `"` =
    //    28 raw bytes, 31 final decoded bytes (spaces trimmed and replaced by one space).
    //    Incremental enforcement must not false-reject at 31 or 32, and must reject at 30.
    let expanded_with_spaces = format!("\"{}     \n\"\n", "\\L".repeat(10));
    let (decoded, _, _) = scalar(&expanded_with_spaces);
    assert_eq!(decoded.len(), 31);
    scan_ok(
        &expanded_with_spaces,
        &Limits::default().with_max_scalar_bytes(31),
    );
    scan_ok(
        &expanded_with_spaces,
        &Limits::default().with_max_scalar_bytes(32),
    );
    let err = scan_err(
        &expanded_with_spaces,
        &Limits::default().with_max_scalar_bytes(30),
    );
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(
        err.limit().map(crate::LimitExceeded::kind),
        Some(LimitKind::ScalarBytes)
    );
    assert_eq!(err.span().map(crate::Span::start), Some(0));

    // Escaped trailing space (`\ `) is protected and never trimmed before `\n`:
    // 3 `\L`s (9 bytes) + `\ ` (1 byte) + ` ` (1 byte) = 11 decoded bytes, 11 raw bytes.
    let protected_space = "\"\\L\\L\\L\\ \n\"\n";
    let (decoded, _, _) = scalar(protected_space);
    assert_eq!(decoded.len(), 11);
    scan_ok(
        protected_space,
        &Limits::default().with_max_scalar_bytes(11),
    );
    let err = scan_err(
        protected_space,
        &Limits::default().with_max_scalar_bytes(10),
    );
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);

    // 2. Single-quoted with `''` escapes and blank-line runs.
    let sq_escaped = "'abc''def'\n"; // 10 raw bytes, 7 decoded bytes.
    scan_ok(sq_escaped, &Limits::default().with_max_scalar_bytes(10));
    let err = scan_err(sq_escaped, &Limits::default().with_max_scalar_bytes(9));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);

    let blank_lines = if cfg!(miri) { 128 } else { 4_096 };
    let sq_blanks = format!("'a{}  b'\n", "\n".repeat(blank_lines));
    let err = scan_err(&sq_blanks, &Limits::default().with_max_scalar_bytes(64));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(err.span().map(crate::Span::start), Some(0));

    // 3. Block scalars: oversized header comment, blank line spaces, content lines, and
    //    leading-blank indentation check (guards removal of duplicate `line_end` scan).
    let pad_len = if cfg!(miri) { 64 } else { 256 };
    let huge_header = format!("k: | # {}\n  a\n", "c".repeat(pad_len));
    let err = scan_err(&huge_header, &Limits::default().with_max_scalar_bytes(32));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(err.span().map(crate::Span::start), Some(3));

    let blank_spaces = format!("k: |\n  a\n{}\n  b\n", " ".repeat(pad_len));
    let err = scan_err(&blank_spaces, &Limits::default().with_max_scalar_bytes(32));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(err.span().map(crate::Span::start), Some(3));

    let explicit_blank_spaces = format!("k: |2\n{}\n  a\n", " ".repeat(pad_len));
    let err = scan_err(
        &explicit_blank_spaces,
        &Limits::default().with_max_scalar_bytes(32),
    );
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(err.span().map(crate::Span::start), Some(3));

    let bad_leading = "k: |\n   \n  a\n";
    let err = scan_err(bad_leading, &Limits::default());
    assert_eq!(err.code(), ErrorCode::InvalidBlockScalarIndentation);

    // 4. Plain scalars: trailing whitespace is trimmed (not false-rejected), while multiline
    //    continuations enforce `max_scalar_bytes` incrementally.
    let padded_plain = format!("a{}\n", " ".repeat(64));
    scan_ok(&padded_plain, &Limits::default().with_max_scalar_bytes(1));
    let multiline_plain = "abc\n  def\n"; // 9 raw bytes (`abc\n  def`), 7 decoded (`abc def`).
    scan_ok(multiline_plain, &Limits::default().with_max_scalar_bytes(9));
    let err = scan_err(multiline_plain, &Limits::default().with_max_scalar_bytes(8));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);

    // 5. Simultaneous `max_events` and `max_scalar_bytes` breach on the same scalar preserves
    //    `Scanner::make` precedence (`LimitKind::Events` wins over `LimitKind::ScalarBytes`).
    let both = Limits::default()
        .with_max_events(0)
        .with_max_scalar_bytes(4);
    for input in [
        "'aaaa''bbbb'\n",
        "\"\\L\\L\\L\\L\"\n",
        "|\n  abcdef\n",
        "aaaa\n  bbbb\n",
    ] {
        let err = scan_err(input, &both);
        assert_eq!(err.code(), ErrorCode::EventCountLimit, "{input:?}");
        assert_eq!(
            err.limit().map(crate::LimitExceeded::kind),
            Some(LimitKind::Events),
            "{input:?}"
        );
    }
}

#[test]
fn incremental_scalar_limit_edge_cases_cover_zero_folded_escaped_break_and_plain_blanks() {
    use crate::ErrorCode;

    let scan_ok = |input: &str, limits: &Limits| {
        let mut scanner = Scanner::new(input, limits).expect("scanner init");
        while scanner
            .next_token(limits)
            .unwrap_or_else(|err| panic!("unexpected error on {input:?}: {err}"))
            .is_some()
        {}
    };
    let scan_err = |input: &str, limits: &Limits| -> Box<crate::Error> {
        let mut scanner = Scanner::new(input, limits).expect("scanner init");
        loop {
            match scanner.next_token(limits) {
                Ok(Some(_)) => {}
                Ok(None) => panic!("expected scalar limit error on {input:?}"),
                Err(err) => return err,
            }
        }
    };

    // 1. `max_scalar_bytes = 0` rejects any non-empty scalar immediately.
    let zero = Limits::default().with_max_scalar_bytes(0);
    for input in ["\"\"\n", "''\n", "a\n", "|\n  a\n", ">\n  a\n"] {
        let err = scan_err(input, &zero);
        assert_eq!(err.code(), ErrorCode::ScalarSizeLimit, "{input:?}");
    }

    // 2. Folded block scalar `>` exact raw-byte boundary (`>\n  ab\n  cd\n` = 12 raw bytes).
    let folded = ">\n  ab\n  cd\n";
    let (decoded, _, _) = scalar(folded);
    assert_eq!(decoded, "ab cd\n");
    scan_ok(folded, &Limits::default().with_max_scalar_bytes(12));
    let err = scan_err(folded, &Limits::default().with_max_scalar_bytes(11));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);

    // 3. Double-quoted `\L` + trailing spaces + escaped line break `\\\n`: trailing spaces before
    //    `\` are NOT trimmed (escaped break keeps preceding spaces), while `\L` expands 2 -> 3.
    let escaped_break = "\"\\L\\L\\L   \\\n  x\"\n";
    let (decoded, _, _) = scalar(escaped_break);
    assert_eq!(decoded.len(), 13); // 9 (`\L`*3) + 3 spaces + 1 (`x`)
    let raw_len = escaped_break.len() - 1; // excluding trailing '\n'
    let exact = decoded.len().max(raw_len);
    scan_ok(
        escaped_break,
        &Limits::default().with_max_scalar_bytes(exact),
    );
    let err = scan_err(
        escaped_break,
        &Limits::default().with_max_scalar_bytes(exact - 1),
    );
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);

    // 4. Multiline plain scalar with a huge blank-line run stops incrementally before allocating.
    let plain_blanks = format!("a{}  b\n", "\n".repeat(4_096));
    let err = scan_err(&plain_blanks, &Limits::default().with_max_scalar_bytes(64));
    assert_eq!(err.code(), ErrorCode::ScalarSizeLimit);
    assert_eq!(err.span().map(crate::Span::start), Some(0));
}