techy 0.1.3

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
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
//! Where callable definitions are stored, and how a name is looked up.
//!
//! A **provider** ([`SpecsProvider`]) is a named store of definitions: it answers a
//! [`CallableQuery`] — an invocation form plus a name — with a [`CallableSpec`] or with
//! "not defined here". The providers in effect are held in order by a [`ScopeStack`],
//! which the parsing state holds ([`StateData::scopes`](crate::core::StateData)).
//!
//! **A name is looked up innermost first**: the provider pushed last is asked first,
//! and the first one that answers wins. Loading a package that redefines a name
//! therefore shadows the definition below it, and a definition made inside a group
//! disappears again when the group ends. When no provider answers, the callable is
//! unresolvable, and the miss reports which providers were searched
//! ([`ScopeStack::searched_providers`]).
//!
//! Three provider implementations ship:
//!
//! - [`Package`] — immutable: built once with [`insert`](Package::insert), then loaded
//!   wholesale. A package, or any single entry in it, may be restricted to certain
//!   parsing modes, and a package may also define specials as data (trigger strings
//!   such as `---`).
//! - [`Scope`] — the target of definitions made during a parse ([`ScopeOp::Define`]).
//!   Updating one produces a new `Scope` instead of changing the old one, which is what
//!   makes group-local definitions revert.
//! - [`FallbackProvider`] — answers *any* name of the callable types registered with
//!   it, so an unknown callable still resolves to a spec. It goes at the bottom of the
//!   stack, where anything defined above it shadows it.
//!
//! [`ErrorCallableSpec`] is the definition that means "invoking this name is an error":
//! the invocation records a [`CallableDefinedAsError`] diagnostic and recovers. Storing
//! it over an existing definition is how a name is taken away again without unloading
//! the package that defined it.
//!
//! # Changing definitions during a parse
//!
//! A parsing state delta contains [`ScopeOp`]s
//! ([`ParsingStateDelta::scope_ops`](crate::core::ParsingStateDelta)): operations on the
//! shape of the stack (push, unload, replace one provider, replace the whole stack) and
//! definition operations addressed to a provider by name, which reach that provider as
//! [`DefinitionOp`]s through [`with_definitions`](SpecsProvider::with_definitions).
//! Operations carry provider `Arc`s directly; the core keeps no registry mapping
//! package names to packages, so a by-name `load("amsmath")` belongs to a preset's
//! driver helpers, which build the `Arc` when they build the delta.
//!
//! Reverting is structural: an outer parsing state still holds the previous `Arc`s, so
//! both a provider pushed for a group and an updated copy of an outer scope are gone
//! when the group ends, at no per-group cost. Failed operations surface through the
//! fallible [`ParsingState::derived`](crate::core::ParsingState::derived) — see
//! [`ScopeOpError`] and [`DeriveError`](crate::core::DeriveError).
//!
//! # Specials across providers
//!
//! [`ScopeStack::scan_specials`] consults every provider innermost-first: the
//! **longest match wins, and ties go to the innermost provider** — pylatexenc's
//! `test_for_specials` behavior, so `---` beats `--` wherever the two are defined.
//! Since two equally long matches at one position are the same spelling, the tie rule
//! is what makes a redefined special shadow the previous definition. A provider's scan
//! error stops the search and propagates.
//!
//! The guide chapter
//! [Defining macros, environments, and specials](crate::guide::specs) covers all of
//! this from the user's side.

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;

use hashbrown::HashMap;

use crate::constructs::{
    ConstructParser, ConstructParserResult, ImplementationError, Invocation, ParseContext,
};
use crate::error::{Diagnostic, DiagnosticInfo, Diagnostics};
use crate::node::{BuildId, NodeKind};
use crate::serialize::SerializableObject;
use crate::source::{Source, SourceSpan, Span};
use crate::spec::{CallableSpec, IntoCallableSpec};
use crate::state::{
    ClosedVocabulary, FeaturePresence, Lang, LangFeatures, LangHasScopes, ParsingState,
    ParsingStateDelta,
};
use crate::token::{
    SpecialsMatch, SpecialsScanError, TokenErrorKind, TriggerChars,
};

mod provenance;

pub use provenance::{DefinitionKey, SpecProvenance};

/// The syntax through which a callable invocation was recognized.
///
/// Carried on a [`CallableQuery`] so resolvers can disambiguate between coexisting
/// command syntaxes — with several [`CommandRule`](crate::core::token::CommandRule)s in scope,
/// `\foo` and `#foo` both tokenize as `Command { name: "foo" }`, and the escape character
/// is *not* recoverable from the token alone (a resolver has no access to the source
/// content behind the token's span).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallableSyntax {
    /// A command token: escape character + name (`\foo`).
    Command {
        /// The escape character that fired ([`CommandRule::escape_char`](crate::core::token::CommandRule)).
        escape_char: char,
    },
    /// A specials trigger (queried from inside a `Lang::scan_specials` implementation,
    /// before any token exists).
    Specials,
    /// Anything else — synthesized invocations, preset-defined resolution paths.
    Other,
}

/// A callable resolution request: everything a [`SpecsProvider`] may dispatch on, minus
/// the parsing state (passed alongside).
///
/// Scopes and packages look a callable up by **name and callable syntax** (e.g. the
/// escape character that fired); they never see the token. A language that must
/// dispatch on token details does so in
/// [`ParseDriver::resolve_command`](crate::core::ParseDriver::resolve_command),
/// which receives the token and its reader, before or instead of consulting the
/// scopes.
pub struct CallableQuery<'a, L: Lang> {
    /// The invocation form being resolved (e.g. the preset's macro form).
    pub callable_type: L::CallableTypeId,
    /// The name to resolve. Providers store *normalized* names; normalization is the
    /// caller's (preset's) business — the core matches exactly.
    pub name: &'a str,
    /// The syntax context of the invocation.
    pub syntax: CallableSyntax,
}

impl<'a, L: Lang> CallableQuery<'a, L> {
    /// A resolution request for `name` under `callable_type`, in `syntax`'s context.
    pub fn new(
        callable_type: L::CallableTypeId,
        name: &'a str,
        syntax: CallableSyntax,
    ) -> CallableQuery<'a, L> {
        CallableQuery { callable_type, name, syntax }
    }
}

// Manual impls: derives would demand `L: Clone`/`L: Debug` although only references and
// plain data are stored.

impl<L: Lang> Clone for CallableQuery<'_, L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lang> Copy for CallableQuery<'_, L> {}

impl<L: Lang> fmt::Debug for CallableQuery<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CallableQuery")
            .field("callable_type", &self.callable_type)
            .field("name", &self.name)
            .field("syntax", &self.syntax)
            .finish()
    }
}

// --- provider failure shapes ---------------------------------------------------------

/// A [`SpecsProvider`] operation failed — the provider-level error of
/// [`retrieve_spec`](SpecsProvider::retrieve_spec) and
/// [`with_definitions`](SpecsProvider::with_definitions). Structured for testability; custom providers report anything beyond the
/// named cases through [`Failed`](ProviderError::Failed).
///
/// A provider error is an *operational* failure (misconfiguration, extension bug, backing
/// I/O), never a source condition: source-shaped failures of the specials scan travel as
/// [`TokenError`](crate::core::token::TokenError)s instead, and "this name is an error" is
/// expressed as an ordinary [`ErrorCallableSpec`] definition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProviderError {
    /// The provider does not accept definition ops (the default
    /// [`with_definitions`](SpecsProvider::with_definitions) — e.g. a [`Package`]).
    NotMutable,
    /// An op referenced a name the provider does not define
    /// ([`DefinitionOp::Remove`] of an absent definition).
    UndefinedName {
        /// The name the op referenced.
        name: Box<str>,
    },
    /// A provider-specific failure, rendered as a message.
    Failed(Box<str>),
}

impl fmt::Display for ProviderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProviderError::NotMutable => {
                write!(f, "the provider does not accept definition ops")
            }
            ProviderError::UndefinedName { name } => {
                write!(f, "no definition named ‘{name}’ in this provider")
            }
            ProviderError::Failed(message) => write!(f, "{message}"),
        }
    }
}

/// A provider *within a stack* failed: the [`ProviderError`] plus which provider it was.
/// The `Err` of [`ScopeStack::retrieve_spec`] — a failing provider stops the search —
/// and the payload of [`ScopeOpError::Provider`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeStackError {
    /// The name of the provider that failed.
    pub provider: Box<str>,
    /// What went wrong.
    pub error: ProviderError,
}

impl fmt::Display for ScopeStackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "provider ‘{}’: {}", self.provider, self.error)
    }
}

impl core::error::Error for ProviderError {}

impl core::error::Error for ScopeStackError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// One [`ScopeOp`] failed while a delta was applied.
///
/// This is the per-op failure record collected by the fallible
/// [`ParsingState::derived`](crate::core::ParsingState::derived) into a
/// [`DeriveError`](crate::core::DeriveError).
///
/// The record is mechanical, not classified: the *caller* decides what a failure
/// means — the in-parse derivation path treats it as a recoverable condition,
/// reported through the recovery entry point
/// ([`ScopeOpFailed`](crate::core::constructs::ScopeOpFailed)); an embedder applying a
/// delta out of parse treats it as its own input error.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeOpError {
    /// The op targeted a provider name not on the stack ([`ScopeOp::Unload`],
    /// [`ScopeOp::Replace`], [`ScopeOp::Remove`]; [`ScopeOp::Define`] instead creates
    /// the scope lazily).
    UnknownProvider {
        /// The name the op targeted.
        name: Box<str>,
    },
    /// The targeted provider rejected or failed the op.
    Provider(ScopeStackError),
    /// The stack belongs to a language that declares the scope stack absent
    /// ([`Lang::Features`]): no scope operation can apply. Reachable only by calling
    /// [`ScopeStack::apply_op`] directly on such a stack — a state delta can never
    /// carry scope ops for one, because the delta's scope-op list is stored through
    /// the same declaration and holds nothing for it.
    ScopesAbsent,
}

impl fmt::Display for ScopeOpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScopeOpError::UnknownProvider { name } => {
                write!(f, "no provider named ‘{name}’ on the scope stack")
            }
            ScopeOpError::Provider(error) => fmt::Display::fmt(error, f),
            ScopeOpError::ScopesAbsent => write!(
                f,
                "the language declares the scope stack absent; no scope operation can apply"
            ),
        }
    }
}

impl core::error::Error for ScopeOpError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            ScopeOpError::UnknownProvider { .. } => None,
            ScopeOpError::Provider(error) => Some(error),
            ScopeOpError::ScopesAbsent => None,
        }
    }
}

// --- ops -------------------------------------------------------------------------------

/// A definition operation as a [`SpecsProvider`] receives it
/// ([`with_definitions`](SpecsProvider::with_definitions)): the provider *is* the scope,
/// so — unlike the delta-level [`ScopeOp`] — no target name is carried.
pub enum DefinitionOp<L: Lang> {
    /// Define `name` under the invocation form `callable_type` (replacing any existing
    /// definition under that key — shadowing within one provider is replacement).
    Define {
        /// The invocation form the definition answers.
        callable_type: L::CallableTypeId,
        /// The (normalized) name being defined.
        name: Box<str>,
        /// The behavior spec.
        spec: Arc<dyn CallableSpec<L>>,
    },
    /// Remove the definition of `name` under `callable_type`. Removing an absent
    /// definition is an error ([`ProviderError::UndefinedName`]), never a silent no-op —
    /// the op builder can always check the visible state first.
    Remove {
        /// The invocation form the definition answers.
        callable_type: L::CallableTypeId,
        /// The (normalized) name to remove.
        name: Box<str>,
    },
}

impl<L: Lang> Clone for DefinitionOp<L> {
    fn clone(&self) -> Self {
        match self {
            DefinitionOp::Define { callable_type, name, spec } => DefinitionOp::Define {
                callable_type: *callable_type,
                name: name.clone(),
                spec: Arc::clone(spec),
            },
            DefinitionOp::Remove { callable_type, name } => {
                DefinitionOp::Remove { callable_type: *callable_type, name: name.clone() }
            }
        }
    }
}

impl<L: Lang> fmt::Debug for DefinitionOp<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DefinitionOp::Define { callable_type, name, spec } => f
                .debug_struct("Define")
                .field("callable_type", callable_type)
                .field("name", name)
                .field("spec", spec)
                .finish(),
            DefinitionOp::Remove { callable_type, name } => f
                .debug_struct("Remove")
                .field("callable_type", callable_type)
                .field("name", name)
                .finish(),
        }
    }
}

/// One scope-stack operation of a state delta
/// ([`ParsingStateDelta::scope_ops`](crate::core::ParsingStateDelta)).
///
/// The variants are stack-shape ops plus definition ops routed to a named provider.
/// Ops apply in delta order, each on the result of the previous; failures are
/// collected per op (the rest still apply) and surface through the fallible
/// [`derived()`](crate::core::ParsingState::derived).
///
/// Name-targeted ops address the **innermost** provider with that name.
pub enum ScopeOp<L: Lang> {
    /// Push a provider as the new innermost entry.
    Push(Arc<dyn SpecsProvider<L>>),
    /// Remove the innermost provider named `name` from the stack. Absent name: error.
    Unload {
        /// The provider name to unload.
        name: Box<str>,
    },
    /// Replace the innermost provider named `name` with `provider` (same stack
    /// position). Absent name: error.
    Replace {
        /// The provider name to replace.
        name: Box<str>,
        /// The replacement.
        provider: Arc<dyn SpecsProvider<L>>,
    },
    /// Replace the whole stack, outermost first.
    ReplaceStack(Vec<Arc<dyn SpecsProvider<L>>>),
    /// Define `(callable_type, name)` in the provider named `scope`, through its
    /// [`with_definitions`](SpecsProvider::with_definitions) (copy-on-write: the stack
    /// entry is replaced by the returned provider). If no provider named `scope` is on
    /// the stack, a fresh [`Scope`] with that name is created **innermost**, holding
    /// the definition — scopes are created lazily on first `Define`, never eagerly per
    /// group. Targeting an immutable provider (a
    /// [`Package`]) is an error.
    Define {
        /// The name of the provider to define into.
        scope: Box<str>,
        /// The invocation form the definition answers.
        callable_type: L::CallableTypeId,
        /// The (normalized) name being defined.
        name: Box<str>,
        /// The behavior spec.
        spec: Arc<dyn CallableSpec<L>>,
    },
    /// Remove the definition of `(callable_type, name)` from the provider named
    /// `scope` (via `with_definitions`, copy-on-write). Absent provider or absent
    /// definition: error. Note that removal deletes from that provider only — a
    /// definition shadowed by *other* providers stays resolvable; "removing" a
    /// [`Package`] definition is expressed by shadowing it with an
    /// [`ErrorCallableSpec`] or unloading the package.
    Remove {
        /// The name of the provider to remove from.
        scope: Box<str>,
        /// The invocation form the definition answers.
        callable_type: L::CallableTypeId,
        /// The (normalized) name to remove.
        name: Box<str>,
    },
}

