instruction-md 0.3.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
//! Metadata and structured bodies (§3.3): YAML 1.2.2's Core Schema restricted to JSON-compatible values. Duplicate
//! keys, non-string keys, custom tags, anchors and aliases, non-finite numbers and a second document are errors;
//! dates stay strings (the Core Schema infers no timestamps) and no constructor runs. JSON bodies are RFC 8259 JSON
//! without duplicate keys; CSV bodies RFC 4180 with a header.
//!
//! The YAML syntax is read by a hand-written parser (block and flow collections, plain, quoted and block scalars,
//! properties, comments, directives and document markers); the problems are then found in the reference's order — a
//! second document, the syntax, a repeated key, then anchors, aliases, tags, keys and non-finite numbers in document
//! order, then a core tag that does not resolve — with the reference's messages. A syntax error's wording is this
//! reader's own.

use std::collections::HashMap;

use serde_json::{Map, Value};

use crate::js::{js_trim, num};
use crate::pattern::Pattern;
use crate::types::KeyOrder;
use std::sync::LazyLock;

/// A YAML (or JSON, or CSV) body that is not a value this edition accepts: the reason.
pub type LoadError = String;

const YAML_TAG: &str = "tag:yaml.org,2002:";
const MAX_DEPTH: usize = 256;

pub(crate) const SECOND_DOCUMENT: &str = "a second YAML document (a `---` line) is not allowed here";

struct Core {
    null: Pattern,
    boolean: Pattern,
    int_oct: Pattern,
    int: Pattern,
    int_hex: Pattern,
    float_nan: Pattern,
    float_exp: Pattern,
    float: Pattern,
}

// The Core Schema's scalars, in the order the reference tries them.
static CORE: LazyLock<Core> = LazyLock::new(|| Core {
    null: Pattern::must(r"^(?:~|[Nn]ull|NULL)?$"),
    boolean: Pattern::must(r"^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$"),
    int_oct: Pattern::must(r"^0o[0-7]+$"),
    int: Pattern::must(r"^[-+]?[0-9]+$"),
    int_hex: Pattern::must(r"^0x[0-9a-fA-F]+$"),
    float_nan: Pattern::must(r"^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$"),
    float_exp: Pattern::must(r"^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$"),
    float: Pattern::must(r"^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$"),
});

#[derive(Clone, Copy, Debug, PartialEq)]
enum Style {
    Plain,
    Quoted,
    Block,
}

#[derive(Debug)]
enum Kind {
    Scalar(String, Style),
    Seq(Vec<YNode>),
    Map(Vec<(YNode, YNode)>),
    Alias,
}

#[derive(Debug)]
struct YNode {
    kind: Kind,
    /// the tag as written, resolved to its long form
    tag: Option<String>,
    anchor: bool,
}

impl YNode {
    fn scalar(s: String, style: Style) -> YNode {
        YNode { kind: Kind::Scalar(s, style), tag: None, anchor: false }
    }
    fn empty() -> YNode {
        YNode::scalar(String::new(), Style::Plain)
    }
}

/// A scalar's Core Schema value.
#[derive(Clone, Debug)]
enum Scalar {
    Null,
    Bool(bool),
    Num(f64),
    Str(String),
}

impl Scalar {
    fn same(&self, other: &Scalar) -> bool {
        match (self, other) {
            (Scalar::Null, Scalar::Null) => true,
            (Scalar::Bool(a), Scalar::Bool(b)) => a == b,
            (Scalar::Num(a), Scalar::Num(b)) => a == b,
            (Scalar::Str(a), Scalar::Str(b)) => a == b,
            _ => false,
        }
    }
}

/// Reads one YAML document (an empty stream is null), with the order its mappings were written in.
pub(crate) fn load_yaml(text: &str) -> Result<(Value, KeyOrder), LoadError> {
    if yaml_documents(text) > 1 {
        return Err(SECOND_DOCUMENT.into());
    }
    let norm = text.strip_prefix('\u{feff}').unwrap_or(text).replace("\r\n", "\n").replace('\r', "\n");
    let mut p = Parser::new(&norm);
    let Some(top) = p.stream()? else {
        return Ok((Value::Null, KeyOrder::default()));
    };
    if duplicate_key(&top) {
        return Err("Map keys must be unique".into());
    }
    if let Some(problem) = yaml_problem(&top) {
        return Err(problem);
    }
    if let Some(tag) = unresolved_tag(&top) {
        return Err(format!("Unresolved tag: {tag}"));
    }
    Ok((yaml_value(&top), yaml_key_order(&top)))
}

/// Parses YAML text into a JSON value (the Core Schema, JSON-compatible values only), as metadata is read.
pub fn parse_yaml(text: &str) -> Result<Value, LoadError> {
    load_yaml(text).map(|(v, _)| v)
}

/// Counts a YAML stream's documents as the reference's YAML library splits them, valid or not (so that a second
/// document is reported before a syntax error, as there): a `---` line starts one; a `...` line ends one, or stands
/// for an empty one; any other line outside a document starts one, except a blank line, a comment or a directive.
fn yaml_documents(text: &str) -> usize {
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let mut n = 0;
    let mut open = false;
    for line in text.split_inclusive('\n') {
        let content = line.trim_end_matches(['\r', '\n']);
        if document_marker(content, "---") {
            n += 1;
            open = true;
        } else if document_marker(content, "...") {
            if !open {
                n += 1;
            }
            open = false;
        } else if open || content.starts_with('%') {
        } else {
            let t = content.trim_start_matches([' ', '\t']);
            if !t.is_empty() && !t.starts_with('#') {
                n += 1;
                open = true;
            }
        }
    }
    n
}

/// Is the line the marker followed by nothing or by whitespace?
fn document_marker(line: &str, marker: &str) -> bool {
    line.starts_with(marker) && matches!(line.as_bytes().get(marker.len()), None | Some(b' ') | Some(b'\t'))
}

// ---- the syntax ----

struct Parser {
    c: Vec<char>,
    col: Vec<u32>,
    line: Vec<u32>,
    i: usize,
    handles: HashMap<String, String>,
    depth: usize,
    /// the node about to be read is a mapping value on its key's line
    inline_value: bool,
    /// a flow collection's or a quoted scalar's continuation lines stand past this column (the block collection it
    /// is in), as YAML 1.2 has it; -1 at the document's top
    min_col: i64,
}

type R<T> = Result<T, LoadError>;

fn blank_char(c: char) -> bool {
    c == ' ' || c == '\t'
}

fn flow_indicator(c: char) -> bool {
    matches!(c, ',' | '[' | ']' | '{' | '}')
}

impl Parser {
    fn new(text: &str) -> Parser {
        let c: Vec<char> = text.chars().collect();
        let mut col = Vec::with_capacity(c.len() + 1);
        let mut line = Vec::with_capacity(c.len() + 1);
        let (mut x, mut y) = (0u32, 1u32);
        for &ch in &c {
            col.push(x);
            line.push(y);
            if ch == '\n' {
                x = 0;
                y += 1;
            } else {
                x += 1;
            }
        }
        col.push(x);
        line.push(y);
        let mut handles = HashMap::new();
        handles.insert("!".to_string(), "!".to_string());
        handles.insert("!!".to_string(), YAML_TAG.to_string());
        Parser { c, col, line, i: 0, handles, depth: 0, inline_value: false, min_col: -1 }
    }

    fn at(&self, k: usize) -> char {
        self.c.get(self.i + k).copied().unwrap_or('\0')
    }

    fn eof(&self) -> bool {
        self.i >= self.c.len()
    }

    fn col_of(&self, i: usize) -> i64 {
        self.col.get(i).copied().unwrap_or(0) as i64
    }

    fn col(&self) -> i64 {
        self.col_of(self.i)
    }

    fn err<T>(&self, what: &str) -> R<T> {
        let line = self.line.get(self.i).copied().unwrap_or(0);
        Err(format!("{what} at line {line}, column {}", self.col() + 1))
    }

    /// Is the character at k a blank, a line break or the end?
    fn blank_or_end(&self, k: usize) -> bool {
        let c = self.at(k);
        c == '\0' && self.i + k >= self.c.len() || c == ' ' || c == '\t' || c == '\n'
    }

    fn skip_blanks(&mut self) {
        while !self.eof() && blank_char(self.at(0)) {
            self.i += 1;
        }
    }

    fn skip_comment(&mut self) {
        if self.at(0) == '#' {
            while !self.eof() && self.at(0) != '\n' {
                self.i += 1;
            }
        }
    }

