tabnas-yaml 0.5.34

A core-subset YAML grammar plugin for the tabnas parsing engine
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
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
/* Copyright (c) 2021-2026 Richard Rodger, MIT License */

//! A core-subset YAML grammar plugin for the
//! [`tabnas`](https://github.com/tabnas/parser) parsing engine.
//!
//! Unlike most tabnas grammars this one layers on
//! [`tabnas_jsonic`](https://github.com/tabnas/jsonic) rather than on the
//! bare engine: YAML's flow collections are relaxed JSON, and the block
//! forms are added around jsonic's `val` / `map` / `list` / `pair` /
//! `elem` rules.
//!
//! ```
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let value = tabnas_yaml::parse("name: Alice\nitems:\n  - one\n  - two\n")?;
//!     assert_eq!(
//!         value.to_string(),
//!         r#"{"name":"Alice","items":["one","two"]}"#
//!     );
//!     Ok(())
//! }
//! ```

#![forbid(unsafe_code)]
// The engine's error type is 664 bytes and every entry point returns it,
// as the other tabnas crates' entry points do.
#![allow(clippy::result_large_err)]

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};

use indexmap::IndexMap;
use serde_json::json;
use tabnas::{
    Context, GrammarSpec, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_NR, TIN_ST, TIN_TX,
    TIN_VL,
};

mod lex;
mod source;
mod state;
mod text;

/// Every `rust` fence in the README is compiled and run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

/// VERSION is this package's version. It MUST equal `ts/package.json`
/// "version": the release orchestrator rewrites all three constants, and
/// `tests/version_test.rs` fails the build if they drift. Mirrors
/// `const VERSION` in `ts/src/yaml.ts` and `go/yaml.go`.
pub const VERSION: &str = "0.5.34";

/// The plugin name, which is also the key its options sit under.
const PLUGIN_NAME: &str = "yaml";

/// The error code for an alias whose anchor does not occur before it.
/// Its template and hint are in [`options_document`].
pub(crate) const UNDEFINED_ALIAS: &str = "yaml_undefined_alias";

/// The error code for an alias inside the node its anchor names.
pub(crate) const RECURSIVE_ALIAS: &str = "yaml_recursive_alias";

/// Set on the instance once the plugin has installed. The install guard
/// reads it together with the instance's rules ([`grammar_installed`]):
/// a derived child inherits this decoration before it has any rule of its
/// own, and a rule of the grammar's name from elsewhere comes without it.
const INSTALLED: &str = "yaml-installed";

/// Errors this crate returns are the engine's, re-exported so a caller
/// does not need `tabnas` in scope to name them.
pub use tabnas::TabnasError as YamlError;

// --- BEGIN EMBEDDED yaml-grammar.jsonic ---
const GRAMMAR_TEXT: &str = r##"
# YAML Grammar Definition
# Parsed by a standard Tabnas instance and passed to tabnas.grammar()
# Function references (@ prefixed) are resolved against the refs map.
# State handlers (bo/ao/bc/ac) remain wired in code, since they use
# closures over per-parse state (anchors, pendingAnchors, etc.).

