techy 0.1.0

A fast, extensible LaTeX parser for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
//! The node tree: flat, immutable, index-based storage for a parse result.
//!
//! A [`NodeTree`] holds every node of one parse in a single vector, and a node's
//! children occupy a contiguous block of that vector. Trees are immutable: they come
//! out of a [`NodeTreeBuilder`] (driven by `ParserSession`) and are only read
//! afterwards, through the [`NodeRef`] proxies and [`NodeSlice`] views. A
//! transformation produces a *new* tree; sources, specs, and parsing states are
//! `Arc`-shared, so that stays cheap.
//!
//! [`NodeKind`] is the closed structural taxonomy — `Chars`, `Group`, `Callable`,
//! `Comment`, `List`. It describes shape only: there is no `Custom` variant, and no
//! variant per invocation form (a macro and an environment are both `Callable` nodes,
//! distinguished by their recorded form). Language-specific per-node data is stored in
//! the uniform node ext ([`NodeExt`], minted once at staging by
//! [`Lang::make_node_ext`](crate::core::Lang::make_node_ext)) rather than in new kinds.
//!
//! Kinds with a payload record it on the node, so that reading a tree never needs a
//! registry lookup: [`GroupData`] holds a group's delimiters as written and its
//! optional class, [`CommentData`] a comment's start delimiter, text, and syntactic
//! post-space, and [`CallableData`] everything specific to one invocation (form,
//! spelling, spec, parsed arguments and slots).
//!
//! A callable's children are the concatenation of one contiguous region per *provided*
//! argument, then one per slot; each region holds the syntax-bearing nodes together
//! with comment and whitespace nodes. [`ParsedArguments`] and [`ParsedSlots`] record
//! those regions ([`ChildRegion`]), the nodes each parser designated as the region's
//! content, and the [`ArgumentSpec`](crate::core::specs::ArgumentSpec) an argument was
//! parsed against.
//!
//! Textual payloads are [`TextContent`](crate::source::TextContent): span-backed when
//! parsed — resolved against the carrying node's own source, `node.span().source()` —
//! and owned when synthesized or normalized. [`NodeTree::materialize`] produces a copy
//! whose payloads are all owned. Callable names are always owned, since they carry
//! identity rather than content.

mod arguments;
mod builder;
mod copy;
mod display;
mod invariants;
mod kind;
mod node_ref;
mod slice;
mod tree;

pub use arguments::{
    BodySlotExt, ChildRegion, ContentNodes, ParsedArgument, ParsedArguments, ParsedSlot,
    ParsedSlots, SlotRole,
};
pub use builder::{
    BuildId, NodeBuildError, NodeTreeBuilder, StagedChildView, StagedChildren,
    StagedNodeView, StagedNodes,
};
pub use display::display_tree;
pub use invariants::{validate_tree, TreeViolation, TreeViolationKind};
pub use kind::{CallableData, CommentData, GroupData, NodeKind};
pub use node_ref::{Descendants, NamedAccessError, NodeRef};
pub use slice::{NodeSlice, NodeSliceIter};
pub use tree::{NodeId, NodeTree, TreeTag};

// `NodeData` is deliberately NOT re-exported publicly ([§dd-dr:public-visibility-sweep]
// Theme C): it is crate-internal — zero public signatures use it; `NodeRef` is the
// read API. The crate-internal alias below serves in-crate consumers of the flat
// storage: the latexlike span-tiling law checker's payload pins (test), and the tree
// serialization driver, which walks the storage-order node slice.
pub(crate) use tree::NodeData;
// Crate-internal subtree copying, shared with `crate::extract`'s builder helpers,
// and the content-parent mapping parameter of the transform driver's record
// translation (`restage_node_with_content_mapping`).
pub(crate) use copy::{copy_subtree_into, ContentParentMapping};
// The span-tiling law's test oracle: pub(crate) per [§dd-dr:tree-validation]'s amendment —
// `validate_tree` is the one public checker; the panicking byte-accounting extras
// are an in-crate test utility (all callers are test code, hence `cfg(test)`).
#[cfg(test)]
pub(crate) use invariants::check_tree_invariants;

use crate::state::{Lang, NodeExtTypes};