impl<L: Lang> Clone for ScopeOp<L> {
    fn clone(&self) -> Self {
        match self {
            ScopeOp::Push(provider) => ScopeOp::Push(Arc::clone(provider)),
            ScopeOp::Unload { name } => ScopeOp::Unload { name: name.clone() },
            ScopeOp::Replace { name, provider } => {
                ScopeOp::Replace { name: name.clone(), provider: Arc::clone(provider) }
            }
            ScopeOp::ReplaceStack(providers) => ScopeOp::ReplaceStack(providers.clone()),
            ScopeOp::Define { scope, callable_type, name, spec } => ScopeOp::Define {
                scope: scope.clone(),
                callable_type: *callable_type,
                name: name.clone(),
                spec: Arc::clone(spec),
            },
            ScopeOp::Remove { scope, callable_type, name } => ScopeOp::Remove {
                scope: scope.clone(),
                callable_type: *callable_type,
                name: name.clone(),
            },
        }
    }
}

impl<L: Lang> fmt::Debug for ScopeOp<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScopeOp::Push(provider) => f.debug_tuple("Push").field(provider).finish(),
            ScopeOp::Unload { name } => {
                f.debug_struct("Unload").field("name", name).finish()
            }
            ScopeOp::Replace { name, provider } => f
                .debug_struct("Replace")
                .field("name", name)
                .field("provider", provider)
                .finish(),
            ScopeOp::ReplaceStack(providers) => {
                f.debug_tuple("ReplaceStack").field(providers).finish()
            }
            ScopeOp::Define { scope, callable_type, name, spec } => f
                .debug_struct("Define")
                .field("scope", scope)
                .field("callable_type", callable_type)
                .field("name", name)
                .field("spec", spec)
                .finish(),
            ScopeOp::Remove { scope, callable_type, name } => f
                .debug_struct("Remove")
                .field("scope", scope)
                .field("callable_type", callable_type)
                .field("name", name)
                .finish(),
        }
    }
}

// --- the provider contract -------------------------------------------------------------

/// A named store of callable definitions: one entry of a [`ScopeStack`].
///
/// A provider answers a [`CallableQuery`] through
/// [`retrieve_spec`](SpecsProvider::retrieve_spec). It may additionally take part in
/// the tokenizer's specials scan ([`scan_specials`](SpecsProvider::scan_specials) and
/// [`specials_trigger_chars`](SpecsProvider::specials_trigger_chars)), accept changes
/// to its definitions ([`with_definitions`](SpecsProvider::with_definitions)), and list
/// what it defines ([`iter_symbols`](SpecsProvider::iter_symbols)); only
/// [`name`](SpecsProvider::name) and `retrieve_spec` have to be implemented.
///
/// The shipped implementations are [`Package`], [`Scope`] and [`FallbackProvider`].
/// Implement the trait yourself for a store of a different kind — a large spec database
/// that loads definitions on demand, for instance, which no fixed data structure could
/// express.
///
/// # Implementing this trait
///
/// **Thread safety is part of the contract** (`Send + Sync` supertraits; see
/// [`CallableSpec`]'s note): every method takes `&self`, so a stateful implementation (a
/// memo cache, a database connection) needs interior mutability regardless — under this
/// contract that means `Mutex`/`RwLock`, not `RefCell`.
///
/// **Downcasting is part of the contract** (`Any` supertrait; [`CallableSpec`]'s
/// downcasting note applies): a consumer recovers a provider's concrete type from a
/// stored `Arc<dyn SpecsProvider<L>>` or `&dyn SpecsProvider<L>`.
///
/// **Serialization is part of the contract** ([`SerializableObject`] supertrait;
/// [`CallableSpec`]'s serialization note applies): a provider on a parsing state's
/// scope stack must be serializable through the `Arc<dyn SpecsProvider<L>>` the stack
/// holds, so the write-side capability sits on every provider type. Fully defaulted:
/// a type that does not participate in serialization adds the one-line empty impl
/// (`impl<L: Lang> SerializableObject<L> for MyProvider<L> {}`); a participating type
/// overrides [`serialize_object`](SerializableObject::serialize_object). Callable
/// only for a language that implements
/// [`SerializableLang`](crate::serialize::SerializableLang).
pub trait SpecsProvider<L: Lang>: fmt::Debug + Send + Sync + Any + SerializableObject<L> {
    /// The provider's name: how definition ops target it ([`ScopeOp::Define`] routing),
    /// and how it appears in diagnostics (the miss detail of
    /// [`ScopeStack::searched_providers`], the provider context of a
    /// [`ScopeStackError`]). Names need not be unique on a stack; name-targeted ops
    /// address the innermost match.
    fn name(&self) -> &str;

    /// Resolve `query` in this provider: `Ok(Some(spec))` on a hit, `Ok(None)` for "not
    /// defined here — continue outward" (which includes "not *visible* here": per-mode
    /// visibility is the provider's own business, checked against
    /// [`state.mode()`](ParsingState::mode); the stack is visibility-blind). `Err` means
    /// the provider itself failed — an operational error that stops the search over the
    /// stack, never a panic.
    fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, L>,
        state: &ParsingState<L>,
    ) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError>;

    /// Specials participation: is a callable-triggering character sequence of this
    /// provider at `content[pos..]`? Same contract as the
    /// [`Lang::scan_specials`] hook it feeds through
    /// the [`ScopeStack::scan_specials`] search — including the [`SpecialsMatch::end`]
    /// obligations and the recovery-token protocol (the `TokenResult` shape is
    /// deliberate: a scanning provider keeps the tokenizer's recoverable-failure
    /// channel, which a [`ProviderError`] could not express). Implementations should return their **longest** match at `pos`.
    /// The default recognizes nothing.
    ///
    /// **`pos` contract:** `pos` must be a byte offset within `content`'s bounds
    /// (`pos <= content.len()`) and on a character boundary. A caller passing an
    /// invalid `pos` violates this contract; an implementation that indexes
    /// `content` with `pos` must answer with an `Err` carrying an
    /// [`ImplementationError`](crate::core::constructs::ImplementationError) rather
    /// than panic ([`Package`] does). The default body below and implementations
    /// that ignore `pos` answer `Ok(None)`.
    fn scan_specials(
        &self,
        state: &ParsingState<L>,
        content: &str,
        pos: usize,
    ) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
        let _ = (state, content, pos);
        Ok(None)
    }

    /// The characters that may start one of this provider's specials triggers — unioned
    /// over the stack at state freeze ([`ScopeStack::specials_trigger_chars`]) into the
    /// per-state filter. Must be a conservative superset of the first characters of
    /// every trigger [`scan_specials`](SpecsProvider::scan_specials) can match,
    /// *regardless of state* (there is deliberately no state parameter: the union is
    /// cached on frozen states — a mode-invisible provider's chars stay in the filter
    /// and its scan declines instead). The default: no specials.
    fn specials_trigger_chars(&self) -> TriggerChars {
        TriggerChars::default()
    }

    /// Apply definition ops **functionally**: return a fresh provider reflecting `ops`,
    /// leaving `self` untouched. This is the copy-on-write mechanism (`Arc::make_mut`
    /// does not exist for `dyn` types): the stack replaces its entry with the returned
    /// `Arc`, and outer states keep holding the old one — scoped reversion stays
    /// structural. Atomic per call: on `Err`, no partial application may be observable.
    ///
    /// The default refuses ([`ProviderError::NotMutable`]) — correct for immutable
    /// providers ([`Package`], [`FallbackProvider`]); [`Scope`] implements it.
    fn with_definitions(
        &self,
        ops: &[DefinitionOp<L>],
    ) -> Result<Arc<dyn SpecsProvider<L>>, ProviderError> {
        let _ = ops;
        Err(ProviderError::NotMutable)
    }

    /// Enumerate this provider's definitions of the invocation form `callable_type`
    /// that are visible under `mode`.
    /// Visibility is the provider's own business, exactly as in
    /// [`retrieve_spec`](SpecsProvider::retrieve_spec) — and since visibility is
    /// mode-determined at every grain, the mode alone is passed, not a full state.
    ///
    /// `None` = this provider **cannot enumerate** (the default — correct for
    /// [`FallbackProvider`], which answers *any* name); `Some` of an empty iterator =
    /// enumerable and nothing visible. Specials definitions enumerate under their
    /// registered callable type with the **trigger spelling as the name**. Yield order
    /// within a provider is unspecified.
    fn iter_symbols(
        &self,
        callable_type: L::CallableTypeId,
        mode: L::ModeId,
    ) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
        let _ = (callable_type, mode);
        None
    }
}

mod sealed {
    use super::{Lang, Package, SpecsProvider};
    use alloc::sync::Arc;

    pub trait SealedProvider<L: Lang> {}
    impl<L: Lang> SealedProvider<L> for Package<L> {}
    impl<L: Lang, P: SpecsProvider<L> + 'static> SealedProvider<L> for Arc<P> {}
    impl<L: Lang> SealedProvider<L> for Arc<dyn SpecsProvider<L>> {}
}

/// Sealed conversion into a shared [`SpecsProvider`] — what
/// [`ParsingState::lang_initial_with_packages`](crate::core::ParsingState::lang_initial_with_packages)
/// accepts as its items.
///
/// A [`Package`] passes **by value**
/// (`lang_initial_with_packages([minilatex_package(), my_pkg])`, with no `Arc::new` at
/// the call site), while an already-shared **`Arc<P>`** or
/// **`Arc<dyn SpecsProvider<L>>`** passes through unchanged rather than being wrapped a
/// second time. The spec-side counterpart is
/// [`IntoCallableSpec`](crate::core::specs::IntoCallableSpec).
///
/// Sealed: the three implementations above are the whole vocabulary; downstream code
/// implements [`SpecsProvider`], never this trait.
pub trait IntoSpecsProvider<L: Lang>: sealed::SealedProvider<L> {
    /// Convert into the shared provider handle scope stacks store.
    fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>>;
}

impl<L: Lang> IntoSpecsProvider<L> for Package<L> {
    fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
        Arc::new(self)
    }
}

impl<L: Lang, P: SpecsProvider<L> + 'static> IntoSpecsProvider<L> for Arc<P> {
    fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
        self
    }
}

impl<L: Lang> IntoSpecsProvider<L> for Arc<dyn SpecsProvider<L>> {
    fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
        self
    }
}

/// One enumerated definition (see [`SpecsProvider::iter_symbols`]): a borrowed,
/// self-describing row — callers clone the `Arc` if they keep it.
pub struct SymbolEntry<'a, L: Lang> {
    /// The invocation form the definition is registered under.
    pub callable_type: L::CallableTypeId,
    /// The defined name — for a specials definition, the trigger spelling (`"--"`).
    pub name: &'a str,
    /// The definition's behavior spec.
    pub spec: &'a Arc<dyn CallableSpec<L>>,
}

// Manual impls: `SymbolEntry` is Copy regardless of `L` (an id and two borrows).

impl<L: Lang> Clone for SymbolEntry<'_, L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lang> Copy for SymbolEntry<'_, L> {}

impl<L: Lang> fmt::Debug for SymbolEntry<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SymbolEntry")
            .field("callable_type", &self.callable_type)
            .field("name", &self.name)
            .field("spec", &self.spec)
            .finish()
    }
}

// --- the escape-shadowing registration check --------------------------------------------

/// Condition (warning): every definition a provider makes under one callable type
/// begins with an escape character and is longer than that one character.
///
/// This is the registration mistake of inserting names *with* their escape character
/// (`"\greet"` instead of `"greet"` — see [`Package::insert`]'s normalized-name
/// contract). The name in a command token does not include the escape character, so
/// none of these definitions can ever resolve.
///
/// A name that is *exactly* one escape character is not a mistake and does not count:
/// the tokenizer reads `\\` as the command whose name is `\`, so `\\` is registered
/// under the one-character name `"\\"`.
///
/// Recorded by [`check_provider_commands_shadowed_by_escape`], which no parse runs by
/// default: a language author calls it once, on the providers they have built.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.provider-commands-shadowed-by-escape")]
pub struct ProviderCommandsShadowedByEscape {
    /// The provider whose definitions are all escape-shadowed.
    pub provider: String,
    /// The affected callable type (its `Debug` rendering — the wire payload cannot
    /// carry a language's type id directly).
    pub callable_type: String,
    /// How many definitions the provider advertises under that type (all of them
    /// escape-shadowed).
    pub count: usize,
    /// One offending name, exactly as registered (e.g. `"\\greet"`).
    pub example: String,
    /// The escape character(s) the offending names begin with.
    pub escape_chars: String,
}

// Hand-written wording: the count needs number agreement, which the derive's message
// format string cannot express.
impl fmt::Display for ProviderCommandsShadowedByEscape {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "every ‘{}’ definition of provider ‘{}’ begins with an escape character \
             followed by more characters (‘{}’ — {} definition{}, e.g. ‘{}’): command \
             names are registered without the escape character, so none of these \
             definitions can resolve",
            self.callable_type,
            self.provider,
            self.escape_chars,
            self.count,
            if self.count == 1 { "" } else { "s" },
            self.example,
        )
    }
}

/// Warns when every definition a provider makes under one callable type begins with an
/// escape character and is longer than that one character — the registration mistake of
/// writing `"\\greet"` where `"greet"` was meant, which leaves the whole table
/// unreachable.
///
/// One [`ProviderCommandsShadowedByEscape`] **warning** is recorded per affected
/// (provider, callable type) pair, at `source`'s start. For each provider on `state`'s
/// scope stack and each callable type in the language's vocabulary, the names the
/// provider lists ([`SpecsProvider::iter_symbols`], over every mode) are tested against
/// the state's command escape characters
/// ([`TokenRules::command_rules`](crate::core::token::TokenRules::command_rules)); the
/// warning fires when **all** of them (at least one) begin with such a character and
/// have at least one character after it.
///
/// A name of exactly one escape character is a legitimate registration and is never
/// counted as a mistake: the tokenizer reads `\\` as the command whose name is `\`, so
/// a package defining that command registers it under the name `"\\"`.
///
/// Nothing is checked when commands are disabled, and providers that cannot list their
/// definitions (a [`FallbackProvider`]) are skipped: this is a best-effort check, not
/// part of the language's semantics. The other half of the defense is the suggestion
/// attached to a resolution miss
/// ([`resolve_command_in_scopes`](crate::core::specs::resolve_command_in_scopes)),
/// which a fallback provider on the stack can silence — this check fires either way.
///
/// **No parse runs this check.** Its answer depends only on the providers and the token
/// rules of `state`, not on any document, so calling it once where the packages are
/// built is enough — on the seed state, in a test or at startup. `source` only anchors
/// the warnings. A language can still run it at the start of every root parse through
/// [`LatexlikeLang::check_parse_start`](crate::latexlike::LatexlikeLang::check_parse_start),
/// at the price of the same warnings in every parse's diagnostics.
///
/// Listing a language's callable types and modes requires [`ClosedVocabulary`] on both,
/// so that bound sits on this function alone rather than on
/// [`Lang`](crate::core::Lang); a language whose vocabularies are not listable simply
/// does without the check.
///
/// The scan of a (provider, callable type) table stops at its first name that is not
/// escape-shadowed, so checking a correctly registered table reads only its first name.
pub fn check_provider_commands_shadowed_by_escape<L: Lang>(
    state: &ParsingState<L>,
    source: &Arc<Source<L::SourceOrigin>>,
    diagnostics: &mut Diagnostics<L::SourceOrigin>,
) where
    L::CallableTypeId: ClosedVocabulary,
    L::ModeId: ClosedVocabulary,
{
    let rules = state.rules();
    if !rules.commands_enabled() || rules.command_rules().is_empty() {
        return;
    }
    let escape_chars: Vec<char> =
        rules.command_rules().iter().map(|rule| rule.escape_char).collect();
    // A name of exactly one escape character is legitimate: the tokenizer reads `\\` as
    // the command whose name is `\`, so that command is registered under the
    // one-character name `"\\"`.
    let shadowed = |name: &str| {
        let mut chars = name.chars();
        chars.next().is_some_and(|first| escape_chars.contains(&first))
            && chars.next().is_some()
    };

    for provider in state.scopes().providers().iter().rev() {
        'tables: for &callable_type in L::CallableTypeId::ALL {
            // The provider's advertised names under this type, over every mode. One
            // name that is not escape-shadowed means no warning for this table.
            let mut names: Vec<&str> = Vec::new();
            for &mode in L::ModeId::ALL {
                let Some(symbols) = provider.iter_symbols(callable_type, mode) else {
                    continue; // cannot enumerate: gracefully absent
                };
                for entry in symbols {
                    if !shadowed(entry.name) {
                        continue 'tables;
                    }
                    names.push(entry.name);
                }
            }
            if names.is_empty() {
                continue;
            }
            // Deduplicated across modes; sorted so the reported example is
            // deterministic.
            names.sort_unstable();
            names.dedup();
            let mut offending_escapes: Vec<char> = names
                .iter()
                .filter_map(|name| name.chars().next())
                .collect();
            offending_escapes.sort_unstable();
            offending_escapes.dedup();
            diagnostics.push(Diagnostic::warning(
                ProviderCommandsShadowedByEscape {
                    provider: provider.name().into(),
                    callable_type: alloc::format!("{callable_type:?}"),
                    count: names.len(),
                    example: names[0].into(),
                    escape_chars: offending_escapes.into_iter().collect(),
                },
                SourceSpan::new(source, Span::empty(0)),
            ));
        }
    }
}