{
  # Amend val rule: YAML indent/element-marker handling.
  rule: val: open: {
    alts: [
      # Doc-frame markers between docs mean an empty value here; back up so
      # the stream rule consumes the marker and starts the next document.
      { s: '#DS' b: 1 a: '@val-set-null' g: yaml }
      { s: '#DE' b: 1 a: '@val-set-null' g: yaml }
      { s: '#DR' b: 1 a: '@val-set-null' g: yaml }
      # Indent followed by content: push indent rule.
      { s: '#IN' c: '@val-indent-deeper' p: indent a: '@val-set-in-from-o0' g: yaml }
      # Same indent followed by element marker: list value at map level.
      { s: ['#IN' '#EL'] c: '@val-indent-eq-parent' p: yamlBlockList a: '@val-set-in-from-o0' g: yaml }
      # End of input means empty value.
      { s: '#ZZ' b: 1 a: '@val-set-null' g: yaml }
      # Same or lesser indent after a colon means empty value — backtrack.
      { s: '#IN' b: 1 u: { yamlEmpty: true } g: yaml }
      # This value is a list: a sequence's entry, or a document's root. A
      # block sequence cannot start on the line of the key it is the value
      # of (key: - a), so a pair's value is not one here.
      { s: '#EL' c: '@val-not-pair-value' p: yamlBlockList a: '@val-set-el-in' g: yaml }
    ]
    inject: { append: false }
  }
  rule: val: close: {
    alts: [
      # Doc-frame markers terminate val; back up for the stream rule.
      { s: '#DS' b: 1 g: 'yaml,end' }
      { s: '#DE' b: 1 g: 'yaml,end' }
      { s: '#DR' b: 1 g: 'yaml,end' }
      { s: '#IN' b: 1 g: 'yaml,close' }
    ]
    inject: { append: false }
  }

  # Indent rule: start for block content at a given indent.
  rule: indent: open: [
    # Key pair => map.
    { s: ['#KEY' '#CL'] p: map b: 2 g: yaml }
    # Element marker => block sequence. yamlBlockList, not jsonic's list:
    # list reads a '[' as its own opening bracket, so a flow sequence as the
    # first item (k:\n  - [1, 2]) became the block sequence itself, or
    # failed at the next item (tabnas/yaml#88).
    { s: '#EL' p: yamlBlockList g: yaml }
    # Flow collection as a block-mapping value on the FOLLOWING line:
    #     required:
    #       [a, b, c]
    # Valid YAML 1.2, and the inline spelling has always worked. The
    # indent rule opens at the deeper indent and meets a
    # flow opener, which only the val rule knows how to read, so hand it back
    # one token so val sees the bracket or brace itself.
    { s: '#OS' p: val b: 1 g: yaml }
    { s: '#OB' p: val b: 1 g: yaml }
    # Plain value after indent (for nested scalars).
    { s: '#KEY' a: '@indent-plain-value' g: yaml }
  ]

  # YAML block list: handles "- " sequences without consuming "[".
  rule: yamlBlockList: open: [
    # Element value is a key-value map: - key: val
    { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
    # Default: push to val for the element's value.
    { p: val g: yaml }
  ]
  rule: yamlBlockList: close: [
    # Doc-frame markers terminate list; back up for the stream rule.
    { s: '#DS' b: 1 g: 'yaml,end' }
    { s: '#DE' b: 1 g: 'yaml,end' }
    { s: '#DR' b: 1 g: 'yaml,end' }
    # Indent followed by element marker: next element at same level.
    { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
    # Same or lesser indent: close list.
    { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
    # Element marker at top level (no preceding newline).
    { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
    { s: '#ZZ' b: 1 g: 'yaml,end' }
  ]

  # Subsequent elements in a yamlBlockList (via rotation).
  rule: yamlBlockElem: open: [
    { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
    { p: val g: yaml }
  ]
  rule: yamlBlockElem: close: [
    # Doc-frame markers terminate elem; back up for the stream rule.
    { s: '#DS' b: 1 g: 'yaml,end' }
    { s: '#DE' b: 1 g: 'yaml,end' }
    { s: '#DR' b: 1 g: 'yaml,end' }
    { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
    { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
    { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
    { s: '#ZZ' b: 1 g: 'yaml,end' }
  ]

  # Amend list rule: close on dedent or same-indent non-element.
  rule: list: close: {
    alts: [
      # Doc-frame markers terminate list; back up for the stream rule.
      { s: '#DS' b: 1 g: 'yaml,end' }
      { s: '#DE' b: 1 g: 'yaml,end' }
      { s: '#DR' b: 1 g: 'yaml,end' }
      { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
    ]
    inject: { append: false }
  }

  # Amend map rule: same-indent indent continues map with pair.
  rule: map: open: {
    alts: [
      { s: '#IN' c: '@o0-eq-in' r: pair g: yaml }
    ]
    inject: { append: false }
  }
  rule: map: close: {
    alts: [
      # Doc-frame markers terminate map; back up for the stream rule.
      { s: '#DS' b: 1 g: 'yaml,end' }
      { s: '#DE' b: 1 g: 'yaml,end' }
      { s: '#DR' b: 1 g: 'yaml,end' }
      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
    ]
    inject: { append: false }
  }

  # Amend pair rule: end of input ends pair; dedent closes, same-indent repeats.
  # Also handle YAML flow-mapping shapes Tabnas doesn't have natively:
  # - implicit null values: {a, b: c}  — KEY followed directly by CA or CB
  # - explicit-key marker:  {? k : v}  — leading #QM is consumed
  rule: pair: open: {
    alts: [
      { s: ['#KEY' '#CA'] a: '@implicit-null-pair' b: 1 g: yaml }
      { s: ['#KEY' '#CB'] a: '@implicit-null-pair' b: 1 g: yaml }
      { s: ['#QM' '#KEY' '#CL'] p: val u: { pair: true } a: '@qm-pairkey' g: yaml }
      { s: ['#QM' '#KEY' '#CA'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
      { s: ['#QM' '#KEY' '#CB'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
      { s: '#ZZ' b: 1 g: 'yaml,end' }
    ]
    inject: { append: false }
  }
  rule: pair: close: {
    alts: [
      # Doc-frame markers terminate pair; back up for the stream rule.
      { s: '#DS' b: 1 g: 'yaml,end' }
      { s: '#DE' b: 1 g: 'yaml,end' }
      { s: '#DR' b: 1 g: 'yaml,end' }
      { s: '#IN' c: '@t0-eq-in' r: pair g: 'yaml,comma' }
      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
    ]
    inject: { append: false }
  }

  # yamlElemMap: a mapping that starts in a sequence entry, "- key: val",
  # or "[key: val]" in a flow sequence. It only opens the mapping (its
  # before-open action makes the node) and hands the first pair, unread,
  # to yamlElemPair, which reads every pair. A pair rule opening on the
  # open mapping names the member in u.key before it pushes the value's
  # rule, so a consumer that follows rule events has the key before a
  # value that is a collection opens. When the rule that opened the
  # mapping named the first member as well, that consumer was never told
  # the key, and the first member's value opened ahead of it
  # (tabnas/yaml#105).
  rule: yamlElemMap: open: [
    { s: ['#KEY' '#CL'] r: yamlElemPair b: 2 g: yaml }
  ]

  # Every pair in a yamlElemMap, the first included.
  rule: yamlElemPair: open: [
    { s: ['#KEY' '#CL'] p: val a: '@elem-key' g: yaml }
  ]
  rule: yamlElemPair: close: [
    # Doc-frame markers terminate elem-pair; back up for the stream rule.
    { s: '#DS' b: 1 g: 'yaml,end' }
    { s: '#DE' b: 1 g: 'yaml,end' }
    { s: '#DR' b: 1 g: 'yaml,end' }
    { s: '#IN' c: '@t0-eq-map-in' r: yamlElemPair g: 'yaml,comma' }
    { s: '#IN' b: 1 g: 'yaml,close' }
    { s: '#CA' b: 1 g: 'yaml,comma' }
    { s: '#CS' b: 1 g: 'yaml,close' }
    { s: '#CB' b: 1 g: 'yaml,close' }
    { s: '#ZZ' g: 'yaml,end' }
  ]

  # Amend elem rule for YAML sequences ("- key: val" at top level of [ ... ]).
  # Also handle flow-sequence explicit-key entries: [? k : v] is a single-pair
  # map element. Eat the leading #QM, then back up KEY+CL so yamlElemMap
  # consumes them as a normal pair.
  rule: elem: open: {
    alts: [
      { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
      { s: ['#QM' '#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
    ]
    inject: { append: false }
  }
  rule: elem: close: {
    alts: [
      # Doc-frame markers terminate elem; back up for the stream rule.
      { s: '#DS' b: 1 g: 'yaml,end' }
      { s: '#DE' b: 1 g: 'yaml,end' }
      { s: '#DR' b: 1 g: 'yaml,end' }
      { s: ['#IN' '#EL'] c: '@t0-eq-in' r: elem g: 'yaml,comma' }
      { s: '#IN' c: '@t0-eq-in' b: 1 g: 'yaml,close' }
      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
      { s: '#EL' r: elem g: 'yaml,comma' }
    ]
    inject: { append: false }
  }
}
"##;
// --- END EMBEDDED yaml-grammar.jsonic ---

/// The options this plugin takes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct YamlOptions {
    /// When true, a parse returns `{meta, content}` instead of bare
    /// content. `meta` is a per-document `{directives, explicit, ended}`
    /// object for a single document, or an array of them for a stream.
    pub meta: bool,
    /// The schema a plain scalar resolves by. `None`, the default, also
    /// reads the YAML 1.1 booleans (`yes`, `no`, `on`, `off`) and jsonic's
    /// number syntax (`1_000`, `0b11`).
    pub schema: Option<Schema>,
}

/// A schema a plain scalar may be resolved by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Schema {
    /// The YAML 1.2 core schema (YAML 1.2.2, 10.3.2) and no other reading:
    /// the YAML 1.1 booleans are strings, and a number is only a decimal
    /// integer or float, a `0o` octal or a `0x` hexadecimal integer.
    Core,
}

impl Schema {
    /// The schema's name in the option bag.
    fn name(self) -> &'static str {
        match self {
            Schema::Core => "core",
        }
    }
}

impl YamlOptions {
    /// The option bag as the engine's plugin values.
    fn to_value(self) -> Value {
        let mut map = IndexMap::new();
        map.insert("meta".to_string(), Value::Bool(self.meta));
        if let Some(schema) = self.schema {
            map.insert(
                "schema".to_string(),
                Value::String(schema.name().to_string()),
            );
        }
        Value::object(map)
    }
}

/// The schema an option bag names: `None` when it names none, and an
/// error for a name this plugin does not know, so that a misspelling
/// cannot leave the default on.
fn schema_option(options: &Value) -> Result<Option<Schema>, PluginError> {
    let named = match options {
        Value::Object(map) => map.get("schema").cloned(),
        _ => None,
    };
    match named {
        None | Some(Value::Null | Value::Undefined) => Ok(None),
        Some(Value::String(name)) if name == "core" => Ok(Some(Schema::Core)),
        Some(other) => Err(PluginError(format!(
            "yaml: unknown schema {}, expected 'core'",
            other.to_json()
        ))),
    }
}

/// Whether this parse resolves plain scalars by the core schema alone.
pub(crate) fn core_schema(context: &Context) -> bool {
    matches!(
        context.options.plugin.get(PLUGIN_NAME),
        Some(Value::Object(map)) if matches!(map.get("schema"), Some(Value::String(name)) if name == "core")
    )
}

// ---------------------------------------------------------------------
// Value helpers
// ---------------------------------------------------------------------

/// Assign a rule's node: the Rust spelling of TypeScript `r.node = v`.
///
/// A pushed or replaced rule SHARES its parent's node cell, so writing
/// through `rule.node.borrow_mut()` would overwrite the parent's node
/// too. Assigning installs a fresh cell instead. The cell is borrowed
/// directly only to mutate a container the rule genuinely shares.
fn set_node(rule: &mut Rule, value: Value) {
    rule.node = Rc::new(RefCell::new(value));
}

fn map_insert(node: &mut Value, key: String, value: Value) {
    match node {
        Value::Object(map) => {
            Arc::make_mut(map).insert(key, value);
        }
        Value::MapRef(map) => {
            Arc::make_mut(map).value.insert(key, value);
        }
        _ => {}
    }
}

/// Set a member this grammar stores itself, outside the engine's pair
/// rule: a key with no value in a flow mapping, and a sequence entry's
/// pair. A key the mapping holds already is combined as jsonic's `pairval`
/// combines one: through the grammar's `map.merge` when it has one, else
/// merged deep under `map.extend`, the default, else replaced by the later
/// value; an earlier null is replaced. So `- a: {b: 1}` and `a: {c: 2}` in
/// one sequence entry merge as they do at the root, as the canonical
/// TypeScript stores them.
fn store_member(rule: &mut Rule, context: &mut Context, key: String, value: Value) {
    let previous = map_entries(&rule.node.borrow()).and_then(|map| map.get(&key).cloned());
    let value = match previous {
        None | Some(Value::Null) | Some(Value::Undefined) => value,
        Some(previous) => {
            if let Some(merge) = context.options.map.merge.clone() {
                merge(previous, value, rule, context)
            } else if context.options.map.extend {
                tabnas_jsonic::deep_merge(previous, value)
            } else {
                value
            }
        }
    };
    map_insert(&mut rule.node.borrow_mut(), key, value);
}

fn map_entries(node: &Value) -> Option<&IndexMap<String, Value>> {
    match node {
        Value::Object(map) => Some(map),
        Value::MapRef(map) => Some(&map.value),
        _ => None,
    }
}

fn list_push(node: &mut Value, value: Value) {
    match node {
        Value::Array(items) => Arc::make_mut(items).push(value),
        Value::ListRef(list) => Arc::make_mut(list).value.push(value),
        _ => {}
    }
}

/// Whether `typeof value === 'object'` would hold in JavaScript, with
/// `null` excluded as the canonical guards exclude it.
fn is_container(value: &Value) -> bool {
    matches!(
        value,
        Value::Object(_) | Value::Array(_) | Value::MapRef(_) | Value::ListRef(_) | Value::Text(_)
    )
}

/// A copy of an anchored value, as an alias presents it, the canonical
/// implementation's `copyAnchored`. An alias is the anchored node again
/// (YAML 1.2.2, 3.2.2.2), so every scalar is kept as it is, a number that
/// is not finite included, where the JSON round trip the canonical
/// implementation once copied with wrote one as null; and every container
/// is rebuilt, so a merge into one alias cannot reach the anchor or another
/// alias.
fn deep_copy(value: &Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut out = IndexMap::new();
            for (key, entry) in map.iter() {
                out.insert(key.clone(), deep_copy(entry));
            }
            Value::object(out)
        }
        Value::MapRef(map) => {
            let mut out = IndexMap::new();
            for (key, entry) in map.value.iter() {
                out.insert(key.clone(), deep_copy(entry));
            }
            Value::object(out)
        }
        Value::Array(items) => Value::array(items.iter().map(deep_copy).collect()),
        Value::ListRef(list) => Value::array(list.value.iter().map(deep_copy).collect()),
        Value::Text(text) => Value::String(text.string.clone()),
        other => other.clone(),
    }
}

/// `String(value)` as JavaScript spells it, which is how a non-string key
/// becomes an object property name.
pub(crate) fn string_of(value: &Value) -> String {
    match value {
        Value::Undefined => "undefined".to_string(),
        Value::Null => "null".to_string(),
        Value::Bool(flag) => flag.to_string(),
        Value::Number(number) => js_number_to_string(*number),
        Value::String(text) => text.clone(),
        Value::Text(text) => text.string.clone(),
        Value::Array(items) => items
            .iter()
            .map(|item| match item {
                Value::Undefined | Value::Null => String::new(),
                other => string_of(other),
            })
            .collect::<Vec<_>>()
            .join(","),
        Value::ListRef(list) => string_of(&Value::array(list.value.clone())),
        Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
    }
}

/// `String(number)` as JavaScript spells it: the shortest digit string
/// that reads back as the same double, in plain decimal while the decimal
/// point stays inside `(-6, 21]` and in exponent form outside it.
fn js_number_to_string(number: f64) -> String {
    if number.is_nan() {
        return "NaN".to_string();
    }
    // Catches -0.0 as well: JavaScript spells both zeros "0".
    if number == 0.0 {
        return "0".to_string();
    }
    if number < 0.0 {
        return format!("-{}", js_number_to_string(-number));
    }
    if number.is_infinite() {
        return "Infinity".to_string();
    }
    let shortest = format!("{number:e}");
    let shortest_k = shortest
        .split_once('e')
        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
        .expect("a finite f64 always formats with an exponent");
    let exponential = format!("{:.*e}", shortest_k - 1, number);
    let (mantissa, exponent) = exponential
        .split_once('e')
        .expect("a finite f64 always formats with an exponent");
    let digits = mantissa
        .chars()
        .filter(|digit| *digit != '.')
        .collect::<String>();
    let digits = digits.trim_end_matches('0');
    let digits = if digits.is_empty() { "0" } else { digits };
    let k = digits.len() as i32;
    let n = exponent
        .parse::<i32>()
        .expect("a formatted exponent is an integer")
        + 1;
    if (k..=21).contains(&n) {
        let mut text = digits.to_string();
        text.push_str(&"0".repeat((n - k) as usize));
        text
    } else if (1..=21).contains(&n) {
        let point = n as usize;
        format!("{}.{}", &digits[..point], &digits[point..])
    } else if (-5..=0).contains(&n) {
        format!("0.{}{}", "0".repeat(-n as usize), digits)
    } else {
        let sign = if n - 1 < 0 { '-' } else { '+' };
        let power = (n - 1).abs();
        if k == 1 {
            format!("{digits}e{sign}{power}")
        } else {
            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
        }
    }
}

/// `Number(text)`, the conversion the unary plus in the canonical scalar
/// handler performs. `None` stands for `NaN`, which is how a plain scalar
/// stays text.
pub(crate) fn js_to_number(text: &str) -> Option<f64> {
    let trimmed = text.trim_matches(js_space);
    if trimmed.is_empty() {
        return Some(0.0);
    }
    if let Some(radix) = match trimmed.get(..2) {
        Some("0x" | "0X") => Some(16u32),
        Some("0o" | "0O") => Some(8),
        Some("0b" | "0B") => Some(2),
        _ => None,
    } {
        let digits = &trimmed[2..];
        if digits.is_empty() || !digits.chars().all(|d| d.is_digit(radix)) {
            return None;
        }
        let mut value = 0.0f64;
        for digit in digits.chars() {
            value = value * f64::from(radix) + f64::from(digit.to_digit(radix).unwrap_or(0));
        }
        return Some(value);
    }
    let (sign, body) = match trimmed.strip_prefix('-') {
        Some(rest) => (-1.0, rest),
        None => (1.0, trimmed.strip_prefix('+').unwrap_or(trimmed)),
    };
    if body == "Infinity" {
        return Some(sign * f64::INFINITY);
    }
    if !is_decimal_literal(body) {
        return None;
    }
    body.parse::<f64>().ok().map(|value| sign * value)
}

/// JavaScript's `\s`, which is also its `StrWhiteSpace`: the ASCII
/// blanks, the Unicode space separators, the two line separators and the
/// byte-order mark. Rust's own `char::is_whitespace` is the `White_Space`
/// property, which differs in both directions: it counts U+0085 and it
/// does not count U+FEFF. Both of those decide a scalar here.
pub(crate) fn js_space(character: char) -> bool {
    matches!(
        character,
        '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
            ..='\u{200a}'
                | '\u{2028}'
                | '\u{2029}'
                | '\u{202f}'
                | '\u{205f}'
                | '\u{3000}'
                | '\u{feff}'
    )
}

/// The ECMAScript `StrUnsignedDecimalLiteral` shape, which is narrower
/// than what Rust's own parser accepts: `inf`, `nan` and `1_0` are not
/// numbers in JavaScript.
fn is_decimal_literal(body: &str) -> bool {
    let bytes = body.as_bytes();
    let mut index = 0;
    let mut integral = 0;
    while index < bytes.len() && bytes[index].is_ascii_digit() {
        index += 1;
        integral += 1;
    }
    let mut fractional = 0;
    if index < bytes.len() && bytes[index] == b'.' {
        index += 1;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
            fractional += 1;
        }
    }
    if integral == 0 && fractional == 0 {
        return false;
    }
    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
        index += 1;
        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
            index += 1;
        }
        let mut exponent = 0;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
            exponent += 1;
        }
        if exponent == 0 {
            return false;
        }
    }
    index == bytes.len()
}

/// The number the core schema reads `text` as, or `None` when it reads a
/// string: a decimal integer or float
/// (`[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?`), an octal one
/// (`0o[0-7]+`) or a hexadecimal one (`0x[0-9a-fA-F]+`). `0b11`, `1_000`,
/// `0X1F`, `-0x30` and `Infinity` are strings under it. Mirrors the
/// canonical `coreNumber`.
pub(crate) fn core_number(text: &str) -> Option<f64> {
    if let Some(digits) = text.strip_prefix("0o") {
        if !digits.is_empty() && digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
            return Some(text::radix_to_f64(digits, 8));
        }
        return None;
    }
    if let Some(digits) = text.strip_prefix("0x") {
        if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Some(text::radix_to_f64(digits, 16));
        }
        return None;
    }
    let body = text.strip_prefix(['-', '+']).unwrap_or(text);
    let bytes = body.as_bytes();
    let mut index = 0;
    let digits = |index: &mut usize| {
        let from = *index;
        while *index < bytes.len() && bytes[*index].is_ascii_digit() {
            *index += 1;
        }
        *index - from
    };
    if bytes.first() == Some(&b'.') {
        index = 1;
        if digits(&mut index) == 0 {
            return None;
        }
    } else {
        if digits(&mut index) == 0 {
            return None;
        }
        if bytes.get(index) == Some(&b'.') {
            index += 1;
            digits(&mut index);
        }
    }
    if matches!(bytes.get(index), Some(b'e' | b'E')) {
        index += 1;
        if matches!(bytes.get(index), Some(b'-' | b'+')) {
            index += 1;
        }
        if digits(&mut index) == 0 {
            return None;
        }
    }
    if index != bytes.len() {
        return None;
    }
    js_to_number(text)
}

/// `parseInt(text, 10)`. The leading run it skips is JavaScript's
/// whitespace, which is not Rust's: `trim_start` would leave a
/// byte-order mark in place and strip a next-line character.
pub(crate) fn parse_int(text: &str) -> f64 {
    let trimmed = text.trim_start_matches(js_space);
    let bytes = trimmed.as_bytes();
    let mut index = 0;
    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
        index += 1;
    }
    let start = index;
    while index < bytes.len() && bytes[index].is_ascii_digit() {
        index += 1;
    }
    if index == start {
        return f64::NAN;
    }
    trimmed[..index].parse::<f64>().unwrap_or(f64::NAN)
}

/// `parseFloat(text)`, skipping the same JavaScript whitespace
/// `parse_int` skips.
pub(crate) fn parse_float(text: &str) -> f64 {
    let trimmed = text.trim_start_matches(js_space);
    let bytes = trimmed.as_bytes();
    let mut index = 0;
    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
        index += 1;
    }
    if trimmed[index..].starts_with("Infinity") {
        return if bytes.first() == Some(&b'-') {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        };
    }
    let mut digits = 0;
    while index < bytes.len() && bytes[index].is_ascii_digit() {
        index += 1;
        digits += 1;
    }
    if index < bytes.len() && bytes[index] == b'.' {
        index += 1;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
            digits += 1;
        }
    }
    if digits == 0 {
        return f64::NAN;
    }
    let mantissa_end = index;
    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
        let mut probe = index + 1;
        if probe < bytes.len() && (bytes[probe] == b'+' || bytes[probe] == b'-') {
            probe += 1;
        }
        let exponent_start = probe;
        while probe < bytes.len() && bytes[probe].is_ascii_digit() {
            probe += 1;
        }
        if probe > exponent_start {
            index = probe;
        }
    }
    trimmed[..index.max(mantissa_end)]
        .parse::<f64>()
        .unwrap_or(f64::NAN)
}

/// `parseInt(text, 16)`. Like `parse_int` it skips JavaScript's leading
/// whitespace, takes an optional sign and then the LONGEST PREFIX that
/// reads as hexadecimal, rather than demanding the whole string: the
/// digits of a `\x`, `\u` or `\U` escape are a fixed-width window that
/// routinely holds the closing quote or the rest of the line, and the
/// canonical handler reads a number out of the window all the same.
/// `NaN` when the prefix has no digit.
pub(crate) fn parse_int_16(text: &str) -> f64 {
    let trimmed = text.trim_start_matches(js_space);
    let bytes = trimmed.as_bytes();
    let mut index = 0;
    let negative = bytes.first() == Some(&b'-');
    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
        index += 1;
    }
    // `parseInt` allows the `0x` prefix when the radix is 16.
    if bytes.len() > index + 1
        && bytes[index] == b'0'
        && (bytes[index + 1] == b'x' || bytes[index + 1] == b'X')
    {
        index += 2;
    }
    let start = index;
    let mut value = 0f64;
    while index < bytes.len() && bytes[index].is_ascii_hexdigit() {
        value = value * 16.0 + f64::from((bytes[index] as char).to_digit(16).expect("hex digit"));
        index += 1;
    }
    if index == start {
        return f64::NAN;
    }
    if negative {
        -value
    } else {
        value
    }
}

