succinctly 0.7.0

High-performance succinct data structures for Rust
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
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
//! YAML parser (oracle) for Phase 5: YAML with multi-document streams.
//!
//! This module implements the sequential oracle that resolves YAML's
//! context-sensitive grammar and emits IB/BP/TY bits for index construction.
//!
//! # Phase 5 Scope
//!
//! - Block mappings and sequences
//! - Flow mappings `{key: value}` and sequences `[a, b, c]`
//! - Simple scalars (unquoted, double-quoted, single-quoted)
//! - Block scalars: literal (`|`) and folded (`>`)
//! - Chomping modifiers: strip (`-`), keep (`+`), clip (default)
//! - Anchors (`&name`) and aliases (`*name`)
//! - Comments (ignored in block context, not allowed in flow)
//! - **Multi-document streams (`---` and `...` markers)**
//!
//! # Document Wrapping
//!
//! All YAML documents are wrapped in a virtual root sequence for consistent API:
//! - Single-document files become 1-element arrays
//! - Multi-document files become N-element arrays
//! - Paths use `.[0].key` instead of `.key`

#[cfg(not(test))]
use alloc::{
    collections::BTreeMap,
    string::{String, ToString},
    vec,
    vec::Vec,
};

#[cfg(test)]
use std::collections::BTreeMap;

use super::error::YamlError;
use super::simd;

/// Node type in the YAML structure tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeType {
    /// Mapping (object-like): key-value pairs
    Mapping,
    /// Sequence (array-like): ordered list
    Sequence,
    /// Scalar value (string, number, etc.)
    #[allow(dead_code)]
    Scalar,
    /// Sequence item (tracks open items awaiting their value)
    SequenceItem,
}

/// Block scalar style (literal or folded).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockStyle {
    /// Literal (`|`): preserves newlines exactly
    Literal,
    /// Folded (`>`): folds newlines to spaces
    Folded,
}

/// Chomping indicator for block scalars.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChompingIndicator {
    /// Clip (default): single trailing newline
    Clip,
    /// Strip (`-`): no trailing newlines
    Strip,
    /// Keep (`+`): preserve all trailing newlines
    Keep,
}

/// Block scalar header information.
#[derive(Debug)]
struct BlockScalarHeader {
    /// Literal or folded style (used for debugging/future extensions)
    #[allow(dead_code)]
    style: BlockStyle,
    /// Chomping behavior
    chomping: ChompingIndicator,
    /// Explicit indentation indicator (1-9), or 0 for auto-detect
    explicit_indent: u8,
}

/// Output from parsing: the semi-index structures.
#[derive(Debug)]
pub struct SemiIndex {
    /// Interest bits: marks positions of structural elements
    pub ib: Vec<u64>,
    /// Balanced parentheses: encodes tree structure
    pub bp: Vec<u64>,
    /// Type bits: 0 = mapping, 1 = sequence at each structural position
    pub ty: Vec<u64>,
    /// Direct mapping from BP open positions to text byte offsets.
    /// For each BP open (1-bit), this stores the corresponding byte offset.
    /// Containers may share position with first child.
    pub bp_to_text: Vec<u32>,
    /// End positions for scalars. For each BP open, stores the end byte offset.
    /// For containers, stores 0 (containers don't have a text end position).
    pub bp_to_text_end: Vec<u32>,
    /// Sequence item marker bits: 1 if this BP position is a sequence item wrapper.
    /// Sequence items have BP open/close but no TY entry.
    pub seq_items: Vec<u64>,
    /// Container marker bits: 1 if this BP position has a TY entry (is a mapping or sequence).
    /// Used to compute correct TY index from BP position.
    pub containers: Vec<u64>,
    /// Number of valid bits in IB (= input length)
    #[allow(dead_code)]
    pub ib_len: usize,
    /// Number of valid bits in BP
    pub bp_len: usize,
    /// Number of valid bits in TY (= number of container opens)
    #[allow(dead_code)]
    pub ty_len: usize,
    /// Anchor definitions: anchor name → BP position of the anchored value
    pub anchors: BTreeMap<String, usize>,
    /// Alias references: BP position of alias → target BP position (resolved at parse time)
    pub aliases: BTreeMap<usize, usize>,
}

/// Parser state for the YAML-lite oracle.
struct Parser<'a> {
    input: &'a [u8],
    pos: usize,

    // Index builders
    ib_words: Vec<u64>,
    bp_words: Vec<u64>,
    ty_words: Vec<u64>,
    seq_item_words: Vec<u64>,
    /// Container marker bits - marks BP positions that have TY entries (mappings/sequences)
    container_words: Vec<u64>,
    bp_pos: usize,
    ty_pos: usize,

    // Direct BP-to-text mapping
    bp_to_text: Vec<u32>,
    /// End positions for scalars (start is in bp_to_text, end is here)
    bp_to_text_end: Vec<u32>,

    // Indentation tracking
    indent_stack: Vec<usize>,

    // Node type stack (to track if we're in mapping or sequence)
    type_stack: Vec<NodeType>,
    /// Cached current type for branchless access (avoids Option unwrapping in hot paths)
    current_type: Option<NodeType>,

    // Anchor and alias tracking
    /// Anchors collected during parsing: name → bp_pos of anchored value
    anchors: BTreeMap<String, usize>,
    /// Aliases collected during parsing: bp_pos → target bp_pos (resolved at parse time)
    aliases: BTreeMap<usize, usize>,

    // Document tracking
    /// Whether we're currently inside a document
    in_document: bool,

    // Explicit key tracking
    /// Whether we have a pending explicit key that needs a value (null if not followed by `:`)
    pending_explicit_key: bool,
}

impl<'a> Parser<'a> {
    fn new(input: &'a [u8]) -> Self {
        let ib_words = vec![0u64; input.len().div_ceil(64).max(1)];
        let bp_words = vec![0u64; input.len().div_ceil(32).max(1)]; // ~2x IB for BP
        let ty_words = vec![0u64; input.len().div_ceil(64).max(1)];
        let seq_item_words = vec![0u64; input.len().div_ceil(32).max(1)]; // Same size as BP
        let container_words = vec![0u64; input.len().div_ceil(32).max(1)]; // Same size as BP

        // Estimate BP opens: ~1 structural element per 8 bytes of input
        let estimated_opens = input.len().div_ceil(8).max(1);

        // Pre-allocate indent/type stacks for typical nesting depths
        let mut indent_stack = Vec::with_capacity(32);
        indent_stack.push(0); // Start at indent 0

        Self {
            input,
            pos: 0,
            ib_words,
            bp_words,
            ty_words,
            seq_item_words,
            container_words,
            bp_pos: 0,
            ty_pos: 0,
            bp_to_text: Vec::with_capacity(estimated_opens),
            bp_to_text_end: Vec::with_capacity(estimated_opens),
            indent_stack,
            type_stack: Vec::with_capacity(32),
            current_type: None,
            anchors: BTreeMap::new(),
            aliases: BTreeMap::new(),
            in_document: false,
            pending_explicit_key: false,
        }
    }

    /// Push a type onto the type stack and update the cached current type.
    #[inline]
    fn push_type(&mut self, node_type: NodeType) {
        self.type_stack.push(node_type);
        self.current_type = Some(node_type);
    }

    /// Pop a type from the type stack and update the cached current type.
    #[inline]
    fn pop_type(&mut self) -> Option<NodeType> {
        let popped = self.type_stack.pop();
        self.current_type = self.type_stack.last().copied();
        popped
    }

    /// Set an interest bit at the current position.
    #[inline]
    fn set_ib(&mut self) {
        let word_idx = self.pos / 64;
        let bit_idx = self.pos % 64;
        if word_idx < self.ib_words.len() {
            self.ib_words[word_idx] |= 1u64 << bit_idx;
        }
    }

    /// Set an interest bit at a specific position.
    #[inline]
    #[allow(dead_code)]
    fn set_ib_at(&mut self, pos: usize) {
        let word_idx = pos / 64;
        let bit_idx = pos % 64;
        if word_idx < self.ib_words.len() {
            self.ib_words[word_idx] |= 1u64 << bit_idx;
        }
    }

    /// Write an open parenthesis (1) to BP at the current text position.
    #[inline]
    fn write_bp_open(&mut self) {
        self.write_bp_open_at(self.pos);
    }

    /// Write an open parenthesis (1) to BP at a specific text position.
    #[inline]
    fn write_bp_open_at(&mut self, text_pos: usize) {
        let word_idx = self.bp_pos / 64;
        let bit_idx = self.bp_pos % 64;
        // Ensure capacity
        while word_idx >= self.bp_words.len() {
            self.bp_words.push(0);
        }
        self.bp_words[word_idx] |= 1u64 << bit_idx;
        // Record the text position for this BP open
        self.bp_to_text.push(text_pos as u32);
        // Placeholder for end position (will be set by set_bp_text_end for scalars)
        self.bp_to_text_end.push(0);
        self.bp_pos += 1;
    }

    /// Set the end text position for the most recently opened BP node.
    /// Call this before write_bp_close for scalar nodes.
    #[inline]
    fn set_bp_text_end(&mut self, end_pos: usize) {
        if let Some(last) = self.bp_to_text_end.last_mut() {
            *last = end_pos as u32;
        }
    }

    /// Write a close parenthesis (0) to BP.
    #[inline]
    fn write_bp_close(&mut self) {
        let word_idx = self.bp_pos / 64;
        // Ensure capacity
        while word_idx >= self.bp_words.len() {
            self.bp_words.push(0);
        }
        // Close is 0, which is default, so just increment position
        self.bp_pos += 1;
    }

    /// Mark the current BP position as a sequence item.
    /// Call this BEFORE write_bp_open for sequence items.
    #[inline]
    fn mark_seq_item(&mut self) {
        let bp_pos = self.bp_pos;
        let word_idx = bp_pos / 64;
        let bit_idx = bp_pos % 64;
        while word_idx >= self.seq_item_words.len() {
            self.seq_item_words.push(0);
        }
        self.seq_item_words[word_idx] |= 1u64 << bit_idx;
    }

    /// Close a pending explicit key by adding a null value node.
    /// Call this when a new key or end of mapping is encountered without an explicit value.
    fn close_pending_explicit_key(&mut self) {
        if self.pending_explicit_key {
            // Add a null value node (empty open/close pair)
            // Use input.len() as the text position to indicate "no text" / null value
            self.write_bp_open_at(self.input.len());
            self.write_bp_close();
            self.pending_explicit_key = false;
        }
    }

    /// Write a type bit: 0 = mapping, 1 = sequence.
    /// Also marks the current BP position as a container.
    #[inline]
    fn write_ty(&mut self, is_sequence: bool) {
        // Mark this BP position as a container (bp_pos - 1 because write_bp_open already incremented)
        let container_bp_pos = self.bp_pos - 1;
        let word_idx = container_bp_pos / 64;
        let bit_idx = container_bp_pos % 64;
        while word_idx >= self.container_words.len() {
            self.container_words.push(0);
        }
        self.container_words[word_idx] |= 1u64 << bit_idx;

        // Write the TY bit
        let ty_word_idx = self.ty_pos / 64;
        let ty_bit_idx = self.ty_pos % 64;
        while ty_word_idx >= self.ty_words.len() {
            self.ty_words.push(0);
        }
        if is_sequence {
            self.ty_words[ty_word_idx] |= 1u64 << ty_bit_idx;
        }
        self.ty_pos += 1;
    }

    /// Get current byte without advancing.
    #[inline]
    fn peek(&self) -> Option<u8> {
        self.input.get(self.pos).copied()
    }

    /// Get byte at offset from current position.
    #[inline]
    fn peek_at(&self, offset: usize) -> Option<u8> {
        self.input.get(self.pos + offset).copied()
    }

    /// Advance position by one byte.
    #[inline]
    fn advance(&mut self) {
        if self.pos < self.input.len() {
            self.pos += 1;
        }
    }

    /// Advance position by multiple bytes.
    #[inline]
    fn advance_by(&mut self, count: usize) {
        self.pos = (self.pos + count).min(self.input.len());
    }

    /// Compute line number at current position (1-indexed).
    /// Only called on error paths, so we pay the cost only when needed.
    #[inline]
    fn current_line(&self) -> usize {
        // Count newlines from start to current position
        self.input[..self.pos]
            .iter()
            .filter(|&&b| b == b'\n')
            .count()
            + 1
    }

    /// Skip whitespace on the current line (spaces and tabs, not newlines).
    #[inline]
    fn skip_inline_whitespace(&mut self) {
        while self.pos < self.input.len() {
            match self.input[self.pos] {
                b' ' | b'\t' => self.pos += 1,
                _ => break,
            }
        }
    }

    /// Skip spaces only (not tabs) with hybrid scalar/SIMD approach.
    /// Returns number of spaces skipped.
    #[inline]
    fn skip_spaces_simd(&mut self) -> usize {
        // Fast path for short runs (0-8 spaces) - avoid SIMD overhead
        let mut count = 0;
        while count < 8 && self.pos < self.input.len() && self.input[self.pos] == b' ' {
            self.pos += 1;
            count += 1;
        }

        // If we found non-space within 8 bytes, we're done
        if count < 8 || self.pos >= self.input.len() {
            return count;
        }

        // For longer runs (>= 8 spaces), use SIMD from current position
        let remaining = super::simd::count_leading_spaces(self.input, self.pos);
        self.pos += remaining;
        count + remaining
    }

    /// Find next newline using SIMD acceleration.
    /// Returns offset from current position, or None if not found.
    #[inline]
    #[allow(dead_code)]
    fn find_next_newline_simd(&self) -> Option<usize> {
        super::simd::find_newline(self.input, self.pos)
    }

    /// SIMD fast-path for skipping regular characters in unquoted values.
    /// Returns the number of bytes that can be safely skipped, or None if
    /// a potential terminator was found immediately.
    #[cfg(all(target_arch = "x86_64", not(feature = "scalar-yaml")))]
    #[inline]
    fn skip_unquoted_simd(&self, _value_start: usize) -> Option<usize> {
        // Use classify_yaml_chars to scan 32 bytes at once
        if let Some(class) = super::simd::classify_yaml_chars(self.input, self.pos) {
            // Check for any potential terminators: newline, colon, or hash
            let terminators = class.newlines | class.colons | class.hash;

            if terminators == 0 {
                // No structural characters in this 32-byte chunk - safe to skip all
                let chunk_size = if self.pos + 32 <= self.input.len() {
                    32
                } else {
                    16
                };
                return Some(chunk_size);
            }

            // Found a potential terminator - find its position
            let first_pos = terminators.trailing_zeros() as usize;

            // If it's at position 0, we can't skip anything
            if first_pos == 0 {
                return None;
            }

            // We can safely skip up to the terminator position
            Some(first_pos)
        } else {
            None
        }
    }

