granit-parser 0.0.2

A YAML parser in pure Rust with strict compliance
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
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
//! Home to the YAML Parser.
//!
//! The parser takes input from the [`crate::scanner::Scanner`], performs final checks for YAML
//! compliance, and emits a stream of YAML events. This stream can for instance be used to create
//! YAML objects.

use crate::{
    input::{str::StrInput, BorrowedInput},
    scanner::{ScalarStyle, ScanError, Scanner, Span, Token, TokenType},
    BufferedInput,
};

use alloc::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet},
    string::{String, ToString},
    vec::Vec,
};
use core::{
    convert::Infallible,
    fmt::{self, Display},
};

#[derive(Clone, Copy, PartialEq, Debug, Eq)]
enum State {
    StreamStart,
    ImplicitDocumentStart,
    DocumentStart,
    DocumentContent,
    DocumentEnd,
    BlockNode,
    BlockSequenceFirstEntry,
    BlockSequenceEntry,
    IndentlessSequenceEntry,
    BlockMappingFirstKey,
    BlockMappingKey,
    BlockMappingValue,
    FlowSequenceFirstEntry,
    FlowSequenceEntry,
    FlowSequenceEntryMappingKey,
    FlowSequenceEntryMappingValue,
    FlowSequenceEntryMappingEnd,
    FlowMappingFirstKey,
    FlowMappingKey,
    FlowMappingValue,
    FlowMappingEmptyValue,
    End,
}

/// An event generated by the YAML parser.
///
/// Events are used in the low-level event-based API (push parser). The API entrypoint is the
/// [`EventReceiver`] trait.
#[derive(Clone, PartialEq, Debug, Eq)]
pub enum Event<'input> {
    /// Reserved for internal use.
    Nothing,
    /// Event generated at the very beginning of parsing.
    StreamStart,
    /// Last event that will be generated by the parser. Signals EOF.
    StreamEnd,
    /// The start of a YAML document.
    ///
    /// When the boolean is `true`, it is an explicit document start
    /// directive (`---`).
    ///
    /// When the boolean is `false`, it is an implicit document start
    /// (without `---`).
    DocumentStart(bool),
    /// The YAML end document directive (`...`).
    DocumentEnd,
    /// A YAML Alias.
    Alias(
        /// The anchor ID the alias refers to.
        usize,
    ),
    /// Value, style, `anchor_id`, tag
    Scalar(
        Cow<'input, str>,
        ScalarStyle,
        usize,
        Option<Cow<'input, Tag>>,
    ),
    /// The start of a YAML sequence (array).
    SequenceStart(
        /// The anchor ID of the start of the sequence.
        usize,
        /// An optional tag
        Option<Cow<'input, Tag>>,
    ),
    /// The end of a YAML sequence (array).
    SequenceEnd,
    /// The start of a YAML mapping (object, hash).
    MappingStart(
        /// The anchor ID of the start of the mapping.
        usize,
        /// An optional tag
        Option<Cow<'input, Tag>>,
    ),
    /// The end of a YAML mapping (object, hash).
    MappingEnd,
}

/// A YAML tag.
#[derive(Clone, PartialEq, Debug, Eq, Ord, PartialOrd, Hash)]
pub struct Tag {
    /// Handle of the tag (`!` included).
    pub handle: String,
    /// The suffix of the tag.
    pub suffix: String,
}

impl Tag {
    /// Returns whether the tag is a YAML tag from the core schema (`!!str`, `!!int`, ...).
    ///
    /// The YAML specification specifies [a list of
    /// tags](https://yaml.org/spec/1.2.2/#103-core-schema) for the Core Schema. This function
    /// checks whether _the handle_ (but not the suffix) is the handle for the YAML Core Schema.
    ///
    /// # Return
    /// Returns `true` if the handle is `tag:yaml.org,2002`, `false` otherwise.
    #[must_use]
    pub fn is_yaml_core_schema(&self) -> bool {
        self.handle == "tag:yaml.org,2002:"
    }
}

impl Display for Tag {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.handle == "!" {
            write!(f, "!{}", self.suffix)
        } else {
            write!(f, "{}{}", self.handle, self.suffix)
        }
    }
}

impl<'input> Event<'input> {
    /// Create an empty scalar.
    fn empty_scalar() -> Self {
        // a null scalar
        Event::Scalar("~".into(), ScalarStyle::Plain, 0, None)
    }

    /// Create an empty scalar with the given anchor.
    fn empty_scalar_with_anchor(anchor: usize, tag: Option<Cow<'input, Tag>>) -> Self {
        Event::Scalar(Cow::default(), ScalarStyle::Plain, anchor, tag)
    }
}

/// A YAML parser.
#[derive(Debug)]
pub struct Parser<'input, T: BorrowedInput<'input>> {
    /// The underlying scanner from which we pull tokens.
    scanner: Scanner<'input, T>,
    /// The stack of _previous_ states we were in.
    ///
    /// States are pushed in the context of subobjects to this stack. The top-most element is the
    /// state in which to come back to when exiting the current state.
    states: Vec<State>,
    /// The state in which we currently are.
    state: State,
    /// The next token from the scanner.
    token: Option<Token<'input>>,
    /// The next YAML event to emit.
    current: Option<(Event<'input>, Span)>,

    /// Pending indentation hint to be attached to the next emitted event span.
    ///
    /// This is used to communicate indentation for block mapping keys. It is set when consuming a
    /// `TokenType::Key` in block style, and is applied to the next emitted node event (the key
    /// itself).
    pending_key_indent: Option<usize>,
    /// Anchors that have been encountered in the YAML document.
    anchors: BTreeMap<Cow<'input, str>, usize>,
    /// Next ID available for an anchor.
    ///
    /// Every anchor is given a unique ID. We use an incrementing ID and this is both the ID to
    /// return for the next anchor and the count of anchor IDs emitted.
    anchor_id_count: usize,
    /// The tag directives (`%TAG`) the parser has encountered.
    ///
    /// Key is the handle, and value is the prefix.
    tags: BTreeMap<String, String>,
    /// Whether we have emitted [`Event::StreamEnd`].
    ///
    /// Emitted means that it has been returned from [`Self::next`]. If it is stored in
    /// [`Self::token`], this is set to `false`.
    stream_end_emitted: bool,
    /// Make tags global across all documents.
    keep_tags: bool,
}

/// Trait to be implemented in order to use the low-level parsing API.
///
/// The low-level parsing API is event-based (a push parser), calling [`EventReceiver::on_event`]
/// for each YAML [`Event`] that occurs.
/// The [`EventReceiver`] trait only receives events. In order to receive both events and their
/// location in the source, use [`SpannedEventReceiver`]. Note that [`EventReceiver`]s implement
/// [`SpannedEventReceiver`] automatically.
///
/// # Event hierarchy
/// The event stream starts with an [`Event::StreamStart`] event followed by an
/// [`Event::DocumentStart`] event. If the YAML document starts with a mapping (an object), an
/// [`Event::MappingStart`] event is emitted. If it starts with a sequence (an array), an
/// [`Event::SequenceStart`] event is emitted. Otherwise, an [`Event::Scalar`] event is emitted.
///
/// In a mapping, key-values are sent as consecutive events. The first event after an
/// [`Event::MappingStart`] will be the key, and following its value. If the mapping contains no
/// sub-mapping or sub-sequence, then even events (starting from 0) will always be keys and odd
/// ones will always be values. The mapping ends when an [`Event::MappingEnd`] event is received.
///
/// In a sequence, values are sent consecutively until the [`Event::SequenceEnd`] event.
///
/// If a value is a sub-mapping or a sub-sequence, an [`Event::MappingStart`] or
/// [`Event::SequenceStart`] event will be sent respectively. Following events until the associated
/// [`Event::MappingStart`] or [`Event::SequenceEnd`] (beware of nested mappings or sequences) will
/// be part of the value and not another key-value pair or element in the sequence.
///
/// For instance, the following yaml:
/// ```yaml
/// a: b
/// c:
///   d: e
/// f:
///   - g
///   - h
/// ```
/// will emit (indented and commented for visibility):
/// ```text
/// StreamStart, DocumentStart, MappingStart,
///   Scalar("a", ..), Scalar("b", ..)
///   Scalar("c", ..), MappingStart, Scalar("d", ..), Scalar("e", ..), MappingEnd,
///   Scalar("f", ..), SequenceStart, Scalar("g", ..), Scalar("h", ..), SequenceEnd,
/// MappingEnd, DocumentEnd, StreamEnd
/// ```
///
/// # Example
/// ```
/// # use granit_parser::{Event, EventReceiver, Parser};
/// #
/// /// Sink of events. Collects them into an array.
/// struct EventSink<'input> {
///     events: Vec<Event<'input>>,
/// }
///
/// /// Implement `on_event`, pushing into `self.events`.
/// impl<'input> EventReceiver<'input> for EventSink<'input> {
///     fn on_event(&mut self, ev: Event<'input>) {
///         self.events.push(ev);
///     }
/// }
///
/// /// Load events from a yaml string.
/// fn str_to_events(yaml: &str) -> Vec<Event<'_>> {
///     let mut sink = EventSink { events: Vec::new() };
///     let mut parser = Parser::new_from_str(yaml);
///     // Load events using our sink as the receiver.
///     parser.load(&mut sink, true).unwrap();
///     sink.events
/// }
/// ```
pub trait EventReceiver<'input> {
    /// Handler called for each YAML event that is emitted by the parser.
    fn on_event(&mut self, ev: Event<'input>);
}

/// Trait to be implemented for using the low-level parsing API.
///
/// Functionally similar to [`EventReceiver`], but receives a [`Span`] as well as the event.
pub trait SpannedEventReceiver<'input> {
    /// Handler called for each event that occurs.
    fn on_event(&mut self, ev: Event<'input>, span: Span);
}

impl<'input, R: EventReceiver<'input>> SpannedEventReceiver<'input> for R {
    fn on_event(&mut self, ev: Event<'input>, _span: Span) {
        self.on_event(ev);
    }
}