/// `String.fromCharCode(n)`, whose argument goes through `ToUint16`: a
/// `NaN` becomes NUL rather than an error, which is why an unreadable
/// `\x` or `\u` escape is a NUL in the canonical handler.
pub(crate) fn to_uint16(number: f64) -> u32 {
    if !number.is_finite() {
        return 0;
    }
    let truncated = number.trunc();
    let wrapped = truncated.rem_euclid(65536.0);
    wrapped as u32
}

/// `String.fromCodePoint(n)`, which THROWS a `RangeError` for anything
/// that is not a code point. `None` stands for the throw: the canonical
/// matcher does not catch it, so the token is never produced and the
/// document is refused.
pub(crate) fn from_code_point(number: f64) -> Option<u32> {
    if !number.is_finite() || number.trunc() != number {
        return None;
    }
    if !(0.0..=1_114_111.0).contains(&number) {
        return None;
    }
    Some(number as u32)
}

/// The plain scalars that are a value and not a string: the YAML 1.2 core
/// schema's (YAML 1.2.2, 10.3.2), and unless `core` is set the YAML 1.1
/// booleans too. Mirrors the canonical `VALUES` and `VALUES_CORE`.
pub(crate) fn yaml_keyword(text: &str, core: bool) -> Option<Value> {
    Some(match text {
        "true" | "True" | "TRUE" => Value::Bool(true),
        "false" | "False" | "FALSE" => Value::Bool(false),
        "yes" | "Yes" | "YES" | "on" | "On" | "ON" if !core => Value::Bool(true),
        "no" | "No" | "NO" | "off" | "Off" | "OFF" if !core => Value::Bool(false),
        "null" | "Null" | "NULL" | "~" => Value::Null,
        ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => Value::Number(f64::INFINITY),
        "-.inf" | "-.Inf" | "-.INF" => Value::Number(f64::NEG_INFINITY),
        ".nan" | ".NaN" | ".NAN" => Value::Number(f64::NAN),
        _ => return None,
    })
}

