shcl 1.2.0

SHCL - Simple Hierarchical Config Language. Reference parser, accessor, writer, and CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
// SPDX-License-Identifier: MIT
// Copyright © 2026 Jim Collier (CryptogID: ѳ6ᴚ℈𐀘𐇦ɛ𐊁¥Mマb϶Δ𐌞)

//! SHCL reference implementation: parser, accessor, writer/formatter.
//! Single file on purpose - the drop-in story is "copy this file into your tree".
//! The language spec lives in project/spec.md; the conformance corpus in
//! project/conformance/ pins every behavior here.
//! Every other binding mirrors this file's structure on purpose (parity over
//! idiom - see style-guide.md), so restructuring here means restructuring all.

use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Public surface
// ---------------------------------------------------------------------------

/// Per-document forgiveness knob. Set once at load; composes with per-call onBad.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Strictness {
	Loose,
	#[default]
	Standard,
	Strict,
}

impl Strictness {
	/// Accepts the CLI spellings: loose|standard|strict or 1|2|3.
	pub fn from_arg(s: &str) -> Option<Strictness> {
		match s.to_ascii_lowercase().as_str() {
			"loose" | "1" => Some(Strictness::Loose),
			"standard" | "2" => Some(Strictness::Standard),
			"strict" | "3" => Some(Strictness::Strict),
			_ => None,
		}
	}
}

/// Only `Error` fails a strict load; `Hint` flags legal-but-lookalike input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
	Error,
	Hint,
}

#[derive(Debug, Clone)]
pub struct Diagnostic {
	pub line: usize, // 1-based
	pub severity: Severity,
	pub message: String,
	/// Stable machine code (E001.., H001..) identifying the diagnostic kind. The
	/// contract lives here; the `message` prose is a free, per-binding voice.
	pub code: &'static str,
}

/// Map a diagnostic message to its stable code. The one place prose couples to a
/// code, so the wording stays free everywhere else.
fn diag_code(msg: &str) -> &'static str {
	if msg.starts_with("field mixed with list elements") {
		"E001"
	} else if msg.starts_with("value after selector on ") {
		"E002"
	} else if msg.starts_with("no instance ") {
		"E003"
	} else if msg.starts_with("wildcard selector is query-only") {
		"E004"
	} else if msg.starts_with("unterminated raw block") {
		"E005"
	} else if msg.starts_with("raw block with no parent field") {
		"E006"
	} else if msg.starts_with("list element with no parent field") {
		"E007"
	} else if msg.starts_with("list element mixed with field children") {
		"E008"
	} else if msg.starts_with("empty list element") {
		"E009"
	} else if msg.starts_with("bare comma in list element") {
		"E010"
	} else if msg.starts_with("field already has a value") {
		"E011"
	} else if msg.starts_with("indentation matches no open level") {
		"E012"
	} else if msg.starts_with("malformed line skipped") {
		"E014"
	} else if msg.starts_with("malformed line: ") {
		"E013"
	} else if msg.starts_with("missing colon") {
		"E015"
	} else if msg.starts_with("nesting deeper than") {
		"E016"
	} else if msg.starts_with("unterminated quote in value") {
		"E017"
	} else if msg.starts_with("merged with ") {
		"H002"
	} else if msg.starts_with("unknown field ") {
		"V001"
	} else if msg.starts_with("required path missing") {
		"V002"
	} else if msg.starts_with("wrong type at ") {
		"V003"
	} else if msg.starts_with("value not allowed at ") {
		"V004"
	} else if msg.starts_with("value below min at ") {
		"V005"
	} else if msg.starts_with("value above max at ") {
		"V006"
	} else if msg.starts_with("instance count out of bounds at ") {
		"V007"
	} else if msg.starts_with("unknown schema key ") {
		"V090"
	} else if msg.starts_with("unknown schema type ") {
		"V091"
	} else if msg.starts_with("bad schema constraint ") {
		"V092"
	} else if msg.starts_with("bad schema path") {
		"V093"
	} else if msg.starts_with("bad schema fragment") {
		"V094"
	} else if msg.starts_with("unknown schema fragment ") {
		"V095"
	} else if msg.starts_with("schema failed to load") {
		"V099"
	} else {
		"E000" // uncategorized error (should not happen; keeps the map total)
	}
}

/// Read status sentinels. `Empty` is informational - the empty value is still returned.
/// Ordered by severity so a worst-of aggregate is just `max`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Status {
	Good,
	Empty,
	NotFound,
	BadType,
	Multiple,
}

/// Why a write would fail (`write_reason()`): the distinctions behind a
/// setter's bare `false`. `Writable` = the path passes the writer's
/// validation; the rest name the five ways it cannot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteReason {
	Writable,
	BadPath,     // empty path, or the scanner rejected it
	ValueInPath, // the path carries a `: value` part; writes take values separately
	Wildcard,    // wildcard selectors are query-only
	NoSuchIndex, // a `[#k]` instance that does not (and can never) exist
	TooDeep,     // deeper than the nesting cap; the writer never creates past it
}

/// Full-tier read result: value plus status plus the original raw text (when the
/// path resolved), so a caller can always recover what was actually in the file.
/// Array reads also carry one status per slot (element, or wildcard instance) in
/// `slots`; `status` is then the worst slot. Scalar reads leave `slots` empty.
/// `line` is the 1-based source line of the resolved binding (0 when the path
/// did not resolve to one node, or the node was writer-built), so a consumer
/// check the schema cannot express can still cite the line. `quoted` is true
/// when the read's single scalar element was quoted in the source - the escape
/// hatch that lets a downstream language reserve `@null` while `"@null"` stays
/// a plain string. Arrays, raw blocks, and empties leave it false.
#[derive(Debug, Clone)]
pub struct Read<T> {
	pub value: T,
	pub status: Status,
	pub raw: Option<String>,
	pub slots: Vec<Status>,
	pub line: usize,
	pub quoted: bool,
}

impl<T> Read<T> {
	fn new(value: T, status: Status, raw: Option<String>) -> Read<T> {
		Read {
			value,
			status,
			raw,
			slots: Vec::new(),
			line: 0,
			quoted: false,
		}
	}
	fn with_slots(value: T, status: Status, raw: Option<String>, slots: Vec<Status>) -> Read<T> {
		Read {
			value,
			status,
			raw,
			slots,
			line: 0,
			quoted: false,
		}
	}
	fn at(mut self, line: usize, quoted: bool) -> Read<T> {
		self.line = line;
		self.quoted = quoted;
		self
	}
	pub fn ok(&self) -> bool {
		matches!(self.status, Status::Good | Status::Empty)
	}
}

#[derive(Debug)]
pub struct LoadError {
	pub diagnostics: Vec<Diagnostic>,
	/// The document the parse produced anyway. Recover-and-continue means the
	/// diagnostics are the point of a failed strict load, and the tree is what
	/// a Standard load would have kept - so a caller can still inspect both.
	pub document: Document,
}

impl std::fmt::Display for LoadError {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		// Name the first few failures right in the message; the bare count made
		// callers dig for information the error was already holding.
		let errs: Vec<&Diagnostic> = self
			.diagnostics
			.iter()
			.filter(|d| d.severity == Severity::Error)
			.collect();
		write!(f, "strict load failed: {} error diagnostic(s)", errs.len())?;
		for d in errs.iter().take(3) {
			write!(f, "; line {}: {} {}", d.line, d.code, d.message)?;
		}
		if errs.len() > 3 {
			write!(f, "; +{} more", errs.len() - 3)?;
		}
		Ok(())
	}
}

impl std::error::Error for LoadError {}

/// Local (floating) date/time unless a zone suffix was present. Fields mirror
/// what was written: a date-only value has no time, and vice versa.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ShclDateTime {
	pub date: Option<(i32, u32, u32)>,         // (year, month, day)
	pub time: Option<(u32, u32, Option<u32>)>, // (hour, minute, seconds if written)
	pub frac: Option<String>,                  // fractional-second digits as typed
	pub zone: Option<ZoneSpec>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ZoneSpec {
	Utc,
	OffsetMinutes(i32),
}

impl std::fmt::Display for ShclDateTime {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		if let Some((y, m, d)) = self.date {
			write!(f, "{:04}-{:02}-{:02}", y, m, d)?;
			if self.time.is_some() {
				write!(f, "T")?;
			}
		}
		if let Some((h, mi, s)) = self.time {
			write!(f, "{:02}:{:02}", h, mi)?;
			if let Some(sec) = s {
				write!(f, ":{:02}", sec)?;
			}
			if let Some(fr) = &self.frac {
				write!(f, ".{}", fr)?;
			}
		}
		match self.zone {
			Some(ZoneSpec::Utc) => write!(f, "Z")?,
			Some(ZoneSpec::OffsetMinutes(off)) => {
				let sign = if off < 0 { '-' } else { '+' };
				let a = off.abs();
				write!(f, "{}{:02}:{:02}", sign, a / 60, a % 60)?;
			}
			None => {}
		}
		Ok(())
	}
}

// ---------------------------------------------------------------------------
// In-memory model
// ---------------------------------------------------------------------------
// One rule covers everything: a node is (field-name, value, children); nodes
// merge when (name, value) matches; empty values merge into the wrapper node.

#[derive(Debug, Clone, PartialEq)]
struct Element {
	text: String, // quote-stripped, escapes NOT applied (applied on string read)
	quoted: bool,
}

/// One whole-line comment held as trivia, plus whether a blank line preceded
/// it - so a blank between comment-only regions survives the round-trip
/// (blank runs collapse to one, same as nodes).
#[derive(Debug, Clone)]
struct Lead {
	text: String,
	blank_before: bool,
}

impl Lead {
	fn plain(text: String) -> Lead {
		Lead {
			text,
			blank_before: false,
		}
	}
}

/// A pending whole-line comment during parse: text, source indent (used only
/// to decide whether it hangs on a deeper block), and the blank it consumed.
struct Pend {
	text: String,
	indent: String,
	blank_before: bool,
}

#[derive(Debug, Clone, PartialEq)]
enum Value {
	Empty,
	Cell(Vec<Element>), // one element = scalar, more = inline array
	Raw {
		content: String,
		info: String,
		fence_char: u8,
		fence_len: usize,
	},
}

impl Value {
	/// Merge key: nodes with equal (name, key) collapse into one.
	fn key(&self) -> String {
		match self {
			Value::Empty => "e".to_string(),
			Value::Cell(els) => {
				// Length-prefix each element so the joined key is injective: a bare
				// NUL separator lets `[a, b]` collide with the single element
				// "a\0b" (NUL is legal in a quoted string), silently merging them.
				let mut k = String::from("c:");
				for e in els {
					k.push_str(&e.text.len().to_string());
					k.push(':');
					k.push_str(&e.text);
				}
				k
			}
			// Info-string is part of identity (a `sql` and a `python` block are
			// different values even with equal bodies); fence style is not. Info is
			// length-prefixed for the same injectivity reason as cell elements.
			Value::Raw { content, info, .. } => format!("r:{}:{}{}", info.len(), info, content),
		}
	}
	/// Human/display form; also what selectors match against (case-sensitive).
	fn display(&self) -> String {
		match self {
			Value::Empty => String::new(),
			Value::Cell(els) => els
				.iter()
				.map(|e| e.text.clone())
				.collect::<Vec<_>>()
				.join(", "),
			Value::Raw { content, .. } => content.clone(),
		}
	}
	fn is_empty(&self) -> bool {
		matches!(self, Value::Empty)
	}
}

#[derive(Debug)]
struct NodeData {
	name: String, // ASCII-folded to lower; non-ASCII never folds
	value: Value,
	children: Vec<usize>,
	parent: usize,
	line: usize,
	star_list: bool,  // value built from stacked "* " lines
	star_mixed: bool, // mix of "* " and field children already diagnosed
	// Comment trivia, verbatim from `#` to end of line. Never part of identity
	// or reads; merged instances concatenate leading, first trailing wins
	// (later ones demote to leading - a canonical line has room for one).
	leading: Vec<Lead>,
	trailing: String, // empty = none
	// Whole-line comments that followed this node's subtree at a deeper indent
	// than the next binding - they belong to this block, not the next node, so
	// a run trailing a block's last child stays put instead of re-attaching
	// dedented. Emitted after the subtree at this node's depth.
	after: Vec<Lead>,
	// Whole-line comments written inside this node's block when no bound child
	// could take them - a header whose children are all commented still owns
	// those lines. Emitted after the subtree one level deeper than this node.
	inside: Vec<Lead>,
	// Blank-line grouping is the other half of hand-authored layout: set when
	// a blank line preceded this node's binding line (runs collapse to one).
	blank_before: bool,
	// Verbatim value text from the source line (after the colon, comment
	// stripped, trimmed) - what a read's `raw` hands back. None when the value
	// was synthesized (writer, stacked list, fence), where raw falls back to
	// the display form.
	src: Option<String>,
}

/// A parsed SHCL document: the tree, its diagnostics, and its strictness level.
#[derive(Debug)]
pub struct Document {
	arena: Vec<NodeData>,
	diags: Vec<Diagnostic>,
	strictness: Strictness,
	orphans: Vec<Lead>, // top-level comments after the last binding line
}

const ROOT: usize = 0;

/// Merge a later instance into an earlier one under the in-file merge rule:
/// children and trivia move over, first trailing wins (a second demotes to a
/// leading line), first spelling stays. The caller drops the loser from the
/// parent's child list; it keeps its arena slot, unreferenced.
fn fold_node_into(arena: &mut [NodeData], survivor: usize, loser: usize) {
	let kids = std::mem::take(&mut arena[loser].children);
	for &k in &kids {
		arena[k].parent = survivor;
	}
	arena[survivor].children.extend(kids);
	let mut lead = std::mem::take(&mut arena[loser].leading);
	arena[survivor].leading.append(&mut lead);
	let trail = std::mem::take(&mut arena[loser].trailing);
	if !trail.is_empty() {
		if arena[survivor].trailing.is_empty() {
			arena[survivor].trailing = trail;
		} else {
			arena[survivor].leading.push(Lead::plain(trail));
		}
	}
	let mut after = std::mem::take(&mut arena[loser].after);
	arena[survivor].after.append(&mut after);
	let mut inside = std::mem::take(&mut arena[loser].inside);
	arena[survivor].inside.append(&mut inside);
}

/// Maximum nesting depth (levels below the document root), enforced at load
/// and by the Writer. Deeper lines are skipped with an `E016` error. The cap
/// is what keeps the recursive tree walks (emit, merge, clone) safely inside
/// every binding's stack, so a hostile or machine-generated document can make
/// a load fail but never crash the consumer.
pub const MAX_DEPTH: usize = 512;

// ---------------------------------------------------------------------------
// Lexical helpers
// ---------------------------------------------------------------------------

fn fold_name(s: &str) -> String {
	s.to_ascii_lowercase() // folds A-Z only; non-ASCII passes through untouched
}

fn is_bare_name_char(c: char) -> bool {
	c.is_ascii_alphanumeric() || c == '-' || c == '_'
}

/// Split off an unquoted trailing comment: (content, comment from `#` on).
/// A `\` shields the next char throughout. Comments are kept as trivia.
fn split_comment(s: &str) -> (&str, Option<&str>) {
	let mut in_quote: Option<char> = None;
	let mut it = s.char_indices();
	while let Some((byte, c)) = it.next() {
		if c == '\\' {
			it.next();
			continue;
		}
		match in_quote {
			Some(q) if c == q => in_quote = None,
			None if c == '"' || c == '\'' => in_quote = Some(c),
			None if c == '#' => return (&s[..byte], Some(&s[byte..])),
			_ => {}
		}
	}
	(s, None)
}

/// Split on unquoted commas; `\` shields the next char.
fn split_unquoted_commas(s: &str) -> Vec<&str> {
	let mut parts = Vec::new();
	let mut in_quote: Option<char> = None;
	let mut start = 0usize;
	let mut it = s.char_indices();
	while let Some((byte, c)) = it.next() {
		if c == '\\' {
			it.next();
			continue;
		}
		match in_quote {
			Some(q) if c == q => in_quote = None,
			None if c == '"' || c == '\'' => in_quote = Some(c),
			None if c == ',' => {
				parts.push(&s[start..byte]);
				start = byte + 1;
			}
			_ => {}
		}
	}
	parts.push(&s[start..]);
	parts
}

/// A dangling trailing backslash would swallow the separator after it on
/// re-emit; store the doubled spelling instead (identical on string read).
fn normalize_dangling_backslash(mut t: String) -> String {
	let run = t.chars().rev().take_while(|&c| c == '\\').count();
	if run % 2 == 1 {
		t.push('\\');
	}
	t
}

/// True when some piece starts with a quote that never closes (the closing
/// quote missing or escaped). Such a piece stays literal - and a quote-aware
/// comment strip has already swallowed any trailing `#` comment into it - so
/// the parser calls it out instead of letting the typo look deliberate.
/// Mid-text apostrophes (`it's fine`) are legal prose and stay silent.
fn unterminated_quote(text: &str) -> bool {
	for piece in split_unquoted_commas(text) {
		let chars: Vec<char> = piece.trim().chars().collect();
		let Some(&first) = chars.first() else {
			continue;
		};
		if first != '"' && first != '\'' {
			continue;
		}
		let closed = chars.len() >= 2 && chars[chars.len() - 1] == first && {
			let mut esc = false;
			for &c in &chars[1..chars.len() - 1] {
				esc = c == '\\' && !esc;
			}
			!esc
		};
		if !closed {
			return true;
		}
	}
	false
}

/// Trim, then strip one matching outer quote pair if present. Unquoted empty
/// slots return None (dropped, never an error).
fn parse_element(piece: &str) -> Option<Element> {
	let t = piece.trim();
	if t.is_empty() {
		return None;
	}
	let chars: Vec<char> = t.chars().collect();
	let first = chars[0];
	if (first == '"' || first == '\'') && chars.len() >= 2 && chars[chars.len() - 1] == first {
		// The closing quote must not itself be escaped (`"a\"` is not closed).
		let mut esc = false;
		for &c in &chars[1..chars.len() - 1] {
			esc = c == '\\' && !esc;
		}
		if !esc {
			let inner: String = chars[1..chars.len() - 1].iter().collect();
			return Some(Element {
				text: inner,
				quoted: true,
			});
		}
	}
	Some(Element {
		text: normalize_dangling_backslash(t.to_string()),
		quoted: false,
	})
}

fn parse_cell(text: &str) -> Value {
	let mut els = Vec::new();
	for piece in split_unquoted_commas(text) {
		if let Some(e) = parse_element(piece) {
			els.push(e);
		}
	}
	if els.is_empty() {
		Value::Empty
	} else {
		Value::Cell(els)
	}
}

/// Escape processing (string reads): \t \n \\ \" \'; unknown escapes stay literal.
fn apply_escapes(s: &str) -> String {
	let mut out = String::with_capacity(s.len());
	let mut it = s.chars();
	while let Some(c) = it.next() {
		if c != '\\' {
			out.push(c);
			continue;
		}
		match it.next() {
			Some('t') => out.push('\t'),
			Some('n') => out.push('\n'),
			Some('\\') => out.push('\\'),
			Some('"') => out.push('"'),
			Some('\'') => out.push('\''),
			Some(other) => {
				out.push('\\');
				out.push(other);
			}
			None => out.push('\\'),
		}
	}
	out
}