    /// Skips blanks, comments and line breaks; checks no tab indents block content.
    fn skip_space(&mut self, block: bool) -> R<()> {
        loop {
            let line_start = self.col() == 0;
            let from = self.i;
            self.skip_blanks();
            if self.eof() {
                return Ok(());
            }
            match self.at(0) {
                '#' if self.i == from || line_start || blank_char(self.c[self.i - 1]) => self.skip_comment(),
                '\n' => {
                    self.i += 1;
                    continue;
                }
                _ => {
                    if block && line_start && self.c[from..self.i].contains(&'\t') {
                        return self.err("a tab cannot indent block content");
                    }
                    return Ok(());
                }
            }
            if self.at(0) == '\n' {
                self.i += 1;
            }
        }
    }

    /// Is a document marker (`---` or `...` at column 0) at the position?
    fn at_marker(&self) -> bool {
        self.col() == 0
            && (self.at(0) == '-' && self.at(1) == '-' && self.at(2) == '-' || self.at(0) == '.' && self.at(1) == '.' && self.at(2) == '.')
            && self.blank_or_end(3)
    }

    fn stream(&mut self) -> R<Option<YNode>> {
        // directives, then the document
        loop {
            self.skip_space(true)?;
            if self.col() == 0 && self.at(0) == '%' {
                self.directive()?;
                continue;
            }
            break;
        }
        let mut started = false;
        if self.at_marker() && self.at(0) == '-' {
            self.i += 3;
            started = true;
        }
        let node = if self.at_marker() || self.eof() {
            if started { Some(YNode::empty()) } else { None }
        } else {
            let save = self.i;
            self.skip_space(true)?;
            if self.eof() || self.at_marker() {
                if started { Some(YNode::empty()) } else { None }
            } else {
                self.i = save;
                Some(self.block_node(-1, false)?)
            }
        };
        self.skip_space(true)?;
        if self.at_marker() && self.at(0) == '.' {
            self.i += 3;
            loop {
                self.skip_space(true)?;
                if self.col() == 0 && self.at(0) == '%' {
                    self.directive()?;
                    continue;
                }
                break;
            }
        }
        if !self.eof() {
            return self.err("did not find the end of the document");
        }
        Ok(node)
    }

    fn directive(&mut self) -> R<()> {
        let start = self.i;
        while !self.eof() && self.at(0) != '\n' {
            self.i += 1;
        }
        let line: String = self.c[start..self.i].iter().collect();
        let line = line.split(" #").next().unwrap_or("").to_string();
        let parts: Vec<&str> = line.split([' ', '\t']).filter(|s| !s.is_empty()).collect();
        if parts.first() == Some(&"%TAG") {
            if parts.len() != 3 || !parts[1].starts_with('!') || !parts[1].ends_with('!') {
                return self.err("a %TAG directive names a handle and a prefix");
            }
            self.handles.insert(parts[1].to_string(), parts[2].to_string());
        }
        Ok(())
    }

    /// A node's properties (a tag, an anchor, in either order): the tag, whether it had an anchor, and whether any
    /// were written.
    fn properties(&mut self, flow: bool) -> R<(Option<String>, bool, bool)> {
        let mut tag = None;
        let mut anchor = false;
        let mut any = false;
        loop {
            match self.at(0) {
                '!' if tag.is_none() => {
                    tag = Some(self.tag(flow)?);
                    any = true;
                }
                '&' if !anchor => {
                    self.i += 1;
                    if self.name(flow) == 0 {
                        return self.err("an anchor needs a name");
                    }
                    anchor = true;
                    any = true;
                }
                _ => return Ok((tag, anchor, any)),
            }
            self.skip_blanks();
        }
    }

    /// An anchor's or an alias's name: its length.
    fn name(&mut self, _flow: bool) -> usize {
        let start = self.i;
        while !self.eof() && !self.blank_or_end(0) && !flow_indicator(self.at(0)) {
            self.i += 1;
        }
        self.i - start
    }

    fn tag(&mut self, flow: bool) -> R<String> {
        let start = self.i;
        self.i += 1;
        if self.at(0) == '<' {
            let from = self.i + 1;
            while !self.eof() && self.at(0) != '>' && self.at(0) != '\n' {
                self.i += 1;
            }
            if self.at(0) != '>' {
                return self.err("a verbatim tag is not closed");
            }
            let s: String = self.c[from..self.i].iter().collect();
            self.i += 1;
            return Ok(s);
        }
        while !self.eof() && !self.blank_or_end(0) && !(flow && flow_indicator(self.at(0))) {
            self.i += 1;
        }
        let written: String = self.c[start..self.i].iter().collect();
        if written == "!" {
            return Ok("!".into());
        }
        // a handle (!, !!, !name!) and a suffix
        let rest = &written[1..];
        let (handle, suffix) = match rest.find('!') {
            Some(k) => (format!("!{}", &rest[..=k]), &rest[k + 1..]),
            None => ("!".to_string(), rest),
        };
        match self.handles.get(&handle) {
            Some(prefix) => Ok(format!("{prefix}{}", percent_decode(suffix))),
            None => self.err(&format!("the tag handle {handle} is not declared")),
        }
    }

    fn enter(&mut self) -> R<()> {
        self.depth += 1;
        if self.depth > MAX_DEPTH {
            return self.err("the YAML is nested too deeply");
        }
        Ok(())
    }

    /// A block node whose parent is indented n; a `-` entry at column n is a sequence when seq_at_n (a mapping's
    /// value). Starts anywhere before the node's content.
    fn block_node(&mut self, n: i64, seq_at_n: bool) -> R<YNode> {
        self.enter()?;
        let r = self.block_node_inner(n, seq_at_n);
        self.depth -= 1;
        r
    }

    fn block_node_inner(&mut self, n: i64, seq_at_n: bool) -> R<YNode> {
        let inline = std::mem::take(&mut self.inline_value);
        let line_before = self.line.get(self.i).copied();
        self.skip_space(true)?;
        let crossed = self.line.get(self.i).copied() != line_before;
        if self.eof() || self.at_marker() || crossed && (self.col() < n || self.col() == n && !(seq_at_n && self.seq_entry())) {
            return Ok(YNode::empty());
        }
        if !crossed && self.col() <= n {
            return Ok(YNode::empty());
        }
        let props_at = self.i;
        let (tag, anchor, any) = self.properties(false)?;
        if any {
            // properties then a line break: they belong to the node on the next lines; then content on the same
            // line: to the key it starts, or to the node itself
            self.skip_blanks();
            if self.at(0) == '#' || self.at(0) == '\n' || self.eof() {
                self.skip_comment();
                let save = self.i;
                self.skip_space(true)?;
                if self.eof() || self.at_marker() || self.col() < n || self.col() == n && !(seq_at_n && self.seq_entry()) {
                    self.i = save;
                    return Ok(YNode { kind: Kind::Scalar(String::new(), Style::Plain), tag, anchor });
                }
                let mut node = self.block_content(n, seq_at_n)?;
                node.tag = tag;
                node.anchor = anchor;
                return Ok(node);
            }
            if self.implicit_key_ahead() {
                if inline {
                    return self.err("mapping values are not allowed in this context");
                }
                let col = self.col_of(props_at);
                return self.block_mapping(col, Some((tag, anchor)));
            }
            if inline && (self.seq_entry() || self.at(0) == '?' && self.blank_or_end(1)) {
                return self.err("a block collection cannot start on its key's line");
            }
            let mut node = self.block_content(n, seq_at_n)?;
            node.tag = tag;
            node.anchor = anchor;
            return Ok(node);
        }
        if inline && (self.seq_entry() || self.at(0) == '?' && self.blank_or_end(1) || self.implicit_key_ahead()) {
            return self.err("mapping values are not allowed in this context");
        }
        self.block_content(n, seq_at_n)
    }

    /// Is a block sequence entry (`-` then a blank or the end) at the position?
    fn seq_entry(&self) -> bool {
        self.at(0) == '-' && self.blank_or_end(1)
    }