// ---------------------------------------------------------------------
// Grammar references
// ---------------------------------------------------------------------

/// The value a token carries as a mapping key, resolving an alias marker
/// against the anchors recorded so far.
fn extract_key(token: &Token, context: &Context) -> Value {
    if token.tin == TIN_VL {
        if let Value::Object(map) = &token.val {
            if let Some(Value::String(name)) = map.get("__yamlAlias") {
                return match state::map_get(context, state::ANCHORS, name) {
                    Some(value) if !matches!(value, Value::Undefined) => value,
                    _ => Value::String(format!("*{name}")),
                };
            }
        }
    }
    if token.tin == TIN_ST || token.tin == TIN_TX {
        token.val.clone()
    } else {
        Value::String(token.src.as_str().to_string())
    }
}

fn token_key(rule: &Rule, index: usize, context: &Context) -> Value {
    let token = if index == 0 { rule.o0() } else { rule.o1() };
    token.map_or(Value::Undefined, |token| extract_key(token, context))
}

fn counter(rule: &Rule, name: &str) -> Option<i32> {
    rule.n.get(name).copied()
}

fn token_number(value: &Value) -> Option<f64> {
    match value {
        Value::Number(number) => Some(*number),
        _ => None,
    }
}

/// The column the mapping of a block sequence's entry starts at, on the
/// line of the source byte `at`: past the line's indentation and every
/// `- ` that leads it, as a block scalar's explicit indent counts its key's
/// column. `- a: 1` starts at 2, `-   a: 1` and `- - a: 1` at 4, and
/// `- &x a: 1` at 2, where the anchor starts the mapping ahead of its first
/// key's own token.
fn entry_column(src: source::Src<'_>, at: usize) -> usize {
    let at = src.clamp(at);
    let mut line = src.line_start(at);
    if line == 0 && src.starts_with(0, lex::BOM_TEXT) {
        line = lex::BOM_TEXT.len();
    }
    let (mut column, mut index) = (0, line);
    while index < at && src.is(index, b' ') {
        column += 1;
        index += 1;
    }
    while index < at && src.is(index, b'-') && matches!(src.at(index + 1), 0x20 | 0x09) {
        column += 2;
        index += 2;
        while index < at && src.is(index, b' ') {
            column += 1;
            index += 1;
        }
    }
    column
}

/// The column of the sequence entry's mapping whose pair this value is,
/// when it is the value of one (`- a: ...`): the mapping's keys stand at
/// that column, so the value nests only below it, as a block mapping's
/// value nests only below its key.
fn entry_map_in(rule: &Rule) -> Option<f64> {
    let parent = rule.parent_rule.as_ref()?;
    if parent.name.as_str() != "yamlElemPair" {
        return None;
    }
    match rule.k.get("yamlMapIn") {
        Some(Value::Number(column)) => Some(*column),
        _ => None,
    }
}

/// The name of the rule that pushed this one.
fn parent_name(rule: &Rule) -> Option<&str> {
    rule.parent_rule.as_ref().map(|parent| parent.name.as_str())
}

/// The name of the anchor an alias marker names: the value of an alias
/// whose anchor was not recorded when it was read.
fn alias_name(value: &Value) -> Option<&str> {
    match value {
        Value::Object(map) => match map.get("__yamlAlias") {
            Some(Value::String(name)) => Some(name.as_str()),
            _ => None,
        },
        _ => None,
    }
}

/// The token `token`, marked bad, when it is an alias to an anchor whose
/// node is still open: an alias inside the node it names, which would hold
/// itself. A rule's action or handler that returns it fails the parse
/// there, with the code. Mirrors the canonical `recursiveAlias`.
fn recursive_alias(token: Option<&Token>, context: &Context) -> Option<Token> {
    let token = token?;
    if token.tin != TIN_VL {
        return None;
    }
    let name = alias_name(&token.val)?;
    if !state::anchor_open(context, name) {
        return None;
    }
    let mut bad = token.clone();
    bad.bad(RECURSIVE_ALIAS);
    Some(bad)
}

/// The column of the token a mapping opens on, when that token is a key
/// and its node is the first thing on its line, and 0 otherwise: a flow
/// mapping's brace, or a key that follows something on its line
/// (`--- a: 1`), keeps the indent of 0. The key's node starts at its
/// properties, so `  &x a: 1` stands at 2 as `  a: 1` does. Mirrors the
/// canonical `firstKeyColumn`.
fn first_key_column(context: &mut Context) -> i32 {
    let Some(token) = context.t0() else {
        return 0;
    };
    if !matches!(token.tin, TIN_TX | TIN_NR | TIN_ST | TIN_VL) {
        return 0;
    }
    let at = token.site.si;
    let windowed = context.source.is_empty();
    let kept = source::Kept::load(context, windowed);
    let touched = std::cell::Cell::new(false);
    let column = {
        let src = kept.src(&context.source, &touched);
        let at = src.clamp(at);
        let line = lex::line_start_of(src, at);
        let mut index = line;
        while index < at && src.is(index, b' ') {
            index += 1;
        }
        let column = src.slice(line, index).len();
        while index < at && (src.is(index, b'&') || src.is(index, b'!')) {
            while index < at && !lex::blank(src.at(index)) {
                index += 1;
            }
            while index < at && lex::blank(src.at(index)) {
                index += 1;
            }
        }
        if index == at {
            i32::try_from(column).unwrap_or(0)
        } else {
            0
        }
    };
    kept.store(context);
    column
}

fn t0_number(context: &Context) -> Option<f64> {
    context.t0().and_then(|token| token_number(&token.val))
}