/// The predicate a `[value]` selector matches with: display form with escapes
/// applied on both sides, so `["q\"uote"]` finds `'q"uote'` - a logical-string
/// match, not spelling against spelling.
fn disp_key(v: &Value) -> String {
	apply_escapes(&v.display())
}

/// Opening fence: a run of >=3 backticks or tildes, then an optional info-string.
fn fence_open(rest: &str) -> Option<(u8, usize, String)> {
	let first = rest.as_bytes().first().copied()?;
	if first != b'`' && first != b'~' {
		return None;
	}
	let run = rest.bytes().take_while(|&b| b == first).count();
	if run < 3 {
		return None;
	}
	Some((first, run, rest[run..].trim().to_string()))
}

fn is_fence_close(line: &str, ch: u8, min_len: usize) -> bool {
	let t = line.trim();
	t.len() >= min_len && !t.is_empty() && t.bytes().all(|b| b == ch)
}

// ---------------------------------------------------------------------------
// Path scanner (shared by file lines and accessor queries)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Selector {
	ByValue(String),
	ByIndex(u64), // u64, not usize: index width must not vary with the target's pointer size
	Wildcard,
}

#[derive(Debug, Clone)]
struct Segment {
	name: String, // folded
	selector: Option<Selector>,
	star: bool, // bare `*` name wildcard; quoted "*" stays a literal name
}

struct PathScan {
	segments: Vec<Segment>,
	value_text: Option<String>, // text after the separator colon, trimmed
}

/// usize view of a selector index: None when it does not fit the target's
/// pointer width. An index that big can only mean "no such instance"; a bare
/// `as` cast would wrap into a live element on a 32-bit build.
fn index_usize(k: u64) -> Option<usize> {
	usize::try_from(k).ok()
}

/// Scan `a . b : [sel] . c : value`. Whitespace around dots/colons/brackets is
/// insignificant. A colon is a selector colon only when the next non-ws char is
/// `[`; otherwise it separates the value. Err(reason) means genuinely ambiguous
/// input, which the caller skips with a diagnostic.
fn scan_path(input: &str) -> Result<PathScan, String> {
	scan_path_ex(input, false)
}

/// Query spelling of scan_path: also accepts a bare `*` segment (the name
/// wildcard - any child name). Document lines never take it; only lookups
/// (reads, the writer probe, schema paths) do.
fn scan_lookup(input: &str) -> Result<PathScan, String> {
	scan_path_ex(input, true)
}