/// Trait to be implemented for fallible event handling without source spans.
///
/// This is the fallible counterpart to [`EventReceiver`]. Use it with [`Parser::try_load`] when
/// event handling may need to stop parsing by returning an application error.
pub trait TryEventReceiver<'input> {
    /// Error returned by this receiver.
    type Error;

    /// Handler called for each YAML event that is emitted by the parser.
    ///
    /// Returning an error stops [`Parser::try_load`] immediately.
    ///
    /// # Errors
    /// Returns `Self::Error` when the receiver wants to stop parsing.
    fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error>;
}

/// Trait to be implemented for fallible event handling with source spans.
///
/// This is the fallible counterpart to [`SpannedEventReceiver`]. Use it with
/// [`Parser::try_load`] when event handling may need to stop parsing by returning an application
/// error.
pub trait TrySpannedEventReceiver<'input> {
    /// Error returned by this receiver.
    type Error;

    /// Handler called for each event that occurs.
    ///
    /// Returning an error stops [`Parser::try_load`] immediately.
    ///
    /// # Errors
    /// Returns `Self::Error` when the receiver wants to stop parsing.
    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error>;
}

impl<'input, R: TryEventReceiver<'input>> TrySpannedEventReceiver<'input> for R {
    type Error = R::Error;

    fn on_event(&mut self, ev: Event<'input>, _span: Span) -> Result<(), Self::Error> {
        TryEventReceiver::on_event(self, ev)
    }
}

/// Error returned by [`Parser::try_load`] and [`ParserTrait::try_load`].
#[derive(Clone, PartialEq, Debug, Eq)]
pub enum TryLoadError<E> {
    /// Scanning or parsing failed.
    Scan(
        /// The scanner or parser error.
        ScanError,
    ),
    /// The receiver returned an application error.
    Receiver(
        /// The error returned by the receiver.
        E,
    ),
}

impl<E> From<ScanError> for TryLoadError<E> {
    fn from(error: ScanError) -> Self {
        Self::Scan(error)
    }
}

impl<E: Display> Display for TryLoadError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Scan(error) => write!(f, "parser error: {error}"),
            Self::Receiver(error) => write!(f, "receiver error: {error}"),
        }
    }
}

impl<E> core::error::Error for TryLoadError<E>
where
    E: core::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Scan(error) => Some(error),
            Self::Receiver(error) => Some(error),
        }
    }
}

fn try_emit<'input, R>(
    recv: &mut R,
    ev: Event<'input>,
    span: Span,
) -> Result<(), TryLoadError<R::Error>>
where
    R: TrySpannedEventReceiver<'input>,
{
    recv.on_event(ev, span).map_err(TryLoadError::Receiver)
}

struct InfallibleSpannedReceiver<'receiver, R>(&'receiver mut R);

impl<'input, R: SpannedEventReceiver<'input>> TrySpannedEventReceiver<'input>
    for InfallibleSpannedReceiver<'_, R>
{
    type Error = Infallible;

    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
        self.0.on_event(ev, span);
        Ok(())
    }
}

fn into_scan_result(result: Result<(), TryLoadError<Infallible>>) -> Result<(), ScanError> {
    match result {
        Ok(()) => Ok(()),
        Err(TryLoadError::Scan(error)) => Err(error),
        Err(TryLoadError::Receiver(error)) => match error {},
    }
}

/// A convenience alias for a `Result` of a parser event.
pub type ParseResult<'input> = Result<(Event<'input>, Span), ScanError>;

/// Trait extracted from `Parser` to support mocking and alternative implementations.
pub trait ParserTrait<'input> {
    /// Try to load the next event and return it, but do not consuming it from `self`.
    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>>;

    /// Try to load the next event and return it, consuming it from `self`.
    fn next_event(&mut self) -> Option<ParseResult<'input>>;

    /// Load the YAML from the stream in `self`, pushing events into `recv`.
    ///
    /// Use this method when event handling is infallible. If receiver code can return an
    /// application error and should stop parsing, use [`ParserTrait::try_load`] instead. If the
    /// caller should directly control when the next event is read, use [`ParserTrait::next_event`]
    /// or [`Parser`]'s [`core::iter::Iterator`] implementation.
    ///
    /// # Errors
    /// Returns `ScanError` when scanning or parsing the stream fails.
    fn load<R: SpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), ScanError>;

    /// Load the YAML from the stream in `self`, stopping if `recv` returns an error.
    ///
    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
    /// inside the stream.
    ///
    /// If the receiver returns an error, the parser is left positioned immediately after the event
    /// that caused the receiver error. Callers should treat the parser as partially consumed.
    ///
    /// # Errors
    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
    /// [`TryLoadError::Receiver`] when `recv` returns an error.
    fn try_load<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), TryLoadError<R::Error>> {
        while let Some(res) = self.next_event() {
            let (ev, span) = res?;
            let is_doc_end = matches!(ev, Event::DocumentEnd);
            let is_stream_end = matches!(ev, Event::StreamEnd);

            try_emit(recv, ev, span)?;

            if is_stream_end {
                break;
            }
            if !multi && is_doc_end {
                break;
            }
        }

        Ok(())
    }
}

impl<'input> Parser<'input, StrInput<'input>> {
    /// Create a new instance of a parser from a &str.
    #[must_use]
    pub fn new_from_str(value: &'input str) -> Self {
        debug_print!("\x1B[;31m>>>>>>>>>> New parser from str\x1B[;0m");
        Parser::new(StrInput::new(value))
    }
}

impl<T> Parser<'static, BufferedInput<T>>
where
    T: Iterator<Item = char>,
{
    /// Create a new instance of a parser from an iterator of `char`s.
    #[must_use]
    pub fn new_from_iter(iter: T) -> Self {
        debug_print!("\x1B[;31m>>>>>>>>>> New parser from iter\x1B[;0m");
        Parser::new(BufferedInput::new(iter))
    }
}