    /// The node at the position (its properties read).
    fn block_content(&mut self, n: i64, _seq_at_n: bool) -> R<YNode> {
        let col = self.col();
        match self.at(0) {
            '-' if self.blank_or_end(1) => return self.block_sequence(col),
            '?' if self.blank_or_end(1) => return self.block_mapping(col, None),
            ':' if self.blank_or_end(1) => return self.block_mapping(col, None),
            '|' | '>' => return self.block_scalar(n),
            _ => {}
        }
        if self.implicit_key_ahead() {
            return self.block_mapping(col, None);
        }
        let outer = std::mem::replace(&mut self.min_col, n);
        let node = match self.at(0) {
            '*' => {
                self.i += 1;
                if self.name(false) == 0 {
                    return self.err("an alias needs a name");
                }
                Ok(YNode { kind: Kind::Alias, tag: None, anchor: false })
            }
            '[' | '{' => self.flow_node(),
            '"' => self.double_quoted().map(|s| YNode::scalar(s, Style::Quoted)),
            '\'' => self.single_quoted().map(|s| YNode::scalar(s, Style::Quoted)),
            _ => self.plain(n, false).map(|s| YNode::scalar(s, Style::Plain)),
        };
        self.min_col = outer;
        let node = node?;
        self.end_of_line()?;
        Ok(node)
    }

    /// Nothing but blanks and a comment may follow a node on its line.
    fn end_of_line(&mut self) -> R<()> {
        self.skip_blanks();
        if self.at(0) == '#' {
            self.skip_comment();
        }
        if !self.eof() && self.at(0) != '\n' {
            if self.at(0) == ':' {
                return self.err("mapping values are not allowed in this context");
            }
            return self.err("did not find the expected end of the line");
        }
        Ok(())
    }

    /// Does an implicit key (a scalar, a flow collection or an alias on this line, then `:` and a blank) start here?
    fn implicit_key_ahead(&self) -> bool {
        let mut k = self.i;
        let at = |k: usize| self.c.get(k).copied().unwrap_or('\0');
        let end_or_blank = |k: usize| k >= self.c.len() || matches!(self.c[k], ' ' | '\t' | '\n');
        match at(k) {
            '"' | '\'' => {
                let q = at(k);
                k += 1;
                while k < self.c.len() && self.c[k] != '\n' {
                    if q == '"' && self.c[k] == '\\' {
                        k += 2;
                        continue;
                    }
                    if self.c[k] == q {
                        if q == '\'' && at(k + 1) == '\'' {
                            k += 2;
                            continue;
                        }
                        break;
                    }
                    k += 1;
                }
                if at(k) != q {
                    return false;
                }
                k += 1;
            }
            '[' | '{' => {
                let mut depth = 0i64;
                while k < self.c.len() && self.c[k] != '\n' {
                    match self.c[k] {
                        '[' | '{' => depth += 1,
                        ']' | '}' => {
                            depth -= 1;
                            if depth == 0 {
                                k += 1;
                                break;
                            }
                        }
                        '"' | '\'' => {
                            let q = self.c[k];
                            k += 1;
                            while k < self.c.len() && self.c[k] != q && self.c[k] != '\n' {
                                k += if q == '"' && self.c[k] == '\\' { 2 } else { 1 };
                            }
                        }
                        _ => {}
                    }
                    k += 1;
                }
                if depth != 0 {
                    return false;
                }
            }
            '*' => {
                k += 1;
                while k < self.c.len() && !end_or_blank(k) && !flow_indicator(self.c[k]) {
                    k += 1;
                }
            }
            c if c == '\0' || c == '\n' || c == '#' => return false,
            '-' | '?' | ':' if end_or_blank(k + 1) => return false,
            _ => {
                // a plain key: until `: `, ` #` or the end of the line
                while k < self.c.len() && self.c[k] != '\n' {
                    if self.c[k] == ':' && end_or_blank(k + 1) {
                        return true;
                    }
                    if self.c[k] == '#' && k > 0 && blank_char(self.c[k - 1]) {
                        return false;
                    }
                    k += 1;
                }
                return false;
            }
        }
        while k < self.c.len() && blank_char(self.c[k]) {
            k += 1;
        }
        at(k) == ':' && end_or_blank(k + 1)
    }

    /// A block mapping whose entries stand at column m; `first`: properties already read for its first key.
    fn block_mapping(&mut self, m: i64, mut first: Option<(Option<String>, bool)>) -> R<YNode> {
        self.enter()?;
        let mut pairs = Vec::new();
        loop {
            let key = if self.at(0) == '?' && self.blank_or_end(1) {
                self.i += 1;
                let k = self.block_node(m, false)?;
                self.skip_space(true)?;
                if !(self.col() == m && self.at(0) == ':' && self.blank_or_end(1)) {
                    pairs.push((k, YNode::empty()));
                    if self.next_entry(m)? {
                        continue;
                    }
                    break;
                }
                k
            } else if self.at(0) == ':' && self.blank_or_end(1) {
                YNode::empty()
            } else {
                let (tag, anchor) = match first.take() {
                    Some(p) => p,
                    None => {
                        let (t, a, _) = self.properties(false)?;
                        (t, a)
                    }
                };
                let mut k = match self.at(0) {
                    '"' => YNode::scalar(self.double_quoted()?, Style::Quoted),
                    '\'' => YNode::scalar(self.single_quoted()?, Style::Quoted),
                    '[' | '{' => self.flow_node()?,
                    '*' => {
                        self.i += 1;
                        self.name(false);
                        YNode { kind: Kind::Alias, tag: None, anchor: false }
                    }
                    _ => YNode::scalar(self.plain_key()?, Style::Plain),
                };
                k.tag = tag.or(k.tag);
                k.anchor = anchor || k.anchor;
                self.skip_blanks();
                if !(self.at(0) == ':' && self.blank_or_end(1)) {
                    return self.err("could not find the expected ':'");
                }
                k
            };
            // the value
            self.i += 1;
            self.skip_blanks();
            let value = if self.at(0) == '#' || self.at(0) == '\n' || self.eof() {
                self.skip_comment();
                self.block_node(m, true)?
            } else {
                // a value on its key's line: a scalar, a flow collection, an alias, a block scalar — never a block
                // collection
                self.inline_value = true;
                self.block_node(m, false)?
            };
            pairs.push((key, value));
            if !self.next_entry(m)? {
                break;
            }
        }
        self.depth -= 1;
        Ok(YNode { kind: Kind::Map(pairs), tag: None, anchor: false })
    }

    /// Moves to the next entry of a mapping at column m: true when there is one.
    fn next_entry(&mut self, m: i64) -> R<bool> {
        let save = self.i;
        self.skip_space(true)?;
        if self.eof() || self.at_marker() || self.col() < m {
            self.i = save;
            return Ok(false);
        }
        if self.col() > m {
            return self.err("bad indentation of a mapping entry");
        }
        if self.seq_entry() {
            return self.err("a sequence entry where a mapping key was expected");
        }
        Ok(true)
    }

    fn block_sequence(&mut self, s: i64) -> R<YNode> {
        self.enter()?;
        let mut items = Vec::new();
        loop {
            self.i += 1; // the -
            self.skip_blanks();
            let item = if self.at(0) == '#' || self.at(0) == '\n' || self.eof() {
                self.skip_comment();
                self.block_node(s, false)?
            } else {
                self.block_node(s, false)?
            };
            items.push(item);
            let save = self.i;
            self.skip_space(true)?;
            if self.eof() || self.at_marker() || self.col() < s {
                self.i = save;
                break;
            }
            if self.col() > s {
                return self.err("bad indentation of a sequence entry");
            }
            if !self.seq_entry() {
                // (the mapping this sequence is a value of goes on)
                self.i = save;
                break;
            }
        }
        self.depth -= 1;
        Ok(YNode { kind: Kind::Seq(items), tag: None, anchor: false })
    }

    /// A plain scalar used as an implicit key: one line, up to `: `.
    fn plain_key(&mut self) -> R<String> {
        if self.at(0) == '@' || self.at(0) == '`' {
            return self.err("a plain scalar cannot start with a reserved character");
        }
        let start = self.i;
        while !self.eof() && self.at(0) != '\n' {
            if self.at(0) == ':' && self.blank_or_end(1) {
                break;
            }
            if self.at(0) == '#' && self.i > start && blank_char(self.c[self.i - 1]) {
                break;
            }
            self.i += 1;
        }
        let s: String = self.c[start..self.i].iter().collect();
        Ok(s.trim_end_matches([' ', '\t']).to_string())
    }