fn scan_path_ex(input: &str, stars: bool) -> Result<PathScan, String> {
	// Byte cursor with inline char decoding (a Vec<char> per call was a parse
	// hot spot). Every position the scanner stops on is a char boundary: it
	// only byte-matches ASCII structure chars, which UTF-8 guarantees cannot
	// appear inside a multibyte sequence, and otherwise advances by whole
	// chars. Backslash still shields the next CHAR, multibyte included.
	let bytes = input.as_bytes();
	let mut pos = 0usize;
	// First char at a known boundary; the fallback arm is unreachable (callers
	// check pos < len first) but keeps the decode total.
	fn char_at(s: &str, pos: usize) -> char {
		s[pos..].chars().next().unwrap_or('\u{0}')
	}
	fn skip_ws(bytes: &[u8], pos: &mut usize) {
		while *pos < bytes.len() && (bytes[*pos] == b' ' || bytes[*pos] == b'\t') {
			*pos += 1;
		}
	}
	fn read_quoted(s: &str, pos: &mut usize) -> Result<String, String> {
		let q = char::from(s.as_bytes()[*pos]); // caller checked: ASCII quote
		*pos += 1;
		let mut out = String::new();
		loop {
			if *pos >= s.len() {
				return Err("unterminated quote".into());
			}
			let c = char_at(s, *pos);
			if c == '\\' && *pos + 1 < s.len() {
				let next = char_at(s, *pos + 1);
				out.push(c);
				out.push(next);
				*pos += 1 + next.len_utf8();
				continue;
			}
			*pos += c.len_utf8();
			if c == q {
				return Ok(out);
			}
			out.push(c);
		}
	}
	let mut segments: Vec<Segment> = Vec::new();
	loop {
		skip_ws(bytes, &mut pos);
		if pos >= bytes.len() {
			return Err("empty path".into());
		}
		// Field name: quoted, bare, or (lookups only) the `*` name wildcard.
		let mut star = false;
		let name = if bytes[pos] == b'"' || bytes[pos] == b'\'' {
			read_quoted(input, &mut pos)?
		} else if stars && bytes[pos] == b'*' {
			pos += 1;
			star = true;
			"*".to_string()
		} else {
			let start = pos;
			// Bare-name chars are ASCII, so the byte-as-char view is exact
			// (bytes >= 0x80 map to chars the predicate rejects either way).
			while pos < bytes.len() && is_bare_name_char(char::from(bytes[pos])) {
				pos += 1;
			}
			if pos == start {
				return Err(format!(
					"expected field name, found '{}'",
					char_at(input, pos)
				));
			}
			input[start..pos].to_string()
		};
		let mut selector: Option<Selector> = None;
		skip_ws(bytes, &mut pos);
		// Optional selector, with its optional sugar colon (colon counts as
		// selector sugar only when the next non-ws char is an open bracket).
		let mut bracket_at: Option<usize> = None;
		if pos < bytes.len() && bytes[pos] == b'[' {
			bracket_at = Some(pos);
		} else if pos < bytes.len() && bytes[pos] == b':' {
			let mut q = pos + 1;
			skip_ws(bytes, &mut q);
			if q < bytes.len() && bytes[q] == b'[' {
				bracket_at = Some(q);
			}
		}
		if let Some(b) = bracket_at {
			pos = b + 1;
			skip_ws(bytes, &mut pos);
			if pos < bytes.len() && (bytes[pos] == b'"' || bytes[pos] == b'\'') {
				let v = read_quoted(input, &mut pos)?;
				selector = Some(Selector::ByValue(v)); // quotes force a value match, even numeric
			} else {
				let start = pos;
				while pos < bytes.len() && bytes[pos] != b']' {
					pos += 1;
				}
				let body: String = input[start..pos].trim().to_string();
				selector = Some(if body == "*" {
					Selector::Wildcard
				} else if let Some(n) = body.strip_prefix('#').and_then(|d| d.parse::<u64>().ok()) {
					Selector::ByIndex(n)
				} else if let Ok(n) = body.parse::<u64>() {
					Selector::ByIndex(n)
				} else if body.is_empty() {
					return Err("empty selector".into());
				} else {
					Selector::ByValue(normalize_dangling_backslash(body))
				});
			}
			skip_ws(bytes, &mut pos);
			if pos >= bytes.len() || bytes[pos] != b']' {
				return Err("unterminated selector".into());
			}
			pos += 1;
			skip_ws(bytes, &mut pos);
		}
		if star && selector.is_some() {
			return Err("selector on a name wildcard".into());
		}
		segments.push(Segment {
			name: fold_name(&name),
			selector,
			star,
		});
		if pos >= bytes.len() {
			return Ok(PathScan {
				segments,
				value_text: None,
			});
		}
		match bytes[pos] {
			b'.' => {
				pos += 1;
			}
			b':' => {
				pos += 1;
				return Ok(PathScan {
					segments,
					value_text: Some(input[pos..].trim().to_string()),
				});
			}
			_ => return Err(format!("unexpected '{}' after field", char_at(input, pos))),
		}
	}
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

struct Parser {
	arena: Vec<NodeData>,
	diags: Vec<Diagnostic>,
	// (indent string, node) for each open level; [0] is the virtual root.
	stack: Vec<(String, usize)>,
	// Per-node (name, value-key) -> first matching child, parallel to arena.
	// Pure lookup accelerator for select_or_create; children keeps the order.
	child_map: Vec<HashMap<(String, String), usize>>,
	// Per-node (name, display) -> first matching child: the `[value]` selector
	// accelerator (its predicate is display(), a different and non-injective
	// key from child_map's). Same first-wins discipline, same mutation sites.
	disp_map: Vec<HashMap<(String, String), usize>>,
	// Whole-line comments waiting for the next line that binds a node. The
	// source indent is kept only to decide after-attachment (a comment deeper
	// than the next binding hangs on the block it sits in).
	pending: Vec<Pend>,
	saw_blank: bool, // a blank line waits to become the next bound node's blank_before
	// An open stacked list defers its merge-key remap (rebuilding the key per
	// element is O(list^2) time); (node, key, display) at deferral start,
	// flushed before any map lookup and at end of parse.
	star_open: Option<(usize, String, String)>,
}

impl Parser {
	fn new() -> Parser {
		Parser {
			arena: vec![NodeData {
				name: String::new(),
				value: Value::Empty,
				children: Vec::new(),
				parent: 0,
				line: 0,
				star_list: false,
				star_mixed: false,
				leading: Vec::new(),
				trailing: String::new(),
				after: Vec::new(),
				inside: Vec::new(),
				blank_before: false,
				src: None,
			}],
			diags: Vec::new(),
			stack: vec![(String::new(), ROOT)],
			child_map: vec![HashMap::new()],
			disp_map: vec![HashMap::new()],
			pending: Vec::new(),
			saw_blank: false,
			star_open: None,
		}
	}

	fn err(&mut self, line: usize, msg: impl Into<String>) {
		let message = msg.into();
		let code = diag_code(&message);
		self.diags.push(Diagnostic {
			line,
			severity: Severity::Error,
			message,
			code,
		});
	}

	/// Find (or create by merge rule) the child of `parent` with this (name, value).
	fn select_or_create(&mut self, parent: usize, name: &str, value: Value, line: usize) -> usize {
		self.star_flush();
		let map_key = (name.to_string(), value.key());
		if let Some(&c) = self.child_map[parent].get(&map_key) {
			return c;
		}
		let idx = self.arena.len();
		self.arena.push(NodeData {
			name: name.to_string(),
			value,
			children: Vec::new(),
			parent,
			line,
			star_list: false,
			star_mixed: false,
			leading: Vec::new(),
			trailing: String::new(),
			after: Vec::new(),
			inside: Vec::new(),
			blank_before: false,
			src: None,
		});
		self.arena[parent].children.push(idx);
		self.child_map.push(HashMap::new());
		self.child_map[parent].insert(map_key, idx);
		self.disp_map.push(HashMap::new());
		let disp = (name.to_string(), disp_key(&self.arena[idx].value));
		self.disp_map[parent].entry(disp).or_insert(idx);
		idx
	}

	/// Apply an open stacked list's deferred remap. Runs before any map lookup
	/// (and at end of parse), so both maps are always fresh when queried.
	fn star_flush(&mut self) {
		if let Some((node, key, disp)) = self.star_open.take() {
			self.remap_child(node, key, disp);
		}
	}

	/// A node's value mutated in place (empty field filled, star element added):
	/// move its map entry from the old key to the new one. First-wins on both
	/// sides so lookups keep matching the earliest sibling, like the scan did.
	fn remap_child(&mut self, node: usize, old_key: String, old_disp: String) {
		let parent = self.arena[node].parent;
		let name = self.arena[node].name.clone();
		if self.child_map[parent].get(&(name.clone(), old_key.clone())) == Some(&node) {
			self.child_map[parent].remove(&(name.clone(), old_key));
		}
		let new_key = self.arena[node].value.key();
		self.child_map[parent]
			.entry((name.clone(), new_key))
			.or_insert(node);
		if self.disp_map[parent].get(&(name.clone(), old_disp.clone())) == Some(&node) {
			self.disp_map[parent].remove(&(name.clone(), old_disp));
		}
		let new_disp = disp_key(&self.arena[node].value);
		self.disp_map[parent]
			.entry((name, new_disp))
			.or_insert(node);
	}

	/// A value that mutates after its sibling group was keyed - an empty field
	/// filled by a fence, a stacked list closed - can land on a key an earlier
	/// sibling already holds, which the keyed lookup can no longer catch. Fold
	/// those pairs so the tree matches a reparse of its own canonical text.
	/// Depth-first, since folding can carry duplicates down a level.
	fn fold_late_dups(&mut self) {
		let mut stack = vec![ROOT];
		while let Some(parent) = stack.pop() {
			let kids = std::mem::take(&mut self.arena[parent].children);
			let mut first: HashMap<(String, String), usize> = HashMap::new();
			let mut keep: Vec<usize> = Vec::with_capacity(kids.len());
			for c in kids {
				let key = (self.arena[c].name.clone(), self.arena[c].value.key());
				match first.get(&key) {
					Some(&survivor) => fold_node_into(&mut self.arena, survivor, c),
					None => {
						first.insert(key, c);
						keep.push(c);
					}
				}
			}
			stack.extend(keep.iter().copied());
			self.arena[parent].children = keep;
		}
	}

	/// Hand pending leading comments (and this line's trailing one) to a node.
	/// First trailing wins; a later one demotes to leading so nothing is lost.
	fn attach_trivia(&mut self, node: usize, trailing: Option<&str>) {
		for p in self.pending.drain(..) {
			self.arena[node].leading.push(Lead {
				text: p.text,
				blank_before: p.blank_before,
			});
		}
		if let Some(t) = trailing {
			if self.arena[node].trailing.is_empty() {
				self.arena[node].trailing = t.to_string();
			} else {
				self.arena[node].leading.push(Lead::plain(t.to_string()));
			}
		}
	}

	/// Comments written deeper than the incoming line belong to the block they
	/// sit in, not to the next binding: hang each on the deepest node whose
	/// bound indent prefixes the comment's, among the levels the incoming
	/// line is closing. Written at that node's own level the comment trails
	/// it (`after`); written deeper it sits inside the node's block
	/// (`inside`) - so a header whose children are all commented still owns
	/// them at their depth. Runs before the incoming line resolves (and at
	/// end of parse with the empty indent, so tail comments keep their block).
	fn hang_deeper_pending(&mut self, new_indent: &str) {
		if self.pending.is_empty() {
			return;
		}
		let taken = std::mem::take(&mut self.pending);
		for p in taken {
			if p.indent.len() > new_indent.len() {
				// A level shallower than the incoming line stays open and may
				// still gain children, so a comment must not hang there - it
				// would emit below the child; keep it pending instead.
				let target = self
					.stack
					.iter()
					.rev()
					.find(|(ind, node)| {
						*node != ROOT
							&& ind.len() >= new_indent.len()
							&& p.indent.starts_with(ind.as_str())
					})
					.map(|(ind, n)| (*n, ind.len() == p.indent.len()));
				if let Some((n, at_own_level)) = target {
					let lead = Lead {
						text: p.text,
						blank_before: p.blank_before,
					};
					if at_own_level {
						self.arena[n].after.push(lead);
					} else {
						self.arena[n].inside.push(lead);
					}
					continue;
				}
			}
			self.pending.push(p);
		}
	}

	/// Resolve which open level this indent belongs to. Child only when the
	/// current top's indent is a proper prefix; otherwise the indent must equal
	/// an open level exactly (dedent), else it is a recoverable error.
	fn resolve_parent(&mut self, indent: &str) -> Option<usize> {
		let (top_indent, top_node) = match self.stack.last() {
			Some(t) => t.clone(),
			None => return None, // sentinel invariant; degrade, never abort
		};
		if indent.len() > top_indent.len() && indent.starts_with(&top_indent) {
			return Some(top_node);
		}
		for i in (0..self.stack.len()).rev() {
			if self.stack[i].0 == indent {
				// Sibling of stack[i]: its parent is the entry below it.
				let parent = if i == 0 { ROOT } else { self.stack[i - 1].1 };
				self.stack.truncate(i.max(1));
				// Keep the sentinel; a top-level line resolves to ROOT.
				if i == 0 {
					self.stack.truncate(1);
				}
				return Some(parent);
			}
		}
		None
	}

	/// Walk path segments under `parent`, select-or-creating; returns the node
	/// for the last segment carrying `value`. None aborts the line (diagnosed).
	fn attach_path(
		&mut self,
		parent: usize,
		segs: &[Segment],
		value: Value,
		line: usize,
	) -> Option<usize> {
		self.star_flush();
		// Field child under a stacked list: diagnose the mix once, keep the field.
		if self.arena[parent].star_list && !self.arena[parent].star_mixed {
			self.arena[parent].star_mixed = true;
			self.err(line, "field mixed with list elements");
		}
		// Nesting cap: parent depth plus the segments this line adds. Checked
		// before any node is created so a rejected line leaves nothing behind.
		let mut parent_depth = 0usize;
		let mut up = parent;
		while up != ROOT {
			parent_depth += 1;
			up = self.arena[up].parent;
		}
		if parent_depth + segs.len() > MAX_DEPTH {
			self.err(
				line,
				format!("nesting deeper than {} levels; line skipped", MAX_DEPTH),
			);
			return None;
		}
		let mut cur = parent;
		for (i, seg) in segs.iter().enumerate() {
			let is_last = i + 1 == segs.len();
			match (&seg.selector, is_last) {
				(Some(Selector::ByValue(v)), _) => {
					// Same escape-applied display predicate resolve_from uses, so
					// a selector also selects an array-valued instance instead of
					// creating a spurious second one - via the disp_map accelerator
					// (the inline spelling was quadratic in siblings without it).
					// Create only when nothing matches.
					let found = self.disp_map[cur]
						.get(&(seg.name.clone(), apply_escapes(v)))
						.copied();
					cur = match found {
						Some(c) => c,
						None => {
							let disc = Value::Cell(vec![Element {
								text: v.clone(),
								quoted: false,
							}]);
							self.select_or_create(cur, &seg.name, disc, line)
						}
					};
					if is_last && !value.is_empty() {
						// `a.b[X]: v` - the discriminator is the value; a second
						// value has nowhere unambiguous to go.
						self.err(
							line,
							format!("value after selector on '{}' ignored", seg.name),
						);
					}
				}
				(Some(Selector::ByIndex(n)), _) => {
					let matches: Vec<usize> = self.arena[cur]
						.children
						.iter()
						.copied()
						.filter(|&c| self.arena[c].name == seg.name)
						.collect();
					if let Some(&found) = index_usize(*n).and_then(|i| matches.get(i)) {
						cur = found;
					} else {
						self.err(line, format!("no instance {} of '{}'", n, seg.name));
						return None;
					}
				}
				(Some(Selector::Wildcard), _) => {
					self.err(line, "wildcard selector is query-only");
					return None;
				}
				(None, false) => {
					cur = self.select_or_create(cur, &seg.name, Value::Empty, line);
				}
				(None, true) => {
					let before = self.arena.len();
					cur = self.select_or_create(cur, &seg.name, value.clone(), line);
					// Two separately-written bindings just combined: legal (the
					// merge rule), but only the parser can see it happened, so
					// say so. Adjacent re-mentions (still the newest binding at
					// this scope) and selector/path-intermediate merges stay
					// silent - those are the deliberate redundant-path idiom.
					if cur < before
						&& self.arena[cur].line != line
						&& self.arena[self.arena[cur].parent].children.last() != Some(&cur)
					{
						let at = self.arena[cur].line;
						let name = seg.name.clone();
						self.diags.push(Diagnostic {
							line,
							severity: Severity::Hint,
							message: format!(
								"merged with '{}' at line {} (same name and value combine)",
								name, at
							),
							code: "H002",
						});
					}
				}
			}
		}
		Some(cur)
	}

	/// Consume raw-block content after an opening fence. Returns (value, next line
	/// index). Content keeps relative indentation; the common leading run is stripped.
	fn consume_raw(
		&mut self,
		lines: &[&str],
		mut i: usize,
		open_line: usize,
		ch: u8,
		len: usize,
		info: String,
	) -> (Value, usize) {
		let mut content: Vec<&str> = Vec::new();
		let mut closed = false;
		while i < lines.len() {
			if is_fence_close(lines[i], ch, len) {
				closed = true;
				i += 1;
				break;
			}
			content.push(lines[i]);
			i += 1;
		}
		if !closed {
			self.err(open_line, "unterminated raw block");
		}
		// Strip the common leading whitespace (the visual nesting); keep the rest.
		let mut common: Option<String> = None;
		for l in content.iter().filter(|l| !l.trim().is_empty()) {
			let lead: String = l.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
			common = Some(match common {
				None => lead,
				Some(prev) => {
					let mut p = String::new();
					for (a, b) in prev.chars().zip(lead.chars()) {
						if a == b {
							p.push(a);
						} else {
							break;
						}
					}
					p
				}
			});
		}
		let common = common.unwrap_or_default();
		let stripped: Vec<&str> = content
			.iter()
			.map(|l| {
				if l.trim().is_empty() {
					""
				} else {
					l.strip_prefix(&common).unwrap_or(l)
				}
			})
			.collect();
		(
			Value::Raw {
				content: stripped.join("\n"),
				info,
				fence_char: ch,
				fence_len: len,
			},
			i,
		)
	}

	/// A bare fence line is a value line for its parent field: fills an empty
	/// value, else creates a new instance of that field (the repeated-leaf rule).
	/// Returns the node the block landed on (None = no parent, diagnosed).
	fn bind_block(&mut self, parent: usize, value: Value, line: usize) -> Option<usize> {
		if parent == ROOT {
			self.err(line, "raw block with no parent field");
			return None;
		}
		if self.arena[parent].value.is_empty() {
			let old_key = self.arena[parent].value.key();
			let old_disp = disp_key(&self.arena[parent].value);
			self.arena[parent].value = value;
			self.remap_child(parent, old_key, old_disp);
			Some(parent)
		} else {
			let (name, grandparent) = (self.arena[parent].name.clone(), self.arena[parent].parent);
			Some(self.select_or_create(grandparent, &name, value, line))
		}
	}

	/// One stacked-list element (`* scalar`) appends to the parent's array.
	fn add_star_element(&mut self, parent: usize, body: &str, line: usize) {
		if parent == ROOT {
			self.err(line, "list element with no parent field");
			return;
		}
		// Uniform-or-nothing (spec): a mix with field children is not a block array.
		if !self.arena[parent].children.is_empty() {
			self.err(line, "list element mixed with field children; ignored");
			return;
		}
		let trimmed = body.trim();
		if trimmed.is_empty() {
			self.err(line, "empty list element");
			return;
		}
		// One scalar per line; a bare comma is an error, not a second element.
		if split_unquoted_commas(trimmed).len() > 1 {
			self.err(line, "bare comma in list element (one element per line)");
			return;
		}
		if unterminated_quote(trimmed) {
			self.err(line, "unterminated quote in value");
		}
		let el = match parse_element(trimmed) {
			Some(e) => e,
			None => {
				self.err(line, "empty list element");
				return;
			}
		};
		if self.arena[parent].value.is_empty() {
			let old_key = self.arena[parent].value.key();
			let old_disp = disp_key(&self.arena[parent].value);
			self.arena[parent].value = Value::Cell(vec![el]);
			self.arena[parent].star_list = true;
			// First element: remap now (Empty -> cell changes both keys), then
			// open the deferral window with the current keys. Rebuilding the
			// keys per appended element was O(list^2) time; the maps only need
			// to be fresh when queried, and every query flushes first.
			self.remap_child(parent, old_key, old_disp);
			let k = self.arena[parent].value.key();
			let d = disp_key(&self.arena[parent].value);
			self.star_open = Some((parent, k, d));
		} else if matches!(self.arena[parent].value, Value::Cell(_)) && self.arena[parent].star_list
		{
			if !matches!(self.star_open, Some((n, _, _)) if n == parent) {
				self.star_flush();
				let old_key = self.arena[parent].value.key();
				let old_disp = disp_key(&self.arena[parent].value);
				self.star_open = Some((parent, old_key, old_disp));
			}
			if let Value::Cell(els) = &mut self.arena[parent].value {
				els.push(el);
			}
		} else {
			self.err(line, "field already has a value; list element ignored");
		}
	}

	/// Legal input that looks like a common mistake: a field repeating as a bare
	/// scalar leaf. Mandatory hint per spec (never fails a load).
	fn emit_repeated_leaf_hints(&mut self) {
		let mut hints: Vec<(usize, String)> = Vec::new();
		for parent in 0..self.arena.len() {
			// Group by name in first-appearance order: hint order must be
			// deterministic or the cross-binding check can't compare `check` output.
			let mut group_of: HashMap<&str, usize> = HashMap::new();
			let mut by_name: Vec<(&str, Vec<usize>)> = Vec::new();
			for &c in &self.arena[parent].children {
				let name = self.arena[c].name.as_str();
				match group_of.get(name) {
					Some(&g) => by_name[g].1.push(c),
					None => {
						group_of.insert(name, by_name.len());
						by_name.push((name, vec![c]));
					}
				}
			}
			for (name, group) in by_name {
				if group.len() < 2 {
					continue;
				}
				let all_scalar_leaves = group.iter().all(|&c| {
					self.arena[c].children.is_empty()
						&& matches!(self.arena[c].value, Value::Cell(_))
						&& !self.arena[c].star_list
				});
				if all_scalar_leaves {
					let line = group.iter().map(|&c| self.arena[c].line).max().unwrap_or(0);
					let joined = group
						.iter()
						.map(|&c| self.arena[c].value.display())
						.collect::<Vec<_>>()
						.join(", ");
					hints.push((line, format!("{}{}'?", h001_head(name), joined)));
				}
			}
		}
		for (line, message) in hints {
			self.diags.push(Diagnostic {
				line,
				severity: Severity::Hint,
				message,
				code: "H001", // repeated bare leaf
			});
		}
	}

	fn parse(mut self, text: &str, strictness: Strictness) -> Document {
		// UTF-8 BOM strip, then split keeping raw lines (CR stripped per line).
		// Lines borrow `text`: they are only read, so no owned copies needed.
		let text = text.strip_prefix('\u{feff}').unwrap_or(text);
		let lines: Vec<&str> = text
			.split('\n')
			.map(|l| l.strip_suffix('\r').unwrap_or(l))
			.collect();
		let mut i = 0usize;
		while i < lines.len() {
			let lineno = i + 1;
			let line = lines[i].trim_end();
			// Indent chars are ASCII space/tab, so a byte scan slices the same run.
			let ilen = line
				.bytes()
				.take_while(|&b| b == b' ' || b == b'\t')
				.count();
			let indent = &line[..ilen];
			let rest = &line[ilen..];
			if rest.is_empty() {
				self.saw_blank = true;
				i += 1;
				continue;
			}
			// Whole-line comment: hold it for the next line that binds a node.
			// It consumes a pending blank into its own flag, so a blank between
			// comment-only regions survives the round-trip.
			if rest.starts_with('#') {
				self.pending.push(Pend {
					text: rest.to_string(),
					indent: indent.to_string(),
					blank_before: std::mem::take(&mut self.saw_blank),
				});
				i += 1;
				continue;
			}
			// Any other line consumes the pending blank; only a field line that
			// binds turns it into grouping.
			let had_blank = std::mem::take(&mut self.saw_blank);
			// A binding line claims the pending comments - but deeper-written
			// ones hang on their own block first.
			self.hang_deeper_pending(indent);
			// Child-indent fence: a value line for its parent field.
			if let Some((ch, len, info)) = fence_open(rest) {
				let parent = match self.resolve_parent(indent) {
					Some(p) => p,
					None => {
						self.err(lineno, "indentation matches no open level");
						i += 1;
						continue;
					}
				};
				let (value, next) = self.consume_raw(&lines, i + 1, lineno, ch, len, info);
				if let Some(node) = self.bind_block(parent, value, lineno) {
					self.attach_trivia(node, None);
				}
				i = next;
				continue;
			}
			// Stacked-list element: colon-less by construction ('*' can't begin a name).
			if let Some(after) = rest.strip_prefix('*') {
				if after.starts_with(' ') || after.starts_with('\t') {
					let parent = match self.resolve_parent(indent) {
						Some(p) => p,
						None => {
							self.err(lineno, "indentation matches no open level");
							i += 1;
							continue;
						}
					};
					let (body, comment) = split_comment(after);
					// Elements have no node of their own; trivia rides the field.
					if parent != ROOT {
						self.attach_trivia(parent, comment);
					}
					self.add_star_element(parent, body, lineno);
					i += 1;
					continue;
				}
				self.err(lineno, "malformed line: '*' must be followed by a space");
				i += 1;
				continue;
			}
			// Field line.
			let (before, comment) = split_comment(rest);
			let content = before.trim_end();
			if content.is_empty() {
				// Only a comment survived (e.g. an escaped lead-in); keep it.
				if let Some(c) = comment {
					self.pending.push(Pend {
						text: c.to_string(),
						indent: indent.to_string(),
						blank_before: had_blank,
					});
				}
				i += 1;
				continue;
			}
			let parent = match self.resolve_parent(indent) {
				Some(p) => p,
				None => {
					self.err(lineno, "indentation matches no open level");
					i += 1;
					continue;
				}
			};
			let scan = match scan_path(content) {
				Ok(s) => s,
				Err(reason) => {
					self.err(lineno, format!("malformed line skipped: {}", reason));
					i += 1;
					continue;
				}
			};
			let mut next = i + 1;
			// The verbatim value span, kept for reads' `raw` (only the plain
			// scalar/inline-array case has a one-line source spelling).
			let mut src_text: Option<String> = None;
			let value = match &scan.value_text {
				None => {
					// A clean path with no colon is the one defined repair:
					// the obvious intent is that path with an empty value.
					self.err(lineno, "missing colon; repaired as an empty value");
					Value::Empty
				}
				Some(v) if v.is_empty() => Value::Empty,
				Some(v) => {
					if let Some((ch, len, info)) = fence_open(v) {
						// Same-line fence spelling.
						let (val, n) = self.consume_raw(&lines, i + 1, lineno, ch, len, info);
						next = n;
						val
					} else {
						if unterminated_quote(v) {
							self.err(lineno, "unterminated quote in value");
						}
						src_text = Some(v.clone());
						parse_cell(v)
					}
				}
			};
			// Record only when the bound node holds exactly this line's value
			// (a merge into an equal-valued node keeps the first line's span;
			// a value dropped after a last-segment selector records nothing).
			let vkey = src_text.as_ref().map(|_| value.key());
			if let Some(node) = self.attach_path(parent, &scan.segments, value, lineno) {
				if let (Some(s), Some(k)) = (src_text, vkey)
					&& self.arena[node].src.is_none()
					&& self.arena[node].value.key() == k
				{
					self.arena[node].src = Some(s);
				}
				if had_blank {
					self.arena[node].blank_before = true;
				}
				self.attach_trivia(node, comment);
				self.stack.push((indent.to_string(), node));
			}
			i = next;
		}
		self.star_flush();
		self.fold_late_dups();
		self.emit_repeated_leaf_hints();
		// Indented tail comments keep their block; only top-level ones orphan.
		self.hang_deeper_pending("");
		let orphans = self
			.pending
			.drain(..)
			.map(|p| Lead {
				text: p.text,
				blank_before: p.blank_before,
			})
			.collect();
		Document {
			arena: self.arena,
			diags: self.diags,
			strictness,
			orphans,
		}
	}
}

// ---------------------------------------------------------------------------
// Document: load, diagnostics, formatter
// ---------------------------------------------------------------------------

impl Document {
	/// Parse at Standard strictness. Never fails: bad lines are skipped and
	/// diagnosed, good values stay readable.
	pub fn parse(text: &str) -> Document {
		Parser::new().parse(text, Strictness::Standard)
	}

	/// Parse at a chosen strictness. Only Strict can fail (any error diagnostic);
	/// the error still carries the parsed document alongside the diagnostics.
	pub fn parse_with(text: &str, strictness: Strictness) -> Result<Document, LoadError> {
		let doc = Parser::new().parse(text, strictness);
		if strictness == Strictness::Strict
			&& doc.diags.iter().any(|d| d.severity == Severity::Error)
		{
			return Err(LoadError {
				diagnostics: doc.diags.clone(),
				document: doc,
			});
		}
		Ok(doc)
	}

	pub fn diagnostics(&self) -> &[Diagnostic] {
		&self.diags
	}

	/// How many error-severity diagnostics the document carries - the "did
	/// this file have errors?" predicate, so recover-and-continue can't read
	/// as success by accident. Counts whatever diagnostics() holds (after
	/// load_and_validate, that includes validation errors).
	pub fn error_count(&self) -> usize {
		self.diags
			.iter()
			.filter(|d| d.severity == Severity::Error)
			.count()
	}

	/// One-shot load-and-validate: parse at a strictness, validate against a
	/// schema, and hand back the document carrying ONE combined diagnostics
	/// list (parse first, then validation - the order `check --schema`
	/// prints), so half the errors can't vanish because a caller forgot one
	/// of the two lists. Never fails: a strict-failing document comes back as
	/// the document plus its diagnostics (error_count() answers "did it
	/// fail"). An empty schema text skips validation entirely. H001 hints the
	/// schema disavows (a declared repeat upper bound above 1) are dropped.
	pub fn load_and_validate(text: &str, schema_text: &str, strictness: Strictness) -> Document {
		let mut doc = Parser::new().parse(text, strictness);
		if !schema_text.trim().is_empty() {
			let schema = Document::parse(schema_text);
			// A schema that did not load would silently drop the constraints on
			// its broken lines, or report every field as unknown - either way
			// blaming the document for the schema. Say so instead, as `check`
			// does, and validate nothing.
			if schema.diags.iter().any(|d| d.severity == Severity::Error) {
				doc.diags.push(Diagnostic {
					line: 0,
					severity: Severity::Error,
					code: "V099",
					message: "schema failed to load".to_string(),
				});
				return doc;
			}
			let vdiags = doc.validate(&schema);
			doc.diags.extend(vdiags);
			suppress_declared_repeats(&schema, &mut doc.diags);
		}
		doc
	}

	pub fn strictness(&self) -> Strictness {
		self.strictness
	}

	/// Canonical form: block layout, tabs, insertion order, minimal quoting,
	/// redundancy collapsed, comments re-emitted as attached trivia. Scalar
	/// text is never rewritten.
	pub fn to_canonical(&self) -> String {
		let mut out = String::new();
		self.emit_children(&self.arena[ROOT].children, 0, &mut out);
		// Comments that never found a following line re-emit at the end.
		for c in &self.orphans {
			if c.blank_before && !out.is_empty() {
				out.push('\n');
			}
			out.push_str(&c.text);
			out.push('\n');
		}
		out
	}

	/// Emit a sibling run. The parent walk already knows whether an earlier
	/// same-name sibling is empty (the raw same-line-fence hazard), so one
	/// seen-empties set here replaces a per-child rescan of the whole run.
	fn emit_children(&self, kids: &[usize], depth: usize, out: &mut String) {
		let mut empties: std::collections::HashSet<&str> = std::collections::HashSet::new();
		for &c in kids {
			let n = &self.arena[c];
			let wm = matches!(n.value, Value::Raw { .. }) && empties.contains(n.name.as_str());
			if n.value.is_empty() {
				empties.insert(n.name.as_str());
			}
			self.emit_node(c, depth, wm, out);
		}
	}

	fn emit_node(&self, idx: usize, depth: usize, would_merge: bool, out: &mut String) {
		let node = &self.arena[idx];
		let pad: String = "\t".repeat(depth);
		// Same-line fence spelling can't carry an inline comment (an unbalanced
		// quote in the info-string could hide the `#` on reparse), so its
		// trailing comment joins the leading lines instead; the flag comes from
		// the parent's walk. Each blank rides its own comment (or the binding
		// line), never as the first output line.
		for c in &node.leading {
			if c.blank_before && !out.is_empty() {
				out.push('\n');
			}
			out.push_str(&pad);
			out.push_str(&c.text);
			out.push('\n');
		}
		if node.blank_before && !out.is_empty() {
			out.push('\n');
		}
		if would_merge && !node.trailing.is_empty() {
			out.push_str(&pad);
			out.push_str(&node.trailing);
			out.push('\n');
		}
		out.push_str(&pad);
		out.push_str(&emit_name(&node.name));
		out.push(':');
		match &node.value {
			Value::Empty => {
				push_trailing(out, &node.trailing);
				out.push('\n');
			}
			Value::Cell(els) => {
				out.push(' ');
				let joined = els.iter().map(emit_element).collect::<Vec<_>>().join(", ");
				out.push_str(&joined);
				push_trailing(out, &node.trailing);
				out.push('\n');
			}
			Value::Raw {
				content,
				info,
				fence_char,
				fence_len,
			} => {
				// Child-indent spelling is canonical: bare name line, fenced
				// block one level deeper, verbatim content. Exception: if an
				// earlier same-name sibling is empty, the bare `name:` header
				// would merge into it on reparse and the fence would fill that
				// instance instead - so use the same-line spelling there.
				if would_merge {
					out.push(' ');
				} else {
					push_trailing(out, &node.trailing);
					out.push('\n');
				}
				let pad: String = "\t".repeat(depth + 1); // block body pad, one deeper
				let fence: String = std::iter::repeat_n(*fence_char as char, *fence_len).collect();
				if !would_merge {
					out.push_str(&pad);
				}
				out.push_str(&fence);
				if !info.is_empty() {
					// An info-string starting with the fence char would extend
					// the run on reparse; a space keeps the fence length intact.
					if info.as_bytes()[0] == *fence_char {
						out.push(' ');
					}
					out.push_str(info);
				}
				out.push('\n');
				if !content.is_empty() {
					for l in content.split('\n') {
						if !l.is_empty() {
							out.push_str(&pad);
						}
						out.push_str(l);
						out.push('\n');
					}
				}
				out.push_str(&pad);
				out.push_str(&fence);
				out.push('\n');
			}
		}
		self.emit_children(&self.arena[idx].children, depth + 1, out);
		// Comments this block owns with no child to carry them, one deeper.
		let ipad: String = "\t".repeat(depth + 1);
		for c in &self.arena[idx].inside {
			if c.blank_before && !out.is_empty() {
				out.push('\n');
			}
			out.push_str(&ipad);
			out.push_str(&c.text);
			out.push('\n');
		}
		// Comments that hung on this block after its last child.
		for c in &self.arena[idx].after {
			if c.blank_before && !out.is_empty() {
				out.push('\n');
			}
			out.push_str(&pad);
			out.push_str(&c.text);
			out.push('\n');
		}
	}
}

/// Inline comment, canonically two spaces before the `#`.
fn push_trailing(out: &mut String, trailing: &str) {
	if !trailing.is_empty() {
		out.push_str("  ");
		out.push_str(trailing);
	}
}

fn emit_name(name: &str) -> String {
	if !name.is_empty() && name.chars().all(is_bare_name_char) {
		name.to_string()
	} else {
		quote_text(name)
	}
}

/// Quote one path segment so it can be spliced into a lookup path: a bare name
/// passes through, anything else comes back quoted and escaped in the form the
/// path scanner accepts. Splicing user-typed text into a path without this is
/// path injection - a dotted name silently reads as nesting. Same spelling
/// `paths()` and the canonical emitter produce.
pub fn quote_segment(name: &str) -> String {
	emit_name(name)
}

/// The single H001 wording site: the hint builder and the schema suppressor
/// both come here, so the suppressor matches the exact head the builder
/// emitted - never a re-parse of free prose. (The leaf name cannot ride on
/// Diagnostic itself: consumers build Diagnostic literals, so its field set
/// is frozen.)
fn h001_head(name: &str) -> String {
	format!(
		"'{}' repeats as a bare leaf - did you mean '{}: ",
		name, name
	)
}

/// Drop the H001 hints a schema disavows: a field whose declared repeat upper
/// bound is above 1 repeats BY DESIGN (repetition is its instance mechanism),
/// so the repeated-bare-leaf hint is structurally a false positive there and
/// trains users to ignore hints. Matching is by leaf name - the filter
/// consumers were hand-rolling - which errs toward quiet, for a hint. Used by
/// `check --schema` and load_and_validate; call it wherever doc diagnostics
/// and a schema meet.
pub fn suppress_declared_repeats(schema: &Document, diags: &mut Vec<Diagnostic>) {
	// Top-level fields plus every fragment's fields: a repeat declared inside
	// a mounted shape disavows the hint the same way.
	let mut groups: Vec<(String, Vec<String>)> =
		vec![("field".to_string(), schema.instances("field"))];
	for k in 0..schema.count("fragment") {
		let base = format!("fragment[#{}].field", k);
		let paths = schema.instances(&base);
		groups.push((base, paths));
	}
	let mut names: Vec<String> = Vec::new();
	for (base, paths) in &groups {
		for (i, p) in paths.iter().enumerate() {
			// repeat is a 1-2 element array (`repeat: lo[, hi]`); the bound
			// that matters here is the last one.
			let rep = schema.read_int_array(&format!("{}[#{}].repeat", base, i));
			if rep.status != Status::Good {
				continue;
			}
			match rep.value.last() {
				Some(&u) if u > 1 => {}
				_ => continue,
			}
			// Leaf name from the parsed path, not a re-split of its text: a
			// quoted last segment may contain dots (`a."b.c"`). The scanner
			// folds the name; the doc side stores names folded too.
			let Ok(scan) = scan_lookup(p) else {
				continue;
			};
			let Some(seg) = scan.segments.last() else {
				continue;
			};
			if seg.star {
				continue; // name wildcard: no single leaf name to disavow
			}
			names.push(seg.name.clone());
		}
	}
	if names.is_empty() {
		return;
	}
	let heads: Vec<String> = names.iter().map(|n| h001_head(n)).collect();
	diags.retain(|d| d.code != "H001" || !heads.iter().any(|h| d.message.starts_with(h.as_str())));
}

/// Minimal quoting: bare unless a reserved character (or lookalike hazard) forces it.
fn emit_element(e: &Element) -> String {
	let t = &e.text;
	let needs = t.is_empty()
		|| t.chars()
			.any(|c| matches!(c, ' ' | '\t' | ',' | ':' | '#' | '"' | '\'' | '[' | ']'))
		|| fence_open(t).is_some();
	if needs { quote_text(t) } else { t.clone() }
}

/// Quote chars that are NOT already escaped in the raw text; escaped ones must
/// stay untouched or every round-trip would re-escape them.
fn bare_quote_counts(t: &str) -> (usize, usize) {
	let (mut dq, mut sq) = (0usize, 0usize);
	let mut it = t.chars();
	while let Some(c) = it.next() {
		match c {
			'\\' => {
				it.next();
			}
			'"' => dq += 1,
			'\'' => sq += 1,
			_ => {}
		}
	}
	(dq, sq)
}

fn quote_text(t: &str) -> String {
	// A dangling trailing backslash would turn the closing quote into an
	// escape pair - the scanner reads the path back wrong, or not at all.
	// Store the doubled spelling (identical on string read), the same rule
	// the element parser applies to bare text.
	let normalized;
	let t = if t.ends_with('\\') {
		normalized = normalize_dangling_backslash(t.to_string());
		normalized.as_str()
	} else {
		t
	};
	let (dq, sq) = bare_quote_counts(t);
	if dq == 0 {
		format!("\"{}\"", t)
	} else if sq == 0 {
		format!("'{}'", t)
	} else {
		// Both quote kinds appear bare: escape the doubles, wrap in doubles.
		let mut out = String::from("\"");
		let mut it = t.chars();
		while let Some(c) = it.next() {
			match c {
				'\\' => {
					out.push(c);
					if let Some(n) = it.next() {
						out.push(n);
					}
				}
				'"' => out.push_str("\\\""),
				_ => out.push(c),
			}
		}
		out.push('"');
		out
	}
}

// ---------------------------------------------------------------------------
// Accessor: path resolution
// ---------------------------------------------------------------------------

enum Resolved {
	None,
	One(usize),
	Many(Vec<usize>),
	// Wildcard: one slot per instance, in file order; Err = why the sub-path
	// did not land on one node (NotFound missing, Multiple ambiguous).
	Slots(Vec<Result<usize, Status>>),
}

impl Document {
	fn children_named(&self, parent: usize, name: &str) -> Vec<usize> {
		self.arena[parent]
			.children
			.iter()
			.copied()
			.filter(|&c| self.arena[c].name == name)
			.collect()
	}

	fn resolve_from(&self, start: &[usize], segs: &[Segment]) -> Resolved {
		let mut cur: Vec<usize> = start.to_vec();
		for (i, seg) in segs.iter().enumerate() {
			let mut next: Vec<usize> = Vec::new();
			for &n in &cur {
				if seg.star {
					next.extend(self.arena[n].children.iter().copied());
				} else {
					next.extend(self.children_named(n, &seg.name));
				}
			}
			if seg.star {
				// Name wildcard: same per-slot split as `[*]`, over every child.
				let rest = &segs[i + 1..];
				let mut slots: Vec<Result<usize, Status>> = Vec::new();
				for inst in next {
					if rest.is_empty() {
						slots.push(Ok(inst));
					} else {
						match self.resolve_from(&[inst], rest) {
							Resolved::One(x) => slots.push(Ok(x)),
							Resolved::None => slots.push(Err(Status::NotFound)),
							_ => slots.push(Err(Status::Multiple)),
						}
					}
				}
				return Resolved::Slots(slots);
			}
			match &seg.selector {
				None => cur = next,
				Some(Selector::ByValue(v)) => {
					let want = apply_escapes(v);
					cur = next
						.into_iter()
						.filter(|&c| disp_key(&self.arena[c].value) == want)
						.collect();
				}
				Some(Selector::ByIndex(k)) => {
					cur = index_usize(*k)
						.and_then(|i| next.get(i))
						.map(|&c| vec![c])
						.unwrap_or_default();
				}
				Some(Selector::Wildcard) => {
					// Remaining path resolves per-instance; slots stay aligned.
					let rest = &segs[i + 1..];
					let mut slots: Vec<Result<usize, Status>> = Vec::new();
					for inst in next {
						if rest.is_empty() {
							slots.push(Ok(inst));
						} else {
							match self.resolve_from(&[inst], rest) {
								Resolved::One(x) => slots.push(Ok(x)),
								Resolved::None => slots.push(Err(Status::NotFound)),
								_ => slots.push(Err(Status::Multiple)),
							}
						}
					}
					return Resolved::Slots(slots);
				}
			}
		}
		match cur.len() {
			0 => Resolved::None,
			1 => Resolved::One(cur[0]),
			_ => Resolved::Many(cur),
		}
	}

	fn resolve(&self, path: &str) -> Result<Resolved, Status> {
		let scan = scan_lookup(path).map_err(|_| Status::NotFound)?;
		if scan.value_text.is_some() {
			return Err(Status::NotFound); // a query has no value part
		}
		Ok(self.resolve_from(&[ROOT], &scan.segments))
	}

	/// Instance count at a path (0 when nothing matches).
	pub fn count(&self, path: &str) -> usize {
		match self.resolve(path) {
			Ok(Resolved::None) | Err(_) => 0,
			Ok(Resolved::One(_)) => 1,
			Ok(Resolved::Many(v)) => v.len(),
			Ok(Resolved::Slots(s)) => s.len(),
		}
	}

	/// Every field path in the document, in file order, deduplicated - a query
	/// recipe for tooling (the differential harness derives reads over the fuzz
	/// set from it). A segment that is not bare-name-safe is emitted quoted and
	/// escaped - the form the path scanner accepts - so each path is a
	/// well-formed lookup path and nothing in the document is hidden.
	pub fn paths(&self) -> Vec<String> {
		let mut out = Vec::new();
		let mut seen = std::collections::HashSet::new();
		let mut stack: Vec<(usize, String)> = self.arena[ROOT]
			.children
			.iter()
			.rev()
			.map(|&c| (c, String::new()))
			.collect();
		while let Some((node, prefix)) = stack.pop() {
			let seg = emit_name(&self.arena[node].name);
			let path = if prefix.is_empty() {
				seg
			} else {
				format!("{}.{}", prefix, seg)
			};
			if seen.insert(path.clone()) {
				out.push(path.clone());
			}
			for &c in self.arena[node].children.iter().rev() {
				stack.push((c, path.clone()));
			}
		}
		out
	}

	/// 1-based source line of the binding at a path, for consumer checks the
	/// schema cannot express. 0 when the path does not resolve to exactly one
	/// node, or the node was writer-built. Merged instances cite the first
	/// binding's line, matching diagnostics.
	pub fn line(&self, path: &str) -> usize {
		match self.resolve(path) {
			Ok(Resolved::One(n)) => self.arena[n].line,
			_ => 0,
		}
	}

	/// The plural line(): 1-based source lines at a path, in file order, so a
	/// repeated field - the case that most wants a citable line - yields every
	/// binding's. Wildcard slots that did not resolve stay in the list as 0,
	/// and a writer-built node is 0, so indices keep matching count().
	pub fn lines(&self, path: &str) -> Vec<usize> {
		match self.resolve(path) {
			Ok(Resolved::One(n)) => vec![self.arena[n].line],
			Ok(Resolved::Many(v)) => v.iter().map(|&n| self.arena[n].line).collect(),
			Ok(Resolved::Slots(s)) => s
				.into_iter()
				.map(|r| match r {
					Ok(n) => self.arena[n].line,
					Err(_) => 0,
				})
				.collect(),
			_ => Vec::new(),
		}
	}

	/// Child field names under a path, in file order, duplicates included -
	/// the "what keys are in this section?" question paths() (deduplicated,
	/// path-shaped) cannot answer. "" enumerates the top level. Names come
	/// back as stored; quote_segment() makes one splice-safe in a path.
	pub fn children(&self, path: &str) -> Vec<String> {
		let node = if path.trim().is_empty() {
			ROOT
		} else {
			match self.resolve(path) {
				Ok(Resolved::One(n)) => n,
				_ => return Vec::new(),
			}
		};
		self.arena[node]
			.children
			.iter()
			.map(|&c| self.arena[c].name.clone())
			.collect()
	}

	/// Instance values at a path, in file order. Wildcard slots that did not
	/// resolve stay in the list as "" so indices keep matching count().
	pub fn instances(&self, path: &str) -> Vec<String> {
		match self.resolve(path) {
			Ok(Resolved::One(n)) => vec![self.arena[n].value.display()],
			Ok(Resolved::Many(v)) => v.iter().map(|&n| self.arena[n].value.display()).collect(),
			Ok(Resolved::Slots(s)) => s
				.into_iter()
				.map(|r| match r {
					Ok(n) => self.arena[n].value.display(),
					Err(_) => String::new(),
				})
				.collect(),
			_ => Vec::new(),
		}
	}
}

// ---------------------------------------------------------------------------
// Writer: typed emit, defaults, comments, structural edits
// ---------------------------------------------------------------------------
// The reverse of the Accessor. A setter builds the canonical stored text for a
// typed value (the inverse of the matching read) and places it at a path,
// creating intermediate nodes on the way. Reads and to_canonical walk children
// vecs, so mutating the arena directly is enough - the parser's child_map is
// already gone and is not maintained here.

/// Read text as the value half of a line, for the setters that take value
/// syntax rather than data. Rejects what could not have come off one line: a
/// line break, or a quote that never closes. An unquoted `#` ends the value
/// here exactly as it would in a file.
fn literal_value(text: &str) -> Option<Value> {
	if text.contains('\n') || text.contains('\r') {
		return None;
	}
	let (v, _) = split_comment(text);
	let v = v.trim();
	if unterminated_quote(v) {
		return None;
	}
	Some(parse_cell(v))
}

fn cell_of(text: String) -> Value {
	Value::Cell(vec![Element {
		text,
		quoted: false,
	}])
}

/// Encode a logical string into stored element text so a scalar read
/// (apply_escapes) hands it back verbatim and an emit/reparse round-trips. Only
/// backslash, newline, and tab need encoding; emit_element wraps quote/reserved
/// chars itself, and reparse strips that wrapping.
fn encode_string(s: &str) -> String {
	let mut out = String::with_capacity(s.len());
	for c in s.chars() {
		match c {
			'\\' => out.push_str("\\\\"),
			'\n' => out.push_str("\\n"),
			'\t' => out.push_str("\\t"),
			_ => out.push(c),
		}
	}
	out
}

/// Pick a backtick fence long enough that no content line closes it early.
fn choose_fence(content: &str) -> (u8, usize) {
	let mut maxrun = 0usize;
	for line in content.split('\n') {
		let t = line.trim();
		if !t.is_empty() && t.bytes().all(|b| b == b'`') {
			maxrun = maxrun.max(t.len());
		}
	}
	(b'`', (maxrun + 1).max(3))
}

/// Inline-array value; the empty array is an empty value (reads back Empty).
fn array_cell(texts: Vec<String>) -> Value {
	if texts.is_empty() {
		Value::Empty
	} else {
		Value::Cell(
			texts
				.into_iter()
				.map(|text| Element {
					text,
					quoted: false,
				})
				.collect(),
		)
	}
}

impl Document {
	/// A fresh document with no bindings - the start point for schema-driven
	/// generation. Loads at Standard; set values, then to_canonical().
	pub fn new() -> Document {
		Document::parse("")
	}

	fn new_child(&mut self, parent: usize, name: &str, value: Value) -> usize {
		let idx = self.arena.len();
		self.arena.push(NodeData {
			name: name.to_string(),
			value,
			children: Vec::new(),
			parent,
			line: 0,
			star_list: false,
			star_mixed: false,
			leading: Vec::new(),
			trailing: String::new(),
			after: Vec::new(),
			inside: Vec::new(),
			// Hand-written files separate top-level sections with a blank line;
			// writer-built ones do the same (the emitter never blanks line 1).
			blank_before: parent == ROOT,
			src: None,
		});
		self.arena[parent].children.push(idx);
		idx
	}

	fn child_or_create(&mut self, parent: usize, name: &str) -> usize {
		match self.arena[parent]
			.children
			.iter()
			.copied()
			.find(|&c| self.arena[c].name == name)
		{
			Some(c) => c,
			None => self.new_child(parent, name, Value::Empty),
		}
	}

	/// Why a write at this path would fail - the reason behind a setter's bare
	/// `false`, so a consumer's error message need not guess. `Writable` means
	/// the same validation `place()` runs would pass; nothing is created.
	pub fn write_reason(&self, path: &str) -> WriteReason {
		let scan = match scan_lookup(path) {
			Ok(s) => s,
			Err(_) => return WriteReason::BadPath,
		};
		if scan.value_text.is_some() {
			return WriteReason::ValueInPath;
		}
		if scan.segments.is_empty() {
			return WriteReason::BadPath;
		}
		// Writer side of the load-time nesting cap: never create deeper.
		if scan.segments.len() > MAX_DEPTH {
			return WriteReason::TooDeep;
		}
		// The probe walk place() validates with: once it falls off the existing
		// tree, a later `[#k]` can never match (fresh intermediates are created
		// childless), so an index segment past that point is unresolvable.
		let mut probe = Some(ROOT);
		for seg in &scan.segments {
			if seg.star {
				return WriteReason::Wildcard;
			}
			match &seg.selector {
				Some(Selector::Wildcard) => return WriteReason::Wildcard,
				Some(Selector::ByIndex(k)) => {
					let Some(c) = probe else {
						return WriteReason::NoSuchIndex;
					};
					let matches: Vec<usize> = self.arena[c]
						.children
						.iter()
						.copied()
						.filter(|&n| self.arena[n].name == seg.name)
						.collect();
					match index_usize(*k).and_then(|i| matches.get(i)) {
						Some(&m) => probe = Some(m),
						None => return WriteReason::NoSuchIndex,
					}
				}
				Some(Selector::ByValue(v)) => {
					let want = apply_escapes(v);
					probe = probe.and_then(|c| {
						self.arena[c].children.iter().copied().find(|&n| {
							self.arena[n].name == seg.name && disp_key(&self.arena[n].value) == want
						})
					});
				}
				None => {
					probe = probe.and_then(|c| {
						self.arena[c]
							.children
							.iter()
							.copied()
							.find(|&n| self.arena[n].name == seg.name)
					});
				}
			}
		}
		WriteReason::Writable
	}

	/// Walk (creating as needed) to the node a write targets. A trailing name
	/// with no selector hits the first same-named instance (or a new one); a
	/// `[value]` selector selects the matching instance or creates it; `[#k]`
	/// must already exist. None = path unusable for a write (write_reason()
	/// says why). Validation runs first, so a doomed path leaves no
	/// half-created intermediates behind.
	fn place(&mut self, path: &str) -> Option<usize> {
		if self.write_reason(path) != WriteReason::Writable {
			return None;
		}
		let scan = scan_lookup(path).ok()?;
		let mut cur = ROOT;
		for seg in &scan.segments {
			if seg.star {
				return None; // write_reason gates this; belt only
			}
			cur = match &seg.selector {
				None => self.child_or_create(cur, &seg.name),
				Some(Selector::ByValue(v)) => {
					let want = apply_escapes(v);
					let found = self.arena[cur].children.iter().copied().find(|&c| {
						self.arena[c].name == seg.name && disp_key(&self.arena[c].value) == want
					});
					match found {
						Some(c) => c,
						None => self.new_child(cur, &seg.name, cell_of(v.clone())),
					}
				}
				Some(Selector::ByIndex(k)) => {
					let matches: Vec<usize> = self.arena[cur]
						.children
						.iter()
						.copied()
						.filter(|&c| self.arena[c].name == seg.name)
						.collect();
					*index_usize(*k).and_then(|i| matches.get(i))?
				}
				Some(Selector::Wildcard) => return None,
			};
		}
		Some(cur)
	}

	fn set_value(&mut self, path: &str, value: Value) -> bool {
		match self.place(path) {
			Some(node) => {
				self.arena[node].value = value;
				self.arena[node].src = None; // written value has no source spelling
				self.collapse_dup(node);
				true
			}
			None => false,
		}
	}

	/// A written value may now collide with a same-named sibling under the
	/// in-file merge rule; fold the pair the way a reparse would (earlier
	/// sibling survives, later one folds children and trivia in) so Writer
	/// output stays a formatter fixpoint.
	fn collapse_dup(&mut self, node: usize) {
		let parent = self.arena[node].parent;
		let name = self.arena[node].name.clone();
		let key = self.arena[node].value.key();
		let siblings = &self.arena[parent].children;
		let Some(other) = siblings
			.iter()
			.copied()
			.find(|&c| c != node && self.arena[c].name == name && self.arena[c].value.key() == key)
		else {
			return;
		};
		let pos = |n: usize| {
			self.arena[parent]
				.children
				.iter()
				.position(|&c| c == n)
				.unwrap_or(usize::MAX)
		};
		let (survivor, loser) = if pos(other) < pos(node) {
			(other, node)
		} else {
			(node, other)
		};
		fold_node_into(&mut self.arena, survivor, loser);
		self.arena[parent].children.retain(|&c| c != loser);
	}

	/// True when the path resolves to at least one real node.
	pub fn exists(&self, path: &str) -> bool {
		match self.resolve(path) {
			Ok(Resolved::One(_)) | Ok(Resolved::Many(_)) => true,
			Ok(Resolved::Slots(s)) => s.iter().any(|r| r.is_ok()),
			_ => false,
		}
	}

	/// Delete the node(s) at a path (with their subtrees); returns how many.
	pub fn remove(&mut self, path: &str) -> usize {
		let targets: Vec<usize> = match self.resolve(path) {
			Ok(Resolved::One(n)) => vec![n],
			Ok(Resolved::Many(v)) => v,
			Ok(Resolved::Slots(s)) => s.into_iter().filter_map(|r| r.ok()).collect(),
			_ => Vec::new(),
		};
		for &t in &targets {
			let p = self.arena[t].parent;
			self.arena[p].children.retain(|&c| c != t);
		}
		targets.len()
	}

	/// Attach a leading comment line to the node at a path (creating an empty
	/// node if it does not exist yet, so a section can be annotated). A missing
	/// `#` is added; only the first line is kept (a comment is one line).
	pub fn set_comment(&mut self, path: &str, text: &str) -> bool {
		match self.place(path) {
			Some(node) => {
				let line = text.split('\n').next().unwrap_or("");
				let c = if line.starts_with('#') {
					line.to_string()
				} else {
					format!("# {}", line)
				};
				self.arena[node].leading.push(Lead::plain(c));
				true
			}
			None => false,
		}
	}

	pub fn set_int(&mut self, path: &str, v: i64) -> bool {
		self.set_value(path, cell_of(v.to_string()))
	}
	pub fn set_float(&mut self, path: &str, v: f64) -> bool {
		self.set_value(path, cell_of(format!("{}", v)))
	}
	pub fn set_bool(&mut self, path: &str, v: bool) -> bool {
		self.set_value(path, cell_of(if v { "true" } else { "false" }.to_string()))
	}
	pub fn set_string(&mut self, path: &str, v: &str) -> bool {
		self.set_value(path, cell_of(encode_string(v)))
	}
	pub fn set_datetime(&mut self, path: &str, v: &ShclDateTime) -> bool {
		self.set_value(path, cell_of(v.to_string()))
	}
	pub fn set_raw(&mut self, path: &str, content: &str, info: &str) -> bool {
		let (fence_char, fence_len) = choose_fence(content);
		self.set_value(
			path,
			Value::Raw {
				content: content.to_string(),
				info: info.to_string(),
				fence_char,
				fence_len,
			},
		)
	}
	pub fn set_empty(&mut self, path: &str) -> bool {
		self.set_value(path, Value::Empty)
	}

	pub fn set_int_array(&mut self, path: &str, v: &[i64]) -> bool {
		self.set_value(path, array_cell(v.iter().map(|x| x.to_string()).collect()))
	}
	pub fn set_float_array(&mut self, path: &str, v: &[f64]) -> bool {
		self.set_value(
			path,
			array_cell(v.iter().map(|x| format!("{}", x)).collect()),
		)
	}
	pub fn set_bool_array(&mut self, path: &str, v: &[bool]) -> bool {
		self.set_value(
			path,
			array_cell(
				v.iter()
					.map(|x| if *x { "true" } else { "false" }.to_string())
					.collect(),
			),
		)
	}
	pub fn set_string_array(&mut self, path: &str, v: &[&str]) -> bool {
		self.set_value(
			path,
			array_cell(v.iter().map(|x| encode_string(x)).collect()),
		)
	}
	pub fn set_datetime_array(&mut self, path: &str, v: &[ShclDateTime]) -> bool {
		self.set_value(path, array_cell(v.iter().map(|x| x.to_string()).collect()))
	}

	// Default (only-if-absent) forms - the "emit defaults" half of the Writer.
	pub fn set_int_default(&mut self, path: &str, v: i64) -> bool {
		if !self.exists(path) {
			return self.set_int(path, v);
		}
		true
	}
	pub fn set_float_default(&mut self, path: &str, v: f64) -> bool {
		if !self.exists(path) {
			return self.set_float(path, v);
		}
		true
	}
	pub fn set_bool_default(&mut self, path: &str, v: bool) -> bool {
		if !self.exists(path) {
			return self.set_bool(path, v);
		}
		true
	}
	pub fn set_string_default(&mut self, path: &str, v: &str) -> bool {
		if !self.exists(path) {
			return self.set_string(path, v);
		}
		true
	}
	/// Write TEXT as value syntax rather than as data: `80, 443` becomes a
	/// two-element array where `set_string` would store one string that has to
	/// be quoted. This is how a caller holding value text - a config line, a
	/// user's `--set` argument - writes it without knowing its shape first.
	/// Fails on text that could not be one line's value (see `literal_value`).
	pub fn set_literal(&mut self, path: &str, text: &str) -> bool {
		match literal_value(text) {
			Some(v) => self.set_value(path, v),
			None => false,
		}
	}
	pub fn set_literal_default(&mut self, path: &str, text: &str) -> bool {
		if !self.exists(path) {
			return self.set_literal(path, text);
		}
		true
	}
	pub fn set_datetime_default(&mut self, path: &str, v: &ShclDateTime) -> bool {
		if !self.exists(path) {
			return self.set_datetime(path, v);
		}
		true
	}
	pub fn set_raw_default(&mut self, path: &str, content: &str, info: &str) -> bool {
		if !self.exists(path) {
			return self.set_raw(path, content, info);
		}
		true
	}
	pub fn set_int_array_default(&mut self, path: &str, v: &[i64]) -> bool {
		if !self.exists(path) {
			return self.set_int_array(path, v);
		}
		true
	}
	pub fn set_float_array_default(&mut self, path: &str, v: &[f64]) -> bool {
		if !self.exists(path) {
			return self.set_float_array(path, v);
		}
		true
	}
	pub fn set_bool_array_default(&mut self, path: &str, v: &[bool]) -> bool {
		if !self.exists(path) {
			return self.set_bool_array(path, v);
		}
		true
	}
	pub fn set_string_array_default(&mut self, path: &str, v: &[&str]) -> bool {
		if !self.exists(path) {
			return self.set_string_array(path, v);
		}
		true
	}
	pub fn set_datetime_array_default(&mut self, path: &str, v: &[ShclDateTime]) -> bool {
		if !self.exists(path) {
			return self.set_datetime_array(path, v);
		}
		true
	}
}

// ---------------------------------------------------------------------------
// Layered loading: overlay a higher-priority document onto a lower one.
// ---------------------------------------------------------------------------

impl Document {
	/// Overlay `over` (a higher-priority layer) onto self (the lower one).
	/// Container instances merge by `(name, value)` exactly like the in-file
	/// rule; a leaf name present in `over` *replaces* self's same-named children
	/// at that scope - provided those base children are leaves too - so scalars,
	/// arrays, and raw blocks get real override while a bare section header
	/// merges instead of wiping. over-only nodes are appended. Comment trivia
	/// rides with each node.
	/// `Load(defaults, site, user)` is a left fold of this: each later file
	/// overlaid on the accumulation of the earlier ones.
	pub fn merge(&mut self, over: &Document) {
		self.overlay(ROOT, over, ROOT);
		// Layers commonly share a footer; keeping one copy of each keeps a
		// stack of files from repeating it once per layer.
		for o in &over.orphans {
			if !self.orphans.iter().any(|e| e.text == o.text) {
				self.orphans.push(o.clone());
			}
		}
	}

	// One grouping pass over each side, then a single children rebuild: the
	// old shape re-filtered the over side per distinct name and re-scanned
	// (and re-keyed) the base side per over node - three O(K^2) terms at one
	// parent, plus a full vector rebuild per replaced name.
	/// A matched instance keeps the base node, so the over side's comments have
	/// to move onto it or they are lost. Same rule as an in-file merge: leading
	/// concatenates in layer order, first trailing wins.
	fn adopt_trivia(&mut self, base: usize, over: &Document, ok: usize) {
		let src = &over.arena[ok];
		let mut lead = src.leading.clone();
		self.arena[base].leading.append(&mut lead);
		if !src.trailing.is_empty() {
			if self.arena[base].trailing.is_empty() {
				self.arena[base].trailing = src.trailing.clone();
			} else {
				self.arena[base]
					.leading
					.push(Lead::plain(src.trailing.clone()));
			}
		}
		let mut after = src.after.clone();
		self.arena[base].after.append(&mut after);
		let mut inside = src.inside.clone();
		self.arena[base].inside.append(&mut inside);
	}

	fn overlay(&mut self, base_parent: usize, over: &Document, over_parent: usize) {
		let over_kids = over.arena[over_parent].children.clone();
		// Over side: name -> node bucket, in first-appearance order.
		let mut order: Vec<String> = Vec::new();
		let mut groups: HashMap<String, Vec<usize>> = HashMap::new();
		for &k in &over_kids {
			let n = &over.arena[k].name;
			groups
				.entry(n.clone())
				.or_insert_with(|| {
					order.push(n.clone());
					Vec::new()
				})
				.push(k);
		}
		// Base side, one pass: does the name have a container instance, and
		// which child carries each (name, key) - every key computed once.
		let base_kids = self.arena[base_parent].children.clone();
		let mut has_container: HashMap<String, bool> = HashMap::new();
		let mut by_key: HashMap<(String, String), usize> = HashMap::new();
		for &b in &base_kids {
			let name = self.arena[b].name.clone();
			let e = has_container.entry(name.clone()).or_insert(false);
			*e = *e || !self.arena[b].children.is_empty();
			by_key.entry((name, self.arena[b].value.key())).or_insert(b);
		}
		// Decide per name. A name whose over-side nodes are all leaves is an
		// override - but only when the base side of the group is leaf-shaped
		// too. Against a base container, a childless over-node is a wrapper
		// mention, not a leaf, so it falls through to the instance merge: a
		// bare section header in a higher layer never wipes the subtree below.
		// Replaced groups splice in the rebuild; everything appended (unmatched
		// instances, and replaced names base never had) keeps processing order.
		let mut replace: HashMap<String, Vec<usize>> = HashMap::new();
		let mut appended: Vec<usize> = Vec::new();
		for name in &order {
			let group = &groups[name];
			let over_leafy = group.iter().all(|&k| over.arena[k].children.is_empty());
			let in_base = has_container.contains_key(name);
			let base_container = has_container.get(name).copied().unwrap_or(false);
			if over_leafy && !base_container {
				let clones: Vec<usize> = group
					.iter()
					.map(|&ok| self.clone_subtree(over, ok, base_parent))
					.collect();
				if in_base {
					replace.insert(name.clone(), clones);
				} else {
					appended.extend(clones);
				}
			} else {
				for &ok in group {
					let okey = over.arena[ok].value.key();
					match by_key.get(&(name.clone(), okey)) {
						Some(&b) => {
							self.adopt_trivia(b, over, ok);
							self.overlay(b, over, ok);
						}
						None => {
							let c = self.clone_subtree(over, ok, base_parent);
							appended.push(c);
						}
					}
				}
			}
		}
		if replace.is_empty() && appended.is_empty() {
			return;
		}
		// Rebuild once: each replaced group lands at its name's first original
		// position (dropped nodes stay in the arena, unreferenced - reads and
		// emit walk children from the root), appends go at the end.
		let mut newkids: Vec<usize> = Vec::with_capacity(base_kids.len() + appended.len());
		let mut spliced: std::collections::HashSet<&str> = std::collections::HashSet::new();
		for &b in &base_kids {
			let name = self.arena[b].name.as_str();
			match replace.get(name) {
				Some(clones) => {
					if spliced.insert(name) {
						newkids.extend(clones.iter().copied());
					}
				}
				None => newkids.push(b),
			}
		}
		newkids.extend(appended.iter().copied());
		self.arena[base_parent].children = newkids;
	}

	/// Deep-copy `over`'s subtree at `oi` into self's arena under `parent`.
	fn clone_subtree(&mut self, over: &Document, oi: usize, parent: usize) -> usize {
		let src = &over.arena[oi];
		let node = NodeData {
			name: src.name.clone(),
			value: src.value.clone(),
			children: Vec::new(),
			parent,
			line: src.line,
			star_list: src.star_list,
			star_mixed: src.star_mixed,
			leading: src.leading.clone(),
			trailing: src.trailing.clone(),
			after: src.after.clone(),
			inside: src.inside.clone(),
			blank_before: src.blank_before,
			src: src.src.clone(),
		};
		let idx = self.arena.len();
		self.arena.push(node);
		let okids = over.arena[oi].children.clone();
		for ok in okids {
			let c = self.clone_subtree(over, ok, idx);
			self.arena[idx].children.push(c);
		}
		idx
	}
}

impl Default for Document {
	fn default() -> Document {
		Document::new()
	}
}

// ---------------------------------------------------------------------------
// Coercion ("intelligent but safe"; Loose re-admits a closed list of tricks)
// ---------------------------------------------------------------------------

const CURRENCY: &[char] = &[
	'$', '¢', '£', '¤', '¥', '₩', '₪', '₫', '€', '₭', '₮', '₱', '₲', '₴', '₹', '₺', '₼', '₽', '₾',
	'₿',
];

fn strip_currency(t: &str) -> &str {
	let mut it = t.chars();
	match it.next() {
		Some(c) if CURRENCY.contains(&c) => it.as_str(),
		_ => t,
	}
}

fn parse_int_text(e: &Element, level: Strictness) -> Option<i64> {
	let mut t = e.text.trim();
	if level == Strictness::Loose {
		t = strip_currency(t);
	}
	// Plain decimal.
	let body = t.strip_prefix(['+', '-']).unwrap_or(t);
	if !body.is_empty() && body.bytes().all(|b| b.is_ascii_digit()) {
		return t.parse::<i64>().ok();
	}
	// Hex.
	let (neg, hex) = match t.strip_prefix('-') {
		Some(r) => (true, r),
		None => (false, t.strip_prefix('+').unwrap_or(t)),
	};
	if let Some(h) = hex.strip_prefix("0x").or_else(|| hex.strip_prefix("0X"))
		&& !h.is_empty()
		&& h.bytes().all(|b| b.is_ascii_hexdigit())
	{
		// Parse the magnitude as u64, then range-check against the sign, so the
		// negative i64::MIN magnitude (0x8000000000000000) reads like its decimal
		// spelling instead of overflowing an i64 parse.
		let m = u64::from_str_radix(h, 16).ok()?;
		return if neg {
			if m == (i64::MAX as u64) + 1 {
				Some(i64::MIN)
			} else if m <= i64::MAX as u64 {
				Some(-(m as i64))
			} else {
				None
			}
		} else if m <= i64::MAX as u64 {
			Some(m as i64)
		} else {
			None
		};
	}
	// Thousands separators, only inside quotes (bare commas are reserved).
	if e.quoted && t.contains(',') {
		let sign_body = t.strip_prefix(['+', '-']).unwrap_or(t);
		let groups: Vec<&str> = sign_body.split(',').collect();
		let well_formed = groups.len() > 1
			&& !groups[0].is_empty()
			&& groups[0].len() <= 3
			&& groups[0].bytes().all(|b| b.is_ascii_digit())
			&& groups[1..]
				.iter()
				.all(|g| g.len() == 3 && g.bytes().all(|b| b.is_ascii_digit()));
		if well_formed {
			return t.replace(',', "").parse::<i64>().ok();
		}
	}
	// Loose: a float (including %) rounds, half away from zero.
	if level == Strictness::Loose
		&& let Some(f) = parse_float_text(e, level)
	{
		let r = f.round();
		if r >= i64::MIN as f64 && r <= i64::MAX as f64 {
			return Some(r as i64);
		}
	}
	None
}

fn float_shape_ok(t: &str) -> bool {
	let body = t.strip_prefix(['+', '-']).unwrap_or(t);
	if body.is_empty() {
		return false;
	}
	let (mantissa, exp) = match body.split_once(['e', 'E']) {
		Some((m, x)) => (m, Some(x)),
		None => (body, None),
	};
	if let Some(x) = exp {
		let xb = x.strip_prefix(['+', '-']).unwrap_or(x);
		if xb.is_empty() || !xb.bytes().all(|b| b.is_ascii_digit()) {
			return false;
		}
	}
	let (int_part, frac_part) = match mantissa.split_once('.') {
		Some((a, b)) => (a, b),
		None => (mantissa, ""),
	};
	if int_part.is_empty() && frac_part.is_empty() {
		return false;
	}
	int_part.bytes().all(|b| b.is_ascii_digit()) && frac_part.bytes().all(|b| b.is_ascii_digit())
}

fn parse_float_text(e: &Element, level: Strictness) -> Option<f64> {
	let mut t = e.text.trim();
	let mut percent = false;
	if level == Strictness::Loose {
		t = strip_currency(t);
		if let Some(inner) = t.strip_suffix('%') {
			t = inner.trim_end();
			percent = true;
		}
	}
	let v = if float_shape_ok(t) {
		t.parse::<f64>().ok()?
	} else {
		// An integer is a valid float on read (incl. hex and quoted thousands).
		let el = Element {
			text: t.to_string(),
			quoted: e.quoted,
		};
		parse_int_text_no_loose(&el)? as f64
	};
	Some(if percent { v / 100.0 } else { v })
}

/// Integer forms only (no Loose float fallback) - used by the float path so the
/// two can't recurse into each other.
fn parse_int_text_no_loose(e: &Element) -> Option<i64> {
	parse_int_text(e, Strictness::Standard)
}

fn parse_bool_text(t: &str, level: Strictness) -> Option<bool> {
	let s = t.trim().to_ascii_lowercase();
	match (level, s.as_str()) {
		(_, "true") => Some(true),
		(_, "false") => Some(false),
		(Strictness::Strict, _) => None,
		(_, "yes") | (_, "on") | (_, "1") => Some(true),
		(_, "no") | (_, "off") | (_, "0") => Some(false),
		(Strictness::Loose, "t")
		| (Strictness::Loose, "y")
		| (Strictness::Loose, "enable")
		| (Strictness::Loose, "enabled") => Some(true),
		(Strictness::Loose, "f")
		| (Strictness::Loose, "n")
		| (Strictness::Loose, "disable")
		| (Strictness::Loose, "disabled") => Some(false),
		_ => None,
	}
}

// ---------------------------------------------------------------------------
// Date/time (closed whitelist; shape match, then calendar validation)
// ---------------------------------------------------------------------------

const MONTHS: &[(&str, u32)] = &[
	("jan", 1),
	("feb", 2),
	("mar", 3),
	("apr", 4),
	("may", 5),
	("jun", 6),
	("jul", 7),
	("aug", 8),
	("sep", 9),
	("oct", 10),
	("nov", 11),
	("dec", 12),
	("january", 1),
	("february", 2),
	("march", 3),
	("april", 4),
	("june", 6),
	("july", 7),
	("august", 8),
	("september", 9),
	("october", 10),
	("november", 11),
	("december", 12),
];

fn month_from_name(s: &str) -> Option<u32> {
	let l = s.to_ascii_lowercase();
	MONTHS.iter().find(|(n, _)| *n == l).map(|(_, m)| *m)
}

fn days_in_month(y: i32, m: u32) -> u32 {
	match m {
		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
		4 | 6 | 9 | 11 => 30,
		2 => {
			if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
				29
			} else {
				28
			}
		}
		_ => 0,
	}
}

