ktav 0.7.0

Ktav — a plain configuration format. Three rules, zero indentation, zero quoting. Serde-native.
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
//! Unit tests for parser-internal helpers.

use super::classify::{classify_value_start, is_float_literal, try_parse_integer};
use super::insert::insert_value;
use super::validate::is_valid_key;
use super::value_start::ValueStart;

use crate::error::Span;
use crate::value::{ObjectMap, Value};

const S: Span = Span::EMPTY;

// --- validate ---------------------------------------------------------------

#[test]
fn valid_keys_accepted() {
    assert!(is_valid_key("port"));
    assert!(is_valid_key("a1"));
    assert!(is_valid_key("kebab-case"));
    assert!(is_valid_key("snake_case"));
    // Under 0.5.0, `#` is allowed inside keys
    assert!(is_valid_key("with#hash"));
    // Internal whitespace is allowed under 0.5.0
    assert!(is_valid_key("has space"));
    assert!(is_valid_key("first name"));
}

#[test]
fn invalid_keys_rejected() {
    assert!(!is_valid_key(""));
    assert!(!is_valid_key("with[bracket"));
    assert!(!is_valid_key("with]bracket"));
    assert!(!is_valid_key("with{brace"));
    assert!(!is_valid_key("with}brace"));
    // Spec 0.6.0 — `:` is permitted inside a DECODED key segment
    // (user expresses it via `\:`). `is_valid_key` runs on the
    // decoded form, so a literal `:` is no longer rejected here.
    assert!(is_valid_key("with:colon"));
    // Same for `.` — permitted in decoded form.
    assert!(is_valid_key("with.dot"));
    // Under 0.5.0+, `,` is still forbidden.
    assert!(!is_valid_key("with,comma"));
    assert!(!is_valid_key("with(paren"));
    assert!(!is_valid_key("with)paren"));
}

#[test]
fn paths_validated_segment_by_segment_via_insert() {
    // Path validation now lives inside `insert_value`; exercise it here
    // the same way the parser does.
    let mut t = ObjectMap::default();
    assert!(insert_value(&mut t, "a.b.c", Value::Null, 1, S).is_ok());

    let mut t = ObjectMap::default();
    assert!(insert_value(&mut t, "a", Value::Null, 1, S).is_ok());

    let mut t = ObjectMap::default();
    // empty segment inside the path
    assert!(insert_value(&mut t, "a..b", Value::Null, 1, S).is_err());

    let mut t = ObjectMap::default();
    // trailing dot -- final segment is empty
    assert!(insert_value(&mut t, "a.b.", Value::Null, 1, S).is_err());

    let mut t = ObjectMap::default();
    // lone dot -- two empty segments
    assert!(insert_value(&mut t, ".", Value::Null, 1, S).is_err());
}

// --- classify ---------------------------------------------------------------

#[test]
fn classify_scalar() {
    match classify_value_start("hello", 1, S, false).unwrap() {
        ValueStart::Scalar(s) => assert_eq!(s, "hello"),
        _ => panic!("expected Scalar"),
    }
}

#[test]
fn classify_keywords() {
    assert!(matches!(
        classify_value_start("null", 1, S, false).unwrap(),
        ValueStart::Null
    ));
    assert!(matches!(
        classify_value_start("true", 1, S, false).unwrap(),
        ValueStart::Bool(true)
    ));
    assert!(matches!(
        classify_value_start("false", 1, S, false).unwrap(),
        ValueStart::Bool(false)
    ));
}

#[test]
fn classify_case_sensitive_keywords() {
    // Only lowercase matches -- "True" / "NULL" are strings.
    match classify_value_start("True", 1, S, false).unwrap() {
        ValueStart::Scalar(s) => assert_eq!(s, "True"),
        _ => panic!("expected Scalar"),
    }
    match classify_value_start("NULL", 1, S, false).unwrap() {
        ValueStart::Scalar(s) => assert_eq!(s, "NULL"),
        _ => panic!("expected Scalar"),
    }
}

#[test]
fn classify_open_compounds() {
    assert!(matches!(
        classify_value_start("{", 1, S, false).unwrap(),
        ValueStart::OpenObject
    ));
    assert!(matches!(
        classify_value_start("[", 1, S, false).unwrap(),
        ValueStart::OpenArray
    ));
}

#[test]
fn classify_empty_inline_compounds() {
    assert!(matches!(
        classify_value_start("{}", 1, S, false).unwrap(),
        ValueStart::EmptyObject
    ));
    assert!(matches!(
        classify_value_start("[]", 1, S, false).unwrap(),
        ValueStart::EmptyArray
    ));
    assert!(matches!(
        classify_value_start("{ }", 1, S, false).unwrap(),
        ValueStart::EmptyObject
    ));
    assert!(matches!(
        classify_value_start("[  ]", 1, S, false).unwrap(),
        ValueStart::EmptyArray
    ));
}

#[test]
fn classify_inline_nonempty_accepted() {
    // Phase 4: inline compounds are now parsed into InlineValue
    match classify_value_start("{a: 1}", 1, S, false).unwrap() {
        ValueStart::InlineValue(v) => {
            assert!(v.as_object().is_some());
            let obj = v.as_object().unwrap();
            assert_eq!(obj.get("a"), Some(&Value::Integer("1".into())));
        }
        other => panic!(
            "expected InlineValue, got {:?}",
            std::mem::discriminant(&other)
        ),
    }
    match classify_value_start("[1, 2]", 1, S, false).unwrap() {
        ValueStart::InlineValue(v) => {
            let arr = v.as_array().unwrap();
            assert_eq!(arr.len(), 2);
            assert_eq!(arr[0], Value::Integer("1".into()));
            assert_eq!(arr[1], Value::Integer("2".into()));
        }
        other => panic!(
            "expected InlineValue, got {:?}",
            std::mem::discriminant(&other)
        ),
    }
}

// --- insert_value -----------------------------------------------------------

#[test]
fn insert_simple_pair() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, "port", Value::String("8080".into()), 1, S).unwrap();
    assert_eq!(t.get("port"), Some(&Value::String("8080".into())));
}

#[test]
fn insert_dotted_path_creates_intermediate_objects() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, "a.b.c", Value::String("x".into()), 1, S).unwrap();
    let a = t.get("a").unwrap().as_object().unwrap();
    let b = a.get("b").unwrap().as_object().unwrap();
    assert_eq!(b.get("c"), Some(&Value::String("x".into())));
}

#[test]
fn insert_duplicate_rejected() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, "x", Value::String("1".into()), 1, S).unwrap();
    let err = insert_value(&mut t, "x", Value::String("2".into()), 2, S);
    assert!(err.is_err());
}

#[test]
fn insert_scalar_then_nested_path_rejected() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, "a", Value::String("leaf".into()), 1, S).unwrap();
    let err = insert_value(&mut t, "a.b", Value::String("x".into()), 2, S);
    assert!(err.is_err());
}

// --- key trimming (0.5.0 § 4) ----------------------------------------------

#[test]
fn insert_trims_key_segments() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, " port ", Value::String("80".into()), 1, S).unwrap();
    assert_eq!(t.get("port"), Some(&Value::String("80".into())));
}

#[test]
fn insert_trims_dotted_key_segments() {
    let mut t = ObjectMap::default();
    insert_value(&mut t, " a . b . c ", Value::String("x".into()), 1, S).unwrap();
    let a = t.get("a").unwrap().as_object().unwrap();
    let b = a.get("b").unwrap().as_object().unwrap();
    assert_eq!(b.get("c"), Some(&Value::String("x".into())));
}

// --- integer literal parsing (0.5.0 § 3.6) ---------------------------------

#[test]
fn integer_decimal_basic() {
    assert_eq!(try_parse_integer("42"), Some(42));
    assert_eq!(try_parse_integer("0"), Some(0));
    assert_eq!(try_parse_integer("-7"), Some(-7));
    assert_eq!(try_parse_integer("+5"), Some(5));
}

#[test]
fn integer_decimal_underscores() {
    assert_eq!(try_parse_integer("1_000"), Some(1000));
    assert_eq!(try_parse_integer("1_000_000"), Some(1_000_000));
}

#[test]
fn integer_hex() {
    assert_eq!(try_parse_integer("0xFF"), Some(255));
    assert_eq!(try_parse_integer("0x1a"), Some(26));
    assert_eq!(try_parse_integer("-0x10"), Some(-16));
}

#[test]
fn integer_octal() {
    assert_eq!(try_parse_integer("0o77"), Some(63));
    assert_eq!(try_parse_integer("0o10"), Some(8));
}

#[test]
fn integer_binary() {
    assert_eq!(try_parse_integer("0b1010"), Some(10));
    assert_eq!(try_parse_integer("0b0"), Some(0));
}

#[test]
fn integer_rejects_bad_forms() {
    assert_eq!(try_parse_integer(""), None);
    assert_eq!(try_parse_integer("+"), None);
    assert_eq!(try_parse_integer("-"), None);
    assert_eq!(try_parse_integer("0x"), None);
    assert_eq!(try_parse_integer("0o"), None);
    assert_eq!(try_parse_integer("0b"), None);
    // Leading underscore
    assert_eq!(try_parse_integer("_42"), None);
    // Trailing underscore
    assert_eq!(try_parse_integer("42_"), None);
    // Double underscore
    assert_eq!(try_parse_integer("4__2"), None);
    // Underscore after prefix
    assert_eq!(try_parse_integer("0x_ff"), None);
    // Not a number
    assert_eq!(try_parse_integer("abc"), None);
    assert_eq!(try_parse_integer("hello"), None);
}

#[test]
fn integer_overflow_returns_none() {
    // i64::MAX + 1
    assert_eq!(try_parse_integer("9223372036854775808"), None);
}

#[test]
fn integer_i64_min() {
    assert_eq!(try_parse_integer("-9223372036854775808"), Some(i64::MIN));
}

#[test]
fn integer_i64_min_negative_prefixed_radixes() {
    // Magnitude 2^63 is exactly i64::MIN when negative, for every radix prefix.
    assert_eq!(try_parse_integer("-0x8000000000000000"), Some(i64::MIN));
    assert_eq!(
        try_parse_integer("-0o1000000000000000000000"),
        Some(i64::MIN)
    );
    assert_eq!(
        try_parse_integer("-0b1000000000000000000000000000000000000000000000000000000000000000"),
        Some(i64::MIN)
    );
}

#[test]
fn integer_prefixed_boundary_overflow_returns_none() {
    // Negative magnitude 2^63 + 1 overflows past i64::MIN in every radix.
    assert_eq!(try_parse_integer("-0x8000000000000001"), None);
    assert_eq!(try_parse_integer("-0o1000000000000000000001"), None);
    assert_eq!(
        try_parse_integer("-0b1000000000000000000000000000000000000000000000000000000000000001"),
        None
    );
    // POSITIVE magnitude 2^63 overflows i64::MAX — only the negative form is i64::MIN.
    assert_eq!(try_parse_integer("0x8000000000000000"), None);
    assert_eq!(try_parse_integer("0o1000000000000000000000"), None);
    assert_eq!(
        try_parse_integer("0b1000000000000000000000000000000000000000000000000000000000000000"),
        None
    );
}

#[test]
fn parse_negative_prefixed_i64_min_end_to_end() {
    // Full pipeline (§ 5.2 rule 13): -2^63 via each prefixed radix parses as
    // the integer i64::MIN, canonicalized to decimal text.
    for literal in [
        "-0x8000000000000000",
        "-0o1000000000000000000000",
        "-0b1000000000000000000000000000000000000000000000000000000000000000",
    ] {
        let doc = format!("x: {literal}");
        let v = crate::parse(&doc).unwrap();
        let obj = v.as_object().unwrap();
        assert_eq!(
            obj.get("x"),
            Some(&Value::Integer("-9223372036854775808".into())),
            "literal {literal}"
        );
    }
}

#[test]
fn parse_prefixed_overflow_falls_to_string_end_to_end() {
    // One past the boundary the integer parser returns None and the literal
    // falls through to String (§ 5.2 rule 13), not an error.
    for literal in ["-0x8000000000000001", "0x8000000000000000"] {
        let doc = format!("x: {literal}");
        let v = crate::parse(&doc).unwrap();
        let obj = v.as_object().unwrap();
        assert_eq!(obj.get("x"), Some(&Value::String(literal.into())));
    }
}

#[test]
fn parse_strict_negative_prefixed_i64_min() {
    // Strict mode rejects ALL prefixed radix literals as LossyScalar by
    // design (see `parse_strict` docs: `0x1A` is lossy) — even when the
    // value round-trips exactly to i64::MIN. Non-strict `parse` accepts
    // it (see parse_negative_prefixed_i64_min_end_to_end).
    let err = crate::parse_strict("x: -0x8000000000000000").unwrap_err();
    match err {
        crate::error::Error::Structured(crate::error::ErrorKind::LossyScalar { body, .. }) => {
            assert_eq!(body, "-0x8000000000000000");
        }
        other => panic!("expected LossyScalar, got {other:?}"),
    }
}

// --- float literal grammar (0.5.0 § 3.6) -----------------------------------

#[test]
fn float_with_decimal_point() {
    assert!(is_float_literal("3.14"));
    assert!(is_float_literal("0.0"));
    assert!(is_float_literal("-3.14"));
    assert!(is_float_literal("+3.14"));
}

#[test]
fn float_with_exponent_no_dot() {
    assert!(is_float_literal("1e10"));
    assert!(is_float_literal("1E10"));
    assert!(is_float_literal("-1e10"));
    assert!(is_float_literal("1e+10"));
    assert!(is_float_literal("1e-10"));
}

#[test]
fn float_with_dot_and_exponent() {
    assert!(is_float_literal("3.14e10"));
    assert!(is_float_literal("1.0E-3"));
}

#[test]
fn float_with_underscores() {
    assert!(is_float_literal("1_000.5"));
    assert!(is_float_literal("1.000_5"));
}

#[test]
fn float_rejects_bad_forms() {
    // Trailing dot
    assert!(!is_float_literal("1."));
    // Leading dot
    assert!(!is_float_literal(".5"));
    // Pure integer (no dot, no exponent)
    assert!(!is_float_literal("42"));
    // Empty exponent
    assert!(!is_float_literal("1e"));
    assert!(!is_float_literal("1e+"));
    // Not a number
    assert!(!is_float_literal("abc"));
}

// --- classify_value_start number inference (0.5.0 § 5.2 rules 13-14) -------