    /// A plain scalar, in block context (its continuation lines indented past n) or in flow context.
    fn plain(&mut self, n: i64, flow: bool) -> R<String> {
        let c0 = self.at(0);
        if matches!(c0, '@' | '`' | '%' | '|' | '>' | '!' | '&' | '#' | '\'' | '"')
            || flow_indicator(c0)
            || matches!(c0, '-' | '?' | ':') && (self.blank_or_end(1) || flow && flow_indicator(self.at(1)))
        {
            return self.err("found a character that cannot start a plain scalar");
        }
        let mut out = String::new();
        let mut first = true;
        loop {
            // one line's text
            let start = self.i;
            while !self.eof() && self.at(0) != '\n' {
                let c = self.at(0);
                if c == ':' && (self.blank_or_end(1) || flow && flow_indicator(self.at(1))) {
                    break;
                }
                if c == '#' && self.i > start && blank_char(self.c[self.i - 1]) {
                    break;
                }
                if flow && flow_indicator(c) {
                    break;
                }
                self.i += 1;
            }
            let mut end = self.i;
            while end > start && blank_char(self.c[end - 1]) {
                end -= 1;
            }
            let text: String = self.c[start..end].iter().collect();
            if !first {
                out.push_str(&text);
            } else {
                out = text;
                first = false;
            }
            // a continuation line?
            if self.at(0) != '\n' {
                break;
            }
            let save = self.i;
            let mut breaks = 0;
            let mut k = self.i;
            loop {
                // k at a line break
                k += 1;
                let line_start = k;
                while k < self.c.len() && blank_char(self.c[k]) {
                    k += 1;
                }
                if k < self.c.len() && self.c[k] == '\n' {
                    breaks += 1;
                    continue;
                }
                let indent = (k - line_start) as i64;
                let content = self.c.get(k).copied().unwrap_or('\0');
                let tabbed = self.c[line_start..k].contains(&'\t');
                let lead_spaces = self.c[line_start..k].iter().take_while(|&&c| c == ' ').count() as i64;
                let stop = k >= self.c.len()
                    || content == '#'
                    || lead_spaces == 0 && {
                        let three: String = self.c[line_start..(line_start + 3).min(self.c.len())].iter().collect();
                        (three == "---" || three == "...") && matches!(self.c.get(line_start + 3), None | Some(' ' | '\t' | '\n'))
                    }
                    || !flow && (indent <= n || tabbed && lead_spaces <= n)
                    || flow && lead_spaces <= self.min_col
                    || flow && flow_indicator(content) && content != '[' && content != '{'
                    || content == ':' && matches!(self.c.get(k + 1), None | Some(' ' | '\t' | '\n'));
                if stop {
                    self.i = save;
                    return Ok(out);
                }
                self.i = k;
                break;
            }
            if breaks == 0 {
                out.push(' ');
            } else {
                out.push_str(&"\n".repeat(breaks));
            }
        }
        Ok(out)
    }

    /// Folds the line break at the position in a quoted scalar: a space, or one line feed per empty line.
    fn fold_quoted(&mut self, out: &mut String) -> R<()> {
        while out.ends_with([' ', '\t']) {
            out.pop();
        }
        let mut breaks = 0;
        while self.at(0) == '\n' {
            self.i += 1;
            if self.at_marker() {
                return self.err("a document marker inside a quoted scalar");
            }
            let line_start = self.i;
            while self.at(0) == ' ' {
                self.i += 1;
            }
            if !self.eof() && self.at(0) != '\n' && ((self.i - line_start) as i64) <= self.min_col {
                return self.err("missing the closing quote: a quoted scalar's lines are indented past its block collection");
            }
            self.skip_blanks();
            if self.at(0) == '\n' {
                breaks += 1;
            }
        }
        if breaks == 0 {
            out.push(' ');
        } else {
            out.push_str(&"\n".repeat(breaks));
        }
        Ok(())
    }

    fn single_quoted(&mut self) -> R<String> {
        self.i += 1;
        let mut out = String::new();
        loop {
            if self.eof() {
                return self.err("found the end of the stream inside a single-quoted scalar");
            }
            match self.at(0) {
                '\'' if self.at(1) == '\'' => {
                    out.push('\'');
                    self.i += 2;
                }
                '\'' => {
                    self.i += 1;
                    return Ok(out);
                }
                '\n' => self.fold_quoted(&mut out)?,
                c => {
                    out.push(c);
                    self.i += 1;
                }
            }
        }
    }