/// The uniform node ext type of a language, minted by
/// [`Lang::make_node_ext`](crate::core::Lang::make_node_ext).
pub type NodeExt<L> = <<L as Lang>::NodeExts as NodeExtTypes>::NodeExt;
/// The parsed-argument ext type of a language (attached to [`ParsedArgument`] records).
pub type ArgumentExt<L> = <<L as Lang>::NodeExts as NodeExtTypes>::ArgumentExt;
/// The parsed-slot ext type of a language (attached to [`ParsedSlot`] records).
pub type SlotExt<L> = <<L as Lang>::NodeExts as NodeExtTypes>::SlotExt;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scopes::ScopeStack;
    use crate::source::{Source, SourceSpan, Span, TextContent};
    use crate::spec::{ArgumentParser, ArgumentSpec, CallableSpec, StdCallableSpec};
    use crate::state::{Lang, ParsingState, TrivialLang, StateData};
    use crate::token::{
        CommandRules, CommentRules, ForbiddenCharsRules, GroupRule, GroupRules,
        ParagraphRules, SpecialsRules, TokenRules, WhitespaceRules,
    };
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec;
    use alloc::vec::Vec;
    use core::ops::Range;

    #[derive(Debug, Clone, Copy)]
    struct PlainLang;
    impl TrivialLang for PlainLang {} // GroupTypeId / CallableTypeId = u32

    const GT_BRACE: u32 = 0;
    const CT_MACRO: u32 = 0;
    const CT_ENVIRONMENT: u32 = 1;

    // `Features = AllLangFeatures` (all test languages here declare it): the plain
    // block literals below only typecheck once the per-feature stores normalize to
    // the blocks themselves.
    fn min_rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
    ) -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules::empty(),
            paragraphs: ParagraphRules { enabled: false },
            groups: GroupRules {
                enabled: true,
                rules: vec![Arc::new(GroupRule {
                    group_type: GT_BRACE,
                    open: "{".into(),
                    close: "}".into(),
                })],
                temporary: Vec::new(),
                expecting_close: None,
            },
            commands: CommandRules {
                enabled: true,
                rules: Vec::new(),
            },
            comments: CommentRules {
                enabled: true,
                rules: Vec::new(),
            },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    fn state<
        L: Lang<StateExt = (), GroupTypeId = u32, Features = crate::state::AllLangFeatures>,
    >() -> Arc<ParsingState<L>> {
        Arc::new(ParsingState::new(StateData {
            rules: min_rules(),
            scopes: ScopeStack::new(),
            mode: Default::default(),
            ext: (),
        }))
    }

    fn spanned(source: &Arc<Source>, range: Range<usize>) -> SourceSpan {
        SourceSpan::new(source, range)
    }

    fn brace_group<L: Lang<GroupTypeId = u32>>(open: Range<usize>, close: Range<usize>) -> GroupData<L> {
        GroupData::new(
            GT_BRACE,
            TextContent::Spanned(Span::new(open.start, open.end)),
            TextContent::Spanned(Span::new(close.start, close.end)),
        )
    }

    /// Stand-in for the standard argument parsers — never invoked; the tests here
    /// hand-build their trees.
    #[derive(Debug)]
    struct StubParser;
    impl<L: Lang> ArgumentParser<L> for StubParser {
        fn parse_argument(
            &self,
            _cx: &mut crate::constructs::ParseContext<'_, '_, L>,
            _spec: &ArgumentSpec<L>,
        ) -> crate::constructs::ConstructParserResult<
            L,
            Option<crate::spec::ParsedArgumentNodes<L>>,
        > {
            Ok(None)
        }
    }

    fn brace_arg_spec<L: Lang<GroupTypeId = u32>>() -> Arc<ArgumentSpec<L>> {
        Arc::new(ArgumentSpec::new_unnamed(Arc::new(StubParser)))
    }

    /// Compile-time proof of the thread-safety contract: trees,
    /// states, and spec handles are `Send + Sync`, so a tree parsed on one thread can be
    /// handed to another.
    #[test]
    fn trees_states_and_specs_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<NodeTree<PlainLang>>();
        assert_send_sync::<ParsingState<PlainLang>>();
        assert_send_sync::<Arc<dyn CallableSpec<PlainLang>>>();
    }

    /// Builds the running example: `x\frac{a}{b} % note` as
    /// List [ Chars"x", Callable\frac(Group(Chars"a"), Group(Chars"b")), Chars" ",
    /// Comment" note" ]. The callable's post-space is the trigger token's own —
    /// empty here, `{` follows the name directly — so the space before the comment is
    /// sibling content (whitespace invariant 3).
    fn example_tree() -> NodeTree<PlainLang> {
        let source: Arc<Source> = Arc::new(Source::new(r"x\frac{a}{b} % note"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let x = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();

        let a_chars =
            b.add(NodeKind::chars(Span::new(7, 8)), spanned(&source, 7..8), st.clone(), vec![], (), ()).unwrap();
        let a_group = b.add(
            NodeKind::group(brace_group(6..7, 8..9)),
            spanned(&source, 6..9),
            st.clone(),
            vec![a_chars], (), (),
        ).unwrap();
        let b_chars =
            b.add(NodeKind::chars(Span::new(10, 11)), spanned(&source, 10..11), st.clone(), vec![], (), ()).unwrap();
        let b_group = b.add(
            NodeKind::group(brace_group(9..10, 11..12)),
            spanned(&source, 9..12),
            st.clone(),
            vec![b_chars], (), (),
        ).unwrap();

        let arg_specs = [brace_arg_spec(), brace_arg_spec()];
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: arg_specs.to_vec(), ..Default::default() });
        let frac = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "frac".into(),
                spec,
                arguments: vec![
                    ParsedArgument::provided(
                        arg_specs[0].clone(),
                        ChildRegion::new(0..1, ContentNodes::InChildrenOf(a_group, 0..1)),
                        (),
                    ),
                    ParsedArgument::provided(
                        arg_specs[1].clone(),
                        ChildRegion::new(1..2, ContentNodes::InChildrenOf(b_group, 0..1)),
                        (),
                    ),
                ]
                .into(),
                slots: ParsedSlots::empty(),
                // The trigger token's own syntactic post-space: empty (`{` follows).
                invocation_syntax: (),
            }),
            spanned(&source, 1..12),
            st.clone(),
            vec![a_group, b_group], (), (),
        ).unwrap();

        let ws =
            b.add(NodeKind::chars(Span::new(12, 13)), spanned(&source, 12..13), st.clone(), vec![], (), ()).unwrap();
        let comment = b.add(
            // start "%" + content " note" + empty post_space (end of input).
            NodeKind::comment(Span::new(13, 14), Span::new(14, 19), Span::empty(19)),
            spanned(&source, 13..19),
            st.clone(),
            vec![], (), (),
        ).unwrap();

        let root = b.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            st.clone(),
            vec![x, frac, ws, comment], (), (),
        ).unwrap();
        b.finish(root).unwrap()
    }

    #[test]
    fn example_tree_passes_the_invariant_checker() {
        // Exercises the checker's callable path (children-block contiguity, post-space
        // suffix, region tiling, InChildrenOf content designations) ahead of 6.4's
        // parser-produced callables.
        check_tree_invariants(&example_tree());
    }

    #[test]
    fn tree_structure_and_accessors() {
        let tree = example_tree();
        let root = tree.root();
        assert!(root.is_list());
        assert_eq!(root.child_count(), 4);
        assert_eq!(tree.node_count(), 9);

        let x = root.child(0).unwrap();
        assert_eq!(x.chars(), Some("x"));
        assert_eq!(x.span_content(), "x");
        assert!(x.comment().is_none());

        let frac = root.child(1).unwrap();
        assert!(frac.is_callable());
        assert_eq!(frac.name(), Some("frac"));
        assert_eq!(frac.callable_type(), Some(CT_MACRO));
        assert_eq!(frac.span_content(), r"\frac{a}{b}");
        assert!(frac.spec().is_some());

        let comment = root.child(3).unwrap();
        let data = comment.comment().unwrap();
        assert_eq!(data.content.resolve(comment.source()), " note");
        assert_eq!(data.start.resolve(comment.source()), "%");
        assert_eq!(data.post_space.resolve(comment.source()), "");
        assert!(comment.chars().is_none());

        assert!(root.child(4).is_none());
        // Out-of-range must hold for indices past u32 too: `1 << 32` truncates to 0
        // under an `as u32` cast and would wrongly return child 0. (checked_shl keeps
        // this compilable on 32-bit targets, where such indices don't exist.)
        if let Some(big) = 1usize.checked_shl(32) {
            assert!(root.child(big).is_none());
        }
        assert!(root.child(usize::MAX).is_none());
        // children() iterates in order:
        let kinds: Vec<bool> = root.children().iter().map(|c| c.is_callable()).collect();
        assert_eq!(kinds, [false, true, false, false]);
    }

    #[test]
    fn slice_answers_sibling_runs_and_rejects_everything_else() {
        // Storage layout of `example_tree()` (breadth-first): 0 root List;
        // 1..5 root's children (x, \frac, ws, comment); 5..7 \frac's children
        // (the two argument groups); 7..8 a-group's child; 8..9 b-group's child.
        let tree = example_tree();
        let root = tree.root();
        let frac = root.child(1).unwrap();

        // Round trip: every accessor-handed range validates back to the same run.
        for range in [
            root.children().range(),
            frac.children().range(),
            frac.argument_nodes(0).unwrap().range(),
            frac.argument_content_nodes(0).unwrap().range(),
            frac.argument_content_nodes(1).unwrap().range(),
        ] {
            let run = tree.slice(range.clone()).expect("accessor range is a sibling run");
            assert_eq!(run.range(), range);
        }

        // Sub-runs of a children block are sibling runs too.
        assert!(tree.slice(2..4).is_some());
        assert!(tree.slice(5..6).is_some());

        // The root has no siblings: 0..1 is the only non-empty run containing it.
        assert_eq!(tree.slice(0..1).unwrap().range(), 0..1);
        assert!(tree.slice(0..2).is_none());
        assert!(tree.slice(0..5).is_none());

        // In-bounds empty runs are real values (accessors hand them out).
        for at in [0u32, 3, 9] {
            let empty = tree.slice(at..at).expect("in-bounds empty range");
            assert!(empty.is_empty());
        }

        // Cross-parent ranges: contiguous in storage, but not one parent's children.
        assert!(tree.slice(4..6).is_none()); // root's last child + \frac's first
        assert!(tree.slice(6..8).is_none()); // \frac's last child + a-group's child
        assert!(tree.slice(7..9).is_none()); // a-group's child + b-group's child

        // Out of bounds and inverted ranges.
        assert!(tree.slice(8..10).is_none());
        assert!(tree.slice(9..10).is_none());
        assert!(tree.slice(10..10).is_none()); // empty, but out of bounds
        #[allow(clippy::reversed_empty_ranges)]
        {
            assert!(tree.slice(4..2).is_none());
        }
    }

    #[test]
    fn argument_access() {
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();

        // Region nodes: the argument's full syntactic extent (here just the group).
        let region0: Vec<_> = frac.argument_nodes(0).unwrap().iter().collect();
        assert_eq!(region0.len(), 1);
        let arg0 = region0[0];
        assert!(arg0.is_group());
        assert_eq!(arg0.group_type(), Some(GT_BRACE));
        assert_eq!(arg0.group_delimiters(), Some(("{", "}")));
        assert_eq!(arg0.span_content(), "{a}");

        // Content nodes: what the parser designated — the group's children, braces
        // excluded; read back as a plain node range, no unwrap heuristics.
        let content0: Vec<_> = frac.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(content0.len(), 1);
        assert_eq!(content0[0].chars(), Some("a"));

        let args = frac.arguments().unwrap();
        // Resolved records are global node-index ranges (the NodeData.children
        // coordinate system), readable through NodeTree::nodes_in:
        let region1 = args.get(1).unwrap().region.as_ref().unwrap();
        assert!(region1.is_resolved());
        assert_eq!(tree.nodes_in(region1.children()).next().unwrap().span_content(), "{b}");
        // The content parent is the group node (delimiter queries, empty-content anchor):
        assert_eq!(tree.node(region1.content_parent()).span_content(), "{b}");

        assert!(frac.argument_nodes(2).is_none());
        assert_eq!(args.len(), 2);
        assert!(args.iter().all(|arg| arg.is_provided()));
        // Every parsed argument knows the spec it was parsed against:
        assert!(args.iter().all(|arg| Arc::strong_count(&arg.spec) >= 2));

        // Non-callables answer None everywhere:
        let x = tree.root().child(0).unwrap();
        assert!(x.argument_nodes(0).is_none());
        assert!(x.name().is_none());
        assert!(x.arguments().is_none());
    }

    /// `staged()` is the non-panicking companion of the resolved-only accessors:
    /// it answers the staged coordinates on a freshly constructed region and `None`
    /// on a region read from a finished tree.
    #[test]
    fn staged_accessor_mirrors_resolution_state() {
        // Freshly constructed regions are staged:
        let region = ChildRegion::new(0..3, ContentNodes::InRegion(1..2));
        assert!(!region.is_resolved());
        let (children, content) = region.staged().unwrap();
        assert_eq!(children.clone(), 0..3);
        assert!(matches!(content, ContentNodes::InRegion(range) if range.clone() == (1..2)));
        let single = ChildRegion::single(4);
        assert_eq!(single.staged().unwrap().0.clone(), 4..5);

        // Regions read from a finished tree are resolved: `staged()` answers `None`.
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();
        let region0 = frac.arguments().unwrap().get(0).unwrap().region.as_ref().unwrap().clone();
        assert!(region0.is_resolved());
        assert!(region0.staged().is_none());
    }

    /// Pins the documented panic of the resolved-only accessors on a still-staged
    /// region — a register-load-bearing contract: the guide's Panics list and
    /// each accessor's Panics section promise exactly this behavior.
    #[test]
    #[should_panic(expected = "child region still staged")]
    fn resolved_only_accessor_panics_on_a_staged_region() {
        let region = ChildRegion::new(0..3, ContentNodes::InRegion(1..2));
        let _ = region.children();
    }

    #[test]
    fn absent_marker_and_named_arguments() {
        // \section*{t}-shaped: star marker provided (a Chars node — pylatexenc behavior),
        // optional arg absent, one group arg. All argument specs are named.
        let source: Arc<Source> = Arc::new(Source::new(r"\section*{t}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let star =
            b.add(NodeKind::chars(Span::new(8, 9)), spanned(&source, 8..9), st.clone(), vec![], (), ()).unwrap();
        let t = b.add(NodeKind::chars(Span::new(10, 11)), spanned(&source, 10..11), st.clone(), vec![], (), ()).unwrap();
        let title = b.add(
            NodeKind::group(brace_group(9..10, 11..12)),
            spanned(&source, 9..12),
            st.clone(),
            vec![t], (), (),
        ).unwrap();

        let star_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "star"));
        let placement_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "placement"));
        let title_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "title"));
        let spec: Arc<dyn CallableSpec<PlainLang>> = Arc::new(StdCallableSpec {
            arguments: vec![star_spec.clone(), placement_spec.clone(), title_spec.clone()],
            ..Default::default()
        });
        let section = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "section".into(),
                spec,
                arguments: vec![
                    ParsedArgument::provided(star_spec, ChildRegion::single(0), ()),
                    ParsedArgument::absent(placement_spec),
                    ParsedArgument::provided(
                        title_spec,
                        ChildRegion::new(1..2, ContentNodes::InChildrenOf(title, 0..1)),
                        (),
                    ),
                ]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![star, title], (), (),
        ).unwrap();
        let tree = b.finish(section).unwrap();

        let node = tree.root();
        // The provided marker is an ordinary Chars child node and counts as its own
        // content (star-as-content convention); the absent optional has an entry but no
        // region — it consumed nothing.
        assert_eq!(node.argument_content_nodes(0).unwrap().iter().next().unwrap().chars(), Some("*"));
        assert!(node.argument_nodes(1).is_none());
        assert_eq!(node.argument_nodes(2).unwrap().iter().next().unwrap().span_content(), "{t}");

        let args = node.arguments().unwrap();
        assert!(args.get(0).unwrap().is_provided());
        assert!(!args.get(1).unwrap().is_provided());
        assert!(args.get(1).unwrap().region.is_none());

        // Region-level content (the marker): the content parent is the callable itself.
        let star_region = args.get(0).unwrap().region.as_ref().unwrap();
        assert_eq!(star_region.content_parent(), node.id());
        assert_eq!(star_region.children(), star_region.content_range());

        // By-name access — absent arguments keep their spec, so "absent" and "no such
        // argument" stay distinguishable:
        let title_region = args.get_named("title").unwrap().region.as_ref().unwrap();
        assert_eq!(
            tree.nodes_in(title_region.children()).next().unwrap().span_content(),
            "{t}"
        );
        assert!(!args.get_named("placement").unwrap().is_provided());
        assert!(args.get_named("nonsense").is_none());
    }

    #[test]
    fn slots_and_body() {
        // An environment-shaped callable: one body slot (a List child after no args).
        let source: Arc<Source> = Arc::new(Source::new(r"\begin{it}hi\end{it}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let hi = b.add(NodeKind::chars(Span::new(10, 12)), spanned(&source, 10..12), st.clone(), vec![], (), ()).unwrap();
        let body = b.add(NodeKind::list(), spanned(&source, 10..12), st.clone(), vec![hi], (), ()).unwrap();

        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec::default());
        let env = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_ENVIRONMENT,
                name: "it".into(),
                spec,
                arguments: ParsedArguments::empty(),
                // The slot record is minted by the driving parser and carries its own
                // name (record-level slots, July 2026 slots session).
                slots: vec![ParsedSlot::new(
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(body, 0..1)),
                    "body",
                    SlotRole::Content,
                    (),
                )]
                .into(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![body], (), (),
        ).unwrap();
        let tree = b.finish(env).unwrap();

        let node = tree.root();
        // The wrapper node: the body `List`, exposed as the slot's content parent.
        let body = node.slot_content_parent(0).unwrap();
        assert!(body.is_list());
        assert_eq!(body.child_count(), 1);
        assert_eq!(body.child(0).unwrap().chars(), Some("hi"));
        assert!(node.slot_content_parent(1).is_none());
        // Slot content reads as a plain node range — the body List's children;
        // `body()` is the same nodes for slot 0:
        let content: Vec<_> = node.slot_content_nodes(0).unwrap().iter().collect();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0].chars(), Some("hi"));
        let body_nodes: Vec<_> = node.body().unwrap().iter().collect();
        assert_eq!(body_nodes.len(), 1);
        assert_eq!(body_nodes[0].id(), content[0].id());
        let slots = node.slots().unwrap();
        assert_eq!(slots.len(), 1);
        // Global layout: env = 0, body List = 1, "hi" chars = 2.
        assert_eq!(slots.get_named("body").unwrap().region.children(), 1..2);
        assert_eq!(slots.get_named("body").unwrap().region.content_range(), 2..3);
    }

    /// A slot whose content sits directly among the callable's children
    /// (`ContentNodes::InRegion`): there is no wrapper node, and `slot_content_parent`
    /// reports that as `None` — never the callable itself, which would send naive
    /// recursive walkers into a loop — while the content accessors work unchanged.
    #[test]
    fn region_level_slot_content_has_no_content_parent() {
        let source: Arc<Source> = Arc::new(Source::new("hi"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let hi = b.add(NodeKind::chars(Span::new(0, 2)), spanned(&source, 0..2), st.clone(), vec![], (), ()).unwrap();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec::default());
        let env = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_ENVIRONMENT,
                name: "it".into(),
                spec,
                arguments: ParsedArguments::empty(),
                slots: vec![ParsedSlot::new(ChildRegion::single(0), "body", SlotRole::Content, ())]
                    .into(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![hi], (), (),
        ).unwrap();
        let tree = b.finish(env).unwrap();

        let node = tree.root();
        // The record itself still anchors the content at the callable:
        let region = &node.slots().unwrap().get(0).unwrap().region;
        assert_eq!(region.content_parent(), node.id());
        // ... but the read API reports "no wrapper node" instead of the callable:
        assert!(node.slot_content_parent(0).is_none());
        let body: Vec<_> = node.body().unwrap().iter().collect();
        assert_eq!(body.len(), 1);
        assert_eq!(body[0].chars(), Some("hi"));
    }

    /// Every id carries its tree layout's tag ([`TreeTag`]), in every build: using an
    /// id minted by one tree on another trips [`NodeTree::node`]'s own-tree assertion
    /// instead of silently resolving to an unrelated node.
    #[test]
    #[should_panic(expected = "does not belong")]
    fn cross_tree_node_id_is_caught() {
        let tree_a = example_tree();
        let tree_b = example_tree();
        let id_from_a = tree_a.root().child(0).unwrap().id();
        let _ = tree_b.node(id_from_a); // in range for tree_b, but foreign
    }

    /// The tag participates in id identity (`Eq`/`Hash`): same-index ids of two
    /// layouts are different values, so one map can key ids from several trees.
    #[test]
    fn tree_tags_participate_in_node_id_identity() {
        let tree_a = example_tree();
        let tree_b = example_tree();
        let a0 = tree_a.root().id();
        let b0 = tree_b.root().id();
        assert_eq!(a0.index(), b0.index());
        assert_ne!(a0, b0); // the tag distinguishes them
        assert_eq!(a0.tree_tag(), tree_a.root().child(1).unwrap().id().tree_tag());

        let mut map = hashbrown::HashMap::new();
        map.insert(a0, "a");
        map.insert(b0, "b");
        assert_eq!(map.len(), 2);
        assert_eq!(map[&a0], "a");
        assert_eq!(map[&b0], "b");
    }

    /// `get()` rejects an in-range foreign id in **every** build (the tag check is not
    /// debug-only), and layout-preserving copies (`clone`, `materialize`,
    /// `annotate`) share the tag — their ids are interchangeable.
    #[test]
    fn get_rejects_foreign_ids_and_copies_share_the_tag() {
        let tree_a = example_tree();
        let tree_b = example_tree(); // same shape: every id is in range for both
        let id_from_a = tree_a.root().child(1).unwrap().id();
        assert!(tree_a.get(id_from_a).is_some());
        assert!(tree_b.get(id_from_a).is_none());

        let cloned = tree_a.clone();
        let materialized = tree_a.materialize();
        let annotated = tree_a.annotate(|node| node.id().index());
        assert!(cloned.get(id_from_a).is_some());
        assert!(materialized.get(id_from_a).is_some());
        assert_eq!(annotated.get(id_from_a).unwrap().annotation(), &id_from_a.index());
    }

    /// `annotate` is zero-copy over the layout: the stages share the frozen core
    /// (`Arc` identity) and the input tree is untouched; the callback runs in
    /// storage order.
    #[test]
    fn annotate_shares_the_core_and_runs_in_storage_order() {
        let tree = example_tree();
        let mut seen: Vec<usize> = Vec::new();
        let annotated = tree.annotate(|node| {
            seen.push(node.id().index());
            node.span_content().len()
        });
        // Storage order = 0..n in index order (breadth-first layout).
        assert_eq!(seen, (0..tree.node_count()).collect::<Vec<_>>());
        // Same core, same tag; only the annotation vector is new.
        assert!(Arc::ptr_eq(&tree.core, &annotated.core));
        assert_eq!(annotated.annotations().len(), tree.node_count());
        // The input tree is untouched (still `A = ()`).
        assert_eq!(tree.annotations().len(), tree.node_count());
        let x = annotated.root().child(0).unwrap();
        assert_eq!(*x.annotation(), 1); // "x"
        // Re-annotation over the annotated stage reads the current annotations.
        let doubled = annotated.annotate(|node| node.annotation() * 2);
        assert_eq!(*doubled.node(x.id()).annotation(), 2);
    }

    /// Noise between arguments: `\frac %h␊ {a}{b}` — the comment and the surrounding
    /// whitespace are ordinary child nodes inside the first argument's region, out of
    /// the way of the designated content.
    #[test]
    fn argument_regions_hold_noise_nodes() {
        let source: Arc<Source> = Arc::new(Source::new("\\frac %h\n {a}{b}"));
        // \frac=0..5  " "=5..6  %h␊=6..9 (content "h"=7..8)  " "=9..10  {a}=10..13  {b}=13..16
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let ws1 = b.add(NodeKind::chars(Span::new(5, 6)), spanned(&source, 5..6), st.clone(), vec![], (), ()).unwrap();
        let com = b.add(
            // start "%" + content "h" + post_space "\n" (the node's span covers all three).
            NodeKind::comment(Span::new(6, 7), Span::new(7, 8), Span::new(8, 9)),
            spanned(&source, 6..9),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let ws2 = b.add(NodeKind::chars(Span::new(9, 10)), spanned(&source, 9..10), st.clone(), vec![], (), ()).unwrap();
        let a = b.add(NodeKind::chars(Span::new(11, 12)), spanned(&source, 11..12), st.clone(), vec![], (), ()).unwrap();
        let a_group = b.add(
            NodeKind::group(brace_group(10..11, 12..13)),
            spanned(&source, 10..13),
            st.clone(),
            vec![a], (), (),
        ).unwrap();
        let bb = b.add(NodeKind::chars(Span::new(14, 15)), spanned(&source, 14..15), st.clone(), vec![], (), ()).unwrap();
        let b_group = b.add(
            NodeKind::group(brace_group(13..14, 15..16)),
            spanned(&source, 13..16),
            st.clone(),
            vec![bb], (), (),
        ).unwrap();

        let arg_specs = [brace_arg_spec(), brace_arg_spec()];
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: arg_specs.to_vec(), ..Default::default() });
        let frac = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "frac".into(),
                spec,
                arguments: vec![
                    ParsedArgument::provided(
                        arg_specs[0].clone(),
                        ChildRegion::new(0..4, ContentNodes::InChildrenOf(a_group, 0..1)),
                        (),
                    ),
                    ParsedArgument::provided(
                        arg_specs[1].clone(),
                        ChildRegion::new(4..5, ContentNodes::InChildrenOf(b_group, 0..1)),
                        (),
                    ),
                ]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![ws1, com, ws2, a_group, b_group], (), (),
        ).unwrap();
        let tree = b.finish(frac).unwrap();

        let frac = tree.root();
        let region0: Vec<_> = frac.argument_nodes(0).unwrap().iter().collect();
        assert_eq!(region0.len(), 4);
        assert_eq!(region0[0].chars(), Some(" ")); // whitespace-only Chars node
        assert!(region0[1].is_comment());
        assert_eq!(
            region0[1].comment().map(|data| data.content.resolve(region0[1].source())),
            Some("h")
        );
        assert!(region0[3].is_group());
        // …while the content is undisturbed by the noise:
        let content0: Vec<_> = frac.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(content0.len(), 1);
        assert_eq!(content0[0].chars(), Some("a"));
        // The second argument is unaffected by the first one's noise:
        assert_eq!(frac.argument_content_nodes(1).unwrap().iter().next().unwrap().chars(), Some("b"));
        // The regions tile the child list: recomposing the children in order
        // reproduces the arguments' text byte-for-byte (span tiling).
        let all: String = frac.children().iter().map(|c| c.span_content()).collect();
        assert_eq!(all, " %h\n {a}{b}");
    }

    /// Content may be designated arbitrarily deep: `\m[{x}]` protects `]`-containing
    /// content behind an inner brace group — the content nodes are the *inner* group's
    /// children. The parser says what the content is; there is no unwrap-double-group
    /// heuristic (pylatexenc's hack).
    #[test]
    fn content_designation_reaches_into_nested_groups() {
        const GT_BRACKET: u32 = 1;
        let source: Arc<Source> = Arc::new(Source::new("\\m[{x}]"));
        // \m=0..2  [=2..3  {=3..4  x=4..5  }=5..6  ]=6..7
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();

        let x = b.add(NodeKind::chars(Span::new(4, 5)), spanned(&source, 4..5), st.clone(), vec![], (), ()).unwrap();
        let inner = b.add(
            NodeKind::group(brace_group(3..4, 5..6)),
            spanned(&source, 3..6),
            st.clone(),
            vec![x], (), (),
        ).unwrap();
        let outer = b.add(
            NodeKind::group(GroupData::new(
                GT_BRACKET,
                TextContent::Spanned(Span::new(2, 3)),
                TextContent::Spanned(Span::new(6, 7)),
            )),
            spanned(&source, 2..7),
            st.clone(),
            vec![inner], (), (),
        ).unwrap();

        let arg_spec = brace_arg_spec();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: vec![ParsedArgument::provided(
                    arg_spec,
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(inner, 0..1)),
                    (),
                )]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![outer], (), (),
        ).unwrap();
        let tree = b.finish(m).unwrap();

        let m = tree.root();
        let region: Vec<_> = m.argument_nodes(0).unwrap().iter().collect();
        assert_eq!(region.len(), 1);
        assert_eq!(region[0].span_content(), "[{x}]");
        let content: Vec<_> = m.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0].chars(), Some("x"));
        // The content parent is the inner group — a descendant of, not a member of,
        // the region:
        let record = m.arguments().unwrap().get(0).unwrap().region.clone().unwrap();
        assert_eq!(tree.node(record.content_parent()).span_content(), "{x}");
    }

    /// Empty content stays anchored: `\m{}` — the content range is empty, but its
    /// parent (the group) still answers "where content would go".
    #[test]
    fn empty_content_is_anchored_by_its_parent() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let group = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let arg_spec = brace_arg_spec();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: vec![ParsedArgument::provided(
                    arg_spec,
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(group, 0..0)),
                    (),
                )]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![group], (), (),
        ).unwrap();
        let tree = b.finish(m).unwrap();

        let record = tree.root().arguments().unwrap().get(0).unwrap().region.clone().unwrap();
        assert!(record.content_range().is_empty());
        assert_eq!(tree.node(record.content_parent()).span_content(), "{}");
        assert_eq!(tree.root().argument_content_nodes(0).unwrap().iter().count(), 0);
    }

    // --- builder contract violations around regions -----------------------------------
    //
    // Contract violations return `NodeBuildError` — extension-implementation bugs must
    // never panic core code (the panic policy).

    /// Helper: a one-argument callable staged over the given children with the given
    /// region record (drives the builder's region checks).
    fn stage_callable_with_arg(
        b: &mut NodeTreeBuilder<PlainLang>,
        source: &Arc<Source>,
        st: &Arc<ParsingState<PlainLang>>,
        args: Vec<ParsedArgument<PlainLang>>,
        children: Vec<BuildId>,
    ) -> Result<BuildId, NodeBuildError> {
        let specs: Vec<_> = args.iter().map(|a| a.spec.clone()).collect();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: specs, ..Default::default() });
        b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: args.into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(source),
            st.clone(),
            children, (), (),
        )
    }

    #[test]
    fn region_out_of_bounds_errors() {
        let source: Arc<Source> = Arc::new(Source::new("\\m"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let args =
            vec![ParsedArgument::provided(brace_arg_spec(), ChildRegion::single(0), ())];
        let result = stage_callable_with_arg(&mut b, &source, &st, args, vec![]);
        assert_eq!(
            result,
            Err(NodeBuildError::RegionOutOfBounds { region: 0..1, n_children: 0 })
        );
    }

    #[test]
    fn overlapping_regions_error() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let group = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let args = vec![
            ParsedArgument::provided(brace_arg_spec(), ChildRegion::single(0), ()),
            ParsedArgument::provided(brace_arg_spec(), ChildRegion::single(0), ()),
        ];
        let result = stage_callable_with_arg(&mut b, &source, &st, args, vec![group]);
        assert_eq!(
            result,
            Err(NodeBuildError::RegionNotTiling { region: 0..1, expected_start: 1 })
        );
    }

    #[test]
    fn region_gaps_error() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let g1 = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let g2 = b.add(
            NodeKind::group(brace_group(4..5, 5..6)),
            spanned(&source, 4..6),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        // One argument claiming only the second child: the first belongs to no region.
        let args =
            vec![ParsedArgument::provided(brace_arg_spec(), ChildRegion::single(1), ())];
        let result = stage_callable_with_arg(&mut b, &source, &st, args, vec![g1, g2]);
        assert_eq!(
            result,
            Err(NodeBuildError::RegionNotTiling { region: 1..2, expected_start: 0 })
        );
    }

    #[test]
    fn trailing_children_outside_regions_error() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let g1 = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let g2 = b.add(
            NodeKind::group(brace_group(4..5, 5..6)),
            spanned(&source, 4..6),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        // One argument claiming only the first child: the second belongs to no region.
        let args =
            vec![ParsedArgument::provided(brace_arg_spec(), ChildRegion::single(0), ())];
        let result = stage_callable_with_arg(&mut b, &source, &st, args, vec![g1, g2]);
        assert_eq!(result, Err(NodeBuildError::ChildrenNotInRegions { unassigned: 1..2 }));
    }

    #[test]
    fn dangling_content_parent_errors() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let group = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        // Content designated inside a staged node that never becomes part of the tree:
        let stray = b.add(NodeKind::list(), spanned(&source, 0..0), st.clone(), vec![], (), ()).unwrap();
        let args = vec![ParsedArgument::provided(
            brace_arg_spec(),
            ChildRegion::new(0..1, ContentNodes::InChildrenOf(stray, 0..0)),
            (),
        )];
        let m = stage_callable_with_arg(&mut b, &source, &st, args, vec![group]).unwrap();
        assert_eq!(
            b.finish(m).unwrap_err(),
            NodeBuildError::ContentParentUnreachable { parent: stray }
        );
    }

    #[test]
    fn content_parent_outside_its_region_errors() {
        let source: Arc<Source> = Arc::new(Source::new("\\m{}{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let g1 = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let g2 = b.add(
            NodeKind::group(brace_group(4..5, 5..6)),
            spanned(&source, 4..6),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        // Argument 0's content designated inside argument 1's group:
        let args = vec![
            ParsedArgument::provided(
                brace_arg_spec(),
                ChildRegion::new(0..1, ContentNodes::InChildrenOf(g2, 0..0)),
                (),
            ),
            ParsedArgument::provided(
                brace_arg_spec(),
                ChildRegion::new(1..2, ContentNodes::InChildrenOf(g2, 0..0)),
                (),
            ),
        ];
        let m = stage_callable_with_arg(&mut b, &source, &st, args, vec![g1, g2]).unwrap();
        assert_eq!(
            b.finish(m).unwrap_err(),
            NodeBuildError::ContentParentOutsideRegion { parent: g2 }
        );
    }

    #[test]
    fn restaging_resolved_records_errors() {
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();
        // Records from a finished tree hold that tree's node-index ranges; staging them
        // into a new builder is a caller bug (the two-phase record contract).
        let data = frac.callable().unwrap().clone();
        let source: Arc<Source> = Arc::new(Source::new("x"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::<PlainLang>::new();
        let result = b.add(NodeKind::callable(data), SourceSpan::entire(&source), st, vec![], (), ());
        assert_eq!(result, Err(NodeBuildError::RegionAlreadyResolved));
    }

    #[test]
    fn sibling_ranges_are_contiguous_and_flat() {
        let tree = example_tree();
        // Every node's children ids are a contiguous ascending run, and each non-root
        // node is the child of exactly one node.
        let mut seen = vec![0usize; tree.node_count()];
        for node in tree.iter_storage_order() {
            let ids: Vec<usize> = node.children().iter().map(|c| c.id().index()).collect();
            for pair in ids.windows(2) {
                assert_eq!(pair[1], pair[0] + 1);
            }
            for id in ids {
                seen[id] += 1;
            }
        }
        assert_eq!(tree.root().id().index(), 0);
        assert_eq!(seen[0], 0); // root: no parent
        assert!(seen[1..].iter().all(|&n| n == 1));
    }

    #[test]
    fn unreachable_staged_nodes_are_dropped() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let _abandoned =
            b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let kept = b.add(NodeKind::chars(Span::new(1, 2)), spanned(&source, 1..2), st.clone(), vec![], (), ()).unwrap();
        let root = b.add(NodeKind::list(), SourceSpan::entire(&source), st, vec![kept], (), ()).unwrap();
        let tree = b.finish(root).unwrap();
        assert_eq!(tree.node_count(), 2);
        assert_eq!(tree.root().child(0).unwrap().chars(), Some("b"));
    }

    #[test]
    fn materialize_owns_all_text_and_preserves_it() {
        let tree = example_tree();
        let owned = tree.materialize();

        // Logical text identical…
        let root = owned.root();
        assert_eq!(root.child(0).unwrap().chars(), Some("x"));
        assert_eq!(root.child(2).unwrap().chars(), Some(" "));
        let comment = root.child(3).unwrap();
        let data = comment.comment().unwrap();
        assert_eq!(data.content.resolve(comment.source()), " note");
        assert_eq!(data.start.resolve(comment.source()), "%");
        let arg0 = root.child(1).unwrap().argument_nodes(0).unwrap().iter().next().unwrap();
        assert_eq!(arg0.group_delimiters(), Some(("{", "}")));
        // …but stored owned:
        for node in owned.iter_storage_order() {
            match node.kind() {
                NodeKind::Chars { content, .. } => assert!(content.is_owned()),
                NodeKind::Comment(data) => {
                    assert!(data.content.is_owned());
                    assert!(data.start.is_owned());
                    assert!(data.post_space.is_owned());
                }
                NodeKind::Group(data) => {
                    assert!(data.open.is_owned());
                    assert!(data.close.is_owned());
                }
                NodeKind::Callable(_) => {
                    // The invocation-syntax payload is `()` for PlainLang; the
                    // latexlike payload's materialize-through is pinned in the
                    // preset's tests.
                }
                _ => {}
            }
        }
        // The original tree is untouched (still span-backed):
        match tree.root().child(0).unwrap().kind() {
            NodeKind::Chars { content, .. } => assert!(!content.is_owned()),
            _ => unreachable!(),
        }
        // Spans (provenance) survive materialization:
        assert_eq!(owned.root().child(1).unwrap().span_content(), r"\frac{a}{b}");
    }

    #[test]
    fn synthesized_groups_may_have_no_group_type() {
        // Internal synthetic groups (not produced by tokenization) carry delimiters but
        // no language group type.
        let source: Arc<Source> = Arc::new(Source::new("y"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let y = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let g = b.add(
            NodeKind::group(GroupData::untyped(TextContent::from("{"), TextContent::from("}"))),
            spanned(&source, 0..1),
            st.clone(),
            vec![y], (), (),
        ).unwrap();
        let tree = b.finish(g).unwrap();

        let group = tree.root();
        assert!(group.is_group());
        assert_eq!(group.group_type(), None);
        assert_eq!(group.group_delimiters(), Some(("{", "}")));
    }

    // --- ext minting: Lang::make_node_ext + StagedChildren ---------------------------

    struct ExtBundle;
    impl crate::state::NodeExtTypes for ExtBundle {
        type NodeExt = u16; // e.g. a bindings-handle index
        type ArgumentExt = ();
        type SlotExt = u8; // e.g. a derived cell/item count
    }

    #[derive(Debug, Clone, Copy)]
    struct ExtLang;
    impl Lang for ExtLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ExtBundle;
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;

        /// A fixed marker value: proves the mint's output lands on the node.
        fn make_node_ext(
            _kind: &NodeKind<Self>,
            _span: &SourceSpan,
            _state: &Arc<ParsingState<Self>>,
            _children: StagedChildren<'_, Self>,
        ) -> Result<u16, NodeBuildError> {
            Ok(42)
        }
    }

    /// The builder demands ready ext values (it never mints); minted or bespoke
    /// values land on the node and read back through `NodeRef::ext()`.
    #[test]
    fn ext_values_are_stored_and_read_back() {
        let source: Arc<Source> = Arc::new(Source::new("y"));
        let st = state::<ExtLang>();
        let mut b = NodeTreeBuilder::new();
        let kind: NodeKind<ExtLang> = NodeKind::chars(Span::new(0, 1));
        let span = spanned(&source, 0..1);
        // The explicit two-line transform-side recipe: mint, then add.
        let ext =
            ExtLang::make_node_ext(&kind, &span, &st, b.staged_children(&[])).unwrap();
        let y = b.add(kind, span, st.clone(), vec![], ext, ()).unwrap();
        // A bespoke value is equally legal on the transform side:
        let root = b
            .add(NodeKind::list(), SourceSpan::entire(&source), st, vec![y], 7u16, ())
            .unwrap();
        let tree = b.finish(root).unwrap();

        assert_eq!(*tree.root().child(0).unwrap().ext(), 42);
        assert_eq!(*tree.root().ext(), 7);
    }

    /// The slot-side symmetry of `ArgumentExt`: per-instance derived
    /// data about one content region (tabular cells, enumerate items) is stored on the
    /// `ParsedSlot` record itself, not on the whole-callable ext.
    #[test]
    fn parsed_slot_carries_ext() {
        let mut slot: ParsedSlot<ExtLang> =
            ParsedSlot::new(ChildRegion::single(0), "body", SlotRole::Content, 0);
        assert_eq!(slot.name(), Some("body"));
        assert_eq!(slot.ext, 0); // demanded at construction — no Default fill exists
        slot.ext = 3;
        assert_eq!(slot.clone().ext, 3);
    }

    // --- slot roles + trait-based body marking ---------------------------------------

    /// A marker-style slot ext without `Default` (the preset's `BodyMarker` shape).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct BodyFlag {
        body: bool,
    }
    impl BodySlotExt for BodyFlag {
        fn is_body(&self) -> bool {
            self.body
        }
        fn make_body() -> BodyFlag {
            BodyFlag { body: true }
        }
    }

    /// A non-`Default` argument ext (a reference-cache shape): custom parsers mint it;
    /// the record constructors demand it.
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct RefExt {
        key: String,
    }

    struct RoleBundle;
    impl crate::state::NodeExtTypes for RoleBundle {
        type NodeExt = ();
        type ArgumentExt = RefExt;
        type SlotExt = BodyFlag;
    }

    #[derive(Debug, Clone, Copy)]
    struct RoleLang;
    impl Lang for RoleLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = RoleBundle;
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;

        fn make_node_ext(
            _kind: &NodeKind<Self>,
            _span: &SourceSpan,
            _state: &Arc<ParsingState<Self>>,
            _children: StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    /// Roles are stored and read back; `body()` selects on the **ext axis alone**
    /// (`BodySlotExt`) — a non-slot-0 body is found, and its `Attached` role does
    /// not hide it (no role conjunction).
    #[test]
    fn body_selects_by_ext_marker_across_roles() {
        let source: Arc<Source> = Arc::new(Source::new("xy"));
        let st = state::<RoleLang>();
        let mut b = NodeTreeBuilder::new();
        let x = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let y = b.add(NodeKind::chars(Span::new(1, 2)), spanned(&source, 1..2), st.clone(), vec![], (), ()).unwrap();
        let spec: Arc<dyn CallableSpec<RoleLang>> = Arc::new(StdCallableSpec::default());
        let env = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_ENVIRONMENT,
                name: "it".into(),
                spec,
                arguments: ParsedArguments::empty(),
                slots: vec![
                    // Slot 0 is NOT the body; the body sits at slot 1, and its
                    // `Attached` role must not hide it from `body()`.
                    ParsedSlot::new(
                        ChildRegion::single(0),
                        "preamble",
                        SlotRole::Content,
                        BodyFlag { body: false },
                    ),
                    ParsedSlot::new(
                        ChildRegion::single(1),
                        "body",
                        SlotRole::Attached,
                        BodySlotExt::make_body(),
                    ),
                ]
                .into(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![x, y], (), (),
        ).unwrap();
        let tree = b.finish(env).unwrap();

        let node = tree.root();
        let slots = node.slots().unwrap();
        assert_eq!(slots.get(0).unwrap().role, SlotRole::Content);
        assert_eq!(slots.get(1).unwrap().role, SlotRole::Attached);
        assert!(!slots.get(0).unwrap().ext.is_body());
        assert!(slots.get(1).unwrap().ext.is_body());
        // body() = the first slot whose ext reports body — slot 1 here.
        let body: Vec<_> = node.body().unwrap().iter().collect();
        assert_eq!(body.len(), 1);
        assert_eq!(body[0].chars(), Some("y"));
    }

    /// `SlotRole` defaults to `Content` (the conceptual default) and is plain data.
    #[test]
    fn slot_role_default_is_content() {
        assert_eq!(SlotRole::default(), SlotRole::Content);
    }

    /// The record collections have discoverable constructors (`new(Vec)`; the
    /// `From<Vec>` conversions remain as low-level conversions), and `ParsedSlot`
    /// follows the
    /// named-first family: `new(region, name, …)` names the slot,
    /// `new_unnamed(region, …)` is the marked anonymous spelling.
    #[test]
    fn record_collections_and_slot_constructors() {
        let args: ParsedArguments<PlainLang> = ParsedArguments::new(vec![
            ParsedArgument::absent(brace_arg_spec()),
        ]);
        assert_eq!(args.len(), 1);

        let named: ParsedSlot<PlainLang> =
            ParsedSlot::new(ChildRegion::single(0), "body", SlotRole::Content, ());
        assert_eq!(named.name(), Some("body"));
        let unnamed: ParsedSlot<PlainLang> =
            ParsedSlot::new_unnamed(ChildRegion::single(1), SlotRole::Hidden, ());
        assert_eq!(unnamed.name(), None);
        assert_eq!(unnamed.role, SlotRole::Hidden);

        let slots: ParsedSlots<PlainLang> = ParsedSlots::new(vec![named, unnamed]);
        assert_eq!(slots.len(), 2);
        assert!(slots.get_named("body").is_some());
    }

    /// The argument-ext pipeline for a language whose `ArgumentExt` has no `Default`:
    /// `ParsedArgumentNodes` demands the parser-minted value, `provided` carries it
    /// into the record, `absent` carries none.
    #[test]
    fn parsed_argument_nodes_demands_the_ext() {
        // A custom parser's output: the record constructor demands the minted ext.
        let region: crate::spec::ParsedArgumentNodes<RoleLang> =
            crate::spec::ParsedArgumentNodes::new(
                vec![],
                ContentNodes::InRegion(0..0),
                RefExt { key: String::from("fig:abc") },
            );
        assert_eq!(region.ext.key, "fig:abc");

        // StubParser is a *custom* parser (mints its own ext — here it never provides),
        // so it implements `ArgumentParser<RoleLang>` although `RefExt: !Default`.
        let spec: Arc<ArgumentSpec<RoleLang>> = Arc::new(ArgumentSpec::new_unnamed(Arc::new(StubParser)));
        let provided = ParsedArgument::provided(
            Arc::clone(&spec),
            ChildRegion::single(0),
            region.ext.clone(),
        );
        assert_eq!(provided.ext.as_ref().unwrap().key, "fig:abc");
        // Absent arguments carry no ext: nothing was parsed, nothing was minted.
        let absent = ParsedArgument::absent(spec);
        assert!(absent.ext.is_none());
        assert!(!absent.is_provided());
    }

    // --- make_node_ext computing from the descent-only children view -----------------

    /// A non-`Default` ext minted from the children: `descendants` reads the
    /// children's already-minted exts; `chars_below` walks the subtree recursively
    /// through `StagedChildren` — grandchild-depth data is reachable at mint time.
    #[derive(Debug, Clone, PartialEq)]
    struct MintExt {
        descendants: u32,
        chars_below: u32,
    }

    struct MintExts;
    impl crate::state::NodeExtTypes for MintExts {
        type NodeExt = MintExt;
        type ArgumentExt = ();
        type SlotExt = ();
    }

    fn chars_below(children: StagedChildren<'_, MintLang>) -> u32 {
        children
            .iter()
            .map(|child| {
                u32::from(matches!(child.kind(), NodeKind::Chars { .. }))
                    + chars_below(child.children())
            })
            .sum()
    }

    #[derive(Debug, Clone, Copy)]
    struct MintLang;
    impl Lang for MintLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = MintExts;
        type InvocationSyntax = ();
        type Driver = crate::engine::StdParseDriver;

        fn make_node_ext(
            _kind: &NodeKind<Self>,
            _span: &SourceSpan,
            _state: &Arc<ParsingState<Self>>,
            children: StagedChildren<'_, Self>,
        ) -> Result<MintExt, NodeBuildError> {
            Ok(MintExt {
                descendants: children.iter().map(|child| child.ext().descendants + 1).sum(),
                chars_below: chars_below(children),
            })
        }
    }

    /// `x{a}` minted bottom-up through the recipe: every node's ext is computed at
    /// staging, the `StagedChildren` view resolves to grandchild depth, and a
    /// non-`Default` ext type flows through the builder end to end.
    #[test]
    fn make_node_ext_reads_staged_children_to_grandchild_depth() {
        let source: Arc<Source> = Arc::new(Source::new("x{a}"));
        let st = state::<MintLang>();
        let mut b: NodeTreeBuilder<MintLang> = NodeTreeBuilder::new();

        let stage = |b: &mut NodeTreeBuilder<MintLang>,
                         kind: NodeKind<MintLang>,
                         span: SourceSpan,
                         children: Vec<BuildId>| {
            let ext = MintLang::make_node_ext(&kind, &span, &st, b.staged_children(&children))
                .unwrap();
            b.add(kind, span, st.clone(), children, ext, ()).unwrap()
        };
        let x = stage(&mut b, NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), vec![]);
        let a = stage(&mut b, NodeKind::chars(Span::new(2, 3)), spanned(&source, 2..3), vec![]);
        let g = stage(&mut b, NodeKind::group(brace_group(1..2, 3..4)), spanned(&source, 1..4), vec![a]);
        let root = stage(&mut b, NodeKind::list(), SourceSpan::entire(&source), vec![x, g]);
        let tree = b.finish(root).unwrap();

        // The root's mint saw the group's ext (child depth) AND the chars node inside
        // the group (grandchild depth, via the recursive view).
        assert_eq!(*tree.root().ext(), MintExt { descendants: 3, chars_below: 2 });
        let group = tree.root().child(1).unwrap();
        assert_eq!(*group.ext(), MintExt { descendants: 1, chars_below: 1 });
        assert_eq!(
            *tree.root().child(0).unwrap().ext(),
            MintExt { descendants: 0, chars_below: 0 }
        );
    }

    /// The mint's error channel at the builder level: `make_node_ext` also runs
    /// for consumer-built trees (the explicit two-line recipe), where no parse or
    /// span context exists — the failure is an ordinary `NodeBuildError` value,
    /// matchable and rendered by `Display`.
    #[test]
    fn a_failing_make_node_ext_surfaces_at_the_builder_level() {
        #[derive(Debug, Clone, Copy)]
        struct MintFailLang;
        impl Lang for MintFailLang {
            type Features = crate::state::AllLangFeatures;
            type GroupTypeId = u32;
            type CallableTypeId = u32;
            type ModeId = ();
            type StateExt = ();
            type Event = ();
            type SessionExt = ();
            type SourceOrigin = Option<String>;
            type Tokenization = crate::token::StdTokenization;
            type NodeExts = ();
            type InvocationSyntax = ();
            type Driver = crate::engine::StdParseDriver;

            fn make_node_ext(
                _kind: &NodeKind<Self>,
                _span: &SourceSpan,
                _state: &Arc<ParsingState<Self>>,
                _children: StagedChildren<'_, Self>,
            ) -> Result<(), NodeBuildError> {
                Err(NodeBuildError::ExtMintFailed { detail: "no ext data source".into() })
            }
        }

        let source: Arc<Source> = Arc::new(Source::new("x"));
        let st = state::<MintFailLang>();
        let b: NodeTreeBuilder<MintFailLang> = NodeTreeBuilder::new();
        let kind: NodeKind<MintFailLang> = NodeKind::chars(Span::new(0, 1));
        let err = MintFailLang::make_node_ext(
            &kind,
            &spanned(&source, 0..1),
            &st,
            b.staged_children(&[]),
        )
        .unwrap_err();
        assert_eq!(
            err,
            NodeBuildError::ExtMintFailed { detail: "no ext data source".into() }
        );
        assert_eq!(
            err.to_string(),
            "the node-ext mint (Lang::make_node_ext) reported a failure: \
             no ext data source"
        );
    }

    /// The descent-only view: children and their subtrees resolve; there is no
    /// sibling/ancestor/arbitrary-id access by construction (the API surface), and a
    /// never-staged id reads as absent instead of panicking.
    #[test]
    fn staged_children_is_descent_only_and_skips_unstaged_ids() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state::<PlainLang>();
        let mut b: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let a = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();

        let view = b.staged_children(core::slice::from_ref(&a));
        assert_eq!(view.len(), 1);
        assert!(!view.is_empty());
        let child = view.get(0).unwrap();
        assert!(matches!(child.kind(), NodeKind::Chars { .. }));
        assert_eq!(child.span().range(), 0..1);
        assert!(Arc::ptr_eq(child.parsing_state(), &st));
        assert!(child.children().is_empty());
        assert_eq!(view.iter().count(), 1);

        // A foreign builder's id (never staged here) is absent, not a panic — the
        // subsequent add() diagnoses it as ChildNotStaged.
        let mut other: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let f0 = other
            .add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ())
            .unwrap();
        let _f1 = other
            .add(NodeKind::chars(Span::new(1, 2)), spanned(&source, 1..2), st.clone(), vec![], (), ())
            .unwrap();
        let beyond = [f0, _f1];
        // `f0`/`f1` happen to be in-range for `b` only if staged there; `f1` is not.
        let view = b.staged_children(&beyond);
        assert_eq!(view.len(), 2);
        assert!(view.get(1).is_none());
        assert_eq!(view.iter().count(), 1);
    }

    // --- the staged read view ---------------------------------------------------------

    #[test]
    fn staged_nodes_view_reads_back_staged_data() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        assert!(b.staged_nodes().is_empty());

        let a = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let l = b.add(NodeKind::list(), spanned(&source, 0..2), st.clone(), vec![a], (), ()).unwrap();

        let staged = b.staged_nodes();
        assert_eq!(staged.len(), 2);

        let view = staged.get(a).unwrap();
        assert_eq!(view.id(), a);
        assert!(matches!(view.kind(), NodeKind::Chars { .. }));
        assert_eq!(view.span().start(), 0);
        assert_eq!(view.span().end(), 1);
        assert!(view.children().is_empty());
        assert!(Arc::ptr_eq(view.parsing_state(), &st));
        let _uniform_ext: &() = view.ext();

        let list_view = staged.get(l).unwrap();
        assert_eq!(list_view.children(), &[a]);
        // Views are plain Copy proxies and debuggable:
        let copy = view;
        assert!(alloc::format!("{:?}", copy).contains("Chars"));
    }

    // --- Debug does not demand anything of the lang ZST itself -----------------------

    struct NoDeriveLang; // deliberately neither Clone nor Debug
    impl TrivialLang for NoDeriveLang {}

    #[test]
    fn debug_and_clone_without_lang_bounds() {
        let source: Arc<Source> = Arc::new(Source::new("z"));
        let st = state::<NoDeriveLang>();
        let mut b = NodeTreeBuilder::new();
        let z = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let root = b.add(NodeKind::list(), SourceSpan::entire(&source), st, vec![z], (), ()).unwrap();
        let tree = b.finish(root).unwrap();

        let cloned = tree.clone();
        let dump = alloc::format!("{:?}", cloned);
        assert!(dump.contains("Chars"));
        let node_dump = alloc::format!("{:?}", tree.root().child(0).unwrap());
        assert!(node_dump.contains("NodeId(1@"));
    }

    #[test]
    fn a_node_cannot_have_two_parents() {
        let source: Arc<Source> = Arc::new(Source::new("w"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let w = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let _l1 = b.add(NodeKind::list(), SourceSpan::entire(&source), st.clone(), vec![w], (), ()).unwrap();
        let result = b.add(NodeKind::list(), SourceSpan::entire(&source), st, vec![w], (), ());
        assert_eq!(result.unwrap_err(), NodeBuildError::ChildAlreadyClaimed { child: w });
    }

    #[test]
    fn unstaged_children_and_roots_error() {
        let source: Arc<Source> = Arc::new(Source::new("w"));
        let st = state::<PlainLang>();
        // A foreign BuildId (minted by another builder) is an implementation bug the
        // empty builder diagnoses as not-staged — as child and as root alike.
        let mut other = NodeTreeBuilder::<PlainLang>::new();
        let foreign = other
            .add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ())
            .unwrap();

        let mut b = NodeTreeBuilder::<PlainLang>::new();
        let result =
            b.add(NodeKind::list(), SourceSpan::entire(&source), st.clone(), vec![foreign], (), ());
        assert_eq!(result.unwrap_err(), NodeBuildError::ChildNotStaged { child: foreign });

        let b = NodeTreeBuilder::<PlainLang>::new();
        assert_eq!(
            b.finish(foreign).unwrap_err(),
            NodeBuildError::RootNotStaged { root: foreign }
        );
    }

    #[test]
    fn finishing_on_a_claimed_root_errors() {
        let source: Arc<Source> = Arc::new(Source::new("w"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let w = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let _list = b.add(NodeKind::list(), SourceSpan::entire(&source), st, vec![w], (), ()).unwrap();
        assert_eq!(b.finish(w).unwrap_err(), NodeBuildError::RootClaimed { root: w });
    }

    #[test]
    fn spanned_content_outside_the_source_errors() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::<PlainLang>::new();
        // A chars payload past the source's end (previously a debug-only assertion;
        // an always-on error since the panic-policy decision).
        let result =
            b.add(NodeKind::chars(Span::new(0, 5)), SourceSpan::entire(&source), st, vec![], (), ());
        assert_eq!(
            result.unwrap_err(),
            NodeBuildError::SpannedContentInvalid {
                what: "chars content",
                span: Span::new(0, 5),
                content_len: 2,
            }
        );
    }

    // --- NodeSlice, descendants, named accessors, subtree copy (Phase 7.8) ------------

    #[test]
    fn node_slice_basics() {
        let tree = example_tree();
        let children = tree.root().children();
        assert_eq!(children.len(), 4);
        assert!(!children.is_empty());
        assert_eq!(children.get(0).unwrap().chars(), Some("x"));
        assert_eq!(children.first().unwrap().chars(), Some("x"));
        assert!(children.last().unwrap().is_comment());
        assert!(children.get(4).is_none());

        // Direct iteration (IntoIterator), adaptor chains (iter()), and reversal.
        let mut count = 0;
        for node in children {
            let _ = node.span_content();
            count += 1;
        }
        assert_eq!(count, 4);
        let kinds: Vec<bool> = children.iter().map(|c| c.is_callable()).collect();
        assert_eq!(kinds, [false, true, false, false]);
        assert_eq!(children.iter().len(), 4); // ExactSizeIterator
        let backwards: Vec<_> = children.iter().rev().map(|c| c.is_comment()).collect();
        assert_eq!(backwards, [true, false, false, false]);

        // Slices are Copy; the range is the global node-index coordinate system.
        let copy = children;
        assert_eq!(copy.range(), children.range());
        let leaf = tree.root().child(0).unwrap();
        assert!(leaf.children().is_empty());
        assert!(leaf.children().span().is_none());
    }

    #[test]
    fn node_slice_spans_are_exact() {
        let tree = example_tree();
        let root = tree.root();
        // The whole child run covers the source.
        let all = root.children().span().unwrap();
        assert_eq!(all.range(), 0..19);
        assert_eq!(root.children().source_text(), Some(r"x\frac{a}{b} % note"));

        // Argument regions and content: exact sub-spans, straight off the nodes.
        let frac = root.child(1).unwrap();
        let region = frac.argument_nodes(0).unwrap();
        assert_eq!(region.span().unwrap().range(), 6..9);
        assert_eq!(region.source_text(), Some("{a}"));
        let content = frac.argument_content_nodes(0).unwrap();
        assert_eq!(content.span().unwrap().range(), 7..8);
        assert_eq!(content.source_text(), Some("a"));
        assert_eq!(content.span().unwrap().content(), "a");

        // Empty content (`\m{}`): no source material — None, honestly.
        let source: Arc<Source> = Arc::new(Source::new("\\m{}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let group = b.add(
            NodeKind::group(brace_group(2..3, 3..4)),
            spanned(&source, 2..4),
            st.clone(),
            vec![], (), (),
        ).unwrap();
        let arg_spec = brace_arg_spec();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: vec![ParsedArgument::provided(
                    arg_spec,
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(group, 0..0)),
                    (),
                )]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![group], (), (),
        ).unwrap();
        let tree = b.finish(m).unwrap();
        let content = tree.root().argument_content_nodes(0).unwrap();
        assert!(content.is_empty());
        assert!(content.span().is_none());
        assert!(content.source_text().is_none());
    }

    #[test]
    fn descendants_walk_in_document_order() {
        let tree = example_tree();
        // Storage order is breadth-first (`x`, `\frac…`, ` `, `%…`, `{a}`, `{b}`, `a`,
        // `b`); document order interleaves the argument groups where they occur.
        let doc: Vec<_> = tree.root().descendants().map(|n| n.span_content()).collect();
        assert_eq!(doc, ["x", r"\frac{a}{b}", "{a}", "a", "{b}", "b", " ", "% note"]);
        // Tree-level sugar walks from the root; subtree walks exclude the start node.
        let via_tree: Vec<_> = tree.descendants().map(|n| n.id()).collect();
        let via_root: Vec<_> = tree.root().descendants().map(|n| n.id()).collect();
        assert_eq!(via_tree, via_root);
        assert_eq!(via_tree.len(), tree.node_count() - 1);
        let frac = tree.root().child(1).unwrap();
        let sub: Vec<_> = frac.descendants().map(|n| n.span_content()).collect();
        assert_eq!(sub, ["{a}", "a", "{b}", "b"]);
        assert_eq!(tree.root().child(0).unwrap().descendants().count(), 0);
    }

    #[test]
    fn named_accessors_mirror_their_index_twins() {
        // The `\section*{t}` tree of absent_marker_and_named_arguments, accessed by name.
        let source: Arc<Source> = Arc::new(Source::new(r"\section*{t}"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let star =
            b.add(NodeKind::chars(Span::new(8, 9)), spanned(&source, 8..9), st.clone(), vec![], (), ()).unwrap();
        let t = b.add(NodeKind::chars(Span::new(10, 11)), spanned(&source, 10..11), st.clone(), vec![], (), ()).unwrap();
        let title = b.add(
            NodeKind::group(brace_group(9..10, 11..12)),
            spanned(&source, 9..12),
            st.clone(),
            vec![t], (), (),
        ).unwrap();
        let star_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "star"));
        let placement_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "placement"));
        let title_spec: Arc<ArgumentSpec<PlainLang>> =
            Arc::new(ArgumentSpec::new(Arc::new(StubParser), "title"));
        let spec: Arc<dyn CallableSpec<PlainLang>> = Arc::new(StdCallableSpec {
            arguments: vec![star_spec.clone(), placement_spec.clone(), title_spec.clone()],
            ..Default::default()
        });
        let body_chars =
            b.add(NodeKind::chars(Span::new(10, 11)), spanned(&source, 10..11), st.clone(), vec![], (), ()).unwrap();
        let body = b.add(NodeKind::list(), spanned(&source, 10..11), st.clone(), vec![body_chars], (), ()).unwrap();
        let section = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "section".into(),
                spec,
                arguments: vec![
                    ParsedArgument::provided(star_spec, ChildRegion::single(0), ()),
                    ParsedArgument::absent(placement_spec),
                    ParsedArgument::provided(
                        title_spec,
                        ChildRegion::new(1..2, ContentNodes::InChildrenOf(title, 0..1)),
                        (),
                    ),
                ]
                .into(),
                slots: vec![ParsedSlot::new(
                    ChildRegion::new(2..3, ContentNodes::InChildrenOf(body, 0..1)),
                    "annex",
                    SlotRole::Content,
                    (),
                )]
                .into(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![star, title, body], (), (),
        ).unwrap();
        let tree = b.finish(section).unwrap();
        let node = tree.root();

        assert_eq!(
            node.argument_nodes_named("title").unwrap().unwrap().source_text(),
            Some("{t}")
        );
        assert_eq!(
            node.argument_content_nodes_named("title")
                .unwrap().unwrap().first().unwrap().chars(),
            Some("t")
        );
        assert_eq!(
            node.argument_content_nodes_named("star")
                .unwrap().unwrap().first().unwrap().chars(),
            Some("*")
        );
        // Absent argument: entry exists, no region — precisely `Ok(None)`.
        assert!(matches!(node.argument_nodes_named("placement"), Ok(None)));
        assert!(matches!(node.argument_content_nodes_named("placement"), Ok(None)));
        // No such argument at all: the category ERROR — never a silent None (the
        // misspelling trap has a discriminator at the call site).
        assert_eq!(
            node.argument_nodes_named("nonsense").unwrap_err(),
            NamedAccessError::UnknownArgumentName { name: "nonsense".into() }
        );
        assert_eq!(
            node.argument_content_nodes_named("nonsense").unwrap_err(),
            NamedAccessError::UnknownArgumentName { name: "nonsense".into() }
        );
        // Slots by name (no Option layer: a recorded slot always has content).
        assert_eq!(
            node.slot_content_nodes_named("annex").unwrap().first().unwrap().chars(),
            Some("t")
        );
        assert_eq!(
            node.slot_content_nodes_named("nonsense").unwrap_err(),
            NamedAccessError::UnknownSlotName { name: "nonsense".into() }
        );
        // Non-callables answer the NotACallable category error throughout.
        let leaf = tree.node(
            node.argument_content_nodes_named("star")
                .unwrap().unwrap().first().unwrap().id(),
        );
        assert_eq!(
            leaf.argument_nodes_named("title").unwrap_err(),
            NamedAccessError::NotACallable
        );
        assert_eq!(
            leaf.slot_content_nodes_named("annex").unwrap_err(),
            NamedAccessError::NotACallable
        );
    }

    #[test]
    fn copy_subtree_reproduces_structure_and_records() {
        let tree = example_tree();
        let mut b = NodeTreeBuilder::new();
        let root = super::copy::copy_subtree_into(&mut b, tree.root(), &mut |_| ()).unwrap();
        let copy = b.finish(root).unwrap();

        // A pure copy is a well-formed tree: full invariants (span partition included).
        check_tree_invariants(&copy);
        assert_eq!(copy.node_count(), tree.node_count());
        // Same document order, same text, same spans (Arc-shared sources).
        let originals: Vec<_> = tree.descendants().map(|n| n.span_content()).collect();
        let copies: Vec<_> = copy.descendants().map(|n| n.span_content()).collect();
        assert_eq!(originals, copies);
        // Region records were re-staged and re-resolved for the new layout.
        let frac = copy.root().child(1).unwrap();
        assert_eq!(frac.argument_content_nodes(0).unwrap().first().unwrap().chars(), Some("a"));
        assert_eq!(frac.argument_nodes(1).unwrap().source_text(), Some("{b}"));
        // Specs and states are shared, not cloned.
        let original_spec = tree.root().child(1).unwrap().spec().unwrap();
        assert!(Arc::ptr_eq(frac.spec().unwrap(), original_spec));
        assert!(Arc::ptr_eq(
            frac.parsing_state(),
            tree.root().child(1).unwrap().parsing_state()
        ));
    }

    #[test]
    fn copy_subtree_restages_nested_content_designations() {
        // The `\m[{x}]` shape: content designated inside a *descendant* group of the
        // region node — the copy must remap the content parent through the id map.
        const GT_BRACKET: u32 = 1;
        let source: Arc<Source> = Arc::new(Source::new("\\m[{x}]"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let x = b.add(NodeKind::chars(Span::new(4, 5)), spanned(&source, 4..5), st.clone(), vec![], (), ()).unwrap();
        let inner = b.add(
            NodeKind::group(brace_group(3..4, 5..6)),
            spanned(&source, 3..6),
            st.clone(),
            vec![x], (), (),
        ).unwrap();
        let outer = b.add(
            NodeKind::group(GroupData::new(
                GT_BRACKET,
                TextContent::Spanned(Span::new(2, 3)),
                TextContent::Spanned(Span::new(6, 7)),
            )),
            spanned(&source, 2..7),
            st.clone(),
            vec![inner], (), (),
        ).unwrap();
        let arg_spec = brace_arg_spec();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: vec![ParsedArgument::provided(
                    arg_spec,
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(inner, 0..1)),
                    (),
                )]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![outer], (), (),
        ).unwrap();
        let tree = b.finish(m).unwrap();

        let mut b = NodeTreeBuilder::new();
        let root = super::copy::copy_subtree_into(&mut b, tree.root(), &mut |_| ()).unwrap();
        let copy = b.finish(root).unwrap();
        check_tree_invariants(&copy);
        let content = copy.root().argument_content_nodes(0).unwrap();
        assert_eq!(content.len(), 1);
        assert_eq!(content.first().unwrap().chars(), Some("x"));
        let record = copy.root().arguments().unwrap().get(0).unwrap().region.clone().unwrap();
        assert_eq!(copy.node(record.content_parent()).span_content(), "{x}");
    }

    // --- staged-side copying (restage_staged_node, StagedNodes::copy_subtree_into) ----

    /// `x\frac{a}{b}` **staged and left unfinished** — the shape a construct parser
    /// sees while the enclosing invocation is still being parsed. Every node gets a
    /// distinct ext value, so a copy that re-minted instead of cloning would show
    /// (`ExtLang`'s mint answers 42).
    struct StagedExample {
        builder: NodeTreeBuilder<ExtLang>,
        source: Arc<Source>,
        x: BuildId,
        a_chars: BuildId,
        a_group: BuildId,
        b_chars: BuildId,
        b_group: BuildId,
        frac: BuildId,
    }

    fn staged_example() -> StagedExample {
        let source: Arc<Source> = Arc::new(Source::new(r"x\frac{a}{b}"));
        let st = state::<ExtLang>();
        let mut b: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let x = b
            .add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], 1, ())
            .unwrap();
        let a_chars = b
            .add(NodeKind::chars(Span::new(7, 8)), spanned(&source, 7..8), st.clone(), vec![], 2, ())
            .unwrap();
        let a_group = b
            .add(
                NodeKind::group(brace_group(6..7, 8..9)),
                spanned(&source, 6..9),
                st.clone(),
                vec![a_chars],
                3,
                (),
            )
            .unwrap();
        let b_chars = b
            .add(
                NodeKind::chars(Span::new(10, 11)),
                spanned(&source, 10..11),
                st.clone(),
                vec![],
                4,
                (),
            )
            .unwrap();
        let b_group = b
            .add(
                NodeKind::group(brace_group(9..10, 11..12)),
                spanned(&source, 9..12),
                st.clone(),
                vec![b_chars],
                5,
                (),
            )
            .unwrap();
        let arg_specs = [brace_arg_spec::<ExtLang>(), brace_arg_spec::<ExtLang>()];
        let spec: Arc<dyn CallableSpec<ExtLang>> =
            Arc::new(StdCallableSpec { arguments: arg_specs.to_vec(), ..Default::default() });
        let frac = b
            .add(
                NodeKind::callable(CallableData {
                    callable_type: CT_MACRO,
                    name: "frac".into(),
                    spec,
                    arguments: vec![
                        ParsedArgument::provided(
                            arg_specs[0].clone(),
                            ChildRegion::new(0..1, ContentNodes::InChildrenOf(a_group, 0..1)),
                            (),
                        ),
                        ParsedArgument::provided(
                            arg_specs[1].clone(),
                            ChildRegion::new(1..2, ContentNodes::InChildrenOf(b_group, 0..1)),
                            (),
                        ),
                    ]
                    .into(),
                    slots: ParsedSlots::empty(),
                    invocation_syntax: (),
                }),
                spanned(&source, 1..12),
                st.clone(),
                vec![a_group, b_group],
                6,
                (),
            )
            .unwrap();
        StagedExample { builder: b, source, x, a_chars, a_group, b_chars, b_group, frac }
    }

    #[test]
    fn staged_copy_subtree_reproduces_structure_spans_exts_and_annotations() {
        let example = staged_example();
        let mut target: NodeTreeBuilder<ExtLang, Option<BuildId>> = NodeTreeBuilder::new();
        let root = example
            .builder
            .staged_nodes()
            .copy_subtree_into(example.frac, &mut target, &mut |view| Some(view.id()))
            .unwrap();
        let copy = target.finish(root).unwrap();
        check_tree_invariants(&copy);

        // Structure and text: the whole `\frac{a}{b}` subtree, in document order.
        assert_eq!(copy.node_count(), 5);
        assert_eq!(copy.root().span_content(), r"\frac{a}{b}");
        let texts: Vec<_> = copy.descendants().map(|n| n.span_content()).collect();
        assert_eq!(texts, ["{a}", "a", "{b}", "b"]);
        // Exts are cloned verbatim, never re-minted (the mint would answer 42).
        assert_eq!(*copy.root().ext(), 6);
        let exts: Vec<u16> = copy.descendants().map(|n| *n.ext()).collect();
        assert_eq!(exts, [3, 2, 5, 4]);
        // States are shared, not cloned.
        assert!(Arc::ptr_eq(
            copy.root().parsing_state(),
            example.builder.staged_nodes().get(example.frac).unwrap().parsing_state()
        ));
        // Every copy names the staged node it came from; nothing here is synthesized.
        assert_eq!(*copy.root().annotation(), Some(example.frac));
        let annotations: Vec<_> = copy.descendants().map(|n| *n.annotation()).collect();
        assert_eq!(
            annotations,
            [
                Some(example.a_group),
                Some(example.a_chars),
                Some(example.b_group),
                Some(example.b_chars),
            ]
        );
        // The `InChildrenOf` records were translated and re-resolved for the new layout.
        let record = copy.root().arguments().unwrap().get(0).unwrap().region.clone().unwrap();
        assert_eq!(copy.node(record.content_parent()).span_content(), "{a}");
        assert_eq!(
            copy.root().argument_content_nodes(1).unwrap().first().unwrap().chars(),
            Some("b")
        );
    }

    #[test]
    fn staged_copy_leaves_the_source_builder_untouched() {
        // A copy reads; it claims nothing. The source builder goes on staging over the
        // very nodes that were copied, and finishes as if no copy had happened.
        let mut example = staged_example();
        let source = Arc::clone(&example.source);
        let mut target: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let copied_x = example
            .builder
            .staged_nodes()
            .copy_subtree_into(example.x, &mut target, &mut |_| ())
            .unwrap();
        let copied_frac = example
            .builder
            .staged_nodes()
            .copy_subtree_into(example.frac, &mut target, &mut |_| ())
            .unwrap();
        let target_root = target
            .add(
                NodeKind::list(),
                SourceSpan::entire(&source),
                state::<ExtLang>(),
                vec![copied_x, copied_frac],
                0,
                (),
            )
            .unwrap();
        let copy = target.finish(target_root).unwrap();
        check_tree_invariants(&copy);
        assert_eq!(copy.node_count(), 7);

        // `x` and `frac` were never claimed by the copy: the source builder still takes
        // them as the children of a new node, and finishes.
        let list = example
            .builder
            .add(
                NodeKind::list(),
                SourceSpan::entire(&source),
                state::<ExtLang>(),
                vec![example.x, example.frac],
                0,
                (),
            )
            .unwrap();
        let original = example.builder.finish(list).unwrap();
        check_tree_invariants(&original);
        assert_eq!(original.node_count(), 7);
    }

    #[test]
    fn restage_staged_node_translates_regions_through_dropped_and_multiplied_children() {
        // A three-argument callable, one region per child: a bare two-character token
        // (`InRegion`), a group (`InChildrenOf`), and a second bare token. The first
        // child is replaced by two nodes, the second by one, and the third by none.
        let source: Arc<Source> = Arc::new(Source::new(r"\m 12{3}4"));
        let st = state::<PlainLang>();
        let mut b: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let one = b
            .add(NodeKind::chars(Span::new(3, 5)), spanned(&source, 3..5), st.clone(), vec![], (), ())
            .unwrap();
        let three = b
            .add(NodeKind::chars(Span::new(6, 7)), spanned(&source, 6..7), st.clone(), vec![], (), ())
            .unwrap();
        let group = b
            .add(
                NodeKind::group(brace_group(5..6, 7..8)),
                spanned(&source, 5..8),
                st.clone(),
                vec![three],
                (),
                (),
            )
            .unwrap();
        let four = b
            .add(NodeKind::chars(Span::new(8, 9)), spanned(&source, 8..9), st.clone(), vec![], (), ())
            .unwrap();
        let arg_specs = [brace_arg_spec::<PlainLang>(), brace_arg_spec(), brace_arg_spec()];
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: arg_specs.to_vec(), ..Default::default() });
        let m = b
            .add(
                NodeKind::callable(CallableData {
                    callable_type: CT_MACRO,
                    name: "m".into(),
                    spec,
                    arguments: vec![
                        ParsedArgument::provided(
                            arg_specs[0].clone(),
                            ChildRegion::new(0..1, ContentNodes::InRegion(0..1)),
                            (),
                        ),
                        ParsedArgument::provided(
                            arg_specs[1].clone(),
                            ChildRegion::new(1..2, ContentNodes::InChildrenOf(group, 0..1)),
                            (),
                        ),
                        ParsedArgument::provided(
                            arg_specs[2].clone(),
                            ChildRegion::new(2..3, ContentNodes::InRegion(0..1)),
                            (),
                        ),
                    ]
                    .into(),
                    slots: ParsedSlots::empty(),
                    invocation_syntax: (),
                }),
                SourceSpan::entire(&source),
                st.clone(),
                vec![one, group, four],
                (),
                (),
            )
            .unwrap();

        // The replacements, staged in a builder of their own: the "12" token cut in
        // two, and a fresh copy of the group.
        let mut target: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let one_a = target
            .add(NodeKind::chars(Span::new(3, 4)), spanned(&source, 3..4), st.clone(), vec![], (), ())
            .unwrap();
        let one_b = target
            .add(NodeKind::chars(Span::new(4, 5)), spanned(&source, 4..5), st.clone(), vec![], (), ())
            .unwrap();
        let new_three = target
            .add(NodeKind::chars(Span::new(6, 7)), spanned(&source, 6..7), st.clone(), vec![], (), ())
            .unwrap();
        let new_group = target
            .add(
                NodeKind::group(brace_group(5..6, 7..8)),
                spanned(&source, 5..8),
                st.clone(),
                vec![new_three],
                (),
                (),
            )
            .unwrap();
        let new_m = {
            let staged = b.staged_nodes();
            let node = staged.get(m).unwrap();
            target
                .restage_staged_node(
                    node,
                    &[vec![one_a, one_b], vec![new_group], vec![]],
                    |old| (old == group).then_some(new_group),
                    (),
                )
                .unwrap()
        };

        // The staged records, in the replacement layout: prefix sums [0, 2, 3, 3].
        let regions: Vec<(Range<u32>, ContentNodes)> = {
            let view = target.staged_nodes().get(new_m).unwrap();
            match view.kind() {
                NodeKind::Callable(data) => data
                    .arguments
                    .iter()
                    .map(|arg| {
                        let (children, content) = arg.region.as_ref().unwrap().staged().unwrap();
                        (children.clone(), content.clone())
                    })
                    .collect(),
                other => panic!("expected a callable, got {:?}", other),
            }
        };
        assert_eq!(
            regions,
            [
                // Multiplied: the region and its content both grew to two nodes.
                (0..2, ContentNodes::InRegion(0..2)),
                // Shifted by that growth; the content parent mapped, its range kept.
                (2..3, ContentNodes::InChildrenOf(new_group, 0..1)),
                // Dropped: still a *provided* argument, now with an empty region.
                (3..3, ContentNodes::InRegion(0..0)),
            ]
        );

        // And the copy is a well-formed tree once resolved.
        let tree = target.finish(new_m).unwrap();
        check_tree_invariants(&tree);
        let content = tree.root().argument_content_nodes(0).unwrap();
        assert_eq!(content.len(), 2);
        assert_eq!(content.source_text(), Some("12"));
        assert_eq!(
            tree.root().argument_content_nodes(1).unwrap().first().unwrap().chars(),
            Some("3")
        );
        assert!(tree.root().argument_content_nodes(2).unwrap().is_empty());
        assert!(tree.root().arguments().unwrap().get(2).unwrap().is_provided());
    }


    #[test]
    fn restage_staged_node_translates_a_slot_region_through_its_replacements() {
        // The environment shape: a marker argument, then a slot whose content is the
        // children of a body `List`. The marker is dropped and the body is replaced by
        // two lists, so the slot's region moves *and* grows while its content
        // designation still names one mapped body.
        let source: Arc<Source> = Arc::new(Source::new(r"\m*{ab}"));
        let st = state::<PlainLang>();
        let mut b: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let marker = b
            .add(NodeKind::chars(Span::new(2, 3)), spanned(&source, 2..3), st.clone(), vec![], (), ())
            .unwrap();
        let a = b
            .add(NodeKind::chars(Span::new(4, 5)), spanned(&source, 4..5), st.clone(), vec![], (), ())
            .unwrap();
        let b_chars = b
            .add(NodeKind::chars(Span::new(5, 6)), spanned(&source, 5..6), st.clone(), vec![], (), ())
            .unwrap();
        let body = b
            .add(NodeKind::list(), spanned(&source, 4..6), st.clone(), vec![a, b_chars], (), ())
            .unwrap();
        let arg_spec = brace_arg_spec::<PlainLang>();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b
            .add(
                NodeKind::callable(CallableData {
                    callable_type: CT_ENVIRONMENT,
                    name: "m".into(),
                    spec,
                    arguments: vec![ParsedArgument::provided(
                        arg_spec,
                        ChildRegion::new(0..1, ContentNodes::InRegion(0..1)),
                        (),
                    )]
                    .into(),
                    slots: ParsedSlots::new(vec![ParsedSlot::new(
                        ChildRegion::new(1..2, ContentNodes::InChildrenOf(body, 0..2)),
                        "body",
                        SlotRole::Content,
                        (),
                    )]),
                    invocation_syntax: (),
                }),
                SourceSpan::entire(&source),
                st.clone(),
                vec![marker, body],
                (),
                (),
            )
            .unwrap();

        // The replacements: the marker dropped, the body doubled. The mapping points
        // the slot's content at the first of the two bodies.
        let mut target: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let mut new_body = || {
            let a = target
                .add(
                    NodeKind::chars(Span::new(4, 5)),
                    spanned(&source, 4..5),
                    st.clone(),
                    vec![],
                    (),
                    (),
                )
                .unwrap();
            let b = target
                .add(
                    NodeKind::chars(Span::new(5, 6)),
                    spanned(&source, 5..6),
                    st.clone(),
                    vec![],
                    (),
                    (),
                )
                .unwrap();
            target
                .add(NodeKind::list(), spanned(&source, 4..6), st.clone(), vec![a, b], (), ())
                .unwrap()
        };
        let body_a = new_body();
        let body_b = new_body();
        let new_m = {
            let staged = b.staged_nodes();
            let node = staged.get(m).unwrap();
            target
                .restage_staged_node(
                    node,
                    &[vec![], vec![body_a, body_b]],
                    |old| (old == body).then_some(body_a),
                    (),
                )
                .unwrap()
        };

        // The staged records, in the replacement layout: prefix sums [0, 0, 2]. The
        // dropped argument keeps an empty region; the slot region shifted to 0..2 and
        // its content designation names the mapped body, range verbatim.
        let (arguments, slots): (Vec<_>, Vec<_>) = {
            let view = target.staged_nodes().get(new_m).unwrap();
            match view.kind() {
                NodeKind::Callable(data) => (
                    data.arguments
                        .iter()
                        .map(|arg| {
                            let (children, content) =
                                arg.region.as_ref().unwrap().staged().unwrap();
                            (children.clone(), content.clone())
                        })
                        .collect(),
                    data.slots
                        .iter()
                        .map(|slot| {
                            let (children, content) = slot.region.staged().unwrap();
                            (slot.name().map(alloc::string::ToString::to_string), children.clone(), content.clone())
                        })
                        .collect(),
                ),
                other => panic!("expected a callable, got {:?}", other),
            }
        };
        assert_eq!(arguments, [(0..0, ContentNodes::InRegion(0..0))]);
        assert_eq!(
            slots,
            [(
                Some(String::from("body")),
                0..2,
                ContentNodes::InChildrenOf(body_a, 0..2)
            )]
        );

        // Resolved, the slot reads back as the mapped body's two children.
        let tree = target.finish(new_m).unwrap();
        assert!(validate_tree(&tree).is_ok(), "{:?}", validate_tree(&tree));
        let content = tree.root().slot_content_nodes_named("body").unwrap();
        assert_eq!(content.len(), 2);
        assert_eq!(content.first().unwrap().chars(), Some("a"));
        assert_eq!(content.get(1).unwrap().chars(), Some("b"));
        assert_eq!(tree.root().slots().unwrap().get(0).unwrap().role, SlotRole::Content);
        // The dropped argument is still provided, with empty content.
        assert!(tree.root().arguments().unwrap().get(0).unwrap().is_provided());
        assert!(tree.root().argument_content_nodes(0).unwrap().is_empty());
    }

    #[test]
    fn restage_staged_node_reports_an_unmapped_content_parent() {
        let example = staged_example();
        let mut target: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let a_group = example
            .builder
            .staged_nodes()
            .copy_subtree_into(example.a_group, &mut target, &mut |_| ())
            .unwrap();
        let b_group = example
            .builder
            .staged_nodes()
            .copy_subtree_into(example.b_group, &mut target, &mut |_| ())
            .unwrap();
        let staged = example.builder.staged_nodes();
        let node = staged.get(example.frac).unwrap();
        // The mapping knows the first argument's group but not the second's.
        let error = target
            .restage_staged_node(
                node,
                &[vec![a_group], vec![b_group]],
                |old| (old == example.a_group).then_some(a_group),
                (),
            )
            .unwrap_err();
        assert_eq!(
            error,
            NodeBuildError::StagedContentParentUnmapped { parent: example.b_group }
        );
    }

    #[test]
    fn restage_staged_node_needs_one_replacement_entry_per_child() {
        let example = staged_example();
        let mut target: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let staged = example.builder.staged_nodes();
        let node = staged.get(example.frac).unwrap();
        let error = target.restage_staged_node(node, &[], |_| None, ()).unwrap_err();
        assert_eq!(
            error,
            NodeBuildError::ReplacementsLengthMismatch { children: 2, replacements: 0 }
        );
    }

    #[test]
    fn staged_copy_of_an_id_that_was_never_staged_is_an_error() {
        // The view of an empty builder holds no node at all, so the copy names the very
        // id it was asked for.
        let example = staged_example();
        let empty: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let mut target: NodeTreeBuilder<ExtLang> = NodeTreeBuilder::new();
        let error = empty
            .staged_nodes()
            .copy_subtree_into(example.frac, &mut target, &mut |_| ())
            .unwrap_err();
        assert_eq!(error, NodeBuildError::ChildNotStaged { child: example.frac });
    }

    // --- navigation: parent links and position/span lookup ----------------------------

    #[test]
    fn parent_and_index_in_parent_are_o1_lookups() {
        let tree = example_tree();
        let root = tree.root();
        assert!(root.parent().is_none());
        assert!(root.index_in_parent().is_none());
        let frac = root.child(1).unwrap();
        assert_eq!(frac.parent().unwrap().id(), root.id());
        assert_eq!(frac.index_in_parent(), Some(1));
        assert_eq!(root.child(3).unwrap().index_in_parent(), Some(3));
        let a_group = frac.child(0).unwrap();
        let a_chars = a_group.child(0).unwrap();
        assert_eq!(a_chars.parent().unwrap().id(), a_group.id());
        assert_eq!(a_chars.index_in_parent(), Some(0));

        // The documented ancestry-walk one-liner, innermost first.
        let chain: Vec<_> = core::iter::successors(a_chars.parent(), |n| n.parent())
            .map(|n| n.id())
            .collect();
        assert_eq!(chain, vec![a_group.id(), frac.id(), root.id()]);
    }

    #[test]
    fn node_at_finds_the_deepest_containing_node() {
        let tree = example_tree();
        let source = Arc::clone(tree.root().span().source());
        let at = |pos: usize| tree.node_at(&crate::source::SourcePos::new(&source, pos));
        // Deepest: offset 7 is inside "a", inside the first group, inside \frac.
        assert_eq!(at(7).unwrap().chars(), Some("a"));
        // Offsets in a node but in none of its children resolve to that node:
        // 6 is the first group's `{` delimiter, 2 is inside the `\frac` spelling.
        let frac = tree.root().child(1).unwrap();
        assert_eq!(at(6).unwrap().id(), frac.child(0).unwrap().id());
        assert_eq!(at(2).unwrap().id(), frac.id());
        let comment = at(14).unwrap();
        assert_eq!(
            comment.comment().map(|data| data.content.resolve(comment.source())),
            Some(" note")
        );
        // Half-open: one past the end of the last node matches nothing.
        assert!(at(19).is_none());
        // A position in a source the tree does not use matches nothing.
        let other: Arc<Source> = Arc::new(Source::new("x"));
        assert!(tree.node_at(&crate::source::SourcePos::new(&other, 0)).is_none());
    }

    #[test]
    fn node_at_never_matches_empty_spans() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let a = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st.clone(), vec![], (), ()).unwrap();
        let marker =
            b.add(NodeKind::chars(Span::empty(1)), spanned(&source, 1..1), st.clone(), vec![], (), ()).unwrap();
        let b_chars =
            b.add(NodeKind::chars(Span::new(1, 2)), spanned(&source, 1..2), st.clone(), vec![], (), ()).unwrap();
        let root = b
            .add(NodeKind::list(), SourceSpan::entire(&source), st.clone(), vec![a, marker, b_chars], (), ())
            .unwrap();
        let tree = b.finish(root).unwrap();
        // The empty-span node at offset 1 never matches; its non-empty sibling does.
        let hit = tree.node_at(&crate::source::SourcePos::new(&source, 1)).unwrap();
        assert_eq!(hit.chars(), Some("b"));
    }

    /// An `\input`-like shape: the resolved content (its own `Source`) attached as
    /// an `Attached` slot below the callable, between same-source siblings.
    fn input_like_tree() -> (NodeTree<PlainLang>, Arc<Source>, Arc<Source>) {
        let main: Arc<Source> = Arc::new(Source::new(r"x\input{f}y"));
        let inc: Arc<Source> =
            Arc::new(Source::resolved("ab", "f", SourceSpan::new(&main, 1..10)));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let x = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&main, 0..1), st.clone(), vec![], (), ()).unwrap();
        let ab =
            b.add(NodeKind::chars(Span::new(0, 2)), SourceSpan::entire(&inc), st.clone(), vec![], (), ()).unwrap();
        let body = b.add(NodeKind::list(), SourceSpan::entire(&inc), st.clone(), vec![ab], (), ()).unwrap();
        let input = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "input".into(),
                spec: Arc::new(StdCallableSpec::default()) as Arc<dyn CallableSpec<PlainLang>>,
                arguments: ParsedArguments::empty(),
                slots: ParsedSlots::new(vec![ParsedSlot::new(
                    ChildRegion::new(0..1, ContentNodes::InChildrenOf(body, 0..1)),
                    "attached",
                    SlotRole::Attached,
                    (),
                )]),
                invocation_syntax: (),
            }),
            spanned(&main, 1..10),
            st.clone(),
            vec![body],
            (),
            (),
        ).unwrap();
        let y = b.add(NodeKind::chars(Span::new(10, 11)), spanned(&main, 10..11), st.clone(), vec![], (), ()).unwrap();
        let root = b
            .add(NodeKind::list(), SourceSpan::entire(&main), st.clone(), vec![x, input, y], (), ())
            .unwrap();
        (b.finish(root).unwrap(), main, inc)
    }

    #[test]
    fn lookups_descend_per_source_across_attached_content() {
        let (tree, main, inc) = input_like_tree();
        let input = tree.root().child(1).unwrap();
        // A position in the attached source is found inside the attached content
        // (different-source nodes on the way are traversed, never matched).
        let hit = tree.node_at(&crate::source::SourcePos::new(&inc, 1)).unwrap();
        assert_eq!(hit.chars(), Some("ab"));
        // A position in the including source, inside the `\input` trigger, stops at
        // the callable: a matching node never descends into different-source children.
        assert_eq!(
            tree.node_at(&crate::source::SourcePos::new(&main, 3)).unwrap().id(),
            input.id()
        );
        // Span queries answer per source the same way.
        let run = tree.covering_slice(&SourceSpan::new(&inc, 0..2)).unwrap();
        assert_eq!(run.len(), 1);
        assert_eq!(run.first().unwrap().chars(), Some("ab"));
        let run = tree.covering_slice(&SourceSpan::new(&main, 1..10)).unwrap();
        assert_eq!(run.len(), 1);
        assert_eq!(run.first().unwrap().id(), input.id());
    }

    #[test]
    fn validate_tree_accepts_multi_source_trees() {
        // The all-trees law is source-blind: the `\input`-like shape — attached-source
        // children under a same-source sibling run — passes `validate_tree`, even
        // though the span-tiling law's byte accounting (children share the parent's source,
        // interior partition) does not hold for it.
        let (tree, _main, _inc) = input_like_tree();
        validate_tree(&tree).unwrap();
    }

    #[test]
    fn covering_slice_finds_the_minimal_sibling_run() {
        let tree = example_tree();
        let source = Arc::clone(tree.root().span().source());
        let q = |range: Range<usize>| SourceSpan::new(&source, range);
        let frac = tree.root().child(1).unwrap();

        // A query equal to one deep node's span: that node, as a single-node run.
        let run = tree.covering_slice(&q(7..8)).unwrap();
        assert_eq!(run.len(), 1);
        assert_eq!(run.first().unwrap().chars(), Some("a"));

        // A query cutting into the middle of nodes covers the whole nodes:
        // bytes 0..8 need the `x` chars node and the whole `\frac{a}{b}` callable.
        let run = tree.covering_slice(&q(0..8)).unwrap();
        assert_eq!(run.len(), 2);
        assert_eq!(run.first().unwrap().chars(), Some("x"));
        assert_eq!(run.last().unwrap().id(), frac.id());

        // Inside the callable: both argument groups, the minimal run of its children.
        let run = tree.covering_slice(&q(6..12)).unwrap();
        assert_eq!(run.len(), 2);
        assert_eq!(run.range(), frac.children().range());

        // Query bytes inside the trigger spelling: the children cannot cover them —
        // the covering node itself, as a single-node run within its parent's list.
        let run = tree.covering_slice(&q(5..8)).unwrap();
        assert_eq!(run.len(), 1);
        assert_eq!(run.first().unwrap().id(), frac.id());

        // An empty query resolves by point containment, like node_at.
        let run = tree.covering_slice(&q(7..7)).unwrap();
        assert_eq!(run.len(), 1);
        assert_eq!(run.first().unwrap().chars(), Some("a"));

        // No node of the tree lies in the query's source: no answer.
        let other: Arc<Source> = Arc::new(Source::new("x\\frac{a}{b} % note"));
        assert!(tree.covering_slice(&SourceSpan::new(&other, 0..2)).is_none());
    }

    // --- slices: the whole-run single-source contract ---------------------------------

    #[test]
    fn slice_span_answers_only_whole_single_source_runs() {
        // Parsed single-source tree: the O(1) fast path answers, exactly.
        let tree = example_tree();
        assert!(tree.is_single_source());
        let children = tree.root().children();
        assert_eq!(children.span().unwrap().range(), 0..19);
        assert_eq!(children.source_text(), Some("x\\frac{a}{b} % note"));

        // Splice a foreign-source *middle* sibling via the restage door: the
        // endpoints still agree on the source, the run as a whole does not — no
        // single-source answer from either accessor.
        let foreign: Arc<Source> = Arc::new(Source::new("Z"));
        let st = state::<PlainLang>();
        let root = tree.root();
        let mut b = NodeTreeBuilder::new();
        let x2 = super::copy::copy_subtree_into(&mut b, root.child(0).unwrap(), &mut |_| ()).unwrap();
        let frac2 = super::copy::copy_subtree_into(&mut b, root.child(1).unwrap(), &mut |_| ()).unwrap();
        let z = b
            .add(NodeKind::chars(Span::new(0, 1)), SourceSpan::entire(&foreign), st.clone(), vec![], (), ())
            .unwrap();
        let c2 = super::copy::copy_subtree_into(&mut b, root.child(3).unwrap(), &mut |_| ()).unwrap();
        let new_root = b
            .restage_node(root, &[vec![x2], vec![frac2], vec![z], vec![c2]], |_| None, ())
            .unwrap();
        let spliced = b.finish(new_root).unwrap();
        assert!(!spliced.is_single_source());

        let run = spliced.root().children();
        // The endpoint check alone would have answered — the whole-run check must not.
        assert!(run.first().unwrap().span().same_source(run.last().unwrap().span()));
        assert_eq!(run.span(), None);
        assert_eq!(run.source_text(), None);

        // Runs avoiding the foreign node still answer (scanned, without the flag).
        let frac_children = spliced.root().child(1).unwrap().children();
        assert_eq!(frac_children.span().unwrap().range(), 6..12);
        assert_eq!(frac_children.source_text(), Some("{a}{b}"));
        // A run that IS the foreign node answers in the foreign source.
        let z_run = spliced.root().child(2).unwrap();
        assert_eq!(
            NodeSlice::new(&spliced, z_run.id().index() as u32..z_run.id().index() as u32 + 1)
                .source_text(),
            Some("Z")
        );
    }

    // --- the level-0 restage primitive ------------------------------------------------

    /// A callable whose one argument region holds two children (noise + content),
    /// with an `InRegion` content designation — the shape whose region arithmetic
    /// `restage_node` must translate through the replacement prefix sums.
    /// (`r"\m x y"`: `x` is region noise, `y` the designated content.)
    fn two_child_region_tree() -> NodeTree<PlainLang> {
        let source: Arc<Source> = Arc::new(Source::new(r"\m x y"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::new();
        let x = b.add(NodeKind::chars(Span::new(3, 4)), spanned(&source, 3..4), st.clone(), vec![], (), ()).unwrap();
        let y = b.add(NodeKind::chars(Span::new(5, 6)), spanned(&source, 5..6), st.clone(), vec![], (), ()).unwrap();
        let arg_spec = brace_arg_spec();
        let spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(StdCallableSpec { arguments: vec![arg_spec.clone()], ..Default::default() });
        let m = b.add(
            NodeKind::callable(CallableData {
                callable_type: CT_MACRO,
                name: "m".into(),
                spec,
                arguments: vec![ParsedArgument::provided(
                    arg_spec,
                    ChildRegion::new(0..2, ContentNodes::InRegion(1..2)),
                    (),
                )]
                .into(),
                slots: ParsedSlots::empty(),
                invocation_syntax: (),
            }),
            SourceSpan::entire(&source),
            st.clone(),
            vec![x, y],
            (),
            (),
        ).unwrap();
        b.finish(m).unwrap()
    }

    #[test]
    fn restage_node_shrinks_regions_under_dropped_children() {
        let tree = two_child_region_tree();
        let m = tree.root();
        let mut b = NodeTreeBuilder::new();
        // Keep only the content child ("y"); the noise child is dropped. The region
        // shrinks from two children to one, and the InRegion designation re-bases.
        let y2 = super::copy::copy_subtree_into(&mut b, m.child(1).unwrap(), &mut |_| ()).unwrap();
        let root = b.restage_node(m, &[vec![], vec![y2]], |_| None, ()).unwrap();
        let new = b.finish(root).unwrap();
        assert_eq!(new.root().child_count(), 1);
        assert!(new.root().arguments().unwrap().get(0).unwrap().is_provided());
        assert_eq!(new.root().argument_nodes(0).unwrap().len(), 1);
        let content = new.root().argument_content_nodes(0).unwrap();
        assert_eq!(content.len(), 1);
        assert_eq!(content.first().unwrap().chars(), Some("y"));
    }

    #[test]
    fn restage_node_keeps_an_emptied_region_provided() {
        let tree = two_child_region_tree();
        let m = tree.root();
        let mut b = NodeTreeBuilder::new();
        // Every region child dropped: provided-with-an-empty-region, not absent.
        let root = b.restage_node(m, &[vec![], vec![]], |_| None, ()).unwrap();
        let new = b.finish(root).unwrap();
        assert_eq!(new.root().child_count(), 0);
        let arg = new.root().arguments().unwrap().get(0).unwrap();
        assert!(arg.is_provided());
        assert_eq!(new.root().argument_nodes(0).unwrap().len(), 0);
        assert_eq!(new.root().argument_content_nodes(0).unwrap().len(), 0);
    }

    #[test]
    fn restage_node_grows_regions_under_multiplied_children() {
        let tree = two_child_region_tree();
        let m = tree.root();
        let mut b = NodeTreeBuilder::new();
        let x2 = super::copy::copy_subtree_into(&mut b, m.child(0).unwrap(), &mut |_| ()).unwrap();
        // The content child is replaced by two nodes: the region grows to three
        // children and the content designation covers both replacements.
        let y2a = super::copy::copy_subtree_into(&mut b, m.child(1).unwrap(), &mut |_| ()).unwrap();
        let y2b = super::copy::copy_subtree_into(&mut b, m.child(1).unwrap(), &mut |_| ()).unwrap();
        let root = b.restage_node(m, &[vec![x2], vec![y2a, y2b]], |_| None, ()).unwrap();
        let new = b.finish(root).unwrap();
        assert_eq!(new.root().child_count(), 3);
        assert_eq!(new.root().argument_nodes(0).unwrap().len(), 3);
        let content = new.root().argument_content_nodes(0).unwrap();
        assert_eq!(content.len(), 2);
        assert!(content.iter().all(|node| node.chars() == Some("y")));
    }

    #[test]
    fn restage_node_is_the_cross_tree_splice_door() {
        // The input NodeRef comes from a *different* tree than the builder's staged
        // nodes — sanctioned by contract (no same-tree assertion, ever).
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();
        let mut b = NodeTreeBuilder::new();
        let ag2 = super::copy::copy_subtree_into(&mut b, frac.child(0).unwrap(), &mut |_| ()).unwrap();
        let bg2 = super::copy::copy_subtree_into(&mut b, frac.child(1).unwrap(), &mut |_| ()).unwrap();
        let a_group_id = frac.child(0).unwrap().id();
        let b_group_id = frac.child(1).unwrap().id();
        let map = move |old: NodeId| {
            if old == a_group_id {
                Some(ag2)
            } else if old == b_group_id {
                Some(bg2)
            } else {
                None
            }
        };
        let root = b.restage_node(frac, &[vec![ag2], vec![bg2]], map, ()).unwrap();
        let new = b.finish(root).unwrap();
        // The records were translated: content designations reach into the new
        // groups (InChildrenOf parents mapped through the callback).
        assert_eq!(
            new.root().argument_content_nodes(0).unwrap().first().unwrap().chars(),
            Some("a")
        );
        assert_eq!(new.root().argument_nodes(1).unwrap().source_text(), Some("{b}"));
        // Spec, state, span, and name are cloned/shared from the old tree's node.
        assert!(Arc::ptr_eq(new.root().spec().unwrap(), frac.spec().unwrap()));
        assert!(Arc::ptr_eq(new.root().parsing_state(), frac.parsing_state()));
        assert_eq!(new.root().span(), frac.span());
        assert_eq!(new.root().name(), Some("frac"));
    }

    #[test]
    fn restage_node_reports_unmapped_content_parents() {
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();
        let a_group_id = frac.child(0).unwrap().id();
        let mut b = NodeTreeBuilder::new();
        let ag2 = super::copy::copy_subtree_into(&mut b, frac.child(0).unwrap(), &mut |_| ()).unwrap();
        let bg2 = super::copy::copy_subtree_into(&mut b, frac.child(1).unwrap(), &mut |_| ()).unwrap();
        let err = b.restage_node(frac, &[vec![ag2], vec![bg2]], |_| None, ()).unwrap_err();
        assert_eq!(err, NodeBuildError::ContentParentUnmapped { parent: a_group_id });
    }

    #[test]
    fn restage_node_demands_one_replacement_entry_per_child() {
        let tree = example_tree();
        let frac = tree.root().child(1).unwrap();
        let mut b = NodeTreeBuilder::new();
        let ag2 = super::copy::copy_subtree_into(&mut b, frac.child(0).unwrap(), &mut |_| ()).unwrap();
        let err = b.restage_node(frac, &[vec![ag2]], |_| None, ()).unwrap_err();
        assert_eq!(
            err,
            NodeBuildError::ReplacementsLengthMismatch { children: 2, replacements: 1 }
        );
    }

    #[test]
    fn restage_node_clones_the_ext_verbatim() {
        // Build the MintLang `x{a}` tree (exts minted bottom-up), then restage the
        // group with a *doubled* child: the copy's ext must be the old node's ext
        // verbatim — never re-minted from the new children.
        let source: Arc<Source> = Arc::new(Source::new("x{a}"));
        let st = state::<MintLang>();
        let mut b: NodeTreeBuilder<MintLang> = NodeTreeBuilder::new();
        let stage = |b: &mut NodeTreeBuilder<MintLang>,
                     kind: NodeKind<MintLang>,
                     span: SourceSpan,
                     children: Vec<BuildId>| {
            let ext = MintLang::make_node_ext(&kind, &span, &st, b.staged_children(&children))
                .unwrap();
            b.add(kind, span, st.clone(), children, ext, ()).unwrap()
        };
        let a = stage(&mut b, NodeKind::chars(Span::new(2, 3)), spanned(&source, 2..3), vec![]);
        let g = stage(&mut b, NodeKind::group(brace_group(1..2, 3..4)), spanned(&source, 1..4), vec![a]);
        let tree = b.finish(g).unwrap();
        assert_eq!(*tree.root().ext(), MintExt { descendants: 1, chars_below: 1 });

        let mut b: NodeTreeBuilder<MintLang> = NodeTreeBuilder::new();
        let a1 = super::copy::copy_subtree_into(&mut b, tree.root().child(0).unwrap(), &mut |_| ()).unwrap();
        let a2 = super::copy::copy_subtree_into(&mut b, tree.root().child(0).unwrap(), &mut |_| ()).unwrap();
        let root = b.restage_node(tree.root(), &[vec![a1, a2]], |_| None, ()).unwrap();
        let new = b.finish(root).unwrap();
        assert_eq!(new.root().child_count(), 2);
        // Cloned verbatim: still the old facts, although two chars now sit below.
        assert_eq!(*new.root().ext(), MintExt { descendants: 1, chars_below: 1 });
        // The copied children carry their old exts verbatim too.
        assert_eq!(
            *new.root().child(0).unwrap().ext(),
            MintExt { descendants: 0, chars_below: 0 }
        );
    }

    #[test]
    fn restage_node_supplies_the_callers_annotation() {
        let tree = two_child_region_tree();
        let m = tree.root();
        let st = state::<PlainLang>();
        let mut b: NodeTreeBuilder<PlainLang, &str> = NodeTreeBuilder::new();
        let y2 = b
            .add(
                NodeKind::chars(Span::new(5, 6)),
                m.child(1).unwrap().span().clone(),
                st.clone(),
                vec![],
                (),
                "child",
            )
            .unwrap();
        let root = b.restage_node(m, &[vec![], vec![y2]], |_| None, "restaged").unwrap();
        let new = b.finish(root).unwrap();
        assert_eq!(*new.root().annotation(), "restaged");
        assert_eq!(*new.root().child(0).unwrap().annotation(), "child");
    }

    #[test]
    fn tree_get_is_the_non_panicking_node_access() {
        let tree = example_tree();
        assert!(tree.get(tree.root().id()).is_some());
        let deep = tree.iter_storage_order().last().unwrap().id();
        assert_eq!(tree.get(deep).unwrap().id(), deep);

        // An id from a different tree misses (out of range here; debug builds also
        // catch in-range foreign ids by provenance tag).
        let source: Arc<Source> = Arc::new(Source::new("w"));
        let st = state::<PlainLang>();
        let mut b = NodeTreeBuilder::<PlainLang>::new();
        let w = b.add(NodeKind::chars(Span::new(0, 1)), spanned(&source, 0..1), st, vec![], (), ()).unwrap();
        let small = b.finish(w).unwrap();
        assert!(small.get(deep).is_none());
    }
}