    /// Broadword fast-path for skipping regular characters in unquoted values (ARM64).
    /// Uses pure u64 arithmetic instead of NEON movemask emulation for better performance.
    /// Returns the number of bytes that can be safely skipped, or None if
    /// a potential terminator was found immediately.
    ///
    /// NOTE: Currently disabled - benchmarks showed neutral to slight regression.
    /// Kept for future investigation. See P4 analysis in docs/parsing/yaml.md.
    #[cfg(all(target_arch = "aarch64", not(feature = "scalar-yaml")))]
    #[inline]
    #[allow(dead_code)]
    fn skip_unquoted_simd(&self, _value_start: usize) -> Option<usize> {
        // Use broadword classify to scan 16 bytes at once (two 8-byte chunks)
        if let Some(class) = super::simd::classify_yaml_chars_16(self.input, self.pos) {
            // Check for any potential terminators: newline, colon, or hash
            let terminators = class.value_terminators();

            if terminators == 0 {
                // No structural characters in this 16-byte chunk - safe to skip all
                return Some(16);
            }

            // Found a potential terminator - find its position
            let first_pos = terminators.trailing_zeros() as usize;

            // If it's at position 0, we can't skip anything
            if first_pos == 0 {
                return None;
            }

            // We can safely skip up to the terminator position
            Some(first_pos)
        } else {
            None
        }
    }

    /// Count leading spaces (indentation) at start of a line.
    fn count_indent(&self) -> Result<usize, YamlError> {
        // Use SIMD-accelerated space counting
        let count = super::simd::count_leading_spaces(self.input, self.pos);

        // Check for tab at the position after spaces
        let next_pos = self.pos + count;
        if next_pos < self.input.len() && self.input[next_pos] == b'\t' {
            // Tab after spaces - check context
            // If we haven't seen any spaces and hit a tab at start of line,
            // that's tab indentation (error). But tab after spaces is content.
            if count == 0 {
                return Err(YamlError::TabIndentation {
                    line: self.current_line(),
                    offset: next_pos,
                });
            }
            // Tab after spaces is start of content, indent count is correct
        }
        Ok(count)
    }

    /// Get the current column position (0-based).
    /// This counts characters from the start of the current line.
    fn current_column(&self) -> usize {
        // Find the start of the current line
        let mut line_start = self.pos;
        while line_start > 0 && self.input[line_start - 1] != b'\n' {
            line_start -= 1;
        }
        self.pos - line_start
    }

    /// Check if at end of meaningful content on this line.
    fn at_line_end(&self) -> bool {
        let mut i = self.pos;
        while i < self.input.len() {
            match self.input[i] {
                b'\n' => return true,
                b'#' => return true, // Comment starts
                b' ' => i += 1,
                _ => return false,
            }
        }
        true // EOF counts as line end
    }

    /// Check if current position starts a key-value pair (compact mapping).
    /// Returns true if there's a `:` followed by space/tab/newline/EOF on this line.
    /// Also returns true for empty key case (`:` at start).
    fn looks_like_mapping_entry(&self) -> bool {
        // If we're at a flow structure, it's not a compact mapping
        match self.peek() {
            Some(b'{') | Some(b'[') => return false,
            // Empty key: `:` at start followed by whitespace/newline/EOF
            Some(b':') => {
                let next = self.peek_at(1);
                if matches!(next, Some(b' ') | Some(b'\t') | Some(b'\n') | None) {
                    return true;
                }
                // Colon not followed by whitespace - continue checking
            }
            _ => {}
        }

        let mut i = self.pos;

        // If starting with a quote, skip the quoted string first
        if i < self.input.len() && (self.input[i] == b'"' || self.input[i] == b'\'') {
            let quote = self.input[i];
            i += 1;
            while i < self.input.len() {
                if self.input[i] == quote {
                    // Check for escaped quote in single-quoted strings
                    if quote == b'\'' && i + 1 < self.input.len() && self.input[i + 1] == b'\'' {
                        i += 2; // Skip ''
                        continue;
                    }
                    i += 1; // Skip closing quote
                    break;
                } else if self.input[i] == b'\\' && quote == b'"' {
                    i += 2; // Skip escape sequence in double-quoted
                } else if self.input[i] == b'\n' {
                    return false; // Unclosed quote
                } else {
                    i += 1;
                }
            }
            // After quoted key, check for `: `
            // Skip optional whitespace
            while i < self.input.len() && self.input[i] == b' ' {
                i += 1;
            }
            if i < self.input.len() && self.input[i] == b':' {
                let next = if i + 1 < self.input.len() {
                    Some(self.input[i + 1])
                } else {
                    None
                };
                return matches!(next, Some(b' ') | Some(b'\t') | Some(b'\n') | None);
            }
            return false;
        }

        // Scan for `: ` pattern in unquoted key
        while i < self.input.len() {
            match self.input[i] {
                b'\n' => return false, // Line ended without finding `: `
                b':' => {
                    // Check what follows the colon
                    let next = if i + 1 < self.input.len() {
                        Some(self.input[i + 1])
                    } else {
                        None
                    };
                    match next {
                        Some(b' ') | Some(b'\t') | Some(b'\n') | None => return true,
                        _ => i += 1, // Colon not followed by whitespace, continue
                    }
                }
                // Note: " and ' in the middle of a key are allowed (e.g., bla"keks: foo)
                // Continue scanning past them.
                _ => i += 1,
            }
        }
        false
    }

    /// Skip to end of line (handles comments).
    #[inline]
    fn skip_to_eol(&mut self) {
        while self.pos < self.input.len() && self.input[self.pos] != b'\n' {
            self.pos += 1;
        }
    }

    /// Skip newline and empty/comment lines.
    fn skip_newlines(&mut self) {
        while let Some(b) = self.peek() {
            if b == b'\n' {
                self.advance();
            } else if b == b'#' {
                // Comment line
                self.skip_to_eol();
            } else if b == b' ' {
                // Check if rest of line is whitespace or comment
                let start = self.pos;
                self.skip_inline_whitespace();
                if self.peek() == Some(b'\n') || self.peek() == Some(b'#') || self.peek().is_none()
                {
                    if self.peek() == Some(b'#') {
                        self.skip_to_eol();
                    }
                    continue;
                } else {
                    // Non-empty content - back up
                    self.pos = start;
                    break;
                }
            } else {
                break;
            }
        }
    }