// --- Package ----------------------------------------------------------------------------

/// One data-driven specials entry of a [`Package`]: a trigger string resolving to a
/// callable — pylatexenc's specials-as-category-data, kept as plain data so packages are
/// loadable wholesale (ligature specials like `---`, `~`, `&`).
struct PackageSpecials<L: Lang> {
    trigger: Box<str>,
    callable_type: L::CallableTypeId,
    spec: Arc<dyn CallableSpec<L>>,
    /// Per-entry mode visibility (`None` = every mode the package is visible in).
    visible_modes: Option<Vec<L::ModeId>>,
}

impl<L: Lang> Clone for PackageSpecials<L> {
    fn clone(&self) -> Self {
        PackageSpecials {
            trigger: self.trigger.clone(),
            callable_type: self.callable_type,
            spec: Arc::clone(&self.spec),
            visible_modes: self.visible_modes.clone(),
        }
    }
}

/// One callable definition of a [`Package`]: the spec plus its per-entry mode
/// visibility. `None` visible modes = visible in every mode the package itself is (the
/// package-level [`set_visible_modes`](Package::set_visible_modes) is the coarse gate,
/// this is the fine one).
struct PackageEntry<L: Lang> {
    spec: Arc<dyn CallableSpec<L>>,
    visible_modes: Option<Vec<L::ModeId>>,
}

impl<L: Lang> Clone for PackageEntry<L> {
    fn clone(&self) -> Self {
        PackageEntry {
            spec: Arc::clone(&self.spec),
            visible_modes: self.visible_modes.clone(),
        }
    }
}

/// Whether a per-entry mode restriction admits `mode` (`None` = every mode).
fn modes_admit<M: Eq>(visible_modes: &Option<Vec<M>>, mode: &M) -> bool {
    match visible_modes {
        None => true,
        Some(modes) => modes.contains(mode),
    }
}

/// A collection of callable definitions, built once and loaded whole: the usual place
/// to put the macros, environments and specials a document uses.
///
/// Create one with [`new`](Package::new), add definitions while you still own it, then
/// load it into the parsing state the parser starts from —
/// [`ParsingState::lang_initial_with_packages`](crate::core::ParsingState::lang_initial_with_packages)
/// takes packages by value. Once shared on a scope stack a package never changes: its
/// [`with_definitions`](SpecsProvider::with_definitions) is the default refusal, and
/// definitions made during a parse go to a [`Scope`] instead.
///
/// ```
/// use techy::core::specs::Package;
/// use techy::latexlike::Latexlike;
///
/// let mut package: Package<Latexlike> = Package::new("mydefs");
/// package.define_macro("emph", ["m"]).unwrap();
/// package.define_environment("quotation", ["o"]).unwrap();
/// assert_eq!(package.len(), 2);
/// ```
///
/// [`define_macro`](Package::define_macro) and
/// [`define_environment`](Package::define_environment) are the latexlike preset's
/// one-liners, taking argument codes directly
/// ([`argument_specs`](crate::latexlike::argument_specs) documents the code table). The
/// general form is [`insert`](Package::insert), which takes an invocation form, a name,
/// and any [`CallableSpec`] you build yourself. The guide chapter
/// [Defining macros, environments, and specials](crate::guide::specs) shows a package
/// through to a finished parse.
///
/// Keys are `(Lang::CallableTypeId, normalized name)` and the mapping is
/// **many-to-one**: several names may share one spec value (`\emph` and `\textit` can
/// hold the same `Arc`). Inserting an existing key replaces the previous definition and
/// returns it.
///
/// **Mode visibility.** A definition can be restricted to certain parsing modes at two
/// grains: the whole package ([`set_visible_modes`](Package::set_visible_modes)) and
/// the single entry
/// ([`insert_in_modes`](Package::insert_in_modes)/[`insert_specials_in_modes`](Package::insert_specials_in_modes)).
/// Both must admit [`ParsingState::mode`] for a definition to resolve; outside its
/// modes a package or an entry answers `Ok(None)` — invisible, not an error. So one
/// loadable package can hold text-only typography specials and math-only scripts side
/// by side. The package checks this itself, inside its own
/// [`retrieve_spec`](SpecsProvider::retrieve_spec) and
/// [`scan_specials`](SpecsProvider::scan_specials); the scope stack does not look at
/// visibility at all.
///
/// **Specials as data.** A package may also define trigger strings
/// ([`insert_specials`](Package::insert_specials)) — `---`, `~`, `&`. Its scan returns
/// the longest matching trigger.
///
/// **Serialization.** A package is serialized by *identity*: its entry holds only the
/// package's name, and the reading side looks the name up among the providers
/// it already holds ([`KnownProviders`](crate::serialize::KnownProviders)) — a package
/// is part of the reading program's own configuration, not something to describe in
/// full. Its *definitions* are
/// serialized by identity too, when the package was built **shared**
/// ([`new_shared`](Package::new_shared)): the specs it issues
/// [`SpecProvenance`] stamps for ([`provenance_for`](Package::provenance_for),
/// [`provenance_for_specials`](Package::provenance_for_specials)) refer back to it.
/// A package built with [`new`](Package::new) and later wrapped in an `Arc` cannot
/// stamp its specs (it has no reference to its own `Arc`), so its specs — unless
/// their type has a self-contained serialized form — cannot be serialized; the
/// package itself still can.
pub struct Package<L: Lang> {
    name: Box<str>,
    specs: HashMap<L::CallableTypeId, HashMap<Box<str>, PackageEntry<L>>>,
    /// Sorted by trigger byte length, longest first (the package-internal longest-match
    /// rule); one entry per trigger string.
    specials: Vec<PackageSpecials<L>>,
    /// `None` = visible in every mode.
    visible_modes: Option<Vec<L::ModeId>>,
    /// The package's own `Arc`, weakly, when built shared ([`Package::new_shared`]):
    /// what its provenance stamps refer to. `None` for a package built with
    /// [`Package::new`].
    self_weak: Option<Weak<dyn SpecsProvider<L>>>,
}

impl<L: Lang> Package<L> {
    /// An empty package. The name identifies it on scope stacks, in the operations that
    /// address a provider by name, and in diagnostics.
    ///
    /// A package built this way cannot issue provenance stamps for its definitions, so
    /// its specs cannot be serialized by identity (see
    /// [`new_shared`](Package::new_shared) and the type's documentation).
    pub fn new(name: impl Into<Box<str>>) -> Package<L> {
        Package {
            name: name.into(),
            specs: HashMap::new(),
            specials: Vec::new(),
            visible_modes: None,
            self_weak: None,
        }
    }

    /// An empty package that `build` fills, returned already shared.
    ///
    /// The package is created inside its own `Arc`, so that while `build` runs it can
    /// issue [`SpecProvenance`] stamps for its definitions
    /// ([`provenance_for`](Package::provenance_for),
    /// [`provenance_for_specials`](Package::provenance_for_specials)); the stamps refer
    /// weakly to the `Arc` being built. Only the specs a package stamps can be
    /// serialized by identity — see the type's documentation.
    ///
    /// Inside `build`, insert the definitions as usual, stamping each spec first: the
    /// crate's spec types take the stamp through their `with_provenance` builder, and
    /// the latexlike one-liners [`define_macro`](Package::define_macro) and
    /// [`define_environment`](Package::define_environment) stamp on their own.
    ///
    /// Calling `new_shared` again inside `build` — a package that builds another shared
    /// package while it is being built — is allowed: each call creates an `Arc` of its
    /// own, and stamping only clones the weak pointer to it, never upgrades it, so
    /// nothing reaches the outer package before `build` returns. A stamp the outer
    /// package issued inside `build` resolves to it
    /// ([`SpecProvenance::provider`]) once `new_shared` has returned, not before.
    ///
    /// ```
    /// use techy::core::specs::{Package, StdCallableSpec};
    /// use techy::core::TrivialLang;
    ///
    /// #[derive(Debug, Clone, Copy)]
    /// struct MyLang;
    /// impl TrivialLang for MyLang {}
    ///
    /// const MACRO: u32 = 0;
    /// let package = Package::<MyLang>::new_shared("mydefs", |package| {
    ///     let stamp = package.provenance_for(MACRO, "emph").expect("a shared package stamps");
    ///     package.insert(MACRO, "emph", StdCallableSpec::default().with_provenance(stamp));
    /// });
    /// assert_eq!(package.name(), "mydefs");
    /// assert!(package.get(MACRO, "emph").is_some());
    /// ```
    pub fn new_shared(
        name: impl Into<Box<str>>,
        build: impl FnOnce(&mut Package<L>),
    ) -> Arc<Package<L>> {
        Arc::new_cyclic(|weak: &Weak<Package<L>>| {
            let mut package = Package::new(name);
            package.self_weak = Some(Weak::clone(weak) as Weak<dyn SpecsProvider<L>>);
            build(&mut package);
            package
        })
    }

    /// This package's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Whether this package was built shared ([`new_shared`](Package::new_shared))
    /// and so issues provenance stamps.
    pub fn is_shared(&self) -> bool {
        self.self_weak.is_some()
    }

    /// The provenance stamp for the definition of `name` under `callable_type` in this
    /// package — for a spec about to be inserted under that key (or already there):
    /// the stamp names this package (weakly), the invocation form, and
    /// [`DefinitionKey::Name`]. `None` unless the package was built shared
    /// ([`new_shared`](Package::new_shared)); nothing checks that the key is or
    /// becomes defined — the caller inserts the stamped spec under it.
    pub fn provenance_for(
        &self,
        callable_type: L::CallableTypeId,
        name: impl Into<Box<str>>,
    ) -> Option<SpecProvenance<L>> {
        let provider = self.self_weak.as_ref()?;
        Some(SpecProvenance::new(Weak::clone(provider), callable_type, DefinitionKey::Name(name.into())))
    }

    /// The provenance stamp for the specials definition of `trigger` under
    /// `callable_type` — the [`provenance_for`](Package::provenance_for) sibling for
    /// [`insert_specials`](Package::insert_specials) entries
    /// ([`DefinitionKey::Trigger`]). `None` unless the package was built shared.
    pub fn provenance_for_specials(
        &self,
        callable_type: L::CallableTypeId,
        trigger: impl Into<Box<str>>,
    ) -> Option<SpecProvenance<L>> {
        let provider = self.self_weak.as_ref()?;
        Some(SpecProvenance::new(
            Weak::clone(provider),
            callable_type,
            DefinitionKey::Trigger(trigger.into()),
        ))
    }

    /// Define `name` (normalized spelling) under the invocation form `callable_type`,
    /// visible in every mode the package is.
    ///
    /// A key that already has a definition is **replaced**, and the previous spec is
    /// returned; a key that had none returns `None`.
    ///
    /// **The name is the *normalized* spelling — never include the escape
    /// character.** Register `"emph"`, not `"\\emph"`: the name in a command token does
    /// not include the escape character, so an escape-prefixed registration can never
    /// match and the definition is silently unreachable.
    ///
    /// This is deliberately not validated here. Which characters are escape characters
    /// is a [`TokenRules`](crate::core::token::TokenRules) fact this layer cannot see,
    /// it can change mid-parse, and a leading escape-character-like character can be
    /// fully intended (`@greet`, registered before `@` *becomes* an escape character).
    /// The mistake is instead caught where it bites: a resolution miss suggests
    /// escape-prefixed near-misses
    /// ([`resolve_command_in_scopes`](crate::core::specs::resolve_command_in_scopes)),
    /// and a check you can run once on the built providers warns when *all* of a
    /// provider's definitions begin with an escape character and continue past it
    /// ([`check_provider_commands_shadowed_by_escape`], which leaves the legitimate
    /// one-character name `"\\"` — the command `\\` — alone).
    ///
    /// **The spec type and the callable type are not cross-checked either.** A
    /// "mismatched" registration — say a plain macro-shaped spec under an environment
    /// form — is legitimate: what parses the invocation is the composition registered
    /// for that invocation form, and the spec only contributes the argument structure.
    /// The latexlike environment composition, for instance, parses any
    /// [`CallableSpec`]'s declared arguments after `\begin{name}` and gives the body the
    /// default handling. The preset one-liners
    /// [`define_macro`](Package::define_macro) and
    /// [`define_environment`](Package::define_environment) pair the two correctly by
    /// construction.
    ///
    /// The spec passes through the sealed [`IntoCallableSpec`] conversion: by value
    /// (`insert(CallableType::Macro, "emph", MacroSpec::new(…))`, with no `Arc::new`),
    /// or already `Arc`-shared, which is how one spec value is registered under several
    /// names.
    pub fn insert<M>(
        &mut self,
        callable_type: L::CallableTypeId,
        name: impl Into<Box<str>>,
        spec: impl IntoCallableSpec<L, M>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.insert_in_modes(callable_type, name, spec, None)
    }

    /// Like [`insert`](Package::insert), but with per-entry mode visibility: the
    /// definition resolves only when [`ParsingState::mode`] is one of `visible_modes`
    /// (`None` = every mode the package is visible in — the [`insert`](Package::insert)
    /// default). This is the fine gate under the package-level
    /// [`set_visible_modes`](Package::set_visible_modes): both must admit the mode. A
    /// text-only accent and a math-only script can be defined in one loadable package.
    pub fn insert_in_modes<M>(
        &mut self,
        callable_type: L::CallableTypeId,
        name: impl Into<Box<str>>,
        spec: impl IntoCallableSpec<L, M>,
        visible_modes: Option<Vec<L::ModeId>>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.specs
            .entry(callable_type)
            .or_default()
            .insert(
                name.into(),
                PackageEntry { spec: spec.into_callable_spec(), visible_modes },
            )
            .map(|previous| previous.spec)
    }