fn register_refs(parser: &mut Tabnas) {
    // The two lexer matchers.
    parser.imperative_lex_match_ref(lex::MATCHER, lex::yaml_matcher);
    parser.imperative_lex_match_ref(text::MATCHER, text::yaml_text);

    // Conditions.
    parser.alt_condition("@val-indent-deeper", |rule, context| {
        let Some(t0) = t0_number(context) else {
            return false;
        };
        if let Some(Value::Number(list_in)) = rule.k.get("yamlListIn") {
            if t0 <= *list_in {
                return false;
            }
        }
        if entry_map_in(rule).is_some_and(|map_in| t0 <= map_in) {
            return false;
        }
        match rule.k.get("yamlIn") {
            Some(Value::Number(parent)) => t0 > *parent,
            _ => true,
        }
    });
    // A sequence at the indent of the key it is the value of, its
    // mapping's or a sequence entry's: `a:\n- x` and `- a:\n  - x`. The
    // key's column is the one that counts. A sequence entry's key stands at
    // its mapping's column, not at an enclosing mapping's, and a sequence
    // entry's own value has no key: a `-` at an enclosing indent is that
    // sequence's next entry.
    parser.alt_condition("@val-indent-eq-parent", |rule, context| {
        let Some(t0) = t0_number(context) else {
            return false;
        };
        match parent_name(rule) {
            Some("yamlElemPair") => {
                matches!(rule.k.get("yamlMapIn"), Some(Value::Number(map_in)) if t0 == *map_in)
            }
            Some("yamlBlockList" | "yamlBlockElem") => false,
            _ => matches!(rule.k.get("yamlIn"), Some(Value::Number(parent)) if t0 == *parent),
        }
    });
    // Whether a value may open a block sequence on its own line: not when
    // it is the value of a mapping's pair. YAML has no `key: - a`: a block
    // sequence starts on the line after its key.
    parser.alt_condition("@val-not-pair-value", |rule, _context| {
        !matches!(parent_name(rule), Some("pair" | "yamlElemPair"))
    });
    parser.alt_condition("@t0-eq-in", |rule, context| {
        matches!((t0_number(context), counter(rule, "in")),
            (Some(t0), Some(indent)) if t0 == f64::from(indent))
    });
    parser.alt_condition("@t0-le-in", |rule, context| {
        matches!((t0_number(context), counter(rule, "in")),
            (Some(t0), Some(indent)) if t0 <= f64::from(indent))
    });
    parser.alt_condition("@t0-lt-in", |rule, context| {
        matches!((t0_number(context), counter(rule, "in")),
            (Some(t0), Some(indent)) if t0 < f64::from(indent))
    });
    parser.alt_condition("@o0-eq-in", |rule, _context| {
        let open = rule.o0().and_then(|token| token_number(&token.val));
        matches!((open, counter(rule, "in")),
            (Some(value), Some(indent)) if value == f64::from(indent))
    });
    parser.alt_condition("@t0-eq-map-in", |rule, context| {
        matches!((t0_number(context), rule.k.get("yamlMapIn")),
            (Some(t0), Some(Value::Number(indent))) if t0 == *indent)
    });

    // Actions.
    parser.action_with_context("@val-set-in-from-o0", |rule, _context| {
        if let Some(value) = rule.o0().and_then(|token| token_number(&token.val)) {
            rule.n_mut().insert("in".to_string(), value as i32);
        }
        Ok(())
    });
    parser.action_with_context("@val-set-null", |rule, _context| {
        set_node(rule, Value::Null);
        Ok(())
    });
    parser.action_with_context("@val-set-el-in", |rule, _context| {
        let column = rule.o0().map_or(0, |token| token.site.ci);
        rule.n_mut().insert("in".to_string(), column as i32 - 1);
        Ok(())
    });
    // A scalar on the line after its key is the value its token read: a
    // number, a boolean or null as well as a string (`a:\n  1` is 1). An
    // alias's marker is resolved by the val that pushed this rule.
    parser.action_with_context("@indent-plain-value", |rule, _context| {
        let node = rule
            .o0()
            .map_or(Value::Undefined, |token| token.val.clone());
        set_node(rule, node);
        Ok(())
    });
    parser.action_with_context("@set-map-in", |rule, context| {
        // A block sequence entry's mapping stands at the column its content
        // starts at. A flow sequence's pair (`[a: 1]`) keeps
        // `r.k.yamlMapIn = r.n.in + 2`, which no indent token reads; with no
        // `in` counter that is `undefined + 2`, which is NaN, and NaN never
        // equals the indent `@t0-eq-map-in` compares it to. A zero here
        // would instead make the comparison true at the outermost indent.
        let block = matches!(rule.name.as_str(), "yamlBlockList" | "yamlBlockElem");
        let indent = match rule.o0() {
            Some(token) if block => {
                // The token's line, as the lexer read it: the whole text,
                // or from a reader the lines the plugin keeps.
                let windowed = context.source.is_empty();
                let kept = source::Kept::load(context, windowed);
                let touched = std::cell::Cell::new(false);
                let column = entry_column(kept.src(&context.source, &touched), token.site.si);
                kept.store(context);
                column as f64
            }
            _ => counter(rule, "in").map_or(f64::NAN, |value| f64::from(value + 2)),
        };
        rule.k_mut()
            .insert("yamlMapIn".to_string(), Value::Number(indent));
        Ok(())
    });
    // A key that is an alias to an anchor whose node is still open is
    // refused there (`recursive_alias`).
    parser.action_with_match_ref("@elem-key", |rule, context, _alt| {
        if let Some(bad) = recursive_alias(rule.o0(), context) {
            return Ok(Some(bad));
        }
        let key = token_key(rule, 0, context);
        rule.u_mut().insert("key".to_string(), key);
        Ok(None)
    });
    parser.action_with_match_ref("@implicit-null-pair", |rule, context, _alt| {
        if let Some(bad) = recursive_alias(rule.o0(), context) {
            return Ok(Some(bad));
        }
        let key = token_key(rule, 0, context);
        rule.u_mut().insert("key".to_string(), key.clone());
        store_member(rule, context, string_of(&key), Value::Null);
        Ok(None)
    });
    parser.action_with_match_ref("@qm-pairkey", |rule, context, _alt| {
        if let Some(bad) = recursive_alias(rule.o1(), context) {
            return Ok(Some(bad));
        }
        let key = token_key(rule, 1, context);
        rule.u_mut().insert("key".to_string(), key);
        Ok(None)
    });
    parser.action_with_match_ref("@qm-implicit-null-pair", |rule, context, _alt| {
        if let Some(bad) = recursive_alias(rule.o1(), context) {
            return Ok(Some(bad));
        }
        let key = token_key(rule, 1, context);
        rule.u_mut().insert("key".to_string(), key.clone());
        store_member(rule, context, string_of(&key), Value::Null);
        Ok(None)
    });

    // The stream rule's actions.
    parser.action_with_context("@yaml-apply-directive", |rule, context| {
        apply_directive(rule, context);
        Ok(())
    });
    parser.action_with_context("@yaml-mark-explicit", |_rule, context| {
        ensure_meta(context);
        set_meta_flag(context, "explicit", true);
        Ok(())
    });
    parser.action_with_context("@yaml-accum-doc", |rule, context| {
        accumulate_document(rule, context);
        Ok(())
    });
    parser.action_with_context("@yaml-accum-and-directive", |rule, context| {
        accumulate_document(rule, context);
        apply_directive(rule, context);
        Ok(())
    });
    parser.action_with_context("@yaml-finalize-stream", |rule, context| {
        finalize_stream(rule, context);
        Ok(())
    });
}

// ---------------------------------------------------------------------
// The stream rule's bookkeeping
// ---------------------------------------------------------------------

fn ensure_meta(context: &mut Context) {
    if context.u.get(state::CUR_META).is_none() {
        let mut meta = IndexMap::new();
        meta.insert("directives".to_string(), Value::array(Vec::new()));
        meta.insert("explicit".to_string(), Value::Bool(false));
        meta.insert("ended".to_string(), Value::Bool(false));
        context
            .u
            .insert(state::CUR_META.to_string(), Value::object(meta));
    }
}

fn set_meta_flag(context: &mut Context, field: &str, value: bool) {
    ensure_meta(context);
    state::map_set(
        context,
        state::CUR_META,
        field.to_string(),
        Value::Bool(value),
    );
}

fn flush_meta(context: &mut Context, ended: bool) {
    ensure_meta(context);
    if ended {
        set_meta_flag(context, "ended", true);
    }
    let meta = context
        .u
        .shift_remove(state::CUR_META)
        .unwrap_or(Value::Undefined);
    state::list_push(context, state::METAS, meta);
}

fn apply_directive(rule: &mut Rule, context: &mut Context) {
    let source = rule.o0().map_or(String::new(), |token| {
        let src = token.src.as_str();
        if src.is_empty() {
            match &token.val {
                Value::String(text) => text.clone(),
                _ => String::new(),
            }
        } else {
            src.to_string()
        }
    });
    if let Some((handle, prefix)) = tag_directive(&source) {
        state::map_set(context, state::TAG_HANDLES, handle, Value::String(prefix));
    }
    ensure_meta(context);
    let mut directives = match state::map_get(context, state::CUR_META, "directives") {
        Some(Value::Array(items)) => (*items).clone(),
        _ => Vec::new(),
    };
    directives.push(Value::String(source));
    state::map_set(
        context,
        state::CUR_META,
        "directives".to_string(),
        Value::array(directives),
    );
}

/// `%TAG <handle> <prefix>`, the only directive that changes a parse.
/// The canonical pattern is `^%TAG\s+(\S+)\s+(\S+)`, so the separator
/// is JavaScript's whitespace: `is_whitespace` and `split_whitespace`
/// would read a next-line character as a separator and a byte-order mark
/// as part of a field.
fn tag_directive(source: &str) -> Option<(String, String)> {
    let rest = source.strip_prefix("%TAG")?;
    if !rest.starts_with(js_space) {
        return None;
    }
    let mut fields = rest.split(js_space).filter(|field| !field.is_empty());
    let handle = fields.next()?;
    let prefix = fields.next()?;
    Some((handle.to_string(), prefix.to_string()))
}

fn child_document(rule: &Rule) -> Option<Value> {
    (!rule.child_node.is_undefined()).then(|| rule.child_node.clone())
}

fn accumulate_document(rule: &mut Rule, context: &mut Context) {
    let value = child_document(rule).unwrap_or(Value::Null);
    state::list_push(context, state::DOCS, value);
    // The close token says whether this document ended with `...`.
    let ended = rule.c0().is_some_and(|token| token.name.as_ref() == "#DE");
    flush_meta(context, ended);
}

fn finalize_stream(rule: &mut Rule, context: &mut Context) {
    if let Some(value) = child_document(rule) {
        state::list_push(context, state::DOCS, value);
        flush_meta(context, false);
    } else if context.u.get(state::CUR_META).is_some() {
        // The final document was opened explicitly but its value
        // coalesced away: a bare `---` at end of stream, or the trailing
        // empty document of `---\n---\n---`. Restore the null the other
        // empty documents are given.
        state::list_push(context, state::DOCS, Value::Null);
        flush_meta(context, false);
    }

    let documents = state::list_all(context, state::DOCS);
    let content = match documents.len() {
        0 => Value::Undefined,
        1 => documents[0].clone(),
        _ => Value::array(documents),
    };

    let want_meta = matches!(
        context
            .options
            .plugin
            .get(PLUGIN_NAME)
            .and_then(|options| match options {
                Value::Object(map) => map.get("meta").cloned(),
                _ => None,
            }),
        Some(Value::Bool(true))
    );

    let result = if want_meta {
        let metas = state::list_all(context, state::METAS);
        let meta = match metas.len() {
            0 => Value::Undefined,
            1 => metas[0].clone(),
            _ => Value::array(metas),
        };
        let mut wrapper = IndexMap::new();
        wrapper.insert("meta".to_string(), meta);
        wrapper.insert("content".to_string(), content);
        Value::object(wrapper)
    } else {
        content
    };

    // A rotation through `r: stream` shares the start rule's node cell,
    // which is the parse root, so writing THROUGH the cell is the Rust
    // spelling of the canonical `ctx.root().node = result`.
    *rule.node.borrow_mut() = result;
}

// ---------------------------------------------------------------------
// Rule lifecycle
// ---------------------------------------------------------------------