    fn double_quoted(&mut self) -> R<String> {
        self.i += 1;
        let mut out = String::new();
        loop {
            if self.eof() {
                return self.err("found the end of the stream inside a double-quoted scalar");
            }
            match self.at(0) {
                '"' => {
                    self.i += 1;
                    return Ok(out);
                }
                '\n' => self.fold_quoted(&mut out)?,
                '\\' => {
                    self.i += 1;
                    let e = self.at(0);
                    self.i += 1;
                    let simple = match e {
                        '0' => Some('\0'),
                        'a' => Some('\u{7}'),
                        'b' => Some('\u{8}'),
                        't' | '\t' => Some('\t'),
                        'n' => Some('\n'),
                        'v' => Some('\u{b}'),
                        'f' => Some('\u{c}'),
                        'r' => Some('\r'),
                        'e' => Some('\u{1b}'),
                        ' ' => Some(' '),
                        '"' => Some('"'),
                        '/' => Some('/'),
                        '\\' => Some('\\'),
                        'N' => Some('\u{85}'),
                        '_' => Some('\u{a0}'),
                        'L' => Some('\u{2028}'),
                        'P' => Some('\u{2029}'),
                        _ => None,
                    };
                    if let Some(c) = simple {
                        out.push(c);
                        continue;
                    }
                    match e {
                        '\n' => {
                            // an escaped line break: the break and the next line's indentation go
                            self.skip_blanks();
                            while self.at(0) == '\n' {
                                out.push('\n');
                                self.i += 1;
                                self.skip_blanks();
                            }
                        }
                        'x' | 'u' | 'U' => {
                            let len = match e {
                                'x' => 2,
                                'u' => 4,
                                _ => 8,
                            };
                            let mut code: u32 = 0;
                            for _ in 0..len {
                                let Some(d) = self.at(0).to_digit(16) else {
                                    return self.err("a malformed escape in a double-quoted scalar");
                                };
                                code = code * 16 + d;
                                self.i += 1;
                            }
                            if (0xd800..0xdc00).contains(&code) && self.at(0) == '\\' && self.at(1) == 'u' {
                                // a surrogate pair, written as two escapes
                                let mut low: u32 = 0;
                                let mut ok = true;
                                for k in 0..4 {
                                    match self.at(2 + k).to_digit(16) {
                                        Some(d) => low = low * 16 + d,
                                        None => ok = false,
                                    }
                                }
                                if ok && (0xdc00..0xe000).contains(&low) {
                                    self.i += 6;
                                    code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00);
                                }
                            }
                            out.push(char::from_u32(code).unwrap_or('\u{fffd}'));
                        }
                        _ => return self.err("an unknown escape in a double-quoted scalar"),
                    }
                }
                c => {
                    out.push(c);
                    self.i += 1;
                }
            }
        }
    }

    /// A literal (`|`) or folded (`>`) block scalar whose parent is indented n.
    fn block_scalar(&mut self, n: i64) -> R<YNode> {
        let folded = self.at(0) == '>';
        self.i += 1;
        let mut chomp = 0i8; // -1 strip, 0 clip, 1 keep
        let mut increment: Option<i64> = None;
        for _ in 0..2 {
            match self.at(0) {
                '+' | '-' if chomp == 0 => {
                    chomp = if self.at(0) == '+' { 1 } else { -1 };
                    self.i += 1;
                }
                d @ '1'..='9' if increment.is_none() => {
                    increment = Some(d as i64 - '0' as i64);
                    self.i += 1;
                }
                _ => {}
            }
        }
        self.skip_blanks();
        if self.at(0) == '#' && blank_char(self.c[self.i - 1]) {
            self.skip_comment();
        }
        if !self.eof() && self.at(0) != '\n' {
            return self.err("did not find the expected comment or line break after a block scalar's header");
        }
        // the content's indentation
        let base = n.max(-1);
        let mut indent = match increment {
            Some(k) => base.max(0) + k - if base < 0 { 1 } else { 0 },
            None => -1,
        };
        let mut out = String::new();
        let mut leading_break = String::new();
        let mut trailing_breaks = String::new();
        let mut leading_blank = false;
        if self.at(0) == '\n' {
            self.i += 1;
        } else {
            // the end of the stream right after the header
            return Ok(YNode::scalar(String::new(), Style::Block));
        }
        // leading empty lines, and the indentation detected
        if indent < 0 {
            let mut max_seen = 0i64;
            let mut k = self.i;
            loop {
                let start = k;
                while k < self.c.len() && self.c[k] == ' ' {
                    k += 1;
                }
                let spaces = (k - start) as i64;
                if k < self.c.len() && self.c[k] == '\n' {
                    max_seen = max_seen.max(spaces);
                    k += 1;
                    continue;
                }
                indent = if k >= self.c.len() { max_seen.max(base + 1) } else { spaces.max(max_seen) };
                if indent <= base {
                    indent = base + 1;
                }
                break;
            }
            if indent < 1 && base >= 0 {
                indent = 1;
            }
            if indent < 0 {
                indent = 0;
            }
        }
        // the breaks before the first line
        self.block_breaks(indent, &mut trailing_breaks);
        while self.col() == indent && !self.eof() && !(indent == 0 && self.at_marker()) && self.at(0) != '\n' {
            let trailing_blank = blank_char(self.at(0));
            if folded && leading_break == "\n" && !leading_blank && !trailing_blank {
                if trailing_breaks.is_empty() {
                    out.push(' ');
                }
                leading_break.clear();
            }
            out.push_str(&leading_break);
            out.push_str(&trailing_breaks);
            leading_break.clear();
            trailing_breaks.clear();
            leading_blank = blank_char(self.at(0));
            while !self.eof() && self.at(0) != '\n' {
                out.push(self.at(0));
                self.i += 1;
            }
            if self.eof() {
                break;
            }
            self.i += 1;
            leading_break.push('\n');
            self.block_breaks(indent, &mut trailing_breaks);
        }
        if chomp != -1 {
            out.push_str(&leading_break);
        }
        if chomp == 1 {
            out.push_str(&trailing_breaks);
        }
        Ok(YNode::scalar(out, Style::Block))
    }

    /// Eats a block scalar's indentation and empty lines, each a break.
    fn block_breaks(&mut self, indent: i64, breaks: &mut String) {
        loop {
            while self.col() < indent && self.at(0) == ' ' {
                self.i += 1;
            }
            if self.at(0) == '\n' && !self.eof() {
                breaks.push('\n');
                self.i += 1;
                continue;
            }
            // a line of more spaces than the indentation, and nothing else, is still an empty line when it ends
            if self.col() >= indent {
                let mut k = self.i;
                while k < self.c.len() && blank_char(self.c[k]) {
                    k += 1;
                }
                if k < self.c.len() && self.c[k] == '\n' && self.col() < indent {
                    self.i = k;
                    continue;
                }
            }
            return;
        }
    }

    fn skip_flow_space(&mut self) -> R<()> {
        loop {
            self.skip_blanks();
            match self.at(0) {
                '#' if self.i == 0 || blank_char(self.c[self.i - 1]) || self.col() == 0 => self.skip_comment(),
                '\n' if !self.eof() => {
                    self.i += 1;
                    if self.at_marker() {
                        return self.err("a document marker inside a flow collection");
                    }
                    let line_start = self.i;
                    while self.at(0) == ' ' {
                        self.i += 1;
                    }
                    let col = (self.i - line_start) as i64;
                    let c = self.at(0);
                    if !self.eof()
                        && !matches!(c, '\n' | '#' | '\t')
                        && (col < self.min_col || col == self.min_col && !matches!(c, ']' | '}'))
                    {
                        return self.err("a flow collection in a block collection must be indented past it");
                    }
                }
                _ => return Ok(()),
            }
        }
    }

    /// A flow node: a collection, a quoted or plain scalar, an alias.
    fn flow_node(&mut self) -> R<YNode> {
        self.enter()?;
        let r = self.flow_node_inner();
        self.depth -= 1;
        r
    }

    fn flow_node_inner(&mut self) -> R<YNode> {
        let (tag, anchor, _) = self.properties(true)?;
        self.skip_flow_space()?;
        let mut node = match self.at(0) {
            '[' => self.flow_sequence()?,
            '{' => self.flow_mapping()?,
            '"' => YNode::scalar(self.double_quoted()?, Style::Quoted),
            '\'' => YNode::scalar(self.single_quoted()?, Style::Quoted),
            '*' => {
                self.i += 1;
                if self.name(true) == 0 {
                    return self.err("an alias needs a name");
                }
                YNode { kind: Kind::Alias, tag: None, anchor: false }
            }
            ',' | ']' | '}' | ':' if !(self.at(0) == ':' && !self.blank_or_end(1) && !flow_indicator(self.at(1))) => YNode::empty(),
            _ if self.eof() => return self.err("found the end of the stream inside a flow collection"),
            _ => YNode::scalar(self.plain(-1, true)?, Style::Plain),
        };
        node.tag = tag.or(node.tag);
        node.anchor = anchor || node.anchor;
        Ok(node)
    }

    /// After a flow key: a `:` value indicator (adjacent after a quoted key or a collection)? An implicit key stands
    /// on one line.
    fn flow_colon(&self, adjacent: bool, key_line: u32) -> R<bool> {
        if self.at(0) != ':' {
            return Ok(false);
        }
        // (after a plain key, `:` is the indicator when a blank or a flow indicator follows it: `{a:[b]}` is a: [b])
        if !adjacent && !(self.blank_or_end(1) || flow_indicator(self.at(1))) {
            return Ok(false);
        }
        if self.line_here() != key_line {
            return self.err("an implicit key stands on one line: did not find expected ',' or '}'");
        }
        Ok(true)
    }

    fn line_here(&self) -> u32 {
        self.line.get(self.i).copied().unwrap_or(0)
    }

    fn flow_sequence(&mut self) -> R<YNode> {
        self.i += 1;
        let mut items = Vec::new();
        loop {
            self.skip_flow_space()?;
            if self.eof() {
                return self.err("found the end of the stream inside a flow sequence");
            }
            if self.at(0) == ']' {
                self.i += 1;
                break;
            }
            let explicit = self.at(0) == '?' && self.blank_or_end(1);
            if explicit {
                self.i += 1;
                self.skip_flow_space()?;
            }
            if self.at(0) == ',' {
                return self.err("did not find expected node content");
            }
            let adjacent = matches!(self.at(0), '"' | '\'' | '[' | '{');
            let key_line = self.line_here();
            let item = self.flow_node()?;
            self.skip_flow_space()?;
            let item = if self.flow_colon(adjacent, if explicit { self.line_here() } else { key_line })? {
                self.i += 1;
                self.skip_flow_space()?;
                let value = if matches!(self.at(0), ',' | ']') { YNode::empty() } else { self.flow_node()? };
                YNode { kind: Kind::Map(vec![(item, value)]), tag: None, anchor: false }
            } else if explicit {
                YNode { kind: Kind::Map(vec![(item, YNode::empty())]), tag: None, anchor: false }
            } else {
                item
            };
            items.push(item);
            self.skip_flow_space()?;
            match self.at(0) {
                ',' => self.i += 1,
                ']' => {}
                _ => return self.err("did not find the expected ',' or ']'"),
            }
        }
        Ok(YNode { kind: Kind::Seq(items), tag: None, anchor: false })
    }

    fn flow_mapping(&mut self) -> R<YNode> {
        self.i += 1;
        let mut pairs = Vec::new();
        loop {
            self.skip_flow_space()?;
            if self.eof() {
                return self.err("found the end of the stream inside a flow mapping");
            }
            if self.at(0) == '}' {
                self.i += 1;
                break;
            }
            if self.at(0) == ',' {
                return self.err("did not find expected node content");
            }
            let explicit = self.at(0) == '?' && self.blank_or_end(1);
            if explicit {
                self.i += 1;
                self.skip_flow_space()?;
            }
            let adjacent = matches!(self.at(0), '"' | '\'' | '[' | '{');
            let key_line = self.line_here();
            let key =
                if self.at(0) == ':' && (self.blank_or_end(1) || flow_indicator(self.at(1))) { YNode::empty() } else { self.flow_node()? };
            self.skip_flow_space()?;
            let value = if self.flow_colon(adjacent, if explicit { self.line_here() } else { key_line })? {
                self.i += 1;
                self.skip_flow_space()?;
                if matches!(self.at(0), ',' | '}') { YNode::empty() } else { self.flow_node()? }
            } else {
                YNode::empty()
            };
            pairs.push((key, value));
            self.skip_flow_space()?;
            match self.at(0) {
                ',' => self.i += 1,
                '}' => {}
                _ => return self.err("did not find the expected ',' or '}'"),
            }
        }
        Ok(YNode { kind: Kind::Map(pairs), tag: None, anchor: false })
    }
}

fn percent_decode(s: &str) -> String {
    if !s.contains('%') {
        return s.to_string();
    }
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%'
            && i + 2 < b.len()
            && let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16))
        {
            out.push((h * 16 + l) as u8);
            i += 3;
            continue;
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8(out).unwrap_or_else(|_| s.to_string())
}