impl<'input, T: BorrowedInput<'input>> Parser<'input, T> {
    /// Get the current anchor offset count.
    pub fn get_anchor_offset(&self) -> usize {
        self.anchor_id_count
    }

    /// Set the current anchor offset count.
    pub fn set_anchor_offset(&mut self, offset: usize) {
        self.anchor_id_count = offset;
    }

    /// Create a new instance of a parser from the given input of characters.
    pub fn new(src: T) -> Self {
        Parser {
            scanner: Scanner::new(src),
            states: Vec::new(),
            state: State::StreamStart,
            token: None,
            current: None,

            pending_key_indent: None,

            anchors: BTreeMap::new(),
            // valid anchor_id starts from 1
            anchor_id_count: 1,
            tags: BTreeMap::new(),
            stream_end_emitted: false,
            keep_tags: false,
        }
    }

    /// Whether to keep tags across multiple documents when parsing.
    ///
    /// This behavior is non-standard as per the YAML specification but can be encountered in the
    /// wild. This boolean allows enabling this non-standard extension. This would result in the
    /// parser accepting input from [test
    /// QLJ7](https://github.com/yaml/yaml-test-suite/blob/ccfa74e56afb53da960847ff6e6976c0a0825709/src/QLJ7.yaml)
    /// of the yaml-test-suite:
    ///
    /// ```yaml
    /// %TAG !prefix! tag:example.com,2011:
    /// --- !prefix!A
    /// a: b
    /// --- !prefix!B
    /// c: d
    /// --- !prefix!C
    /// e: f
    /// ```
    ///
    /// With `keep_tags` set to `false`, the above YAML is rejected. As per the specification, tags
    /// only apply to the document immediately following them. This would error on `!prefix!B`.
    ///
    /// With `keep_tags` set to `true`, the above YAML is accepted by the parser.
    #[must_use]
    pub fn keep_tags(mut self, value: bool) -> Self {
        self.keep_tags = value;
        self
    }

    /// Try to load the next event and return it, but do not consuming it from `self`.
    ///
    /// Any subsequent call to [`Parser::peek`] will return the same value, until a call to
    /// [`Iterator::next`] or [`Parser::load`].
    ///
    /// # Errors
    /// Returns `ScanError` when loading the next event fails.
    pub fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
        ParserTrait::peek(self)
    }

    /// Try to load the next event and return it, consuming it from `self`.
    ///
    /// # Errors
    /// Returns `ScanError` when loading the next event fails.
    pub fn next_event(&mut self) -> Option<ParseResult<'input>> {
        ParserTrait::next_event(self)
    }

    /// Implementation function for [`Self::next_event`] without the `Option`.
    ///
    /// [`Self::next_event`] should conform to the expectations of an [`Iterator`] and return an
    /// option. This burdens the parser code. This function is used internally when an option is
    /// undesirable.
    fn next_event_impl<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match self.current.take() {
            None => self.parse(),
            Some(v) => Ok(v),
        }
    }

    /// Peek at the next token from the scanner.
    fn peek_token(&mut self) -> Result<&Token<'_>, ScanError> {
        match self.token {
            None => {
                self.token = Some(self.scan_next_token()?);
                Ok(self.token.as_ref().unwrap())
            }
            Some(ref tok) => Ok(tok),
        }
    }

    /// Extract and return the next token from the scanner.
    ///
    /// This function does _not_ make use of `self.token`.
    fn scan_next_token(&mut self) -> Result<Token<'input>, ScanError> {
        let token = self.scanner.next();
        match token {
            None => match self.scanner.get_error() {
                None => Err(self.unexpected_eof()),
                Some(e) => Err(e),
            },
            Some(tok) => Ok(tok),
        }
    }

    #[cold]
    fn unexpected_eof(&self) -> ScanError {
        let info = match self.state {
            State::FlowSequenceFirstEntry | State::FlowSequenceEntry => {
                "unexpected EOF while parsing a flow sequence"
            }
            State::FlowMappingFirstKey
            | State::FlowMappingKey
            | State::FlowMappingValue
            | State::FlowMappingEmptyValue => "unexpected EOF while parsing a flow mapping",
            State::FlowSequenceEntryMappingKey
            | State::FlowSequenceEntryMappingValue
            | State::FlowSequenceEntryMappingEnd => {
                "unexpected EOF while parsing an implicit flow mapping"
            }
            State::BlockSequenceFirstEntry | State::BlockSequenceEntry => {
                "unexpected EOF while parsing a block sequence"
            }
            State::BlockMappingFirstKey | State::BlockMappingKey | State::BlockMappingValue => {
                "unexpected EOF while parsing a block mapping"
            }
            _ => "unexpected eof",
        };
        ScanError::new_str(self.scanner.mark(), info)
    }

    fn fetch_token<'a>(&mut self) -> Token<'a>
    where
        'input: 'a,
    {
        self.token
            .take()
            .expect("fetch_token needs to be preceded by peek_token")
    }

    /// Skip the next token from the scanner.
    fn skip(&mut self) {
        self.token = None;
    }
    /// Pops the top-most state and make it the current state.
    fn pop_state(&mut self) {
        self.state = self.states.pop().unwrap();
    }
    /// Push a new state atop the state stack.
    fn push_state(&mut self, state: State) {
        self.states.push(state);
    }

    fn parse<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        if self.state == State::End {
            return Ok((Event::StreamEnd, Span::empty(self.scanner.mark())));
        }
        let (ev, span) = self.state_machine()?;
        if let Some(indent) = self.pending_key_indent.take() {
            Ok((ev, span.with_indent(Some(indent))))
        } else {
            Ok((ev, span))
        }
    }

    /// Load the YAML from the stream in `self`, pushing events into `recv`.
    ///
    /// The contents of the stream are parsed and the corresponding events are sent into the
    /// receiver. For detailed explanations about how events work, see [`EventReceiver`].
    ///
    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
    /// inside the stream.
    ///
    /// Use this method when event handling is infallible. If receiver code can return an
    /// application error and should stop parsing, use [`Parser::try_load`] instead. If the caller
    /// should directly control when the next event is read, use [`Parser`]'s
    /// [`core::iter::Iterator`] implementation.
    ///
    /// Note that any [`EventReceiver`] is also a [`SpannedEventReceiver`], so implementing the
    /// former is enough to call this function.
    ///
    /// # Example
    /// ```
    /// # use granit_parser::{Event, EventReceiver, Parser};
    /// # fn main() -> Result<(), granit_parser::ScanError> {
    /// struct EventSink<'input> {
    ///     events: Vec<Event<'input>>,
    /// }
    ///
    /// impl<'input> EventReceiver<'input> for EventSink<'input> {
    ///     fn on_event(&mut self, ev: Event<'input>) {
    ///         self.events.push(ev);
    ///     }
    /// }
    ///
    /// let mut parser = Parser::new_from_str("a: 1\n");
    /// let mut sink = EventSink { events: Vec::new() };
    ///
    /// parser.load(&mut sink, false)?;
    ///
    /// assert!(sink
    ///     .events
    ///     .iter()
    ///     .any(|ev| matches!(ev, Event::Scalar(value, ..) if value == "a")));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Returns `ScanError` when loading fails.
    pub fn load<R: SpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), ScanError> {
        ParserTrait::load(self, recv, multi)
    }

    /// Load the YAML from the stream in `self`, pushing events into `recv`.
    ///
    /// This is the fallible counterpart to [`Parser::load`]. If `recv` returns an error, parsing
    /// stops immediately and that error is returned as [`TryLoadError::Receiver`].
    ///
    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
    /// inside the stream.
    ///
    /// If the receiver returns an error, the parser is left positioned immediately after the event
    /// that caused the receiver error. Callers should treat the parser as partially consumed.
    ///
    /// # Example
    /// ```
    /// # use granit_parser::{Event, Parser, TryEventReceiver, TryLoadError};
    /// #[derive(Debug, PartialEq, Eq)]
    /// enum ValidationError {
    ///     ForbiddenScalar,
    /// }
    ///
    /// struct Validator;
    ///
    /// impl<'input> TryEventReceiver<'input> for Validator {
    ///     type Error = ValidationError;
    ///
    ///     fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
    ///         if matches!(ev, Event::Scalar(value, ..) if value.as_ref() == "bad") {
    ///             Err(ValidationError::ForbiddenScalar)
    ///         } else {
    ///             Ok(())
    ///         }
    ///     }
    /// }
    ///
    /// let mut parser = Parser::new_from_str("value: bad\n");
    /// let mut validator = Validator;
    ///
    /// let err = parser.try_load(&mut validator, false).unwrap_err();
    ///
    /// assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenScalar));
    /// ```
    ///
    /// # Errors
    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
    /// [`TryLoadError::Receiver`] when `recv` returns an error.
    pub fn try_load<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), TryLoadError<R::Error>> {
        ParserTrait::try_load(self, recv, multi)
    }

    fn try_load_document<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        first_ev: Event<'input>,
        span: Span,
        recv: &mut R,
    ) -> Result<(), TryLoadError<R::Error>> {
        if !matches!(first_ev, Event::DocumentStart(_)) {
            return Err(TryLoadError::Scan(ScanError::new_str(
                span.start,
                "did not find expected <document-start>",
            )));
        }
        try_emit(recv, first_ev, span)?;

        let (ev, span) = self.next_event_impl()?;
        self.try_load_node(ev, span, recv)?;

        // DOCUMENT-END is expected.
        let (ev, mark) = self.next_event_impl()?;
        assert_eq!(ev, Event::DocumentEnd);
        try_emit(recv, ev, mark)?;

        Ok(())
    }

    fn try_load_node<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        first_ev: Event<'input>,
        span: Span,
        recv: &mut R,
    ) -> Result<(), TryLoadError<R::Error>> {
        match first_ev {
            Event::Alias(..) | Event::Scalar(..) => try_emit(recv, first_ev, span),
            Event::SequenceStart(..) => {
                try_emit(recv, first_ev, span)?;
                self.try_load_sequence(recv)
            }
            Event::MappingStart(..) => {
                try_emit(recv, first_ev, span)?;
                self.try_load_mapping(recv)
            }
            _ => {
                #[cfg(feature = "debug_prints")]
                std::println!("UNREACHABLE EVENT: {first_ev:?}");
                unreachable!();
            }
        }
    }

    fn try_load_mapping<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
    ) -> Result<(), TryLoadError<R::Error>> {
        let (mut key_ev, mut key_mark) = self.next_event_impl()?;
        while key_ev != Event::MappingEnd {
            // key
            self.try_load_node(key_ev, key_mark, recv)?;

            // value
            let (ev, mark) = self.next_event_impl()?;
            self.try_load_node(ev, mark, recv)?;

            // next event
            let (ev, mark) = self.next_event_impl()?;
            key_ev = ev;
            key_mark = mark;
        }
        try_emit(recv, key_ev, key_mark)?;
        Ok(())
    }

    fn try_load_sequence<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
    ) -> Result<(), TryLoadError<R::Error>> {
        let (mut ev, mut mark) = self.next_event_impl()?;
        while ev != Event::SequenceEnd {
            self.try_load_node(ev, mark, recv)?;

            // next event
            let (next_ev, next_mark) = self.next_event_impl()?;
            ev = next_ev;
            mark = next_mark;
        }
        try_emit(recv, ev, mark)?;
        Ok(())
    }

    fn state_machine<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        // let next_tok = self.peek_token().cloned()?;
        // println!("cur_state {:?}, next tok: {:?}", self.state, next_tok);
        debug_print!("\n\x1B[;33mParser state: {:?} \x1B[;0m", self.state);

        match self.state {
            State::StreamStart => self.stream_start(),

            State::ImplicitDocumentStart => self.document_start(true),
            State::DocumentStart => self.document_start(false),
            State::DocumentContent => self.document_content(),
            State::DocumentEnd => self.document_end(),

            State::BlockNode => self.parse_node(true, false),
            // State::BlockNodeOrIndentlessSequence => self.parse_node(true, true),
            // State::FlowNode => self.parse_node(false, false),
            State::BlockMappingFirstKey => self.block_mapping_key(true),
            State::BlockMappingKey => self.block_mapping_key(false),
            State::BlockMappingValue => self.block_mapping_value(),

            State::BlockSequenceFirstEntry => self.block_sequence_entry(true),
            State::BlockSequenceEntry => self.block_sequence_entry(false),

            State::FlowSequenceFirstEntry => self.flow_sequence_entry(true),
            State::FlowSequenceEntry => self.flow_sequence_entry(false),

            State::FlowMappingFirstKey => self.flow_mapping_key(true),
            State::FlowMappingKey => self.flow_mapping_key(false),
            State::FlowMappingValue => self.flow_mapping_value(false),

            State::IndentlessSequenceEntry => self.indentless_sequence_entry(),

            State::FlowSequenceEntryMappingKey => self.flow_sequence_entry_mapping_key(),
            State::FlowSequenceEntryMappingValue => self.flow_sequence_entry_mapping_value(),
            State::FlowSequenceEntryMappingEnd => self.flow_sequence_entry_mapping_end(),
            State::FlowMappingEmptyValue => self.flow_mapping_value(true),

            /* impossible */
            State::End => unreachable!(),
        }
    }

    fn stream_start<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match *self.peek_token()? {
            Token(span, TokenType::StreamStart(_)) => {
                self.state = State::ImplicitDocumentStart;
                self.skip();
                Ok((Event::StreamStart, span))
            }
            Token(span, _) => Err(ScanError::new_str(
                span.start,
                "did not find expected <stream-start>",
            )),
        }
    }

    fn document_start<'a>(&mut self, implicit: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        while let TokenType::DocumentEnd = self.peek_token()?.1 {
            self.skip();
        }

        // Anchors are scoped to a single document.
        self.anchors.clear();

        match *self.peek_token()? {
            Token(span, TokenType::StreamEnd) => {
                self.state = State::End;
                self.skip();
                Ok((Event::StreamEnd, span))
            }
            Token(
                _,
                TokenType::VersionDirective(..)
                | TokenType::TagDirective(..)
                | TokenType::ReservedDirective(..)
                | TokenType::DocumentStart,
            ) => {
                // explicit document
                self.explicit_document_start()
            }
            Token(span, _) if implicit => {
                self.parser_process_directives()?;
                self.push_state(State::DocumentEnd);
                self.state = State::BlockNode;
                Ok((Event::DocumentStart(false), span))
            }
            _ => {
                // explicit document
                self.explicit_document_start()
            }
        }
    }

    fn parser_process_directives(&mut self) -> Result<(), ScanError> {
        let mut version_directive_received = false;
        let mut tags = if self.keep_tags {
            self.tags.clone()
        } else {
            BTreeMap::new()
        };
        let mut document_tag_handles = BTreeSet::new();

        loop {
            match self.peek_token()? {
                Token(span, TokenType::VersionDirective(_, _)) => {
                    // XXX parsing with warning according to spec
                    //if major != 1 || minor > 2 {
                    //    return Err(ScanError::new_str(tok.0,
                    //        "found incompatible YAML document"));
                    //}
                    if version_directive_received {
                        return Err(ScanError::new_str(
                            span.start,
                            "duplicate version directive",
                        ));
                    }
                    version_directive_received = true;
                }
                Token(mark, TokenType::TagDirective(handle, prefix)) => {
                    if !document_tag_handles.insert(handle.to_string()) {
                        return Err(ScanError::new_str(mark.start, "the TAG directive must only be given at most once per handle in the same document"));
                    }
                    tags.insert(handle.to_string(), prefix.to_string());
                }
                Token(_, TokenType::ReservedDirective(_, _)) => {
                    // Reserved directives are ignored
                }
                _ => break,
            }
            self.skip();
        }

        self.tags = tags;
        Ok(())
    }

    fn explicit_document_start<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        self.parser_process_directives()?;
        match *self.peek_token()? {
            Token(mark, TokenType::DocumentStart) => {
                self.push_state(State::DocumentEnd);
                self.state = State::DocumentContent;
                self.skip();
                Ok((Event::DocumentStart(true), mark))
            }
            Token(span, _) => Err(ScanError::new_str(
                span.start,
                "did not find expected <document start>",
            )),
        }
    }

    fn document_content<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match *self.peek_token()? {
            Token(
                mark,
                TokenType::VersionDirective(..)
                | TokenType::TagDirective(..)
                | TokenType::ReservedDirective(..)
                | TokenType::DocumentStart
                | TokenType::DocumentEnd
                | TokenType::StreamEnd,
            ) => {
                self.pop_state();
                // empty scalar
                Ok((Event::empty_scalar(), mark))
            }
            _ => self.parse_node(true, false),
        }
    }

    fn document_end<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        let mut explicit_end = false;
        let span: Span = match *self.peek_token()? {
            Token(span, TokenType::DocumentEnd) => {
                explicit_end = true;
                self.skip();
                span
            }
            Token(span, _) => span,
        };

        if self.keep_tags {
            // Never persist default handles across document boundaries. Allowing `%TAG !! ...`
            // or `%TAG ! ...` to leak into following documents lets earlier documents alter how
            // explicit tags are interpreted later on.
            self.tags.remove("!!");
            self.tags.remove("");
        } else {
            self.tags.clear();
        }
        if explicit_end {
            self.state = State::ImplicitDocumentStart;
        } else {
            if let Token(
                span,
                TokenType::VersionDirective(..)
                | TokenType::TagDirective(..)
                | TokenType::ReservedDirective(..),
            ) = *self.peek_token()?
            {
                return Err(ScanError::new_str(
                    span.start,
                    "missing explicit document end marker before directive",
                ));
            }
            self.state = State::DocumentStart;
        }

        Ok((Event::DocumentEnd, span))
    }

    fn register_anchor(&mut self, name: Cow<'input, str>, mark: &Span) -> Result<usize, ScanError> {
        // anchors can be overridden/reused
        // if self.anchors.contains_key(name) {
        //     return Err(ScanError::new_str(*mark,
        //         "while parsing anchor, found duplicated anchor"));
        // }
        let new_id = self.anchor_id_count;
        self.anchor_id_count = self.anchor_id_count.checked_add(1).ok_or_else(|| {
            ScanError::new_str(
                mark.start,
                "while parsing anchor, anchor count exceeded supported limit",
            )
        })?;
        self.anchors.insert(name, new_id);
        Ok(new_id)
    }

    #[allow(clippy::too_many_lines)]
    fn parse_node<'a>(&mut self, block: bool, indentless_sequence: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        let mut anchor_id = 0;
        let mut tag = None;
        match *self.peek_token()? {
            Token(_, TokenType::Alias(_)) => {
                self.pop_state();
                if let Token(span, TokenType::Alias(name)) = self.fetch_token() {
                    match self.anchors.get(&*name) {
                        None => {
                            return Err(ScanError::new_str(
                                span.start,
                                "while parsing node, found unknown anchor",
                            ))
                        }
                        Some(id) => return Ok((Event::Alias(*id), span)),
                    }
                }
                unreachable!()
            }
            Token(_, TokenType::Anchor(_)) => {
                if let Token(span, TokenType::Anchor(name)) = self.fetch_token() {
                    anchor_id = self.register_anchor(name, &span)?;
                    if let TokenType::Tag(..) = self.peek_token()?.1 {
                        if let TokenType::Tag(handle, suffix) = self.fetch_token().1 {
                            tag = Some(self.resolve_tag(span, &handle, suffix)?);
                        } else {
                            unreachable!()
                        }
                    }
                } else {
                    unreachable!()
                }
            }
            Token(mark, TokenType::Tag(..)) => {
                if let TokenType::Tag(handle, suffix) = self.fetch_token().1 {
                    tag = Some(self.resolve_tag(mark, &handle, suffix)?);
                    if let TokenType::Anchor(_) = &self.peek_token()?.1 {
                        if let Token(mark, TokenType::Anchor(name)) = self.fetch_token() {
                            anchor_id = self.register_anchor(name, &mark)?;
                        } else {
                            unreachable!()
                        }
                    }
                } else {
                    unreachable!()
                }
            }
            _ => {}
        }
        match *self.peek_token()? {
            Token(mark, TokenType::BlockEntry) if indentless_sequence => {
                self.state = State::IndentlessSequenceEntry;
                Ok((Event::SequenceStart(anchor_id, tag), mark))
            }
            Token(_, TokenType::Scalar(..)) => {
                self.pop_state();
                if let Token(mark, TokenType::Scalar(style, v)) = self.fetch_token() {
                    Ok((Event::Scalar(v, style, anchor_id, tag), mark))
                } else {
                    unreachable!()
                }
            }
            Token(mark, TokenType::FlowSequenceStart) => {
                self.state = State::FlowSequenceFirstEntry;
                Ok((Event::SequenceStart(anchor_id, tag), mark))
            }
            Token(mark, TokenType::FlowMappingStart) => {
                self.state = State::FlowMappingFirstKey;
                Ok((Event::MappingStart(anchor_id, tag), mark))
            }
            Token(mark, TokenType::BlockSequenceStart) if block => {
                self.state = State::BlockSequenceFirstEntry;
                Ok((Event::SequenceStart(anchor_id, tag), mark))
            }
            Token(mark, TokenType::BlockMappingStart) if block => {
                self.state = State::BlockMappingFirstKey;
                Ok((Event::MappingStart(anchor_id, tag), mark))
            }
            // ex 7.2, an empty scalar can follow a secondary tag
            Token(mark, _) if tag.is_some() || anchor_id > 0 => {
                self.pop_state();
                Ok((Event::empty_scalar_with_anchor(anchor_id, tag), mark))
            }
            Token(span, _) => {
                let info = match self.state {
                    State::FlowSequenceFirstEntry | State::FlowSequenceEntry => {
                        "unexpected EOF while parsing a flow sequence"
                    }
                    State::FlowMappingFirstKey
                    | State::FlowMappingKey
                    | State::FlowMappingValue
                    | State::FlowMappingEmptyValue => "unexpected EOF while parsing a flow mapping",
                    State::FlowSequenceEntryMappingKey
                    | State::FlowSequenceEntryMappingValue
                    | State::FlowSequenceEntryMappingEnd => {
                        "unexpected EOF while parsing an implicit flow mapping"
                    }
                    State::BlockSequenceFirstEntry | State::BlockSequenceEntry => {
                        "unexpected EOF while parsing a block sequence"
                    }
                    State::BlockMappingFirstKey
                    | State::BlockMappingKey
                    | State::BlockMappingValue => "unexpected EOF while parsing a block mapping",
                    _ => "while parsing a node, did not find expected node content",
                };
                Err(ScanError::new_str(span.start, info))
            }
        }
    }

    fn block_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        // skip BlockMappingStart
        if first {
            let _ = self.peek_token()?;
            //self.marks.push(tok.0);
            self.skip();
        }
        match *self.peek_token()? {
            Token(_, TokenType::Key) => {
                // Indentation is only meaningful for block mapping keys.
                if let Token(key_span, TokenType::Key) = *self.peek_token()? {
                    self.pending_key_indent = Some(key_span.start.col());
                }
                self.skip();
                if let Token(mark, TokenType::Key | TokenType::Value | TokenType::BlockEnd) =
                    *self.peek_token()?
                {
                    self.state = State::BlockMappingValue;
                    // empty scalar
                    Ok((Event::empty_scalar(), mark))
                } else {
                    self.push_state(State::BlockMappingValue);
                    self.parse_node(true, true)
                }
            }
            // XXX(chenyh): libyaml failed to parse spec 1.2, ex8.18
            Token(mark, TokenType::Value) => {
                self.state = State::BlockMappingValue;
                Ok((Event::empty_scalar(), mark))
            }
            Token(mark, TokenType::BlockEnd) => {
                self.pop_state();
                self.skip();
                Ok((Event::MappingEnd, mark))
            }
            Token(span, _) => Err(ScanError::new_str(
                span.start,
                "while parsing a block mapping, did not find expected key",
            )),
        }
    }

    fn block_mapping_value<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match *self.peek_token()? {
            Token(mark, TokenType::Value) => {
                self.skip();
                if let Token(_, TokenType::Key | TokenType::Value | TokenType::BlockEnd) =
                    *self.peek_token()?
                {
                    self.state = State::BlockMappingKey;
                    // empty scalar
                    Ok((Event::empty_scalar(), mark))
                } else {
                    self.push_state(State::BlockMappingKey);
                    self.parse_node(true, true)
                }
            }
            Token(mark, _) => {
                self.state = State::BlockMappingKey;
                // empty scalar
                Ok((Event::empty_scalar(), mark))
            }
        }
    }

    fn flow_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        if first {
            let _ = self.peek_token()?;
            self.skip();
        }
        let span: Span = if let Token(mark, TokenType::FlowMappingEnd) = *self.peek_token()? {
            mark
        } else {
            if !first {
                match *self.peek_token()? {
                    Token(_, TokenType::FlowEntry) => self.skip(),
                    Token(span, _) => {
                        return Err(ScanError::new_str(
                            span.start,
                            "while parsing a flow mapping, did not find expected ',' or '}'",
                        ))
                    }
                }
            }

            match *self.peek_token()? {
                Token(_, TokenType::Key) => {
                    self.skip();
                    if let Token(
                        mark,
                        TokenType::Value | TokenType::FlowEntry | TokenType::FlowMappingEnd,
                    ) = *self.peek_token()?
                    {
                        self.state = State::FlowMappingValue;
                        return Ok((Event::empty_scalar(), mark));
                    }
                    self.push_state(State::FlowMappingValue);
                    return self.parse_node(false, false);
                }
                Token(marker, TokenType::Value) => {
                    self.state = State::FlowMappingValue;
                    return Ok((Event::empty_scalar(), marker));
                }
                Token(_, TokenType::FlowMappingEnd) => (),
                _ => {
                    self.push_state(State::FlowMappingEmptyValue);
                    return self.parse_node(false, false);
                }
            }

            self.peek_token()?.0
        };

        self.pop_state();
        self.skip();
        Ok((Event::MappingEnd, span))
    }

    fn flow_mapping_value<'a>(&mut self, empty: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        let span: Span = {
            if empty {
                let Token(mark, _) = *self.peek_token()?;
                self.state = State::FlowMappingKey;
                return Ok((Event::empty_scalar(), mark));
            }
            match *self.peek_token()? {
                Token(span, TokenType::Value) => {
                    self.skip();
                    match self.peek_token()?.1 {
                        TokenType::FlowEntry | TokenType::FlowMappingEnd => {}
                        _ => {
                            self.push_state(State::FlowMappingKey);
                            return self.parse_node(false, false);
                        }
                    }
                    span
                }
                Token(marker, _) => marker,
            }
        };

        self.state = State::FlowMappingKey;
        Ok((Event::empty_scalar(), span))
    }

    fn flow_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        // skip FlowMappingStart
        if first {
            let _ = self.peek_token()?;
            //self.marks.push(tok.0);
            self.skip();
        }
        match *self.peek_token()? {
            Token(mark, TokenType::FlowSequenceEnd) => {
                self.pop_state();
                self.skip();
                return Ok((Event::SequenceEnd, mark));
            }
            Token(_, TokenType::FlowEntry) if !first => {
                self.skip();
            }
            Token(span, _) if !first => {
                return Err(ScanError::new_str(
                    span.start,
                    "while parsing a flow sequence, expected ',' or ']'",
                ));
            }
            _ => { /* next */ }
        }
        match *self.peek_token()? {
            Token(mark, TokenType::FlowSequenceEnd) => {
                self.pop_state();
                self.skip();
                Ok((Event::SequenceEnd, mark))
            }
            Token(mark, TokenType::Key) => {
                self.state = State::FlowSequenceEntryMappingKey;
                self.skip();
                Ok((Event::MappingStart(0, None), mark))
            }
            _ => {
                self.push_state(State::FlowSequenceEntry);
                self.parse_node(false, false)
            }
        }
    }

    fn indentless_sequence_entry<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match *self.peek_token()? {
            Token(mark, TokenType::BlockEntry) => {
                self.skip();
                if let Token(
                    _,
                    TokenType::BlockEntry | TokenType::Key | TokenType::Value | TokenType::BlockEnd,
                ) = *self.peek_token()?
                {
                    self.state = State::IndentlessSequenceEntry;
                    Ok((Event::empty_scalar(), mark))
                } else {
                    self.push_state(State::IndentlessSequenceEntry);
                    self.parse_node(true, false)
                }
            }
            Token(mark, _) => {
                self.pop_state();
                Ok((Event::SequenceEnd, mark))
            }
        }
    }

    fn block_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
    where
        'input: 'a,
    {
        // BLOCK-SEQUENCE-START
        if first {
            let _ = self.peek_token()?;
            //self.marks.push(tok.0);
            self.skip();
        }
        match *self.peek_token()? {
            Token(mark, TokenType::BlockEnd) => {
                self.pop_state();
                self.skip();
                Ok((Event::SequenceEnd, mark))
            }
            Token(mark, TokenType::BlockEntry) => {
                self.skip();
                if let Token(_, TokenType::BlockEntry | TokenType::BlockEnd) = *self.peek_token()? {
                    self.state = State::BlockSequenceEntry;
                    Ok((Event::empty_scalar(), mark))
                } else {
                    self.push_state(State::BlockSequenceEntry);
                    self.parse_node(true, false)
                }
            }
            Token(span, _) => Err(ScanError::new_str(
                span.start,
                "while parsing a block collection, did not find expected '-' indicator",
            )),
        }
    }

    fn flow_sequence_entry_mapping_key<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        if let Token(mark, TokenType::FlowEntry | TokenType::FlowSequenceEnd) =
            *self.peek_token()?
        {
            self.state = State::FlowSequenceEntryMappingValue;
            Ok((Event::empty_scalar(), mark))
        } else {
            self.push_state(State::FlowSequenceEntryMappingValue);
            self.parse_node(false, false)
        }
    }

    fn flow_sequence_entry_mapping_value<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        match *self.peek_token()? {
            Token(_, TokenType::Value) => {
                self.skip();
                self.state = State::FlowSequenceEntryMappingValue;
                let Token(span, ref tok) = *self.peek_token()?;
                if matches!(tok, TokenType::FlowEntry | TokenType::FlowSequenceEnd) {
                    self.state = State::FlowSequenceEntryMappingEnd;
                    Ok((Event::empty_scalar(), Span::empty(span.start)))
                } else {
                    self.push_state(State::FlowSequenceEntryMappingEnd);
                    self.parse_node(false, false)
                }
            }
            Token(mark, _) => {
                self.state = State::FlowSequenceEntryMappingEnd;
                Ok((Event::empty_scalar(), mark))
            }
        }
    }

    #[allow(clippy::unnecessary_wraps)]
    fn flow_sequence_entry_mapping_end<'a>(&mut self) -> ParseResult<'a>
    where
        'input: 'a,
    {
        self.state = State::FlowSequenceEntry;
        let Token(span, _) = *self.peek_token()?;
        Ok((Event::MappingEnd, Span::empty(span.start)))
    }

    /// Resolve a tag from the handle and the suffix.
    fn resolve_tag(
        &self,
        span: Span,
        handle: &Cow<'input, str>,
        suffix: Cow<'input, str>,
    ) -> Result<Cow<'input, Tag>, ScanError> {
        let suffix = suffix.into_owned();
        let tag = if handle == "!!" {
            // "!!" is a shorthand for "tag:yaml.org,2002:". However, that default can be
            // overridden.
            Tag {
                handle: self
                    .tags
                    .get("!!")
                    .map_or_else(|| "tag:yaml.org,2002:".to_string(), ToString::to_string),
                suffix,
            }
        } else if handle.is_empty() && suffix == "!" {
            // "!" introduces a local tag. Local tags may have their prefix overridden.
            match self.tags.get("") {
                Some(prefix) => Tag {
                    handle: prefix.clone(),
                    suffix,
                },
                None => Tag {
                    handle: String::new(),
                    suffix,
                },
            }
        } else {
            // Lookup handle in our tag directives.
            let prefix = self.tags.get(&**handle);
            if let Some(prefix) = prefix {
                Tag {
                    handle: prefix.clone(),
                    suffix,
                }
            } else {
                // Otherwise, it may be a local handle. With a local handle, the handle is set to
                // "!" and the suffix to whatever follows it ("!foo" -> ("!", "foo")).
                // If the handle is of the form "!foo!", this cannot be a local handle and we need
                // to error.
                if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
                    return Err(ScanError::new_str(span.start, "the handle wasn't declared"));
                }
                Tag {
                    handle: handle.to_string(),
                    suffix,
                }
            }
        };
        Ok(Cow::Owned(tag))
    }
}