fn wire_rules(parser: &mut Tabnas) {
    parser.define_rule("val", |spec| {
        spec.add_ao(|rule, context| {
            let pending = state::list_take(context, state::PENDING_ANCHORS);
            if !pending.is_empty() {
                // Only whether the open node was a scalar is ever read back,
                // so a container is recorded as `Undefined`: a clone of an
                // inherited container is a second handle on the parent's
                // accumulator (see below).
                let open_node = match &*rule.node.borrow() {
                    node if is_container(node) => Value::Undefined,
                    node => node.clone(),
                };
                name_anchors(rule, &pending, &open_node);
                for anchor in &pending {
                    if let Value::Object(entry) = anchor {
                        if let Some(Value::String(name)) = entry.get("n") {
                            state::hold_anchor(context, name, 1.0);
                        }
                    }
                }
                rule.u_mut()
                    .insert("yamlAnchors".to_string(), Value::array(pending));
                rule.u_mut()
                    .insert("yamlAnchorOpenNode".to_string(), open_node);
                // The arrays inside the anchored value are kept, behind a
                // stream that empties them, until the anchor is recorded
                // at this val's close ([`state::PRUNE_HOLD`]).
                state::hold_pruning(context, 1.0);
            }
            // A YAML alt that opens on `#IN` or `#EL` (pushing `indent` or
            // `yamlBlockList`, or backing up for an empty value) leaves this val's node as the cell
            // it inherited from its parent: the parent MAP when the value is
            // a pair's and starts on the next line. jsonic's val before-close
            // stashes a clone of that node (`u.openval`), a second `Arc` on
            // the map the pair is about to insert into, so every insert
            // copied the whole map and a mapping of N such values parsed in
            // O(N^2). jsonic's own alts reset the node when they open; these
            // do the same. The value is the child's either way.
            // The empty-value alt (`#IN`, backed up) is the same shape: the
            // val ends with no value, and the stash held the map while the
            // pair inserted that absence.
            let yaml_alt = matches!(
                rule.o0().map(|token| token.name.as_ref()),
                Some("#EL" | "#IN")
            );
            if yaml_alt && is_container(&rule.node.borrow()) {
                set_node(rule, Value::Undefined);
            }
        });
        spec.add_bc(|rule, _context| {
            if matches!(rule.u.get("yamlEmpty"), Some(Value::Bool(true))) {
                set_node(rule, Value::Undefined);
            }
        });
        spec.add_ac_with_state(Arc::new(|rule, context, _next, _out| {
            Ok(close_val(rule, context))
        }));
    });

    parser.define_rule("indent", |spec| {
        spec.add_bc(|rule, _context| {
            if !rule.child_node.is_undefined() {
                let child = rule.child_node.clone();
                set_node(rule, child);
            }
        });
    });

    parser.define_rule("yamlBlockList", |spec| {
        spec.add_bo(|rule, _context| {
            // A fresh cell, as `r.node = []` installs a fresh array.
            // Every rotation of this rule shares the cell it installs, so
            // the elements all land in one list, which is what the
            // canonical port passes along in `k.yamlBlockArr`.
            set_node(rule, Value::array(Vec::new()));
            set_indent_key(rule, "yamlListIn");
        });
        spec.add_bc(|rule, _context| {
            let value = if rule.child_node.is_undefined() {
                Value::Null
            } else {
                rule.child_node.clone()
            };
            list_push(&mut rule.node.borrow_mut(), value);
        });
    });

    parser.define_rule("yamlBlockElem", |spec| {
        spec.add_bc(|rule, _context| {
            let value = if rule.child_node.is_undefined() {
                Value::Null
            } else {
                rule.child_node.clone()
            };
            list_push(&mut rule.node.borrow_mut(), value);
        });
    });

    parser.define_rule("list", |spec| {
        spec.add_bo(|rule, _context| {
            set_indent_key(rule, "yamlListIn");
            // A YAML block sequence reaches `list` through the indent
            // rule's `#EL` alternate, with no `[` and no implicit-list
            // promotion, so neither of jsonic's array builders runs and
            // the node is still the inherited parent container. Allocate
            // the array here so the element pushes land in a list.
            if rule
                .parent_rule
                .as_ref()
                .is_some_and(|parent| parent.name.as_ref() == "indent")
            {
                set_node(rule, Value::array(Vec::new()));
            }
        });
    });

    // A quoted `<<` key is an ordinary key: YAML resolves only a plain
    // `<<` to the merge key (the merge type is YAML 1.1's, and a quoted
    // scalar is always a string). The pair notes a quoted one on the
    // mapping's node cell, which every pair of a mapping shares, and the
    // map leaves that mapping unmerged, as the canonical port does.
    parser.define_rule("pair", |spec| {
        spec.add_ao_with_state(Arc::new(|rule, context, _next, _out| {
            let key = match rule.o0() {
                Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
                other => other,
            };
            if let Some(bad) = recursive_alias(key, context) {
                return Ok(Some(bad));
            }
            hold_merge(rule, context);
            Ok(None)
        }));
        spec.add_bc(|rule, context| {
            note_literal_merge_key(rule, context);
        });
        spec.add_ac(|rule, context| {
            release_merge(rule, context);
        });
    });

    parser.define_rule("map", |spec| {
        spec.add_bo(|rule, context| {
            if counter(rule, "in").is_none() {
                // No indent token came before this mapping: it is a
                // document's root, or a flow mapping. A root block mapping
                // stands at the column of its first key, which need not be
                // 0 (YAML 1.2.2, 9.1.1: a document's root node is indented
                // by -1, so any column is deeper).
                let column = first_key_column(context);
                rule.n_mut().insert("in".to_string(), column);
            }
            set_indent_key(rule, "yamlIn");
        });
        spec.add_ac(|rule, context| {
            if !state::map_take(context, state::LITERAL_MERGE, &cell_address(rule)) {
                // Each key a merge brings is named in the map's counters
                // as `<<key`, whose value is the number of the source it
                // came from, so the map's close pass names every key it
                // merged and where it took it: a host that reads the rule
                // passes (YAML's transducer part) writes those members of
                // those sources, and no other, as the mapping's last, as
                // `mergeMember` does in the canonical source.
                for (key, source) in apply_merge_keys(rule) {
                    rule.n_mut().insert(format!("<<{key}"), source);
                }
            }
        });
    });

    // `yamlElemMap` only makes the map: its open alternate hands every
    // pair, the first included, to `yamlElemPair` (see the grammar), so it
    // never reaches a close phase and stores nothing itself.
    parser.define_rule("yamlElemMap", |spec| {
        spec.add_bo(|rule, _context| {
            set_node(rule, Value::object(IndexMap::new()));
        });
    });

    parser.define_rule("yamlElemPair", |spec| {
        spec.add_bc(|rule, context| {
            store_elem_pair(rule, context);
        });
    });
}

/// The val rule's after-close: an alias whose anchor was not yet recorded
/// when it was read is resolved, or refused when its anchor's node is
/// still open; and the anchors this val claimed are recorded, their nodes
/// now closed. A token returned is a refusal.
fn close_val(rule: &mut Rule, context: &mut Context) -> Option<Token> {
    let alias = alias_name(&rule.node.borrow()).map(str::to_string);
    if let Some(name) = alias {
        if state::anchor_open(context, &name) {
            // The alias's own token: this val's, or its indent child's when
            // the alias stands on the line after its key.
            let node = rule.node.borrow().clone();
            let own = rule.o0().filter(|token| token.val == node).cloned();
            let child = rule
                .child_rule
                .as_ref()
                .and_then(|child| child.o.first().filter(|token| token.val == node).cloned());
            let mut token = own.or(child).or_else(|| rule.o0().cloned())?;
            token.bad(RECURSIVE_ALIAS);
            return Some(token);
        }
        let resolved =
            state::map_get(context, state::ANCHORS, &name).map_or(Value::Undefined, |value| {
                if is_container(&value) {
                    deep_copy(&value)
                } else {
                    value
                }
            });
        set_node(rule, resolved);
    }

    let Some(Value::Array(anchors)) = rule.u.get("yamlAnchors").cloned() else {
        return None;
    };
    let open_node = rule
        .u
        .get("yamlAnchorOpenNode")
        .cloned()
        .unwrap_or(Value::Undefined);
    let node = rule.node.borrow().clone();
    for anchor in anchors.iter() {
        let Value::Object(entry) = anchor else {
            continue;
        };
        let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
        let Some(Value::String(name)) = entry.get("n") else {
            continue;
        };
        // An inline anchor that named a scalar keeps that scalar: the
        // container this val ended up holding belongs to a later, deeper
        // value.
        if inline
            && !matches!(open_node, Value::Undefined | Value::Null)
            && !is_container(&open_node)
            && is_container(&node)
        {
            continue;
        }
        let value = if is_container(&node) {
            deep_copy(&node)
        } else {
            node.clone()
        };
        state::map_set(context, state::ANCHORS, name.clone(), value);
    }
    // The node has closed: an alias after it names a finished node.
    for anchor in anchors.iter() {
        if let Value::Object(entry) = anchor {
            if let Some(Value::String(name)) = entry.get("n") {
                state::hold_anchor(context, name, -1.0);
            }
        }
    }
    // Recorded: the hold this val raised at its open is released.
    state::hold_pruning(context, -1.0);
    None
}

/// `r.k.<name> = r.n.in`, including when there is no `in` counter: the
/// canonical assignment writes `undefined` there, and every reader takes
/// that as "no enclosing indent". Writing a zero instead would make a
/// block sequence at the outermost indent look nested inside itself.
fn set_indent_key(rule: &mut Rule, name: &str) {
    let indent =
        counter(rule, "in").map_or(Value::Undefined, |value| Value::Number(f64::from(value)));
    rule.k_mut().insert(name.to_string(), indent);
}

fn store_elem_pair(rule: &mut Rule, context: &mut Context) {
    let Some(key) = rule.u.get("key").cloned() else {
        return;
    };
    if matches!(key, Value::Null | Value::Undefined) {
        return;
    }
    // A pair whose value never arrived (`- a:` before the next entry) is
    // a null member, as `a:` at the root is: the canonical implementation
    // stores null for it, as the Go port does, and
    // `test/spec/sequence-of-mappings.tsv` pins the member.
    let child = if rule.child_node.is_undefined() {
        Value::Null
    } else {
        rule.child_node.clone()
    };
    store_member(rule, context, string_of(&key), child);
}