    /// Define the specials `trigger` (e.g. `"---"`) as resolving to `spec` under the
    /// invocation form `callable_type`, visible in every mode the package is. One entry
    /// per trigger string: inserting an existing trigger replaces it (and returns the
    /// previous spec). The spec passes through the sealed [`IntoCallableSpec`]
    /// conversion, exactly as in [`insert`](Package::insert) — whose parameter order
    /// (callable type first, then the key) this method mirrors.
    pub fn insert_specials<M>(
        &mut self,
        callable_type: L::CallableTypeId,
        trigger: impl Into<Box<str>>,
        spec: impl IntoCallableSpec<L, M>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.insert_specials_in_modes(callable_type, trigger, spec, None)
    }

    /// Like [`insert_specials`](Package::insert_specials), but with per-entry mode
    /// visibility: the trigger is recognized only when [`ParsingState::mode`] is one of
    /// `visible_modes` (`None` = every mode the package is visible in). Text-mode
    /// typography ligatures (`` `` ``, `---`) and math-mode scripts can share one
    /// package, each firing only in its own mode.
    pub fn insert_specials_in_modes<M>(
        &mut self,
        callable_type: L::CallableTypeId,
        trigger: impl Into<Box<str>>,
        spec: impl IntoCallableSpec<L, M>,
        visible_modes: Option<Vec<L::ModeId>>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        let spec = spec.into_callable_spec();
        let trigger = trigger.into();
        if let Some(existing) =
            self.specials.iter_mut().find(|entry| entry.trigger == trigger)
        {
            existing.callable_type = callable_type;
            existing.visible_modes = visible_modes;
            return Some(core::mem::replace(&mut existing.spec, spec));
        }
        self.specials.push(PackageSpecials { trigger, callable_type, spec, visible_modes });
        // Longest first; the stable sort keeps insertion order among equal lengths
        // (irrelevant for matching — equal-length triggers differ in content).
        self.specials.sort_by_key(|entry| core::cmp::Reverse(entry.trigger.len()));
        None
    }

    /// Restrict the *whole package* to the given parsing modes (`None` = visible
    /// everywhere, the default) — the coarse gate. Visibility is checked by the package
    /// itself, against [`ParsingState::mode`]: outside its modes the package answers
    /// "not here" for resolution and specials alike. For per-definition control under
    /// this gate, see [`insert_in_modes`](Package::insert_in_modes) and
    /// [`insert_specials_in_modes`](Package::insert_specials_in_modes).
    pub fn set_visible_modes(&mut self, modes: Option<Vec<L::ModeId>>) {
        self.visible_modes = modes;
    }

    /// The spec defined under `(callable_type, name)`, if any (visibility-blind: this
    /// is the raw data accessor; mode checks apply only on the provider paths).
    ///
    /// **Specials are not reachable here.** They are keyed by **trigger**, not by
    /// name, and are held in a separate store — `get` answers `None` for a specials
    /// definition even immediately after
    /// [`insert_specials`](Package::insert_specials) (whose `callable_type`
    /// parameter is what the *match* reports, not a lookup key here). To read
    /// them back, use [`get_specials`](Package::get_specials) (by trigger),
    /// [`iter_symbols`](SpecsProvider::iter_symbols) (which lists
    /// specials with the trigger as the name) or
    /// [`scan_specials`](SpecsProvider::scan_specials) (the matching path);
    /// [`len`](Package::len) counts them.
    pub fn get(
        &self,
        callable_type: L::CallableTypeId,
        name: &str,
    ) -> Option<&Arc<dyn CallableSpec<L>>> {
        self.specs.get(&callable_type)?.get(name).map(|entry| &entry.spec)
    }

    /// The spec of the specials definition registered for `trigger` under
    /// `callable_type`, if any (visibility-blind, like [`get`](Package::get)): the
    /// raw accessor of the specials store, keyed by the trigger string exactly as
    /// registered ([`insert_specials`](Package::insert_specials)). The callable type
    /// must be the one the entry was registered with — a trigger registered under
    /// another type answers `None`.
    pub fn get_specials(
        &self,
        callable_type: L::CallableTypeId,
        trigger: &str,
    ) -> Option<&Arc<dyn CallableSpec<L>>> {
        self.specials
            .iter()
            .find(|entry| entry.callable_type == callable_type && &*entry.trigger == trigger)
            .map(|entry| &entry.spec)
    }

    /// Number of definitions across all callable types (specials entries included).
    pub fn len(&self) -> usize {
        self.specs.values().map(HashMap::len).sum::<usize>() + self.specials.len()
    }

    /// Whether the package holds no definitions at all.
    pub fn is_empty(&self) -> bool {
        self.specs.values().all(HashMap::is_empty) && self.specials.is_empty()
    }

    fn visible_in(&self, mode: L::ModeId) -> bool {
        modes_admit(&self.visible_modes, &mode)
    }
}

// The `SerializableObject` (identity by name) and `DeserializableObject` impls live
// in `crate::serialize::drivers::specs`, with the other core spec/provider types'.

impl<L: Lang> SpecsProvider<L> for Package<L> {
    fn name(&self) -> &str {
        &self.name
    }

    fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, L>,
        state: &ParsingState<L>,
    ) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
        if !self.visible_in(state.mode()) {
            return Ok(None);
        }
        let Some(entry) =
            self.specs.get(&query.callable_type).and_then(|defs| defs.get(query.name))
        else {
            return Ok(None);
        };
        // Per-entry mode gate under the package-level one (both must admit the mode).
        if !modes_admit(&entry.visible_modes, &state.mode()) {
            return Ok(None);
        }
        Ok(Some(Arc::clone(&entry.spec)))
    }

    /// See the trait method's `pos` contract: an invalid `pos` (out of
    /// `content`'s bounds, or not a character boundary) answers an `Err`
    /// carrying an [`ImplementationError`] whose message names which of the two
    /// cases applies — checked before the visibility gate, so a caller bug is
    /// reported regardless of the package's mode visibility.
    fn scan_specials(
        &self,
        state: &ParsingState<L>,
        content: &str,
        pos: usize,
    ) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
        // Caller contract violation — same error spelling as the token
        // reader's own `Lang::scan_specials` match-end validation: a
        // `Custom`-wrapped `ImplementationError`, no recovery (an
        // implementation bug aborts even under tolerant recovery). The error
        // span is clamped to the content so it stays liftable to a source
        // span.
        let Some(rest) = content.get(pos..) else {
            let case = if pos > content.len() {
                "out of the content's bounds"
            } else {
                "not a character boundary"
            };
            return Err(SpecialsScanError {
                kind: TokenErrorKind::Custom(Box::new(ImplementationError::new(
                    alloc::format!(
                        "Package::scan_specials called with an invalid position {pos} \
                         ({case}; content length {})",
                        content.len()
                    ),
                ))),
                span: Span::empty(pos.min(content.len())),
            });
        };
        if !self.visible_in(state.mode()) {
            return Ok(None);
        }
        // Entries are sorted longest-first: the first hit is the package's longest.
        for entry in &self.specials {
            // A mode-invisible entry is not there: skip it (a shorter visible trigger
            // may still match). The trigger-char union stays mode-blind, so the
            // tokenizer still probes here and this scan declines.
            if !modes_admit(&entry.visible_modes, &state.mode()) {
                continue;
            }
            if rest.starts_with(&*entry.trigger) {
                let end = pos + entry.trigger.len();
                return Ok(Some(SpecialsMatch {
                    end,
                    callable_type: entry.callable_type,
                    spec: Arc::clone(&entry.spec),
                }));
            }
        }
        Ok(None)
    }

    fn specials_trigger_chars(&self) -> TriggerChars {
        let mut chars = String::new();
        for entry in &self.specials {
            if let Some(first) = entry.trigger.chars().next() {
                if !chars.contains(first) {
                    chars.push(first);
                }
            }
        }
        TriggerChars::Only(chars)
    }

    fn iter_symbols(
        &self,
        callable_type: L::CallableTypeId,
        mode: L::ModeId,
    ) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
        // Outside the package-level gate: enumerable, nothing visible.
        if !self.visible_in(mode) {
            return Some(Box::new(core::iter::empty()));
        }
        // Both storage tables contribute by their entries' *recorded* type — the
        // package never asks which type "means" specials.
        let named = self
            .specs
            .get(&callable_type)
            .into_iter()
            .flat_map(HashMap::iter)
            .filter(move |(_, entry)| modes_admit(&entry.visible_modes, &mode))
            .map(move |(name, entry)| SymbolEntry {
                callable_type,
                name,
                spec: &entry.spec,
            });
        let specials = self
            .specials
            .iter()
            .filter(move |entry| {
                entry.callable_type == callable_type && modes_admit(&entry.visible_modes, &mode)
            })
            .map(move |entry| SymbolEntry {
                callable_type,
                name: &entry.trigger,
                spec: &entry.spec,
            });
        Some(Box::new(named.chain(specials)))
    }
}

/// A clone is a new, unshared package: it copies the name, the definitions (sharing
/// their spec `Arc`s), and the visibility, but not the shared identity — the clone
/// issues no provenance stamps of its own, and the stamps its specs may hold go on
/// naming the package they were cloned from.
///
/// Consequence for serialization: a parse driven by a clone (the clone in the scope
/// stack, its specs stamped by the original) serializes the clone and the original
/// as two provider entries of one name — the states refer to the clone, the specs to
/// the original — and a reading side that resolves the name through a
/// [`ProviderRecipe`](crate::serialize::ProviderRecipe) alone rebuilds the two entries
/// as two packages, so the spec a tree node holds is not the instance held by the
/// package in the rebuilt state's scope stack (a reading side that holds the very
/// `Arc`s in its [`KnownProviders`](crate::serialize::KnownProviders) resolves both
/// entries to that one instance).
impl<L: Lang> Clone for Package<L> {
    fn clone(&self) -> Self {
        Package {
            name: self.name.clone(),
            specs: self.specs.clone(),
            specials: self.specials.clone(),
            visible_modes: self.visible_modes.clone(),
            self_weak: None,
        }
    }
}

impl<L: Lang> fmt::Debug for Package<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Package")
            .field("name", &self.name)
            .field("definitions", &self.len())
            .field("visible_modes", &self.visible_modes)
            .field("shared", &self.is_shared())
            .finish()
    }
}

// --- Scope -------------------------------------------------------------------------------

/// The provider that definitions made *during* a parse go into — what
/// [`ScopeOp::Define`] and [`ScopeOp::Remove`] address by name.
///
/// A scope is never modified in place:
/// [`with_definitions`](SpecsProvider::with_definitions) returns a fresh `Scope` and
/// the stack replaces its entry with it, while outer parsing states go on holding the
/// old `Arc`. That is what makes a definition made inside a group disappear when the
/// group ends, even when the scope it went into sits below other providers on the
/// stack.
///
/// Scopes are created as they are needed: the first [`ScopeOp::Define`] naming a scope
/// that is not on the stack creates it as the innermost entry. Building one directly
/// with [`new`](Scope::new) and [`insert`](Scope::insert) is for seeding an initial
/// parsing state.
///
/// Keys are `(Lang::CallableTypeId, normalized name)`, and several names may share one
/// spec value. Definitions are held in a `BTreeMap`, so iteration order is
/// deterministic.
///
/// **Serialization.** A scope holds definitions made during a parse, so it is
/// serialized in full — its name and every definition, each spec as an entry of its
/// own (by identity or in a self-contained form, whatever the spec's type writes) —
/// and rebuilt through [`new`](Scope::new) and [`insert`](Scope::insert).
pub struct Scope<L: Lang> {
    name: Box<str>,
    #[allow(clippy::type_complexity)]
    specs: BTreeMap<L::CallableTypeId, BTreeMap<Box<str>, Arc<dyn CallableSpec<L>>>>,
}

impl<L: Lang> Scope<L> {
    /// An empty scope. The name is how definition ops target it.
    pub fn new(name: impl Into<Box<str>>) -> Scope<L> {
        Scope { name: name.into(), specs: BTreeMap::new() }
    }

    /// This scope's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Define `name` under `callable_type` directly, while the scope is still owned —
    /// for seeding an initial parsing state, or in tests. Definitions made during a
    /// parse go through [`ScopeOp::Define`] instead.
    ///
    /// A key that already has a definition is **replaced**, and the previous spec is
    /// returned; a key that had none returns `None`.
    pub fn insert(
        &mut self,
        callable_type: L::CallableTypeId,
        name: impl Into<Box<str>>,
        spec: Arc<dyn CallableSpec<L>>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.specs.entry(callable_type).or_default().insert(name.into(), spec)
    }

    /// Remove the definition of `name` under `callable_type` directly (builder-style).
    /// Returns the removed spec, or `None` if it was not defined.
    pub fn remove(
        &mut self,
        callable_type: L::CallableTypeId,
        name: &str,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.specs.get_mut(&callable_type)?.remove(name)
    }

    /// The spec defined under `(callable_type, name)`, if any.
    pub fn get(
        &self,
        callable_type: L::CallableTypeId,
        name: &str,
    ) -> Option<&Arc<dyn CallableSpec<L>>> {
        self.specs.get(&callable_type)?.get(name)
    }

    /// Number of definitions across all callable types.
    pub fn len(&self) -> usize {
        self.specs.values().map(BTreeMap::len).sum()
    }

    /// Whether the scope holds no definitions.
    pub fn is_empty(&self) -> bool {
        self.specs.values().all(BTreeMap::is_empty)
    }

    /// Every definition — `(callable type, name, spec)` — ordered by callable type,
    /// then by name (the storage order; deterministic).
    pub fn definitions(
        &self,
    ) -> impl Iterator<Item = (L::CallableTypeId, &str, &Arc<dyn CallableSpec<L>>)> + '_ {
        self.specs.iter().flat_map(|(callable_type, definitions)| {
            definitions.iter().map(move |(name, spec)| (*callable_type, &**name, spec))
        })
    }
}

// The `SerializableObject` (the definitions in full) and `DeserializableObject`
// impls live in `crate::serialize::drivers::specs`.

impl<L: Lang> SpecsProvider<L> for Scope<L> {
    fn name(&self) -> &str {
        &self.name
    }

    fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, L>,
        _state: &ParsingState<L>,
    ) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
        Ok(self.get(query.callable_type, query.name).cloned())
    }

    /// Copy-on-write: clone the maps, apply `ops` in order, return a fresh `Scope`.
    /// Atomic — the first failing op discards the copy and nothing is observable.
    fn with_definitions(
        &self,
        ops: &[DefinitionOp<L>],
    ) -> Result<Arc<dyn SpecsProvider<L>>, ProviderError> {
        let mut fresh = self.clone();
        for op in ops {
            match op {
                DefinitionOp::Define { callable_type, name, spec } => {
                    fresh.insert(*callable_type, name.clone(), Arc::clone(spec));
                }
                DefinitionOp::Remove { callable_type, name } => {
                    if fresh.remove(*callable_type, name).is_none() {
                        return Err(ProviderError::UndefinedName { name: name.clone() });
                    }
                }
            }
        }
        Ok(Arc::new(fresh))
    }

    fn iter_symbols(
        &self,
        callable_type: L::CallableTypeId,
        mode: L::ModeId,
    ) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
        // Scope definitions carry no visibility — every mode sees them all.
        let _ = mode;
        let entries = self
            .specs
            .get(&callable_type)
            .into_iter()
            .flat_map(BTreeMap::iter)
            .map(move |(name, spec)| SymbolEntry { callable_type, name, spec });
        Some(Box::new(entries))
    }
}