impl<'input, T: BorrowedInput<'input>> ParserTrait<'input> for Parser<'input, T> {
    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
        if let Some(ref x) = self.current {
            Some(Ok(x))
        } else {
            if self.stream_end_emitted {
                return None;
            }
            match self.next_event_impl() {
                Ok(token) => self.current = Some(token),
                Err(e) => return Some(Err(e)),
            }
            self.current.as_ref().map(Ok)
        }
    }

    fn next_event(&mut self) -> Option<ParseResult<'input>> {
        if self.stream_end_emitted {
            return None;
        }

        let tok = self.next_event_impl();
        if matches!(tok, Ok((Event::StreamEnd, _))) {
            self.stream_end_emitted = true;
        }
        Some(tok)
    }

    fn load<R: SpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), ScanError> {
        let mut recv = InfallibleSpannedReceiver(recv);
        into_scan_result(ParserTrait::try_load(self, &mut recv, multi))
    }

    fn try_load<R: TrySpannedEventReceiver<'input>>(
        &mut self,
        recv: &mut R,
        multi: bool,
    ) -> Result<(), TryLoadError<R::Error>> {
        let stream_start_buffered = matches!(self.current.as_ref(), Some((Event::StreamStart, _)));
        if !self.scanner.stream_started() || stream_start_buffered {
            let (ev, span) = self.next_event_impl()?;
            if ev != Event::StreamStart {
                return Err(TryLoadError::Scan(ScanError::new_str(
                    span.start,
                    "did not find expected <stream-start>",
                )));
            }
            try_emit(recv, ev, span)?;
        }

        if self.scanner.stream_ended() {
            // XXX has parsed?
            try_emit(recv, Event::StreamEnd, Span::empty(self.scanner.mark()))?;
            return Ok(());
        }
        loop {
            let (ev, span) = self.next_event_impl()?;
            if ev == Event::StreamEnd {
                try_emit(recv, ev, span)?;
                return Ok(());
            }
            // clear anchors before a new document
            self.anchors.clear();
            self.try_load_document(ev, span, recv)?;
            if !multi {
                break;
            }
        }
        Ok(())
    }
}