/// Name, in the val's counters, each anchor it claims that its close may
/// record as its node: the counter `&name`, whose value is the val's own
/// instance number, and the counter `yamlAnchored`, of the same value,
/// which marks the val. A host that reads the rule passes (YAML's
/// transducer part) knows the anchored val as the one whose `yamlAnchored`
/// is its own `i`, keeps the events of its value, and writes them again at
/// an alias of a name. An inline anchor on a val that opened on a scalar
/// records that scalar or nothing (the val's after-close), so it is not
/// named. Mirrors `nameAnchors` in the canonical source.
fn name_anchors(rule: &mut Rule, anchors: &[Value], open_node: &Value) {
    let scalar = !matches!(open_node, Value::Undefined | Value::Null) && !is_container(open_node);
    // A parse of more rules than an `i32` counts names no anchor, so an
    // alias of one past them is refused rather than written wrong.
    let Ok(instance) = i32::try_from(rule.i) else {
        return;
    };
    for anchor in anchors {
        let Value::Object(entry) = anchor else {
            continue;
        };
        let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
        let Some(Value::String(name)) = entry.get("n") else {
            continue;
        };
        if inline && scalar {
            continue;
        }
        rule.n_mut().insert(format!("&{name}"), instance);
        rule.n_mut().insert("yamlAnchored".to_string(), instance);
    }
}

/// A plain `<<` holds a streaming host's pruning ([`state::PRUNE_HOLD`])
/// from its pair's open to its close: the map's after-close merges the
/// sources the `<<` value lists, and a sequence of them, emptied behind
/// the stream when its rule closed, would merge nothing.
fn hold_merge(rule: &mut Rule, context: &mut Context) {
    let token = match rule.o0() {
        Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
        other => other,
    };
    let plain = token.is_some_and(|token| token.tin != TIN_ST);
    if plain && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
        rule.u_mut()
            .insert("yamlMergeHold".to_string(), Value::Bool(true));
        state::hold_pruning(context, 1.0);
    }
}

/// The hold [`hold_merge`] raised, released as the merge key's pair closes.
fn release_merge(rule: &mut Rule, context: &mut Context) {
    if matches!(rule.u.get("yamlMergeHold"), Some(Value::Bool(true))) {
        rule.u_mut()
            .insert("yamlMergeHold".to_string(), Value::Bool(false));
        state::hold_pruning(context, -1.0);
    }
}

/// Note a quoted `<<` key on the mapping it belongs to: the key a pair
/// names is `<<`, and its token is a quoted scalar's (`#ST`), the token
/// after the `?` of an explicit key in a flow mapping.
fn note_literal_merge_key(rule: &Rule, context: &mut Context) {
    let token = match rule.o0() {
        Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
        other => other,
    };
    let quoted = token.is_some_and(|token| token.tin == TIN_ST);
    if quoted && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
        state::map_set(
            context,
            state::LITERAL_MERGE,
            cell_address(rule),
            Value::Bool(true),
        );
    }
}

/// The address of a rule's node cell. A mapping's pairs share its cell,
/// and the cell lives as long as the parse that built it, so the address
/// names the mapping.
fn cell_address(rule: &Rule) -> String {
    format!("{:p}", Rc::as_ptr(&rule.node))
}

/// Resolve a `<<` merge key in place: the merged entries are appended
/// after the explicit ones, and an explicit key always wins. It answers
/// the keys it merged, in the order it merged them, each with the number
/// of the source it came from: 1 for the mapping a `<<` names, and for a
/// sequence, the place of the mapping among the sequence's mappings,
/// counted from 1.
fn apply_merge_keys(rule: &mut Rule) -> Vec<(String, i32)> {
    let mut merged = Vec::new();
    let mut node = rule.node.borrow_mut();
    let Some(entries) = map_entries(&node) else {
        return merged;
    };
    let Some(merge) = entries.get("<<").cloned() else {
        return merged;
    };
    let sources = match &merge {
        Value::Array(items) => (**items).clone(),
        Value::ListRef(list) => list.value.clone(),
        other => vec![other.clone()],
    };
    match &mut *node {
        Value::Object(map) => {
            Arc::make_mut(map).shift_remove("<<");
        }
        Value::MapRef(map) => {
            Arc::make_mut(map).value.shift_remove("<<");
        }
        _ => {}
    }
    let mut number = 0;
    for source in sources {
        let Some(source_entries) = map_entries(&source) else {
            continue;
        };
        number += 1;
        let additions: Vec<(String, Value)> = source_entries
            .iter()
            .filter(|(key, _)| {
                map_entries(&node).is_some_and(|entries| !entries.contains_key(*key))
            })
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();
        for (key, value) in additions {
            merged.push((key.clone(), number));
            map_insert(&mut node, key, value);
        }
    }
    merged
}

// ---------------------------------------------------------------------
// Installation
// ---------------------------------------------------------------------

/// The lexer and option overlay this plugin needs, plus the `stream`
/// rule, which the canonical implementation also declares in code rather
/// than in the shared grammar file.
fn options_document() -> serde_json::Value {
    json!({
        "rule": {
            "stream": {
                "open": [
                    // A directive line: apply it, then look again.
                    { "s": "#DR", "a": "@yaml-apply-directive", "r": "stream", "g": "yaml" },
                    // An explicit document start: push val for its content.
                    { "s": "#DS", "a": "@yaml-mark-explicit", "p": "val", "g": "yaml" },
                    // A `...` with no document open terminates nothing, so
                    // it produces no document. Consume it and look again.
                    { "s": "#DE", "r": "stream", "g": "yaml" },
                    // End of source: close immediately.
                    { "s": "#ZZ", "b": 1, "g": "yaml" },
                    // The implicit first document.
                    { "p": "val", "g": "yaml" }
                ],
                "close": [
                    { "s": "#ZZ", "a": "@yaml-finalize-stream", "g": "yaml" },
                    { "s": "#DR", "a": "@yaml-accum-and-directive", "r": "stream", "g": "yaml" },
                    { "s": "#DE", "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" },
                    { "s": "#DS", "b": 1, "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" }
                ]
            }
        },
        "options": {
            // A bare colon is not a YAML token; `: ` is, and the matcher
            // emits it.
            "fixed": { "token": { "#CL": null } },
            // A colon still ends unquoted text.
            "ender": ":",
            // YAML's quoting is not the engine's: both forms are lexed by
            // the YAML matcher, and a backtick is not a quote at all.
            "string": { "chars": "" },
            "lex": {
                "match": {
                    // Below the first built-in band, so YAML syntax is
                    // seen before the fixed-token matcher.
                    "yaml": { "order": 5e5, "make": "@yaml-matcher" },
                    // Between the number matcher and the text matcher,
                    // which is where `options.text.check` runs.
                    "yamlText": { "order": 7.5e6, "make": "@yaml-text" }
                }
            },
            // A document stream is the entry point, and it opens into the
            // shared `val` rule.
            "rule": { "start": "stream" },
            // This plugin's own error codes, with the templates and hints
            // the engine fills from the bad token. Each is declared in every
            // runtime and listed in tabnas.plugin.json.
            "error": {
                "yaml_undefined_alias": "undefined alias: {src}",
                "yaml_recursive_alias": "recursive alias: {src}",
                "yaml_tab_indent": "tab in indentation"
            },
            "hint": {
                "yaml_undefined_alias": "\nThe alias {src} names no anchor that occurs before it in the document.\nAn anchor is written &name on the node it names, and an alias can only\nname an anchor defined earlier.",
                "yaml_recursive_alias": "\nThe alias {src} names the anchor of a node it is inside, so the node\nwould hold itself. This parser gives a tree, which cannot. Anchor the\npart that repeats, and name that from outside it.",
                "yaml_tab_indent": "\nA tab stands in this line's indentation, before a mapping key or a\nsequence entry. YAML indents block structure with spaces alone, so the\nline's depth cannot be read. Indent the line with spaces."
            }
        }
    })
}

/// jsonic's numbers are doubles, so `b: 2` arrives as `2.0`; the
/// alternate decoder reads an integer field as an integer. Put every
/// whole number back into integer form.
fn integral_numbers(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Number(number) => match number.as_f64() {
            Some(float) if float.fract() == 0.0 && float.abs() < 9.0e15 => json!(float as i64),
            _ => serde_json::Value::Number(number),
        },
        serde_json::Value::Array(items) => {
            serde_json::Value::Array(items.into_iter().map(integral_numbers).collect())
        }
        serde_json::Value::Object(fields) => serde_json::Value::Object(
            fields
                .into_iter()
                .map(|(key, value)| (key, integral_numbers(value)))
                .collect(),
        ),
        other => other,
    }
}

/// The grammar document, parsed from the embedded jsonic text exactly as
/// the TypeScript and Go ports parse their copies of it.
fn grammar_document() -> Result<serde_json::Value, PluginError> {
    let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
        .map_err(|error| PluginError(format!("yaml: cannot parse the grammar text: {error}")))?;
    let document = integral_numbers(parsed.to_json());
    if document
        .get("rule")
        .and_then(serde_json::Value::as_object)
        .is_none()
    {
        return Err(PluginError(
            "yaml: the grammar text has no `rule` table".to_string(),
        ));
    }
    Ok(document)
}