impl<L: Lang> Clone for Scope<L> {
    fn clone(&self) -> Self {
        Scope { name: self.name.clone(), specs: self.specs.clone() }
    }
}

impl<L: Lang> fmt::Debug for Scope<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Scope")
            .field("name", &self.name)
            .field("definitions", &self.len())
            .finish()
    }
}

// --- FallbackProvider --------------------------------------------------------------------

/// A provider that answers **any** name of the callable types registered with it: what
/// an unknown callable resolves to.
///
/// Push it at the *bottom* of the scope stack. Since lookup goes innermost first, every
/// real definition above it shadows it, and it answers only the names nothing else
/// defines — so the stack itself needs no separate notion of a fallback.
///
/// Register one spec per callable type with [`set`](FallbackProvider::set). Because a
/// spec holds no name of its own, that single spec value answers every unknown name of
/// its type: an unknown `\foo` costs no allocation, and a callable node's spec is never
/// missing for a callable type registered here.
///
/// **Serialization.** Serialized in full — its name and every fallback, each spec as
/// an entry of its own — and rebuilt through [`new`](FallbackProvider::new) and
/// [`set`](FallbackProvider::set).
pub struct FallbackProvider<L: Lang> {
    name: Box<str>,
    fallbacks: BTreeMap<L::CallableTypeId, Arc<dyn CallableSpec<L>>>,
}

impl<L: Lang> FallbackProvider<L> {
    /// An empty fallback provider.
    pub fn new(name: impl Into<Box<str>>) -> FallbackProvider<L> {
        FallbackProvider { name: name.into(), fallbacks: BTreeMap::new() }
    }

    /// Register the spec that answers every name of `callable_type`.
    ///
    /// A callable type that already had a fallback keeps the new one instead, and the
    /// previous spec is returned; otherwise the result is `None`.
    pub fn set(
        &mut self,
        callable_type: L::CallableTypeId,
        spec: Arc<dyn CallableSpec<L>>,
    ) -> Option<Arc<dyn CallableSpec<L>>> {
        self.fallbacks.insert(callable_type, spec)
    }

    /// The registered fallback for `callable_type`, if any.
    pub fn get(&self, callable_type: L::CallableTypeId) -> Option<&Arc<dyn CallableSpec<L>>> {
        self.fallbacks.get(&callable_type)
    }

    /// Every registered fallback — `(callable type, spec)` — ordered by callable type
    /// (the storage order; deterministic).
    pub fn fallbacks(&self) -> impl Iterator<Item = (L::CallableTypeId, &Arc<dyn CallableSpec<L>>)> + '_ {
        self.fallbacks.iter().map(|(callable_type, spec)| (*callable_type, spec))
    }
}

// The `SerializableObject` (the fallbacks in full) and `DeserializableObject` impls
// live in `crate::serialize::drivers::specs`.

impl<L: Lang> SpecsProvider<L> for FallbackProvider<L> {
    fn name(&self) -> &str {
        &self.name
    }

    fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, L>,
        _state: &ParsingState<L>,
    ) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
        Ok(self.fallbacks.get(&query.callable_type).cloned())
    }
}

impl<L: Lang> Clone for FallbackProvider<L> {
    fn clone(&self) -> Self {
        FallbackProvider { name: self.name.clone(), fallbacks: self.fallbacks.clone() }
    }
}

impl<L: Lang> fmt::Debug for FallbackProvider<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FallbackProvider")
            .field("name", &self.name)
            .field("callable_types", &self.fallbacks.len())
            .finish()
    }
}

// --- ErrorCallableSpec ---------------------------------------------------------------------

/// Condition: a callable defined to be an error was invoked.
///
/// [`ErrorCallableSpec`] is that definition — a name made undefined on purpose. The
/// invocation recovers by staging the trigger as a `Chars` node over its own source
/// span.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.callable-defined-as-error")]
pub struct CallableDefinedAsError {
    /// The invocation spelling, as written.
    pub name: String,
    /// Optional detail configured on the spec — *why* this name is an error ("removed
    /// by {package}", "not available in this mode").
    pub detail: Option<String>,
}

// Hand-written wording: the detail suffix is conditional (a branch the derive's message
// format string cannot express).
impl fmt::Display for CallableDefinedAsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "‘{}’ is defined to be an error", self.name)?;
        if let Some(detail) = &self.detail {
            write!(f, ": {detail}")?;
        }
        Ok(())
    }
}

/// A [`CallableSpec`] whose invocation is an error: how a name is *defined to be
/// undefined*.
///
/// Storing it under a name shadows every definition below it, a
/// [`FallbackProvider`]'s included, so this is how a definition is taken away without
/// unloading the package that made it. There is no separate "masked" resolution
/// outcome: ordinary search order does the work, and the diagnostic can say more than a
/// mask could.
///
/// Invoking it records a [`CallableDefinedAsError`] through the recovery entry point —
/// aborting under strict recovery, recording a diagnostic under tolerant recovery — and
/// then stages the trigger as a `Chars` node over its own source span, consuming
/// nothing further. [`with_detail`](ErrorCallableSpec::with_detail) adds *why* the name
/// is an error to the message.
#[derive(Debug, Clone, Default)]
pub struct ErrorCallableSpec {
    /// Optional detail for the diagnostic — *why* the name is an error.
    pub detail: Option<Box<str>>,
}

impl ErrorCallableSpec {
    /// An error spec with no detail beyond the standard message.
    pub fn new() -> ErrorCallableSpec {
        ErrorCallableSpec { detail: None }
    }

    /// An error spec whose diagnostic includes `detail`.
    pub fn with_detail(detail: impl Into<Box<str>>) -> ErrorCallableSpec {
        ErrorCallableSpec { detail: Some(detail.into()) }
    }
}

// The `SerializableObject` (a self-contained form: the detail) and
// `DeserializableObject` impls live in `crate::serialize::drivers::specs`.

impl<L: Lang> CallableSpec<L> for ErrorCallableSpec {
    /// Infallible: `Ok(...)` wrapping is this implementation's whole use of the
    /// `Result`.
    fn make_invocation_parser<'a>(
        &'a self,
        invocation: Invocation<'a, L>,
    ) -> Result<
        Box<dyn ConstructParser<L, Output = BuildId> + 'a>,
        crate::error::ParseError<L::SourceOrigin>,
    >
    {
        Ok(Box::new(ErrorInvocationParser { invocation, detail: self.detail.as_deref() }))
    }
}

/// The invocation parser of [`ErrorCallableSpec`]: diagnose, stage the trigger as chars,
/// consume nothing further (the dispatch arm already consumed the trigger token whole).
struct ErrorInvocationParser<'a, L: Lang> {
    invocation: Invocation<'a, L>,
    detail: Option<&'a str>,
}

impl<L: Lang> ConstructParser<L> for ErrorInvocationParser<'_, L> {
    type Output = BuildId;

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, L>,
    ) -> ConstructParserResult<L, (BuildId, Option<Box<ParsingStateDelta<L>>>)> {
        let span = cx.tokens.source_span_of(self.invocation.token);
        cx.recover(
            CallableDefinedAsError {
                name: self.invocation.name.into(),
                detail: self.detail.map(String::from),
            },
            span.clone(),
        )?;
        // Tolerant continuation: markup in a Chars node is the accepted recovery
        // artifact (DESIGN_RATIONALE.md [§dd-dr:errors]).
        let id = cx
            .stage_node(
                NodeKind::chars(span.span()),
                span.clone(),
                Arc::clone(&cx.state),
                Vec::new(),
            )
            .map_err(|error| cx.staging_error(error, span))?;
        Ok((id, None))
    }
}

// --- ScopeStack ---------------------------------------------------------------------------

/// The ordered list of providers in effect, stored in the parsing state
/// ([`StateData::scopes`](crate::core::StateData)).
///
/// Name resolution ([`retrieve_spec`](ScopeStack::retrieve_spec)) and the specials scan
/// ([`scan_specials`](ScopeStack::scan_specials)) both go over the entries **innermost
/// (last-pushed) first**, and the first provider that answers wins — so a later
/// definition of a name shadows an earlier one, the way `\newcommand` does.
///
/// The stack is deliberately not itself a [`SpecsProvider`] — stacks do not nest — and
/// holds no fallback of its own: what happens for an unknown name is decided by an
/// ordinary [`FallbackProvider`] at the bottom of the stack. It does not look at mode
/// visibility either; a mode-restricted [`Package`] declines inside its own methods.
///
/// Changes during a parse go through [`ScopeOp`]s in a parsing state delta;
/// [`apply_op`](ScopeStack::apply_op) is the operation behind them, and can also be
/// called directly on an owned stack, for example while seeding an initial state.
///
/// **Storage follows the language's feature declarations.** Like the token-rules
/// blocks, the provider list is stored through the scopes presence declaration of
/// [`Lang::Features`] ([`FeaturePresence::Store`]): for a language that declares the
/// scope stack absent, the list is replaced by the zero-sized store and the stack is
/// permanently empty — every lookup gives the empty-stack answer,
/// [`push`](ScopeStack::push) requires a language with the feature
/// ([`LangHasScopes`]), and [`apply_op`](ScopeStack::apply_op) reports
/// [`ScopeOpError::ScopesAbsent`].
pub struct ScopeStack<L: Lang> {
    /// Outermost first; searches iterate in reverse. For a language that declares the
    /// scope stack absent, this is the zero-sized store — no list exists.
    // The store projection is the point of the field; an alias would hide the very
    // indirection this declaration exists to state.
    #[allow(clippy::type_complexity)]
    stack: <<L::Features as LangFeatures>::Scopes as FeaturePresence>::Store<
        Vec<Arc<dyn SpecsProvider<L>>>,
    >,
}

impl<L: Lang> ScopeStack<L> {
    /// An empty stack: no definitions at all. Every language constructs one (the
    /// parsing state stores a stack unconditionally); for a language that declares
    /// the scope stack absent, the empty stack is the only value the stack ever has.
    pub fn new() -> ScopeStack<L> {
        ScopeStack { stack: <L::Features as LangFeatures>::Scopes::store_with(Vec::new) }
    }

    /// A stack over `providers` (outermost first), for any language: the
    /// deserialization path, which rebuilds a stack from serialized data under a
    /// generic `L` and so cannot use [`push`](ScopeStack::push) (bounded on the
    /// feature). `None` when the language declares the scope stack absent and
    /// `providers` is non-empty — such a stack cannot exist; an empty list yields the
    /// empty stack for every language.
    pub(crate) fn from_providers(providers: Vec<Arc<dyn SpecsProvider<L>>>) -> Option<ScopeStack<L>> {
        if !<L::Features as LangFeatures>::Scopes::PRESENT && !providers.is_empty() {
            return None;
        }
        Some(ScopeStack { stack: <L::Features as LangFeatures>::Scopes::store_with(|| providers) })
    }

    /// The provider list through the storage projection: the stored entries, or the
    /// empty slice when the language declares the scope stack absent (the stack is
    /// then permanently empty). Every read-only method routes through this, so each
    /// gives its empty-stack answer under an absent declaration.
    fn entries(&self) -> &[Arc<dyn SpecsProvider<L>>] {
        <L::Features as LangFeatures>::Scopes::store_get(&self.stack)
            .map_or(&[], |providers| providers.as_slice())
    }

    /// Push a provider as the new innermost entry. Requires a language whose
    /// features declare the scope stack present ([`LangHasScopes`]).
    pub fn push(&mut self, provider: Arc<dyn SpecsProvider<L>>)
    where
        L: LangHasScopes,
    {
        // Under the bound the store is transparent: the field is the list itself.
        self.stack.push(provider);
    }

    /// The providers, outermost first (the storage order; searches run innermost-first).
    /// The empty slice when the language declares the scope stack absent.
    pub fn providers(&self) -> &[Arc<dyn SpecsProvider<L>>] {
        self.entries()
    }