// ---- the Core Schema and the checks ----

/// The tag without the Core Schema's prefix (`str`, `int`), or as written.
fn short_tag(tag: &str) -> &str {
    tag.strip_prefix(YAML_TAG).unwrap_or(tag)
}

/// One of the Core Schema's (and JSON's) tags.
fn core_tag(tag: &str) -> bool {
    matches!(tag, "str" | "int" | "float" | "bool" | "null" | "seq" | "map")
}

/// A scalar node's Core Schema value; `None` for an explicit core tag its text does not fit (and a node that is no
/// scalar).
fn scalar(n: &YNode) -> (Scalar, bool) {
    let Kind::Scalar(s, style) = &n.kind else {
        return (Scalar::Null, false);
    };
    let tag = match &n.tag {
        Some(t) if t == "!" => return (Scalar::Str(s.clone()), true),
        Some(t) => short_tag(t).to_string(),
        None if *style != Style::Plain => return (Scalar::Str(s.clone()), true),
        None => String::new(),
    };
    let fits = |t: &str| tag.is_empty() || tag == t;
    let core = &*CORE;
    if tag == "str" {
        return (Scalar::Str(s.clone()), true);
    }
    if fits("null") && core.null.is_match(s) {
        return (Scalar::Null, true);
    }
    if fits("bool") && core.boolean.is_match(s) {
        return (Scalar::Bool(s.starts_with(['t', 'T'])), true);
    }
    if fits("int") && core.int_oct.is_match(s) {
        return (Scalar::Num(integer(&s[2..], 8)), true);
    }
    if fits("int") && core.int.is_match(s) {
        return (Scalar::Num(plus_zero(s.parse().unwrap_or(0.0))), true);
    }
    if fits("int") && core.int_hex.is_match(s) {
        return (Scalar::Num(integer(&s[2..], 16)), true);
    }
    if fits("float") && core.float_nan.is_match(s) {
        if s.to_ascii_lowercase().ends_with("nan") {
            return (Scalar::Num(f64::NAN), true);
        }
        return (Scalar::Num(if s.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }), true);
    }
    if fits("float") && (core.float_exp.is_match(s) || core.float.is_match(s)) {
        // (out of range: ±Infinity, which is refused)
        return (Scalar::Num(plus_zero(s.parse().unwrap_or(0.0))), true);
    }
    (Scalar::Str(s.clone()), tag.is_empty() || !core_tag(&tag))
}

/// -0 reads as 0, as JSON writes it.
fn plus_zero(f: f64) -> f64 {
    if f == 0.0 { 0.0 } else { f }
}

/// Digits in a base, as the nearest f64.
fn integer(digits: &str, base: u32) -> f64 {
    let mut exact: Option<u128> = Some(0);
    let mut approx = 0.0f64;
    for c in digits.chars() {
        let d = c.to_digit(base).unwrap_or(0);
        exact = exact.and_then(|v| v.checked_mul(base as u128)).and_then(|v| v.checked_add(d as u128));
        approx = approx * base as f64 + d as f64;
    }
    match exact {
        Some(v) => v as f64,
        None => approx,
    }
}

/// Does a mapping repeat a key (compared as the scalars resolve)?
fn duplicate_key(n: &YNode) -> bool {
    match &n.kind {
        Kind::Map(pairs) => {
            let mut keys: Vec<Scalar> = Vec::new();
            for (k, _) in pairs {
                if let Kind::Scalar(..) = k.kind {
                    let (v, _) = scalar(k);
                    if keys.iter().any(|seen| seen.same(&v)) {
                        return true;
                    }
                    keys.push(v);
                }
            }
            pairs.iter().any(|(k, v)| duplicate_key(k) || duplicate_key(v))
        }
        Kind::Seq(items) => items.iter().any(duplicate_key),
        _ => false,
    }
}

/// The first node (in document order) that is no JSON value: an alias, an anchor, a tag outside the Core Schema, a
/// non-finite number, a key that is not a string.
fn yaml_problem(n: &YNode) -> Option<String> {
    if let Kind::Alias = n.kind {
        return Some("YAML aliases are not allowed".into());
    }
    if n.anchor {
        return Some("YAML anchors are not allowed".into());
    }
    if let Some(t) = &n.tag
        && t != "!"
        && !core_tag(short_tag(t))
    {
        return Some(format!("the YAML tag {t} is not allowed"));
    }
    if let Kind::Scalar(..) = n.kind
        && let (Scalar::Num(f), _) = scalar(n)
        && !f.is_finite()
    {
        return Some("non-finite numbers are not allowed".into());
    }
    match &n.kind {
        Kind::Map(pairs) => {
            for (k, v) in pairs {
                let is_string = matches!(k.kind, Kind::Scalar(..)) && matches!(scalar(k).0, Scalar::Str(_));
                if !is_string {
                    return Some("mapping keys must be strings".into());
                }
                if let Some(p) = yaml_problem(k).or_else(|| yaml_problem(v)) {
                    return Some(p);
                }
            }
            None
        }
        Kind::Seq(items) => items.iter().find_map(yaml_problem),
        _ => None,
    }
}

/// The first explicit core tag its node does not fit: a scalar's text (`!!int abc`), or a collection of another
/// kind (`!!str [a]`).
fn unresolved_tag(n: &YNode) -> Option<String> {
    let tag = n.tag.as_deref().map(short_tag).unwrap_or("");
    match &n.kind {
        Kind::Scalar(..) => {
            if !scalar(n).1 {
                return n.tag.clone();
            }
        }
        _ if n.tag.is_none() || !core_tag(tag) => {}
        Kind::Seq(_) if tag != "seq" => return n.tag.clone(),
        Kind::Map(_) if tag != "map" => return n.tag.clone(),
        _ => {}
    }
    match &n.kind {
        Kind::Map(pairs) => pairs.iter().find_map(|(k, v)| unresolved_tag(k).or_else(|| unresolved_tag(v))),
        Kind::Seq(items) => items.iter().find_map(unresolved_tag),
        _ => None,
    }
}

fn key_string(k: &YNode) -> String {
    match scalar(k).0 {
        Scalar::Str(s) => s,
        _ => String::new(),
    }
}

fn yaml_value(n: &YNode) -> Value {
    match &n.kind {
        Kind::Map(pairs) => {
            let mut m = Map::new();
            for (k, v) in pairs {
                m.insert(key_string(k), yaml_value(v));
            }
            Value::Object(m)
        }
        Kind::Seq(items) => Value::Array(items.iter().map(yaml_value).collect()),
        Kind::Scalar(..) => match scalar(n).0 {
            Scalar::Null => Value::Null,
            Scalar::Bool(b) => Value::Bool(b),
            Scalar::Num(f) => num(f),
            Scalar::Str(s) => Value::String(s),
        },
        Kind::Alias => Value::Null,
    }
}

fn yaml_key_order(n: &YNode) -> KeyOrder {
    let mut order = KeyOrder::default();
    if let Kind::Map(pairs) = &n.kind {
        for (k, v) in pairs {
            let key = key_string(k);
            order.0.entry(String::new()).or_default().push(key.clone());
            if let Kind::Map(sub) = &v.kind {
                let list = order.0.entry(key).or_default();
                for (sk, _) in sub {
                    list.push(key_string(sk));
                }
            }
        }
    }
    order
}

// ---- JSON and CSV ----

/// Reads RFC 8259 JSON, refusing a repeated key, with the order its objects were written in.
pub(crate) fn load_json(text: &str) -> Result<(Value, KeyOrder), LoadError> {
    let v: Value = match serde_json::from_str(text) {
        Ok(v) => v,
        Err(e) => {
            let message = e.to_string();
            // (a number past what an f64 holds is the reference's Infinity, which canonical JSON cannot write)
            if message.starts_with("number out of range") {
                return Err("non-finite numbers are not allowed".into());
            }
            return Err(js_trim(message.lines().next().unwrap_or("")).to_string());
        }
    };
    let mut scan = JsonScan { b: text.as_bytes(), i: 0, order: KeyOrder::default(), dup: None };
    scan.value("", true, 0);
    if let Some(dup) = scan.dup {
        return Err(format!("the JSON key \"{dup}\" is repeated"));
    }
    Ok((normalize_numbers(v), scan.order))
}