/// Install YAML on a jsonic-enabled `parser`.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut parser = tabnas_jsonic::make();
///     tabnas_yaml::yaml(&mut parser, &tabnas_yaml::YamlOptions::default())?;
///     assert_eq!(parser.parse("a: 1")?.to_string(), r#"{"a":1}"#);
///     Ok(())
/// }
/// ```
pub fn yaml(parser: &mut Tabnas, options: &YamlOptions) -> Result<(), PluginError> {
    // Guard against a second install on the same instance, which would
    // install the grammar twice. A derived child must not be caught by
    // it: `Tabnas::derive` copies the parent's decorations onto the child
    // before it re-runs the plugins, as the canonical TypeScript does, so
    // the child carries the mark and none of the grammar
    // (tabnas/parser#244). The guard therefore asks for both, the mark
    // this plugin set and a rule only this grammar installs: a child has
    // the mark alone and installs again, and an instance carrying a rule
    // of that name from elsewhere has the rule alone and goes on to the
    // checks below.
    if parser.decoration::<bool>(INSTALLED).is_some() && grammar_installed(parser) {
        return Ok(());
    }
    // This plugin reshapes jsonic's rules rather than declaring a whole
    // grammar, so an instance without them earns a clear refusal now
    // instead of a grammar that can parse nothing later.
    if !parser.rule_names().iter().any(|name| name == "val") {
        return Err(PluginError(
            "yaml: the jsonic grammar is not installed on this instance; \
             install tabnas_jsonic first"
                .to_string(),
        ));
    }
    parser.decorate(INSTALLED, true);
    parser.set_plugin_options(PLUGIN_NAME, options.to_value());

    // The tokens the matcher emits by name, allocated before any grammar
    // names them.
    for name in ["#IN", "#EL", "#QM", "#DS", "#DE", "#DR"] {
        parser.token(name);
    }

    register_refs(parser);

    let spec = GrammarSpec::from_value(options_document())
        .map_err(|error| PluginError(format!("yaml: invalid option document: {error}")))?;
    parser
        .grammar(&spec)
        .map_err(|error| PluginError(format!("yaml: cannot apply the options: {error}")))?;

    let spec = GrammarSpec::from_value(grammar_document()?)
        .map_err(|error| PluginError(format!("yaml: invalid grammar document: {error}")))?;
    parser
        .grammar(&spec)
        .map_err(|error| PluginError(format!("yaml: cannot apply the grammar: {error}")))?;

    wire_rules(parser);

    // Replaces jsonic's guard, which counts only jsonic's own containers
    // (see `DEPTH_GUARD`). A guard rather than the parse budget, which is
    // one slot a caller's `parse_budget` replaces: the limit holds
    // whatever budget the caller sets.
    parser.parse_guard(DEPTH_GUARD, within_depth_limit);
    Ok(())
}

/// Whether this grammar's rules are on `parser`, judged by a rule only it
/// installs: `yamlBlockList`, the block sequence, from the grammar
/// document. Read with the [`INSTALLED`] mark: a derived child starts
/// with no rules of its own and earns the grammar again, and a second
/// `yaml` call on one instance returns early.
fn grammar_installed(parser: &Tabnas) -> bool {
    parser
        .rule_names()
        .iter()
        .any(|name| name == "yamlBlockList")
}

/// How many containers a parse may hold before it is refused, with the
/// engine's `cancel` code: jsonic's number, so a flow collection, which
/// is jsonic's, is bounded where it always was.
///
/// The engine parses iteratively, but displaying, converting or dropping
/// a `Value` walks the tree with the call stack, so an unbounded document
/// ends the caller's process rather than returning an error: a compact
/// block sequence 64,000 levels deep parsed, and then overflowed a 2 MiB
/// stack when it was dropped. TypeScript and Go have no limit, which
/// `../DIVERGENCE.md` records.
const DEPTH_LIMIT: usize = 127;

/// The name the depth check is installed under, as a parse guard.
///
/// It is the name jsonic installs its own check under, so this one
/// replaces it. jsonic's counts its `map` and `list` rules, which is all a
/// flow collection or an indented block collection uses, but a compact
/// block sequence (`- - - x`) nests through YAML's own rules, and under
/// jsonic's check it went unbounded.
const DEPTH_GUARD: &str = "depth";

/// Whether a rule of this name holds a container: jsonic's `map` and
/// `list`, and YAML's own block collections. A block sequence opens as
/// `yamlBlockList` and, after its first entry, is replaced by
/// `yamlBlockElem`; a mapping that starts in a sequence entry opens as
/// `yamlElemMap` and is replaced by `yamlElemPair` before its first pair.
/// Each replacement shares the container's cell and takes its place on
/// the stack, so a container is counted once under whichever name it has
/// reached. jsonic's `pair` and `elem`, and `indent`, hold none.
fn is_container_rule(name: &str) -> bool {
    matches!(
        name,
        "map" | "list" | "yamlBlockList" | "yamlBlockElem" | "yamlElemMap" | "yamlElemPair"
    )
}

/// How many containers are open: those on the rule stack, and the rule
/// the loop is working on, which the engine hands over apart from them.
///
/// Counted afresh at each step. Every level holds a container and a few
/// other rules, so the stack a step walks is bounded by the limit itself.
fn depth(context: &Context) -> usize {
    let ancestors = context
        .rule_stack
        .iter()
        .filter(|rule| is_container_rule(&rule.name))
        .count();
    let current = usize::from(
        context
            .rule
            .as_ref()
            .is_some_and(|rule| is_container_rule(&rule.name)),
    );
    ancestors + current
}

/// The depth guard: [`DEPTH_LIMIT`] containers parse, the next one is
/// refused.
fn within_depth_limit(context: &Context) -> bool {
    depth(context) <= DEPTH_LIMIT
}

/// The plugin form of [`yaml`], for [`Tabnas::use_plugin`]. Installed
/// this way the grammar is re-applied to derived instances, as every
/// native plugin is.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut parser = tabnas_jsonic::make();
///     parser.use_plugin(tabnas_yaml::plugin(), None)?;
///     assert_eq!(parser.parse("- a\n- b")?.to_string(), r#"["a","b"]"#);
///     Ok(())
/// }
/// ```
pub fn plugin() -> Plugin {
    Plugin::new(PLUGIN_NAME, |parser, options| {
        let meta = matches!(
            match options {
                Value::Object(map) => map.get("meta").cloned(),
                _ => None,
            },
            Some(Value::Bool(true))
        );
        let schema = schema_option(options)?;
        yaml(parser, &YamlOptions { meta, schema })
    })
    .with_defaults(YamlOptions::default().to_value())
}

/// Build a YAML parser with caller options.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let parser = tabnas_yaml::make_with(tabnas_yaml::YamlOptions { meta: true, ..Default::default() });
///     let value = parser.parse("---\na: 1\n...")?;
///     assert_eq!(
///         value.to_string(),
///         r#"{"meta":{"directives":[],"explicit":true,"ended":true},"content":{"a":1}}"#
///     );
///     Ok(())
/// }
/// ```
#[must_use]
pub fn make_with(options: YamlOptions) -> Tabnas {
    let mut parser = tabnas_jsonic::make();
    parser
        .use_plugin(plugin(), Some(options.to_value()))
        .expect("the yaml grammar documents are fixed and valid");
    // Read a reader a window at a time (admin ADR-30): the plugin's
    // matcher and text check read the source through the window, asking
    // the engine to cut again over a wider one where a scan reaches its
    // end, and keep the lines before the cursor that their backward scans
    // read (`source.rs`); jsonic's base cuts its tokens with the engine's
    // own matchers. Set on the parser this crate makes whole, not in
    // [`plugin`], which a host may install beneath matchers of its own.
    parser
        .set_options(|options| options.lex.window = true)
        .expect("lex.window sets");
    parser
}

/// Build a YAML parser with the default options.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let parser = tabnas_yaml::make();
///     assert_eq!(parser.parse("a:\n  b: 1")?.to_string(), r#"{"a":{"b":1}}"#);
///     Ok(())
/// }
/// ```
#[must_use]
pub fn make() -> Tabnas {
    make_with(YamlOptions::default())
}

/// Parse a YAML source string with the shared default parser.
///
/// The parser is built once, on first use, and reused after that, as the
/// other two runtimes do. Reuse is safe: [`Tabnas::parse`] takes `&self`
/// and builds a fresh parse context per call, and every piece of
/// per-parse state this grammar keeps lives in that context.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let value = tabnas_yaml::parse("- 1\n- 2\n")?;
///     assert_eq!(value.to_string(), "[1,2]");
///     Ok(())
/// }
/// ```
pub fn parse(src: &str) -> Result<Value, YamlError> {
    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
    DEFAULT.get_or_init(make).parse(src)
}

/// One optional alchemy translation source and its explicit entry point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The definition a host calls after linking the source.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional embedding of a plain tree in the format's schema, with its reverse.
    pub embed: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
    /// An optional transducer: the format's JSON events from its parser's
    /// rule passes, for a host that reads parser events.
    pub transduce: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: None,
    embed: None,
    render: Some(TranslationPart {
        entry: "yaml-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
    transduce: Some(TranslationPart {
        entry: "yaml-transduce",
        source: Some(include_str!("../translate/transduce.alc")),
    }),
};

/// Return YAML's immutable translation parts.
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shape YAML is read as and written from (`tree`), the file that holds
/// the render, the sentences that say what the render does not keep, and
/// the file that holds the transducer part (`transduce`), the document's
/// JSON events from the grammar's rule passes under its default options,
/// through which a host that reads parser events reads a document. The
/// crate embeds its own copies, `translate/manifest.json` and
/// `translate/transduce.alc`, since a packaged crate holds nothing outside
/// `rs/`; `tests/translate_test.rs` holds each copy to its file.
///
/// ```
/// assert!(tabnas_yaml::manifest_text().contains("\"translate\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// YAML's render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `yaml-render` writes a tree's events as one
/// YAML document. A host links it with its own program. The crate embeds
/// its own copy, `translate/render.alc`, held to the file as the
/// manifest's is.
///
/// ```
/// assert!(tabnas_yaml::render_text().contains("def yaml-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    match TRANSLATION.render {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}