    /// Check for unsupported YAML features (Phase 4: anchors and aliases now supported).
    fn check_unsupported(&self) -> Result<(), YamlError> {
        if let Some(b) = self.peek() {
            match b {
                // Flow style is supported in Phase 2+
                b'{' | b'[' => {
                    // Allowed - will be parsed by parse_flow_*
                }
                // Block scalars are supported in Phase 3+
                b'|' | b'>' => {
                    // Allowed - will be parsed by parse_block_scalar()
                }
                // Anchors and aliases are supported in Phase 4+
                b'&' | b'*' => {
                    // Allowed - will be parsed by parse_anchor() or parse_alias()
                }
                // Explicit keys (`?`) are now supported
                b'?' => {}
                b'!' => {
                    return Err(YamlError::TagNotSupported { offset: self.pos });
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Check if we're at a document start marker (`---`).
    fn is_document_start(&self) -> bool {
        if self.pos + 2 >= self.input.len() {
            return false;
        }
        let slice = &self.input[self.pos..self.pos + 3];
        if slice != b"---" {
            return false;
        }
        // Must be followed by space, newline, or EOF
        self.peek_at(3) == Some(b' ') || self.peek_at(3) == Some(b'\n') || self.peek_at(3).is_none()
    }

    /// Check if we're at a document end marker (`...`).
    fn is_document_end(&self) -> bool {
        if self.pos + 2 >= self.input.len() {
            return false;
        }
        let slice = &self.input[self.pos..self.pos + 3];
        if slice != b"..." {
            return false;
        }
        // Must be followed by space, newline, or EOF
        self.peek_at(3) == Some(b' ') || self.peek_at(3) == Some(b'\n') || self.peek_at(3).is_none()
    }

    /// Skip past a document marker (`---` or `...`).
    /// Does NOT skip content after the marker - that should be parsed.
    fn skip_document_marker(&mut self) {
        // Skip the 3-character marker
        self.advance();
        self.advance();
        self.advance();
        // Skip trailing space after marker if present
        if self.peek() == Some(b' ') {
            self.advance();
        }
    }

    /// Check if there's parseable content on the current line (not just whitespace/comment).
    fn has_content_on_line(&self) -> bool {
        let mut i = 0;
        loop {
            match self.peek_at(i) {
                Some(b' ') | Some(b'\t') => i += 1,
                Some(b'\n') | Some(b'\r') | Some(b'#') | None => return false,
                _ => return true,
            }
        }
    }

    /// Parse content after a document marker on the same line (e.g., `--- >` or `--- value`).
    fn parse_inline_document_value(&mut self) -> Result<(), YamlError> {
        // Skip leading whitespace
        while self.peek() == Some(b' ') || self.peek() == Some(b'\t') {
            self.advance();
        }

        match self.peek() {
            Some(b'|') | Some(b'>') => {
                // Block scalar
                self.parse_block_scalar(0)?;
            }
            Some(b'"') => {
                // Quoted string
                self.set_ib();
                self.write_bp_open();
                self.parse_double_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'\'') => {
                // Single-quoted string
                self.set_ib();
                self.write_bp_open();
                self.parse_single_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'[') | Some(b'{') => {
                // Flow collection
                self.parse_value(0)?;
            }
            Some(b'-')
                if self.peek_at(1) == Some(b' ')
                    || self.peek_at(1) == Some(b'\t')
                    || self.peek_at(1) == Some(b'\n')
                    || self.peek_at(1).is_none() =>
            {
                // Block sequence item
                self.parse_sequence_item(0)?;
            }
            Some(_) if self.looks_like_mapping_entry() => {
                // Mapping entry
                self.parse_mapping_entry(0)?;
            }
            Some(_) => {
                // Plain scalar at document root
                self.set_ib();
                self.write_bp_open();
                let end = self.parse_unquoted_value_doc_root(0);
                self.set_bp_text_end(end);
                self.write_bp_close();
            }
            None => {}
        }

        Ok(())
    }

    /// Start a new document within the virtual root sequence.
    /// This doesn't open a container - the document IS its content.
    fn start_document(&mut self) {
        self.in_document = true;
    }

    /// End the current document, closing any open containers.
    fn end_document(&mut self) {
        if !self.in_document {
            return;
        }

        // Close any remaining open containers within the document
        // The virtual root is at indent_stack[0], so close everything above it
        while self.indent_stack.len() > 1 {
            // If we're closing a mapping that has a pending explicit key, close it first
            if self.current_type == Some(NodeType::Mapping) {
                self.close_pending_explicit_key();
            }
            self.indent_stack.pop();
            self.pop_type();
            self.write_bp_close();
        }

        self.in_document = false;
    }

    /// Parse a double-quoted string.
    ///
    /// Uses SIMD fast-path to skip to the next quote or backslash.
    fn parse_double_quoted(&mut self) -> Result<usize, YamlError> {
        let start = self.pos;
        self.advance(); // Skip opening quote

        loop {
            // SIMD fast-path: find next quote or backslash
            if let Some(offset) = simd::find_quote_or_escape(self.input, self.pos, self.input.len())
            {
                // Skip to the found character
                self.advance_by(offset);

                // Now process the found character
                match self.peek() {
                    Some(b'"') => {
                        self.advance();
                        return Ok(self.pos - start);
                    }
                    Some(b'\\') => {
                        self.advance(); // Skip backslash
                        if self.peek().is_some() {
                            self.advance(); // Skip escaped char
                        } else {
                            return Err(YamlError::UnexpectedEof {
                                context: "escape sequence in string",
                            });
                        }
                    }
                    _ => {
                        // Should not happen since we found quote or backslash
                        self.advance();
                    }
                }
            } else {
                // No quote or backslash found - string is unclosed
                return Err(YamlError::UnclosedQuote {
                    start_offset: start,
                    quote_type: '"',
                });
            }
        }
    }

    /// Parse a single-quoted string.
    ///
    /// Uses SIMD fast-path to skip to the next single quote.
    fn parse_single_quoted(&mut self) -> Result<usize, YamlError> {
        let start = self.pos;
        self.advance(); // Skip opening quote

        loop {
            // SIMD fast-path: find next single quote
            if let Some(offset) = simd::find_single_quote(self.input, self.pos, self.input.len()) {
                // Skip to the found quote
                self.advance_by(offset);

                // Check for escaped quote ('')
                if self.peek_at(1) == Some(b'\'') {
                    self.advance();
                    self.advance();
                } else {
                    self.advance();
                    return Ok(self.pos - start);
                }
            } else {
                // No quote found - string is unclosed
                return Err(YamlError::UnclosedQuote {
                    start_offset: start,
                    quote_type: '\'',
                });
            }
        }
    }

    /// Parse an unquoted scalar value with a minimum indentation requirement.
    /// Handles multiline plain scalars - continues on lines more indented than start_indent.
    /// When `is_doc_root` is true, same-indent lines continue the scalar (YAML spec 7.4).
    fn parse_unquoted_value_with_indent(&mut self, start_indent: usize) -> usize {
        self.parse_unquoted_value_with_indent_impl(start_indent, false)
    }

    /// Parse an unquoted scalar at document root level.
    /// At document root, same-indent lines continue the scalar (YAML spec 7.4).
    fn parse_unquoted_value_doc_root(&mut self, start_indent: usize) -> usize {
        self.parse_unquoted_value_with_indent_impl(start_indent, true)
    }

    fn parse_unquoted_value_with_indent_impl(
        &mut self,
        start_indent: usize,
        is_doc_root: bool,
    ) -> usize {
        let start = self.pos;
        // Track the actual end of content (before newlines we skip)
        let mut content_end = start;

        loop {
            let line_start = self.pos;
            // Parse content on current line
            // Use inline scalar loop for common case, SIMD for long runs
            while let Some(b) = self.peek() {
                match b {
                    b'\n' => break,
                    b'#' => {
                        // # is only a comment if preceded by whitespace (space or tab)
                        if self.pos > start && matches!(self.input[self.pos - 1], b' ' | b'\t') {
                            break;
                        }
                        self.advance();
                    }
                    b':' => {
                        // Colon followed by whitespace ends the value (could be a key)
                        // But in value context, colons in URLs etc. are allowed
                        if self.peek_at(1) == Some(b' ')
                            || self.peek_at(1) == Some(b'\t')
                            || self.peek_at(1) == Some(b'\n')
                        {
                            break;
                        }
                        self.advance();
                    }
                    _ => {
                        // SIMD/broadword fast-path: skip long runs of regular characters
                        // Only use SIMD if we have enough remaining bytes to justify overhead
                        #[cfg(all(target_arch = "x86_64", not(feature = "scalar-yaml")))]
                        if self.input.len() - self.pos >= 32 {
                            if let Some(skip) = self.skip_unquoted_simd(start) {
                                self.advance_by(skip);
                                continue;
                            }
                        }
                        // ARM64 broadword disabled - see P4 analysis in docs/parsing/yaml.md
                        // #[cfg(target_arch = "aarch64")]
                        // if self.input.len() - self.pos >= 16 {
                        //     if let Some(skip) = self.skip_unquoted_simd(start) {
                        //         self.advance_by(skip);
                        //         continue;
                        //     }
                        // }
                        self.advance();
                    }
                }
            }

            // Only update content_end if we parsed content on this line
            // (Skip if we just returned from an empty line continuation)
            if self.pos > line_start {
                content_end = self.pos;
            }

            // Check if we can continue to next line
            if self.peek() != Some(b'\n') {
                break;
            }

            // Look ahead to see if next line is a continuation
            let mut lookahead = self.pos + 1; // Skip \n
            let mut next_indent = 0;

            // Count indentation on next line (only spaces count as indent in YAML)
            while lookahead < self.input.len() && self.input[lookahead] == b' ' {
                next_indent += 1;
                lookahead += 1;
            }

            // Check what comes after the indent
            if lookahead >= self.input.len() {
                // EOF - stop here
                break;
            }

            let next_char = self.input[lookahead];

            // If empty line (just whitespace then newline), skip it and continue
            // This includes lines with only spaces, tabs, or a mix
            if next_char == b'\n' || next_char == b'\t' {
                // Check if rest of line is whitespace
                let mut check_pos = lookahead;
                while check_pos < self.input.len() && matches!(self.input[check_pos], b' ' | b'\t')
                {
                    check_pos += 1;
                }
                if check_pos >= self.input.len()
                    || self.input[check_pos] == b'\n'
                    || self.input[check_pos] == b'\r'
                {
                    // Empty line - skip it and continue
                    self.advance(); // Skip current \n
                                    // Skip to end of empty line
                    while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                        self.advance();
                    }
                    continue;
                }
                // Tab followed by content - for document root scalars (start_indent == 0),
                // this is a continuation per YAML spec example 7.12 "Plain Lines".
                // The tabs become part of the folded content (converted to space).
                if start_indent == 0 && next_char == b'\t' {
                    // Continue to next line - this is a valid continuation
                    self.advance(); // Skip \n
                                    // Skip leading whitespace (tabs are content, but we're at the scalar's level)
                    while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                        self.advance();
                    }
                    continue;
                }
            }

            // Continuation requires more indent than where scalar started,
            // EXCEPT at document root (start_indent == 0) where same-indent is allowed.
            // Next line shouldn't start block structure or be a comment.
            //
            // For sequence indicators `- `, they're only block structure if at a
            // "proper" indent level. A `- ` at indent just 1 greater than start_indent
            // (like ` - ` when start_indent is 0) is scalar content, not a sequence.
            // This handles cases like AB8U where the `- ` is at an invalid indent.
            let is_sequence_indicator = next_char == b'-'
                && lookahead + 1 < self.input.len()
                && matches!(self.input[lookahead + 1], b' ' | b'\t');
            let sequence_indicator_is_block_structure = is_sequence_indicator
                && (next_indent <= start_indent || next_indent >= start_indent + 2);

            // At document root, same-indent continues the scalar (YAML spec 7.4).
            // Inside containers, must be more indented than start.
            let indent_allows_continuation = is_doc_root || next_indent > start_indent;

            if indent_allows_continuation
                && next_char != b'#'
                && !sequence_indicator_is_block_structure
                && !(next_char == b':'
                    && lookahead + 1 < self.input.len()
                    && matches!(self.input[lookahead + 1], b' ' | b'\n'))
            {
                // Continue to next line
                self.advance(); // Skip \n
                                // Skip leading whitespace
                while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                    self.advance();
                }
            } else {
                // Not a continuation - stop here
                break;
            }
        }

        // Trim trailing whitespace from content_end
        let mut end = content_end;
        while end > start && matches!(self.input[end - 1], b' ' | b'\t') {
            end -= 1;
        }

        // Return absolute end position (not length)
        end
    }

    /// Parse an unquoted key (stops at colon+space).
    fn parse_unquoted_key(&mut self) -> Result<usize, YamlError> {
        let start = self.pos;

        while let Some(b) = self.peek() {
            match b {
                b':' => {
                    // Check for colon + whitespace or colon + newline
                    if self.peek_at(1) == Some(b' ')
                        || self.peek_at(1) == Some(b'\t')
                        || self.peek_at(1) == Some(b'\n')
                        || self.peek_at(1).is_none()
                    {
                        break;
                    }
                    // Colon not followed by whitespace is part of the key
                    // (e.g., "key::" or URLs like "http://example.com")
                    self.advance();
                }
                b'\n' => {
                    // Key without colon
                    return Err(YamlError::KeyWithoutValue {
                        offset: start,
                        line: self.current_line(),
                    });
                }
                b'#' => {
                    // # is only a comment if preceded by whitespace
                    // Otherwise it's part of the key (e.g., "a#b: value")
                    if self.pos > start && self.input[self.pos - 1] == b' ' {
                        return Err(YamlError::KeyWithoutValue {
                            offset: start,
                            line: self.current_line(),
                        });
                    }
                    self.advance();
                }
                _ => {
                    // SIMD/broadword fast-path: skip long runs of regular characters
                    #[cfg(all(target_arch = "x86_64", not(feature = "scalar-yaml")))]
                    if self.input.len() - self.pos >= 32 {
                        if let Some(skip) = self.skip_unquoted_simd(start) {
                            self.advance_by(skip);
                            continue;
                        }
                    }
                    // ARM64 broadword disabled - see P4 analysis in docs/parsing/yaml.md
                    // #[cfg(target_arch = "aarch64")]
                    // if self.input.len() - self.pos >= 16 {
                    //     if let Some(skip) = self.skip_unquoted_simd(start) {
                    //         self.advance_by(skip);
                    //         continue;
                    //     }
                    // }
                    self.advance();
                }
            }
        }

        // Trim trailing whitespace
        let mut end = self.pos;
        while end > start && self.input[end - 1] == b' ' {
            end -= 1;
        }

        // Empty key is valid in YAML (e.g., `: value`)
        // Return absolute end position
        Ok(end)
    }

    /// Close containers that are at higher indent levels.
    fn close_deeper_indents(&mut self, new_indent: usize) {
        while self.indent_stack.len() > 1 {
            let current_indent = *self.indent_stack.last().unwrap();
            // Only close containers that are DEEPER than the new indent.
            // Containers at the same level should stay open so new entries
            // can be added to them.
            if current_indent > new_indent {
                // If we're closing a mapping that has a pending explicit key, close it first
                if self.current_type == Some(NodeType::Mapping) {
                    self.close_pending_explicit_key();
                }
                self.indent_stack.pop();
                self.pop_type();
                self.write_bp_close();
            } else {
                break;
            }
        }
    }

    /// Close a sequence that was the value of a previous mapping entry.
    ///
    /// When we're about to add a new entry to a mapping at indent N, and the top
    /// of the stack is a Sequence at indent N with a Mapping below it also at
    /// indent N, the Sequence was the value of a previous entry and must be closed.
    ///
    /// YAML allows sequences-as-values to start at the same indent as the key:
    /// ```yaml
    /// foo:      # key at indent 0
    /// - item    # sequence value at indent 0  <- allowed
    /// bar:      # new key at indent 0 - closes the sequence
    /// ```
    fn close_same_indent_sequence_before_mapping_entry(&mut self, indent: usize) {
        // Check if we have a Sequence at same indent as a Mapping below it
        if self.indent_stack.len() >= 2 && self.type_stack.len() >= 2 {
            let top_idx = self.indent_stack.len() - 1;
            let top_indent = self.indent_stack[top_idx];
            let top_type = self.type_stack[top_idx];
            let below_indent = self.indent_stack[top_idx - 1];
            let below_type = self.type_stack[top_idx - 1];

            // If Sequence at indent N is on top of Mapping at indent N,
            // and we're adding a mapping entry at indent N, close the Sequence
            if top_type == NodeType::Sequence
                && below_type == NodeType::Mapping
                && top_indent == indent
                && below_indent == indent
            {
                self.indent_stack.pop();
                self.pop_type();
                self.write_bp_close();
            }
        }
    }

    /// Parse a sequence item (starts with `- `).
    fn parse_sequence_item(&mut self, indent: usize) -> Result<(), YamlError> {
        let _item_start = self.pos;

        // Mark the `-` position
        self.set_ib();

        // First close any deeper containers. This might reveal an existing sequence
        // at this indent level that we can reuse.
        self.close_deeper_indents(indent);

        // Now check if we need to open a new sequence (check AFTER closing)
        // Normally, sequence items must be at the exact same indent as the sequence.
        // However, for nested sequences created by `- - item` pattern, items can be
        // at greater indent because the nested sequence's indent is virtual.
        //
        // We need a new sequence if:
        // 1. There's no sequence on the stack, OR
        // 2. The item indent doesn't match the sequence indent
        let need_new_sequence = self.current_type != Some(NodeType::Sequence)
            || self.indent_stack.last().copied() != Some(indent);

        if need_new_sequence {
            // Open new sequence
            self.write_bp_open();
            self.write_ty(true); // 1 = sequence
            self.indent_stack.push(indent);
            self.push_type(NodeType::Sequence);
        }

        // Open the sequence item node
        self.mark_seq_item();
        self.write_bp_open();

        // Skip `- `
        self.advance(); // -
        self.skip_inline_whitespace();

        self.check_unsupported()?;

        // Track the sequence item on the stack so close_deeper_indents can close it.
        // We use indent + 1 as a virtual indent - any content at indent > indent
        // is considered part of this item.
        //
        // NOTE: This means for `- foo`, the item is at virtual indent 1, so content
        // at indent 2 would be part of the item. But the sequence itself is at indent 0.
        self.indent_stack.push(indent + 1);
        self.push_type(NodeType::SequenceItem);

        // Check what follows
        if self.at_line_end() {
            // Content is on the next line(s) at greater indentation.
            // Leave the item open - subsequent content at indent > this item's
            // indent will be parsed as the item's value. The item will be closed
            // by close_deeper_indents when we see content at indent <= sequence indent.
            return Ok(());
        }

        // Check for nested sequence: `- - item` (sequence item containing a sequence)
        if self.peek() == Some(b'-')
            && matches!(
                self.peek_at(1),
                Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') | None
            )
        {
            // Nested sequence - the item value is another sequence.
            // Use the actual column position of the nested `-` as the indent.
            // This ensures that subsequent items at the same column (like `- d` after `- c`)
            // will be correctly recognized as siblings in the same sequence.
            let nested_indent = self.current_column();
            self.parse_sequence_item(nested_indent)?;
            // Don't close the outer item - it will be closed when we return
            // to a lower indent level.
        } else if self.looks_like_mapping_entry() {
            // Check for compact mapping: `- key: value`
            // This is a mapping entry directly as the sequence item value
            // The sequence item contains a mapping.
            // Use indent + 2 so that entries at actual indent >= indent+2 are
            // considered part of this mapping.
            let compact_indent = indent + 2;
            self.parse_compact_mapping_entry(compact_indent)?;
            // Don't close anything - mapping and item will be closed by
            // close_deeper_indents when we see content at lower indent.
        } else {
            // Parse the item value normally
            // Pass structure indent for block scalars (content must be > this)
            self.parse_value(indent)?;
            // Close the sequence item for simple values
            self.indent_stack.pop();
            self.pop_type();
            self.write_bp_close();
        }

        Ok(())
    }

    /// Parse a compact mapping entry within a sequence item.
    /// This handles `- key: value` where the mapping is inline with the sequence item.
    fn parse_compact_mapping_entry(&mut self, indent: usize) -> Result<(), YamlError> {
        // Open a mapping for this compact entry
        self.write_bp_open();
        self.write_ty(false); // 0 = mapping
        self.indent_stack.push(indent);
        self.push_type(NodeType::Mapping);

        // Mark key position
        self.set_ib();

        // Open key node
        self.write_bp_open();

        // Parse the key
        let key_end = match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
                self.pos
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
                self.pos
            }
            _ => self.parse_unquoted_key()?,
        };
        self.set_bp_text_end(key_end);

        // Close key node
        self.write_bp_close();

        // Expect colon
        if self.peek() != Some(b':') {
            return Err(YamlError::UnexpectedCharacter {
                offset: self.pos,
                char: self.peek().map(|b| b as char).unwrap_or('\0'),
                context: "expected ':' after key in compact mapping",
            });
        }
        self.advance(); // Skip ':'

        // Skip space after colon
        self.skip_inline_whitespace();

        // Parse value
        if self.at_line_end() {
            // Value is on next line or implicit null
            self.skip_to_eol();

            // Look ahead to determine if this is a null value or a nested structure
            self.skip_newlines();
            if self.peek().is_none() {
                // EOF - null value: emit empty value node
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
            } else {
                let next_indent = self.count_indent().unwrap_or(0);

                // Check if next content is a sequence indicator
                let saved_pos = self.pos;
                self.advance_by(next_indent);
                let is_sequence_indicator = matches!(self.peek(), Some(b'-'))
                    && matches!(
                        self.peek_at(1),
                        Some(b' ') | Some(b'\t') | Some(b'\n') | None
                    );
                self.pos = saved_pos;

                if next_indent < indent || (next_indent == indent && !is_sequence_indicator) {
                    // Next line is at lower indent, or same indent but not a sequence
                    // - null value: emit empty value node
                    self.set_ib();
                    self.write_bp_open();
                    self.write_bp_close();
                }
                // Otherwise, value is a nested structure - main loop will handle it
            }
        } else {
            // Inline value
            self.check_unsupported()?;

            // Open value node
            self.set_ib();
            self.write_bp_open();
            let end_pos = self.parse_inline_value(indent)?;
            self.set_bp_text_end(end_pos);
            self.write_bp_close();
        }