/// Numbers as this crate keeps them (an integral one as an integer).
fn normalize_numbers(v: Value) -> Value {
    match v {
        Value::Number(n) => num(n.as_f64().unwrap_or(0.0)),
        Value::Array(list) => Value::Array(list.into_iter().map(normalize_numbers).collect()),
        Value::Object(m) => Value::Object(m.into_iter().map(|(k, v)| (k, normalize_numbers(v))).collect()),
        v => v,
    }
}

/// Reads valid JSON text for the order of its objects' keys (the top object's, and its objects', as KeyOrder has
/// them) and the first key an object repeats.
struct JsonScan<'a> {
    b: &'a [u8],
    i: usize,
    order: KeyOrder,
    dup: Option<String>,
}

impl JsonScan<'_> {
    fn space(&mut self) {
        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\r' | b'\n') {
            self.i += 1;
        }
    }

    fn string(&mut self) -> String {
        let start = self.i;
        self.i += 1;
        while self.i < self.b.len() && self.b[self.i] != b'"' {
            self.i += if self.b[self.i] == b'\\' { 2 } else { 1 };
        }
        self.i += 1;
        let raw = std::str::from_utf8(&self.b[start..self.i.min(self.b.len())]).unwrap_or("\"\"");
        serde_json::from_str::<String>(raw).unwrap_or_default()
    }

    /// One value; an object's keys are recorded under path when keep. True when a key repeats.
    fn value(&mut self, path: &str, keep: bool, depth: usize) -> bool {
        self.space();
        if self.i >= self.b.len() || depth > 512 {
            return false;
        }
        match self.b[self.i] {
            b'{' => {
                self.i += 1;
                let mut keys: Vec<String> = Vec::new();
                loop {
                    self.space();
                    if self.i >= self.b.len() {
                        return false;
                    }
                    if self.b[self.i] == b'}' {
                        self.i += 1;
                        return false;
                    }
                    if self.b[self.i] == b',' {
                        self.i += 1;
                        continue;
                    }
                    let key = self.string();
                    if keys.contains(&key) {
                        self.dup = Some(key);
                        return true;
                    }
                    keys.push(key.clone());
                    if keep {
                        self.order.0.entry(path.to_string()).or_default().push(key.clone());
                    }
                    self.space();
                    self.i += 1; // the colon
                    let deeper = keep && path.is_empty() && !key.is_empty();
                    if self.value(&key, deeper, depth + 1) {
                        return true;
                    }
                }
            }
            b'[' => {
                self.i += 1;
                loop {
                    self.space();
                    if self.i >= self.b.len() {
                        return false;
                    }
                    match self.b[self.i] {
                        b']' => {
                            self.i += 1;
                            return false;
                        }
                        b',' => self.i += 1,
                        _ => {
                            if self.value("", false, depth + 1) {
                                return true;
                            }
                        }
                    }
                }
            }
            b'"' => {
                self.string();
                false
            }
            _ => {
                while self.i < self.b.len() && !matches!(self.b[self.i], b' ' | b'\t' | b'\r' | b'\n' | b',' | b']' | b'}') {
                    self.i += 1;
                }
                false
            }
        }
    }
}