fn valid_date(y: i32, m: u32, d: u32) -> bool {
	(1..=12).contains(&m) && d >= 1 && d <= days_in_month(y, m)
}

fn parse_date_part(s: &str) -> Option<(i32, u32, u32)> {
	let s = s.trim();
	// Compact 8-digit YYYYMMDD.
	if s.len() == 8 && s.bytes().all(|b| b.is_ascii_digit()) {
		let y: i32 = s[..4].parse().ok()?;
		let m: u32 = s[4..6].parse().ok()?;
		let d: u32 = s[6..8].parse().ok()?;
		return valid_date(y, m, d).then_some((y, m, d));
	}
	// Space-separated named-month forms; a comma may follow the day in "Mon DD, YYYY".
	let toks: Vec<&str> = s.split_whitespace().collect();
	if toks.len() == 3 {
		if let Some(m) = month_from_name(toks[0]) {
			let day_tok = toks[1].strip_suffix(',').unwrap_or(toks[1]);
			let d: u32 = day_tok.parse().ok()?;
			let y: i32 = parse_year4(toks[2])?;
			return valid_date(y, m, d).then_some((y, m, d));
		}
		if let Some(m) = month_from_name(toks[1]) {
			let d: u32 = toks[0].parse().ok()?;
			let y: i32 = parse_year4(toks[2])?;
			return valid_date(y, m, d).then_some((y, m, d));
		}
		return None;
	}
	if toks.len() != 1 {
		return None;
	}
	// Delimited forms: one of - / . used uniformly.
	let delim = s.chars().find(|c| matches!(c, '-' | '/' | '.'))?;
	let parts: Vec<&str> = s.split(delim).collect();
	if parts.len() != 3 || parts.iter().any(|p| p.is_empty()) {
		return None;
	}
	// The delimiter must be uniform: no other delimiter chars anywhere.
	if s.chars().filter(|c| matches!(c, '-' | '/' | '.')).count() != 2 {
		return None;
	}
	if parts[0].len() == 4 && parts[0].bytes().all(|b| b.is_ascii_digit()) {
		// Year-first all-numeric.
		let y: i32 = parts[0].parse().ok()?;
		let m: u32 = parse_num2(parts[1])?;
		let d: u32 = parse_num2(parts[2])?;
		return valid_date(y, m, d).then_some((y, m, d));
	}
	if let Some(m) = month_from_name(parts[0]) {
		let d: u32 = parse_num2(parts[1])?;
		let y: i32 = parse_year4(parts[2])?;
		return valid_date(y, m, d).then_some((y, m, d));
	}
	if let Some(m) = month_from_name(parts[1]) {
		let d: u32 = parse_num2(parts[0])?;
		let y: i32 = parse_year4(parts[2])?;
		return valid_date(y, m, d).then_some((y, m, d));
	}
	None // everything else (MM/DD/YYYY, 2-digit years, epoch) is rejected by decision
}