impl<'input, T: BorrowedInput<'input>> Iterator for Parser<'input, T> {
    type Item = Result<(Event<'input>, Span), ScanError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_event()
    }
}

#[cfg(test)]
mod test {
    use alloc::{
        borrow::ToOwned,
        string::{String, ToString},
        vec::Vec,
    };

    use crate::scanner::{ScalarStyle, Span};

    use super::{
        Event, EventReceiver, Parser, Tag, TryEventReceiver, TryLoadError, TrySpannedEventReceiver,
    };

    #[derive(Default)]
    struct CollectingSink<'input> {
        events: Vec<Event<'input>>,
    }

    impl<'input> EventReceiver<'input> for CollectingSink<'input> {
        fn on_event(&mut self, ev: Event<'input>) {
            self.events.push(ev);
        }
    }

    fn first_error_info(input: &str) -> String {
        for event in Parser::new_from_str(input) {
            if let Err(err) = event {
                return err.info().to_owned();
            }
        }
        panic!("expected parser error")
    }

    #[test]
    fn display_resolved_core_tag_without_extra_bang() {
        let tag = Tag {
            handle: "tag:yaml.org,2002:".to_owned(),
            suffix: "str".to_owned(),
        };

        assert_eq!(tag.to_string(), "tag:yaml.org,2002:str");
    }

    #[test]
    fn tag_helpers_distinguish_core_and_local_tags() {
        let core = Tag {
            handle: "tag:yaml.org,2002:".to_owned(),
            suffix: "int".to_owned(),
        };
        let local = Tag {
            handle: "!".to_owned(),
            suffix: "thing".to_owned(),
        };

        assert!(core.is_yaml_core_schema());
        assert!(!local.is_yaml_core_schema());
        assert_eq!(local.to_string(), "!thing");
    }

    #[test]
    fn test_peek_eq_parse() {
        let s = "
a0 bb: val
a1: &x
    b1: 4
    b2: d
a2: 4
a3: [1, 2, 3]
a4:
    - [a1, a2]
    - 2
a5: *x
";
        let mut p = Parser::new_from_str(s);
        loop {
            let event_peek = p.peek().unwrap().unwrap().clone();
            let event = p.next_event().unwrap().unwrap();
            assert_eq!(event, event_peek);
            if event.0 == Event::StreamEnd {
                break;
            }
        }
    }

    #[test]
    fn test_peek_and_next_return_none_after_stream_end() {
        let mut parser = Parser::new_from_str("");

        assert!(matches!(
            parser.next_event().unwrap().unwrap().0,
            Event::StreamStart
        ));
        assert!(matches!(
            parser.next_event().unwrap().unwrap().0,
            Event::StreamEnd
        ));
        assert!(parser.next_event().is_none());
        assert!(parser.peek().is_none());
    }

    #[test]
    fn test_load_after_stream_already_ended_emits_stream_end() {
        let mut parser = Parser::new_from_str("");
        while parser.next_event().is_some() {}

        let mut sink = CollectingSink::default();
        parser.load(&mut sink, true).unwrap();

        assert_eq!(sink.events, vec![Event::StreamEnd]);
    }

    #[test]
    fn test_load_visits_nested_collection_events() {
        let mut parser = Parser::new_from_str("root:\n  - item: value\n  - [a, b]\n");
        let mut sink = CollectingSink::default();

        parser.load(&mut sink, true).unwrap();

        assert_eq!(
            sink.events,
            vec![
                Event::StreamStart,
                Event::DocumentStart(false),
                Event::MappingStart(0, None),
                Event::Scalar("root".into(), ScalarStyle::Plain, 0, None),
                Event::SequenceStart(0, None),
                Event::MappingStart(0, None),
                Event::Scalar("item".into(), ScalarStyle::Plain, 0, None),
                Event::Scalar("value".into(), ScalarStyle::Plain, 0, None),
                Event::MappingEnd,
                Event::SequenceStart(0, None),
                Event::Scalar("a".into(), ScalarStyle::Plain, 0, None),
                Event::Scalar("b".into(), ScalarStyle::Plain, 0, None),
                Event::SequenceEnd,
                Event::SequenceEnd,
                Event::MappingEnd,
                Event::DocumentEnd,
                Event::StreamEnd,
            ]
        );
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    enum ValidationError {
        ForbiddenValue,
    }

    struct FailingSink<'input> {
        events: Vec<Event<'input>>,
    }

    impl<'input> TryEventReceiver<'input> for FailingSink<'input> {
        type Error = ValidationError;

        fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
            let should_fail = matches!(&ev, Event::Scalar(value, ..) if value.as_ref() == "bad");
            self.events.push(ev);
            if should_fail {
                Err(ValidationError::ForbiddenValue)
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn test_try_load_stops_on_receiver_error() {
        let mut parser = Parser::new_from_str("ok: bad\nafter: value\n");
        let mut sink = FailingSink { events: Vec::new() };

        let err = parser.try_load(&mut sink, true).unwrap_err();

        assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenValue));
        assert!(sink
            .events
            .iter()
            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "ok")));
        assert!(sink
            .events
            .iter()
            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "bad")));
        assert!(!sink
            .events
            .iter()
            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "after")));
    }

    struct SpannedFailingSink {
        failed_span: Option<Span>,
    }

    impl<'input> TrySpannedEventReceiver<'input> for SpannedFailingSink {
        type Error = Span;

        fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
            if matches!(ev, Event::Scalar(value, ..) if value.as_ref() == "bad") {
                self.failed_span = Some(span);
                Err(span)
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn test_try_load_spanned_receiver_gets_span() {
        let mut parser = Parser::new_from_str("value: bad\n");
        let mut sink = SpannedFailingSink { failed_span: None };

        let err = parser.try_load(&mut sink, false).unwrap_err();

        let TryLoadError::Receiver(span) = err else {
            panic!("expected receiver error");
        };

        assert_eq!(Some(span), sink.failed_span);
        assert!(!span.is_empty());
    }

    struct NeverFails {
        count: usize,
    }

    impl<'input> TryEventReceiver<'input> for NeverFails {
        type Error = ValidationError;

        fn on_event(&mut self, _ev: Event<'input>) -> Result<(), Self::Error> {
            self.count += 1;
            Ok(())
        }
    }

    #[test]
    fn test_try_load_returns_scan_error() {
        let mut parser = Parser::new_from_str("%YAML 1.2\n%YAML 1.2\n---\n");
        let mut sink = NeverFails { count: 0 };

        let err = parser.try_load(&mut sink, true).unwrap_err();

        let TryLoadError::Scan(err) = err else {
            panic!("expected scan error");
        };
        assert_eq!(err.info(), "duplicate version directive");
    }

    #[test]
    fn test_try_load_after_stream_already_ended_emits_stream_end() {
        let mut parser = Parser::new_from_str("");
        while parser.next_event().is_some() {}

        let mut sink = FailingSink { events: Vec::new() };
        parser.try_load(&mut sink, true).unwrap();

        assert_eq!(sink.events, vec![Event::StreamEnd]);
    }

    #[test]
    fn test_load_single_document_stops_before_next_document() {
        let mut parser = Parser::new_from_str("a: 1\n---\nb: 2\n");
        let mut sink = CollectingSink::default();

        parser.load(&mut sink, false).unwrap();

        assert!(sink
            .events
            .iter()
            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "a")));
        assert!(!sink
            .events
            .iter()
            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "b")));
        assert!(matches!(sink.events.last(), Some(Event::DocumentEnd)));
    }

    #[test]
    fn test_duplicate_version_directive_errors() {
        assert_eq!(
            first_error_info("%YAML 1.2\n%YAML 1.2\n---\n"),
            "duplicate version directive"
        );
    }

    #[test]
    fn test_duplicate_tag_directive_errors() {
        assert_eq!(
            first_error_info("%TAG !t! tag:test,2024:\n%TAG !t! tag:other,2024:\n---\n"),
            "the TAG directive must only be given at most once per handle in the same document"
        );
    }

    #[test]
    fn test_directive_after_implicit_document_requires_explicit_end() {
        assert_eq!(
            first_error_info("---\nkey: value\n%YAML 1.2\n---\n"),
            "missing explicit document end marker before directive"
        );
    }

    #[test]
    fn test_anchor_offset_overflow_reports_error() {
        let mut parser = Parser::new_from_str("&a value");
        parser.set_anchor_offset(usize::MAX);

        let err = parser
            .find_map(Result::err)
            .expect("anchor registration should overflow");

        assert_eq!(
            err.info(),
            "while parsing anchor, anchor count exceeded supported limit"
        );
    }

    #[test]
    fn test_alias_resolves_to_registered_anchor_id() {
        let events = Parser::new_from_str("- &a value\n- *a\n")
            .map(|event| event.unwrap().0)
            .collect::<Vec<_>>();

        assert!(events.iter().any(|event| matches!(event, Event::Alias(1))));
    }

    #[test]
    fn test_anchor_then_tag_applies_both_to_scalar() {
        let events = Parser::new_from_str("&a !!str value")
            .map(|event| event.unwrap().0)
            .collect::<Vec<_>>();

        let Some(Event::Scalar(value, _, anchor_id, Some(tag))) = events
            .iter()
            .find(|event| matches!(event, Event::Scalar(value, ..) if value == "value"))
        else {
            panic!("expected tagged anchored scalar");
        };

        assert_eq!(value, "value");
        assert_eq!(*anchor_id, 1);
        assert_eq!(tag.handle, "tag:yaml.org,2002:");
        assert_eq!(tag.suffix, "str");
    }

    #[test]
    fn test_tag_then_anchor_applies_both_to_scalar() {
        let events = Parser::new_from_str("!!str &a value")
            .map(|event| event.unwrap().0)
            .collect::<Vec<_>>();

        let Some(Event::Scalar(value, _, anchor_id, Some(tag))) = events
            .iter()
            .find(|event| matches!(event, Event::Scalar(value, ..) if value == "value"))
        else {
            panic!("expected tagged anchored scalar");
        };

        assert_eq!(value, "value");
        assert_eq!(*anchor_id, 1);
        assert_eq!(tag.handle, "tag:yaml.org,2002:");
        assert_eq!(tag.suffix, "str");
    }

    #[test]
    fn test_multiple_tag_directives_are_kept_within_document() {
        let text = r"
%TAG !a! tag:a,2024:
%TAG !b! tag:b,2024:
---
first: !a!x foo
second: !b!y bar
";

        let mut seen_a = false;
        let mut seen_b = false;
        for event in Parser::new_from_str(text) {
            let (event, _) = event.unwrap();
            if let Event::Scalar(_, _, _, Some(tag)) = event {
                if tag.handle == "tag:a,2024:" {
                    seen_a = true;
                } else if tag.handle == "tag:b,2024:" {
                    seen_b = true;
                }
            }
        }

        assert!(seen_a);
        assert!(seen_b);
    }

    #[test]
    fn test_tags_are_cleared_when_next_document_has_no_directives() {
        let text = r"
%TAG !t! tag:test,2024:
--- !t!1
foo
--- !t!2
bar
";

        let mut parser = Parser::new_from_str(text);
        for event in parser.by_ref() {
            let (event, _) = event.unwrap();
            if let Event::DocumentEnd = event {
                break;
            }
        }

        match parser.next().unwrap().unwrap().0 {
            Event::DocumentStart(true) => {}
            _ => panic!("expected explicit second document start"),
        }

        let err = parser.next().unwrap().unwrap_err();
        assert!(format!("{err}").contains("the handle wasn't declared"));
    }

    #[test]
    fn test_pull_parser_clears_anchors_between_documents() {
        let mut parser = Parser::new_from_str(
            "--- &a value
--- *a
",
        );

        for event in parser.by_ref() {
            let (event, _) = event.unwrap();
            if matches!(event, Event::DocumentEnd) {
                break;
            }
        }

        match parser.next().unwrap().unwrap().0 {
            Event::DocumentStart(true) => {}
            _ => panic!("expected explicit second document start"),
        }

        let err = parser.next().unwrap().unwrap_err();
        assert!(format!("{err}").contains("unknown anchor"));
    }

    #[test]
    fn test_keep_tags_across_multiple_documents() {
        let text = r#"
%YAML 1.1
%TAG !t! tag:test,2024:
--- !t!1 &1
foo: "bar"
--- !t!2 &2
baz: "qux"
"#;
        for x in Parser::new_from_str(text).keep_tags(true) {
            let x = x.unwrap();
            if let Event::MappingStart(_, tag) = x.0 {
                let tag = tag.unwrap();
                assert_eq!(tag.handle, "tag:test,2024:");
            }
        }

        for x in Parser::new_from_str(text).keep_tags(false) {
            if x.is_err() {
                // Test successful
                return;
            }
        }
        panic!("Test failed, did not encounter error")
    }

    #[test]
    fn test_flow_sequence_mapping_allows_empty_key() {
        let parser = Parser::new_from_str("[?: value]");
        for event in parser {
            event.expect("parser should accept flow sequence mappings with empty keys");
        }
    }

    #[test]
    fn test_keep_tags_does_not_persist_default_tag_handles() {
        let text = "%TAG !! tag:evil,2024:\n--- !!int 1\n--- !!int 2\n";

        let mut int_tags = Vec::new();
        for event in Parser::new_from_str(text).keep_tags(true) {
            let event = event.unwrap().0;
            if let Event::Scalar(_, _, _, Some(tag)) = event {
                if tag.suffix == "int" {
                    int_tags.push(tag.handle.clone());
                }
            }
        }

        assert_eq!(int_tags, vec!["tag:evil,2024:", "tag:yaml.org,2002:"]);
    }

    #[test]
    fn test_load_after_peek_stream_start() {
        #[derive(Default)]
        struct Sink<'input> {
            events: Vec<Event<'input>>,
        }

        impl<'input> EventReceiver<'input> for Sink<'input> {
            fn on_event(&mut self, ev: Event<'input>) {
                self.events.push(ev);
            }
        }

        let mut parser = Parser::new_from_str("key: value\n");
        let mut sink = Sink::default();

        assert_eq!(parser.peek().unwrap().unwrap().0, Event::StreamStart);
        parser.load(&mut sink, false).unwrap();

        assert!(matches!(sink.events.first(), Some(Event::StreamStart)));
        assert!(matches!(sink.events.get(1), Some(Event::DocumentStart(_))));
    }
}