/// Reads RFC 4180 CSV (§7): a header of unique nonempty names, then records of the same width; cells stay strings.
pub(crate) fn load_csv(text: &str) -> Result<(Vec<String>, Vec<Vec<String>>), LoadError> {
    let src = text.replace("\r\n", "\n").replace('\r', "\n");
    let mut records: Vec<Vec<String>> = Vec::new();
    let mut record: Vec<String> = Vec::new();
    let mut cell = String::new();
    let mut quoted = false;
    let mut chars = src.chars().peekable();
    while let Some(c) = chars.next() {
        if quoted {
            if c == '"' {
                if chars.peek() == Some(&'"') {
                    cell.push('"');
                    chars.next();
                    continue;
                }
                quoted = false;
                continue;
            }
            cell.push(c);
            continue;
        }
        match c {
            '"' => {
                if !cell.is_empty() {
                    return Err(format!("a quote inside an unquoted CSV field (record {})", records.len() + 1));
                }
                quoted = true;
            }
            ',' => record.push(std::mem::take(&mut cell)),
            '\n' => {
                record.push(std::mem::take(&mut cell));
                records.push(std::mem::take(&mut record));
            }
            c => cell.push(c),
        }
    }
    if quoted {
        return Err("an unclosed quoted CSV field".into());
    }
    if !cell.is_empty() || !record.is_empty() {
        record.push(cell);
        records.push(record);
    }
    if records.is_empty() {
        return Err("a CSV body needs a header record".into());
    }
    let header = records.remove(0);
    if header.iter().any(String::is_empty) {
        return Err("CSV header names must be nonempty".into());
    }
    let mut names: Vec<&String> = header.iter().collect();
    names.sort();
    names.dedup();
    if names.len() != header.len() {
        return Err("CSV header names must be unique".into());
    }
    for (i, r) in records.iter().enumerate() {
        if r.len() != header.len() {
            return Err(format!("CSV record {} has {} fields; the header has {}", i + 2, r.len(), header.len()));
        }
    }
    Ok((header, records))
}

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

    fn same(a: &Value, b: &Value) -> bool {
        match (a, b) {
            (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
            (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(a, b)| same(a, b)),
            (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same(v, w))),
            _ => a == b,
        }
    }

    #[test]
    fn core_schema() {
        let cases: Vec<(&str, Value)> = vec![
            ("x: 0x1F\n", json!({"x": 31})),
            ("x: 0o17\n", json!({"x": 15})),
            ("x: 010\n", json!({"x": 10})),
            ("x: 1_000\n", json!({"x": "1_000"})),
            ("x: yes\n", json!({"x": "yes"})),
            ("x: 2026-10-26\n", json!({"x": "2026-10-26"})),
            ("x: 1e3\n", json!({"x": 1000})),
            ("x: -0\n", json!({"x": 0})),
            ("x: !!str 1\n", json!({"x": "1"})),
            ("x: !!int 0x10\n", json!({"x": 16})),
            ("<<: {a: 1}\n", json!({"<<": {"a": 1}})),
            ("x: ~\ny: Null\nz:\n", json!({"x": null, "y": null, "z": null})),
            ("", Value::Null),
            ("# only a comment\n", Value::Null),
            ("- a\n- b: c\n", json!(["a", {"b": "c"}])),
            ("x: '12:30'\ny: 12:30\n", json!({"x": "12:30", "y": "12:30"})),
            ("? !!str 1\n: v\n", json!({"1": "v"})),
            ("x: !!null ''\n", json!({"x": null})),
            ("x: \"\\u00e9\"\n", json!({"x": "\u{e9}"})),
            ("x: !!seq [a]\n", json!({"x": ["a"]})),
            ("x: !!map {a: 1}\n", json!({"x": {"a": 1}})),
            ("x: 0b11\ny: 0X1F\n", json!({"x": "0b11", "y": "0X1F"})),
            ("x: !!int 0o17\n", json!({"x": 15})),
            ("x: !!int +12\n", json!({"x": 12})),
            ("x: !!float 1.5e3\n", json!({"x": 1500})),
            ("x: !!bool True\n", json!({"x": true})),
            ("x: !!str null\n", json!({"x": "null"})),
            ("x: !!null ~\n", json!({"x": null})),
            ("x: !!null null\n", json!({"x": null})),
            ("x: !!null Null\n", json!({"x": null})),
            ("x: !!null NULL\n", json!({"x": null})),
            ("x: !!float 1e3\n", json!({"x": 1000})),
            ("x: !!float -1.\n", json!({"x": -1})),
            ("x: !!float +.5\n", json!({"x": 0.5})),
            ("x: !!float .5e-3\n", json!({"x": 0.0005})),
            ("x: !!float 0.5\n", json!({"x": 0.5})),
            ("x: !!float -0.0\n", json!({"x": 0})),
            ("x: !!float 00.5\n", json!({"x": 0.5})),
            ("x: !!float 5.\n", json!({"x": 5})),
            ("x: !!float +5.e5\n", json!({"x": 500000})),
            ("x: !!float 5.e+5\n", json!({"x": 500000})),
            ("x: !!float 5.E-5\n", json!({"x": 5e-05})),
            ("x: !!float -5E5\n", json!({"x": -500000})),
            ("%YAML 1.2\n---\nx: 1\n", json!({"x": 1})),
            ("%YAML 1.1\n---\nx: yes\n", json!({"x": "yes"})),
            ("x: 1\n...\n", json!({"x": 1})),
            ("x: a\u{2028}b\n", json!({"x": "a\u{2028}b"})),
            ("x: 'a\u{85}b'\n", json!({"x": "a\u{85}b"})),
            ("- \u{2029}\n", json!(["\u{2029}"])),
            // block structure
            ("a:\n  b: 1\n  c: [x, y]\nd:\n- 1\n- 2\n", json!({"a": {"b": 1, "c": ["x", "y"]}, "d": [1, 2]})),
            ("a: |\n  one\n  two\nb: >-\n  folded\n  text\n\n  para\n", json!({"a": "one\ntwo\n", "b": "folded text\npara"})),
            ("a: long\n  plain text\n", json!({"a": "long plain text"})),
            ("- a: 1\n  b: 2\n- - x\n  - y\n", json!([{"a": 1, "b": 2}, ["x", "y"]])),
            ("x: \"a\n  b\"\n", json!({"x": "a b"})),
            ("x: {a: 1, b: [2, {c: d}]}\n", json!({"x": {"a": 1, "b": [2, {"c": "d"}]}})),
            ("description: \"Day, °C\" # note\n", json!({"description": "Day, °C"})),
            ("x: https://example.org/a#b\n", json!({"x": "https://example.org/a#b"})),
            ("list:\n  - { uri: ./a.md, as: a }\n", json!({"list": [{"uri": "./a.md", "as": "a"}]})),
            ("a: |+\n  x\n\nb: 1\n", json!({"a": "x\n\n", "b": 1})),
            ("a: >\n  one\n    two\n  three\n", json!({"a": "one\n  two\nthree\n"})),
            // as the reference's YAML 1.2 reads them (yaml.v3, a YAML 1.1 reader, refuses these)
            ("t: { u: https://example.org/a?b }\n", json!({"t": {"u": "https://example.org/a?b"}})),
            ("t: { values:[warm, plain] }\n", json!({"t": {"values": ["warm", "plain"]}})),
            ("t: {summary:? C}\n", json!({"t": {"summary:? C": null}})),
            ("k: [\n  a,\n]\n", json!({"k": ["a"]})),
            ("k: [a,\n b]\n", json!({"k": ["a", "b"]})),
            ("[a,\nb]\n", json!(["a", "b"])),
        ];
        for (src, want) in cases {
            match load_yaml(src) {
                Ok((got, _)) => assert!(same(&got, &want), "{src:?}: {got:?}, want {want:?}"),
                Err(e) => panic!("{src:?}: {e}"),
            }
        }
    }

    #[test]
    fn refusals() {
        let cases = [
            ("a: 1\na: 2\n", "Map keys must be unique"),
            ("x: !!int abc\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!float 1\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !foo bar\n", "the YAML tag !foo is not allowed"),
            ("x: !!binary aGk=\n", "the YAML tag tag:yaml.org,2002:binary is not allowed"),
            ("1: a\n", "mapping keys must be strings"),
            ("true: a\n", "mapping keys must be strings"),
            ("? [a]\n: b\n", "mapping keys must be strings"),
            ("a: 1\n---\n", SECOND_DOCUMENT),
            ("a: [1, 2\n---\nb: 1\n", SECOND_DOCUMENT),
            ("a: \"x\n---\ny\"\n", SECOND_DOCUMENT),
            ("a: b: c\n...\nb: 1\n", SECOND_DOCUMENT),
            ("...\n---\n", SECOND_DOCUMENT),
            ("x: .inf\n", "non-finite numbers are not allowed"),
            ("x: 1e400\n", "non-finite numbers are not allowed"),
            ("x: &a 1\ny: *a\n", "YAML anchors are not allowed"),
            ("notes: &a [1, *a]\n", "YAML anchors are not allowed"),
            ("a: {x: 1, x: 2}\n", "Map keys must be unique"),
            ("null: a\n~: b\n", "Map keys must be unique"),
            ("k: [1, {a: .nan}]\n", "non-finite numbers are not allowed"),
            ("? !!int 1\n: v\n", "mapping keys must be strings"),
            ("x: !!bool yes\n", "Unresolved tag: tag:yaml.org,2002:bool"),
            ("x: !!set {a: ~}\n", "the YAML tag tag:yaml.org,2002:set is not allowed"),
            ("x: !!omap [a: 1]\n", "the YAML tag tag:yaml.org,2002:omap is not allowed"),
            ("x: !!pairs [a: 1]\n", "the YAML tag tag:yaml.org,2002:pairs is not allowed"),
            ("x: !!merge <<\n", "the YAML tag tag:yaml.org,2002:merge is not allowed"),
            ("x: !<!bar> baz\n", "the YAML tag !bar is not allowed"),
            ("x: !local:t v\n", "the YAML tag !local:t is not allowed"),
            ("x: +.inf\n", "non-finite numbers are not allowed"),
            ("x: -.Inf\n", "non-finite numbers are not allowed"),
            ("x: .NaN\n", "non-finite numbers are not allowed"),
            ("x: !!float .nan\n", "non-finite numbers are not allowed"),
            ("x: !!str [a]\n", "Unresolved tag: tag:yaml.org,2002:str"),
            ("x: !!int [a]\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!null {}\n", "Unresolved tag: tag:yaml.org,2002:null"),
            ("x: !!str {a: 1}\n", "Unresolved tag: tag:yaml.org,2002:str"),
            ("x: !!binary [a]\n", "the YAML tag tag:yaml.org,2002:binary is not allowed"),
            ("x: !!float 0x1F\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!int .5\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!null 0\n", "Unresolved tag: tag:yaml.org,2002:null"),
            ("x: !!bool 1\n", "Unresolved tag: tag:yaml.org,2002:bool"),
            ("x: !!int ''\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!float ''\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!bool ''\n", "Unresolved tag: tag:yaml.org,2002:bool"),
            ("x: !!int null\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!null nUll\n", "Unresolved tag: tag:yaml.org,2002:null"),
            ("x: !!bool tRue\n", "Unresolved tag: tag:yaml.org,2002:bool"),
            ("x: !!int 0x\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!int 0o\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!int 0o8\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!int 0xG\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!int 1e3\n", "Unresolved tag: tag:yaml.org,2002:int"),
            ("x: !!float .\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 1.5.5\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 1e\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float e3\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float -.inf\n", "non-finite numbers are not allowed"),
            ("x: !!float .NAN\n", "non-finite numbers are not allowed"),
            ("x: !!float .Nan\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float +.nan\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float -.INF\n", "non-finite numbers are not allowed"),
            ("x: !!float .iNf\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 1_0.5\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 5e5.5\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float ++5.5\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 5..5\n", "Unresolved tag: tag:yaml.org,2002:float"),
            ("x: !!float 0x1.8p1\n", "Unresolved tag: tag:yaml.org,2002:float"),
        ];
        for (src, want) in cases {
            match load_yaml(src) {
                Ok((v, _)) => panic!("{src:?}: {v:?}, want {want:?}"),
                Err(e) => assert_eq!(e, want, "{src:?}"),
            }
        }
        for src in [
            "x: [*a]\n",
            "x: [a, b\n",
            "x: 'a\n",
            "a: b: c\n",
            "a:\n  - b\n c: d\n",
            &"[".repeat(5000),
            // continuation lines indented past their block collection, implicit keys on one line, no empty entries
            "k: [a,\nb]\n",
            "k: \"a\nb\"\n",
            "- \"a\nb\"\n",
            "k:\n  x: [a,\n  b]\n",
            "t: { ur\ni: x }\n",
            "t: [, b]\n",
            "t: [a,, b]\n",
        ] {
            assert!(load_yaml(src).is_err(), "{src:?}");
        }
    }

    #[test]
    fn json_and_csv() {
        assert_eq!(load_json(r#"{"a": {"b": 1, "b": 2}}"#).unwrap_err(), r#"the JSON key "b" is repeated"#);
        assert!(load_json(r#"[{"a": 1}, {"a": 2}]"#).is_ok());
        for (src, want) in [
            ("a,b\n1\n", "CSV record 2 has 1 fields; the header has 2"),
            ("a,a\n1,2\n", "CSV header names must be unique"),
            ("a,\n1,2\n", "CSV header names must be nonempty"),
            ("", "a CSV body needs a header record"),
            ("a\n\"x\n", "an unclosed quoted CSV field"),
            ("a,b\n1,x\"y\"\n", "a quote inside an unquoted CSV field (record 2)"),
        ] {
            assert_eq!(load_csv(src).unwrap_err(), want, "{src:?}");
        }
        let (_, rows) = load_csv("a,b\r\n1,\"x,\"\"y\"\"\"\r\n").unwrap();
        assert_eq!(rows, vec![vec!["1".to_string(), "x,\"y\"".to_string()]]);
    }
}