fn parse_year4(s: &str) -> Option<i32> {
	(s.len() == 4 && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok())?
}

fn parse_num2(s: &str) -> Option<u32> {
	((s.len() == 1 || s.len() == 2) && s.bytes().all(|b| b.is_ascii_digit()))
		.then(|| s.parse().ok())?
}

/// (hour, minute, seconds-if-written), fraction digits, zone.
type TimeParts = ((u32, u32, Option<u32>), Option<String>, Option<ZoneSpec>);

/// Time with optional meridiem, fraction, zone: `H:MM[:SS[.f+]][ AM|PM][Z|+HH:MM]`.
fn parse_time_part(s: &str) -> Option<TimeParts> {
	let mut t = s.trim();
	// Zone suffix first (only valid after a time).
	let mut zone: Option<ZoneSpec> = None;
	if let Some(rest) = t.strip_suffix(['Z', 'z']) {
		zone = Some(ZoneSpec::Utc);
		t = rest.trim_end();
	} else if t.len() >= 6 {
		// Byte-wise on purpose: a str slice here can land mid-char and panic when
		// the tail holds multibyte text. All-ASCII match implies the cut is a
		// char boundary, so the later &t[..len-6] is safe.
		let tail = &t.as_bytes()[t.len() - 6..];
		let sign = tail[0];
		if (sign == b'+' || sign == b'-')
			&& tail[1].is_ascii_digit()
			&& tail[2].is_ascii_digit()
			&& tail[3] == b':'
			&& tail[4].is_ascii_digit()
			&& tail[5].is_ascii_digit()
		{
			let hh = i32::from(tail[1] - b'0') * 10 + i32::from(tail[2] - b'0');
			let mm = i32::from(tail[4] - b'0') * 10 + i32::from(tail[5] - b'0');
			if hh <= 23 && mm <= 59 {
				let mut off = hh * 60 + mm;
				if sign == b'-' {
					off = -off;
				}
				zone = Some(ZoneSpec::OffsetMinutes(off));
				t = t[..t.len() - 6].trim_end();
			}
		}
	}
	// Meridiem: mandatory minutes already implied by the H:MM shape; dotted
	// a.m. is rejected (the '.' fails the digit checks below).
	let mut meridiem: Option<bool> = None; // true = PM
	let lower = t.to_ascii_lowercase();
	if let Some(rest) = lower.strip_suffix("am") {
		meridiem = Some(false);
		t = &t[..rest.trim_end().len()];
	} else if let Some(rest) = lower.strip_suffix("pm") {
		meridiem = Some(true);
		t = &t[..rest.trim_end().len()];
	}
	let t = t.trim_end();
	// Fraction: only after seconds, '.' delimiter, 1-9 digits.
	let (hms, frac) = match t.split_once('.') {
		Some((a, f)) => {
			if f.is_empty() || f.len() > 9 || !f.bytes().all(|b| b.is_ascii_digit()) {
				return None;
			}
			(a, Some(f.to_string()))
		}
		None => (t, None),
	};
	let parts: Vec<&str> = hms.split(':').collect();
	if parts.len() < 2 || parts.len() > 3 {
		return None;
	}
	if frac.is_some() && parts.len() != 3 {
		return None; // fraction can only follow HH:MM:SS
	}
	let h_raw: u32 = parse_num2(parts[0])?;
	let mi: u32 = (parts[1].len() == 2)
		.then(|| parse_num2(parts[1]))
		.flatten()?;
	let sec: Option<u32> = match parts.get(2) {
		Some(p) => Some((p.len() == 2).then(|| parse_num2(p)).flatten()?),
		None => None,
	};
	if mi > 59 || sec.is_some_and(|x| x > 59) {
		return None;
	}
	let h = match meridiem {
		None => {
			if h_raw > 23 {
				return None;
			}
			h_raw
		}
		Some(pm) => {
			if !(1..=12).contains(&h_raw) {
				return None;
			}
			match (pm, h_raw) {
				(false, 12) => 0,
				(false, x) => x,
				(true, 12) => 12,
				(true, x) => x + 12,
			}
		}
	};
	Some(((h, mi, sec), frac, zone))
}