#[test]
fn classify_infers_integer() {
    match classify_value_start("42", 1, S, false).unwrap() {
        ValueStart::Integer(s) => assert_eq!(s, "42"),
        other => panic!("expected Integer, got {:?}", std::mem::discriminant(&other)),
    }
    match classify_value_start("-7", 1, S, false).unwrap() {
        ValueStart::Integer(s) => assert_eq!(s, "-7"),
        other => panic!("expected Integer, got {:?}", std::mem::discriminant(&other)),
    }
    // Hex produces canonical decimal
    match classify_value_start("0xFF", 1, S, false).unwrap() {
        ValueStart::Integer(s) => assert_eq!(s, "255"),
        other => panic!("expected Integer, got {:?}", std::mem::discriminant(&other)),
    }
}

#[test]
fn classify_infers_float() {
    match classify_value_start("3.14", 1, S, false).unwrap() {
        ValueStart::Float(_) => {}
        other => panic!("expected Float, got {:?}", std::mem::discriminant(&other)),
    }
    match classify_value_start("1e10", 1, S, false).unwrap() {
        ValueStart::Float(_) => {}
        other => panic!("expected Float, got {:?}", std::mem::discriminant(&other)),
    }
}

#[test]
fn classify_integer_overflow_falls_to_string() {
    // i64::MAX + 1 should be a String
    match classify_value_start("9223372036854775808", 1, S, false).unwrap() {
        ValueStart::Scalar(s) => assert_eq!(s, "9223372036854775808"),
        other => panic!(
            "expected Scalar (String), got {:?}",
            std::mem::discriminant(&other)
        ),
    }
}

// --- inline compound parsing (Phase 4) ------------------------------------

#[test]
fn parse_inline_object_single_pair() {
    let v = crate::parse("a: {name: alice}").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("name"), Some(&Value::String("alice".into())));
}

#[test]
fn parse_inline_object_multiple_pairs() {
    let v = crate::parse("server: {host: localhost, port: 8080, tls: true}").unwrap();
    let obj = v.as_object().unwrap();
    let server = obj.get("server").unwrap().as_object().unwrap();
    assert_eq!(server.get("host"), Some(&Value::String("localhost".into())));
    assert_eq!(server.get("port"), Some(&Value::Integer("8080".into())));
    assert_eq!(server.get("tls"), Some(&Value::Bool(true)));
}

#[test]
fn parse_inline_array_integers() {
    let v = crate::parse("a: [1, 2, 3]").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_array().unwrap();
    assert_eq!(a[0], Value::Integer("1".into()));
    assert_eq!(a[1], Value::Integer("2".into()));
    assert_eq!(a[2], Value::Integer("3".into()));
}

#[test]
fn parse_inline_nested_objects() {
    let v = crate::parse("cfg: {outer: {middle: {inner: deep}}}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    let outer = cfg.get("outer").unwrap().as_object().unwrap();
    let middle = outer.get("middle").unwrap().as_object().unwrap();
    assert_eq!(middle.get("inner"), Some(&Value::String("deep".into())));
}

#[test]
fn parse_inline_midvalue_brace_is_literal() {
    let v = crate::parse("cfg: {a: hello{world, b: x}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("hello{world".into())));
    assert_eq!(cfg.get("b"), Some(&Value::String("x".into())));
}

/// Regression tests for the § 5.2 rules 6–9 closer scan
/// (`scan_inline_closer`): nested compounds at value positions,
/// `::`-prefixed scalar items in arrays, and quote-path (slow-path)
/// bodies must all find their matching closer instead of tripping over
/// literal braces.
#[test]
fn parse_inline_closer_scan_value_positions_and_raw_items() {
    // Array whose first item is an object (value position after `[`).
    let v = crate::parse("x: [{b: 1}]").unwrap();
    let arr = v.as_object().unwrap().get("x").unwrap().as_array().unwrap();
    assert_eq!(
        arr[0].as_object().unwrap().get("b"),
        Some(&Value::Integer("1".into()))
    );

    // Array whose first item is a nested array.
    let v = crate::parse("x: [[1]]").unwrap();
    let arr = v.as_object().unwrap().get("x").unwrap().as_array().unwrap();
    let inner = arr[0].as_array().unwrap();
    assert_eq!(inner[0], Value::Integer("1".into()));

    // Nested at two levels inside object values.
    let v = crate::parse("{a: [{b: 1, c: 2}]}").unwrap();
    let a = v.as_object().unwrap().get("a").unwrap().as_array().unwrap();
    assert_eq!(
        a[0].as_object().unwrap().get("c"),
        Some(&Value::Integer("2".into()))
    );

    // A `::`-prefixed item is a plain <inline-scalar> (§ 4: an item
    // position derives only <inline-value>; the raw `::` branch exists
    // only at inline-PAIR positions). The scalar `:: {abc` terminates at
    // the FIRST unescaped closer (R5-F3) — that `}` mismatches the `[`
    // opener, so the array has no matching closer.
    match crate::parse("x: [:: {abc}]") {
        Err(crate::Error::Structured(crate::error::ErrorKind::UnterminatedInlineCompound {
            ..
        })) => {}
        other => panic!("expected UnterminatedInlineCompound, got {other:?}"),
    }
    match crate::parse("[:: {abc}]") {
        Err(crate::Error::Structured(crate::error::ErrorKind::UnterminatedInlineCompound {
            ..
        })) => {}
        other => panic!("expected UnterminatedInlineCompound, got {other:?}"),
    }
    // Escaping the closers keeps the braces in the scalar (§ 3.7); the
    // `::` prefix stays literal content, so the scalar is `:: {abc}` →
    // String (§ 5.2), and the unescaped `]` closes the array.
    let v = crate::parse("x: [:: \\{abc\\}]").unwrap();
    let arr = v.as_object().unwrap().get("x").unwrap().as_array().unwrap();
    assert_eq!(arr[0], Value::String(":: {abc}".into()));

    // Slow path (quote bytes present): array-of-object value after a
    // quoted key/value pair.
    let v = crate::parse("{k: \"v\", arr: [{b: 1}]}").unwrap();
    let obj = v.as_object().unwrap();
    let arr = obj.get("arr").unwrap().as_array().unwrap();
    assert_eq!(
        arr[0].as_object().unwrap().get("b"),
        Some(&Value::Integer("1".into()))
    );
    // § 5.3.3 opacity is keys-only, so the `]` inside the value quotes
    // is structural; it returns depth to zero without matching the
    // body's `}`, so the body has no matching closer (§ 5.2 rule 9)
    // and the document is rejected.
    assert!(crate::parse("{a: \"x] y\", b: 1}").is_err());

    // Root-position array with an object first item.
    let v = crate::parse("[{b: 1}]").unwrap();
    assert_eq!(
        v.as_array().unwrap()[0].as_object().unwrap().get("b"),
        Some(&Value::Integer("1".into()))
    );
}

#[test]
fn parse_inline_escape_comma() {
    let v = crate::parse("a: {greeting: hello\\, world}").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(
        a.get("greeting"),
        Some(&Value::String("hello, world".into()))
    );
}

#[test]
fn parse_inline_empty_value() {
    let v = crate::parse("a: {x:, y: 1}").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("x"), Some(&Value::String("".into())));
    assert_eq!(a.get("y"), Some(&Value::Integer("1".into())));
}

#[test]
fn parse_inline_trailing_comma() {
    let v = crate::parse("a: {name: alice, age: 30,}").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("name"), Some(&Value::String("alice".into())));
    assert_eq!(a.get("age"), Some(&Value::Integer("30".into())));
}

#[test]
fn parse_inline_no_whitespace() {
    let v = crate::parse("a: {x:1,y:2,z:3}").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("x"), Some(&Value::Integer("1".into())));
    assert_eq!(a.get("y"), Some(&Value::Integer("2".into())));
    assert_eq!(a.get("z"), Some(&Value::Integer("3".into())));
}

#[test]
fn parse_inline_dotted_keys() {
    let v = crate::parse("cfg: {a.b: 1, a.c: 2}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    let a = cfg.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("b"), Some(&Value::Integer("1".into())));
    assert_eq!(a.get("c"), Some(&Value::Integer("2".into())));
}

#[test]
fn parse_inline_escape_newline() {
    let v = crate::parse("multiline: {body: line1\\nline2\\nline3}").unwrap();
    let obj = v.as_object().unwrap();
    let ml = obj.get("multiline").unwrap().as_object().unwrap();
    assert_eq!(
        ml.get("body"),
        Some(&Value::String("line1\nline2\nline3".into()))
    );
}

// --- 0.7 § 3.7 / § 5.2: a recognised escape forces String ----------------

#[test]
fn parse_inline_escape_forces_string_not_float() {
    let v = crate::parse("cfg: {v: 1\\.0}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("1.0".into())));
}

#[test]
fn parse_inline_escape_forces_string_not_float_exponent() {
    let v = crate::parse("cfg: {v: 1\\.e2}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("1.e2".into())));
}

#[test]
fn parse_inline_escape_forces_string_in_array_item() {
    let v = crate::parse("cfg: [1\\.0]").unwrap();
    let obj = v.as_object().unwrap();
    let arr = obj.get("cfg").unwrap().as_array().unwrap();
    assert_eq!(arr[0], Value::String("1.0".into()));
}

#[test]
fn parse_inline_unescaped_float_still_classifies_float() {
    let v = crate::parse("cfg: {v: 1.5}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::Float("1.5".into())));
}

#[test]
fn parse_inline_keywords_still_classify() {
    let v = crate::parse("cfg: {t: true, f: false, n: null}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("t"), Some(&Value::Bool(true)));
    assert_eq!(cfg.get("f"), Some(&Value::Bool(false)));
    assert_eq!(cfg.get("n"), Some(&Value::Null));
}

// --- 0.7 § 5.2 rule 14 / § 5.9.8: float domain floor (overflow→String,
// underflow→±0.0 Float) and zero canonicalisation -------------------------

#[test]
fn parse_float_positive_overflow_to_string() {
    let v = crate::parse("v: 1e9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::String("1e9999".into())));
}

#[test]
fn parse_float_negative_overflow_to_string() {
    let v = crate::parse("v: -1e9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::String("-1e9999".into())));
}

#[test]
fn parse_float_underflow_to_positive_zero() {
    let v = crate::parse("v: 1e-9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::Float("0.0".into())));
}

#[test]
fn parse_float_negative_underflow_to_negative_zero() {
    let v = crate::parse("v: -1e-9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::Float("-0.0".into())));
}

#[test]
fn parse_float_finite_literals_still_float() {
    let v = crate::parse("a: 3.14\nb: 1e6\nc: 1e-2").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a"), Some(&Value::Float("3.14".into())));
    assert_eq!(obj.get("b"), Some(&Value::Float("1000000.0".into())));
    assert_eq!(obj.get("c"), Some(&Value::Float("0.01".into())));
}

#[test]
fn parse_strict_float_overflow_to_string_same_as_lax() {
    // Domain exclusion is not a lossy-form mismatch, so strict does not error.
    let v = crate::parse_strict("v: 1e9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::String("1e9999".into())));
    let v = crate::parse_strict("v: -1e9999").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("v"), Some(&Value::String("-1e9999".into())));
}

#[test]
fn parse_strict_float_underflow_is_lossy_written_form() {
    // Underflow is an ordinary finite Float, so strict's canonical-form
    // check applies — distinct from overflow's domain exclusion.
    match crate::parse_strict("v: 1e-9999") {
        Err(crate::Error::Structured(crate::ErrorKind::LossyScalar { .. })) => {}
        other => panic!("expected LossyScalar, got {:?}", other),
    }
}

#[test]
fn parse_inline_float_positive_overflow_to_string() {
    let v = crate::parse("v: {x: 1e9999}").unwrap();
    let obj = v.as_object().unwrap();
    let inner = obj.get("v").unwrap().as_object().unwrap();
    assert_eq!(inner.get("x"), Some(&Value::String("1e9999".into())));
}

#[test]
fn parse_inline_float_negative_overflow_to_string() {
    let v = crate::parse("v: {x: -1e9999}").unwrap();
    let obj = v.as_object().unwrap();
    let inner = obj.get("v").unwrap().as_object().unwrap();
    assert_eq!(inner.get("x"), Some(&Value::String("-1e9999".into())));
}

#[test]
fn parse_inline_float_underflow_to_positive_zero() {
    let v = crate::parse("v: {x: 1e-9999}").unwrap();
    let obj = v.as_object().unwrap();
    let inner = obj.get("v").unwrap().as_object().unwrap();
    assert_eq!(inner.get("x"), Some(&Value::Float("0.0".into())));
}

#[test]
fn parse_inline_float_negative_underflow_to_negative_zero() {
    let v = crate::parse("v: {x: -1e-9999}").unwrap();
    let obj = v.as_object().unwrap();
    let inner = obj.get("v").unwrap().as_object().unwrap();
    assert_eq!(inner.get("x"), Some(&Value::Float("-0.0".into())));
}

#[test]
fn parse_strict_inline_float_overflow_to_string_same_as_lax() {
    let v = crate::parse_strict("v: {x: 1e9999}").unwrap();
    let obj = v.as_object().unwrap();
    let inner = obj.get("v").unwrap().as_object().unwrap();
    assert_eq!(inner.get("x"), Some(&Value::String("1e9999".into())));
}

#[test]
fn parse_float_zero_canonical_roundtrip() {
    let v = crate::parse("z: 1e-9999\nnz: -1e-9999\n").unwrap();
    let out = crate::emit_canonical(&v).unwrap();
    assert_eq!(out, "z: 0.0\nnz: -0.0\n");
    assert_eq!(crate::parse(&out).unwrap(), v);
}

#[test]
fn parse_float_overflow_string_canonical_roundtrip() {
    let v = crate::parse("v: 1e9999\nw: -1e9999\n").unwrap();
    let out = crate::emit_canonical(&v).unwrap();
    assert_eq!(out, "v:: 1e9999\nw:: -1e9999\n");
    assert_eq!(crate::parse(&out).unwrap(), v);
}

#[test]
fn parse_inline_nested_arrays() {
    let v = crate::parse("matrix: [[1, 2], [3, 4], [5, 6]]").unwrap();
    let obj = v.as_object().unwrap();
    let matrix = obj.get("matrix").unwrap().as_array().unwrap();
    assert_eq!(matrix.len(), 3);
    let first = matrix[0].as_array().unwrap();
    assert_eq!(first[0], Value::Integer("1".into()));
    assert_eq!(first[1], Value::Integer("2".into()));
}

#[test]
fn parse_inline_mixed_nested() {
    let v = crate::parse("users: [{name: alice, age: 30}, {name: bob, age: 25}]").unwrap();
    let obj = v.as_object().unwrap();
    let users = obj.get("users").unwrap().as_array().unwrap();
    assert_eq!(users.len(), 2);
    let alice = users[0].as_object().unwrap();
    assert_eq!(alice.get("name"), Some(&Value::String("alice".into())));
    assert_eq!(alice.get("age"), Some(&Value::Integer("30".into())));
}

// --- top-level inline (section 5.0.1 rules 2-5) ---------------------------

#[test]
fn parse_top_level_inline_object() {
    let v = crate::parse("{a: 1, b: hello}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a"), Some(&Value::Integer("1".into())));
    assert_eq!(obj.get("b"), Some(&Value::String("hello".into())));
}

#[test]
fn parse_top_level_inline_array() {
    let v = crate::parse("[1, 2, 3]").unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 3);
    assert_eq!(arr[0], Value::Integer("1".into()));
}

#[test]
fn parse_top_level_explicit_object() {
    let v = crate::parse("{\na: 1\nb: 2\n}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a"), Some(&Value::Integer("1".into())));
    assert_eq!(obj.get("b"), Some(&Value::Integer("2".into())));
}

#[test]
fn parse_top_level_explicit_array() {
    let v = crate::parse("[\nfoo\nbar\n]").unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 2);
    assert_eq!(arr[0], Value::String("foo".into()));
    assert_eq!(arr[1], Value::String("bar".into()));
}

#[test]
fn parse_orphan_after_top_level_inline() {
    let err = crate::parse("{a: 1}\norphan: line").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::OrphanLineAfterTopLevelInline { .. }) => {}
        other => panic!("expected OrphanLineAfterTopLevelInline, got: {}", other),
    }
}

// --- inline error cases ---------------------------------------------------

#[test]
fn parse_inline_unterminated_object() {
    let err = crate::parse("cfg: {a: 1, b: 2").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::UnterminatedInlineCompound { .. }) => {}
        other => panic!("expected UnterminatedInlineCompound, got: {}", other),
    }
}

#[test]
fn parse_inline_double_comma() {
    let err = crate::parse("arr: [1,, 2]").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::MalformedInlineCompound { .. }) => {}
        other => panic!("expected MalformedInlineCompound, got: {}", other),
    }
}