    /// The provider names, **innermost first** (the search order — the order the miss
    /// detail reports).
    pub fn provider_names(&self) -> impl Iterator<Item = &str> + '_ {
        self.entries().iter().rev().map(|provider| provider.name())
    }

    /// A [`Display`](fmt::Display) adapter rendering the searched-provider detail for
    /// resolution misses (the `UnresolvableCommand` "searched: …" detail): exhausting
    /// the stack always searched *every* provider (the stack is visibility-blind), so
    /// the searched set is a property of the stack itself.
    pub fn searched_providers(&self) -> SearchedProviders<'_, L> {
        SearchedProviders { stack: self }
    }

    /// Number of providers on the stack.
    pub fn len(&self) -> usize {
        self.entries().len()
    }

    /// Whether the stack holds no providers.
    pub fn is_empty(&self) -> bool {
        self.entries().is_empty()
    }

    /// Resolve `query`: search the providers innermost-first; the first hit wins.
    /// `Ok(None)` is the structured miss — the whole stack was searched (compose the
    /// diagnostic detail via [`searched_providers`](ScopeStack::searched_providers)).
    /// A provider `Err` stops the search and propagates with the provider's name
    /// attached.
    pub fn retrieve_spec(
        &self,
        query: &CallableQuery<'_, L>,
        state: &ParsingState<L>,
    ) -> Result<Option<Arc<dyn CallableSpec<L>>>, ScopeStackError> {
        for provider in self.entries().iter().rev() {
            match provider.retrieve_spec(query, state) {
                Ok(Some(spec)) => return Ok(Some(spec)),
                Ok(None) => {}
                Err(error) => {
                    return Err(ScopeStackError { provider: provider.name().into(), error })
                }
            }
        }
        Ok(None)
    }

    /// The specials scan (the standard body of a preset's
    /// [`Lang::scan_specials`]): consult **every**
    /// provider innermost-first; the **longest** match wins, ties go **innermost**
    /// (pylatexenc `test_for_specials` parity — `---` beats `--` across providers, and
    /// an equal-length match is the same spelling, so the tie rule implements
    /// shadowing). A provider's scan `Err` stops the search and propagates.
    /// `pos` is passed through to every provider unchecked, under the `pos`
    /// contract documented on [`SpecsProvider::scan_specials`] (within
    /// `content`'s bounds, on a character boundary).
    pub fn scan_specials(
        &self,
        state: &ParsingState<L>,
        content: &str,
        pos: usize,
    ) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
        let mut best: Option<SpecialsMatch<L>> = None;
        for provider in self.entries().iter().rev() {
            if let Some(matched) = provider.scan_specials(state, content, pos)? {
                // Strictly longer wins; an equal-length later (outer) match loses.
                if best.as_ref().is_none_or(|current| matched.end > current.end) {
                    best = Some(matched);
                }
            }
        }
        Ok(best)
    }

    /// The trigger-character union over all providers (the standard body of a preset's
    /// [`Lang::specials_trigger_chars`]) —
    /// computed at state freeze and cached on the state, like every trigger filter.
    pub fn specials_trigger_chars(&self) -> TriggerChars {
        let mut union = TriggerChars::default();
        for provider in self.entries() {
            union = union.union(&provider.specials_trigger_chars());
        }
        union
    }

    /// Enumerate the definitions of the invocation form `callable_type` in scope under
    /// `mode`, **shadowing applied**: providers are consulted innermost-first (each
    /// pre-filters by visibility, so this mirrors [`retrieve_spec`](ScopeStack::retrieve_spec)
    /// resolution under that mode), and the first occurrence of a name wins. For
    /// specials definitions the "name" is the trigger spelling — identical triggers
    /// shadow innermost-wins, exactly the [`scan_specials`](ScopeStack::scan_specials)
    /// tie rule; distinct triggers coexist (longest-match is positional resolution, not
    /// shadowing).
    ///
    /// Providers that cannot enumerate ([`SpecsProvider::iter_symbols`] = `None`, e.g.
    /// a [`FallbackProvider`] answering *any* name) are skipped: the listing covers the
    /// enumerable definitions, not the open-ended fallback behavior. For the raw
    /// per-provider walk without dedup, iterate [`providers`](ScopeStack::providers)
    /// yourself. To enumerate *every* form, drive this once per type — via
    /// [`ClosedVocabulary::ALL`](crate::core::ClosedVocabulary) where the language's
    /// type vocabulary implements it.
    pub fn iter_symbols(
        &self,
        callable_type: L::CallableTypeId,
        mode: L::ModeId,
    ) -> Vec<SymbolEntry<'_, L>> {
        let mut seen: hashbrown::HashSet<&str> = hashbrown::HashSet::new();
        let mut symbols = Vec::new();
        for provider in self.entries().iter().rev() {
            let Some(entries) = provider.iter_symbols(callable_type, mode) else {
                continue;
            };
            for entry in entries {
                if seen.insert(entry.name) {
                    symbols.push(entry);
                }
            }
        }
        symbols
    }

    /// Apply one [`ScopeOp`] — the primitive behind
    /// [`ParsingStateDelta::scope_ops`](crate::core::ParsingStateDelta). Name-targeted
    /// ops address the innermost provider with that name; failures are reported, never
    /// silent (see the per-variant docs on [`ScopeOp`]). On a stack of a language that
    /// declares the scope stack absent, every op fails with
    /// [`ScopeOpError::ScopesAbsent`] — such a call can only be direct: a state delta
    /// cannot carry scope ops for that language.
    pub fn apply_op(&mut self, op: &ScopeOp<L>) -> Result<(), ScopeOpError> {
        let Some(stack) =
            <L::Features as LangFeatures>::Scopes::store_get_mut(&mut self.stack)
        else {
            return Err(ScopeOpError::ScopesAbsent);
        };
        match op {
            ScopeOp::Push(provider) => {
                stack.push(Arc::clone(provider));
                Ok(())
            }
            ScopeOp::Unload { name } => {
                let index = Self::innermost_position(stack, name).ok_or_else(|| {
                    ScopeOpError::UnknownProvider { name: name.clone() }
                })?;
                stack.remove(index);
                Ok(())
            }
            ScopeOp::Replace { name, provider } => {
                let index = Self::innermost_position(stack, name).ok_or_else(|| {
                    ScopeOpError::UnknownProvider { name: name.clone() }
                })?;
                stack[index] = Arc::clone(provider);
                Ok(())
            }
            ScopeOp::ReplaceStack(providers) => {
                *stack = providers.clone();
                Ok(())
            }
            ScopeOp::Define { scope, callable_type, name, spec } => {
                let op = DefinitionOp::Define {
                    callable_type: *callable_type,
                    name: name.clone(),
                    spec: Arc::clone(spec),
                };
                match Self::innermost_position(stack, scope) {
                    Some(index) => Self::route_definition(stack, index, scope, op),
                    None => {
                        // Lazy creation: the first Define into an absent scope name
                        // creates it, innermost (DESIGN_RATIONALE.md [§dd-dr:specs]).
                        let mut fresh = Scope::new(scope.clone());
                        fresh.insert(*callable_type, name.clone(), Arc::clone(spec));
                        stack.push(Arc::new(fresh));
                        Ok(())
                    }
                }
            }
            ScopeOp::Remove { scope, callable_type, name } => {
                let op = DefinitionOp::Remove {
                    callable_type: *callable_type,
                    name: name.clone(),
                };
                let index = Self::innermost_position(stack, scope).ok_or_else(|| {
                    ScopeOpError::UnknownProvider { name: scope.clone() }
                })?;
                Self::route_definition(stack, index, scope, op)
            }
        }
    }

    /// Route one definition op to the provider at `index` (copy-on-write entry swap).
    fn route_definition(
        stack: &mut [Arc<dyn SpecsProvider<L>>],
        index: usize,
        scope: &str,
        op: DefinitionOp<L>,
    ) -> Result<(), ScopeOpError> {
        match stack[index].with_definitions(&[op]) {
            Ok(fresh) => {
                stack[index] = fresh;
                Ok(())
            }
            Err(error) => Err(ScopeOpError::Provider(ScopeStackError {
                provider: scope.into(),
                error,
            })),
        }
    }

    /// Index of the innermost provider named `name`, if any.
    fn innermost_position(
        stack: &[Arc<dyn SpecsProvider<L>>],
        name: &str,
    ) -> Option<usize> {
        stack.iter().rposition(|provider| provider.name() == name)
    }
}

impl<L: Lang> Default for ScopeStack<L> {
    fn default() -> Self {
        ScopeStack::new()
    }
}

// Manual impls: derives would demand `L: Clone`/`L: Debug`; cloning is cheap (`Arc`s).

impl<L: Lang> Clone for ScopeStack<L> {
    fn clone(&self) -> Self {
        ScopeStack { stack: self.stack.clone() }
    }
}

impl<L: Lang> fmt::Debug for ScopeStack<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScopeStack").field("providers", &self.stack).finish()
    }
}

/// [`Display`](fmt::Display) adapter over a stack's searched providers — see
/// [`ScopeStack::searched_providers`].
pub struct SearchedProviders<'a, L: Lang> {
    stack: &'a ScopeStack<L>,
}

impl<L: Lang> fmt::Display for SearchedProviders<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.stack.is_empty() {
            return write!(f, "no providers on the scope stack");
        }
        write!(f, "searched providers: ")?;
        for (i, name) in self.stack.provider_names().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{name}")?;
        }
        Ok(())
    }
}