/// Whole-value date/time parse per the whitelist. None = BadType.
pub fn parse_datetime(text: &str) -> Option<ShclDateTime> {
	let t = text.trim();
	if t.is_empty() {
		return None;
	}
	if let Some(colon) = t.find(':') {
		// Scan back over the 1-2 hour digits to find where the time starts.
		let bytes = t.as_bytes();
		let mut k = colon;
		while k > 0 && bytes[k - 1].is_ascii_digit() && colon - k < 2 {
			k -= 1;
		}
		if k == colon {
			return None; // ':' with no hour digits before it
		}
		if k == 0 {
			// Time-only value.
			let ((h, mi, s), frac, zone) = parse_time_part(t)?;
			return Some(ShclDateTime {
				date: None,
				time: Some((h, mi, s)),
				frac,
				zone,
			});
		}
		// Combined: one separator char between date and time.
		let sep = t[..k].chars().last()?;
		if !matches!(sep, 'T' | 't' | ' ' | '_' | '-' | '/' | '.') {
			return None;
		}
		let date_str = &t[..k - sep.len_utf8()];
		let date = parse_date_part(date_str)?;
		let ((h, mi, s), frac, zone) = parse_time_part(&t[k..])?;
		return Some(ShclDateTime {
			date: Some(date),
			time: Some((h, mi, s)),
			frac,
			zone,
		});
	}
	// Date-only.
	let date = parse_date_part(t)?;
	Some(ShclDateTime {
		date: Some(date),
		time: None,
		frac: None,
		zone: None,
	})
}

// ---------------------------------------------------------------------------
// Accessor: typed reads
// ---------------------------------------------------------------------------

impl Document {
	/// Single node at a path, or the failing status.
	fn node_at(&self, path: &str) -> Result<usize, Status> {
		match self.resolve(path)? {
			Resolved::None => Err(Status::NotFound),
			Resolved::Many(_) | Resolved::Slots(_) => Err(Status::Multiple),
			Resolved::One(n) => Ok(n),
		}
	}

	/// A read's `raw`: the verbatim source value text when the value came from
	/// one source line, else the display form (writer-built, stacked list, raw
	/// block - shapes with no one-line source spelling).
	fn raw_of(&self, n: usize) -> String {
		match &self.arena[n].src {
			Some(s) => s.clone(),
			None => self.arena[n].value.display(),
		}
	}