        // Don't close the mapping here - leave it open so subsequent lines
        // at compatible indent levels can add more entries. The mapping will
        // be closed by close_deeper_indents when we return to a lower indent.

        Ok(())
    }

    /// Parse a mapping key-value pair.
    fn parse_mapping_entry(&mut self, indent: usize) -> Result<(), YamlError> {
        let _entry_start = self.pos;

        // First close any containers that are deeper than our indent level.
        // This ensures we return to the appropriate context before deciding
        // whether to open a new mapping or add to an existing one.
        self.close_deeper_indents(indent);

        // If there's a pending explicit key without value, close it with null
        self.close_pending_explicit_key();

        // Close any sequence that was the value of a previous mapping entry.
        // This handles:
        //   foo:
        //   - item  <- sequence at same indent as mapping
        //   bar:    <- new entry closes the sequence
        self.close_same_indent_sequence_before_mapping_entry(indent);

        // Now check if we need to open a new mapping
        let need_new_mapping = self.current_type != Some(NodeType::Mapping)
            || self.indent_stack.last().copied() != Some(indent);

        if need_new_mapping {
            // Open new mapping (virtual - no IB bit, children will have IB)
            self.write_bp_open();
            self.write_ty(false); // 0 = mapping
            self.indent_stack.push(indent);
            self.push_type(NodeType::Mapping);
        }

        // Mark key position
        self.set_ib();

        // Open key node
        self.write_bp_open();

        // Check for anchor on key - record it pointing to this key BP
        // The key BP was just opened, so bp_pos is now one past the key's position
        if self.peek() == Some(b'&') {
            // Consume `&`
            self.advance();
            // Parse anchor name
            let name = self.parse_anchor_name()?;
            // Skip whitespace after anchor name
            self.skip_inline_whitespace();
            // Record anchor pointing to the key (bp_pos - 1, since we just opened the key BP)
            self.anchors.insert(name, self.bp_pos - 1);
        }

        // Parse the key - check for empty key first (colon at start)
        let key_end = if self.peek() == Some(b':') {
            // Empty key - check that it's followed by proper terminator
            let next = self.peek_at(1);
            if matches!(next, Some(b' ') | Some(b'\t') | Some(b'\n') | None) {
                // Empty key case - key length is 0, don't advance yet
                self.pos
            } else {
                // Colon followed by something else - not an empty key
                self.parse_unquoted_key()?
            }
        } else {
            // Parse the key
            match self.peek() {
                Some(b'"') => {
                    self.parse_double_quoted()?;
                    self.pos
                }
                Some(b'\'') => {
                    self.parse_single_quoted()?;
                    self.pos
                }
                Some(b'*') => {
                    // Alias as key - parse alias name
                    // Skip `*`
                    self.advance();
                    // Parse alias name (same rules as anchor names)
                    let alias_name = self.parse_anchor_name()?;
                    // Record the alias reference
                    // Look up the anchor's BP position
                    if let Some(&target_bp_pos) = self.anchors.get(&alias_name) {
                        self.aliases.insert(self.bp_pos - 1, target_bp_pos);
                    }
                    self.pos
                }
                _ => self.parse_unquoted_key()?,
            }
        };
        self.set_bp_text_end(key_end);

        // Close key node
        self.write_bp_close();

        // Skip optional whitespace between key and colon (e.g., 'key' : value)
        self.skip_inline_whitespace();

        // Expect colon
        if self.peek() != Some(b':') {
            return Err(YamlError::UnexpectedCharacter {
                offset: self.pos,
                char: self.peek().map(|b| b as char).unwrap_or('\0'),
                context: "expected ':' after key",
            });
        }
        self.advance(); // Skip ':'

        // Skip space after colon
        self.skip_inline_whitespace();

        // Parse value
        if self.at_line_end() {
            // Check if at EOF - if so, we need an explicit empty value node
            if self.peek().is_none() {
                // EOF after colon - emit empty value
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                return Ok(());
            }
            // Value is on next line - check what kind of value
            self.skip_to_eol();

            // Look ahead to see what the next content line looks like
            self.skip_newlines();
            if self.peek().is_none() {
                // EOF - null value: emit empty value node
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                return Ok(());
            }

            // Count indentation of next line
            let next_indent = self.count_indent().unwrap_or(0);

            // Check what's at the next line's content position
            let saved_pos = self.pos;
            self.advance_by(next_indent);
            let next_char = self.peek();
            let is_sequence_indicator = matches!(next_char, Some(b'-'))
                && matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\t') | Some(b'\n') | None
                );
            self.pos = saved_pos;

            if next_indent < indent {
                // Next line is at lower indent - definitely null value
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                return Ok(());
            }

            if next_indent == indent && !is_sequence_indicator {
                // Next line is at same indent but NOT a sequence - null value
                // (If it were a sequence, the sequence is the value of this key)
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                return Ok(());
            }

            // Re-advance to content position for the remaining checks
            self.advance_by(next_indent);

            // Check if this is a nested structure or a plain scalar value
            match self.peek() {
                Some(b'-')
                    if matches!(
                        self.peek_at(1),
                        Some(b' ') | Some(b'\t') | Some(b'\n') | None
                    ) =>
                {
                    // Sequence - will be handled by main loop
                    self.pos = saved_pos;
                    return Ok(());
                }
                Some(b'?') if matches!(self.peek_at(1), Some(b' ') | Some(b'\n') | None) => {
                    // Explicit key - will be handled by main loop
                    self.pos = saved_pos;
                    return Ok(());
                }
                Some(b'{') | Some(b'[') | Some(b'|') | Some(b'>') => {
                    // Flow/block structure - will be handled by main loop
                    self.pos = saved_pos;
                    return Ok(());
                }
                Some(b'#') => {
                    // Comment - will be handled by main loop
                    self.pos = saved_pos;
                    return Ok(());
                }
                Some(b'&') | Some(b'*') => {
                    // Anchor or alias on its own line - will be handled by main loop
                    self.pos = saved_pos;
                    return Ok(());
                }
                _ => {
                    // Check if this looks like a mapping entry
                    if self.looks_like_mapping_entry() {
                        // Nested mapping - will be handled by main loop
                        self.pos = saved_pos;
                        return Ok(());
                    }
                    // Plain scalar value - parse it here with key's indent as base
                    self.set_ib();
                    self.write_bp_open();
                    let end_pos = self.parse_unquoted_value_with_indent(indent);
                    self.set_bp_text_end(end_pos);
                    self.write_bp_close();
                    return Ok(());
                }
            }
        }

        {
            self.check_unsupported()?;

            // Check for anchor first - it prefixes the actual value
            let anchor_name = if self.peek() == Some(b'&') {
                Some(self.parse_anchor()?)
            } else {
                None
            };

            // After anchor, check if value continues on next line
            if self.at_line_end() {
                // Need to check if the next line has content for this value,
                // or if the value is null (same or lower indent on next line)
                self.skip_to_eol();

                // Save position to look ahead
                let saved_pos = self.pos;

                // Look at next content line
                self.skip_newlines();
                if self.peek().is_none() {
                    // EOF - value is null, create explicit null node for anchor
                    self.pos = saved_pos;
                    self.set_ib();
                    self.write_bp_open();
                    self.write_bp_close();
                    return Ok(());
                }

                let next_indent = self.count_indent().unwrap_or(0);

                // Check if next line is a sequence at same indent as key
                // Sequences can be at same indent as their parent mapping key
                let pos_before_check = self.pos;
                let is_sequence_at_same_indent = {
                    // Skip past indent spaces to check what follows (SIMD accelerated)
                    self.skip_spaces_simd();
                    matches!(self.peek(), Some(b'-'))
                        && matches!(self.peek_at(1), Some(b' ') | Some(b'\n') | None)
                };
                // Restore position after checking
                self.pos = pos_before_check;

                if next_indent <= indent && !is_sequence_at_same_indent {
                    // Next line is at same or lower indent and not a sequence - value is null
                    // Create explicit null node for anchor to point to
                    self.pos = saved_pos;
                    self.set_ib();
                    self.write_bp_open();
                    self.write_bp_close();
                    return Ok(());
                }

                // Value is on next line (nested structure or same-indent sequence)
                // Position is at start of content line for main loop to parse
                return Ok(());
            }

            // Check for alias - this IS the value
            if self.peek() == Some(b'*') {
                self.parse_alias()?;
                return Ok(());
            }

            // Check for flow style or block scalar - these handle their own BP
            match self.peek() {
                Some(b'[') => {
                    self.parse_flow_sequence()?;
                }
                Some(b'{') => {
                    self.parse_flow_mapping()?;
                }
                Some(b'|') | Some(b'>') => {
                    // Block scalar - handles its own BP
                    self.parse_block_scalar(indent)?;
                }
                _ => {
                    // Scalar value - wrap in BP
                    self.set_ib();
                    self.write_bp_open();
                    let end_pos = self.parse_inline_value(indent)?;
                    self.set_bp_text_end(end_pos);
                    self.write_bp_close();
                }
            }

            // Suppress unused warning for anchor_name
            let _ = anchor_name;
        }

        Ok(())
    }

    /// Parse an explicit key (`? key`).
    /// The key can be any value: scalar, sequence, or mapping.
    fn parse_explicit_key(&mut self, indent: usize) -> Result<(), YamlError> {
        // Close any deeper containers
        self.close_deeper_indents(indent);

        // If there's a pending explicit key without value, close it with null
        self.close_pending_explicit_key();

        // Check if we need to open a new mapping
        let need_new_mapping = self.current_type != Some(NodeType::Mapping)
            || self.indent_stack.last().copied() != Some(indent);

        if need_new_mapping {
            // Open new mapping
            self.write_bp_open();
            self.write_ty(false); // 0 = mapping
            self.indent_stack.push(indent);
            self.push_type(NodeType::Mapping);
        }

        // Skip `?`
        self.advance();

        // Skip whitespace/comments after `?`
        self.skip_inline_whitespace();

        // Check for anchor before key
        if self.peek() == Some(b'&') {
            let _ = self.parse_anchor()?;
            self.skip_inline_whitespace();
        }

        // Check what the key is
        if self.at_line_end() {
            // Key content might be on next line(s), or this could be an empty key
            // Save position for potential empty key emission (after the `?`)
            let key_pos = self.pos;
            self.skip_to_eol();

            // Look ahead to see what's on the next line
            self.skip_newlines();
            if self.peek().is_none() {
                // EOF - empty key (null) with implicit null value
                // Emit empty key node using the position after `?`
                self.pos = key_pos;
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                self.pending_explicit_key = true;
                return Ok(());
            }

            let next_indent = self.count_indent().unwrap_or(0);

            // Check if next line starts with `:` at same indent (explicit value)
            // or has other content at same/lower indent (meaning empty key)
            let saved_pos = self.pos;
            self.advance_by(next_indent);
            let next_char = self.peek();
            self.pos = saved_pos;

            if next_indent <= indent {
                // Next content is at same or lower indent
                if next_char == Some(b':')
                    && (next_indent == indent)
                    && matches!(
                        self.input.get(saved_pos + next_indent + 1).copied(),
                        Some(b' ') | Some(b'\t') | Some(b'\n') | None
                    )
                {
                    // `: value` at same indent - empty key (null), value follows
                    // Emit empty key node using the position after `?`
                    self.pos = key_pos;
                    self.set_ib();
                    self.write_bp_open();
                    self.write_bp_close();
                    // Restore position for main loop to process `: value`
                    self.pos = saved_pos;
                    self.pending_explicit_key = true;
                    return Ok(());
                }
                // Other content at same/lower indent - empty key (null) with implicit null value
                // Emit empty key node using the position after `?`
                self.pos = key_pos;
                self.set_ib();
                self.write_bp_open();
                self.write_bp_close();
                // Restore position for main loop to process next content
                self.pos = saved_pos;
                self.pending_explicit_key = true;
                return Ok(());
            }

            // Content at deeper indent - that's the key content
            // Let the main loop parse it (don't restore position - stay at content start)
            return Ok(());
        }

        // Mark key position
        self.set_ib();

        // Parse the key value inline
        match self.peek() {
            Some(b'-')
                if matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\n') | Some(b'\r') | None
                ) =>
            {
                // Sequence as key - open key node and let sequence parsing continue
                // The key will be a sequence
                self.write_bp_open();
                self.write_ty(true); // sequence
                self.indent_stack.push(indent + 2); // Indent for sequence content
                self.push_type(NodeType::Sequence);

                // Parse first sequence item inline
                self.write_bp_open(); // item node
                self.advance(); // skip `-`
                self.skip_inline_whitespace();

                if !self.at_line_end() {
                    // Parse item value
                    if self.looks_like_mapping_entry() {
                        self.parse_compact_mapping_entry(indent + 3)?;
                    } else {
                        self.parse_value(indent + 2)?;
                    }
                }
                self.write_bp_close(); // close item
            }
            Some(b'[') => {
                // Flow sequence as key
                self.write_bp_open();
                self.parse_flow_sequence()?;
                self.write_bp_close();
            }
            Some(b'{') => {
                // Flow mapping as key
                self.write_bp_open();
                self.parse_flow_mapping()?;
                self.write_bp_close();
            }
            Some(b'|') | Some(b'>') => {
                // Block scalar as key
                self.parse_block_scalar(indent)?;
            }
            Some(b'"') => {
                // Double-quoted key
                self.write_bp_open();
                self.parse_double_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'\'') => {
                // Single-quoted key
                self.write_bp_open();
                self.parse_single_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            _ => {
                // Unquoted scalar key
                self.write_bp_open();
                let end_pos = self.parse_unquoted_value_with_indent(indent);
                self.set_bp_text_end(end_pos);
                self.write_bp_close();
            }
        }

        // Mark that we have an explicit key waiting for a value
        self.pending_explicit_key = true;

        Ok(())
    }

    /// Parse an explicit value (`: value` after explicit key).
    fn parse_explicit_value(&mut self, indent: usize) -> Result<(), YamlError> {
        // Close deeper structures, but keep the mapping at this indent open
        self.close_deeper_indents(indent + 1);

        // This value is for the pending explicit key
        self.pending_explicit_key = false;

        // Skip `:`
        self.advance();

        // Skip whitespace after `:`
        self.skip_inline_whitespace();

        // Check for anchor
        if self.peek() == Some(b'&') {
            let _ = self.parse_anchor()?;
            self.skip_inline_whitespace();
        }

        // Check if value is on this line or next
        if self.at_line_end() {
            // Value is on next line(s) or null
            self.skip_to_eol();
            return Ok(());
        }

        // Parse the value
        match self.peek() {
            Some(b'-')
                if matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') | None
                ) =>
            {
                // Sequence as value
                self.write_bp_open();
                self.write_ty(true); // sequence
                self.indent_stack.push(indent + 2);
                self.push_type(NodeType::Sequence);

                // Parse first sequence item
                self.write_bp_open(); // item node
                self.advance(); // skip `-`
                self.skip_inline_whitespace();

                if !self.at_line_end() {
                    if self.looks_like_mapping_entry() {
                        self.parse_compact_mapping_entry(indent + 3)?;
                    } else {
                        self.parse_value(indent + 2)?;
                    }
                }
                self.write_bp_close(); // close item
            }
            Some(b'[') => {
                self.parse_flow_sequence()?;
            }
            Some(b'{') => {
                self.parse_flow_mapping()?;
            }
            Some(b'|') | Some(b'>') => {
                self.parse_block_scalar(indent)?;
            }
            Some(b'"') => {
                self.set_ib();
                self.write_bp_open();
                self.parse_double_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'\'') => {
                self.set_ib();
                self.write_bp_open();
                self.parse_single_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'*') => {
                // Alias as value
                self.parse_alias()?;
            }
            _ => {
                self.set_ib();
                self.write_bp_open();
                let end_pos = self.parse_unquoted_value_with_indent(indent);
                self.set_bp_text_end(end_pos);
                self.write_bp_close();
            }
        }

        Ok(())
    }

    /// Parse an inline scalar value (on the same line as the key).
    /// Returns the end position of the scalar content.
    fn parse_inline_value(&mut self, min_indent: usize) -> Result<usize, YamlError> {
        let end = match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
                self.pos
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
                self.pos
            }
            _ => self.parse_unquoted_value_with_indent(min_indent),
        };
        Ok(end)
    }

    /// Parse a value (could be scalar or nested structure).
    fn parse_value(&mut self, min_indent: usize) -> Result<(), YamlError> {
        self.check_unsupported()?;

        // Check for anchor first - it prefixes the actual value
        if self.peek() == Some(b'&') {
            self.parse_anchor()?;
            // Now parse the actual value that follows
        }

        // Check for alias - this IS the value (no value follows)
        if self.peek() == Some(b'*') {
            return self.parse_alias();
        }

        match self.peek() {
            Some(b'"') => {
                self.set_ib();
                self.write_bp_open();
                self.parse_double_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'\'') => {
                self.set_ib();
                self.write_bp_open();
                self.parse_single_quoted()?;
                self.set_bp_text_end(self.pos);
                self.write_bp_close();
            }
            Some(b'-') if self.peek_at(1) == Some(b' ') || self.peek_at(1) == Some(b'\t') => {
                // Inline sequence item - this creates a nested sequence
                // The caller already opened a BP node for us
            }
            Some(b'[') => {
                // Flow sequence
                self.parse_flow_sequence()?;
            }
            Some(b'{') => {
                // Flow mapping
                self.parse_flow_mapping()?;
            }
            Some(b'|') | Some(b'>') => {
                // Block scalar - handles its own BP
                self.parse_block_scalar(min_indent)?;
            }
            _ => {
                self.set_ib();
                self.write_bp_open();
                let end_pos = self.parse_unquoted_value_with_indent(min_indent);
                self.set_bp_text_end(end_pos);
                self.write_bp_close();
            }
        }
        Ok(())
    }

    // =========================================================================
    // Flow style parsing (Phase 2)
    // =========================================================================

    /// Skip whitespace in flow context (spaces, tabs, newlines, and comments).
    /// Unlike block context, newlines are allowed within flow constructs.
    /// Comments (`# ...`) are also skipped in flow context.
    fn skip_flow_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            match b {
                b' ' | b'\t' | b'\n' | b'\r' => self.advance(),
                b'#' => {
                    // Skip comment to end of line
                    self.skip_to_eol();
                }
                _ => break,
            }
        }
    }

    /// Check if current position starts an implicit mapping entry in flow context.
    /// Returns true if there's a `key : value` pattern (colon followed by space).
    /// This is used to detect patterns like `[ YAML : separate ]`.
    fn looks_like_flow_mapping_entry(&self) -> bool {
        let mut i = self.pos;

        // Skip quoted string if present
        if i < self.input.len() && (self.input[i] == b'"' || self.input[i] == b'\'') {
            let quote = self.input[i];
            i += 1;
            while i < self.input.len() {
                if self.input[i] == quote {
                    if quote == b'\'' && i + 1 < self.input.len() && self.input[i + 1] == b'\'' {
                        // Escaped single quote
                        i += 2;
                        continue;
                    }
                    i += 1; // Skip closing quote
                    break;
                } else if self.input[i] == b'\\' && quote == b'"' {
                    i += 2; // Skip escape sequence
                } else {
                    i += 1;
                }
            }
            // Skip whitespace after quoted string
            while i < self.input.len() && matches!(self.input[i], b' ' | b'\t') {
                i += 1;
            }
            // Check for colon - after quoted key, colon can be adjacent (no space required)
            if i < self.input.len() && self.input[i] == b':' {
                return true;
            }
            return false;
        }

        // Skip flow mapping or sequence if present (e.g., {JSON: like}:value or [a,b]:value)
        if i < self.input.len() && (self.input[i] == b'{' || self.input[i] == b'[') {
            let open = self.input[i];
            let close = if open == b'{' { b'}' } else { b']' };
            let mut depth = 1;
            i += 1;
            while i < self.input.len() && depth > 0 {
                match self.input[i] {
                    b'"' | b'\'' => {
                        // Skip quoted string inside the flow
                        let quote = self.input[i];
                        i += 1;
                        while i < self.input.len() {
                            if self.input[i] == quote {
                                if quote == b'\''
                                    && i + 1 < self.input.len()
                                    && self.input[i + 1] == b'\''
                                {
                                    i += 2;
                                    continue;
                                }
                                i += 1;
                                break;
                            } else if self.input[i] == b'\\' && quote == b'"' {
                                i += 2;
                            } else {
                                i += 1;
                            }
                        }
                    }
                    c if c == open => {
                        depth += 1;
                        i += 1;
                    }
                    c if c == close => {
                        depth -= 1;
                        i += 1;
                    }
                    _ => i += 1,
                }
            }
            // After the flow, check for colon - can be adjacent (no space required)
            if i < self.input.len() && self.input[i] == b':' {
                return true;
            }
            return false;
        }

        // Scan unquoted content for `: ` pattern
        while i < self.input.len() {
            match self.input[i] {
                b',' | b']' | b'}' | b'\n' => return false,
                b':' => {
                    let next = if i + 1 < self.input.len() {
                        Some(self.input[i + 1])
                    } else {
                        None
                    };
                    // In flow context, colon must be followed by space, or flow indicator
                    return matches!(
                        next,
                        Some(b' ') | Some(b'\t') | Some(b',') | Some(b']') | Some(b'}') | None
                    );
                }
                _ => i += 1,
            }
        }
        false
    }

    /// Check if we're looking at an explicit key indicator `?` in flow context
    fn looks_like_explicit_flow_key(&self) -> bool {
        self.peek() == Some(b'?')
            && matches!(
                self.peek_at(1),
                Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') | None
            )
    }

    /// Parse an explicit mapping entry in flow context: `? key : value`
    /// Creates a single-pair mapping as the sequence element.
    fn parse_explicit_flow_mapping_entry(&mut self) -> Result<(), YamlError> {
        // Open implicit mapping
        self.set_ib();
        self.write_bp_open();
        self.write_ty(false); // 0 = mapping

        // Skip `?`
        self.advance();
        self.skip_flow_whitespace();

        // Parse key - can be scalar, quoted, flow mapping, or flow sequence
        self.set_ib();
        self.write_bp_open();
        let key_end = match self.peek() {
            Some(b'{') => {
                self.parse_flow_mapping()?;
                self.pos
            }
            Some(b'[') => {
                self.parse_flow_sequence()?;
                self.pos
            }
            Some(b':') => {
                // Empty key (null) - ?: means null key
                // Don't consume anything, write empty node
                self.pos
            }
            Some(b',') | Some(b']') | Some(b'}') => {
                // Empty key (null) - ? followed by terminator
                self.pos
            }
            _ => self.parse_explicit_flow_key_scalar()?,
        };
        self.set_bp_text_end(key_end);
        self.write_bp_close();

        // Skip whitespace before possible colon
        self.skip_flow_whitespace();

        // Check for colon (explicit value indicator)
        if self.peek() == Some(b':') {
            self.advance();
            self.skip_flow_whitespace();

            // Parse value (if present before , or ])
            if !matches!(self.peek(), Some(b',') | Some(b']') | Some(b'}') | None) {
                self.set_ib();
                self.write_bp_open();
                match self.peek() {
                    Some(b'[') => {
                        self.parse_flow_sequence()?;
                        self.set_bp_text_end(self.pos);
                    }
                    Some(b'{') => {
                        self.parse_flow_mapping()?;
                        self.set_bp_text_end(self.pos);
                    }
                    _ => {
                        let end = self.parse_flow_scalar()?;
                        self.set_bp_text_end(end);
                    }
                }
                self.write_bp_close();
            } else {
                // Empty value (null)
                self.set_ib();
                self.write_bp_open();
                // Null has no text end
                self.write_bp_close();
            }
        } else {
            // No colon - value is null
            self.write_bp_open_at(self.input.len());
            // Null has no text end
            self.write_bp_close();
        }

        // Close implicit mapping
        self.write_bp_close();

        Ok(())
    }

    /// Parse an implicit mapping entry in flow context: `key : value`
    /// Creates a single-pair mapping as the sequence element.
    fn parse_implicit_flow_mapping_entry(&mut self) -> Result<(), YamlError> {
        // Open implicit mapping
        self.set_ib();
        self.write_bp_open();
        self.write_ty(false); // 0 = mapping

        // Parse key - can be scalar, quoted, flow mapping, or flow sequence
        self.set_ib();
        self.write_bp_open();
        let key_end = match self.peek() {
            Some(b'{') => {
                self.parse_flow_mapping()?;
                self.pos
            }
            Some(b'[') => {
                self.parse_flow_sequence()?;
                self.pos
            }
            _ => self.parse_flow_key_scalar()?,
        };
        self.set_bp_text_end(key_end);
        self.write_bp_close();

        // Skip whitespace before colon
        self.skip_inline_whitespace();

        // Expect and skip colon
        if self.peek() != Some(b':') {
            return Err(YamlError::UnexpectedCharacter {
                offset: self.pos,
                char: self.peek().map(|b| b as char).unwrap_or('\0'),
                context: "expected ':' in implicit flow mapping entry",
            });
        }
        self.advance();
        self.skip_flow_whitespace();

        // Parse value (if present before , or ])
        if !matches!(self.peek(), Some(b',') | Some(b']') | Some(b'}') | None) {
            self.set_ib();
            self.write_bp_open();
            let val_end = match self.peek() {
                Some(b'[') => {
                    self.parse_flow_sequence()?;
                    self.pos
                }
                Some(b'{') => {
                    self.parse_flow_mapping()?;
                    self.pos
                }
                _ => self.parse_flow_scalar()?,
            };
            self.set_bp_text_end(val_end);
            self.write_bp_close();
        } else {
            // Empty value (null)
            self.set_ib();
            self.write_bp_open();
            // Null has no text end
            self.write_bp_close();
        }

        // Close implicit mapping
        self.write_bp_close();

        Ok(())
    }

    /// Parse a flow sequence: `[item1, item2, ...]`
    fn parse_flow_sequence(&mut self) -> Result<(), YamlError> {
        // Mark the `[` position
        self.set_ib();

        // Open sequence container
        self.write_bp_open();
        self.write_ty(true); // 1 = sequence

        // Skip `[`
        self.advance();
        self.skip_flow_whitespace();

        // Parse items
        let mut first = true;
        while self.peek() != Some(b']') {
            if self.peek().is_none() {
                return Err(YamlError::UnexpectedEof {
                    context: "flow sequence",
                });
            }

            if !first {
                // Expect comma
                if self.peek() != Some(b',') {
                    return Err(YamlError::UnexpectedCharacter {
                        offset: self.pos,
                        char: self.peek().map(|b| b as char).unwrap_or('\0'),
                        context: "expected ',' or ']' in flow sequence",
                    });
                }
                self.advance(); // Skip `,`
                self.skip_flow_whitespace();

                // Allow trailing comma
                if self.peek() == Some(b']') {
                    break;
                }
            }
            first = false;

            // Check for anchor first - it prefixes the actual value
            if self.peek() == Some(b'&') {
                self.parse_anchor()?;
            }

            // Check for alias - this IS the value
            if self.peek() == Some(b'*') {
                self.parse_alias()?;
                self.skip_flow_whitespace();
                continue;
            }

            // Check for explicit key `? key : value` in flow context
            if self.looks_like_explicit_flow_key() {
                self.parse_explicit_flow_mapping_entry()?;
            } else if self.looks_like_flow_mapping_entry() {
                // Check for implicit mapping entry (handles all key types including { and [)
                // This is an implicit single-pair mapping: [ key : value ]
                self.parse_implicit_flow_mapping_entry()?;
            } else {
                // Parse flow value (item) - containers handle their own BP
                match self.peek() {
                    Some(b'[') => {
                        self.parse_flow_sequence()?;
                    }
                    Some(b'{') => {
                        self.parse_flow_mapping()?;
                    }
                    _ => {
                        // Plain scalar value - wrap in BP
                        self.set_ib();
                        self.write_bp_open();
                        let end = self.parse_flow_scalar()?;
                        self.set_bp_text_end(end);
                        self.write_bp_close();
                    }
                }
            }
            self.skip_flow_whitespace();
        }

        // Skip `]`
        if self.peek() == Some(b']') {
            self.set_ib();
            self.advance();
        }

        // Close sequence
        self.write_bp_close();

        Ok(())
    }

    /// Parse a flow mapping: `{key: value, ...}`
    fn parse_flow_mapping(&mut self) -> Result<(), YamlError> {
        // Mark the `{` position
        self.set_ib();

        // Open mapping container
        self.write_bp_open();
        self.write_ty(false); // 0 = mapping

        // Skip `{`
        self.advance();
        self.skip_flow_whitespace();

        // Parse key-value pairs
        let mut first = true;
        while self.peek() != Some(b'}') {
            if self.peek().is_none() {
                return Err(YamlError::UnexpectedEof {
                    context: "flow mapping",
                });
            }

            if !first {
                // Expect comma
                if self.peek() != Some(b',') {
                    return Err(YamlError::UnexpectedCharacter {
                        offset: self.pos,
                        char: self.peek().map(|b| b as char).unwrap_or('\0'),
                        context: "expected ',' or '}' in flow mapping",
                    });
                }
                self.advance(); // Skip `,`
                self.skip_flow_whitespace();

                // Allow trailing comma
                if self.peek() == Some(b'}') {
                    break;
                }
            }
            first = false;

            // Parse key
            self.set_ib();
            self.write_bp_open();
            self.parse_flow_key()?;
            self.set_bp_text_end(self.pos);
            self.write_bp_close();

            self.skip_flow_whitespace();

            // Check for colon - if missing, value is implicitly null
            if self.peek() == Some(b':') {
                self.advance(); // Skip `:`
                self.skip_flow_whitespace();

                // Parse value - check for anchor or alias first
                // Check for anchor prefix on value
                let _anchor_name = if self.peek() == Some(b'&') {
                    Some(self.parse_anchor()?)
                } else {
                    None
                };

                // Check for alias (standalone value)
                if self.peek() == Some(b'*') {
                    self.parse_alias()?;
                } else {
                    // Parse the actual value - for nested containers, they handle their own BP
                    match self.peek() {
                        Some(b'[') => {
                            self.parse_flow_sequence()?;
                        }
                        Some(b'{') => {
                            self.parse_flow_mapping()?;
                        }
                        _ => {
                            // Scalar value - wrap in BP
                            self.set_ib();
                            self.write_bp_open();
                            let end = self.parse_flow_scalar()?;
                            self.set_bp_text_end(end);
                            self.write_bp_close();
                        }
                    }
                }
            } else if matches!(self.peek(), Some(b',') | Some(b'}')) {
                // Key without colon/value - emit empty value (implicit null)
                self.set_ib();
                self.write_bp_open();
                // Null has no text end
                self.write_bp_close();
            } else {
                return Err(YamlError::UnexpectedCharacter {
                    offset: self.pos,
                    char: self.peek().map(|b| b as char).unwrap_or('\0'),
                    context: "expected ':', ',' or '}' after key in flow mapping",
                });
            }

            self.skip_flow_whitespace();
        }

        // Skip `}`
        if self.peek() == Some(b'}') {
            self.set_ib();
            self.advance();
        }

        // Close mapping
        self.write_bp_close();

        Ok(())
    }

    /// Parse a key in flow context.
    /// Keys can be scalars, flow sequences, or flow mappings (complex keys).
    fn parse_flow_key(&mut self) -> Result<(), YamlError> {
        // Check for anchor on key
        if self.peek() == Some(b'&') {
            let _ = self.parse_anchor()?;
            self.skip_flow_whitespace();
        }

        // Check for explicit key indicator
        if self.looks_like_explicit_flow_key() {
            // Skip `?`
            self.advance();
            self.skip_flow_whitespace();
            // Parse the actual key
            match self.peek() {
                Some(b'"') => {
                    self.parse_double_quoted()?;
                }
                Some(b'\'') => {
                    self.parse_single_quoted()?;
                }
                Some(b'[') => {
                    self.parse_flow_sequence()?;
                }
                Some(b'{') => {
                    self.parse_flow_mapping()?;
                }
                Some(b':') | Some(b',') | Some(b'}') => {
                    // Empty key (null) - don't consume anything
                }
                _ => {
                    self.parse_explicit_flow_unquoted_key()?;
                }
            }
            return Ok(());
        }

        match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
            }
            Some(b'[') => {
                // Flow sequence as key (complex key)
                self.parse_flow_sequence()?;
            }
            Some(b'{') => {
                // Flow mapping as key (complex key)
                self.parse_flow_mapping()?;
            }
            Some(b'*') => {
                // Alias as key
                self.parse_alias()?;
            }
            _ => {
                self.parse_flow_unquoted_key()?;
            }
        }
        Ok(())
    }

    /// Parse an unquoted key in flow context.
    /// Stops at `:`, `,`, `}`, `]`, or whitespace before those.
    /// Handles multiline keys (continues across newlines with proper indentation).
    fn parse_flow_unquoted_key(&mut self) -> Result<usize, YamlError> {
        let start = self.pos;

        while let Some(b) = self.peek() {
            match b {
                b':' | b',' | b'}' | b']' => break,
                b'\n' | b'\r' => {
                    // Multiline key - check if next line continues the key
                    let mut lookahead = self.pos;
                    // Skip newline
                    if lookahead < self.input.len() && self.input[lookahead] == b'\r' {
                        lookahead += 1;
                    }
                    if lookahead < self.input.len() && self.input[lookahead] == b'\n' {
                        lookahead += 1;
                    }
                    // Skip leading whitespace on next line
                    while lookahead < self.input.len()
                        && matches!(self.input[lookahead], b' ' | b'\t')
                    {
                        lookahead += 1;
                    }
                    // Check what follows
                    if lookahead >= self.input.len()
                        || matches!(self.input[lookahead], b':' | b',' | b'}' | b']')
                    {
                        // Delimiter or EOF - stop key here
                        break;
                    }
                    // Continue parsing on next line
                    self.advance(); // Skip newline char(s)
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                    // Skip leading whitespace
                    while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                        self.advance();
                    }
                }
                b' ' | b'\t' => {
                    // Check if whitespace is followed by a delimiter
                    let mut lookahead = self.pos + 1;
                    while lookahead < self.input.len() {
                        match self.input[lookahead] {
                            b' ' | b'\t' => lookahead += 1,
                            b':' | b',' | b'}' | b']' => {
                                // Whitespace before delimiter - stop here
                                break;
                            }
                            b'\n' | b'\r' => {
                                // Newline - check next line
                                break;
                            }
                            _ => {
                                // Continue with the key
                                self.advance();
                                break;
                            }
                        }
                    }
                    if lookahead == self.input.len()
                        || matches!(
                            self.input[lookahead],
                            b':' | b',' | b'}' | b']' | b'\n' | b'\r'
                        )
                    {
                        break;
                    }
                }
                _ => self.advance(),
            }
        }

        // Trim trailing whitespace
        let mut end = self.pos;
        while end > start && matches!(self.input[end - 1], b' ' | b'\t') {
            end -= 1;
        }

        // Empty key is valid in YAML (e.g., `[ : value ]`)
        // Return absolute end position
        Ok(end)
    }

    /// Parse a scalar value in flow context (string or unquoted).
    fn parse_flow_scalar(&mut self) -> Result<usize, YamlError> {
        let end = match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
                self.pos
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
                self.pos
            }
            _ => self.parse_flow_unquoted_value(),
        };
        Ok(end)
    }

    /// Parse a flow key (for implicit mapping entries).
    /// Like parse_flow_scalar but also stops at `: ` (colon followed by space/flow indicator).
    fn parse_flow_key_scalar(&mut self) -> Result<usize, YamlError> {
        let end = match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
                self.pos
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
                self.pos
            }
            _ => {
                // Use existing parse_flow_unquoted_key which stops at `:`
                self.parse_flow_unquoted_key()?
            }
        };
        Ok(end)
    }

    /// Parse an unquoted value in flow context.
    /// Stops at `,`, `}`, `]`, `#` (comment), or newline.
    /// Returns the absolute end position (with trailing whitespace trimmed).
    fn parse_flow_unquoted_value(&mut self) -> usize {
        let start = self.pos;

        while let Some(b) = self.peek() {
            match b {
                b',' | b'}' | b']' => break,
                b'#' => {
                    // # is a comment if preceded by whitespace
                    if self.pos > start && matches!(self.input[self.pos - 1], b' ' | b'\t') {
                        break;
                    }
                    self.advance();
                }
                b'\n' | b'\r' => {
                    // Multiline value - check if next line continues the value
                    let mut lookahead = self.pos;
                    // Skip newline
                    if lookahead < self.input.len() && self.input[lookahead] == b'\r' {
                        lookahead += 1;
                    }
                    if lookahead < self.input.len() && self.input[lookahead] == b'\n' {
                        lookahead += 1;
                    }
                    // Skip leading whitespace on next line
                    while lookahead < self.input.len()
                        && matches!(self.input[lookahead], b' ' | b'\t')
                    {
                        lookahead += 1;
                    }
                    // Check what follows
                    if lookahead >= self.input.len()
                        || matches!(self.input[lookahead], b',' | b'}' | b']' | b'#')
                    {
                        // Delimiter, comment, or EOF - stop value here
                        break;
                    }
                    // Continue parsing on next line
                    self.advance(); // Skip \r if present
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                    // Skip leading whitespace
                    while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                        self.advance();
                    }
                }
                _ => self.advance(),
            }
        }

        // Trim trailing whitespace
        let mut end = self.pos;
        while end > start && matches!(self.input[end - 1], b' ' | b'\t') {
            end -= 1;
        }

        end
    }

    /// Parse an explicit flow key scalar.
    /// Unlike implicit flow keys which stop at `:`, explicit keys stop at `: ` (colon+space)
    /// because the colon is part of the explicit value syntax.
    fn parse_explicit_flow_key_scalar(&mut self) -> Result<usize, YamlError> {
        let end = match self.peek() {
            Some(b'"') => {
                self.parse_double_quoted()?;
                self.pos
            }
            Some(b'\'') => {
                self.parse_single_quoted()?;
                self.pos
            }
            _ => self.parse_explicit_flow_unquoted_key()?,
        };
        Ok(end)
    }

    /// Parse an explicit unquoted key in flow context.
    /// Stops at `: ` (colon followed by whitespace) or flow delimiters, but NOT at bare `:`.
    fn parse_explicit_flow_unquoted_key(&mut self) -> Result<usize, YamlError> {
        let start = self.pos;

        while let Some(b) = self.peek() {
            match b {
                b',' | b'}' | b']' => break,
                b':' => {
                    // Only stop at `: ` or `:\n` or `:` at end
                    let next = self.peek_at(1);
                    if matches!(
                        next,
                        Some(b' ')
                            | Some(b'\t')
                            | Some(b'\n')
                            | Some(b'\r')
                            | Some(b',')
                            | Some(b'}')
                            | Some(b']')
                            | None
                    ) {
                        break;
                    }
                    // Colon not followed by space - include it in the key
                    self.advance();
                }
                b'\n' | b'\r' => {
                    // Multiline key - check if next line continues the key
                    let mut lookahead = self.pos;
                    // Skip newline
                    if lookahead < self.input.len() && self.input[lookahead] == b'\r' {
                        lookahead += 1;
                    }
                    if lookahead < self.input.len() && self.input[lookahead] == b'\n' {
                        lookahead += 1;
                    }
                    // Skip leading whitespace on next line
                    while lookahead < self.input.len()
                        && matches!(self.input[lookahead], b' ' | b'\t')
                    {
                        lookahead += 1;
                    }
                    // Check what follows
                    if lookahead >= self.input.len()
                        || matches!(self.input[lookahead], b',' | b'}' | b']')
                    {
                        // Delimiter or EOF - stop key here
                        break;
                    }
                    // Check for `: ` on next line (explicit value indicator)
                    if lookahead + 1 < self.input.len()
                        && self.input[lookahead] == b':'
                        && matches!(self.input[lookahead + 1], b' ' | b'\t' | b'\n' | b'\r')
                    {
                        // Explicit value indicator - stop key here
                        break;
                    }
                    // Check for single `:` followed by flow delimiter
                    if lookahead < self.input.len()
                        && self.input[lookahead] == b':'
                        && (lookahead + 1 >= self.input.len()
                            || matches!(self.input[lookahead + 1], b',' | b'}' | b']'))
                    {
                        break;
                    }
                    // Continue parsing on next line
                    self.advance(); // Skip newline char(s)
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                    // Skip leading whitespace
                    while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                        self.advance();
                    }
                }
                b' ' | b'\t' => {
                    // Check if whitespace is followed by `: ` or a delimiter
                    let mut lookahead = self.pos + 1;
                    while lookahead < self.input.len()
                        && matches!(self.input[lookahead], b' ' | b'\t')
                    {
                        lookahead += 1;
                    }
                    if lookahead < self.input.len() {
                        match self.input[lookahead] {
                            b':' => {
                                // Check if colon is followed by space/end
                                let after_colon = if lookahead + 1 < self.input.len() {
                                    Some(self.input[lookahead + 1])
                                } else {
                                    None
                                };
                                if matches!(
                                    after_colon,
                                    Some(b' ')
                                        | Some(b'\t')
                                        | Some(b'\n')
                                        | Some(b'\r')
                                        | Some(b',')
                                        | Some(b'}')
                                        | Some(b']')
                                        | None
                                ) {
                                    // Whitespace before `: ` - stop here
                                    break;
                                }
                                // Colon not followed by space - continue with the key
                                self.advance();
                            }
                            b',' | b'}' | b']' => {
                                // Whitespace before delimiter - stop here
                                break;
                            }
                            b'\n' | b'\r' => {
                                // Newline - check next line
                                break;
                            }
                            _ => {
                                // Continue with the key
                                self.advance();
                            }
                        }
                    } else {
                        break;
                    }
                }
                _ => self.advance(),
            }
        }

        // Trim trailing whitespace
        let mut end = self.pos;
        while end > start && matches!(self.input[end - 1], b' ' | b'\t') {
            end -= 1;
        }

        // Return absolute end position
        Ok(end)
    }

    // =========================================================================
    // Block scalar parsing (Phase 3)
    // =========================================================================

    /// Parse the header of a block scalar (indicator + modifiers).
    /// Returns the header info and advances past the header.
    fn parse_block_scalar_header(&mut self) -> Result<BlockScalarHeader, YamlError> {
        let style = match self.peek() {
            Some(b'|') => BlockStyle::Literal,
            Some(b'>') => BlockStyle::Folded,
            _ => {
                return Err(YamlError::UnexpectedCharacter {
                    offset: self.pos,
                    char: self.peek().map(|b| b as char).unwrap_or('\0'),
                    context: "expected block scalar indicator (| or >)",
                });
            }
        };
        self.advance(); // consume indicator

        let mut chomping = ChompingIndicator::Clip;
        let mut explicit_indent: u8 = 0;

        // Parse optional modifiers (order can vary: |2- or |-2)
        for _ in 0..2 {
            match self.peek() {
                Some(b'-') => {
                    chomping = ChompingIndicator::Strip;
                    self.advance();
                }
                Some(b'+') => {
                    chomping = ChompingIndicator::Keep;
                    self.advance();
                }
                Some(c) if c.is_ascii_digit() && c != b'0' => {
                    explicit_indent = c - b'0';
                    self.advance();
                }
                _ => break,
            }
        }

        Ok(BlockScalarHeader {
            style,
            chomping,
            explicit_indent,
        })
    }

    /// Detect content indentation from the first non-empty line.
    /// Returns the indentation level, or None if block is empty.
    fn detect_block_content_indent(&mut self, base_indent: usize) -> Option<usize> {
        let saved_pos = self.pos;

        // Scan ahead to find first non-empty line
        loop {
            if self.peek().is_none() {
                // EOF - empty block scalar
                self.pos = saved_pos;
                return None;
            }

            // Count spaces at start of line (SIMD accelerated)
            let indent = self.skip_spaces_simd();

            // Check what's on this line
            match self.peek() {
                Some(b'\n') => {
                    // Empty line - skip and continue
                    self.advance();
                }
                Some(b'#') => {
                    // Comment line - skip to end
                    self.skip_to_eol();
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                }
                Some(b'\r') => {
                    // Handle \r\n
                    self.advance();
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                }
                None => {
                    // EOF
                    self.pos = saved_pos;
                    return None;
                }
                _ => {
                    // Found content - restore position and return indent
                    self.pos = saved_pos;

                    if indent <= base_indent {
                        // Content must be more indented than indicator
                        return None;
                    }
                    return Some(indent);
                }
            }
        }
    }

    /// Consume block scalar content lines until indentation drops.
    /// Returns the end position of the content (before trailing newlines based on chomping).
    fn consume_block_scalar_content(
        &mut self,
        content_indent: usize,
        chomping: ChompingIndicator,
    ) -> usize {
        // Use SIMD to quickly find where the block scalar ends
        let block_end = simd::find_block_scalar_end(self.input, self.pos, content_indent)
            .unwrap_or(self.input.len());

        // Now we need to walk through the content to find:
        // 1. last_content_end - position after last non-empty line
        // 2. trailing_newline_start - where trailing newlines begin
        let mut last_content_end = self.pos;
        let mut trailing_newline_start = self.pos;

        while self.pos < block_end {
            let line_start = self.pos;

            // Count spaces at start of line (SIMD accelerated)
            let _line_indent = self.skip_spaces_simd();

            // Check what's on this line
            match self.peek() {
                Some(b'\n') => {
                    // Empty line - part of trailing newlines
                    trailing_newline_start = line_start;
                    self.advance();
                }
                Some(b'\r') => {
                    // Handle \r\n
                    trailing_newline_start = line_start;
                    self.advance();
                    if self.peek() == Some(b'\n') {
                        self.advance();
                    }
                }
                None => {
                    break; // EOF
                }
                _ => {
                    // This is a content line - skip to end
                    self.skip_to_eol();
                    last_content_end = self.pos;
                    trailing_newline_start = self.pos;

                    if self.peek() == Some(b'\n') {
                        self.advance();
                    } else if self.peek() == Some(b'\r') {
                        self.advance();
                        if self.peek() == Some(b'\n') {
                            self.advance();
                        }
                    }
                }
            }
        }

        // Position should now be at block_end
        self.pos = block_end;

        // Return position based on chomping
        match chomping {
            ChompingIndicator::Strip => last_content_end,
            ChompingIndicator::Clip => {
                // Include one trailing newline if there was content
                if last_content_end > 0 && trailing_newline_start > last_content_end {
                    last_content_end + 1 // Include one newline
                } else {
                    last_content_end
                }
            }
            ChompingIndicator::Keep => self.pos, // Include all trailing newlines
        }
    }

    /// Parse a block scalar (| or >) including all content lines.
    fn parse_block_scalar(&mut self, base_indent: usize) -> Result<(), YamlError> {
        // Mark the indicator position
        self.set_ib();
        self.write_bp_open();

        // Parse the header
        let header = self.parse_block_scalar_header()?;

        // Skip to end of indicator line (may have trailing comment)
        self.skip_to_eol();
        if self.peek() == Some(b'\n') {
            self.advance();
        } else if self.peek() == Some(b'\r') {
            self.advance();
            if self.peek() == Some(b'\n') {
                self.advance();
            }
        }

        // Determine content indentation
        let content_indent = if header.explicit_indent > 0 {
            base_indent + header.explicit_indent as usize
        } else {
            // Auto-detect from first content line
            match self.detect_block_content_indent(base_indent) {
                Some(indent) => indent,
                None => {
                    // Empty block scalar
                    self.set_bp_text_end(self.pos);
                    self.write_bp_close();
                    return Ok(());
                }
            }
        };

        // Consume content lines
        let content_end = self.consume_block_scalar_content(content_indent, header.chomping);

        // Close the block scalar node
        self.set_bp_text_end(content_end);
        self.write_bp_close();

        Ok(())
    }

    // =========================================================================
    // Anchor and alias parsing (Phase 4)
    // =========================================================================

    /// Parse an anchor name (characters after `&` or `*`).
    /// Valid anchor names: `[a-zA-Z0-9_-]+` (YAML 1.2 compliant)
    fn parse_anchor_name(&mut self) -> Result<String, YamlError> {
        let start = self.pos;

        // Use SIMD to find the end of the anchor name (P4 optimization)
        let end = simd::parse_anchor_name(self.input, start);
        self.pos = end;

        if self.pos == start {
            return Err(YamlError::InvalidAnchorName {
                offset: start,
                reason: "anchor name cannot be empty",
            });
        }

        // Convert to string
        let name = core::str::from_utf8(&self.input[start..self.pos])
            .map_err(|_| YamlError::InvalidUtf8 { offset: start })?
            .to_string();

        Ok(name)
    }

    /// Parse an anchor definition (`&name`).
    /// Records the anchor and returns, expecting the value to follow.
    fn parse_anchor(&mut self) -> Result<String, YamlError> {
        // Consume `&`
        self.advance();

        // Parse anchor name
        let name = self.parse_anchor_name()?;

        // Skip whitespace after anchor name
        self.skip_inline_whitespace();

        // Record anchor - will point to the next BP position (the value)
        // YAML allows anchor redefinition - later definitions override earlier ones
        // Store placeholder - will be updated when value BP is opened
        self.anchors.insert(name.clone(), self.bp_pos);

        Ok(name)
    }

    /// Parse an alias reference (`*name`).
    /// Creates a leaf node in the BP tree pointing to the aliased value.
    fn parse_alias(&mut self) -> Result<(), YamlError> {
        // Mark alias position
        self.set_ib();
        self.write_bp_open();

        // Consume `*`
        self.advance();

        // Parse anchor name
        let name = self.parse_anchor_name()?;

        // Resolve alias to anchor at parse time
        // This ensures we get the anchor definition that was active at this point
        let alias_bp_pos = self.bp_pos - 1;
        if let Some(&target_bp_pos) = self.anchors.get(&name) {
            self.aliases.insert(alias_bp_pos, target_bp_pos);
        }
        // Note: If anchor not found, we don't record it.
        // Forward references (alias before anchor) are not supported.

        // Close the alias node
        self.set_bp_text_end(self.pos);
        self.write_bp_close();

        Ok(())
    }

    /// Main parsing loop.
    fn parse(&mut self) -> Result<SemiIndex, YamlError> {
        if self.input.is_empty() {
            return Err(YamlError::EmptyInput);
        }

        // Skip initial whitespace and comments
        self.skip_newlines();

        // Open virtual root sequence (wraps all documents)
        // Position 0 with text position 0
        self.write_bp_open_at(0);
        self.write_ty(true); // Root is a sequence
        self.push_type(NodeType::Sequence);
        // Use usize::MAX as a sentinel indent for virtual root
        // This ensures document content at indent 0 creates its own container
        self.indent_stack[0] = usize::MAX;

        // Parse all documents (may be empty for comment-only files)
        if self.peek().is_some() {
            self.parse_documents()?;
        }

        // Close any remaining open document
        self.end_document();

        // Close virtual root sequence
        self.pop_type();
        self.write_bp_close();

        // Truncate over-allocated bitvectors to actual used length.
        // Parser pre-allocates worst-case (e.g., bp_words at input.len()/32 words)
        // but actual usage is typically much smaller (e.g., 1-2% for sparse YAML).
        let bp_word_count = self.bp_pos.div_ceil(64).max(1);
        let ty_word_count = self.ty_pos.div_ceil(64).max(1);

        let mut bp = core::mem::take(&mut self.bp_words);
        bp.truncate(bp_word_count);
        bp.shrink_to_fit();

        let mut ty = core::mem::take(&mut self.ty_words);
        ty.truncate(ty_word_count);
        ty.shrink_to_fit();

        let mut seq_items = core::mem::take(&mut self.seq_item_words);
        seq_items.truncate(bp_word_count);
        seq_items.shrink_to_fit();

        let mut containers = core::mem::take(&mut self.container_words);
        containers.truncate(bp_word_count);
        containers.shrink_to_fit();

        let mut bp_to_text = core::mem::take(&mut self.bp_to_text);
        bp_to_text.shrink_to_fit();

        let mut bp_to_text_end = core::mem::take(&mut self.bp_to_text_end);
        bp_to_text_end.shrink_to_fit();

        Ok(SemiIndex {
            ib: core::mem::take(&mut self.ib_words),
            bp,
            ty,
            bp_to_text,
            bp_to_text_end,
            seq_items,
            containers,
            ib_len: self.input.len(),
            bp_len: self.bp_pos,
            ty_len: self.ty_pos,
            anchors: core::mem::take(&mut self.anchors),
            aliases: core::mem::take(&mut self.aliases),
        })
    }

    /// Parse all documents in the stream.
    fn parse_documents(&mut self) -> Result<(), YamlError> {
        // Skip leading `---` if present (optional for first doc)
        if self.is_document_start() {
            self.skip_document_marker();

            // Check for inline content after `---` (e.g., `--- >` or `--- value`)
            if self.has_content_on_line() {
                self.start_document();
                self.parse_inline_document_value()?;
                // Don't skip newlines yet - let the main loop handle it
            } else {
                self.skip_newlines();
            }
        }

        // Check if file is empty after markers
        if self.peek().is_none() {
            // Empty YAML - nothing to parse
            return Ok(());
        }

        // Start first document if not already started
        if !self.in_document {
            self.start_document();
        }

        // Parse document content
        loop {
            self.skip_newlines();

            if self.peek().is_none() {
                break;
            }

            // Check for document end marker
            if self.is_document_end() {
                self.end_document();
                self.skip_document_marker();

                // Check for inline content after `...` (shouldn't normally have content)
                if !self.has_content_on_line() {
                    self.skip_newlines();
                }

                // Check for another document or EOF
                if self.peek().is_none() {
                    break;
                }

                // If there's a document start marker, skip it and check for inline content
                if self.is_document_start() {
                    self.skip_document_marker();
                    if self.has_content_on_line() {
                        self.start_document();
                        self.parse_inline_document_value()?;
                    } else {
                        self.skip_newlines();
                    }
                }

                // Start new document if there's content and not already started
                if self.peek().is_some() && !self.is_document_end() && !self.in_document {
                    self.start_document();
                }
                continue;
            }

            // Check for document start marker (new document)
            if self.is_document_start() {
                self.end_document();
                self.skip_document_marker();

                // Check for inline content after `---` (e.g., `--- >` or `--- value`)
                if self.has_content_on_line() {
                    self.start_document();
                    self.parse_inline_document_value()?;
                } else {
                    self.skip_newlines();
                    // Start new document if there's content
                    if self.peek().is_some() {
                        self.start_document();
                    }
                }
                continue;
            }

            // Parse document content
            self.parse_document_line()?;
        }

        Ok(())
    }

    /// Parse a single line of document content.
    fn parse_document_line(&mut self) -> Result<(), YamlError> {
        self.check_unsupported()?;

        // Count indentation - but handle tabs specially for flow structures
        let indent = match self.count_indent() {
            Ok(n) => n,
            Err(YamlError::TabIndentation { .. }) => {
                // Tabs found - check if this leads to a flow structure
                // Skip all leading whitespace (tabs and spaces)
                while matches!(self.peek(), Some(b' ') | Some(b'\t')) {
                    self.advance();
                }
                // If it's a flow structure, that's allowed
                match self.peek() {
                    Some(b'{') | Some(b'[') => {
                        self.close_deeper_indents(0);
                        self.parse_value(0)?;
                        // Move to next line if we haven't already
                        if self.peek() == Some(b'\n') {
                            self.advance();
                        }
                        return Ok(());
                    }
                    _ => {
                        // Not a flow structure - re-report the tab error
                        return Err(YamlError::TabIndentation {
                            line: self.current_line(),
                            offset: self.pos,
                        });
                    }
                }
            }
            Err(e) => return Err(e),
        };

        // Skip to content
        self.advance_by(indent);

        // close_deeper_indents will handle closing any SequenceItem entries
        // when we return to a lower indent level

        // Check what kind of content this is
        match self.peek() {
            Some(b'-')
                if matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') | None
                ) =>
            {
                self.parse_sequence_item(indent)?;
            }
            Some(b'?')
                if matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\n') | Some(b'\r') | None
                ) =>
            {
                // Explicit key indicator
                self.parse_explicit_key(indent)?;
            }
            Some(b':')
                if matches!(
                    self.peek_at(1),
                    Some(b' ') | Some(b'\n') | Some(b'\r') | None
                ) =>
            {
                // Explicit value indicator (value for previous explicit key)
                self.parse_explicit_value(indent)?;
            }
            Some(b'#') => {
                // Comment line - skip
                self.skip_to_eol();
            }
            Some(b'\n') => {
                // Empty line
                self.advance();
            }
            Some(b'{') | Some(b'[') => {
                // Flow mapping or sequence at document root
                self.close_deeper_indents(indent);
                self.parse_value(indent)?;
            }
            Some(b'&') => {
                // Anchor - check if this is `&anchor key: value` (anchor on mapping key)
                // In that case, let parse_mapping_entry handle the anchor so it points
                // to the key, not the mapping container.
                self.close_deeper_indents(indent);

                // Look ahead to see if this is `&anchor key:` pattern
                let is_anchor_on_mapping_key = {
                    let saved_pos = self.pos;
                    // Skip `&`
                    self.advance();
                    // Skip anchor name
                    while let Some(b) = self.peek() {
                        match b {
                            b' ' | b'\t' | b'\n' | b'\r' | b'[' | b']' | b'{' | b'}' | b',' => {
                                break
                            }
                            b':' => {
                                if let Some(next) = self.peek_at(1) {
                                    if next == b' '
                                        || next == b'\t'
                                        || next == b'\n'
                                        || next == b'\r'
                                    {
                                        break;
                                    }
                                }
                                self.advance();
                            }
                            _ => self.advance(),
                        }
                    }
                    // Skip whitespace after anchor
                    while self.peek() == Some(b' ') || self.peek() == Some(b'\t') {
                        self.advance();
                    }
                    // Check if what follows looks like a mapping entry
                    let result = self.looks_like_mapping_entry();
                    self.pos = saved_pos;
                    result
                };

                if is_anchor_on_mapping_key {
                    // Let parse_mapping_entry handle the anchor
                    self.parse_mapping_entry(indent)?;
                } else {
                    // Parse anchor here for non-mapping-key cases
                    let _anchor_name = self.parse_anchor()?;
                    // Skip any whitespace after anchor
                    self.skip_inline_whitespace();
                    // Check what follows
                    match self.peek() {
                        Some(b'\n') | None => {
                            // Anchor with value on next line - will be parsed in next iteration
                        }
                        Some(b'-')
                            if matches!(
                                self.peek_at(1),
                                Some(b' ') | Some(b'\t') | Some(b'\n') | None
                            ) =>
                        {
                            // Anchor before block sequence on same line
                            self.parse_sequence_item(indent)?;
                        }
                        Some(b'{') | Some(b'[') => {
                            // Anchor before flow collection
                            self.parse_value(indent)?;
                        }
                        _ => {
                            // Scalar value - only doc_root if not inside a container
                            self.set_ib();
                            self.write_bp_open();
                            // type_stack.len() == 1 means we're inside only the virtual root sequence
                            let is_truly_doc_root = self.type_stack.len() <= 1;
                            let end_pos = match self.peek() {
                                Some(b'"') => {
                                    self.parse_double_quoted()?;
                                    self.pos
                                }
                                Some(b'\'') => {
                                    self.parse_single_quoted()?;
                                    self.pos
                                }
                                _ => {
                                    if is_truly_doc_root {
                                        self.parse_unquoted_value_doc_root(indent)
                                    } else {
                                        self.parse_unquoted_value_with_indent(indent)
                                    }
                                }
                            };
                            self.set_bp_text_end(end_pos);
                            self.write_bp_close();
                        }
                    }
                }
            }
            Some(b'*') => {
                // Alias - could be a standalone value or a key in a mapping
                // Check if this is `*alias : value` pattern (alias as mapping key)
                if self.looks_like_mapping_entry() {
                    // Alias is a key - let parse_mapping_entry handle it
                    self.parse_mapping_entry(indent)?;
                } else {
                    // Standalone alias value
                    self.close_deeper_indents(indent);
                    self.parse_alias()?;
                }
            }
            Some(_) => {
                // Check if this looks like a mapping entry (has `: ` on this line)
                // This handles both quoted keys ("foo": bar) and unquoted keys (foo: bar)
                if self.looks_like_mapping_entry() {
                    self.parse_mapping_entry(indent)?;
                } else {
                    // Scalar value - either bare document scalar or value in a container
                    self.close_deeper_indents(indent);
                    self.set_ib();
                    self.write_bp_open();
                    // Only use doc_root mode if we're not inside any container
                    // type_stack.len() == 1 means we're inside only the virtual root sequence
                    let is_truly_doc_root = self.type_stack.len() <= 1;
                    let end_pos = match self.peek() {
                        Some(b'"') => {
                            self.parse_double_quoted()?;
                            self.pos
                        }
                        Some(b'\'') => {
                            self.parse_single_quoted()?;
                            self.pos
                        }
                        _ => {
                            if is_truly_doc_root {
                                self.parse_unquoted_value_doc_root(indent)
                            } else {
                                self.parse_unquoted_value_with_indent(indent)
                            }
                        }
                    };
                    self.set_bp_text_end(end_pos);
                    self.write_bp_close();
                }
            }
            None => {}
        }

        // Move to next line if we haven't already
        if self.peek() == Some(b'\n') {
            self.advance();
        }

        Ok(())
    }
}