impl<L: Lang> fmt::Debug for SearchedProviders<'_, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::spec::StdCallableSpec;
    use crate::state::StateData;
    use crate::token::{
        CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
        SpecialsRules, TokenErrorKind, TokenRules, WhitespaceRules,
    };
    use alloc::string::{String, ToString};
    use alloc::vec;

    const MACRO: u32 = 0;
    const ENVIRONMENT: u32 = 1;

    #[derive(Debug, Clone, Copy)]
    struct PlainLang;
    impl crate::state::TrivialLang for PlainLang {}

    // `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<Features = crate::state::AllLangFeatures>>() -> TokenRules<L> {
        TokenRules {
            whitespace: WhitespaceRules::empty(),
            paragraphs: ParagraphRules { enabled: false },
            groups: GroupRules {
                enabled: true,
                rules: vec![],
                temporary: vec![],
                expecting_close: None,
            },
            commands: CommandRules {
                enabled: true,
                rules: vec![],
            },
            comments: CommentRules {
                enabled: true,
                rules: vec![],
            },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    fn state_with(scopes: ScopeStack<PlainLang>) -> ParsingState<PlainLang> {
        ParsingState::new(StateData { rules: min_rules(), scopes, mode: (), ext: () })
    }

    fn new_spec<L: Lang>() -> Arc<dyn CallableSpec<L>> {
        Arc::new(StdCallableSpec::default())
    }

    fn macro_query(name: &str) -> CallableQuery<'_, PlainLang> {
        CallableQuery::new(MACRO, name, CallableSyntax::Command { escape_char: '\\' })
    }

    fn package_with(name: &str, definitions: &[(&str, &Arc<dyn CallableSpec<PlainLang>>)]) -> Package<PlainLang> {
        let mut package = Package::new(name);
        for (defined, spec) in definitions {
            package.insert(MACRO, *defined, Arc::clone(spec));
        }
        package
    }

    // --- Package data surface -----------------------------------------------------------

    #[test]
    fn dyn_specs_provider_downcasts_to_its_concrete_type() {
        // The `Any` supertrait: a stored `Arc<dyn SpecsProvider<L>>` gives its concrete
        // type back through dyn-to-`Any` upcasting.
        let provider: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(Package::new("mypkg"));
        let any: &dyn Any = &*provider;
        let package = any.downcast_ref::<Package<PlainLang>>().expect("downcast to Package");
        assert_eq!(package.name(), "mypkg");
    }

    #[test]
    fn package_insert_get_replace() {
        let mut package: Package<PlainLang> = Package::new("test");
        assert!(package.is_empty());

        let first = new_spec();
        let second = new_spec();
        assert!(package.insert(MACRO, "foo", first.clone()).is_none());
        assert!(Arc::ptr_eq(package.get(MACRO, "foo").unwrap(), &first));

        // Same key replaces (shadowing within one provider = replacement) and returns
        // the previous spec; other callable types are separate key spaces.
        let previous = package.insert(MACRO, "foo", second.clone()).unwrap();
        assert!(Arc::ptr_eq(&previous, &first));
        assert!(package.get(ENVIRONMENT, "foo").is_none());
        assert_eq!(package.len(), 1);
    }

    #[test]
    fn specs_are_flyweights_across_names() {
        let mut package: Package<PlainLang> = Package::new("test");
        let shared = new_spec();
        package.insert(MACRO, "emph", shared.clone());
        package.insert(MACRO, "textit", shared.clone());

        let a = package.get(MACRO, "emph").unwrap();
        let b = package.get(MACRO, "textit").unwrap();
        assert!(Arc::ptr_eq(a, b));
    }

    #[test]
    fn a_shared_package_may_build_another_shared_package_inside_its_own_build() {
        let mut outer_stamp = None;
        let mut inner = None;
        let outer = Package::<PlainLang>::new_shared("outer", |package| {
            let stamp = package.provenance_for(MACRO, "outer-macro").expect("a shared package stamps");
            // While `build` runs, the outer package's own stamp resolves to nothing:
            // its `Arc` is not finished, so the weak pointer cannot be upgraded.
            assert!(stamp.provider().is_none());
            package.insert(MACRO, "outer-macro", new_spec());

            // A second shared package, built here, gets an `Arc` of its own.
            let nested = Package::<PlainLang>::new_shared("inner", |nested| {
                let nested_stamp = nested.provenance_for(MACRO, "inner-macro").expect("a shared package stamps");
                assert!(nested_stamp.provider().is_none());
                nested.insert(MACRO, "inner-macro", new_spec());
            });
            assert!(nested.is_shared());
            // The inner package is finished, so its stamps resolve to it — while the
            // outer one is still being built.
            let nested_stamp = nested.provenance_for(MACRO, "inner-macro").unwrap();
            assert_eq!(nested_stamp.provider().expect("the inner package is finished").name(), "inner");

            outer_stamp = Some(stamp);
            inner = Some(nested);
        });

        assert!(outer.is_shared());
        let inner = inner.unwrap();
        assert!(inner.is_shared());
        assert!(inner.get(MACRO, "inner-macro").is_some());
        assert!(outer.get(MACRO, "outer-macro").is_some());

        // The stamp issued inside `build` resolves to the outer package now.
        let provider = outer_stamp.unwrap().provider().expect("the outer package is finished");
        assert_eq!(provider.name(), "outer");
        let outer_provider: Arc<dyn SpecsProvider<PlainLang>> = outer.clone();
        assert!(Arc::ptr_eq(&provider, &outer_provider));
        // Both stamps issued inside the inner build resolve to the inner package.
        let nested_stamp = inner.provenance_for(MACRO, "inner-macro").unwrap();
        let inner_provider: Arc<dyn SpecsProvider<PlainLang>> = inner.clone();
        assert!(Arc::ptr_eq(&nested_stamp.provider().unwrap(), &inner_provider));
    }

    // --- stack retrieval: shadowing, fallbacks, error specs, provider errors ------------

    #[test]
    fn stack_retrieval_innermost_wins() {
        let outer_spec = new_spec();
        let inner_spec = new_spec();

        let outer = package_with("outer", &[("foo", &outer_spec), ("bar", &outer_spec)]);
        let inner = package_with("inner", &[("foo", &inner_spec)]);

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(outer));
        stack.push(Arc::new(inner));
        let st = state_with(ScopeStack::new());

        // "foo" shadowed by the innermost; "bar" falls through to the outer package;
        // a full miss is the structured Ok(None).
        let foo = stack.retrieve_spec(&macro_query("foo"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&foo, &inner_spec));
        let bar = stack.retrieve_spec(&macro_query("bar"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&bar, &outer_spec));
        assert!(stack.retrieve_spec(&macro_query("nope"), &st).unwrap().is_none());
    }

    #[test]
    fn fallback_provider_is_ordinary_bottom_of_stack_policy() {
        let defined = new_spec();
        let unknown_macro = new_spec();

        let mut fallbacks: FallbackProvider<PlainLang> = FallbackProvider::new("fallbacks");
        assert!(fallbacks.set(MACRO, unknown_macro.clone()).is_none());
        assert!(Arc::ptr_eq(fallbacks.get(MACRO).unwrap(), &unknown_macro));

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(fallbacks)); // bottom: pushed first
        stack.push(Arc::new(package_with("outer", &[("known", &defined)])));
        let st = state_with(ScopeStack::new());

        // Stack hit above the fallback: the fallback never answers.
        let known = stack.retrieve_spec(&macro_query("known"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&known, &defined));

        // Miss above: the fallback answers *any* name of its type — same singleton.
        let a = stack.retrieve_spec(&macro_query("nope"), &st).unwrap().unwrap();
        let b = stack.retrieve_spec(&macro_query("also-nope"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&a, &unknown_macro));
        assert!(Arc::ptr_eq(&a, &b));

        // No fallback registered for ENVIRONMENT: a true miss.
        let env_query =
            CallableQuery::new(ENVIRONMENT, "nope", CallableSyntax::Command { escape_char: '\\' });
        assert!(stack.retrieve_spec(&env_query, &st).unwrap().is_none());
    }

    #[test]
    fn error_spec_shadowing_suppresses_lower_entries_and_fallback() {
        // "Defined to be an error" is an ordinary definition: shadowing with an
        // ErrorCallableSpec suppresses the package definition *and* the fallback purely
        // by search order (a theorem of ordering, not an extra rule).
        let real = new_spec();
        let error_spec: Arc<dyn CallableSpec<PlainLang>> =
            Arc::new(ErrorCallableSpec::with_detail("removed on purpose"));

        let mut fallbacks: FallbackProvider<PlainLang> = FallbackProvider::new("fallbacks");
        fallbacks.set(MACRO, new_spec());
        let mut shadow: Scope<PlainLang> = Scope::new("shadow");
        shadow.insert(MACRO, "gone", Arc::clone(&error_spec));

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(fallbacks));
        stack.push(Arc::new(package_with("outer", &[("gone", &real)])));
        stack.push(Arc::new(shadow));
        let st = state_with(ScopeStack::new());

        let resolved = stack.retrieve_spec(&macro_query("gone"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&resolved, &error_spec));
    }

    #[test]
    fn provider_error_aborts_retrieval_with_the_providers_name() {
        #[derive(Debug)]
        struct Failing;
        impl SerializableObject<PlainLang> for Failing {}
        impl SpecsProvider<PlainLang> for Failing {
            fn name(&self) -> &str {
                "failing"
            }
            fn retrieve_spec(
                &self,
                _query: &CallableQuery<'_, PlainLang>,
                _state: &ParsingState<PlainLang>,
            ) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
                Err(ProviderError::Failed("backing store unavailable".into()))
            }
        }

        let answer = new_spec();
        let mut stack = ScopeStack::new();
        stack.push(Arc::new(package_with("outer", &[("foo", &answer)])));
        stack.push(Arc::new(Failing)); // innermost: hit first, aborts the fold
        let st = state_with(ScopeStack::new());

        let error = stack.retrieve_spec(&macro_query("foo"), &st).unwrap_err();
        assert_eq!(&*error.provider, "failing");
        assert_eq!(error.error, ProviderError::Failed("backing store unavailable".into()));
        assert!(error.to_string().contains("failing"));
    }

    #[test]
    fn searched_providers_reports_innermost_first() {
        let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
        assert_eq!(stack.searched_providers().to_string(), "no providers on the scope stack");

        stack.push(Arc::new(package_with("outer", &[])));
        stack.push(Arc::new(package_with("inner", &[])));
        assert_eq!(
            stack.searched_providers().to_string(),
            "searched providers: inner, outer"
        );
        assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["inner", "outer"]);
    }

    // --- custom-provider dispatch (carried over from the Phase 4 lookup contract) --------

    #[test]
    fn provider_can_dispatch_on_syntax() {
        // `\foo` and `#foo` resolve to different specs (open question [§dd-dr:open-questions] (a), decided
        // July 2026; the query carries the fired escape char).
        #[derive(Debug)]
        struct BySyntax {
            backslash: Arc<dyn CallableSpec<PlainLang>>,
            hash: Arc<dyn CallableSpec<PlainLang>>,
        }
        impl SerializableObject<PlainLang> for BySyntax {}
        impl SpecsProvider<PlainLang> for BySyntax {
            fn name(&self) -> &str {
                "by-syntax"
            }
            fn retrieve_spec(
                &self,
                query: &CallableQuery<'_, PlainLang>,
                _state: &ParsingState<PlainLang>,
            ) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
                Ok(match query.syntax {
                    CallableSyntax::Command { escape_char: '\\' } => Some(self.backslash.clone()),
                    CallableSyntax::Command { escape_char: '#' } => Some(self.hash.clone()),
                    _ => None,
                })
            }
        }

        let by_syntax = BySyntax { backslash: new_spec(), hash: new_spec() };
        let backslash_spec = by_syntax.backslash.clone();
        let hash_spec = by_syntax.hash.clone();

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(by_syntax));
        let st = state_with(ScopeStack::new());

        let via_backslash = stack.retrieve_spec(&macro_query("foo"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&via_backslash, &backslash_spec));

        let hash_query =
            CallableQuery::new(MACRO, "foo", CallableSyntax::Command { escape_char: '#' });
        let via_hash = stack.retrieve_spec(&hash_query, &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&via_hash, &hash_spec));
    }

    // --- mode visibility ------------------------------------------------------------------

    #[derive(Debug, Clone, Copy, PartialEq, Eq, core::hash::Hash, Default)]
    enum Mode {
        #[default]
        Text,
        Math,
    }

    #[derive(Debug, Clone, Copy)]
    struct ModedLang;
    impl Lang for ModedLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = Mode;
        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: &crate::node::NodeKind<Self>,
            _span: &crate::source::SourceSpan<Self::SourceOrigin>,
            _state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    fn moded_state(scopes: ScopeStack<ModedLang>, mode: Mode) -> ParsingState<ModedLang> {
        ParsingState::new(StateData { rules: min_rules(), scopes, mode, ext: () })
    }

    #[test]
    fn package_mode_visibility_is_checked_by_the_package_itself() {
        let math_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
        let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();

        let mut math_pkg: Package<ModedLang> = Package::new("math-only");
        math_pkg.insert(MACRO, "vec", Arc::clone(&math_spec));
        math_pkg.insert_specials(MACRO, "&", Arc::clone(&math_spec));
        math_pkg.set_visible_modes(Some(vec![Mode::Math]));

        let mut base: Package<ModedLang> = Package::new("allmodes");
        base.insert(MACRO, "vec", Arc::clone(&text_spec));

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(base));
        stack.push(Arc::new(math_pkg)); // innermost, but mode-restricted
        let text_state = moded_state(stack.clone(), Mode::Text);
        let math_state = moded_state(stack.clone(), Mode::Math);

        let query: CallableQuery<'_, ModedLang> =
            CallableQuery::new(MACRO, "vec", CallableSyntax::Command { escape_char: '\\' });

        // Text mode: the restricted package answers "not here" — the stack is
        // visibility-blind and simply continues outward.
        let in_text = stack.retrieve_spec(&query, &text_state).unwrap().unwrap();
        assert!(Arc::ptr_eq(&in_text, &text_spec));
        // Math mode: the innermost package answers.
        let in_math = stack.retrieve_spec(&query, &math_state).unwrap().unwrap();
        assert!(Arc::ptr_eq(&in_math, &math_spec));

        // Specials scan respects the same visibility; the trigger-char union does NOT
        // (chars stay in the filter regardless of state — the scan declines instead).
        assert!(stack.scan_specials(&text_state, "&x", 0).unwrap().is_none());
        assert!(stack.scan_specials(&math_state, "&x", 0).unwrap().is_some());
        assert_eq!(stack.specials_trigger_chars(), TriggerChars::Only("&".into()));
    }

    #[test]
    fn per_entry_mode_visibility_gates_within_a_package() {
        let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
        let any_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();

        // One package, no package-level restriction: a text-only entry and an all-modes
        // entry side by side — the fine gate (per-entry mode visibility).
        let mut pkg: Package<ModedLang> = Package::new("mixed");
        pkg.insert_in_modes(MACRO, "emph", Arc::clone(&text_spec), Some(vec![Mode::Text]));
        pkg.insert(MACRO, "vec", Arc::clone(&any_spec)); // all modes
        pkg.insert_specials_in_modes(MACRO, "--", Arc::clone(&text_spec), Some(vec![Mode::Text]));
        pkg.insert_specials(MACRO, "~", Arc::clone(&any_spec)); // all modes

        let mut stack = ScopeStack::new();
        stack.push(Arc::new(pkg));
        let text_state = moded_state(stack.clone(), Mode::Text);
        let math_state = moded_state(stack.clone(), Mode::Math);

        let emph: CallableQuery<'_, ModedLang> =
            CallableQuery::new(MACRO, "emph", CallableSyntax::Command { escape_char: '\\' });
        let vec_q: CallableQuery<'_, ModedLang> =
            CallableQuery::new(MACRO, "vec", CallableSyntax::Command { escape_char: '\\' });

        // The text-only definition resolves in text, not in math; the all-modes one in
        // both.
        assert!(stack.retrieve_spec(&emph, &text_state).unwrap().is_some());
        assert!(stack.retrieve_spec(&emph, &math_state).unwrap().is_none());
        assert!(stack.retrieve_spec(&vec_q, &text_state).unwrap().is_some());
        assert!(stack.retrieve_spec(&vec_q, &math_state).unwrap().is_some());

        // Specials obey the same per-entry gate; the trigger-char union stays mode-blind.
        assert!(stack.scan_specials(&text_state, "--x", 0).unwrap().is_some());
        assert!(stack.scan_specials(&math_state, "--x", 0).unwrap().is_none());
        assert!(stack.scan_specials(&text_state, "~x", 0).unwrap().is_some());
        assert!(stack.scan_specials(&math_state, "~x", 0).unwrap().is_some());
    }

    // --- Scope: copy-on-write definition updates ------------------------------------------

    #[test]
    fn scope_with_definitions_is_functional_and_atomic() {
        let original_spec = new_spec();
        let mut scope: Scope<PlainLang> = Scope::new("user");
        scope.insert(MACRO, "foo", Arc::clone(&original_spec));
        let scope: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(scope);
        let st = state_with(ScopeStack::new());

        // Define returns a fresh provider; the original is untouched (CoW).
        let added = new_spec();
        let fresh = scope
            .with_definitions(&[DefinitionOp::Define {
                callable_type: MACRO,
                name: "bar".into(),
                spec: Arc::clone(&added),
            }])
            .unwrap();
        assert!(fresh.retrieve_spec(&macro_query("bar"), &st).unwrap().is_some());
        assert!(scope.retrieve_spec(&macro_query("bar"), &st).unwrap().is_none());

        // Remove works on the fresh copy; removing an absent name is an error…
        let removed = fresh
            .with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "foo".into() }])
            .unwrap();
        assert!(removed.retrieve_spec(&macro_query("foo"), &st).unwrap().is_none());
        let error = removed
            .with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "foo".into() }])
            .unwrap_err();
        assert_eq!(error, ProviderError::UndefinedName { name: "foo".into() });

        // …and a failing op anywhere in the batch discards the whole batch (atomic).
        let error = scope
            .with_definitions(&[
                DefinitionOp::Define {
                    callable_type: MACRO,
                    name: "baz".into(),
                    spec: new_spec(),
                },
                DefinitionOp::Remove { callable_type: MACRO, name: "absent".into() },
            ])
            .unwrap_err();
        assert_eq!(error, ProviderError::UndefinedName { name: "absent".into() });
        assert!(scope.retrieve_spec(&macro_query("baz"), &st).unwrap().is_none());
    }

    #[test]
    fn immutable_providers_refuse_definition_ops() {
        let package: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("pkg", &[]));
        let error = package
            .with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "x".into() }])
            .unwrap_err();
        assert_eq!(error, ProviderError::NotMutable);
    }

    // --- ScopeStack::apply_op ---------------------------------------------------------------

    #[test]
    fn apply_op_stack_shapes() {
        let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
        let a: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("a", &[]));
        let b: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("b", &[]));
        let b2: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("b", &[]));

        stack.apply_op(&ScopeOp::Push(Arc::clone(&a))).unwrap();
        stack.apply_op(&ScopeOp::Push(Arc::clone(&b))).unwrap();
        assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["b", "a"]);

        // Replace swaps in place (innermost match).
        stack.apply_op(&ScopeOp::Replace { name: "b".into(), provider: Arc::clone(&b2) }).unwrap();
        assert!(Arc::ptr_eq(&stack.providers()[1], &b2));

        // Unload removes; unknown names are errors, never silent no-ops.
        stack.apply_op(&ScopeOp::Unload { name: "b".into() }).unwrap();
        assert_eq!(stack.len(), 1);
        let error = stack.apply_op(&ScopeOp::Unload { name: "b".into() }).unwrap_err();
        assert_eq!(error, ScopeOpError::UnknownProvider { name: "b".into() });
        let error = stack
            .apply_op(&ScopeOp::Replace { name: "zz".into(), provider: Arc::clone(&b2) })
            .unwrap_err();
        assert_eq!(error, ScopeOpError::UnknownProvider { name: "zz".into() });

        // ReplaceStack swaps wholesale.
        stack.apply_op(&ScopeOp::ReplaceStack(vec![Arc::clone(&b2)])).unwrap();
        assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["b"]);
    }

    #[test]
    fn apply_op_define_routes_cow_and_lazily_creates() {
        let st = state_with(ScopeStack::new());
        let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
        let mut user: Scope<PlainLang> = Scope::new("user");
        user.insert(MACRO, "foo", new_spec());
        stack.push(Arc::new(user));
        stack.push(Arc::new(package_with("pkg", &[])));
        let before = stack.clone(); // shares the Arcs — the structural-reversion stand-in

        // Define routed to the (non-innermost) named scope: CoW entry swap — the
        // cloned stack still holds the old provider and never sees the definition.
        let added = new_spec();
        stack
            .apply_op(&ScopeOp::Define {
                scope: "user".into(),
                callable_type: MACRO,
                name: "bar".into(),
                spec: Arc::clone(&added),
            })
            .unwrap();
        let bar = stack.retrieve_spec(&macro_query("bar"), &st).unwrap().unwrap();
        assert!(Arc::ptr_eq(&bar, &added));
        assert!(before.retrieve_spec(&macro_query("bar"), &st).unwrap().is_none());
        assert!(!Arc::ptr_eq(&stack.providers()[0], &before.providers()[0]));
        assert!(Arc::ptr_eq(&stack.providers()[1], &before.providers()[1]));

        // Define into an absent scope name creates it lazily, innermost.
        stack
            .apply_op(&ScopeOp::Define {
                scope: "local".into(),
                callable_type: MACRO,
                name: "baz".into(),
                spec: new_spec(),
            })
            .unwrap();
        assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["local", "pkg", "user"]);
        assert!(stack.retrieve_spec(&macro_query("baz"), &st).unwrap().is_some());

        // Define routed to an immutable provider fails with the provider's refusal.
        let error = stack
            .apply_op(&ScopeOp::Define {
                scope: "pkg".into(),
                callable_type: MACRO,
                name: "x".into(),
                spec: new_spec(),
            })
            .unwrap_err();
        assert_eq!(
            error,
            ScopeOpError::Provider(ScopeStackError {
                provider: "pkg".into(),
                error: ProviderError::NotMutable,
            })
        );

        // Remove routes the same way; an absent *provider* is UnknownProvider.
        stack
            .apply_op(&ScopeOp::Remove {
                scope: "user".into(),
                callable_type: MACRO,
                name: "bar".into(),
            })
            .unwrap();
        assert!(stack.retrieve_spec(&macro_query("bar"), &st).unwrap().is_none());
        let error = stack
            .apply_op(&ScopeOp::Remove {
                scope: "nowhere".into(),
                callable_type: MACRO,
                name: "bar".into(),
            })
            .unwrap_err();
        assert_eq!(error, ScopeOpError::UnknownProvider { name: "nowhere".into() });
    }

    // --- specials: package data, the stack fold, trigger unions ---------------------------

    fn specials_package(
        name: &str,
        triggers: &[(&str, &Arc<dyn CallableSpec<PlainLang>>)],
    ) -> Package<PlainLang> {
        let mut package = Package::new(name);
        for (trigger, spec) in triggers {
            package.insert_specials(MACRO, *trigger, Arc::clone(spec));
        }
        package
    }

    #[test]
    fn package_specials_match_longest_within_the_package() {
        let short = new_spec();
        let long = new_spec();
        let mut package = specials_package("lig", &[("--", &short), ("---", &long)]);
        let st = state_with(ScopeStack::new());

        // The match reports its end; the matched text `content[pos..end]` is the name.
        let matched = package.scan_specials(&st, "---x", 0).unwrap().unwrap();
        assert_eq!(matched.end, 3);
        assert!(Arc::ptr_eq(&matched.spec, &long));

        let matched = package.scan_specials(&st, "--x", 0).unwrap().unwrap();
        assert_eq!(matched.end, 2);
        assert!(package.scan_specials(&st, "x--", 0).unwrap().is_none());

        // Positions are absolute; matching mid-content works on byte offsets.
        let matched = package.scan_specials(&st, "a--b", 1).unwrap().unwrap();
        assert_eq!(matched.end, 3);

        // Re-inserting an existing trigger replaces its resolution.
        let replacement = new_spec();
        let previous = package.insert_specials(MACRO, "---", Arc::clone(&replacement)).unwrap();
        assert!(Arc::ptr_eq(&previous, &long));
        let matched = package.scan_specials(&st, "---", 0).unwrap().unwrap();
        assert!(Arc::ptr_eq(&matched.spec, &replacement));

        assert_eq!(package.specials_trigger_chars(), TriggerChars::Only("-".into()));
    }

    /// The `pos` contract: an invalid position (out of the content's bounds or
    /// not a character boundary) answers an implementation-error `SpecialsScanError`
    /// — never a panic, never a silent no-match — while every valid boundary
    /// position scans as before.
    #[test]
    fn package_scan_specials_rejects_invalid_positions_with_an_error() {
        let spec = new_spec();
        let package = specials_package("lig", &[("--", &spec)]);
        let st = state_with(ScopeStack::new());

        // Out of range — the message names the case.
        let error = package.scan_specials(&st, "--", 7).unwrap_err();
        assert!(error.kind.to_string().contains("extension contract violation"));
        assert!(error.kind.to_string().contains("invalid position 7"));
        assert!(
            error.kind.to_string().contains("out of the content's bounds"),
            "{:?}",
            error
        );

        // Mid-character: `é` is two bytes, so pos 1 is not a character boundary —
        // named as the boundary case, not the bounds case.
        let error = package.scan_specials(&st, "é--", 1).unwrap_err();
        assert!(error.kind.to_string().contains("invalid position 1"));
        assert!(
            error.kind.to_string().contains("not a character boundary"),
            "{:?}",
            error
        );

        // Valid boundary positions are unaffected — end of content included.
        assert!(package.scan_specials(&st, "x--", 1).unwrap().is_some());
        assert!(package.scan_specials(&st, "--", 2).unwrap().is_none());
        assert!(package.scan_specials(&st, "é--", 2).unwrap().is_some());
    }

    #[test]
    fn stack_specials_fold_longest_wins_ties_innermost() {
        let inner_short = new_spec();
        let outer_long = new_spec();
        let outer_short = new_spec();

        // Inner provider defines `--`; outer defines `--` AND `---`.
        let inner = specials_package("inner", &[("--", &inner_short)]);
        let outer = specials_package("outer", &[("--", &outer_short), ("---", &outer_long)]);
        let mut stack = ScopeStack::new();
        stack.push(Arc::new(outer));
        stack.push(Arc::new(inner));
        let st = state_with(ScopeStack::new());

        // Longest wins across providers: `---` (outer) beats `--` (inner) — the
        // pylatexenc parity case.
        let matched = stack.scan_specials(&st, "---", 0).unwrap().unwrap();
        assert_eq!(matched.end, 3);
        assert!(Arc::ptr_eq(&matched.spec, &outer_long));

        // Equal length is the same spelling: the tie goes innermost — shadowing.
        let matched = stack.scan_specials(&st, "--x", 0).unwrap().unwrap();
        assert!(Arc::ptr_eq(&matched.spec, &inner_short));

        // Union of trigger chars over providers, deduplicated.
        assert_eq!(stack.specials_trigger_chars(), TriggerChars::Only("-".into()));
    }

    #[test]
    fn stack_specials_fold_propagates_provider_scan_errors() {
        #[derive(Debug)]
        struct FailingScan;
        impl SerializableObject<PlainLang> for FailingScan {}
        impl SpecsProvider<PlainLang> for FailingScan {
            fn name(&self) -> &str {
                "failing-scan"
            }
            fn retrieve_spec(
                &self,
                _query: &CallableQuery<'_, PlainLang>,
                _state: &ParsingState<PlainLang>,
            ) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
                Ok(None)
            }
            fn scan_specials(
                &self,
                _state: &ParsingState<PlainLang>,
                _content: &str,
                _pos: usize,
            ) -> Result<Option<SpecialsMatch<PlainLang>>, SpecialsScanError> {
                Err(SpecialsScanError {
                    kind: TokenErrorKind::Custom(Box::new(
                        crate::constructs::ImplementationError::new("scan broke".to_string()),
                    )),
                    span: crate::source::Span::new(0, 1),
                })
            }
            fn specials_trigger_chars(&self) -> TriggerChars {
                TriggerChars::Any
            }
        }

        let ok = new_spec();
        let mut stack = ScopeStack::new();
        stack.push(Arc::new(specials_package("outer", &[("-", &ok)])));
        stack.push(Arc::new(FailingScan));
        let st = state_with(ScopeStack::new());

        let error = stack.scan_specials(&st, "-", 0).unwrap_err();
        assert!(error.kind.to_string().contains("scan broke"));
        assert_eq!(stack.specials_trigger_chars(), TriggerChars::Any);
    }

    // --- iter_symbols (Phase 7.8) -----------------------------------------------------

    fn names_of<'a, L: Lang>(symbols: &[SymbolEntry<'a, L>]) -> Vec<&'a str> {
        symbols.iter().map(|entry| entry.name).collect()
    }

    #[test]
    fn package_enumerates_by_callable_type_including_specials() {
        let spec = new_spec();
        let mut pkg: Package<PlainLang> = Package::new("p");
        pkg.insert(MACRO, "alpha", Arc::clone(&spec));
        pkg.insert(ENVIRONMENT, "itemize", Arc::clone(&spec));
        pkg.insert_specials(MACRO, "--", Arc::clone(&spec));

        let mut macros = names_of(&pkg.iter_symbols(MACRO, ()).unwrap().collect::<Vec<_>>());
        macros.sort_unstable();
        // The by-name table and the specials table both contribute under the entries'
        // *recorded* type; the specials row's name is the trigger spelling.
        assert_eq!(macros, ["--", "alpha"]);
        let environments =
            names_of(&pkg.iter_symbols(ENVIRONMENT, ()).unwrap().collect::<Vec<_>>());
        assert_eq!(environments, ["itemize"]);
        // Rows are self-describing and borrow the stored spec.
        let row = pkg.iter_symbols(ENVIRONMENT, ()).unwrap().next().unwrap();
        assert_eq!(row.callable_type, ENVIRONMENT);
        assert!(Arc::ptr_eq(row.spec, &spec));
    }

    #[test]
    fn package_iter_symbols_applies_both_visibility_gates() {
        let spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
        let mut pkg: Package<ModedLang> = Package::new("mixed");
        pkg.insert(MACRO, "vec", Arc::clone(&spec)); // all modes
        pkg.insert_in_modes(MACRO, "emph", Arc::clone(&spec), Some(vec![Mode::Text]));
        pkg.insert_specials_in_modes(MACRO, "--", Arc::clone(&spec), Some(vec![Mode::Text]));

        let mut in_text = names_of(&pkg.iter_symbols(MACRO, Mode::Text).unwrap().collect::<Vec<_>>());
        in_text.sort_unstable();
        assert_eq!(in_text, ["--", "emph", "vec"]);
        // The per-entry gate filters; the all-modes entry stays.
        assert_eq!(
            names_of(&pkg.iter_symbols(MACRO, Mode::Math).unwrap().collect::<Vec<_>>()),
            ["vec"]
        );

        // The package-level gate: enumerable, nothing visible (Some(empty), not None).
        let mut gated: Package<ModedLang> = Package::new("math-only");
        gated.insert(MACRO, "frac", new_spec());
        gated.set_visible_modes(Some(vec![Mode::Math]));
        assert_eq!(gated.iter_symbols(MACRO, Mode::Text).unwrap().count(), 0);
        assert_eq!(gated.iter_symbols(MACRO, Mode::Math).unwrap().count(), 1);
    }

    #[test]
    fn scope_enumerates_ignoring_mode() {
        let mut scope: Scope<ModedLang> = Scope::new("local");
        scope.insert(MACRO, "beta", new_spec());
        scope.insert(ENVIRONMENT, "quote", new_spec());
        // Scope definitions carry no visibility: every mode sees them.
        assert_eq!(names_of(&scope.iter_symbols(MACRO, Mode::Math).unwrap().collect::<Vec<_>>()), ["beta"]);
        assert_eq!(names_of(&scope.iter_symbols(MACRO, Mode::Text).unwrap().collect::<Vec<_>>()), ["beta"]);
        assert_eq!(
            names_of(&scope.iter_symbols(ENVIRONMENT, Mode::Text).unwrap().collect::<Vec<_>>()),
            ["quote"]
        );
    }

    #[test]
    fn default_iter_symbols_is_not_enumerable() {
        // FallbackProvider answers *any* name — it keeps the trait default.
        let mut fallback: FallbackProvider<PlainLang> = FallbackProvider::new("fallback");
        fallback.set(MACRO, new_spec());
        assert!(fallback.iter_symbols(MACRO, ()).is_none());
    }

    #[test]
    fn stack_iter_symbols_dedups_innermost_first_and_skips_unenumerable() {
        let outer_spec = new_spec();
        let inner_spec = new_spec();
        let mut outer: Package<PlainLang> = Package::new("outer");
        outer.insert(MACRO, "alpha", Arc::clone(&outer_spec));
        outer.insert(MACRO, "omega", Arc::clone(&outer_spec));
        let mut inner: Scope<PlainLang> = Scope::new("inner");
        inner.insert(MACRO, "alpha", Arc::clone(&inner_spec)); // shadows outer's

        let mut fallback: FallbackProvider<PlainLang> = FallbackProvider::new("fallback");
        fallback.set(MACRO, new_spec());

        let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
        stack.push(Arc::new(fallback)); // unenumerable: skipped, not an error
        stack.push(Arc::new(outer));
        stack.push(Arc::new(inner));

        let symbols = stack.iter_symbols(MACRO, ());
        let mut names = names_of(&symbols);
        names.sort_unstable();
        assert_eq!(names, ["alpha", "omega"]);
        // First (innermost) visible occurrence wins — mirrors retrieve_spec resolution.
        let alpha = symbols.iter().find(|entry| entry.name == "alpha").unwrap();
        assert!(Arc::ptr_eq(alpha.spec, &inner_spec));
        // Innermost entries come first in the listing.
        assert_eq!(names_of(&symbols)[0], "alpha");

        // A mode-invisible provider's entries fall through to outer ones: the dedup is
        // "first *visible* wins", because each provider pre-filters by mode.
        let moded_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
        let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
        let mut math_pkg: Package<ModedLang> = Package::new("math-only");
        math_pkg.insert(MACRO, "vec", Arc::clone(&moded_spec));
        math_pkg.set_visible_modes(Some(vec![Mode::Math]));
        let mut base: Package<ModedLang> = Package::new("allmodes");
        base.insert(MACRO, "vec", Arc::clone(&text_spec));
        let mut stack: ScopeStack<ModedLang> = ScopeStack::new();
        stack.push(Arc::new(base));
        stack.push(Arc::new(math_pkg));
        let in_text = stack.iter_symbols(MACRO, Mode::Text);
        assert!(Arc::ptr_eq(in_text[0].spec, &text_spec));
        let in_math = stack.iter_symbols(MACRO, Mode::Math);
        assert!(Arc::ptr_eq(in_math[0].spec, &moded_spec));
    }

    #[test]
    fn escape_shadowing_check_reports_per_provider_and_type() {
        use crate::latexlike::{
            CallableType, EnvironmentSpec, Latexlike, MacroSpec,
        };
        use crate::source::Source;

        // Identifier stability: the reserved wire identifier, frozen by the slate.
        assert_eq!(
            ProviderCommandsShadowedByEscape::IDENTIFIER,
            "core.specs.provider-commands-shadowed-by-escape"
        );

        // One provider, two tables: the Environment table is all-escape-shadowed,
        // the Macro table is clean — exactly one warning, naming the shadowed
        // type. (Pooling the tables would let the clean entry silence it.)
        let mut package: Package<Latexlike> = Package::new("mixed");
        package.insert(CallableType::Macro, "good", Arc::new(MacroSpec::default()));
        package.insert(
            CallableType::Environment,
            r"\align",
            Arc::new(EnvironmentSpec::new(alloc::vec![])),
        );
        let state =
            crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([package])
                .expect("seed state");
        let source = Arc::new(Source::new("any content"));
        let mut diagnostics = crate::error::Diagnostics::new();
        check_provider_commands_shadowed_by_escape(&state, &source, &mut diagnostics);
        assert_eq!(diagnostics.len(), 1);
        let diagnostic = diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.severity(), crate::error::Severity::Warning);
        let condition = diagnostic
            .data()
            .downcast_ref::<ProviderCommandsShadowedByEscape>()
            .unwrap();
        assert_eq!(condition.provider, "mixed");
        assert_eq!(condition.callable_type, "Environment");
        assert_eq!(condition.count, 1);
        assert_eq!(condition.example, r"\align");
        assert_eq!(condition.escape_chars, "\\");
    }

    #[test]
    fn escape_shadowing_check_leaves_one_character_names_alone() {
        use crate::latexlike::{CallableType, Latexlike, MacroSpec};
        use crate::source::Source;

        /// The warnings the check records for a package of `names` under `Macro`.
        fn warnings(names: &[&str]) -> usize {
            let mut package: Package<Latexlike> = Package::new("pkg");
            for name in names {
                package.insert(CallableType::Macro, *name, Arc::new(MacroSpec::default()));
            }
            let state =
                crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([package])
                    .expect("seed state");
            let source = Arc::new(Source::new("any content"));
            let mut diagnostics = crate::error::Diagnostics::new();
            check_provider_commands_shadowed_by_escape(&state, &source, &mut diagnostics);
            diagnostics.len()
        }

        // The command `\\` is registered under the one-character name `\`: the
        // tokenizer reads a single non-name character as a one-character command name.
        // That is a legitimate registration, alone or beside a real mistake.
        assert_eq!(warnings(&["\\"]), 0);
        assert_eq!(warnings(&["\\", r"\greet"]), 0);
        // Other one-character command names — `\#`, read as the command `#` — likewise.
        assert_eq!(warnings(&["\\", "#"]), 0);
        // The mistake itself still warns, one character past the escape included.
        assert_eq!(warnings(&[r"\greet"]), 1);
        assert_eq!(warnings(&[r"\x"]), 1);
        assert_eq!(warnings(&[r"\greet", r"\x"]), 1);
    }

    #[test]
    fn closed_vocabulary_drives_whole_scope_enumeration() {
        use crate::state::ClosedVocabulary;

        // The tooling pattern the trait exists for: enumerate every invocation form of
        // a language whose vocabulary is statically listable.
        fn all_symbols<L: Lang>(stack: &ScopeStack<L>, mode: L::ModeId) -> Vec<(L::CallableTypeId, Box<str>)>
        where
            L::CallableTypeId: ClosedVocabulary,
        {
            let mut all = Vec::new();
            for &callable_type in L::CallableTypeId::ALL {
                for entry in stack.iter_symbols(callable_type, mode) {
                    all.push((entry.callable_type, Box::from(entry.name)));
                }
            }
            all
        }

        use crate::latexlike::{CallableType, Latexlike, Mode as LMode};
        let seed = crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([
            crate::latexlike::minidefs::minilatex_package(),
        ]).expect("seed state");
        let symbols = all_symbols(&seed.scopes().clone(), LMode::Text);
        let has = |ct: CallableType, name: &str| {
            symbols.iter().any(|(t, n)| *t == ct && &**n == name)
        };
        // The builtin package's \begin/\end are ordinary Macro entries; minilatex's
        // typography ligatures are Specials rows named by their trigger.
        assert!(has(CallableType::Macro, "begin"));
        assert!(has(CallableType::Macro, "end"));
        assert!(has(CallableType::Specials, "--"));
        assert!(has(CallableType::Specials, "~"));
        // The ligatures are text-only: invisible under Math.
        let in_math = all_symbols(&seed.scopes().clone(), LMode::Math);
        assert!(!in_math.iter().any(|(t, n)| *t == CallableType::Specials && &**n == "--"));
        // ALL lists the full vocabularies.
        assert_eq!(CallableType::ALL.len(), 3);
        assert_eq!(<() as ClosedVocabulary>::ALL, &[()]);
    }
}