	fn scalar_element<'a>(&self, v: &'a Value) -> Result<&'a Element, Status> {
		match v {
			Value::Empty => Err(Status::Empty),
			Value::Raw { .. } => Err(Status::BadType),
			Value::Cell(els) if els.len() == 1 => Ok(&els[0]),
			Value::Cell(_) => Err(Status::BadType), // an array is not one scalar
		}
	}

	fn read_scalar<T: Default>(
		&self,
		path: &str,
		coerce: impl Fn(&Element) -> Option<T>,
	) -> Read<T> {
		let node = match self.node_at(path) {
			Ok(n) => n,
			Err(st) => return Read::new(T::default(), st, None),
		};
		let value = &self.arena[node].value;
		let raw = Some(self.raw_of(node));
		let line = self.arena[node].line;
		match self.scalar_element(value) {
			Ok(el) => match coerce(el) {
				Some(v) => Read::new(v, Status::Good, raw).at(line, el.quoted),
				None => Read::new(T::default(), Status::BadType, raw).at(line, el.quoted),
			},
			Err(st) => Read::new(T::default(), st, raw).at(line, false),
		}
	}

	pub fn read_int(&self, path: &str) -> Read<i64> {
		let lvl = self.strictness;
		self.read_scalar(path, |e| parse_int_text(e, lvl))
	}

	pub fn read_float(&self, path: &str) -> Read<f64> {
		let lvl = self.strictness;
		self.read_scalar(path, |e| parse_float_text(e, lvl))
	}

	pub fn read_bool(&self, path: &str) -> Read<bool> {
		let lvl = self.strictness;
		self.read_scalar(path, |e| parse_bool_text(&e.text, lvl))
	}

	pub fn read_datetime(&self, path: &str) -> Read<ShclDateTime> {
		self.read_scalar(path, |e| parse_datetime(&e.text))
	}

	/// Any value reads as a string: a raw block yields its content, an array its
	/// canonical inline text. Escapes are applied.
	pub fn read_string(&self, path: &str) -> Read<String> {
		let node = match self.node_at(path) {
			Ok(n) => n,
			Err(st) => return Read::new(String::new(), st, None),
		};
		let value = &self.arena[node].value;
		let raw = Some(self.raw_of(node));
		let line = self.arena[node].line;
		match value {
			Value::Empty => Read::new(String::new(), Status::Empty, raw).at(line, false),
			Value::Raw { content, .. } => {
				Read::new(content.clone(), Status::Good, raw).at(line, false)
			}
			Value::Cell(els) if els.len() == 1 => {
				Read::new(apply_escapes(&els[0].text), Status::Good, raw).at(line, els[0].quoted)
			}
			// Canonical inline form (quoting + escapes intact), so the string
			// re-parses to the same array - not the bare display join.
			Value::Cell(els) => Read::new(
				els.iter().map(emit_element).collect::<Vec<_>>().join(", "),
				Status::Good,
				raw,
			)
			.at(line, false),
		}
	}

	/// Raw-block content (verbatim). Non-block values are BadType.
	pub fn read_raw(&self, path: &str) -> Read<String> {
		let node = match self.node_at(path) {
			Ok(n) => n,
			Err(st) => return Read::new(String::new(), st, None),
		};
		let value = &self.arena[node].value;
		let raw = Some(self.raw_of(node));
		let line = self.arena[node].line;
		match value {
			Value::Raw { content, .. } => {
				Read::new(content.clone(), Status::Good, raw).at(line, false)
			}
			Value::Empty => Read::new(String::new(), Status::Empty, raw).at(line, false),
			_ => Read::new(String::new(), Status::BadType, raw).at(line, false),
		}
	}

	/// The advisory info-string of a raw block ("" when absent).
	pub fn read_raw_info(&self, path: &str) -> Read<String> {
		let node = match self.node_at(path) {
			Ok(n) => n,
			Err(st) => return Read::new(String::new(), st, None),
		};
		let raw = Some(self.raw_of(node));
		let line = self.arena[node].line;
		match &self.arena[node].value {
			Value::Raw { info, .. } => Read::new(info.clone(), Status::Good, raw).at(line, false),
			_ => Read::new(String::new(), Status::BadType, raw).at(line, false),
		}
	}

	fn read_array<T: Default>(
		&self,
		path: &str,
		coerce: impl Fn(&Element) -> Option<T>,
	) -> Read<Vec<T>> {
		// Wildcard paths: one slot per instance, missing sub-paths keep their slot
		// (spec: never silently dropped). Each slot reads like a scalar of the
		// target type and records its own status; the aggregate is the worst one.
		match self.resolve(path) {
			Err(st) => Read::new(Vec::new(), st, None),
			Ok(Resolved::Slots(slots)) => {
				let mut out: Vec<T> = Vec::new();
				let mut sts: Vec<Status> = Vec::new();
				for slot in &slots {
					match slot {
						Err(st) => {
							out.push(T::default());
							sts.push(*st);
						}
						Ok(n) => match self.scalar_element(&self.arena[*n].value) {
							Ok(el) => match coerce(el) {
								Some(v) => {
									out.push(v);
									sts.push(Status::Good);
								}
								None => {
									out.push(T::default());
									sts.push(Status::BadType);
								}
							},
							Err(st) => {
								out.push(T::default());
								sts.push(st);
							}
						},
					}
				}
				let status = if sts.is_empty() {
					Status::Empty
				} else {
					sts.iter().copied().max().unwrap_or(Status::Good)
				};
				Read::with_slots(out, status, None, sts)
			}
			Ok(Resolved::None) => Read::new(Vec::new(), Status::NotFound, None),
			Ok(Resolved::Many(_)) => Read::new(Vec::new(), Status::Multiple, None),
			Ok(Resolved::One(n)) => {
				let value = &self.arena[n].value;
				let raw = Some(self.raw_of(n));
				let line = self.arena[n].line;
				match value {
					Value::Empty => Read::new(Vec::new(), Status::Empty, raw).at(line, false),
					Value::Raw { .. } => {
						Read::new(Vec::new(), Status::BadType, raw).at(line, false)
					}
					Value::Cell(els) => {
						let mut out = Vec::with_capacity(els.len());
						let mut sts = Vec::with_capacity(els.len());
						for el in els {
							match coerce(el) {
								Some(v) => {
									out.push(v);
									sts.push(Status::Good);
								}
								None => {
									out.push(T::default());
									sts.push(Status::BadType);
								}
							}
						}
						let status = sts.iter().copied().max().unwrap_or(Status::Good);
						Read::with_slots(out, status, raw, sts).at(line, false)
					}
				}
			}
		}
	}

	pub fn read_int_array(&self, path: &str) -> Read<Vec<i64>> {
		let lvl = self.strictness;
		self.read_array(path, |e| parse_int_text(e, lvl))
	}

	pub fn read_float_array(&self, path: &str) -> Read<Vec<f64>> {
		let lvl = self.strictness;
		self.read_array(path, |e| parse_float_text(e, lvl))
	}

	pub fn read_bool_array(&self, path: &str) -> Read<Vec<bool>> {
		let lvl = self.strictness;
		self.read_array(path, |e| parse_bool_text(&e.text, lvl))
	}

	pub fn read_datetime_array(&self, path: &str) -> Read<Vec<ShclDateTime>> {
		self.read_array(path, |e| parse_datetime(&e.text))
	}

	pub fn read_string_array(&self, path: &str) -> Read<Vec<String>> {
		self.read_array(path, |e| Some(apply_escapes(&e.text)))
	}

	// Full tier, Result form: Ok(value) on Good; the sentinel otherwise. Empty
	// still comes back as Err(Empty) here; use read_* to also get the empty value.

	pub fn get_int(&self, path: &str) -> Result<i64, Status> {
		let r = self.read_int(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_float(&self, path: &str) -> Result<f64, Status> {
		let r = self.read_float(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_bool(&self, path: &str) -> Result<bool, Status> {
		let r = self.read_bool(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_string(&self, path: &str) -> Result<String, Status> {
		let r = self.read_string(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_raw(&self, path: &str) -> Result<String, Status> {
		let r = self.read_raw(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_datetime(&self, path: &str) -> Result<ShclDateTime, Status> {
		let r = self.read_datetime(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	// Array get-tier: Ok only when the whole read is Good, so `.unwrap_or(def)`
	// gives the convenience "the array, or this fallback array" - the array
	// analogue of the scalar get_*. Per-slot substitution is the full read_*
	// tier (its `slots`) or the CLI's --default, not this.
	pub fn get_int_array(&self, path: &str) -> Result<Vec<i64>, Status> {
		let r = self.read_int_array(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_float_array(&self, path: &str) -> Result<Vec<f64>, Status> {
		let r = self.read_float_array(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_bool_array(&self, path: &str) -> Result<Vec<bool>, Status> {
		let r = self.read_bool_array(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_string_array(&self, path: &str) -> Result<Vec<String>, Status> {
		let r = self.read_string_array(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}

	pub fn get_datetime_array(&self, path: &str) -> Result<Vec<ShclDateTime>, Status> {
		let r = self.read_datetime_array(path);
		if r.status == Status::Good {
			Ok(r.value)
		} else {
			Err(r.status)
		}
	}
}

// ---------------------------------------------------------------------------
// Validator: schema-as-SHCL
// ---------------------------------------------------------------------------
// The schema is an ordinary parsed document: a flat list of `field: <path>`
// instances whose children are the constraints (closed vocabulary - see
// spec.md "Schema validation"). Validation reuses the accessor's path scan and
// the typed coercions, so document strictness composes for free. Schema faults
// (V09x) come first and the surviving constraints still check the document;
// only the unknown-field sweep needs a fault-free schema. One line-number
// space per result.

const SCHEMA_TYPES: [&str; 11] = [
	"int",
	"float",
	"bool",
	"string",
	"datetime",
	"raw",
	"int-array",
	"float-array",
	"bool-array",
	"string-array",
	"datetime-array",
];

// The allowed set, pre-coerced at schema-build time into the constraint's type
// space so per-node checks are a plain contains().
#[derive(Clone)]
enum AllowedSet {
	Ints(Vec<i64>),
	Floats(Vec<f64>),
	Bools(Vec<bool>),
	Dates(Vec<ShclDateTime>),
	Strings(Vec<String>),
}

#[derive(Clone)]
struct Constraint {
	path: String, // as written in the schema; message text only
	segs: Vec<Segment>,
	ty: Option<String>, // member of SCHEMA_TYPES
	required: bool,
	allowed: Option<AllowedSet>,
	min_i: Option<i64>,
	max_i: Option<i64>,
	min_f: Option<f64>,
	max_f: Option<f64>,
	repeat: Option<(u64, u64)>,
	inherits: Option<String>, // fragment mounted at this path (subtree shape)
	inherits_line: usize,     // schema line of the `inherits` key, for V095
	// Generator-only (`shcl init`): validation ignores both.
	desc: Option<String>,         // `desc`, a one-line description
	default_text: Option<String>, // `default`, emitted as an inline value
}

/// An interpreted schema: the top-level constraints plus the named fragments
/// their `inherits` keys can mount.
struct SchemaDef {
	cons: Vec<Constraint>,
	frags: HashMap<String, Vec<Constraint>>,
}

fn vdiag(out: &mut Vec<Diagnostic>, line: usize, msg: String) {
	let code = diag_code(&msg);
	out.push(Diagnostic {
		line,
		severity: Severity::Error,
		message: msg,
		code,
	});
}

/// One scalar constraint value (escapes applied), or None for anything else.
fn single_text(v: &Value) -> Option<String> {
	match v {
		Value::Cell(els) if els.len() == 1 => Some(apply_escapes(&els[0].text)),
		_ => None,
	}
}

/// Interpret a parsed schema document into constraints and fragments, plus
/// any schema faults (V09x, schema-file lines). Whatever parsed cleanly is
/// kept even when faults are present - a broken key drops that key, a broken
/// field drops that field - so a caller can still check the document against
/// the surviving constraints.
fn build_schema(schema: &Document) -> (SchemaDef, Vec<Diagnostic>) {
	let mut faults: Vec<Diagnostic> = Vec::new();
	let mut cons: Vec<Constraint> = Vec::new();
	let mut frags: HashMap<String, Vec<Constraint>> = HashMap::new();
	for &f in &schema.arena[ROOT].children {
		let node = &schema.arena[f];
		match node.name.as_str() {
			"field" => {
				if let Some(c) = parse_field(schema, f, &mut faults) {
					cons.push(c);
				}
			}
			"fragment" => {
				let name = single_text(&node.value).filter(|n| !n.is_empty());
				let Some(name) = name else {
					vdiag(&mut faults, node.line, "bad schema fragment".to_string());
					continue;
				};
				if frags.contains_key(&name) {
					vdiag(
						&mut faults,
						node.line,
						format!("bad schema fragment '{}': duplicate", name),
					);
					continue;
				}
				let mut fcs: Vec<Constraint> = Vec::new();
				for &k in &schema.arena[f].children {
					let kid = &schema.arena[k];
					if kid.name == "field" {
						if let Some(c) = parse_field(schema, k, &mut faults) {
							fcs.push(c);
						}
					} else {
						vdiag(
							&mut faults,
							kid.line,
							format!("bad schema fragment '{}': unknown key '{}'", name, kid.name),
						);
					}
				}
				frags.insert(name, fcs);
			}
			other => {
				vdiag(
					&mut faults,
					node.line,
					format!("unknown schema key '{}'", other),
				);
			}
		}
	}
	// Every mount must name a declared fragment; cycles (self or mutual) are
	// legal - expansion is demand-driven against a finite document.
	for c in cons.iter().chain(frags.values().flatten()) {
		if let Some(fr) = &c.inherits
			&& !frags.contains_key(fr)
		{
			vdiag(
				&mut faults,
				c.inherits_line,
				format!("unknown schema fragment '{}'", fr),
			);
		}
	}
	// One constraint per line in practice, so line order = file order.
	faults.sort_by_key(|d| d.line);
	(SchemaDef { cons, frags }, faults)
}

/// One `field:` instance (top-level or inside a fragment) -> a Constraint.
/// None = faults were reported and the constraint is dropped.
fn parse_field(schema: &Document, f: usize, faults: &mut Vec<Diagnostic>) -> Option<Constraint> {
	let node = &schema.arena[f];
	let path = match single_text(&node.value) {
		Some(p) => p,
		None => {
			vdiag(faults, node.line, "bad schema path".to_string());
			return None;
		}
	};
	let segs = match scan_lookup(&path) {
		Ok(s) if s.value_text.is_none() => s.segments,
		_ => {
			vdiag(faults, node.line, format!("bad schema path: {}", path));
			return None;
		}
	};
	let mut c = Constraint {
		path,
		segs,
		ty: None,
		required: false,
		allowed: None,
		min_i: None,
		max_i: None,
		min_f: None,
		max_f: None,
		repeat: None,
		inherits: None,
		inherits_line: 0,
		desc: None,
		default_text: None,
	};
	// Deferred so `min: 1` may precede `type: int` in the file.
	let mut required: Option<bool> = None;
	let mut allowed_at: Option<usize> = None;
	let mut min_at: Option<usize> = None;
	let mut max_at: Option<usize> = None;
	for &k in &schema.arena[f].children {
		let kid = &schema.arena[k];
		if kid.value.is_empty() {
			continue; // dangling key: treated as absent
		}
		match kid.name.as_str() {
			"type" => match single_text(&kid.value).map(|t| t.to_ascii_lowercase()) {
				Some(t) if SCHEMA_TYPES.contains(&t.as_str()) => {
					if c.ty.is_some() {
						vdiag(faults, kid.line, "bad schema constraint 'type'".to_string());
					} else {
						c.ty = Some(t);
					}
				}
				Some(t) => {
					vdiag(faults, kid.line, format!("unknown schema type '{}'", t));
				}
				None => vdiag(faults, kid.line, "bad schema constraint 'type'".to_string()),
			},
			"required" => {
				let v =
					single_text(&kid.value).and_then(|t| parse_bool_text(&t, Strictness::Standard));
				match v {
					Some(b) if required.is_none() => required = Some(b),
					_ => vdiag(
						faults,
						kid.line,
						"bad schema constraint 'required'".to_string(),
					),
				}
			}
			"allowed" => match &kid.value {
				Value::Cell(_) if allowed_at.is_none() => allowed_at = Some(k),
				_ => vdiag(
					faults,
					kid.line,
					"bad schema constraint 'allowed'".to_string(),
				),
			},
			"min" => match &kid.value {
				Value::Cell(els) if els.len() == 1 && min_at.is_none() => min_at = Some(k),
				_ => vdiag(faults, kid.line, "bad schema constraint 'min'".to_string()),
			},
			"max" => match &kid.value {
				Value::Cell(els) if els.len() == 1 && max_at.is_none() => max_at = Some(k),
				_ => vdiag(faults, kid.line, "bad schema constraint 'max'".to_string()),
			},
			"repeat" => match &kid.value {
				Value::Cell(els) if c.repeat.is_none() && matches!(els.len(), 1 | 2) => {
					let lo = els[0].text.parse::<u64>().ok();
					let hi = els.last().and_then(|e| e.text.parse::<u64>().ok());
					match (lo, hi) {
						(Some(a), Some(b)) if a <= b => c.repeat = Some((a, b)),
						_ => vdiag(
							faults,
							kid.line,
							"bad schema constraint 'repeat'".to_string(),
						),
					}
				}
				_ => vdiag(
					faults,
					kid.line,
					"bad schema constraint 'repeat'".to_string(),
				),
			},
			"inherits" => match single_text(&kid.value).filter(|t| !t.is_empty()) {
				Some(t) if c.inherits.is_none() => {
					c.inherits = Some(t);
					c.inherits_line = kid.line;
				}
				_ => vdiag(
					faults,
					kid.line,
					"bad schema constraint 'inherits'".to_string(),
				),
			},
			// Generator-only (`shcl init`); validation ignores both. First
			// occurrence wins (a merged schema could carry two).
			"desc" => {
				if c.desc.is_none() {
					c.desc = single_text(&kid.value);
				}
			}
			"default" => {
				if c.default_text.is_none() {
					c.default_text = emit_value_inline(&kid.value);
				}
			}
			other => vdiag(faults, kid.line, format!("unknown schema key '{}'", other)),
		}
	}
	c.required = required.unwrap_or(false);
	let base =
		c.ty.as_deref()
			.map(|t| t.strip_suffix("-array").unwrap_or(t))
			.unwrap_or("string");
	if let Some(a) = allowed_at {
		let kid = &schema.arena[a];
		// allowed_at is only ever set for a Cell; if that invariant slips,
		// skip the constraint rather than abort the consumer.
		let Value::Cell(els) = &kid.value else {
			return None;
		};
		// Schema values are read at Standard; only the document's values
		// coerce at the document's strictness.
		let set = match base {
			"int" => els
				.iter()
				.map(|e| parse_int_text(e, Strictness::Standard))
				.collect::<Option<Vec<_>>>()
				.map(AllowedSet::Ints),
			"float" => els
				.iter()
				.map(|e| parse_float_text(e, Strictness::Standard))
				.collect::<Option<Vec<_>>>()
				.map(AllowedSet::Floats),
			"bool" => els
				.iter()
				.map(|e| parse_bool_text(&e.text, Strictness::Standard))
				.collect::<Option<Vec<_>>>()
				.map(AllowedSet::Bools),
			"datetime" => els
				.iter()
				.map(|e| parse_datetime(&e.text))
				.collect::<Option<Vec<_>>>()
				.map(AllowedSet::Dates),
			"raw" => None, // a raw body has no element space to enumerate
			_ => Some(AllowedSet::Strings(
				els.iter().map(|e| apply_escapes(&e.text)).collect(),
			)),
		};
		match set {
			Some(s) => c.allowed = Some(s),
			None => vdiag(
				faults,
				kid.line,
				"bad schema constraint 'allowed'".to_string(),
			),
		}
	}
	for (at, is_min) in [(min_at, true), (max_at, false)] {
		let Some(m) = at else { continue };
		let kid = &schema.arena[m];
		// min/max is only ever a one-element Cell; if that invariant slips,
		// skip the constraint rather than abort the consumer.
		let el = match &kid.value {
			Value::Cell(els) if els.len() == 1 => &els[0],
			_ => continue,
		};
		let key = if is_min { "min" } else { "max" };
		match base {
			"int" => match parse_int_text(el, Strictness::Standard) {
				Some(v) if is_min => c.min_i = Some(v),
				Some(v) => c.max_i = Some(v),
				None => vdiag(faults, kid.line, format!("bad schema constraint '{}'", key)),
			},
			"float" => match parse_float_text(el, Strictness::Standard) {
				Some(v) if is_min => c.min_f = Some(v),
				Some(v) => c.max_f = Some(v),
				None => vdiag(faults, kid.line, format!("bad schema constraint '{}'", key)),
			},
			_ => vdiag(faults, kid.line, format!("bad schema constraint '{}'", key)),
		}
	}
	Some(c)
}

/// A schema `default`/`allowed` value re-emitted as an inline value (minimal
/// quoting, array elements joined by ", "). None for empty or raw - neither has
/// a usable one-line form. Used by the generator, not the validator.
fn emit_value_inline(v: &Value) -> Option<String> {
	match v {
		Value::Cell(els) => Some(els.iter().map(emit_element).collect::<Vec<_>>().join(", ")),
		_ => None,
	}
}

// ---------------------------------------------------------------------------
// Schema-driven generation: a schema + the Writer -> a commented starter config.
// ---------------------------------------------------------------------------

fn allowed_join(a: &AllowedSet) -> String {
	match a {
		AllowedSet::Ints(v) => v
			.iter()
			.map(|x| x.to_string())
			.collect::<Vec<_>>()
			.join(", "),
		AllowedSet::Floats(v) => v
			.iter()
			.map(|x| x.to_string())
			.collect::<Vec<_>>()
			.join(", "),
		AllowedSet::Bools(v) => v
			.iter()
			.map(|x| if *x { "true" } else { "false" }.to_string())
			.collect::<Vec<_>>()
			.join(", "),
		AllowedSet::Dates(v) => v
			.iter()
			.map(|x| x.to_string())
			.collect::<Vec<_>>()
			.join(", "),
		AllowedSet::Strings(v) => v.join(", "),
	}
}

/// The `# type, ...` annotation line summarizing a constraint, ASCII only.
fn gen_annotation(c: &Constraint, tyname: &str) -> String {
	let mut parts: Vec<String> = vec![tyname.to_string()];
	if let Some(a) = &c.allowed {
		parts.push(format!("one of: {}", allowed_join(a)));
	} else if c.min_i.is_some() || c.max_i.is_some() {
		parts.push(match (c.min_i, c.max_i) {
			(Some(lo), Some(hi)) => format!("{}-{}", lo, hi),
			(Some(lo), None) => format!(">= {}", lo),
			(None, Some(hi)) => format!("<= {}", hi),
			(None, None) => String::new(), // guarded above; keep the map total
		});
	} else if c.min_f.is_some() || c.max_f.is_some() {
		parts.push(match (c.min_f, c.max_f) {
			(Some(lo), Some(hi)) => format!("{}-{}", lo, hi),
			(Some(lo), None) => format!(">= {}", lo),
			(None, Some(hi)) => format!("<= {}", hi),
			(None, None) => String::new(), // guarded above; keep the map total
		});
	}
	if let Some((lo, hi)) = c.repeat {
		parts.push(if lo == hi {
			format!("repeat {}", lo)
		} else {
			format!("repeat {}-{}", lo, hi)
		});
	}
	if c.required {
		parts.push("required".to_string());
	}
	parts.join(", ")
}

/// A default carrying a literal newline cannot sit on a value line; the quoted
/// escaped spelling reads back to the same string.
fn gen_default_text(v: &str) -> String {
	if !v.contains('\n') {
		return v.to_string();
	}
	let mut s = String::from("\"");
	for ch in v.chars() {
		match ch {
			'\\' => s.push_str("\\\\"),
			'"' => s.push_str("\\\""),
			'\n' => s.push_str("\\n"),
			'\t' => s.push_str("\\t"),
			c => s.push(c),
		}
	}
	s.push('"');
	s
}

/// Emit a commented, typed starter config from a schema (`shcl init --schema`).
/// Paths that must exist (required, or a repeat lower bound of 1+) are live
/// (their `default`, or an empty value); optional paths are commented out so
/// the file is valid and minimal as-is. A must-exist wildcard path whose
/// parent gets materialized by another live line is generated too, in dotted
/// form - otherwise the file would fail the very schema that produced it -
/// and remaining wildcard or `[#N]` paths (which cannot be materialized) are
/// listed in a trailing comment block. The output always loads clean and
/// validates clean against its schema, except a repeat lower bound of 2+
/// (identical generated lines would merge, so the shortfall is reported).
/// A footer naming the format and pointing at the spec is written last unless
/// `no_banner`; the flag is negative so leaving it alone writes the footer.
/// Err = schema faults (V09x), same as `validate`/`check --schema`.
pub fn generate(schema: &Document, no_banner: bool) -> Result<String, Vec<Diagnostic>> {
	// Generation lays the whole schema out, so unlike validation it has no
	// safe partial mode: any fault fails it.
	let (def, faults) = build_schema(schema);
	if !faults.is_empty() {
		return Err(faults);
	}
	let (cons, cuts) = expand_mounts(&def);
	if cons.len() >= GEN_MAX_FIELDS {
		return Err(vec![Diagnostic {
			line: 0,
			severity: Severity::Error,
			code: "V096",
			message: format!(
				"schema expands past {} fields; fragments mounted at more than one path multiply",
				GEN_MAX_FIELDS
			),
		}]);
	}
	let must_exist = |c: &Constraint| c.required || matches!(c.repeat, Some((lo, _)) if lo >= 1);
	let has_wild = |c: &Constraint| {
		c.segs
			.iter()
			.any(|s| matches!(s.selector, Some(Selector::Wildcard)))
	};
	// `[#N]` needs a pre-existing instance and its `#` would start a comment
	// on a binding line; a path with a literal newline cannot be written at
	// all. Both go to the trailing note instead of emitting a broken line.
	// A path deeper than a document may nest cannot be generated either: the
	// line would draw E016 on the way back in.
	let unwritable = |c: &Constraint| {
		c.segs.len() > MAX_DEPTH
			|| c.segs
				.iter()
				.any(|s| matches!(s.selector, Some(Selector::ByIndex(_))) || s.star)
			|| c.path.contains('\n')
	};
	// Live concrete paths materialize instances; decide which must-exist
	// wildcards get filled (their first-wildcard parent chain is a prefix of
	// some live path). Fixpoint: a fill can materialize another's parent.
	fn names_of(segs: &[Segment]) -> Vec<&str> {
		segs.iter().map(|s| s.name.as_str()).collect()
	}
	let mut live: Vec<Vec<&str>> = cons
		.iter()
		.filter(|c| !has_wild(c) && !unwritable(c) && must_exist(c))
		.map(|c| names_of(&c.segs))
		.collect();
	let mut fill = vec![false; cons.len()];
	loop {
		let mut changed = false;
		for (i, c) in cons.iter().enumerate() {
			if fill[i] || !has_wild(c) || unwritable(c) || !must_exist(c) {
				continue;
			}
			let Some(k) = c
				.segs
				.iter()
				.position(|s| matches!(s.selector, Some(Selector::Wildcard)))
			else {
				continue;
			};
			let parent = names_of(&c.segs[..k + 1]);
			if live
				.iter()
				.any(|p| p.len() >= parent.len() && p[..parent.len()] == parent[..])
			{
				fill[i] = true;
				live.push(names_of(&c.segs));
				changed = true;
			}
		}
		if !changed {
			break;
		}
	}
	let mut out = String::new();
	let mut wild: Vec<(String, String)> = Vec::new();
	let mut first = true;
	for (i, c) in cons.iter().enumerate() {
		let tyname = c.ty.clone().unwrap_or_else(|| "any".to_string());
		if unwritable(c) || (has_wild(c) && !fill[i]) {
			wild.push((c.path.replace('\n', "\\n"), tyname));
			continue;
		}
		if !first {
			out.push('\n');
		}
		first = false;
		if let Some(d) = &c.desc {
			for line in d.split('\n') {
				out.push_str("# ");
				out.push_str(line);
				out.push('\n');
			}
		}
		out.push_str("# ");
		// The annotation is a comment: a newline smuggled in via an allowed
		// string value must not break out of it.
		out.push_str(&gen_annotation(c, &tyname).replace('\n', "\\n"));
		out.push('\n');
		// A filled wildcard emits in dotted form, targeting the first (the
		// materialized) instance. Rebuilt from the parsed segments, not by
		// cutting text out of the path: the same path can be written several
		// ways, and only the segments say what it means.
		let path = if fill[i] {
			gen_path_text(&c.segs)
		} else {
			c.path.clone()
		};
		let prefix = if must_exist(c) { "" } else { "#" };
		match &c.default_text {
			Some(v) => out.push_str(&format!("{}{}: {}\n", prefix, path, gen_default_text(v))),
			None => out.push_str(&format!("{}{}:\n", prefix, path)),
		}
	}
	// Cycle-cut mounts last: their "type" column names the fragment that
	// belongs at the path.
	wild.extend(cuts);
	if !wild.is_empty() {
		if !first {
			out.push('\n');
		}
		out.push_str("# Paths needing an instance name (not generated):\n");
		for (p, t) in &wild {
			out.push_str(&format!("#   {}   {}\n", p, t));
		}
	}
	if !no_banner {
		if !out.is_empty() {
			out.push('\n');
		}
		out.push_str(GEN_BANNER);
	}
	Ok(out)
}

/// Ceiling on how many fields one schema may expand to. Fragments that mount
/// each other at more than one path multiply, so a short schema can otherwise
/// ask for more output than the machine can hold; past this the generator
/// reports a schema fault rather than running until something breaks.
const GEN_MAX_FIELDS: usize = 10_000;

/// Footer telling whoever opens the generated file what the format is and
/// where its spec lives. It is output, so every binding emits these bytes
/// exactly; the Legal line names SHCL as its subject so it cannot be read as
/// a claim over the config it sits in.
const GEN_BANNER: &str = "\
#
# This config file format is SHCL.
# \"Simple Hierarchical Config Language\"
#    Home     https://github.com/jim-collier/shcl
#    Syntax   https://github.com/jim-collier/shcl/blob/main/project/spec.md
#    Legal    SHCL is Copyright © 2026 Jim Collier. License: MIT. No warranty.
#
";

/// Render parsed segments back as a dotted path, dropping wildcard selectors
/// (a generated line targets the one instance it materializes) and quoting a
/// name that needs it, so the result is a path the scanner reads back the same.
fn gen_path_text(segs: &[Segment]) -> String {
	let mut out = String::new();
	for (i, s) in segs.iter().enumerate() {
		if i > 0 {
			out.push('.');
		}
		if s.star {
			out.push('*');
		} else {
			out.push_str(&emit_name(&s.name));
		}
		match &s.selector {
			Some(Selector::ByValue(v)) => {
				out.push('[');
				out.push_str(v);
				out.push(']');
			}
			Some(Selector::ByIndex(k)) => {
				out.push_str(&format!("[#{}]", k));
			}
			Some(Selector::Wildcard) | None => {}
		}
	}
	out
}

/// Inline every fragment mount into a flat constraint list, depth-first in
/// schema order, each field's path and segments prefixed by its mount's. A
/// mount whose fragment is already expanding (a cycle) stops there and is
/// returned as (path, fragment name) for the trailing not-generated block.
fn expand_mounts(def: &SchemaDef) -> (Vec<Constraint>, Vec<(String, String)>) {
	fn go(
		list: &[Constraint],
		def: &SchemaDef,
		at: Option<(&str, &[Segment])>,
		stack: &mut Vec<String>,
		out: &mut Vec<Constraint>,
		cuts: &mut Vec<(String, String)>,
	) {
		for c in list {
			let mut cc = c.clone();
			if let Some((p, s)) = at {
				cc.path = format!("{}.{}", p, c.path);
				let mut segs = s.to_vec();
				segs.extend(c.segs.iter().cloned());
				cc.segs = segs;
			}
			let path = cc.path.clone();
			let segs = cc.segs.clone();
			if out.len() >= GEN_MAX_FIELDS {
				return;
			}
			out.push(cc);
			if let Some(fr) = &c.inherits {
				// A chain long enough to outrun the stack, or a mount that
				// re-enters, stops here and is noted instead of expanded.
				if stack.iter().any(|x| x == fr) || stack.len() >= MAX_DEPTH {
					cuts.push((path.replace('\n', "\\n"), fr.clone()));
				} else if let Some(fcs) = def.frags.get(fr) {
					stack.push(fr.clone());
					go(fcs, def, Some((&path, &segs)), stack, out, cuts);
					stack.pop();
				}
			}
		}
	}
	let mut out: Vec<Constraint> = Vec::new();
	let mut cuts: Vec<(String, String)> = Vec::new();
	let mut stack: Vec<String> = Vec::new();
	go(&def.cons, def, None, &mut stack, &mut out, &mut cuts);
	(out, cuts)
}

/// Two-row Levenshtein; powers the "did you mean" prose (never the code).
fn edit_distance(a: &str, b: &str) -> usize {
	let a: Vec<char> = a.chars().collect();
	let b: Vec<char> = b.chars().collect();
	let mut prev: Vec<usize> = (0..=b.len()).collect();
	let mut cur = vec![0usize; b.len() + 1];
	for i in 1..=a.len() {
		cur[0] = i;
		for j in 1..=b.len() {
			let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
			cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
		}
		std::mem::swap(&mut prev, &mut cur);
	}
	prev[b.len()]
}

impl Document {
	/// Validate this document against a schema document (itself plain SHCL -
	/// spec.md "Schema validation"). Empty result = the document conforms.
	/// Diagnostic lines are document lines (0 = document scope); schema faults
	/// (V09x, schema-file lines) come first, and the surviving constraints
	/// still check the document. Only the unknown-field sweep needs a
	/// fault-free schema: a dropped constraint would turn the fields it
	/// declared into false unknowns, so that check skips rather than misfire.
	pub fn validate(&self, schema: &Document) -> Vec<Diagnostic> {
		let (def, faults) = build_schema(schema);
		let schema_ok = faults.is_empty();
		let mut out = faults;
		for c in &def.cons {
			self.v_check(c, &def, &mut out);
		}
		if schema_ok {
			self.v_unknown(&def, &mut out);
		}
		out
	}

	// Resolution contexts: the whole document for a plain path; each enclosing
	// instance for the part of a path after a wildcard. required/repeat evaluate
	// per context (anchor line 0 = document scope), so `server[*].port` +
	// required means a port under EACH server - vacuously true with no servers.
	fn v_contexts(
		&self,
		start: Vec<usize>,
		segs: &[Segment],
		anchor: usize,
		out: &mut Vec<(usize, Vec<usize>)>,
	) {
		let mut cur = start;
		for (i, seg) in segs.iter().enumerate() {
			let mut next: Vec<usize> = Vec::new();
			for &n in &cur {
				if seg.star {
					next.extend(self.arena[n].children.iter().copied());
				} else {
					next.extend(self.children_named(n, &seg.name));
				}
			}
			if seg.star {
				// Name wildcard: same per-instance split as `[*]`, any child name.
				let rest = &segs[i + 1..];
				if rest.is_empty() {
					out.push((anchor, next));
				} else {
					for inst in next {
						let line = self.arena[inst].line;
						self.v_contexts(vec![inst], rest, line, out);
					}
				}
				return;
			}
			match &seg.selector {
				None => cur = next,
				Some(Selector::ByValue(v)) => {
					let want = apply_escapes(v);
					cur = next
						.into_iter()
						.filter(|&c| disp_key(&self.arena[c].value) == want)
						.collect();
				}
				Some(Selector::ByIndex(k)) => {
					cur = index_usize(*k)
						.and_then(|i| next.get(i))
						.map(|&c| vec![c])
						.unwrap_or_default();
				}
				Some(Selector::Wildcard) => {
					let rest = &segs[i + 1..];
					if rest.is_empty() {
						out.push((anchor, next));
					} else {
						for inst in next {
							let line = self.arena[inst].line;
							self.v_contexts(vec![inst], rest, line, out);
						}
					}
					return;
				}
			}
		}
		out.push((anchor, cur));
	}

	fn v_check(&self, c: &Constraint, def: &SchemaDef, out: &mut Vec<Diagnostic>) {
		let mut mounted = std::collections::HashSet::new();
		self.v_check_from(c, def, ROOT, 0, out, &mut mounted);
	}

	// A mounted fragment's fields run per resolved node, right after that
	// node's own checks, in fragment order - depth-first, so diagnostic order
	// stays derivable. Termination is structural: every mount descends at
	// least one document level, and the document is finite.
	fn v_check_from(
		&self,
		c: &Constraint,
		def: &SchemaDef,
		start: usize,
		anchor0: usize,
		out: &mut Vec<Diagnostic>,
		mounted: &mut std::collections::HashSet<(String, usize)>,
	) {
		let mut ctxs: Vec<(usize, Vec<usize>)> = Vec::new();
		self.v_contexts(vec![start], &c.segs, anchor0, &mut ctxs);
		for (anchor, found) in &ctxs {
			if c.required && found.is_empty() {
				vdiag(out, *anchor, format!("required path missing: {}", c.path));
			}
			if let Some((lo, hi)) = c.repeat {
				let n = found.len() as u64;
				if n < lo || n > hi {
					vdiag(
						out,
						*anchor,
						format!(
							"instance count out of bounds at '{}': {} not in {}..{}",
							c.path, n, lo, hi
						),
					);
				}
			}
			for &n in found {
				self.v_node(c, n, out);
				if let Some(fr) = &c.inherits
					&& let Some(fcs) = def.frags.get(fr)
				{
					// Two constraints can resolve to the same node and mount the
					// same fragment there. The second mount would repeat the
					// first's work and its diagnostics, and repeating it per
					// level is what makes a recursive schema cost double per
					// document level, so each pair is done once.
					if mounted.insert((fr.clone(), n)) {
						for fc in fcs {
							self.v_check_from(fc, def, n, self.arena[n].line, out, mounted);
						}
					}
				}
			}
		}
	}

	fn v_node(&self, c: &Constraint, n: usize, out: &mut Vec<Diagnostic>) {
		let node = &self.arena[n];
		let line = node.line;
		let kind = c.ty.as_deref();
		let base = kind
			.map(|t| t.strip_suffix("-array").unwrap_or(t))
			.unwrap_or("string");
		let is_array = kind.is_some_and(|t| t.ends_with("-array"));
		let wrong = |out: &mut Vec<Diagnostic>| {
			vdiag(
				out,
				line,
				format!(
					"wrong type at '{}': value is not a valid {}",
					c.path,
					kind.unwrap_or("string")
				),
			);
		};
		match &node.value {
			// Empty passes everything; required already counted it as present.
			Value::Empty => {}
			Value::Raw { content, .. } => {
				// A raw block satisfies `raw` and scalar `string` (any value
				// reads as a string); every other kind is a type miss.
				if kind.is_some() && (base != "raw" && base != "string" || is_array) {
					wrong(out);
					return;
				}
				if let Some(AllowedSet::Strings(set)) = &c.allowed
					&& !set.contains(content)
				{
					vdiag(
						out,
						line,
						format!("value not allowed at '{}': {}", c.path, content),
					);
				}
			}
			Value::Cell(els) => {
				if base == "raw" {
					wrong(out);
					return;
				}
				// A scalar kind on a multi-element value is the array-where-one-
				// scalar-expected miss - except string, which reads arrays.
				if kind.is_some() && !is_array && base != "string" && els.len() > 1 {
					wrong(out);
					return;
				}
				match base {
					"int" => {
						let mut vals: Vec<i64> = Vec::with_capacity(els.len());
						for e in els {
							match parse_int_text(e, self.strictness) {
								Some(v) => vals.push(v),
								None => {
									wrong(out);
									return;
								}
							}
						}
						if let Some(AllowedSet::Ints(set)) = &c.allowed
							&& let Some(i) = vals.iter().position(|v| !set.contains(v))
						{
							vdiag(
								out,
								line,
								format!("value not allowed at '{}': {}", c.path, els[i].text),
							);
						}
						if let Some(lo) = c.min_i
							&& vals.iter().any(|v| *v < lo)
						{
							vdiag(out, line, format!("value below min at '{}'", c.path));
						}
						if let Some(hi) = c.max_i
							&& vals.iter().any(|v| *v > hi)
						{
							vdiag(out, line, format!("value above max at '{}'", c.path));
						}
					}
					"float" => {
						let mut vals: Vec<f64> = Vec::with_capacity(els.len());
						for e in els {
							match parse_float_text(e, self.strictness) {
								Some(v) => vals.push(v),
								None => {
									wrong(out);
									return;
								}
							}
						}
						if let Some(AllowedSet::Floats(set)) = &c.allowed
							&& let Some(i) = vals.iter().position(|v| !set.contains(v))
						{
							vdiag(
								out,
								line,
								format!("value not allowed at '{}': {}", c.path, els[i].text),
							);
						}
						if let Some(lo) = c.min_f
							&& vals.iter().any(|v| *v < lo)
						{
							vdiag(out, line, format!("value below min at '{}'", c.path));
						}
						if let Some(hi) = c.max_f
							&& vals.iter().any(|v| *v > hi)
						{
							vdiag(out, line, format!("value above max at '{}'", c.path));
						}
					}
					"bool" => {
						let mut vals: Vec<bool> = Vec::with_capacity(els.len());
						for e in els {
							match parse_bool_text(&e.text, self.strictness) {
								Some(v) => vals.push(v),
								None => {
									wrong(out);
									return;
								}
							}
						}
						if let Some(AllowedSet::Bools(set)) = &c.allowed
							&& let Some(i) = vals.iter().position(|v| !set.contains(v))
						{
							vdiag(
								out,
								line,
								format!("value not allowed at '{}': {}", c.path, els[i].text),
							);
						}
					}
					"datetime" => {
						let mut vals: Vec<ShclDateTime> = Vec::with_capacity(els.len());
						for e in els {
							match parse_datetime(&e.text) {
								Some(v) => vals.push(v),
								None => {
									wrong(out);
									return;
								}
							}
						}
						if let Some(AllowedSet::Dates(set)) = &c.allowed
							&& let Some(i) = vals.iter().position(|v| !set.contains(v))
						{
							vdiag(
								out,
								line,
								format!("value not allowed at '{}': {}", c.path, els[i].text),
							);
						}
					}
					// string kind or untyped: every element coerces; only the
					// allowed set can fail, in logical-string space.
					_ => {
						if let Some(AllowedSet::Strings(set)) = &c.allowed {
							let bad = els
								.iter()
								.map(|e| apply_escapes(&e.text))
								.find(|s| !set.contains(s));
							if let Some(b) = bad {
								vdiag(
									out,
									line,
									format!("value not allowed at '{}': {}", c.path, b),
								);
							}
						}
					}
				}
			}
		}
	}

	// Unknown-field sweep: a schema path legalizes its name chain and every
	// prefix (selectors ignored). Only the topmost unknown node is reported;
	// its subtree is implied unknown and skipped.
	fn v_unknown(&self, def: &SchemaDef, out: &mut Vec<Diagnostic>) {
		let cons = &def.cons;
		// Chains below a fragment mount only match by descending the mounts.
		let has_mounts = cons.iter().any(|c| c.inherits.is_some());
		let mut legal: std::collections::HashSet<String> = std::collections::HashSet::new();
		// Sibling names per parent chain, built once (schema order): v_suggest
		// used to rebuild every chain per unknown field, which bit hardest on
		// the wholesale-unmatched documents the feature exists for.
		let mut siblings: HashMap<String, Vec<String>> = HashMap::new();
		// Paths with a `*` segment can't live in the exact-chain hash; they
		// match element-wise (a star matches any one name, prefixes included).
		let mut star_pats: Vec<&[Segment]> = Vec::new();
		for c in cons {
			if c.segs.iter().any(|s| s.star) {
				star_pats.push(&c.segs);
			}
			let mut chain = String::new();
			for s in &c.segs {
				if s.star {
					break; // no sibling entry for '*'; deeper chains are pattern-only
				}
				siblings
					.entry(chain.clone())
					.or_default()
					.push(s.name.clone());
				chain_push(&mut chain, &s.name);
				legal.insert(chain.clone());
			}
		}
		let mut stack: Vec<(usize, String, String)> = self.arena[ROOT]
			.children
			.iter()
			.rev()
			.map(|&c| (c, String::new(), String::new()))
			.collect();
		while let Some((n, pchain, pshown)) = stack.pop() {
			let node = &self.arena[n];
			let mut chain = pchain.clone();
			chain_push(&mut chain, &node.name);
			let shown = if pshown.is_empty() {
				node.name.clone()
			} else {
				format!("{}.{}", pshown, node.name)
			};
			let known = legal.contains(&chain)
				|| star_legal(&star_pats, &chain)
				|| (has_mounts && chain_legal(cons, &def.frags, &chain));
			if !known {
				let hint = v_suggest(&siblings, &pchain, &node.name);
				vdiag(out, node.line, format!("unknown field '{}'{}", shown, hint));
				continue;
			}
			for &k in node.children.iter().rev() {
				stack.push((k, chain.clone(), shown.clone()));
			}
		}
	}
}

/// Chain keys join segments length-prefixed (`<len>:<name>`), not with a bare
/// NUL: NUL is legal in a quoted name, so a single field named "x\0y" would
/// impersonate the two-segment path x.y. Same injectivity reasoning as
/// Value::key's cell encoding - and like it, the length unit is each
/// binding's native one (bytes here), because only injectivity matters.
fn chain_push(chain: &mut String, name: &str) {
	chain.push_str(&name.len().to_string());
	chain.push(':');
	chain.push_str(name);
}

/// Decode a chain key back into its segments. Total: bails at the first
/// shape the encoder can't have produced.
fn chain_parts(chain: &str) -> Vec<&str> {
	let mut parts = Vec::new();
	let b = chain.as_bytes();
	let mut i = 0;
	while i < b.len() {
		let mut n = 0usize;
		while i < b.len() && b[i].is_ascii_digit() {
			n = n * 10 + (b[i] - b'0') as usize;
			i += 1;
		}
		if i >= b.len() || b[i] != b':' || i + 1 + n > b.len() {
			break;
		}
		i += 1;
		parts.push(&chain[i..i + n]);
		i += n;
	}
	parts
}

/// Element-wise chain match against the star-bearing schema paths: a `*`
/// segment matches any one name, and every prefix of a path is legal.
fn star_legal(pats: &[&[Segment]], chain: &str) -> bool {
	if pats.is_empty() {
		return false;
	}
	let parts: Vec<&str> = chain_parts(chain);
	pats.iter().any(|p| {
		p.len() >= parts.len()
			&& parts
				.iter()
				.enumerate()
				.all(|(i, seg)| p[i].star || p[i].name == *seg)
	})
}

/// Chain legality through fragment mounts: the general matcher - element-wise
/// like star_legal (stars wild, prefixes legal), and when a mount's whole path
/// matched with chain left over, the remainder is retried against the mounted
/// fragment's fields. Terminates: every descent consumes >= 1 part.
fn chain_legal(cons: &[Constraint], frags: &HashMap<String, Vec<Constraint>>, chain: &str) -> bool {
	let parts: Vec<&str> = chain_parts(chain);
	chain_parts_legal(cons, frags, &parts)
}

fn chain_parts_legal(
	cons: &[Constraint],
	frags: &HashMap<String, Vec<Constraint>>,
	parts: &[&str],
) -> bool {
	for c in cons {
		let n = c.segs.len();
		let k = parts.len().min(n);
		if (0..k).all(|i| c.segs[i].star || c.segs[i].name == parts[i]) {
			if parts.len() <= n {
				return true;
			}
			if let Some(fr) = &c.inherits
				&& let Some(fcs) = frags.get(fr)
				&& chain_parts_legal(fcs, frags, &parts[n..])
			{
				return true;
			}
		}
	}
	false
}

/// Closest legal sibling name (same parent chain, schema order, edit distance
/// <= 2) as "; did you mean 'x'?" - or nothing. Prose only, never contract.
fn v_suggest(siblings: &HashMap<String, Vec<String>>, parent_chain: &str, name: &str) -> String {
	let mut best: Option<(usize, &str)> = None;
	if let Some(names) = siblings.get(parent_chain) {
		for s in names {
			let dist = edit_distance(name, s);
			if dist <= 2 && best.is_none_or(|(bd, _)| dist < bd) {
				best = Some((dist, s.as_str()));
			}
		}
	}
	match best {
		Some((_, n)) => format!("; did you mean '{}'?", n),
		None => String::new(),
	}
}