#[test]
fn parse_inline_bad_escape() {
    let err = crate::parse("cfg: {a: foo\\t}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_inline_backslash_at_eol() {
    let err = crate::parse("cfg: {a: foo\\").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

// --- 0.7 § 3.7 / § 3.7.1 / § 6.13: \uXXXX unicode escapes -----------------

#[test]
fn parse_unicode_escape_basic_inline() {
    let v = crate::parse("cfg: {a: \\u0041}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("A".into())));
}

#[test]
fn parse_unicode_escape_not_greedy_inline() {
    let v = crate::parse("cfg: {a: \\u00411}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("A1".into())));
}

#[test]
fn parse_unicode_escape_not_greedy_in_key() {
    let v = crate::parse("k\\u00411: v").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("kA1"), Some(&Value::String("v".into())));
}

#[test]
fn parse_unicode_escape_hex_case_insensitive() {
    let v = crate::parse("cfg: {a: \\u00e9, b: \\u00E9, c: \\uAbCd}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("\u{e9}".into())));
    assert_eq!(cfg.get("b"), Some(&Value::String("\u{e9}".into())));
    assert_eq!(cfg.get("c"), Some(&Value::String("\u{ABCD}".into())));
}

#[test]
fn parse_unicode_escape_too_few_digits() {
    let err = crate::parse("cfg: {a: \\u12}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_too_few_digits_at_value_end() {
    let err = crate::parse("cfg: [\\u12]").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_non_hex_before_fourth_digit() {
    let err = crate::parse("cfg: {a: \\u12g4}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_surrogate_pair() {
    let v = crate::parse("cfg: {a: \\uD83D\\uDE00}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("\u{1F600}".into())));
}

#[test]
fn parse_unicode_escape_lone_high_surrogate() {
    let err = crate::parse("cfg: {a: \\uD800}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_lone_high_surrogate_before_literal() {
    let err = crate::parse("cfg: {a: \\uD800x}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_high_surrogate_then_non_low_escape() {
    let err = crate::parse("cfg: {a: \\uD800\\u0041}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_high_surrogate_then_high_surrogate() {
    let err = crate::parse("cfg: {a: \\uD800\\uD801}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_lone_low_surrogate() {
    let err = crate::parse("cfg: {a: \\uDC00}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_boundaries_around_surrogate_range() {
    let v = crate::parse("cfg: {a: \\uD7FF, b: \\uE000}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("\u{D7FF}".into())));
    assert_eq!(cfg.get("b"), Some(&Value::String("\u{E000}".into())));
}

#[test]
fn parse_unicode_escape_in_key() {
    let v = crate::parse("\\u0041b: v").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("Ab"), Some(&Value::String("v".into())));
}

#[test]
fn parse_unicode_escape_decoded_dot_is_not_structural() {
    let v = crate::parse("a\\u002Eb: v").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a.b"), Some(&Value::String("v".into())));
    assert!(obj.get("a").is_none());
}

#[test]
fn parse_unicode_escape_decoded_colon_is_not_structural() {
    let v = crate::parse("\\u003A: v").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get(":"), Some(&Value::String("v".into())));
}

#[test]
fn parse_unicode_escape_malformed_in_key_still_errors() {
    let err = crate::parse("a\\u12.b: v").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_not_processed_in_plain_body() {
    let v = crate::parse("note: \\u0041").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("note"), Some(&Value::String("\\u0041".into())));
}

#[test]
fn parse_unicode_escape_not_processed_in_multiline_string() {
    let v = crate::parse("note: (\n\\u0041\n)").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("note"), Some(&Value::String("\\u0041".into())));
}

#[test]
fn parse_uppercase_u_is_not_unicode_escape() {
    let err = crate::parse("cfg: {a: \\U0041}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_forces_string_not_integer() {
    let v = crate::parse("cfg: {v: \\u0030}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("0".into())));
}

#[test]
fn parse_named_escapes_still_work_regression() {
    let v = crate::parse(
        "cfg: {a: \\\\, b: \\,, c: \\}, d: \\], e: \\{, f: \\[, g: \\n, h: \\r, i: \\., j: \\:}",
    )
    .unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("a"), Some(&Value::String("\\".into())));
    assert_eq!(cfg.get("b"), Some(&Value::String(",".into())));
    assert_eq!(cfg.get("c"), Some(&Value::String("}".into())));
    assert_eq!(cfg.get("d"), Some(&Value::String("]".into())));
    assert_eq!(cfg.get("e"), Some(&Value::String("{".into())));
    assert_eq!(cfg.get("f"), Some(&Value::String("[".into())));
    // § 4 / § 3.7 (spec 0.7): trimming is a source-matching concern and
    // happens BEFORE decoding, so `\n`/`\r` decode to real edge
    // whitespace that survives in the String value.
    assert_eq!(cfg.get("g"), Some(&Value::String("\n".into())));
    assert_eq!(cfg.get("h"), Some(&Value::String("\r".into())));
    assert_eq!(cfg.get("i"), Some(&Value::String(".".into())));
    assert_eq!(cfg.get("j"), Some(&Value::String(":".into())));
}

#[test]
fn parse_unicode_escape_high_then_malformed_low_errors() {
    let err = crate::parse("cfg: {a: \\uD800\\uZZ}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::BadEscapeSequence { .. }) => {}
        other => panic!("expected BadEscapeSequence, got: {}", other),
    }
}

#[test]
fn parse_unicode_escape_preserves_decoded_edge_whitespace() {
    // Renamed behaviour per spec 0.7 § 4 / § 3.7: decoded edge whitespace
    // (here U+0009 tabs) is PRESERVED — only source-level edge whitespace
    // is trimmed.
    let v = crate::parse("cfg: {v: \\u0009A\\u0009}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("\tA\t".into())));
}

#[test]
fn parse_unicode_escape_interior_whitespace_preserved() {
    // § 5.2: trimming removes edge whitespace only; a decoded newline
    // in the interior survives.
    let v = crate::parse("cfg: {v: A\\nB}").unwrap();
    let obj = v.as_object().unwrap();
    let cfg = obj.get("cfg").unwrap().as_object().unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("A\nB".into())));
}

// --- validate (spec 0.7 quoted keys, § 5.3.3) --------------------------------

use super::inline::{decode_key_segment, process_escapes};
use super::validate::{check_key, KeyValidity};
use crate::error::{Error, ErrorKind};

#[test]
fn check_key_quoted_segments() {
    use KeyValidity::{Empty, Invalid, Valid};

    // Bare still works.
    assert_eq!(check_key("port"), Valid);
    // Quoted: other quote chars and structural bytes are ordinary content.
    assert_eq!(check_key("\"a b\""), Valid);
    assert_eq!(check_key("`it's \"quoted\"`"), Valid);
    assert_eq!(check_key("\"a,b{c}d[e]:f.g\""), Valid);
    // Quoted content is never trimmed.
    assert_eq!(check_key("\" a \""), Valid);
    assert_eq!(check_key("\" \""), Valid);
    // Empty quoted content is EmptyKey (§ 6.5), for all three delimiters.
    assert_eq!(check_key("\"\""), Empty);
    assert_eq!(check_key("''"), Empty);
    assert_eq!(check_key("``"), Empty);
    // Content after the closer (§ 6.4 "nothing may follow the closer").
    assert_eq!(check_key("\"a\"b"), Invalid);
    assert_eq!(check_key("\"a\" \"b\""), Invalid);
    // Unterminated (normally diagnosed earlier as UnterminatedQuotedKey).
    assert_eq!(check_key("'\"unbalanced"), Invalid);
    // Bare forbidden control bytes / DEL (spec 0.7 § 4 <key-char>).
    assert_eq!(check_key("\u{1}a"), Invalid);
    assert_eq!(check_key("\u{7F}"), Invalid);
    // VT (0x0B) and FF (0x0C) are ALLOWED (new under 0.7).
    assert!(is_valid_key("a\u{B}b"));
    assert!(is_valid_key("a\u{C}b"));
    // Quoted forbidden control byte.
    assert_eq!(check_key("\"\u{1}\""), Invalid);
    // Quoted with escapes — structural bytes via escapes are fine.
    assert_eq!(check_key(r#""a\.b\u{41}""#), Valid);
}

#[test]
fn process_escapes_quote_escapes() {
    assert_eq!(process_escapes(r#"a"b"#, 1, S).unwrap(), "a\"b");
    assert_eq!(process_escapes(r"a\'b", 1, S).unwrap(), "a'b");
    assert_eq!(process_escapes(r"a`b", 1, S).unwrap(), "a`b");
    // Combined with the pre-existing escape set.
    assert_eq!(process_escapes(r"a\:\.b", 1, S).unwrap(), "a:.b");
}

#[test]
fn decode_key_segment_quoted() {
    assert_eq!(decode_key_segment("\"a b\"", 1, S).unwrap(), "a b");
    assert_eq!(
        decode_key_segment("`it's \"quoted\"`", 1, S).unwrap(),
        "it's \"quoted\""
    );
    // Interior is NOT trimmed (spec 0.7 § 5.3.3).
    assert_eq!(decode_key_segment("\" a \"", 1, S).unwrap(), " a ");
    assert_eq!(decode_key_segment(r#""a\:b""#, 1, S).unwrap(), "a:b");
    assert_eq!(decode_key_segment(r#""a\u0041b""#, 1, S).unwrap(), "aAb");
}

#[test]
fn parse_quoted_keys() {
    // Root-level quoted key.
    let v = crate::parse("\"a\": 1").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a"), Some(&Value::Integer("1".into())));

    // A single space as the key — quoted content is never trimmed.
    let v = crate::parse("\" \": 1").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get(" "), Some(&Value::Integer("1".into())));

    // Empty quoted content → EmptyKey (§ 6.5).
    let e = crate::parse("\"\": 1").unwrap_err();
    assert!(matches!(e, Error::Structured(ErrorKind::EmptyKey { .. })));

    // Content after the closer → InvalidKey (§ 6.4).
    let e = crate::parse("\"a\"b: 1").unwrap_err();
    assert!(matches!(e, Error::Structured(ErrorKind::InvalidKey { .. })));

    // Quotes NOT in first position are ordinary key chars (unchanged).
    let v = crate::parse("port\": 1").unwrap();
    assert_eq!(
        v.as_object().unwrap().get("port\""),
        Some(&Value::Integer("1".into()))
    );
    let v = crate::parse("a\"b: 1").unwrap();
    assert_eq!(
        v.as_object().unwrap().get("a\"b"),
        Some(&Value::Integer("1".into()))
    );

    // Value-side: quote escapes now decode inside inline scalar values.
    let v = crate::parse("cfg: {v: say \"hi\"}").unwrap();
    let cfg = v
        .as_object()
        .unwrap()
        .get("cfg")
        .unwrap()
        .as_object()
        .unwrap();
    assert_eq!(cfg.get("v"), Some(&Value::String("say \"hi\"".into())));
}

// --- quoted keys: scanners (spec 0.7 § 5.3.3) -------------------------------

use super::inline::find_matching_close;
use super::inline::find_unescaped_colon_inline;
use super::inline::has_quote_bytes;
use super::inline::split_top_level;
use super::inline::ColonScan;
use super::inline::InlineBody;
use super::inline::InlineBounds;
use super::inline::{key_is_single_segment, scan_unescaped_colon, split_key_path};

#[test]
fn quoted_colon_scan_finds_colon_outside_spans() {
    assert_eq!(scan_unescaped_colon("a: 1"), ColonScan::Found(1));
    // Colon inside quotes is skipped.
    assert_eq!(scan_unescaped_colon("\"a: b\": 1"), ColonScan::Found(6));
    assert_eq!(scan_unescaped_colon("'a' : 1"), ColonScan::Found(4));
    assert_eq!(scan_unescaped_colon("`a:b`: 1"), ColonScan::Found(5));
    // Dotted path with a quoted middle segment.
    assert_eq!(scan_unescaped_colon("a.\"b:c\".d: 1"), ColonScan::Found(9));
    // Whitespace after the dot is skipped before the quote test.
    assert_eq!(scan_unescaped_colon("a . \"b\": 1"), ColonScan::Found(7));
}

#[test]
fn quoted_colon_scan_unterminated() {
    assert_eq!(
        scan_unescaped_colon("\"unterm: 1"),
        ColonScan::UnterminatedQuote
    );
    assert_eq!(
        scan_unescaped_colon("a.\"unterm"),
        ColonScan::UnterminatedQuote
    );
}

#[test]
fn quoted_colon_scan_absent_and_escapes() {
    assert_eq!(scan_unescaped_colon("no colon"), ColonScan::Absent);
    // Escaped colon is not a separator.
    assert_eq!(scan_unescaped_colon("a\\:b: 1"), ColonScan::Found(4));
    // Escaped quote inside the span does not close it.
    assert_eq!(scan_unescaped_colon("\"a\\\"b\": 1"), ColonScan::Found(6));
    // Junk after the closer is still scanned normally.
    assert_eq!(scan_unescaped_colon("\"a\"b: 1"), ColonScan::Found(4));
}

#[test]
fn r10f1_colon_scan_value_side_quotes_are_not_key_quotes() {
    // R10-F1: the separator search checks quote-opacity only over the
    // KEY PREFIX up to the candidate colon — the value's own quotes,
    // dots and colons must never turn the pair's own separator into
    // segment content or an unterminated key.
    assert_eq!(scan_unescaped_colon("a: \"b:c\""), ColonScan::Found(1));
    // A value quote that never closes is still VALUE content: Found,
    // not UnterminatedQuote.
    assert_eq!(
        scan_unescaped_colon("a: \"unterminated"),
        ColonScan::Found(1)
    );
    // The positive-control shape: a dot-armed segment start and an
    // unterminated quote INSIDE the value, with a colon after both.
    assert_eq!(
        scan_unescaped_colon("a: b.\"unterm: 2\""),
        ColonScan::Found(1)
    );
    assert_eq!(
        scan_unescaped_colon("a: b.c.\"x:y\".d"),
        ColonScan::Found(1)
    );
    // Truly UNterminated value-side quote after a dot (no closer): the
    // pair separator is still the first colon. This literal is in the
    // golden-corpus input set on purpose: under the pre-fix scope bug
    // (opacity checked over the whole pair) it would flip to
    // UnterminatedQuote, so the corpus distinguishes the value-side
    // sub-class too.
    assert_eq!(
        scan_unescaped_colon("a: b.\"unterm: 2"),
        ColonScan::Found(1)
    );
    // A non-segment-start quote in the prefix is ordinary key content:
    // the colon AFTER it is still found (and `a: b"c: d` shows the pair
    // separator is the FIRST unescaped colon — value quotes cannot move
    // it).
    assert_eq!(scan_unescaped_colon("ab\"c:d: 1"), ColonScan::Found(4));
    assert_eq!(scan_unescaped_colon("a: b\"c: d"), ColonScan::Found(1));
    // Multi-segment keys with quoted middles: candidates inside a span
    // resume after its closer, and the NEXT candidate is the separator.
    assert_eq!(scan_unescaped_colon("a.\"x:y\".b: 1"), ColonScan::Found(9));
    assert_eq!(scan_unescaped_colon("\"a\".\"b\": 1"), ColonScan::Found(7));
    // Escaped quote in the key prefix never opens a segment.
    assert_eq!(scan_unescaped_colon("a\\\"b: 1"), ColonScan::Found(4));
    // Prefix ending mid segment-start whitespace still finds the colon.
    assert_eq!(scan_unescaped_colon("a .  \"b\": 1"), ColonScan::Found(8));
}

#[test]
fn r10f1_colon_scan_no_candidate_corners() {
    // No unescaped colon candidate anywhere: the slow walk still
    // distinguishes Absent from UnterminatedQuote (§ 5.3.3 keeps
    // precedence over MissingSeparator even with no colon at all).
    assert_eq!(scan_unescaped_colon("a b"), ColonScan::Absent);
    assert_eq!(scan_unescaped_colon("a\\:b"), ColonScan::Absent);
    assert_eq!(
        scan_unescaped_colon("\"unterm"),
        ColonScan::UnterminatedQuote
    );
    assert_eq!(
        scan_unescaped_colon("a.\"unterm"),
        ColonScan::UnterminatedQuote
    );
    // A closed quoted key with no colon after it: Absent, not
    // UnterminatedQuote.
    assert_eq!(scan_unescaped_colon("\"a\" b"), ColonScan::Absent);
}

#[test]
fn quoted_split_key_path_keeps_quotes_in_slices() {
    assert_eq!(split_key_path("a.\"b.c\".d"), vec!["a", "\"b.c\"", "d"]);
    assert_eq!(split_key_path("\"a\".\"b\""), vec!["\"a\"", "\"b\""]);
    // Escaped dot is not a separator (no quote bytes → fast path).
    assert_eq!(split_key_path("a\\.b"), vec!["a\\.b"]);
    // Post-dot whitespace stays in the slice — callers trim.
    assert_eq!(split_key_path("a. \"b\""), vec!["a", " \"b\""]);
    assert_eq!(split_key_path("\"a.b\""), vec!["\"a.b\""]);
}

#[test]
fn quoted_key_is_single_segment() {
    assert!(key_is_single_segment("\"a.b\""));
    assert!(!key_is_single_segment("a.\"b\".c"));
    // Unterminated span swallows the rest — one segment (defensive).
    assert!(key_is_single_segment("\"unterm"));
}

#[test]
fn quoted_find_unescaped_colon_inline() {
    // `}` inside a quoted key segment does not affect depth.
    assert_eq!(find_unescaped_colon_inline("\"a}b\": 1"), Some(5));
    // Span never closes — no colon found; caller maps to unterminated.
    assert_eq!(find_unescaped_colon_inline("\"a: 1"), None);
    // Value-side quotes are ignored.
    assert_eq!(find_unescaped_colon_inline("a: \"b}"), Some(1));
}

#[test]
fn quoted_split_top_level_object_mode() {
    // Comma inside a quoted KEY does not split.
    assert_eq!(
        split_top_level(
            "\"a}b\": 1, c: 2",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("\"a}b\": 1, c: 2"),
            has_quote_bytes("\"a}b\": 1, c: 2".as_bytes())
        )
        .unwrap(),
        vec!["\"a}b\": 1", " c: 2"]
    );
    // Comma inside a quoted VALUE does split ("Keys only"): value
    // quotes are ordinary content, so both commas are split points.
    assert_eq!(
        split_top_level(
            "a: \"x,y\", b: 2",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("a: \"x,y\", b: 2"),
            has_quote_bytes("a: \"x,y\", b: 2".as_bytes())
        )
        .unwrap(),
        vec!["a: \"x", "y\"", " b: 2"]
    );
    // Unterminated quoted key segment.
    match split_top_level(
        "\"a: 1",
        1,
        S,
        InlineBody::Object,
        InlineBounds::for_input("\"a: 1"),
        has_quote_bytes("\"a: 1".as_bytes()),
    ) {
        Err(crate::Error::Structured(crate::ErrorKind::UnterminatedInlineCompound { .. })) => {}
        other => panic!(
            "expected UnterminatedInlineCompound, got: {:?}",
            other.err()
        ),
    }
}

#[test]
fn quoted_split_top_level_array_mode_ignores_quotes() {
    // Array bodies never track quotes (value positions — "Keys only"):
    // today's behaviour kept exactly, so the comma inside the quotes
    // splits.
    assert_eq!(
        split_top_level(
            "\"a,b\", c",
            1,
            S,
            InlineBody::Array,
            InlineBounds::for_input("\"a,b\", c"),
            has_quote_bytes("\"a,b\", c".as_bytes())
        )
        .unwrap(),
        vec!["\"a", "b\"", " c"]
    );
}

#[test]
fn quoted_find_matching_close_object_mode() {
    // `}` inside a quoted key segment is opaque to balance counting.
    let input = "{\"a}b\": 1}";
    assert_eq!(
        find_matching_close(input, b'{', b'}'),
        Some(input.len() - 1)
    );
    // Unterminated span → no matching close.
    assert_eq!(find_matching_close("{\"a: 1}", b'{', b'}'), None);
    let input = "{a: 1, \"b}c\": 2}";
    assert_eq!(
        find_matching_close(input, b'{', b'}'),
        Some(input.len() - 1)
    );
    // Array-scope positions keep quotes as content (spec "Keys only"):
    // the `]` inside the quotes still closes the compound — no nested
    // object is involved.
    assert_eq!(find_matching_close("[\"a]b\"]", b'[', b']'), Some(3));
}

#[test]
fn quoted_find_matching_close_triple_nested() {
    // A `{` opens a fresh pair list at any nesting level, so quoted-key
    // recognition must be tracked per level (spec 0.7 § 5.3.3).
    let input = r#"{a: {b: {"c}d": 1}}}"#;
    assert_eq!(
        find_matching_close(input, b'{', b'}'),
        Some(input.len() - 1)
    );
    let input = r#"{b: {"c}d": 1}}"#;
    assert_eq!(
        find_matching_close(input, b'{', b'}'),
        Some(input.len() - 1)
    );
}

#[test]
fn r3f1_split_top_level_trailing_ws_after_comma_no_phantom_segment() {
    // R3-F1: whitespace after a trailing comma sent `skip_segment_ws`
    // to EOF and the loop indexed out of bounds. The loop must end
    // without emitting a phantom whitespace-only segment.
    for tail in [" ", "\t", "\u{00a0}"] {
        let body = format!("\"a\": 1,{tail}");
        assert_eq!(
            split_top_level(
                &body,
                1,
                S,
                InlineBody::Object,
                InlineBounds::for_input(&body),
                has_quote_bytes(body.as_bytes()),
            )
            .unwrap(),
            vec!["\"a\": 1"]
        );
    }
    // Comma at EOF without whitespace: unchanged — the empty final
    // segment is still emitted and the caller accepts it.
    assert_eq!(
        split_top_level(
            "\"a\": 1,",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("\"a\": 1,"),
            has_quote_bytes("\"a\": 1,".as_bytes())
        )
        .unwrap(),
        vec!["\"a\": 1", ""]
    );
    // Quoted key and quoted VALUE before the trailing comma.
    assert_eq!(
        split_top_level(
            "\"a b\": 1, ",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("\"a b\": 1, "),
            has_quote_bytes("\"a b\": 1, ".as_bytes())
        )
        .unwrap(),
        vec!["\"a b\": 1"]
    );
    assert_eq!(
        split_top_level(
            "a: \"x\", ",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("a: \"x\", "),
            has_quote_bytes("a: \"x\", ".as_bytes())
        )
        .unwrap(),
        vec!["a: \"x\""]
    );
}

// R3-F1's original catch was the PANIC (`b.` + whitespace to EOF sent
// `skip_segment_ws` past the end); keeping the no-panic behavior was
// correct. The Err(EmptyKey) category asserted here since R3 was not
// (R11-F1) — the review's own words: "the absence of panic was
// correct, the chosen category was not." Reaching `EofAfterWsSkip`
// proves the armed segment holds no unescaped separator, so
// `split_top_level` now pushes the raw remainder exactly like the
// `Exhausted` branch (and hence `SplitFast`) does; the caller's colon
// search then resolves the § 6.12 missing-separator category
// (MalformedInlineCompound), pinned at the full-parse level below.
#[test]
fn r3f1_split_top_level_dotted_key_trailing_ws_raw_last_segment() {
    // Dotted-key `.` + whitespace to EOF: the raw last segment is
    // pushed — byte-identical to what the quote-free fast machine
    // produces for the same shape.
    for tail in [" ", "\t"] {
        let body = format!(" \"a\": 1, b.{tail}");
        let seg2 = format!(" b.{tail}");
        assert_eq!(
            split_top_level(
                &body,
                1,
                S,
                InlineBody::Object,
                InlineBounds::for_input(&body),
                has_quote_bytes(body.as_bytes()),
            )
            .unwrap(),
            vec![" \"a\": 1", seg2.as_str()]
        );
    }
    // Leading-dot form, same shape (quote bytes present: slow path).
    assert_eq!(
        split_top_level(
            " \"a\". ",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input(" \"a\". "),
            has_quote_bytes(" \"a\". ".as_bytes()),
        )
        .unwrap(),
        vec![" \"a\". "]
    );
    // Dot followed by a real segment still works.
    assert_eq!(
        split_top_level(
            "a. b : 1",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("a. b : 1"),
            has_quote_bytes("a. b : 1".as_bytes())
        )
        .unwrap(),
        vec!["a. b : 1"]
    );
    // The corrected category, resolved where it belongs: the full
    // parse finds no separator in the pushed raw segment and raises
    // MalformedInlineCompound (§ 6.12), not EmptyKey.
    match crate::parse("{\"a\": 1, b. }") {
        Err(crate::Error::Structured(crate::ErrorKind::MalformedInlineCompound { .. })) => {}
        other => panic!("expected MalformedInlineCompound, got {other:?}"),
    }
}

#[test]
fn r3f1_find_matching_close_eof_after_trailing_ws() {
    // R3-F1 sibling: untrimmed text ending in whitespace after a comma,
    // no closer — None, not an index panic.
    assert_eq!(find_matching_close("{\"a\": 1, ", b'{', b'}'), None);
    // Closer present after the whitespace: unchanged (skip stops at `}`).
    assert_eq!(find_matching_close("{\"a\": 1, }", b'{', b'}'), Some(9));
}

#[test]
fn r3f1_scan_inline_closer_eof_after_trailing_ws() {
    use super::inline::{scan_inline_closer, InlineCloserScan};
    // R3-F1 sibling: untrimmed text ending in whitespace after a comma,
    // no closer on this text — NotFound, not an index panic.
    assert!(matches!(
        scan_inline_closer("{\"a\": 1, ", b'{', b'}', 1, S),
        InlineCloserScan::NotFound
    ));
    // Closer present after the whitespace: unchanged.
    assert!(matches!(
        scan_inline_closer("{\"a\": 1, }", b'{', b'}', 1, S),
        InlineCloserScan::Found(9)
    ));
}

#[test]
fn r3f1_find_unescaped_colon_inline_eof_after_dotted_ws() {
    // R3-F1 sibling: untrimmed text ending in whitespace after a dot —
    // None, not an index panic.
    assert_eq!(find_unescaped_colon_inline("a. "), None);
    // Dot then colon: unchanged.
    assert_eq!(find_unescaped_colon_inline("a. : 1"), Some(3));
}

// --- quoted keys: parse-level (spec 0.7 § 5.3.3) ----------------------------

#[test]
fn quoted_key_with_spaces() {
    let v = crate::parse("\"a b\": 1").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a b"), Some(&Value::Integer("1".into())));
}

#[test]
fn quoted_key_backtick_with_inner_quotes() {
    let v = crate::parse("`it's \"quoted\"`: 1").unwrap();
    let obj = v.as_object().unwrap();
    let key = obj.keys().next().unwrap().clone();
    assert_eq!(key, "it's \"quoted\"");
    assert_eq!(key.len(), 13);
}

#[test]
fn quoted_key_interior_not_trimmed() {
    let v = crate::parse("\" a \": 1").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get(" a "), Some(&Value::Integer("1".into())));
}

#[test]
fn quoted_segment_in_dotted_path() {
    let v = crate::parse("a.\"b.c\".d: 1").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    let mid = a.get("b.c").unwrap().as_object().unwrap();
    assert_eq!(mid.get("d"), Some(&Value::Integer("1".into())));
}

#[test]
fn quoted_adjacent_segments_decode() {
    let v = crate::parse("\"a\".\"b\": 1").unwrap();
    let obj = v.as_object().unwrap();
    let a = obj.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("b"), Some(&Value::Integer("1".into())));
}

#[test]
fn quoted_key_comma_inside_inline_object() {
    let v = crate::parse("k: {\"a,b\": 1, c: 2}").unwrap();
    let k = v
        .as_object()
        .unwrap()
        .get("k")
        .unwrap()
        .as_object()
        .unwrap();
    assert_eq!(k.len(), 2);
    assert_eq!(k.get("a,b"), Some(&Value::Integer("1".into())));
    assert_eq!(k.get("c"), Some(&Value::Integer("2".into())));
}

#[test]
fn quoted_key_brace_inside_inline_object() {
    let v = crate::parse("k: {\"a}b\": 1, c: 2}").unwrap();
    let k = v
        .as_object()
        .unwrap()
        .get("k")
        .unwrap()
        .as_object()
        .unwrap();
    assert_eq!(k.len(), 2);
    assert_eq!(k.get("a}b"), Some(&Value::Integer("1".into())));
    assert_eq!(k.get("c"), Some(&Value::Integer("2".into())));
}

#[test]
fn quoted_key_brace_inside_root_inline_object() {
    let v = crate::parse("{\"a}b\": 1, c: 2}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.len(), 2);
    assert_eq!(obj.get("a}b"), Some(&Value::Integer("1".into())));
    assert_eq!(obj.get("c"), Some(&Value::Integer("2".into())));
}

#[test]
fn quoted_key_unterminated_inline_root_is_unterminated_compound() {
    let err = crate::parse("{\"a: 1}").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::UnterminatedInlineCompound { .. }) => {}
        other => panic!("expected UnterminatedInlineCompound, got: {}", other),
    }
}

#[test]
fn quoted_key_unterminated_after_established_object() {
    let err = crate::parse("y: 1\n'unterminated: 1").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::UnterminatedQuotedKey { .. }) => {}
        other => panic!("expected UnterminatedQuotedKey, got: {}", other),
    }
}

#[test]
fn quoted_key_unterminated_in_root_pair_falls_to_array() {
    // Unterminated quote swallows the colon, so the root line is
    // array-item shape (§ 5.0.1 rule 7) and the line is stored verbatim.
    let v = crate::parse("'tis the season: fa").unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0], Value::String("'tis the season: fa".into()));
}

#[test]
fn quoted_root_object_key() {
    let v = crate::parse("\"port\": 1").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("port"), Some(&Value::Integer("1".into())));
}

#[test]
fn quoted_key_unterminated_in_established_object_line() {
    let err = crate::parse("cfg:\n  a: 1\n  \"unterminated: 1").unwrap_err();
    match err {
        crate::Error::Structured(crate::ErrorKind::UnterminatedQuotedKey { .. }) => {}
        other => panic!("expected UnterminatedQuotedKey, got: {}", other),
    }
}

// R3-F2: quote-awareness must apply to nested Objects inside an
// Array-outer scan, not only when the OUTERMOST container is an Object.
#[test]
fn r3f2_find_matching_close_array_nested_quoted_keys() {
    use super::inline::find_matching_close;
    // `]` inside a quoted key of a nested Object must be opaque.
    assert_eq!(
        find_matching_close("[{\"x]y\": 1},2]", b'[', b']'),
        Some(13)
    );
    assert_eq!(
        find_matching_close("[{\"x}y\": 1},2]", b'[', b']'),
        Some(13)
    );
    // Unterminated quoted key swallows the rest — no matching close.
    assert_eq!(find_matching_close("[{\"x]y\": 1", b'[', b']'), None);
    // Doubly nested arrays with a quoted-key object at the bottom.
    // Input is 14 bytes; the matching closer is the last byte at index 13.
    assert_eq!(
        find_matching_close("[[{\"x]y\": 1}]]", b'[', b']'),
        Some(13)
    );
}

#[test]
fn r3f2_scan_inline_closer_array_nested_quoted_keys() {
    use super::inline::{scan_inline_closer, InlineCloserScan};
    assert!(matches!(
        scan_inline_closer("[{\"x]y\": 1},2]", b'[', b']', 1, S),
        InlineCloserScan::Found(13)
    ));
    assert!(matches!(
        scan_inline_closer("[{\"x}y\": 1},2]", b'[', b']', 1, S),
        InlineCloserScan::Found(13)
    ));
    assert!(matches!(
        scan_inline_closer("[[{\"x]y\": 1}]]", b'[', b']', 1, S),
        InlineCloserScan::Found(13)
    ));
    // Non-regression: object-outer body already tracks quotes (10 bytes; closer at index 9).
    assert!(matches!(
        scan_inline_closer("{\"x}y\": 1}", b'{', b'}', 1, S),
        InlineCloserScan::Found(9)
    ));
}

#[test]
fn r3f2_split_top_level_array_body_quoted_key_object() {
    use super::inline::{split_top_level, InlineBody};
    // The nested object (with `]` in a quoted key) must be skipped
    // wholesale: the comma inside it never splits, the one after it does.
    assert_eq!(
        split_top_level(
            "{\"x]y\": 1},2",
            1,
            S,
            InlineBody::Array,
            InlineBounds::for_input("{\"x]y\": 1},2"),
            has_quote_bytes("{\"x]y\": 1},2".as_bytes())
        )
        .unwrap(),
        vec!["{\"x]y\": 1}", "2"]
    );
}

// --- R3-F4: mid-scalar braces have no structural meaning (spec 0.7 § 5.8.5) --

#[test]
fn r3f4_split_top_level_midvalue_balanced_brace_splits_at_inner_comma() {
    use super::inline::{split_top_level, InlineBody};
    // R3-F4: a balanced `{...}` mid-scalar must NOT be skipped wholesale;
    // the comma inside it is a real top-level separator (§ 5.8.5), and
    // the comma after the mid-scalar `}` also splits (no comma-shielding).
    assert_eq!(
        split_top_level(
            "a: x{y,z}, b: 2",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("a: x{y,z}, b: 2"),
            has_quote_bytes("a: x{y,z}, b: 2".as_bytes())
        )
        .unwrap(),
        vec!["a: x{y", "z}", " b: 2"]
    );
}

#[test]
fn r3f4_split_top_level_midvalue_brace_quote_aware_slow_path() {
    use super::inline::{split_top_level, InlineBody};
    // R3-F4: same rule on the quote-aware slow path.
    assert_eq!(
        split_top_level(
            "k: \"v\", a: x{y,z}, b: 2",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("k: \"v\", a: x{y,z}, b: 2"),
            has_quote_bytes("k: \"v\", a: x{y,z}, b: 2".as_bytes())
        )
        .unwrap(),
        vec!["k: \"v\"", " a: x{y", "z}", " b: 2"]
    );
}

#[test]
fn r3f4_split_top_level_array_body_midvalue_brace_splits_at_inner_comma() {
    use super::inline::{split_top_level, InlineBody};
    // R3-F4: array bodies share the fast splitter and the rule.
    assert_eq!(
        split_top_level(
            "x{y,z}, 2",
            1,
            S,
            InlineBody::Array,
            InlineBounds::for_input("x{y,z}, 2"),
            has_quote_bytes("x{y,z}, 2".as_bytes())
        )
        .unwrap(),
        vec!["x{y", "z}", " 2"]
    );
}

#[test]
fn r3f4_split_top_level_genuine_value_start_compounds_guard() {
    use super::inline::{split_top_level, InlineBody};
    // R3-F4 guards: a compound that IS the first code point of a value
    // keeps its structural meaning — no split inside it.
    assert_eq!(
        split_top_level(
            "{a: 1}, 2",
            1,
            S,
            InlineBody::Array,
            InlineBounds::for_input("{a: 1}, 2"),
            has_quote_bytes("{a: 1}, 2".as_bytes())
        )
        .unwrap(),
        vec!["{a: 1}", " 2"]
    );
    assert_eq!(
        split_top_level(
            "a: {y: 1}, b: 2",
            1,
            S,
            InlineBody::Object,
            InlineBounds::for_input("a: {y: 1}, b: 2"),
            has_quote_bytes("a: {y: 1}, b: 2".as_bytes())
        )
        .unwrap(),
        vec!["a: {y: 1}", " b: 2"]
    );
}

#[test]
fn r3f4_scan_inline_closer_midvalue_balanced_brace_is_body_closer() {
    use super::inline::{scan_inline_closer, InlineCloserScan};
    // R3-F4: the `}` after `z` (the mid-scalar close) is the body's
    // closer — the scan must not treat the balanced span as opaque.
    assert!(matches!(
        scan_inline_closer("{a: x{y,z}, b: 2}", b'{', b'}', 1, S),
        InlineCloserScan::Found(9)
    ));
}

#[test]
fn r3f4_scan_inline_closer_crossed_bracket_not_found() {
    use super::inline::{scan_inline_closer, InlineCloserScan};
    // R3-F4: the crossed `]` mid-scalar is not a matching `}` closer.
    assert!(matches!(
        scan_inline_closer("{a: x[y,z], b: 2}", b'{', b'}', 1, S),
        InlineCloserScan::NotFound
    ));
}

#[test]
fn r3f4_scan_inline_closer_genuine_compounds_guard() {
    use super::inline::{scan_inline_closer, InlineCloserScan};
    // R3-F4 guards: value-start compounds still find their real closer.
    assert!(matches!(
        scan_inline_closer("{a: {y: 1}, b: 2}", b'{', b'}', 1, S),
        InlineCloserScan::Found(16)
    ));
    assert!(matches!(
        scan_inline_closer("[{a: 1}, 2]", b'[', b']', 1, S),
        InlineCloserScan::Found(10)
    ));
}

// R8 regression: the InlineBounds memo must be a PURE memo — every
// recorded (opener, closer) pair must be exactly what the live
// dispatches compute over the same span. The recording walk once
// popped a frame at a later kind-matched closer even though a crossed
// closer inside the span had already returned the span's own depth to
// zero (the byte where the standalone scan stops with `NotFound`), so
// the memo said `Found` where the live scan said `NotFound` and split
// segmented differently (observable: different
// MalformedInlineCompound detail payloads, fuzz2-confirmed). This test
// cross-checks every recorded pair against BOTH live dispatches over
// exactly the shapes that fired, plus an exhaustive sweep of short
// structural bodies.
#[test]
fn memo_bounds_are_a_pure_memo_of_the_live_dispatches() {
    use super::inline::{
        find_matching_close, scan_inline_closer, scan_inline_closer_with_bounds, InlineCloserScan,
    };

    // Shapes that fired during the audit / differential fuzz (the four
    // MEMO_MISMATCH audit slices, embedded in a value position so the
    // gate walk actually records spans around them, and the four
    // fuzz2-diverging documents).
    let hostile = [
        "{a: {]}{, ,x{x,}",
        "{a: {[][x]}]}n\"}",
        "{a: {x   ]}, 2}",
        "{a: {]a{ :x}}",
        "{a: [a],{:[,:,}]}",
        "{a: [ a:,:[],{:[}, ]}",
        "{a: [],{[:[,}]}",
        "{a: [],[:[},a[{ {,a ]}",
        // R8-F2: the five review inputs. Pre-fix the quote-free
        // members let the fast gate walk phantom-open an Array
        // after the closed `[]` (value_start residue) and record /
        // verdict differently from their quote-bearing twins.
        "[[][text]",
        "[[]['text]",
        "[{}[text]",
        "{a: [[][text]}",
        "{a: [[][text], q: '}",
    ];

    let check = |body: &str| {
        let bytes = body.as_bytes();
        let (open, close) = if bytes[0] == b'[' {
            (b'[', b']')
        } else {
            (b'{', b'}')
        };
        let mut pairs = Vec::new();
        let verdict = scan_inline_closer_with_bounds(body, open, close, 0, S, &mut pairs);
        // Recording only happens on a Found gate; nothing to check otherwise.
        if !matches!(verdict, InlineCloserScan::Found(_)) {
            assert!(
                pairs.is_empty(),
                "bounds recorded on a non-Found gate: {body:?} {pairs:?}"
            );
            return;
        }
        for &(o, c) in &pairs {
            let ob = bytes[o];
            let (so, sc) = if ob == b'[' {
                (b'[', b']')
            } else {
                (b'{', b'}')
            };
            // BOTH consumer shapes must agree with the memo:
            // - the SUFFIX `&body[o..]` is what split's opener jump
            //   sub-scans (`scan_inline_closer(&input[i..], ...)`), and
            // - the BOUNDED VALUE `&body[o..=c]` is what the find-first
            //   dispatch hands to `known_closer` / `find_matching_close`
            //   / `scan_inline_closer`. R8-F2: checking the suffix alone
            //   let a quote-aware memo agree with a quote-aware re-scan
            //   while the actual consumer re-scanned the bounded value
            //   in quote-free fast mode. For the bounded shape the
            //   recorded closer is the last byte, so the live dispatch
            //   must find it exactly there.
            for (shape_name, span) in [("suffix", &body[o..]), ("bounded", &body[o..=c])] {
                // `c - o` is the recorded closer's index in both shapes;
                // for the bounded shape it is also the last byte, which
                // is exactly the `idx == len - 1` closed-compound read
                // the find-first dispatch gives a memo hit.
                assert!(
                    matches!(
                        scan_inline_closer(span, so, sc, 0, S),
                        InlineCloserScan::Found(f) if f == c - o
                    ),
                    "scan ({shape_name}) disagrees with the memo at {o}..{c} in {body:?}"
                );
                assert_eq!(
                    find_matching_close(span, so, sc),
                    Some(c - o),
                    "find ({shape_name}) disagrees with the memo at {o}..{c} in {body:?}"
                );
            }
        }
    };

    for b in hostile {
        check(b);
    }

    // Exhaustive sweep over short structural bodies (depth, crossed
    // closers, mid-scalar openers, raw markers, top-level commas).
    // R8-F2: the alphabet MUST carry quote bytes (all three § 5.3.3
    // delimiters) and § 3.3 whitespace — without them every body is
    // quote-free, the gate always picks the fast walk, and the whole
    // quote-aware memo surface (ScanQ recordings consumed by a
    // quote-free consumer slice) is unreachable. That blind spot is
    // why the R8-F2 family survived this test.
    let alpha: &[u8] = b"{[]}a:,.'\"` ";
    let mut buf = [0u8; 5];
    for len in 1..=5usize {
        let total = alpha.len().pow(len as u32);
        for mut idx in 0..total {
            for d in (0..len).rev() {
                buf[d] = alpha[idx % alpha.len()];
                idx /= alpha.len();
            }
            let body = std::str::from_utf8(&buf[..len]).unwrap();
            // Only bodies the gate scan accepts as inline compounds build a map.
            if body.starts_with('{') || body.starts_with('[') {
                check(body);
            }
        }
    }
}

// R8 regression pin: the fuzz2-diverging documents must keep the
// pre-R8 segmentation (ground truth probed from main @ 4477ae2). The
// memo bug changed only the `detail` payload (which segment the
// diagnostic quoted), so the pins cover the payload exactly. The
// fourth former member of this list is pinned separately below: R8-F2
// legitimately moved its whole category, not just its detail.
// R9-F1 reclassification: all three inputs moved a second time, for an
// independent spec reason. The old MalformedInlineCompound verdict
// depended on former quirk 4 — find/scan commas set `value_start = true`
// even in Object scopes — so the `{` after the Object comma
// phantom-opened a compound (§ 5.8.5) that consumed a `}` and let the
// walk reach the body's own closer; the pair split then ran and quoted
// a missing-separator detail. § 4 excludes brackets from `<key-char>`
// and `<inline-pair>` begins with `<key>`, so the position after an
// Object comma is a KEY position and the `{` there is NOT a
// value-position opener. Without the phantom scope a `]` returns the
// shared depth to zero first; § 5.2's matching-closer rule requires a
// depth-0 closer to be the body's own kind, so there is no same-line
// matching closer and § 6.11 diagnoses UnterminatedInlineCompound —
// the identical reading the quote-aware sibling below pins for
// `k: {a: [],[:[},a[{ {,a ]}` since R8-F2.
#[test]
fn r9f1_crossed_closer_fuzz_inputs_reclassified_by_key_position() {
    let cases = [
        "k: {a: [a],{:[,:,}]}",
        "k: {a: [ a:,:[],{:[}, ]}",
        "k: {a: [],{[:[,}]}",
    ];
    for input in cases {
        let expect_unterminated = |res: Result<(), crate::Error>| {
            assert!(
                matches!(
                    res,
                    Err(crate::Error::Structured(
                        crate::ErrorKind::UnterminatedInlineCompound { .. }
                    ))
                ),
                "input {input:?}: expected UnterminatedInlineCompound, got {res:?}"
            );
        };
        expect_unterminated(crate::parse(input).map(|_| ()));
        expect_unterminated(crate::parse_strict(input).map(|_| ()));
        expect_unterminated(crate::from_str::<serde_json::Value>(input).map(|_| ()));
        expect_unterminated(crate::parse_events(input, |_| {}).map(|_| ()));
    }
}

// R9-F1: an unescaped `[`/`{` in an inline-KEY position is a forbidden
// `<key-char>` (§ 4), so once the separator is located the pair is
// diagnosed as InvalidKey (§ 6.4 via § 5.3.1's bare-segment rule) —
// never as a compound-shape error. Two mechanisms carried the old
// verdicts: (a) find/scan commas set `value_start = true` even in
// Object scopes, so the opener gate admitted the bracket as a
// value-position compound opener whose closer then swallowed the
// body's own (UnterminatedInlineCompound) — § 4 puts the `<key>`
// production first in `<inline-pair>`, so a comma's successor position
// in an Object is a key position; (b) the inline pair's colon scan
// counted `{`/`[` as depth and hid the separator that is actually
// present (MalformedInlineCompound "missing ':'") — § 5.3.1: "Validation
// operates on the raw prefix up to the first unescaped separator,
// however malformed the separator's surrounding whitespace is".
#[test]
fn r9f1_key_bracket_is_invalid_key_not_phantom_compound() {
    use crate::ErrorKind;
    let cases = [
        // First pair (mechanism (b) only).
        "{[a: 1}",
        "{{a: 1}",
        // Later pair after an Object comma (mechanism (a) in the shape
        // scan and the split, then (b) in the pair split). A quote in a
        // neighbouring value must not change the diagnosis (§ 5.3.3:
        // quotes in value positions are ordinary content).
        "{x: 0, [a: 1}",
        "{x: 0, {a: 1}",
        "{x: 0, [a: 1, q: '}",
    ];
    for input in cases {
        let expect_invalid_key = |res: Result<(), crate::Error>| match res {
            Err(crate::Error::Structured(ErrorKind::InvalidKey { key, .. })) => {
                assert!(
                    key.starts_with('[') || key.starts_with('{'),
                    "input {input:?}: unexpected offending key {key:?}"
                );
            }
            other => panic!("input {input:?}: expected InvalidKey, got {other:?}"),
        };
        expect_invalid_key(crate::parse(input).map(|_| ()));
        expect_invalid_key(crate::parse_strict(input).map(|_| ()));
        expect_invalid_key(crate::from_str::<serde_json::Value>(input).map(|_| ()));
        expect_invalid_key(crate::parse_events(input, |_| {}).map(|_| ()));
    }
}

// R9-F1 positive controls: the fix must not touch legitimate brackets.
// - `\[` is a § 3.7 escape form: the decoded key is the ordinary
//   single-segment key `[a` (decode-time semantics unchanged).
// - `[1]` after `a:` IS a value position (§ 5.8.5): the value is a
//   real nested Array; likewise a nested Object value.
// - Quoted-key opacity (§ 5.3.3) stays exactly as it is: the `}` inside
//   the quoted segment is content, and a quoted key may quote brackets.
#[test]
fn r9f1_key_bracket_positive_controls_unchanged() {
    use crate::Value;

    let v = crate::parse(r"{x: 0, \[a: 1}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("x"), Some(&Value::Integer("0".into())));
    assert_eq!(obj.get("[a"), Some(&Value::Integer("1".into())));

    let v = crate::parse(r"{\[a: 1}").unwrap();
    assert_eq!(
        v.as_object().unwrap().get("[a"),
        Some(&Value::Integer("1".into()))
    );

    let v = crate::parse("{x: 0, a: [1]}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("x"), Some(&Value::Integer("0".into())));
    assert_eq!(
        obj.get("a"),
        Some(&Value::Array(vec![Value::Integer("1".into())]))
    );

    let v = crate::parse("{x: 0, a: {b: 2}}").unwrap();
    let inner = v
        .as_object()
        .unwrap()
        .get("a")
        .unwrap()
        .as_object()
        .unwrap();
    assert_eq!(inner.get("b"), Some(&Value::Integer("2".into())));

    // § 5.3.3's own example, verbatim: the quoted key's `}` is content.
    let v = crate::parse("{\"a}b\": 1, c: 2}").unwrap();
    let obj = v.as_object().unwrap();
    assert_eq!(obj.get("a}b"), Some(&Value::Integer("1".into())));
    assert_eq!(obj.get("c"), Some(&Value::Integer("2".into())));

    // A quoted key may quote brackets; the quoted span stays opaque.
    let v = crate::parse("{\"[x]\": 1}").unwrap();
    assert_eq!(
        v.as_object().unwrap().get("[x]"),
        Some(&Value::Integer("1".into()))
    );

    // Same values via the event entry point.
    assert!(crate::parse_events(r"{x: 0, \[a: 1}", |_| {}).is_ok());
    assert!(crate::parse_events("{x: 0, a: [1]}", |_| {}).is_ok());
    assert!(crate::parse_events("{\"a}b\": 1, c: 2}", |_| {}).is_ok());
}

// R9-F1 precedence: a forbidden bracket AND a malformed escape in the
// same inline compound. § 5.2's rules-6–9 preamble (spec: "the result
// is BadEscapeSequence (§ 6.13), which takes precedence over a missing
// closer") fires while the compound triage scans for the closer —
// before any pair is split — so the escape wins inside `{...}`. The
// multiline pair path runs no compound triage; § 5.3.1's bare-segment
// listing orders InvalidKey (raw forbidden `<key-char>`) before
// BadEscapeSequence (malformed `\X`) within one segment, and the shared
// validator checks forbidden raw bytes before decoding, so `a\q[` is
// InvalidKey.
#[test]
fn r9f1_forbidden_bracket_and_bad_escape_precedence() {
    let expect_bad_escape = |res: Result<(), crate::Error>| {
        assert!(
            matches!(
                res,
                Err(crate::Error::Structured(
                    crate::ErrorKind::BadEscapeSequence { .. }
                ))
            ),
            "expected BadEscapeSequence, got {res:?}"
        );
    };
    expect_bad_escape(crate::parse(r"{[a\q: 1}").map(|_| ()));
    expect_bad_escape(crate::parse_strict(r"{[a\q: 1}").map(|_| ()));
    expect_bad_escape(crate::from_str::<serde_json::Value>(r"{[a\q: 1}").map(|_| ()));
    expect_bad_escape(crate::parse_events(r"{[a\q: 1}", |_| {}).map(|_| ()));

    let err = crate::parse(r"a\q[ : 1").expect_err("must be InvalidKey");
    assert!(
        matches!(
            err,
            crate::Error::Structured(crate::ErrorKind::InvalidKey { .. })
        ),
        "expected InvalidKey, got {err:?}"
    );
}

// R9-F1 unit pin: the inline pair's separator scan shares the § 4/§ 5.3
// key-separator scanner — NO compound depth in the key. A bracket in
// the key prefix must not hide the separator that is actually present.
#[test]
fn r9f1_find_unescaped_colon_inline_ignores_key_depth() {
    assert_eq!(find_unescaped_colon_inline("[a: 1"), Some(2));
    assert_eq!(find_unescaped_colon_inline("{a: 1"), Some(2));
    // Quoted bracket content is skipped wholesale; the span's end is
    // followed by the separator.
    assert_eq!(find_unescaped_colon_inline("\"[a\": 1"), Some(4));
    // A colon inside a nested VALUE compound never wins: the separator
    // precedes the value, which is why dropping key-side depth is safe.
    assert_eq!(find_unescaped_colon_inline("a: {b: 1}"), Some(1));
    assert_eq!(find_unescaped_colon_inline("a: [1, {c: 2}]"), Some(1));
}

// R8-F2 recategorization of the fourth formerly-pinned document:
// `k: {a: [],[:[},a[{ {,a ]}` reached the pair-split path only via the
// FAST gate walk, which carried `in_key = true` residue through the
// gated `[` after the top-level comma (former quirk 2) and
// phantom-opened the `[:[` Array as a nested compound, shifting the
// depth accounting so the body's own `}` seemed to close it. The
// quote-aware machine sets `in_key = false` at every opener, so the
// `}` after `[:[` matches no scope kind and the `]` before the final
// `}` is a CROSSED closer at depth 0 — § 5.2's matching-closer rule
// yields no same-line matching closer, which § 6.11 diagnoses as
// UnterminatedInlineCompound. The fast machine now agrees (R8-F2), so
// every entry point reports UnterminatedInlineCompound.
#[test]
fn r8f2_fast_in_key_residue_no_longer_recategorizes_crossed_closer() {
    let input = "k: {a: [],[:[},a[{ {,a ]}";
    let expect_unterminated = |res: Result<(), crate::Error>| {
        assert!(
            matches!(
                res,
                Err(crate::Error::Structured(
                    crate::ErrorKind::UnterminatedInlineCompound { .. }
                ))
            ),
            "input {input:?}: expected UnterminatedInlineCompound"
        );
    };
    expect_unterminated(crate::parse(input).map(|_| ()));
    expect_unterminated(crate::parse_strict(input).map(|_| ()));
    expect_unterminated(crate::parse_events(input, |_| {}).map(|_| ()));
}

// R8-F2 regression: the five review-round-8 inputs. Every one is an
// INVALID document, and the quote-aware reading gives the same
// category for all five. The value position is already consumed by the
// closed inner compound (the empty `[]` / `{}`), so the trailing
// `[text` is content after a closed value, not an unterminated one:
//
// - § 5.8.5: "The decision is made once, when the parser begins
//   reading an inline value: if the first non-whitespace code point is
//   `{` or `[`, the value is a nested compound; otherwise the value is
//   an inline scalar that runs to the next unescaped `,` / `}` / `]`"
//   — after the inner compound closes there is no open value for a
//   following `[` to open.
// - § 6.12: "Non-whitespace content after the same-line matching
//   closer of a value-position compound ... The closer makes the
//   compound closed; the trailing bytes are therefore malformed
//   content, not an unterminated compound." The enclosing compound
//   itself still closes on the same line, so the defect is
//   MalformedInlineCompound, not UnterminatedInlineCompound.
// - § 5.3.3 ("Keys only"): a quote character in a value position
//   "is ordinary content with no special meaning" — the later
//   unrelated `'` in the last input must not change any earlier
//   byte's role, so the quote-free and quote-bearing twins MUST get
//   the same verdict.
//
// Pre-R8-F2 the fast walks left `value_start` set after the empty
// Array closed (former quirk 1) and carried `in_key` residue through
// `[` openers (former quirk 2), phantom-opened a nested compound at
// the next `[`, swallowed the enclosing body's own closer, and
// reported UnterminatedInlineCompound for the quote-free twins
// (`[[][text]`, `{a: [[][text]}`) while the quote-bearing twins
// (`[[]['text]`, `{a: [[][text], q: '}`) already reported
// MalformedInlineCompound — the same bytes, two verdicts, decided by
// a later unrelated quote.
#[test]
fn r8f2_closed_empty_array_consumes_value_start_across_modes() {
    let cases = [
        "[[][text]",
        "[[]['text]",
        "[{}[text]",
        "{a: [[][text]}",
        "{a: [[][text], q: '}",
    ];
    for input in cases {
        let expect_malformed = |res: Result<(), crate::Error>| {
            assert!(
                matches!(
                    res,
                    Err(crate::Error::Structured(
                        crate::ErrorKind::MalformedInlineCompound { .. }
                    ))
                ),
                "input {input:?}: expected MalformedInlineCompound"
            );
        };
        expect_malformed(crate::parse(input).map(|_| ()));
        expect_malformed(crate::parse_strict(input).map(|_| ()));
        expect_malformed(crate::parse_events(input, |_| {}).map(|_| ()));
    }
}

// --- R8-F6 probe: deterministic InlineBounds index-cost counters -----------

#[path = "../../benches/fixtures_ix.rs"]
mod ix_fixtures;

#[test]
fn ix_probe_r8f6_fixture_shapes_are_valid() {
    use crate::Value;

    // Wide arrays of tiny compounds: one Array of n empty Objects.
    let doc = ix_fixtures::wide_line_arr_tiny(64);
    let v = crate::parse(&doc).expect("wide_arr_tiny must parse");
    let arr = v.as_object().unwrap().get("k").unwrap().as_array().unwrap();
    assert_eq!(arr.len(), 64);
    assert!(arr
        .iter()
        .all(|it| matches!(it, Value::Object(o) if o.is_empty())));

    // Wide objects of tiny compounds: one Object with n empty Objects.
    let doc = ix_fixtures::wide_line_obj_tiny(64);
    let v = crate::parse(&doc).expect("wide_obj_tiny must parse");
    let obj = v
        .as_object()
        .unwrap()
        .get("k")
        .unwrap()
        .as_object()
        .unwrap();
    assert_eq!(obj.len(), 64);
    assert!(obj
        .iter()
        .all(|(_, it)| matches!(it, Value::Object(o) if o.is_empty())));

    // Two-level: Array of n one-Arrays of one empty Object.
    let doc = ix_fixtures::wide_line_two_level(64);
    let v = crate::parse(&doc).expect("two_level must parse");
    let arr = v.as_object().unwrap().get("k").unwrap().as_array().unwrap();
    assert_eq!(arr.len(), 64);
    for it in arr {
        let inner = it.as_array().expect("two-level item must be an Array");
        assert_eq!(inner.len(), 1);
        assert!(matches!(inner[0], Value::Object(ref o) if o.is_empty()));
    }

    // Many small trees: root of `lines` pairs, each a 2-item Array.
    let doc = ix_fixtures::many_inline_trees(50);
    let v = crate::parse(&doc).expect("many_trees must parse");
    let root = v.as_object().unwrap();
    assert_eq!(root.len(), 50);
    for (k, it) in root {
        let arr = it
            .as_array()
            .unwrap_or_else(|| panic!("{k}: expected Array"));
        assert_eq!(arr.len(), 2, "{k}: expected 2 items");
    }

    // Deep chain: the "k" spine nests exactly `depth` Objects down
    // (root key is "k"; each nested level repeats the key "a").
    let doc = ix_fixtures::deep_chain(32);
    let v = crate::parse(&doc).expect("deep_chain must parse");
    let mut depth = 0usize;
    let mut cur = &v;
    while let Some(obj) = cur.as_object() {
        let key = if depth == 0 { "k" } else { "a" };
        cur = obj
            .get(key)
            .unwrap_or_else(|| panic!("deep_chain spine key {key} missing"));
        depth += 1;
        if cur.as_object().is_none() {
            break;
        }
    }
    assert_eq!(depth, 33, "deep_chain spine depth drift");

    // The long single lines really are long (no accidental line cap
    // shrinking C below the intended shape).
    assert!(ix_fixtures::wide_line_arr_tiny(4096).len() > 12_000);
}

fn ix_print_counters(
    name: &str,
    path: &str,
    doc_bytes: usize,
    s: &super::inline::ix_probe::Snapshot,
) {
    println!(
        "IX\t{name}\t{path}\tdoc_bytes={doc_bytes}\tbodies={}\tbody_bytes={}\tpairs={}\tpairs_max={}\tkc={}/{}\tkc_steps={}\tkc_steps_max={}\toca={}/{}\toca_steps={}\toca_steps_max={}\tsort={}\tsort_elems={}\tsort_cmps={}",
        s.bodies, s.body_bytes, s.pairs_total, s.pairs_max,
        s.kc_hits, s.kc_calls, s.kc_steps, s.kc_steps_max,
        s.oca_hits, s.oca_calls, s.oca_steps, s.oca_steps_max,
        s.sort_calls, s.sort_elems, s.sort_cmps,
    );
}

/// R8-F6 measurement: run both parse paths over the whole shape space
/// and print the deterministic ix_probe counters per shape and path.
/// Run filtered with --nocapture: `cargo test --release --lib ix_probe -- --nocapture`.
#[test]
fn ix_probe_r8f6_index_counters() {
    use std::fmt::Write as _;

    let shapes: Vec<(&str, String)> = vec![
        ("wide_arr_tiny_64", ix_fixtures::wide_line_arr_tiny(64)),
        ("wide_arr_tiny_1024", ix_fixtures::wide_line_arr_tiny(1024)),
        ("wide_arr_tiny_4096", ix_fixtures::wide_line_arr_tiny(4096)),
        (
            "wide_arr_small_1024",
            ix_fixtures::wide_line_arr_small(1024),
        ),
        ("wide_obj_tiny_1024", ix_fixtures::wide_line_obj_tiny(1024)),
        ("two_level_512", ix_fixtures::wide_line_two_level(512)),
        ("many_trees_2000", ix_fixtures::many_inline_trees(2000)),
        ("deep_chain_32", ix_fixtures::deep_chain(32)),
        ("deep_chain_96", ix_fixtures::deep_chain(96)),
        ("inline_doc_50k", {
            // Same generator as the harness bench_ab `inline_from_str`
            // scenario (verbatim here: benches/fixtures.rs has no copy).
            let mut out = String::with_capacity(51_200);
            let mut i = 0u32;
            while out.len() < 50_000 {
                let _ = writeln!(
                    out,
                    "k{i}: {{a: {i}, b: text item {i}, c: [{i}, {}, {i}], d:: raw {i}, e: {{deep: {}.5}}}}",
                    i + 1,
                    i % 10
                );
                i += 1;
            }
            out
        }),
        ("synth_50k", ix_fixtures::medium_50k()),
    ];

    for (name, doc) in &shapes {
        let doc_bytes = doc.len();
        // Owned path (`parse`).
        super::inline::ix_probe::reset();
        let v = crate::parse(doc).unwrap_or_else(|e| panic!("{name}: owned parse failed: {e}"));
        let s = super::inline::ix_probe::snapshot();
        assert!(!v.as_object().expect(name).is_empty());
        ix_print_counters(name, "P", doc_bytes, &s);

        // Thin path (`parse_events`).
        super::inline::ix_probe::reset();
        let mut events = 0usize;
        crate::parse_events(doc, |_ev| {
            events += 1;
        })
        .unwrap_or_else(|e| panic!("{name}: thin parse failed: {e}"));
        let s = super::inline::ix_probe::snapshot();
        assert!(events > 0);
        ix_print_counters(name, "E", doc_bytes, &s);
    }
}

fn ix_run_parse(input: &str) -> bool {
    std::hint::black_box(crate::parse(input).is_ok())
}

fn ix_run_events(input: &str) -> bool {
    std::hint::black_box(crate::parse_events(input, |_ev| {}).is_ok())
}

/// R8-F6 wall-clock side-instrument (NOISY MACHINE — deterministic
/// counters above are the primary instrument). INSTRUMENTED: this runs
/// in the lib test binary, i.e. the cfg(test) build with ix_probe
/// counters live and the counting global allocator of src/arena_probe
/// in place — its numbers are NOT production timings; the
/// uninstrumented instrument is the a2-harness binary `bench_ix`.
/// Same scenario names as the counters test, bench_ab-style output: `SCEN <shape>:<path>
/// iters=<n>` then nine `SCEN <shape>:<path> batch=<i> nanos=<ns>`
/// lines; normalize per iteration with each run's own iters line.
/// Plus micro lines: `MIKC ...` (ns/op of `known_closer` hit/miss over
/// the wide_arr_small body's C=1024 pairs) and `MISORT ...` (ns per
/// `sort_unstable_by_key` of C elements in the all-sibling pop order,
/// which is already ascending).
///
/// #[ignore] (R9-F2): calibration loops and nine timing batches per
/// scenario must not run in the ordinary suite. Run explicitly, in a
/// single-threaded window of its own:
/// `cargo test --release --lib ix_probe_r8f6_wall_clock -- --ignored --test-threads=1 --nocapture`
#[test]
#[ignore]
fn ix_probe_r8f6_wall_clock() {
    use std::fmt::Write as _;
    use std::hint::black_box;
    use std::time::{Duration, Instant};

    let shapes: Vec<(&str, String)> = vec![
        ("wide_arr_tiny_1024", ix_fixtures::wide_line_arr_tiny(1024)),
        ("wide_arr_tiny_4096", ix_fixtures::wide_line_arr_tiny(4096)),
        (
            "wide_arr_small_1024",
            ix_fixtures::wide_line_arr_small(1024),
        ),
        ("wide_obj_tiny_1024", ix_fixtures::wide_line_obj_tiny(1024)),
        ("two_level_512", ix_fixtures::wide_line_two_level(512)),
        ("many_trees_2000", ix_fixtures::many_inline_trees(2000)),
        ("deep_chain_96", ix_fixtures::deep_chain(96)),
        ("inline_doc_50k", {
            // Same generator as the harness bench_ab `inline_from_str`
            // scenario (verbatim here: benches/fixtures.rs has no copy).
            let mut out = String::with_capacity(51_200);
            let mut i = 0u32;
            while out.len() < 50_000 {
                let _ = writeln!(
                    out,
                    "k{i}: {{a: {i}, b: text item {i}, c: [{i}, {}, {i}], d:: raw {i}, e: {{deep: {}.5}}}}",
                    i + 1,
                    i % 10
                );
                i += 1;
            }
            out
        }),
        ("synth_50k", ix_fixtures::medium_50k()),
    ];

    for (name, doc) in &shapes {
        for (path, run) in [
            ("P", ix_run_parse as fn(&str) -> bool),
            ("E", ix_run_events),
        ] {
            // 2 untimed warmups, then calibrate to one >= 40 ms batch.
            for _ in 0..2 {
                run(doc);
            }
            let mut iters: u64 = 1;
            loop {
                let t = Instant::now();
                for _ in 0..iters {
                    black_box(run(doc));
                }
                if t.elapsed() >= Duration::from_millis(40) || iters >= (1 << 22) {
                    break;
                }
                iters *= 2;
            }
            println!("SCEN {name}:{path} iters={iters}");
            for batch in 0..9u32 {
                let t = Instant::now();
                for _ in 0..iters {
                    black_box(run(doc));
                }
                println!(
                    "SCEN {name}:{path} batch={batch} nanos={}",
                    t.elapsed().as_nanos() as u64
                );
            }
        }
    }

    // Micro: known_closer over the wide_arr_small_1024 body — C=1024
    // pairs, hits on opener slices, misses on a mid-item slice.
    let line = ix_fixtures::wide_line_arr_small(1024);
    // The closer scan wants the compound body itself (leading `[`),
    // not the whole `k: [...]` line.
    let body = line.trim_end_matches('\n');
    let body = &body["k: ".len()..];
    let mut pairs = Vec::new();
    let verdict = super::inline::scan_inline_closer_with_bounds(body, b'[', b']', 0, S, &mut pairs);
    assert!(matches!(verdict, super::inline::InlineCloserScan::Found(_)));
    assert_eq!(
        pairs.len(),
        1024,
        "wide_arr_small body must record 1024 pairs"
    );
    let bounds = InlineBounds::over(body, &pairs);
    // Children are `{a:1}` at stride 6 from offset 1.
    let hit_slice = &body[1..6];
    assert_eq!(bounds.known_closer(hit_slice), Some(4));
    let miss_slice = &body[3..8];
    assert_eq!(bounds.known_closer(miss_slice), None);
    for (label, slice, expect) in [("hit", hit_slice, 4usize), ("miss", miss_slice, 0usize)] {
        let mut iters: u64 = 1;
        loop {
            let t = Instant::now();
            for _ in 0..iters {
                black_box(bounds.known_closer(black_box(slice)));
            }
            if t.elapsed() >= Duration::from_millis(40) || iters >= (1 << 24) {
                break;
            }
            iters *= 2;
        }
        let mut best: u128 = u128::MAX;
        for _ in 0..9u32 {
            let t = Instant::now();
            for _ in 0..iters {
                black_box(bounds.known_closer(black_box(slice)));
            }
            best = best.min(t.elapsed().as_nanos());
        }
        println!("MIKC C=1024 kind={label} expect={expect} iters={iters} min_batch_nanos={best} ns_per_op={}", best as f64 / iters as f64);
    }

    // Micro: sort cost of the boundary vec in the all-sibling pop
    // order — siblings pop left-to-right, so the recorded order for
    // these shapes is already ascending; reverse brackets the worst
    // case pdqsort would face on this table.
    for (order_label, table) in [
        (
            "asc",
            (0..1024).map(|i| (i * 6, i * 6 + 4)).collect::<Vec<_>>(),
        ),
        (
            "reverse",
            (0..1024)
                .rev()
                .map(|i| (i * 6, i * 6 + 4))
                .collect::<Vec<_>>(),
        ),
    ] {
        let mut iters: u64 = 1;
        loop {
            let t = Instant::now();
            for _ in 0..iters {
                let mut t2 = table.clone();
                t2.sort_unstable_by_key(|p| p.0);
                black_box(&t2);
            }
            if t.elapsed() >= Duration::from_millis(40) || iters >= (1 << 20) {
                break;
            }
            iters *= 2;
        }
        let mut best: u128 = u128::MAX;
        for _ in 0..9u32 {
            let t = Instant::now();
            for _ in 0..iters {
                let mut t2 = table.clone();
                t2.sort_unstable_by_key(|p| p.0);
                black_box(&t2);
            }
            best = best.min(t.elapsed().as_nanos());
        }
        println!("MISORT C=1024 order={order_label} iters={iters} min_batch_nanos={best} ns_per_sort_incl_clone={}", best as f64 / iters as f64);
    }
}
/// R8-F6 direct A/B, RELABELED by the round-9 review (R9-F3): the
/// bypass forces the live-dispatch fallback, so the batch delta is
/// cached-vs-uncached PARSING — the memo's benefit — measured in the
/// instrumented lib-test binary (cfg(test) ix counters + the counting
/// global allocator). It is NOT the isolated cost of the binary
/// search, and not a comparison of index choices; that isolated,
/// uninstrumented measurement lives in the a2-harness binary
/// `bench_ix` (binary search vs monotonic cursor vs passed boundary,
/// both sides keeping the recorded boundaries). Positive controls per
/// shape: (1) the bypassed parse must produce a Value whose Debug
/// matches the memo-on parse exactly; (2) with the bypass engaged the
/// ix_probe lookup counters must be zero (a vacuous A/B would show
/// zeros anyway — this proves the switch really flipped).
///
/// #[ignore] (R9-F2): timing batches must not run in the ordinary
/// suite. Run explicitly, single-threaded:
/// `cargo test --release --lib ix_probe_r8f6_memo_lookup_ab -- --ignored --test-threads=1 --nocapture`
#[test]
#[ignore]
fn ix_probe_r8f6_memo_lookup_ab() {
    use std::hint::black_box;
    use std::time::{Duration, Instant};

    use super::inline::ix_probe;

    let shapes: Vec<(&str, String)> = vec![
        ("wide_arr_tiny_1024", ix_fixtures::wide_line_arr_tiny(1024)),
        ("wide_arr_tiny_4096", ix_fixtures::wide_line_arr_tiny(4096)),
        (
            "wide_arr_small_1024",
            ix_fixtures::wide_line_arr_small(1024),
        ),
        ("wide_obj_tiny_1024", ix_fixtures::wide_line_obj_tiny(1024)),
        ("two_level_512", ix_fixtures::wide_line_two_level(512)),
        ("many_trees_2000", ix_fixtures::many_inline_trees(2000)),
        ("deep_chain_96", ix_fixtures::deep_chain(96)),
    ];

    for (name, doc) in &shapes {
        // Positive control 1: bypassed parse is byte-identical.
        ix_probe::reset();
        let on = crate::parse(doc).unwrap_or_else(|e| panic!("{name}: memo parse failed: {e}"));
        let lookups_before_bypass = {
            let s = ix_probe::snapshot();
            s.kc_calls + s.oca_calls
        };
        let bypassed = ix_probe::set_bypass(true);
        let off = crate::parse(doc).unwrap_or_else(|e| panic!("{name}: bypass parse failed: {e}"));
        let lookup_calls_while_bypassed = {
            let s = ix_probe::snapshot();
            s.kc_calls + s.oca_calls - lookups_before_bypass
        };
        drop(bypassed);
        assert_eq!(
            format!("{on:?}"),
            format!("{off:?}"),
            "{name}: bypass changed the parse result"
        );
        // Positive control 2: the switch really rerouted every lookup
        // (delta across the bypassed parse only — the memo-on parse's
        // counts precede the baseline snapshot).
        assert_eq!(
            lookup_calls_while_bypassed, 0,
            "{name}: bypass did not engage"
        );

        for (label, bypass) in [("on", false), ("off", true)] {
            let _mode = ix_probe::set_bypass(bypass);
            for _ in 0..2 {
                black_box(crate::parse(doc).is_ok());
            }
            let mut iters: u64 = 1;
            loop {
                let t = Instant::now();
                for _ in 0..iters {
                    black_box(crate::parse(doc).is_ok());
                }
                let e = t.elapsed();
                if e >= Duration::from_millis(40) || iters >= (1 << 22) {
                    break;
                }
                iters *= 2;
            }
            for batch in 0..9u32 {
                let t = Instant::now();
                for _ in 0..iters {
                    black_box(crate::parse(doc).is_ok());
                }
                let e = t.elapsed();
                println!(
                    "AB {name} memo={label} iters={iters} batch={batch} nanos={}",
                    e.as_nanos() as u64
                );
            }
        }
    }
}

// --- R10-F1: quote-presence prescan cost (deterministic counters) ----------

#[test]
fn r10f1_deep_chain_leaf_shapes_are_valid() {
    use crate::Value;

    // The D x M family must have exactly the requested spine depth and
    // leaf length — a shape drift would silently weaken the counter
    // pins below.
    for (depth, leaf_bytes) in [(1usize, 8usize), (4, 64), (32, 512), (100, 16)] {
        let doc = ix_fixtures::deep_chain_leaf(depth, leaf_bytes);
        let mut v = crate::parse(&doc).expect("family document must parse");
        let mut levels = 0usize;
        while let Some(obj) = v.as_object() {
            let key = if levels == 0 { "k" } else { "a" };
            v = obj
                .get(key)
                .unwrap_or_else(|| panic!("spine key {key} missing at level {levels}"))
                .clone();
            levels += 1;
        }
        assert_eq!(levels, depth + 1, "spine depth at depth={depth}");
        match &v {
            Value::String(s) => assert_eq!(s.len(), leaf_bytes, "leaf at depth={depth}"),
            other => panic!("leaf must be a String, got {other:?}"),
        }
    }
    assert!(ix_fixtures::deep_chain_leaf(64, 4096).len() > 4096 + 64 * 5);
}

#[test]
fn r10f1_root_quotes_threaded_over_quotefree_descendants() {
    use crate::Value;

    // The root body carries the quote flag, so quote-free descendant
    // levels run the quote-aware machines; their segmentation must be
    // exactly what the quote-free machines produce (R8-F2
    // byte-identity): the quoted key stays ONE key (its comma is
    // opaque, its dot is content), and the quote-free descendants
    // split normally.
    let doc = "{\"a,b\": {c: {d: 1, e: 2}}, g: [1, [2, 3]]}";
    let v = crate::parse(doc).expect("threaded doc must parse");
    let root = v.as_object().unwrap();
    let quoted = root.get("a,b").expect("quoted key must survive whole");
    let quoted = quoted.as_object().expect("quoted key maps to object");
    let c = quoted.get("c").unwrap().as_object().unwrap();
    assert_eq!(c.get("d"), Some(&Value::Integer("1".into())));
    assert_eq!(c.get("e"), Some(&Value::Integer("2".into())));
    let g = root.get("g").unwrap().as_array().unwrap();
    assert_eq!(g[0], Value::Integer("1".into()));
    assert_eq!(g[1].as_array().unwrap()[0], Value::Integer("2".into()));

    // All three engines accept the same document.
    crate::parse_strict(doc).expect("strict must accept");
    crate::from_str::<serde_json::Value>(doc).expect("serde must accept");
    let mut events = 0usize;
    crate::parse_events(doc, |_| {
        events += 1;
    })
    .expect("events must accept");
    assert!(events > 0);
}

#[test]
fn r10f1_quote_prescan_cost_no_depth_multiplier() {
    // Fixed leaf M=512, varying depth D. Before R10-F1 the two prescan
    // sites (`split_top_level`'s dispatch and the separator scan) saw
    // the whole M-byte leaf at EVERY level, ~2*M*D recorded bytes; the
    // threaded root flag leaves a constant number of root-body scans
    // plus per-level key-prefix work.
    let m = 512usize;
    let measure = |depth: usize| {
        let doc = ix_fixtures::deep_chain_leaf(depth, m);
        super::inline::ix_probe::reset();
        let v = crate::parse(&doc).expect("family document must parse");
        assert!(v.as_object().is_some());
        super::inline::ix_probe::snapshot().hq_bytes
    };
    let d1 = measure(1);
    let d32 = measure(32);
    assert!(d1 >= m as u64, "root-body prescan must happen: d1={d1}");
    assert!(
        d32 < 2 * d1 + 32 * 64,
        "prescan bytes must not multiply by depth: d1={d1} d32={d32}"
    );
    assert!(d32 < 8 * m as u64, "absolute bound: d32={d32} m={m}");
}

#[test]
fn r10f1_quote_prescan_cost_linear_in_leaf() {
    // Fixed depth D=8, varying leaf M. The total prescan volume must
    // stay a small constant factor of M (the pre-fix code recorded
    // ~2*M*8 bytes here) and grow roughly linearly in M.
    let measure = |m: usize| {
        let doc = ix_fixtures::deep_chain_leaf(8, m);
        super::inline::ix_probe::reset();
        let _ = crate::parse(&doc).expect("family document must parse");
        super::inline::ix_probe::snapshot().hq_bytes
    };
    let small = measure(512);
    let large = measure(8192);
    assert!(small >= 512, "root prescan must happen: {small}");
    assert!(small < 8 * 512, "small bound: {small}");
    assert!(
        large >= 8192,
        "prescan must still scale with the leaf: {large}"
    );
    assert!(large < 8 * 8192, "large bound: {large}");
    let ratio = large as f64 / small as f64;
    assert!(
        ratio > 8.0 && ratio < 32.0,
        "growth must be ~linear in M: ratio={ratio}"
    );
}

/// Deterministic companion to the two scaling pins: prints the
/// quote-prescan counters over the whole D x M family for both parse
/// paths, so a future round can re-derive the before/after table with
/// `cargo test --lib ix_probe_r10f1_quote_prescan_counters -- --nocapture`.
#[test]
fn ix_probe_r10f1_quote_prescan_counters() {
    let shapes = [
        (1usize, 512usize),
        (4, 512),
        (8, 512),
        (32, 512),
        (64, 512),
        (8, 8192),
        (8, 65536),
    ];
    for (depth, leaf) in shapes {
        let doc = ix_fixtures::deep_chain_leaf(depth, leaf);
        for (path, run) in [
            (
                "P",
                Box::new(|doc: &str| {
                    let _ = crate::parse(doc);
                }) as Box<dyn Fn(&str)>,
            ),
            (
                "E",
                Box::new(|doc: &str| {
                    let _ = crate::parse_events(doc, |_| {});
                }) as Box<dyn Fn(&str)>,
            ),
        ] {
            super::inline::ix_probe::reset();
            run(&doc);
            let s = super::inline::ix_probe::snapshot();
            println!(
                "HQ\tdeep_chain_leaf\t{path}\tdepth={depth}\tleaf={leaf}\tdoc_bytes={}\thq_calls={}\thq_bytes={}\thq_max={}",
                doc.len(),
                s.hq_calls,
                s.hq_bytes,
                s.hq_max
            );
        }
    }
}

// R11-F1: the ROOT quote flag (R10-F1) routes quote-free descendants
// through the quote-aware split machine, so SplitQ's last-segment
// handling must match SplitFast's on this shape: a `.`-armed segment
// whose § 3.3 whitespace skip runs to EOF has no separator, and the
// pushed raw segment must resolve — through the callers' colon search
// (§ 5.8.2/§ 5.3: separator finding precedes key validation) — to the
// § 6.12 missing-separator MalformedInlineCompound on every entry
// point. The pre-fix SplitQ raised EmptyKey here whenever the ROOT
// carried a quote anywhere (ancestor key, sibling value, sibling
// array item), while a quote-free root took SplitFast and already
// said MalformedInlineCompound for the very same nested body.
#[test]
fn r11f1_splitq_last_segment_missing_separator_matches_fast_machine() {
    use crate::ErrorKind;

    let expect_malformed = |input: &str, res: Result<(), crate::Error>| {
        assert!(
            matches!(
                res,
                Err(crate::Error::Structured(
                    ErrorKind::MalformedInlineCompound { .. }
                ))
            ),
            "input {input:?}: expected MalformedInlineCompound, got {res:?}"
        );
    };
    let all_entry_points = |input: &str| {
        expect_malformed(input, crate::parse(input).map(|_| ()));
        expect_malformed(input, crate::parse_strict(input).map(|_| ()));
        expect_malformed(
            input,
            crate::from_str::<serde_json::Value>(input).map(|_| ()),
        );
        expect_malformed(input, crate::parse_events(input, |_| {}).map(|_| ()));
    };

    // The finding's repro documents (SPACE after the dot). The nested
    // body `b.  ` is quote-free in every case — only the threaded
    // flag selects SplitQ for it.
    for input in [
        r"{a: {b. }}",       // quote-free root: SplitFast already said Malformed
        r"{a: {b. }, q: '}", // quote in a SIBLING VALUE after
        r"{q: ', a: {b. }}", // quote in a SIBLING VALUE before
        r#"{"a": {b. }}"#,   // quote at an ANCESTOR KEY position
        r"[{b. }, ']",       // quote in a SIBLING ARRAY ITEM
    ] {
        all_entry_points(input);
    }

    // SPACE, TAB and U+2000 after the dot trigger the identical path
    // (assembled from pieces so the corpus harvest sees only the
    // trivial fragments).
    for tail in [" ", "\t", "\u{2000}"] {
        let mut doc = String::from("{a: {b.");
        doc.push_str(tail);
        doc.push_str("}, q: '}");
        all_entry_points(&doc);
    }

    // The sibling quote's SPECIES is irrelevant (§ 5.3.3: value-side
    // quotes are content).
    for q in ["'", "\"", "`"] {
        let doc = format!(r"{{a: {{b. }}, q: {q}}}");
        all_entry_points(&doc);
    }

    // Positive controls — unchanged by the fix. No trailing whitespace
    // after the dot: plain Exhausted path, MalformedInlineCompound
    // before and after (SplitFast verdict included via the quote-free
    // root).
    for input in [r"{a: {b.}, q: '}", r"{a: {b.}}"] {
        all_entry_points(input);
    }
    // Valid trailing comma: Ok everywhere, same tree.
    let ok_doc = r"{a: {b: 1, }, q: '}";
    let v = crate::parse(ok_doc).expect("trailing-comma control must parse");
    let root = v.as_object().unwrap();
    let a = root.get("a").unwrap().as_object().unwrap();
    assert_eq!(a.get("b"), Some(&Value::Integer("1".into())));
    assert_eq!(root.get("q"), Some(&Value::String("'".into())));
    crate::parse_strict(ok_doc).expect("strict must accept");
    crate::from_str::<serde_json::Value>(ok_doc).expect("serde must accept");
    crate::parse_events(ok_doc, |_| {}).expect("events must accept");

    // The GENUINE dotted key with an empty final segment HAS a
    // separator, never reaches EofAfterWsSkip, and stays EmptyKey
    // (§ 6.5 via insert_value) — quote-free root and quoted sibling
    // alike.
    for input in [r"{a.: 1}", r#"{"a": 1, b.: 2}"#] {
        for res in [
            crate::parse(input).map(|_| ()),
            crate::parse_strict(input).map(|_| ()),
            crate::from_str::<serde_json::Value>(input).map(|_| ()),
            crate::parse_events(input, |_| {}).map(|_| ()),
        ] {
            assert!(
                matches!(
                    res,
                    Err(crate::Error::Structured(ErrorKind::EmptyKey { .. }))
                ),
                "input {input:?}: expected EmptyKey, got {res:?}"
            );
        }
    }
}