/// Build a semi-index from YAML input.
pub fn build_semi_index(input: &[u8]) -> Result<SemiIndex, YamlError> {
    let mut parser = Parser::new(input);
    parser.parse()
}

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

    #[test]
    fn test_simple_mapping() {
        let yaml = b"name: Alice";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
        let index = result.unwrap();
        assert!(index.bp_len > 0);
    }

    #[test]
    fn test_simple_sequence() {
        let yaml = b"- item1\n- item2";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_nested_mapping() {
        let yaml = b"person:\n  name: Alice\n  age: 30";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_double_quoted_string() {
        let yaml = b"name: \"Alice\"";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_single_quoted_string() {
        let yaml = b"name: 'Alice'";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_comment() {
        let yaml = b"# This is a comment\nname: Alice";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_inline_comment() {
        let yaml = b"name: Alice # inline comment";
        let result = build_semi_index(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn test_tab_indentation_error() {
        let yaml = b"name:\n\tvalue";
        let result = build_semi_index(yaml);
        assert!(matches!(result, Err(YamlError::TabIndentation { .. })));
    }

    #[test]
    fn test_flow_sequence() {
        let yaml = b"items: [1, 2, 3]";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "Flow sequence should parse: {:?}", result);
    }

    #[test]
    fn test_flow_mapping() {
        let yaml = b"person: {name: Alice, age: 30}";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "Flow mapping should parse: {:?}", result);
    }

    #[test]
    fn test_flow_nested() {
        let yaml = b"data: {users: [{name: Alice}, {name: Bob}]}";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "Nested flow should parse: {:?}", result);
    }

    #[test]
    fn test_flow_with_strings() {
        let yaml = b"items: [\"hello\", 'world', plain]";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Flow with strings should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_flow_trailing_comma() {
        let yaml = b"items: [1, 2, 3,]";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Flow with trailing comma should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_flow_empty_sequence() {
        let yaml = b"items: []";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Empty flow sequence should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_flow_empty_mapping() {
        let yaml = b"data: {}";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Empty flow mapping should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_empty_input() {
        let yaml = b"";
        let result = build_semi_index(yaml);
        assert!(matches!(result, Err(YamlError::EmptyInput)));
    }

    #[test]
    fn test_whitespace_only() {
        // Whitespace-only is valid YAML (empty stream)
        let yaml = b"   \n\n  ";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Whitespace-only should parse as empty stream"
        );
    }

    // =========================================================================
    // Block scalar tests (Phase 3)
    // =========================================================================

    #[test]
    fn test_block_literal_basic() {
        let yaml = b"text: |\n  line1\n  line2\n";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "Block literal should parse: {:?}", result);
    }

    #[test]
    fn test_block_folded_basic() {
        let yaml = b"text: >\n  line1\n  line2\n";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "Block folded should parse: {:?}", result);
    }

    #[test]
    fn test_block_literal_strip() {
        let yaml = b"text: |-\n  content\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block literal strip should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_literal_keep() {
        let yaml = b"text: |+\n  content\n\n\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block literal keep should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_folded_strip() {
        let yaml = b"text: >-\n  content\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block folded strip should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_folded_keep() {
        let yaml = b"text: >+\n  content\n\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block folded keep should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_explicit_indent() {
        let yaml = b"text: |2\n  content\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block with explicit indent should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_explicit_indent_with_chomping() {
        let yaml = b"text: |2-\n  content\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block with explicit indent and chomping should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_empty() {
        let yaml = b"text: |\nnext: value\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Empty block scalar should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_in_sequence() {
        let yaml = b"- |\n  item\n- value\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block scalar in sequence should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_with_nested_indent() {
        let yaml = b"code: |\n  def foo():\n    return 42\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block with nested indent should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_multiple() {
        let yaml = b"one: |\n  first\ntwo: |\n  second\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Multiple block scalars should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_block_with_comment() {
        let yaml = b"text: | # this is a comment\n  content\n";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "Block scalar with comment should parse: {:?}",
            result
        );
    }

    // =========================================================================
    // Multi-document stream tests (Phase 5)
    // =========================================================================

    #[test]
    fn test_single_document_wrapped() {
        // Single document should be wrapped in virtual root sequence
        let yaml = b"name: Alice";
        let result = build_semi_index(yaml).unwrap();
        // Root is sequence (TY bit 0 = 1)
        assert!(result.ty[0] & 1 == 1, "root should be sequence");
        // At least 2 TY bits (root sequence + document mapping)
        assert!(result.ty_len >= 2, "should have at least 2 containers");
    }

    #[test]
    fn test_explicit_document_start() {
        // Leading `---` should be handled
        let yaml = b"---\nname: Alice";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "explicit document start should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_two_documents() {
        // Two documents separated by `---`
        let yaml = b"---\nname: Alice\n---\nname: Bob";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "two documents should parse: {:?}", result);
    }

    #[test]
    fn test_document_end_marker() {
        // Document end marker `...` followed by new document
        let yaml = b"---\nname: Alice\n...\n---\nname: Bob";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "document with end marker should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_document_end_at_eof() {
        // Document end marker at EOF
        let yaml = b"name: Alice\n...";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "document end at EOF should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_mixed_document_types() {
        // First document is sequence, second is mapping
        let yaml = b"---\n- item1\n- item2\n---\nkey: value";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "mixed document types should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_empty_between_markers() {
        // Empty content between document markers
        let yaml = b"---\n---\nname: Alice";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "empty document should parse: {:?}", result);
    }

    #[test]
    fn test_document_marker_in_flow() {
        // `---` inside a quoted string should not be treated as marker
        let yaml = b"text: \"---\"";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "quoted document marker should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_three_documents() {
        let yaml = b"---\na: 1\n---\nb: 2\n---\nc: 3";
        let result = build_semi_index(yaml);
        assert!(result.is_ok(), "three documents should parse: {:?}", result);
    }

    #[test]
    fn test_question_mark_in_value() {
        // Question mark should be allowed in plain scalar values
        let yaml = b"- a?string";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "question mark in value should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_question_mark_in_key() {
        // Question mark should be allowed in plain scalar keys
        let yaml = b"key?: value";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "question mark in key should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_question_mark_in_flow_key() {
        // Question mark in flow mapping key
        let yaml = b"{key?: value}";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "question mark in flow key should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_question_mark_in_flow_value() {
        // Question mark in flow mapping value
        let yaml = b"{key: value?}";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "question mark in flow value should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_question_marks_full() {
        // Full JR7V test case - question marks in various contexts
        let yaml = b"- a?string\n- another ? string\n- key: value?\n- [a?string]\n- [another ? string]\n- {key: value? }\n- {key: value?}\n- {key?: value }";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "question marks test should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_compact_mapping_in_sequence() {
        // This is `- key: value` - a compact mapping within a sequence item
        let yaml = b"- key: value";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "compact mapping in sequence should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_flow_mapping_in_sequence() {
        // Flow mapping inside sequence item with various spacing patterns
        let yaml = b"- { one : two , three: four , }\n- {five: six,seven : eight}";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "flow mapping in sequence should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_double_colon_plain_scalar() {
        // ::vector is a plain scalar, not a mapping entry
        let yaml = b"- ::vector";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "double colon plain scalar should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_quoted_key_mapping() {
        // Quoted keys with special characters
        let yaml = b"\"foo\": bar\n'single': value";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "quoted key mapping should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_empty_key_in_flow_sequence() {
        // CFD4: [ : empty key ]
        let yaml = b"- [ : empty key ]";
        let result = build_semi_index(yaml);
        assert!(
            result.is_ok(),
            "empty key in flow sequence should parse: {:?}",
            result
        );
    }

    #[test]
    fn test_explicit_empty_key() {
        // Test: `?\n: value` should parse as {null: "value"}
        use crate::jq::document::DocumentValue;
        use crate::jq::eval_generic::to_owned;
        use crate::yaml::light::YamlValue;
        use crate::yaml::YamlIndex;

        let yaml = b"?\n: value\n";
        let index = YamlIndex::build(yaml).expect("parse failed");

        // Debug: print BP structure
        eprintln!("BP len: {}", index.bp().len());
        for i in 0..index.bp().len() {
            let is_open = index.bp().is_open(i);
            eprintln!("BP {}: {}", i, if is_open { "OPEN" } else { "CLOSE" });
        }

        // Get the first document
        let doc_cursor = index.root(yaml).first_child().expect("no document");
        eprintln!("Doc value: {:?}", doc_cursor.value());

        // Check that it's a mapping
        match doc_cursor.value() {
            YamlValue::Mapping(fields) => {
                let mut count = 0;
                for field in fields {
                    let key_val = field.key();
                    eprintln!("Field: key={:?}, value={:?}", key_val, field.value());
                    // Test as_str on the key
                    eprintln!("  key.as_str() = {:?}", key_val.as_str());
                    eprintln!("  key.is_null() = {:?}", key_val.is_null());
                    count += 1;
                }
                eprintln!("Field count: {}", count);
                assert!(
                    count > 0,
                    "mapping should have at least one field, but has {}",
                    count
                );

                // Now test to_owned conversion
                eprintln!("\n=== Testing to_owned conversion ===");
                let owned = to_owned(&doc_cursor.value());
                eprintln!("to_owned result: {:?}", owned);
            }
            other => panic!("expected mapping, got {:?}", other),
        }
    }
}