usage-derive 6.6.0

Derive macro that compiles a CLI definition into parse tables and a usage spec
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
//! Turning a [`Cli`] into the code that parses for it.
//!
//! Three things are emitted, and the split is the whole point of the design:
//!
//! - `static` parse tables, which is all a successful parse reads.
//! - `static` metadata, which spec emission and help reading read and a parse
//!   never touches.
//! - a `parse` function that is a `match` on table indices, assigning straight
//!   into the struct's fields. No map, no intermediate value, nothing allocated
//!   that does not end up in the result.
//!
//! Both trees are emitted into one hidden module per type so that a CLI's tables
//! do not collide with anything, and so `cargo expand` shows them together.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use crate::crate_name::{crate_name, FoundCrate};
use crate::model::{
    rendered_path, to_kebab, type_name, AdmonitionKind, ArgGroup, ArgGroupMember, Cli,
    ConditionalDefault, Dispatch, DoubleDash, ExampleDecl, Field, HeadingDecl, Kind, SchemaSource,
    Shape, Subcommands, ValueEnum, Variant, ViewDecl,
};

fn admonitions(field: &Field) -> TokenStream {
    let entries = field.admonitions.iter().map(|admonition| {
        let text = &admonition.text;
        let kind = match admonition.kind {
            AdmonitionKind::Note => quote!(usage_argv::spec::AdmonitionKind::Note),
            AdmonitionKind::Warning => quote!(usage_argv::spec::AdmonitionKind::Warning),
        };
        quote!(usage_argv::spec::AdmonitionMeta { kind: #kind, text: #text })
    });
    quote!(&[#(#entries),*])
}

/// Construct the user's command type after its generated partial has been checked.
///
/// An empty named struct is `Self {}`, while a unit struct is just `Self`. Keeping
/// that syntax decision here prevents the root, settings, and nested-command build
/// paths from drifting apart.
fn built_value(cli: &Cli, sub_build: &TokenStream, fields: &[TokenStream]) -> TokenStream {
    if cli.unit {
        debug_assert!(cli.fields.is_empty());
        quote!(Self)
    } else {
        let field_reads = cli.fields.iter().map(|field| &field.ident);
        quote! {
            {
                let __usage_built = Self {
                    #sub_build
                    #(#fields),*
                };
                // A parsed compatibility flag may intentionally be accepted and ignored.
                // Reading every field here keeps `#[deny(dead_code)]` from blaming the
                // adopter for a field the derive itself owns. These shared references
                // generate no runtime work after optimization.
                #(let _ = &__usage_built.#field_reads;)*
                __usage_built
            }
        }
    }
}

/// Apply a root command's cross-field validation after every typed field exists.
fn validated_value(cli: &Cli, built: &TokenStream) -> TokenStream {
    let Some(validate_with) = &cli.validate_with else {
        return built.clone();
    };
    quote! {{
        let __usage_built = #built;
        #validate_with(&__usage_built)
            .map_err(usage_argv::ValidationError::into_parse_error)?;
        __usage_built
    }}
}

/// The runtime as the adopter depended on it.
///
/// A direct `usage-argv` dependency wins when both forms are present: a low-level adopter may
/// deliberately enable a different feature set there. Otherwise the `usage-rs` facade provides
/// the runtime as `usage::argv`, keeping derives, tables, and their versions behind one
/// dependency.
///
/// Resolved by reading the adopter's `Cargo.toml` directly rather than via `proc-macro-crate`,
/// so the derive does not drag `toml_edit` into every compile.
fn runtime_path() -> TokenStream {
    match crate_name("usage-argv") {
        Ok(FoundCrate::Name(name)) => {
            let runtime = format_ident!("{name}");
            quote!(::#runtime)
        }
        _ => match crate_name("usage-rs") {
            Ok(FoundCrate::Itself) => quote!(::usage_rs::argv),
            Ok(FoundCrate::Name(name)) => {
                let facade = format_ident!("{name}");
                quote!(::#facade::argv)
            }
            // Preserve the old useful compiler error when neither dependency was declared.
            _ => quote!(::usage_argv),
        },
    }
}

/// The derive package as the adopter depended on it.
///
/// Most emitted code only needs the runtime path. Unit subcommands synthesize an empty `Args`
/// struct, though, so that derive must come through the facade too when it is the application's
/// only dependency.
fn derive_path() -> TokenStream {
    match crate_name("usage-derive") {
        Ok(FoundCrate::Name(name)) => {
            let derive = format_ident!("{name}");
            quote!(::#derive)
        }
        _ => match crate_name("usage-rs") {
            Ok(FoundCrate::Itself) => quote!(::usage_rs),
            Ok(FoundCrate::Name(name)) => {
                let facade = format_ident!("{name}");
                quote!(::#facade)
            }
            _ => quote!(::usage_derive),
        },
    }
}

/// The schema library, as the adopter depended on it.
///
/// Emitted only where a `schema_from = T` was written, so a CLI that never asks for one
/// needs no such dependency. This crate does not have one either: it writes the path and
/// the adopter's compile resolves it, the same arrangement `usage_config` already has.
fn schemars_path() -> TokenStream {
    match crate_name("schemars") {
        Ok(FoundCrate::Itself) => quote!(::schemars),
        Ok(FoundCrate::Name(name)) => {
            let schemars = format_ident!("{}", name.replace('-', "_"));
            quote!(::#schemars)
        }
        // Keeps the useful "use of undeclared crate" error pointing at the attribute.
        _ => quote!(::schemars),
    }
}

/// The cold expression evaluator, resolved independently of the binding runtime.
fn validation_path() -> TokenStream {
    match crate_name("usage-validation") {
        Ok(FoundCrate::Itself) => quote!(::usage_validation),
        Ok(FoundCrate::Name(name)) => {
            let validation = format_ident!("{}", name.replace('-', "_"));
            quote!(::#validation)
        }
        _ => match crate_name("usage-rs") {
            Ok(FoundCrate::Itself) => quote!(::usage_rs::validation),
            Ok(FoundCrate::Name(name)) => {
                let facade = format_ident!("{}", name.replace('-', "_"));
                quote!(::#facade::validation)
            }
            _ => quote!(::usage_validation),
        },
    }
}

pub fn emit(cli: &Cli) -> TokenStream {
    let ident = &cli.ident;
    let runtime = runtime_path();
    let dispatch = emit_command_dispatch(cli, &runtime);
    let validation = validation_path();
    let validation_import = cli
        .fields
        .iter()
        .any(|field| field.validate.is_some())
        .then(|| quote!(use #validation as usage_validation;));

    let flags: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Flag { .. }))
        .collect();
    let args: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Arg { .. }))
        .collect();

    // Left unset when the struct says nothing, which is what lets the parser inherit it: one
    // command per struct, and a macro expansion cannot see the command above it. An earlier
    // version resolved it here and wrote `Value` for every silent command, which made the
    // root's declaration reach the root alone.
    let unknown_flags = unknown_flags_tokens(cli);

    let default_subcommand = option_str(cli.default_subcommand.as_deref());
    let multicall = cli.multicall;
    let no_binary_name = cli.no_binary_name;
    let arg_required_else_help = cli.arg_required_else_help;
    let dont_delimit_trailing_values = cli.dont_delimit_trailing_values;
    let args_override_self = cli.args_override_self;
    let subcommand_negates_reqs = cli.subcommand_negates_reqs;
    let args_conflicts_with_subcommands = cli.args_conflicts_with_subcommands;
    let subcommand_precedence_over_arg = cli.subcommand_precedence_over_arg;
    let allow_missing_positional = cli.allow_missing_positional;
    let disable_help_flag = cli.disable_help_flag;
    let disable_help_subcommand = cli.disable_help_subcommand;
    let disable_version_flag = cli.disable_version_flag;
    let subcommand_help_heading = option_str(cli.subcommand_help_heading.as_deref());
    let subcommand_value_name = option_str(cli.subcommand_value_name.as_deref());
    let next_line_help = cli.next_line_help;
    let flatten_help = cli.flatten_help;
    let term_width = option_usize(cli.term_width);
    let max_term_width = option_usize(cli.max_term_width);
    let usage = option_str(cli.usage.as_deref());
    let help_template = option_str(cli.help_template.as_deref());
    let restart_token = option_str(cli.restart_token.as_deref());
    let mount = option_str(cli.mount.as_deref());
    let OutputTokens {
        decls: output_schema_decls,
        outputs,
        select,
        exit_codes,
    } = output_tokens(cli);
    // A bare `T` subcommand field says the command cannot run alone; an `Option<T>` says it
    // can. The parser already refuses the invocation from the type — this is so the emitted
    // spec says it too, since help, docs and completions read that rather than the type.
    let flatten_checks = flatten_checks(cli);
    let subcommand_required = cli.fields.iter().any(|f| {
        matches!(
            f.kind,
            Kind::Subcommand {
                optional: false,
                ..
            }
        )
    });
    let before_help = option_expr(cli.before_help.as_ref());
    let before_long_help = option_expr(cli.before_long_help.as_ref());
    let after_help = option_expr(cli.after_help.as_ref());
    let after_long_help = option_expr(cli.after_long_help.as_ref());
    let examples = examples_table(&cli.examples);
    let headings = headings_table(&cli.headings);
    let root_key = key_ident("COMMAND", None);
    let keys = key_consts(&cli.fingerprint, flags.len(), args.len());
    let flag_tables = flags.iter().enumerate().map(|(i, f)| flag_table(i, f));
    let arg_tables = args.iter().enumerate().map(|(i, f)| arg_table(i, f));
    let flag_metas = flags
        .iter()
        .enumerate()
        .map(|(i, f)| flag_meta(cli, i, f, &cli.ident));
    let arg_metas = args
        .iter()
        .enumerate()
        .map(|(i, f)| arg_meta(cli, i, f, &cli.ident));
    let clause_field = cli.fields.iter().find_map(|field| {
        let Kind::Clause { ty, separator } = &field.kind else {
            return None;
        };
        Some((field, ty, separator))
    });
    let clause_table = clause_field
        .map(|(field, ty, separator)| {
            let name = proc_macro2::Literal::string(&field.name);
            let separator = separator.as_ref().map_or_else(
                || quote!(::core::option::Option::None),
                |separator| {
                    let separator = proc_macro2::Literal::byte_string(separator.as_bytes());
                    quote!(::core::option::Option::Some(#separator))
                },
            );
            quote!(::core::option::Option::Some(usage_argv::Clause {
                key: 0,
                name: #name,
                separator: #separator,
                flags: <#ty as usage_argv::spec::CommandArgs>::COMMAND.flags,
                args: <#ty as usage_argv::spec::CommandArgs>::COMMAND.args,
            }))
        })
        .unwrap_or_else(|| quote!(::core::option::Option::None));
    let clause_meta = clause_field
        .map(|(field, ty, separator)| {
            let name = proc_macro2::Literal::string(&field.name);
            let separator = option_str(separator.as_deref());
            quote!(::core::option::Option::Some(usage_argv::spec::ClauseMeta {
                name: #name,
                separator: #separator,
                help: ::core::option::Option::None,
                long_help: ::core::option::Option::None,
                flags: <#ty as usage_argv::spec::CommandArgs>::META.flags,
                args: <#ty as usage_argv::spec::CommandArgs>::META.args,
                canonical_selector: <#ty as usage_argv::spec::CommandArgs>::canonical_selector,
            }))
        })
        .unwrap_or_else(|| quote!(::core::option::Option::None));
    let implicit_clause_assertions = clause_field
        .filter(|(_, _, separator)| separator.is_none())
        .map(|(_, ty, _)| {
            quote! {
                const _: () = {
                    const INNER: &usage_argv::Command<'static> =
                        <#ty as usage_argv::spec::CommandArgs>::COMMAND;
                    assert!(
                        INNER.args.len() == 1,
                        "an implicit clause needs exactly one positional argument",
                    );
                    assert!(
                        INNER.args[0].required && !INNER.args[0].var,
                        "an implicit clause positional must be required and non-variadic",
                    );
                    assert!(
                        INNER.subcommands.is_empty(),
                        "an implicit clause cannot contain subcommands",
                    );
                    assert!(
                        INNER.args[0].sigil.is_none(),
                        "an implicit clause positional cannot use a sigil",
                    );
                };
            }
        });

    // Both the plain slices and, when a field is flattened, the joined arrays.
    let tables = tables(cli);
    let table_decls = &tables.decls;
    let meta_table_decls = &tables.meta_decls;
    let (group_meta_decl, group_meta_table_ref) = group_meta_table(cli);
    let flag_table_ref = &tables.flags;
    let arg_table_ref = &tables.args;
    let flag_meta_table_ref = &tables.flag_metas;
    let arg_meta_table_ref = &tables.arg_metas;
    let flatten_group_table_ref = &tables.flatten_groups;

    let name = &cli.name;
    let bin = option_str(cli.bin.as_deref());
    let version = match &cli.version {
        Some(tokens) => quote!(::core::option::Option::Some(#tokens)),
        None => quote!(::core::option::Option::None),
    };
    let author = option_expr(cli.author.as_ref());
    let license = option_expr(cli.license.as_ref());
    let repository = option_expr(cli.repository.as_ref());
    let source_code_link_template = option_expr(cli.source_code_link_template.as_ref());
    let about = cli
        .about_attr
        .as_ref()
        .map(|value| option_expr(Some(value)))
        .unwrap_or_else(|| option_str(cli.about.as_deref()));
    let long_about = cli
        .long_about_attr
        .as_ref()
        .map(|value| option_expr(Some(value)))
        .unwrap_or_else(|| option_str(cli.long_about.as_deref()));
    let deprecated = option_str(cli.deprecated.as_deref());
    let deprecated_warn_at = option_str(cli.deprecated_warn_at.as_deref());
    let deprecated_remove_at = option_str(cli.deprecated_remove_at.as_deref());
    let surface = option_str(cli.surface.as_deref());
    let available_if = &cli.available_if;

    // The same wiring a nested command uses: the root differs only in how it is
    // entered, so it does not get its own copy.
    let parts = subcommand_parts(cli);
    let sub_commands = parts
        .as_ref()
        .map(|p| p.commands.clone())
        .unwrap_or_default();
    let sub_default = parts
        .as_ref()
        .map(|p| p.default.clone())
        .unwrap_or_default();
    let sub_external = parts
        .as_ref()
        .map(|p| p.external.clone())
        .unwrap_or_default();
    let sub_metas = parts.as_ref().map(|p| p.metas.clone()).unwrap_or_default();
    let sub_build = parts.as_ref().map(|p| p.build.clone()).unwrap_or_default();
    let sub_default_view_build = parts
        .as_ref()
        .map(|p| p.default_view_build.clone())
        .unwrap_or_default();
    let partial = partial_struct(cli);
    let argument_lookup = argument_lookup_functions(cli);
    let deprecations = deprecations_fn(cli);
    let defaults = partial_defaults(cli);
    let merge = merge_fn(cli);
    // A root resolves settings when it binds one itself, or when it says so — which is how a CLI
    // whose bound flags all live in a flattened group asks for the entry points, since it cannot
    // see another struct's fields. A root that does neither gets the compile-time guard instead of
    // the layer, so a group's binding cannot go quietly uncollected.
    let resolves = cli.fields.iter().any(|f| f.setting.is_some()) || cli.settings;
    let config = crate::config::config_path();
    // A root that names its settings type gets a spec carrying the `config` block, appended
    // after the command tree: KDL nodes are read by name, so position is presentation. Written
    // as an append rather than as the whole body so that it composes with `spec_extra`, which
    // appends to the same string — a root can have both.
    let config_extra = match &cli.config {
        Some(ty) => quote! {
            __usage_kdl.push_str(&#config::spec_kdl_with(
                <#ty>::SETTINGS_PROPS,
                <#ty>::SETTINGS_SPEC,
            ));
        },
        None => TokenStream::new(),
    };
    // The argv collection every process entry shares: the full refs for parsing, the
    // view- or multicall-rewritten words for help routing, and the selected view.
    // Before the preamble, which interpolates the intercept.
    let (spec_endpoint, spec_endpoint_intercept) = spec_endpoint_fns(cli);
    let parse_preamble = quote! {
                    let __usage_all: ::std::vec::Vec<::std::ffi::OsString> =
                        ::std::env::args_os().collect();
                    let __usage_all_refs: ::std::vec::Vec<&::std::ffi::OsStr> =
                        __usage_all.iter().map(|a| a.as_os_str()).collect();
                    // In the shared preamble rather than in `parse` alone: the point of the
                    // endpoint is that *any* usage binary answers `__usage_spec__`, so a CLI
                    // that resolves settings has to answer it too.
                    #spec_endpoint_intercept
                    let __usage_raw: ::std::vec::Vec<::std::ffi::OsString> =
                        if let ::std::option::Option::Some((__usage_argv0, __usage_words)) =
                            __usage_all_refs.split_first()
                        {
                            if let ::std::option::Option::Some(__usage_view) =
                                usage_argv::spec::view_for_program(&SPEC, __usage_argv0)
                            {
                                if __usage_words.first().is_some_and(|word| {
                                    usage_argv::is_version_arg(SPEC.root.cmd, word)
                                })
                                {
                                    __usage_words
                                        .iter()
                                        .map(|word| (*word).to_os_string())
                                        .collect()
                                } else {
                                    __usage_view
                                        .root
                                        .split_ascii_whitespace()
                                        .map(::std::ffi::OsString::from)
                                        .chain(
                                            __usage_words
                                                .iter()
                                                .map(|word| (*word).to_os_string()),
                                        )
                                        .collect()
                                }
                            } else if SPEC.multicall {
                                let mut __usage_words: ::std::vec::Vec<::std::ffi::OsString> =
                                    __usage_words
                                        .iter()
                                        .map(|word| (*word).to_os_string())
                                        .collect();
                                if let ::std::option::Option::Some(__usage_word) =
                                    __usage_argv0.to_str().and_then(|s| {
                                        usage_argv::multicall_applet(s, SPEC.name, SPEC.bin)
                                    })
                                {
                                    __usage_words.insert(
                                        0,
                                        ::std::ffi::OsString::from(__usage_word),
                                    );
                                }
                                __usage_words
                            } else {
                                __usage_words
                                    .iter()
                                    .map(|word| (*word).to_os_string())
                                    .collect()
                            }
                        } else {
                            ::std::vec::Vec::new()
                        };
                    let __usage_argv: ::std::vec::Vec<&::std::ffi::OsStr> =
                        __usage_raw.iter().map(|a| a.as_os_str()).collect();
                    let __usage_selected_view = __usage_all
                        .first()
                        .and_then(|argv0| usage_argv::spec::view_for_program(&SPEC, argv0));
                    // This is the entry point that *is* the process — it already exits for a help
                    // request — so it answers a failure the way a command-line program does:
                    // the message on stderr, and a non-zero status. `parse_from` hands the error
                    // back instead, for a library embedding this that wants to decide.
    };

    let parts = settings(cli);
    // Only the layer calls it, so a root that has children and no settings of its own emits
    // neither: the guard below is what speaks for that case.
    let settings_given = parts.as_ref().filter(|_| resolves).map(|s| s.given.clone());
    let settings_bindings = parts
        .as_ref()
        .filter(|_| resolves)
        .map(|s| s.bindings.clone());
    let settings_layer = resolves.then(|| settings_layer(&config));
    let settings_guard = (!resolves).then(|| settings_guard(cli)).flatten();
    // The name an adopter uses, forwarding to the one inside the const block, which is where
    // the table that reads it lives.
    let settings_binding_forward = settings_bindings.as_ref().map(|_| {
        quote! {
            /// Every flag this CLI reads into a setting, and the setting it sets.
            ///
            /// What `usage_config::Registry::drift` compares against the flags the spec
            /// *declares*, so a documented flag nothing reads — hk has thirteen — fails a test
            /// rather than a user.
            pub const SETTINGS_BINDINGS: &'static [(&'static str, &'static str)] =
                SETTINGS_BINDINGS;
        }
    });
    // The second entry point, emitted only when something is bound: it returns what the parser saw
    // as well as the struct, which is the whole reason it exists.
    let settings_parse = settings_bindings.as_ref().map(|_| {
        let sub_build = sub_build.clone();
        let field_finals: Vec<_> = cli
            .fields
            .iter()
            .filter(|f| !matches!(f.kind, Kind::Subcommand { .. }))
            .map(|field| field_final(field, None))
            .collect();
        let built = validated_value(cli, &built_value(cli, &sub_build, &field_finals));
        quote! {
            /// Parse a command line, and the settings it gave values for.
            ///
            /// The layer is built before the struct because the two read the same partial and the
            /// struct consumes it — and because a value the struct refuses is one this never
            /// returns, the layer going with it.
            pub fn parse_from_with_settings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                Self::__usage_parse_from_with_settings(argv, ::std::option::Option::None)
            }

            /// [`Self::parse_from_with_settings`], collecting the deprecations it used.
            ///
            /// A settings adopter renders these through its own logging rather than to raw
            /// stderr, which is the whole reason the collecting form exists.
            pub fn parse_from_with_settings_and_warnings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
                warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                Self::__usage_parse_from_with_settings(
                    argv,
                    ::std::option::Option::Some(warnings),
                )
            }

            #[doc(hidden)]
            fn __usage_parse_from_with_settings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
                __usage_warnings: ::std::option::Option<
                    &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                >,
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                // The layer from what argv left, and only then the rest: `check` fills a field
                // from its `env` and marks it given, and a variable's value contributed here
                // would sit in the layer that outranks every other, named after a flag nobody
                // typed — and counted twice by a `union` setting whose CLI also has an
                // `EnvLayer`. The environment has a layer of its own to arrive in.
                #defaults
                read_argv_into(Self::command(), argv, &mut partial)?;
                let __usage_settings = settings_layer(&partial);
                check(&mut partial)?;
                if let ::std::option::Option::Some(__usage_out) = __usage_warnings {
                    Self::__usage_deprecations(&partial, __usage_out);
                }
                let __usage_built = #built;
                ::std::result::Result::Ok((__usage_built, __usage_settings))
            }
        }
    });
    let apply = apply_fn(cli);
    let post = post_binding(cli);
    let (completion, completion_intercept) = completion_fns(cli);
    let embedded_spec_request = cli.spec_endpoint.then(|| {
        quote! {
            if let ::std::option::Option::Some(__usage_answer) =
                Self::spec_request(&__usage_refs)
            {
                return usage_argv::embedded::Outcome::Exit(usage_argv::embedded::Exit {
                    text: __usage_answer,
                    stderr: false,
                    code: 0,
                });
            }
        }
    });
    let embedded_completion_request = cli.completion.then(|| {
        quote! {
            if let ::std::option::Option::Some(__usage_answer) = Self::completion_request(argv) {
                return usage_argv::embedded::Outcome::Exit(usage_argv::embedded::Exit {
                    text: __usage_answer,
                    stderr: false,
                    code: 0,
                });
            }
        }
    });
    let spec_extra = spec_extra_append(cli);
    // `field: local` rather than the shorthand, because the locals are prefixed:
    // a field called `text` or `parser` would otherwise collide with something the
    // generated code needs.
    // Collected rather than left lazy: it is used by both the inherent `build` and the trait
    // impl beside it, and an iterator cannot be walked twice.
    let field_finals: Vec<_> = cli
        .fields
        .iter()
        .filter(|f| !matches!(f.kind, Kind::Subcommand { .. }))
        .map(|field| field_final(field, None))
        .collect();
    let built = validated_value(cli, &built_value(cli, &sub_build, &field_finals));
    let built_for_view = if cli.views.is_empty() {
        built.clone()
    } else {
        let default_view_omitter = quote!(usage_argv::spec::DefaultViewOmitter);
        let view_field_finals: Vec<_> = cli
            .fields
            .iter()
            .filter(|f| !matches!(f.kind, Kind::Subcommand { .. }))
            .map(|field| field_final(field, Some(&default_view_omitter)))
            .collect();
        // A one-command view promotes the selected child directly. None of that child's
        // fields are omitted, so constructing it through the view-aware trait would impose
        // `Default` on every value type in every sibling command for no semantic reason.
        // Deeper views still need view-aware construction for the injected intermediate
        // commands whose own fields are absent from argv.
        let view_sub_build = if cli
            .views
            .iter()
            .all(|view| view.root.split_ascii_whitespace().count() == 1)
        {
            &sub_build
        } else {
            &sub_default_view_build
        };
        validated_value(cli, &built_value(cli, view_sub_build, &view_field_finals))
    };
    let update_clone_bound = cli
        .validate_with
        .as_ref()
        .map(|_| quote!(where Self: ::std::clone::Clone));
    let update_merge = if let Some(validate_with) = &cli.validate_with {
        quote! {
            let mut __usage_candidate = self.clone();
            merge(partial, &mut __usage_candidate)?;
            #validate_with(&__usage_candidate)
                .map_err(usage_argv::ValidationError::into_parse_error)?;
            *self = __usage_candidate;
            ::std::result::Result::Ok(())
        }
    } else {
        quote!(merge(partial, self))
    };

    let parse_into = cli.try_into.as_ref().map(|target| {
        quote! {
            /// Parse a command line and finalize the parser type into the application's domain type.
            pub fn parse_into_from<'v>(
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<#target, usage_argv::Error<'static, 'v>> {
                Self::parse_from(argv).and_then(Self::__usage_finalize)
            }

            /// [`Self::parse_into_from`], collecting the deprecations it used.
            pub fn parse_into_from_with_warnings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
                warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
            ) -> ::std::result::Result<#target, usage_argv::Error<'static, 'v>> {
                Self::parse_from_with_warnings(argv, warnings).and_then(Self::__usage_finalize)
            }

            /// Parse a full argv, including the program name, and finalize it.
            pub fn parse_into_from_argv<'v>(
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<#target, usage_argv::Error<'static, 'v>> {
                Self::parse_from_argv(argv).and_then(Self::__usage_finalize)
            }

            /// Parse using clap's argv convention and finalize it.
            pub fn try_parse_into_from<'v>(
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<#target, usage_argv::Error<'static, 'v>> {
                Self::try_parse_from(argv).and_then(Self::__usage_finalize)
            }

            #[doc(hidden)]
            fn __usage_finalize<'v>(
                parsed: Self,
            ) -> ::std::result::Result<#target, usage_argv::Error<'static, 'v>> {
                <#target as ::std::convert::TryFrom<Self>>::try_from(parsed)
                    .map_err(usage_argv::ValidationError::into_parse_error)
            }

        /// Parse the process's arguments and finalize them into the domain type.
        pub fn parse_into() -> #target {
            #completion_intercept
            #parse_preamble
            let mut __usage_warnings = ::std::vec::Vec::new();
            let __usage_result = Self::__usage_parse_from_argv(
                &__usage_all_refs,
                ::std::option::Option::Some(&mut __usage_warnings),
            ).and_then(Self::__usage_finalize);
            match __usage_result {
                ::std::result::Result::Ok(finalized) => {
                    if !__usage_warnings.is_empty() {
                        ::std::eprint!(
                            "{}",
                            usage_argv::render_warnings(&__usage_warnings),
                        );
                    }
                    finalized
                }
                ::std::result::Result::Err(error) => {
                    Self::__usage_exit_on_error(
                        error,
                        &__usage_all_refs,
                        &__usage_argv,
                        __usage_selected_view,
                    )
                }
            }
            }
        }
    });

    // The process entry with a settings layer beside it, for a CLI that binds settings and
    // resolves them at startup — the fleet's `main` shape. Same help, version, and error
    // behaviour as `parse`, through the same shared renderer.
    let settings_parse_entry = settings_bindings.as_ref().map(|_| {
        quote! {
            /// Parse a full argv, including the program name, and the settings it
            /// gave values for.
            ///
            /// The `parse_from_argv` counterpart of [`Self::parse_from_with_settings`]:
            /// argv0 is stripped, views and multicall applets are honoured, and the
            /// layer is built from what the parser saw.
            pub fn parse_from_argv_with_settings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                Self::__usage_parse_from_argv_with_settings(
                    argv,
                    ::std::option::Option::None,
                )
            }

            /// [`Self::parse_from_argv_with_settings`], collecting the deprecations it used.
            pub fn parse_from_argv_with_settings_and_warnings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
                warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                Self::__usage_parse_from_argv_with_settings(
                    argv,
                    ::std::option::Option::Some(warnings),
                )
            }

            #[doc(hidden)]
            fn __usage_parse_from_argv_with_settings<'v>(
                argv: &[&'v ::std::ffi::OsStr],
                __usage_warnings: ::std::option::Option<
                    &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                >,
            ) -> ::std::result::Result<
                (Self, #config::CliLayer),
                usage_argv::Error<'static, 'v>,
            > {
                let ::std::option::Option::Some((__usage_argv0, __usage_words)) =
                    argv.split_first()
                else {
                    return Self::__usage_parse_from_with_settings(&[], __usage_warnings);
                };
                if let ::std::option::Option::Some(__usage_view) =
                    usage_argv::spec::view_for_program(&SPEC, __usage_argv0)
                {
                    let mut __usage_rewritten = ::std::vec::Vec::with_capacity(
                        __usage_words.len()
                            + __usage_view.root.split_ascii_whitespace().count(),
                    );
                    __usage_rewritten.extend(
                        __usage_view.root
                            .split_ascii_whitespace()
                            .map(::std::ffi::OsStr::new),
                    );
                    __usage_rewritten.extend_from_slice(__usage_words);
                    #defaults
                    read_argv_into_view(
                        Self::command(),
                        &__usage_rewritten,
                        &mut partial,
                        ::std::option::Option::Some(__usage_view),
                    )?;
                    // Before `check`, for the same reason `parse_from_with_settings` is:
                    // the layer holds what argv gave, not what the environment filled.
                    let __usage_settings = settings_layer(&partial);
                    check_with_view(
                        &mut partial,
                        ::std::option::Option::Some(__usage_view),
                    )?;
                    if let ::std::option::Option::Some(__usage_out) = __usage_warnings {
                        Self::__usage_deprecations(&partial, __usage_out);
                    }
                    return ::std::result::Result::Ok((#built_for_view, __usage_settings));
                }
                if SPEC.multicall {
                    if let ::std::option::Option::Some(__usage_word) =
                        __usage_argv0.to_str().and_then(|s| {
                            usage_argv::multicall_applet(s, SPEC.name, SPEC.bin)
                        })
                    {
                        let mut __usage_rewritten =
                            ::std::vec::Vec::with_capacity(argv.len());
                        __usage_rewritten.push(::std::ffi::OsStr::new(__usage_word));
                        __usage_rewritten.extend_from_slice(__usage_words);
                        return Self::__usage_parse_from_with_settings(
                            &__usage_rewritten,
                            __usage_warnings,
                        );
                    }
                }
                Self::__usage_parse_from_with_settings(__usage_words, __usage_warnings)
            }

            /// Parse the process's own arguments, and the settings they gave values for.
            ///
            /// [`Self::parse`] with the layer beside the struct: it prints a help page or
            /// a version and leaves, and renders a failure to stderr with exit 2.
            pub fn parse_with_settings() -> (Self, #config::CliLayer) {
                #completion_intercept
                #parse_preamble
                // The same as `parse`: this is an entry point that *is* the process, so it is
                // one of the two that may write to stderr, and a failure prints nothing about
                // deprecations because what the user typed did not run.
                let mut __usage_warnings = ::std::vec::Vec::new();
                match Self::__usage_parse_from_argv_with_settings(
                    &__usage_all_refs,
                    ::std::option::Option::Some(&mut __usage_warnings),
                ) {
                    ::std::result::Result::Ok(__usage_parsed) => {
                        if !__usage_warnings.is_empty() {
                            ::std::eprint!(
                                "{}",
                                usage_argv::render_warnings(&__usage_warnings),
                            );
                        }
                        __usage_parsed
                    }
                    ::std::result::Result::Err(e) => Self::__usage_exit_on_error(
                        e,
                        &__usage_all_refs,
                        &__usage_argv,
                        __usage_selected_view,
                    ),
                }
            }
        }
    });

    let min_usage_version = option_str(cli.min_usage_version.as_deref());
    let views: Vec<_> = cli
        .views
        .iter()
        .map(|view| {
            let id = &view.id;
            let name = &view.name;
            let bin = &view.bin;
            let root = &view.root;
            let all_globals = view.all_globals;
            let globals = &view.globals;
            quote! {
                usage_argv::spec::ViewMeta {
                    id: #id,
                    name: #name,
                    bin: #bin,
                    root: #root,
                    all_globals: #all_globals,
                    globals: &[#(#globals),*],
                }
            }
        })
        .collect();
    let has_version = cli.version.is_some() || cli.long_version.is_some();
    let runtime_version = cli
        .runtime_version
        .as_ref()
        .or(cli.version.as_ref())
        .or(cli.runtime_long_version.as_ref())
        .or(cli.long_version.as_ref())
        .cloned()
        .unwrap_or_else(|| quote!(""));
    let long_version = cli
        .long_version
        .as_ref()
        .map(|tokens| quote!(::core::option::Option::Some(#tokens)))
        .unwrap_or_else(|| quote!(::core::option::Option::None));
    let runtime_long_version = cli
        .runtime_long_version
        .as_ref()
        .or(cli.long_version.as_ref())
        .cloned();
    let output_long_version = runtime_long_version
        .clone()
        .unwrap_or_else(|| runtime_version.clone());
    let runtime_name_decl = cli.runtime_name.as_ref().map(|runtime_name| {
        quote! {
            let __usage_runtime_name: &'static str = #runtime_name;
        }
    });
    let runtime_bin_decl = cli.runtime_bin.as_ref().map(|runtime_bin| {
        quote! {
            let __usage_runtime_bin: &'static str = #runtime_bin;
        }
    });
    let runtime_version_decl = cli.runtime_version.as_ref().map(|_| {
        quote! {
            let __usage_runtime_version =
                ::std::string::ToString::to_string(&(#runtime_version));
        }
    });
    let runtime_long_version_decl = runtime_long_version.as_ref().map(|value| {
        quote! {
            let __usage_runtime_long_version =
                ::std::string::ToString::to_string(&(#value));
        }
    });
    let effective_name = if cli.runtime_name.is_some() {
        quote!(__usage_runtime_name)
    } else {
        quote!(Self::spec().name)
    };
    let effective_bin = if cli.runtime_bin.is_some() {
        quote!(::std::option::Option::Some(__usage_runtime_bin))
    } else {
        quote!(Self::spec().bin)
    };
    let effective_version = if cli.runtime_version.is_some() {
        quote!(::std::option::Option::Some(
            __usage_runtime_version.as_str()
        ))
    } else {
        quote!(Self::spec().version)
    };
    let has_runtime_identity = cli.runtime_name.is_some() || cli.runtime_bin.is_some();
    let effective_long_version = if runtime_long_version.is_some() {
        quote!(::std::option::Option::Some(
            __usage_runtime_long_version.as_str()
        ))
    } else {
        quote!(Self::spec().long_version)
    };
    let effective_spec = if has_runtime_identity
        || cli.runtime_version.is_some()
        || runtime_long_version.is_some()
    {
        quote! {
            // Portable literals remain in `SPEC`; runtime expressions are evaluated only on
            // cold output paths. Successful argv parsing still reads the static tables directly.
            #runtime_name_decl
            #runtime_bin_decl
            #runtime_version_decl
            #runtime_long_version_decl
            let __usage_runtime_spec = usage_argv::spec::Spec {
                name: #effective_name,
                bin: #effective_bin,
                version: #effective_version,
                long_version: #effective_long_version,
                ..*Self::spec()
            };
            let __usage_spec = &__usage_runtime_spec;
        }
    } else {
        quote! {
            let __usage_spec = Self::spec();
        }
    };

    // The embedded counterpart to `parse_into_from`. It cannot live in the `parse_into` block
    // above, which is built before the runtime identity `effective_spec` depends on.
    let embedded_outcome_into = cli.try_into.as_ref().map(|target| {
        quote! {
            /// [`Self::embedded_outcome`], finalized into the application's domain type.
            ///
            /// Spec and completion requests, help, versions and failures behave exactly as
            /// they do there, and a `TryFrom` finalization error becomes the same failure
            /// response a parse error does.
            pub fn embedded_outcome_into(
                argv: &[::std::ffi::OsString],
            ) -> usage_argv::embedded::Outcome<#target> {
                let __usage_refs: ::std::vec::Vec<&::std::ffi::OsStr> =
                    argv.iter().map(|arg| arg.as_os_str()).collect();
                #embedded_spec_request
                #embedded_completion_request
                #effective_spec
                usage_argv::embedded::outcome(
                    __usage_spec,
                    Self::command(),
                    &__usage_refs,
                    Self::parse_into_from,
                )
            }
        }
    });

    // One renderer for every help request. Which page a request becomes — and whether it is the
    // route the words took or a fallback by address — is decided once, in usage-argv, rather
    // than three times here in code nobody reads until it is wrong. It is also what lets a test
    // harness render the page this program would have printed rather than one of its own.
    let page_of = |style: TokenStream| {
        quote! {
            let __usage_page = match __usage_selected_view {
                ::std::option::Option::Some(view) => usage_argv::help::page_view(
                    __usage_spec,
                    Self::command(),
                    &__usage_all_refs,
                    cmd,
                    view,
                    __usage_want,
                    #style,
                ),
                ::std::option::Option::None => usage_argv::help::page(
                    __usage_spec,
                    Self::command(),
                    &__usage_argv,
                    cmd,
                    __usage_want,
                    #style,
                ),
            };
        }
    };
    let render_page = page_of(quote!(usage_argv::help::Style::auto()));
    let render_page_stderr = page_of(quote!(usage_argv::help::Style::auto_stderr()));
    let runtime_program = cli
        .runtime_bin
        .as_ref()
        .or(cli.runtime_name.as_ref())
        .cloned();
    let runtime_program_for_version = runtime_program
        .as_ref()
        .map(|program| {
            quote! {
                let __usage_bin: &'static str = #program;
            }
        })
        .unwrap_or_else(|| {
            quote! {
                let __usage_bin = Self::spec().bin.unwrap_or(Self::spec().name);
            }
        });
    let runtime_name_view = cli.runtime_name.as_ref().map(|name| quote!(.name(#name)));
    let runtime_bin_view = cli.runtime_bin.as_ref().map(|bin| quote!(.bin(#bin)));
    let runtime_app = has_runtime_identity.then(|| {
        quote! {
            /// This CLI's cold-path view with its computed process identity applied.
            ///
            /// Runtime identity is required to be `&'static str`, so this borrows the
            /// static metadata and allocates nothing.
            pub fn runtime_app() -> usage_argv::spec::SpecView<'static> {
                Self::app() #runtime_name_view #runtime_bin_view
            }
        }
    });
    quote! {
        #[doc(hidden)]
        #[allow(
            non_upper_case_globals,
            non_snake_case,
            unused_imports,
            // Fires when a metadata struct happens to be fully specified. `..EMPTY`
            // is kept on purpose: it is what lets usage-argv gain a metadata field
            // without breaking every crate that derives.
            clippy::needless_update
        )]
        const _: () = {
            use #runtime as usage_argv;
            #validation_import

            #flatten_checks
            #keys
            #(#flag_tables)*
            #(#arg_tables)*
            #table_decls

            pub static ROOT: usage_argv::Command = usage_argv::Command {
                // Only where a version was declared, which is when clap adds the flag: a
                // `--version` that answers with nothing is worse than one that is not there.
                version: #has_version,
                unknown_flags: #unknown_flags,
                arg_required_else_help: #arg_required_else_help,
                subcommand_negates_reqs: #subcommand_negates_reqs,
                args_conflicts_with_subcommands: #args_conflicts_with_subcommands,
                subcommand_precedence_over_arg: #subcommand_precedence_over_arg,
                allow_missing_positional: #allow_missing_positional,
                disable_help_flag: #disable_help_flag,
                disable_help_subcommand: #disable_help_subcommand,
                disable_version_flag: #disable_version_flag,
                dont_delimit_trailing_values: #dont_delimit_trailing_values,
                name: #name,
                key: #root_key,
                flags: #flag_table_ref,
                args: #arg_table_ref,
                clause: #clause_table,
                #sub_commands
                #sub_default
                #sub_external
                ..usage_argv::Command::EMPTY
            };

            // The model can see that the root has a subcommand field, but the enum is
            // expanded separately. Its COMMANDS table is the point where an
            // external-only enum becomes distinguishable from one with named applets.
            const _: () = assert!(
                !#multicall || !ROOT.subcommands.is_empty(),
                "`multicall` needs at least one named subcommand to select",
            );
            #implicit_clause_assertions
            const _: () = usage_argv::assert_clause_flag_spellings(&ROOT);

            #(#flag_metas)*
            #(#arg_metas)*
            #meta_table_decls

            #group_meta_decl

            #(#output_schema_decls)*

            pub static ROOT_META: usage_argv::spec::CommandMeta = usage_argv::spec::CommandMeta {
                cmd: &ROOT,
                outputs: #outputs,
                select: #select,
                exit_codes: #exit_codes,
                about: #about,
                long_about: #long_about,
                deprecated: #deprecated,
                deprecated_warn_at: #deprecated_warn_at,
                deprecated_remove_at: #deprecated_remove_at,
                surface: #surface,
                available_if: &[#(#available_if),*],
                restart_token: #restart_token,
                subcommand_required: #subcommand_required,
                subcommand_help_heading: #subcommand_help_heading,
                subcommand_value_name: #subcommand_value_name,
                next_line_help: #next_line_help,
                flatten_help: #flatten_help,
                term_width: #term_width,
                max_term_width: #max_term_width,
                args_override_self: #args_override_self,
                mount: #mount,
                before_help: #before_help,
                before_long_help: #before_long_help,
                after_help: #after_help,
                after_long_help: #after_long_help,
                examples: #examples,
                headings: #headings,
                flags: #flag_meta_table_ref,
                args: #arg_meta_table_ref,
                clause: #clause_meta,
                groups: #group_meta_table_ref,
                flatten_groups: #flatten_group_table_ref,
                #sub_metas
                ..usage_argv::spec::CommandMeta::EMPTY
            };

            // Values arrive as the bytes that were on the command line. This version
            // holds them as `String`, and converts lossily, which is what mise
            // already does with its own argv. Rejecting a non-UTF-8 value needs an
            // error type for value conversion, and that arrives with typed fields.
            pub fn __usage_text(value: &[u8]) -> ::std::vec::Vec<u8> {
                value.to_vec()
            }

            pub fn __usage_value_text(
                value: ::std::option::Option<&[u8]>,
            ) -> ::std::vec::Vec<u8> {
                value.map(__usage_text).unwrap_or_default()
            }

            #partial
            #apply
            #argument_lookup
            #deprecations

            /// Everything decided after the last token.
            ///
            /// In the module rather than beside the parse, so every reference it makes
            /// to the user's own types sits at one consistent scope — the root and a
            /// nested command generate the same code here.
            /// `__usage_standing` is what an update already had: `None` for an ordinary
            /// parse, which folds every question about it away. One body rather than an
            /// update-only copy, because this is the largest function a CLI generates and
            /// most CLIs never call the entry point that passes a value here.
            fn check_with_view_standing<'t, 'v>(
                partial: &mut Partial,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
                __usage_standing: ::std::option::Option<&#ident>,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                partial.__usage_view = __usage_view;
                // Read unconditionally: a command that declares nothing to check would
                // otherwise leave the parameter unused in the user's crate, where
                // nobody can silence it.
                let _ = (&partial, __usage_standing.is_some());
                let args_override_self = #args_override_self;
                #post
                ::std::result::Result::Ok(())
            }

            fn check_with_view<'t, 'v>(
                partial: &mut Partial,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_view_standing(partial, __usage_view, ::std::option::Option::None)
            }

            pub fn check<'t, 'v>(
                partial: &mut Partial,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_view(partial, ::std::option::Option::None)
            }

            /// `check`, against the union of this command line and what the caller had.
            pub fn check_update<'t, 'v>(
                partial: &mut Partial,
                __usage_standing: &#ident,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_view_standing(
                    partial,
                    ::std::option::Option::None,
                    ::std::option::Option::Some(__usage_standing),
                )
            }

            #merge

            /// Every token read, and nothing else decided.
            ///
            /// The partial as *argv* left it: before a declared default fills a field, before the
            /// environment does, before anything is checked. In the module because two entry
            /// points want it, and one of them wants exactly this much — a settings layer is
            /// what the command line contributed, and `check` fills fields from the environment
            /// and marks them given, which would hand a variable's value to the layer that
            /// outranks every other and name it after a flag nobody typed.
            pub fn read_argv<'v>(
                command: &'static usage_argv::Command<'static>,
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<Partial, usage_argv::Error<'static, 'v>> {
                #defaults
                read_argv_into(command, argv, &mut partial)?;
                ::std::result::Result::Ok(partial)
            }

            /// `read_argv`, filling a partial the caller already owns.
            ///
            /// The entry points call this rather than `read_argv`, because a `Partial` is
            /// the whole CLI's worth of accumulator — every command's fields, inlined —
            /// and returning one by value is a memcpy of all of it. At mise's scale that is
            /// 11KB a move, and returning it up the chain from here to `parse_from` made
            /// four: 87% of a parse was spent copying a struct of which all but one
            /// command's worth goes untouched. Threading `&mut` puts the partial in the
            /// frame that will consume it, leaving only the one copy that builds it.
            pub fn read_argv_into<'v>(
                command: &'static usage_argv::Command<'static>,
                argv: &[&'v ::std::ffi::OsStr],
                partial: &mut Partial,
            ) -> ::std::result::Result<(), usage_argv::Error<'static, 'v>> {
                read_argv_into_view(command, argv, partial, ::std::option::Option::None)
            }

            pub fn read_argv_into_view<'v>(
                command: &'static usage_argv::Command<'static>,
                argv: &[&'v ::std::ffi::OsStr],
                partial: &mut Partial,
                view: ::std::option::Option<&'static usage_argv::spec::ViewMeta<'static>>,
            ) -> ::std::result::Result<(), usage_argv::Error<'static, 'v>> {
                let mut __usage_parser = usage_argv::Parser::new(command, argv);
                if let ::std::option::Option::Some(view) = view {
                    __usage_parser = __usage_parser.with_view(view);
                }
                while let ::std::option::Option::Some(__usage_event) =
                    __usage_parser.next_event()
                {
                    let __usage_event = __usage_event?;
                    // Asked *before* the event is applied, and answered with the command in
                    // scope: `mise config --help` is a question about `config`, and the parser
                    // is what knows how deep the words reached.
                    if let usage_argv::Event::Flag { flag, .. } = &__usage_event {
                        if usage_argv::is_help_flag(flag) {
                            if flag.action == usage_argv::ArgAction::HelpAll {
                                return ::std::result::Result::Err(usage_argv::Error::HelpAll {
                                    cmd: __usage_parser.command(),
                                });
                            }
                            let long = match flag.action {
                                usage_argv::ArgAction::HelpShort => false,
                                usage_argv::ArgAction::HelpLong => true,
                                usage_argv::ArgAction::Help => !flag.longs.is_empty(),
                                _ => false,
                            };
                            return ::std::result::Result::Err(usage_argv::Error::Help {
                                cmd: __usage_parser.command(),
                                long,
                            });
                        }
                        // Same shape, and for the same reason: a question rather than a
                        // failure, answered by whoever knows the version string.
                        if usage_argv::is_version_flag(flag) {
                            return ::std::result::Result::Err(
                                usage_argv::Error::Version {
                                    long: !flag.longs.is_empty(),
                                },
                            );
                        }
                    }
                    // `apply` handles this command's own fields and routes anything
                    // else into its subcommands, which is why a nested command needs
                    // nothing extra here.
                    apply(partial, &__usage_event);
                }

                if __usage_parser.command().arg_required_else_help
                    && __usage_parser.command_start() == argv.len()
                {
                    return ::std::result::Result::Err(usage_argv::Error::MissingArgsHelp {
                        cmd: __usage_parser.command(),
                    });
                }

                ::std::result::Result::Ok(())
            }

            /// Every token read, and everything decided after the last one.
            ///
            /// What a caller that only wants the struct wants: a partial nothing more will be
            /// added to. A struct cannot answer what the *parser* saw — a `bool` field is `false`
            /// whether the flag was absent or negated — so the entry point that wants that reads
            /// the two halves apart instead.
            pub fn read<'v>(
                command: &'static usage_argv::Command<'static>,
                argv: &[&'v ::std::ffi::OsStr],
            ) -> ::std::result::Result<Partial, usage_argv::Error<'static, 'v>> {
                #defaults
                read_into(command, argv, &mut partial)?;
                ::std::result::Result::Ok(partial)
            }

            /// `read`, filling a partial the caller already owns. See `read_argv_into`.
            pub fn read_into<'v>(
                command: &'static usage_argv::Command<'static>,
                argv: &[&'v ::std::ffi::OsStr],
                partial: &mut Partial,
            ) -> ::std::result::Result<(), usage_argv::Error<'static, 'v>> {
                read_argv_into(command, argv, partial)?;
                check(partial)?;
                ::std::result::Result::Ok(())
            }

            #settings_given
            #settings_bindings
            #settings_layer
            #settings_guard

            pub static SPEC: usage_argv::spec::Spec = usage_argv::spec::Spec {
                name: #name,
                bin: #bin,
                version: #version,
                long_version: #long_version,
                author: #author,
                license: #license,
                repository: #repository,
                source_code_link_template: #source_code_link_template,
                min_usage_version: #min_usage_version,
                about: #about,
                long_about: #long_about,
                usage: #usage,
                help_template: #help_template,
                default_subcommand: #default_subcommand,
                multicall: #multicall,
                views: &[#(#views),*],
                root: &ROOT_META,
            };

            impl #ident {
                /// The parse tables for this CLI.
                ///
                /// `static`, so reaching them costs nothing: there is no command tree
                /// to build before a parse can start.
                pub fn command() -> &'static usage_argv::Command<'static> {
                    &ROOT
                }

                /// This CLI's spec, for emitting, documenting, or completing.
                pub fn spec() -> &'static usage_argv::spec::Spec<'static> {
                    &SPEC
                }

                /// A borrowed cold-path view for runtime identity and sparse metadata overlays.
                ///
                /// Parsing continues to read [`Self::command`] directly; constructing this
                /// copies no command tree and performs no work on an ordinary invocation.
                pub fn app() -> usage_argv::spec::SpecView<'static> {
                    Self::spec().view()
                }

                #runtime_app

                /// Render a help page using this CLI's process identity.
                ///
                /// [`Self::spec`] keeps the portable `name_spec` / `bin_spec` literals.
                /// `parse()` already evaluates computed `name` / `bin` when it prints help;
                /// this is the same overlay for a `parse_from` caller that handles
                /// [`usage_argv::Error::Help`] itself.
                pub fn render_help(
                    cmd: &usage_argv::Command<'_>,
                    long: bool,
                ) -> ::std::option::Option<::std::string::String> {
                    #effective_spec
                    usage_argv::help::render(__usage_spec, cmd, long)
                }

                /// Render a parse failure using this CLI's process identity.
                ///
                /// The counterpart of [`Self::render_help`] for every error that is not a
                /// help or version request. `parse()` uses the same overlay on stderr.
                pub fn render_failure<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    error: &usage_argv::Error<'static, 'v>,
                ) -> ::std::string::String {
                    #effective_spec
                    usage_argv::render_failure(__usage_spec, argv, error)
                }

                /// This CLI's spec as KDL, which is what `usage g markdown|manpage`
                /// and the completion generators read.
                pub fn to_kdl() -> ::std::string::String {
                    #[allow(unused_mut)]
                    let mut __usage_kdl = SPEC.to_kdl();
                    #config_extra
                    #spec_extra
                    __usage_kdl
                }

                #spec_endpoint

                /// Answer the complete usage control protocol without printing or exiting.
                ///
                /// Input excludes the program name, like [`Self::parse_from`]. Spec and
                /// completion requests become successful stdout responses; ordinary argv is
                /// parsed, with help, version, and failures represented by the same outcome.
                pub fn embedded_outcome(
                    argv: &[::std::ffi::OsString],
                ) -> usage_argv::embedded::Outcome<Self> {
                    let __usage_refs: ::std::vec::Vec<&::std::ffi::OsStr> =
                        argv.iter().map(|arg| arg.as_os_str()).collect();
                    #embedded_spec_request
                    #embedded_completion_request
                    #effective_spec
                    usage_argv::embedded::outcome(
                        __usage_spec,
                        Self::command(),
                        &__usage_refs,
                        Self::parse_from,
                    )
                }

                #embedded_outcome_into

                #settings_binding_forward
                #settings_parse
                #parse_into

                /// Parse a command line, excluding the program name.
                pub fn parse_from<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_parse_from(argv, ::std::option::Option::None)
                }

                /// Parse a command line, and collect what it used that is deprecated.
                ///
                /// Reported rather than printed: a library cannot decide where this program's
                /// output goes, and a CLI that queues its diagnostics until its logging is up
                /// needs them as values rather than as lines on stderr. [`Self::parse`], which
                /// *is* the process, renders them itself.
                ///
                /// A warning whose `deprecated_warn_at` this CLI's version has not reached is
                /// not collected — that is what declaring one means.
                pub fn parse_from_with_warnings<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_parse_from(argv, ::std::option::Option::Some(warnings))
                }

                /// The two above. Collecting is `Option` rather than always-on so a caller that
                /// did not ask for warnings does not walk the tree looking for them.
                #[doc(hidden)]
                fn __usage_parse_from<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    __usage_warnings: ::std::option::Option<
                        &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                    >,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    // The partial is built here and filled through `&mut`, rather than
                    // returned up the chain: see `read_argv_into`.
                    #defaults
                    read_into(Self::command(), argv, &mut partial)?;
                    if let ::std::option::Option::Some(__usage_out) = __usage_warnings {
                        Self::__usage_deprecations(&partial, __usage_out);
                    }
                    ::std::result::Result::Ok(#built)
                }

                /// Everything this invocation used that its declaration says not to use, gated by
                /// the version the CLI is actually running as.
                ///
                /// The gate lives here rather than where the metadata is read because this is the
                /// only place that knows the answer: a nested command's tables say nothing about
                /// the root's version, and a computed `runtime_version` settles only at run time.
                #[doc(hidden)]
                fn __usage_deprecations(
                    partial: &Partial,
                    out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) {
                    let mut __usage_found = ::std::vec::Vec::new();
                    deprecations(partial, &mut __usage_found);
                    // An empty `Vec` has not allocated, and a CLI with nothing deprecated never
                    // reaches the version comparison at all.
                    if !__usage_found.is_empty() {
                        #effective_spec
                        usage_argv::warn::retain_reached(
                            &mut __usage_found,
                            __usage_spec.version,
                        );
                        out.append(&mut __usage_found);
                    }
                }

                /// Parse a full argv, including the program name.
                ///
                /// This is the test- and embedding-friendly counterpart to
                /// [`Self::parse`]: it strips argv0 for an ordinary CLI and
                /// applies the same basename-based applet selection for a
                /// multicall CLI, while returning errors instead of exiting.
                pub fn parse_from_argv<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_parse_from_argv(argv, ::std::option::Option::None)
                }

                /// [`Self::parse_from_argv`], collecting the deprecations it used.
                pub fn parse_from_argv_with_warnings<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_parse_from_argv(argv, ::std::option::Option::Some(warnings))
                }

                #[doc(hidden)]
                fn __usage_parse_from_argv<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    __usage_warnings: ::std::option::Option<
                        &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                    >,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    let ::std::option::Option::Some((__usage_argv0, __usage_words)) =
                        argv.split_first()
                    else {
                        return Self::__usage_parse_from(&[], __usage_warnings);
                    };
                    if let ::std::option::Option::Some(__usage_view) =
                        usage_argv::spec::view_for_program(&SPEC, __usage_argv0)
                    {
                        let mut __usage_rewritten = ::std::vec::Vec::with_capacity(
                            __usage_words.len()
                                + __usage_view.root.split_ascii_whitespace().count(),
                        );
                        __usage_rewritten.extend(
                            __usage_view.root
                                .split_ascii_whitespace()
                                .map(::std::ffi::OsStr::new),
                        );
                        __usage_rewritten.extend_from_slice(__usage_words);
                        #defaults
                        read_argv_into_view(
                            Self::command(),
                            &__usage_rewritten,
                            &mut partial,
                            ::std::option::Option::Some(__usage_view),
                        )?;
                        check_with_view(
                            &mut partial,
                            ::std::option::Option::Some(__usage_view),
                        )?;
                        if let ::std::option::Option::Some(__usage_out) = __usage_warnings {
                            Self::__usage_deprecations(&partial, __usage_out);
                        }
                        return ::std::result::Result::Ok(#built_for_view);
                    }
                    if SPEC.multicall {
                        if let ::std::option::Option::Some(__usage_word) =
                            __usage_argv0.to_str().and_then(|s| {
                                usage_argv::multicall_applet(s, SPEC.name, SPEC.bin)
                            })
                        {
                            let mut __usage_rewritten =
                                ::std::vec::Vec::with_capacity(argv.len());
                            __usage_rewritten.push(::std::ffi::OsStr::new(__usage_word));
                            __usage_rewritten.extend_from_slice(__usage_words);
                            return Self::__usage_parse_from(
                                &__usage_rewritten,
                                __usage_warnings,
                            );
                        }
                    }
                    Self::__usage_parse_from(__usage_words, __usage_warnings)
                }

                /// Merge a command line, excluding the program name, into this value.
                ///
                /// The counterpart of [`Self::parse_from`] for a CLI parsed more than once:
                /// a REPL's standing options, a daemon reconfigured while it runs. The rules
                /// are stated rather than inherited, because a parse cannot be run backwards
                /// through `FromStr` to seed itself from a value — what the caller already
                /// has is read from the struct instead, by the checks that need to know a
                /// field is filled.
                ///
                /// Relationships see what is already there: `required`, `requires_if`,
                /// `conflicts` and the rest treat a field that already holds a value as
                /// present, so this validates the union of both inputs rather than this argv
                /// alone. Environment variables and declared defaults fill only fields still
                /// empty, so an update never clobbers a value the caller set. A collection
                /// this command line mentions is replaced whole; one it says nothing about is
                /// left alone. A subcommand word naming a different variant replaces it,
                /// discarding the old variant's fields, since selecting a command is a
                /// routing decision rather than a value to merge.
                ///
                /// `self` is left untouched when this returns an error: nothing is merged
                /// until every check has passed.
                ///
                /// Two things a standing value cannot answer, because the bytes it was parsed
                /// from are gone: a check about what a value *is* — a choice list, a
                /// `validate` expression — is skipped for a field this argv did not supply,
                /// and a `requires_if` comparing against a particular value does not match
                /// one that merely stands.
                pub fn try_update_from<'v>(
                    &mut self,
                    argv: &[&'v ::std::ffi::OsStr],
                ) -> ::std::result::Result<(), usage_argv::Error<'static, 'v>>
                #update_clone_bound
                {
                    // A fresh partial, never seeded from `self`: `FromStr` has no inverse, so
                    // there is no way back from a typed field to the word that made it.
                    #defaults
                    read_argv_into(Self::command(), argv, &mut partial)?;
                    check_update(&mut partial, self)?;
                    #update_merge
                }

                /// Merge a full argv, including the program name, into this value.
                ///
                /// The [`Self::parse_from_argv`] counterpart of [`Self::try_update_from`]:
                /// argv0 is stripped, a multicall applet name selects its subcommand, and a
                /// view's program name is rewritten to the command it promotes. A view
                /// projects a struct that omits the root fields it does not carry; an update
                /// has no such struct to project into, so the words are rewritten and the
                /// omitted fields are simply ones this command line said nothing about.
                pub fn try_update_from_argv<'v>(
                    &mut self,
                    argv: &[&'v ::std::ffi::OsStr],
                ) -> ::std::result::Result<(), usage_argv::Error<'static, 'v>>
                #update_clone_bound
                {
                    let ::std::option::Option::Some((__usage_argv0, __usage_words)) =
                        argv.split_first()
                    else {
                        return self.try_update_from(&[]);
                    };
                    if let ::std::option::Option::Some(__usage_view) =
                        usage_argv::spec::view_for_program(&SPEC, __usage_argv0)
                    {
                        let mut __usage_rewritten = ::std::vec::Vec::with_capacity(
                            __usage_words.len()
                                + __usage_view.root.split_ascii_whitespace().count(),
                        );
                        __usage_rewritten.extend(
                            __usage_view.root
                                .split_ascii_whitespace()
                                .map(::std::ffi::OsStr::new),
                        );
                        __usage_rewritten.extend_from_slice(__usage_words);
                        return self.try_update_from(&__usage_rewritten);
                    }
                    if SPEC.multicall {
                        if let ::std::option::Option::Some(__usage_word) =
                            __usage_argv0.to_str().and_then(|s| {
                                usage_argv::multicall_applet(s, SPEC.name, SPEC.bin)
                            })
                        {
                            let mut __usage_rewritten =
                                ::std::vec::Vec::with_capacity(argv.len());
                            __usage_rewritten.push(::std::ffi::OsStr::new(__usage_word));
                            __usage_rewritten.extend_from_slice(__usage_words);
                            return self.try_update_from(&__usage_rewritten);
                        }
                    }
                    self.try_update_from(__usage_words)
                }

                /// [`Self::try_update_from`], answering a failure the way [`Self::parse`]
                /// does: help or a version on stdout, a message on stderr, and exit.
                pub fn update_from<'v>(&mut self, argv: &[&'v ::std::ffi::OsStr])
                #update_clone_bound
                {
                    if let ::std::result::Result::Err(e) = self.try_update_from(argv) {
                        Self::__usage_exit_on_error(
                            e,
                            argv,
                            argv,
                            ::std::option::Option::None,
                        );
                    }
                }

                /// [`Self::try_update_from_argv`], exiting on failure as [`Self::parse`] does.
                pub fn update_from_argv<'v>(&mut self, argv: &[&'v ::std::ffi::OsStr])
                #update_clone_bound
                {
                    if let ::std::result::Result::Err(e) = self.try_update_from_argv(argv) {
                        let __usage_words =
                            argv.split_first().map_or(argv, |(_, rest)| rest);
                        Self::__usage_exit_on_error(
                            e,
                            argv,
                            __usage_words,
                            ::std::option::Option::None,
                        );
                    }
                }

                /// Parse using clap's `try_parse_from` argv contract.
                ///
                /// Input includes argv0 by default. `#[usage(no_binary_name)]`
                /// opts into treating every supplied word as an argument.
                pub fn try_parse_from<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_try_parse_from(argv, ::std::option::Option::None)
                }

                /// [`Self::try_parse_from`], collecting the deprecations it used.
                pub fn try_parse_from_with_warnings<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    warnings: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    Self::__usage_try_parse_from(argv, ::std::option::Option::Some(warnings))
                }

                #[doc(hidden)]
                fn __usage_try_parse_from<'v>(
                    argv: &[&'v ::std::ffi::OsStr],
                    __usage_warnings: ::std::option::Option<
                        &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                    >,
                ) -> ::std::result::Result<Self, usage_argv::Error<'static, 'v>> {
                    if #no_binary_name {
                        Self::__usage_parse_from(argv, __usage_warnings)
                    } else {
                        Self::__usage_parse_from_argv(argv, __usage_warnings)
                    }
                }

                /// Parse the process's own arguments.
                #completion

                pub fn parse() -> Self {
                    #completion_intercept
                    #parse_preamble
                    // Collected here rather than printed where they are found: `parse` is the
                    // entry point that *is* the process, so it is the one that may write to
                    // stderr. A failure prints nothing about deprecations — the error is what
                    // the user needs, and what they typed did not run.
                    let mut __usage_warnings = ::std::vec::Vec::new();
                    match Self::__usage_parse_from_argv(
                        &__usage_all_refs,
                        ::std::option::Option::Some(&mut __usage_warnings),
                    ) {
                        ::std::result::Result::Ok(parsed) => {
                            if !__usage_warnings.is_empty() {
                                ::std::eprint!(
                                    "{}",
                                    usage_argv::render_warnings(&__usage_warnings),
                                );
                            }
                            parsed
                        }
                        ::std::result::Result::Err(e) => Self::__usage_exit_on_error(
                            e,
                            &__usage_all_refs,
                            &__usage_argv,
                            __usage_selected_view,
                        ),
                    }
                }

                #settings_parse_entry

                /// Render a parse failure the way the process entry does, and leave.
                ///
                /// This is reached only from an entry point that *is* the process — it
                /// already exits for a help request — so it answers a failure the way a
                /// command-line program does: the message on stderr, and a non-zero status.
                /// `parse_from` hands the error back instead, for a library embedding this
                /// that wants to decide. One copy, shared by `parse` and by
                /// `parse_with_settings` when settings are bound.
                fn __usage_exit_on_error<'v>(
                    __usage_error: usage_argv::Error<'static, 'v>,
                    __usage_all_refs: &[&'v ::std::ffi::OsStr],
                    __usage_argv: &[&'v ::std::ffi::OsStr],
                    __usage_selected_view: ::std::option::Option<
                        &usage_argv::spec::ViewMeta<'static>,
                    >,
                ) -> ! {
                    match __usage_error {
                        // Not failures: someone asked a question, and the answer goes to stdout.
                        usage_argv::Error::Version { long } => {
                            #runtime_program_for_version
                            let __usage_bin = __usage_selected_view
                                .map(|view| view.bin)
                                .unwrap_or(__usage_bin);
                            let __usage_version = if long {
                                #output_long_version
                            } else {
                                #runtime_version
                            };
                            ::std::println!("{__usage_bin} {__usage_version}");
                            usage_argv::__usage_process_exit(0);
                        }
                        usage_argv::Error::Help { cmd, long } => {
                            #effective_spec
                            let __usage_want = if long {
                                usage_argv::help::Page::Long
                            } else {
                                usage_argv::help::Page::Short
                            };
                            #render_page
                            match __usage_page {
                                ::std::option::Option::Some(page) => {
                                    ::std::print!("{page}");
                                    usage_argv::__usage_process_exit(0);
                                }
                                // Only reachable if the command came from another CLI's tables.
                                ::std::option::Option::None => usage_argv::__usage_process_exit(0),
                            }
                        }
                        usage_argv::Error::MissingArgsHelp { cmd } => {
                            #effective_spec
                            let __usage_want = usage_argv::help::Page::Short;
                            #render_page_stderr
                            match __usage_page {
                                ::std::option::Option::Some(page) => {
                                    ::std::eprint!("{page}");
                                    usage_argv::__usage_process_exit(2);
                                }
                                ::std::option::Option::None => usage_argv::__usage_process_exit(2),
                            }
                        }
                        usage_argv::Error::HelpAll { cmd } => {
                            #effective_spec
                            let __usage_want = usage_argv::help::Page::All;
                            #render_page
                            match __usage_page {
                                ::std::option::Option::Some(page) => {
                                    ::std::print!("{page}");
                                    usage_argv::__usage_process_exit(0);
                                }
                                ::std::option::Option::None => usage_argv::__usage_process_exit(0),
                            }
                        }
                        e => {
                            #effective_spec
                            let __usage_failure = match __usage_selected_view {
                                ::std::option::Option::Some(view) => {
                                    usage_argv::render_failure_view(
                                        __usage_spec,
                                        &__usage_all_refs,
                                        &e,
                                        view,
                                    )
                                }
                                ::std::option::Option::None => {
                                    usage_argv::render_failure(
                                        __usage_spec,
                                        &__usage_argv,
                                        &e,
                                    )
                                }
                            };
                            ::std::eprint!(
                                "{}",
                                __usage_failure
                            );
                            // clap's, so a script that checks for it keeps working.
                            usage_argv::__usage_process_exit(2);
                        }
                    }
                }
            }
        };

        #dispatch
    }
}

/// A compile-time refusal of a flattened group that declares subcommands.
///
/// Flatten joins one struct's flags and arguments into another's tables. Subcommands are not
/// joined — the parent's table has no entry for them — but the group's own `build` still
/// demands one, so the shape compiles into a command that cannot be run and whose emitted
/// spec says it can: `subcommand_required` reads the parent's own fields and sees none.
///
/// Refused rather than supported, as `Option<T>` flatten is: joining two commands' subcommand
/// sets needs a rule for which enum a word selects from, and nothing in the fleet asks for
/// one. Checked in the *parent's* expansion, where the group is only a type — its `COMMAND`
/// is a `const`, so the parent can look at it during const evaluation without the two
/// expansions ever seeing each other. Written as the user wrote it, like every other use of a
/// flattened type here: the tables are emitted beside their struct now rather than in a module
/// above it, so there is no path to rewrite.
fn flatten_checks(cli: &Cli) -> TokenStream {
    let shape_checks = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        Some(quote! {
            const _: () = ::core::assert!(
                <#ty as usage_argv::spec::CommandArgs>::COMMAND.subcommands.is_empty(),
                "a flattened group cannot declare subcommands: flatten joins flags and \
                 arguments into the parent's tables and leaves subcommands behind, so the \
                 command would require one that no word could select. Declare the \
                 `subcommand` field on the command's own struct instead."
            );
        })
    });
    let command = if cli.composable {
        quote!(COMMAND)
    } else {
        quote!(ROOT)
    };
    let relationship_checks = cli.fields.iter().flat_map(|field| {
        field
            .overrides
            .iter()
            .filter(|selector| cli.field_for_selector(selector).is_none())
            .map(|selector| {
                quote! {
                    const _: () = ::core::assert!(
                        usage_argv::spec::flag_selector_count(&#command, #selector) == 1,
                        ::core::concat!(
                            "`overrides = ",
                            #selector,
                            "` must name exactly one flag after flattened groups are composed",
                        ),
                    );
                }
            })
    });
    quote!(#(#shape_checks)* #(#relationship_checks)*)
}

/// A command's `unknown_flags`, as the table's `Option`.
///
/// `None` is not a default so much as a deferral: the parser carries the enclosing command's
/// answer down, so a struct that declares nothing keeps whatever it was given. Only a struct
/// that says something writes anything.
fn unknown_flags_tokens(cli: &Cli) -> TokenStream {
    match cli.unknown_flags.as_deref() {
        Some("error") => quote!(::core::option::Option::Some(
            usage_argv::UnknownFlags::Error
        )),
        Some(_) => quote!(::core::option::Option::Some(
            usage_argv::UnknownFlags::Value
        )),
        None => quote!(::core::option::Option::None),
    }
}

/// The `spec_extra` tail, appended to the emitted document.
///
/// Appended rather than merged: this crate does not parse KDL, so extra nodes join the document
/// and not the model. Both `to_kdl` and the endpoint read the same function, so a checked-in
/// artifact and what the binary hands a tool cannot differ.
fn spec_extra_append(cli: &Cli) -> TokenStream {
    let Some(path) = cli.spec_extra.as_deref() else {
        return TokenStream::new();
    };
    quote! {
        {
            // Resolved in the declaring crate, which is where the path was written.
            const __USAGE_SPEC_EXTRA: &str = ::core::include_str!(::core::concat!(
                ::core::env!("CARGO_MANIFEST_DIR"),
                "/",
                #path,
            ));
            let __usage_extra = __USAGE_SPEC_EXTRA.trim();
            if !__usage_extra.is_empty() {
                __usage_kdl = ::std::format!(
                    "{}\n{}\n",
                    __usage_kdl.trim_end(),
                    __usage_extra,
                );
            }
        }
    }
}

/// The spec endpoint, which every CLI has unless it says otherwise.
///
/// Two pieces, the same shape as the completion pair below: a function that answers, and the line
/// in `parse` that notices. On by default because the point of it is that a tool can ask *any*
/// usage binary for its spec — an endpoint each adopter has to remember to enable is one no
/// external tool can rely on. `spec_endpoint = false` is the way out for a binary that does not
/// want to carry the KDL writer.
fn spec_endpoint_fns(cli: &Cli) -> (TokenStream, TokenStream) {
    if !cli.spec_endpoint {
        return (TokenStream::new(), TokenStream::new());
    }
    let functions = quote! {
        /// This CLI's own spec, when argv asks for it.
        ///
        /// `Some` for a command line whose first word is `usage_argv::SPEC_REQUEST`, and `None`
        /// for an ordinary invocation — including one that names a command of that spelling,
        /// which keeps a declaration ahead of the built-in. Takes the command line *without*
        /// the program name, like [`Self::parse_from`].
        ///
        /// [`Self::parse`] answers it and exits. An embedder that renders its own output, or
        /// wants to refuse the request, calls this instead.
        pub fn spec_request(
            argv: &[&::std::ffi::OsStr],
        ) -> ::std::option::Option<::std::string::String> {
            if usage_argv::is_spec_request(Self::command(), argv) {
                ::std::option::Option::Some(Self::to_kdl())
            } else {
                ::std::option::Option::None
            }
        }
    };
    let intercept = quote! {
        // Before the view and multicall rewrites below, for the reason a completion request is
        // answered before the parse: asking what this CLI *is* is not one of the things it does,
        // so its grammar has no say. Reads the argv already collected, so the endpoint costs one
        // comparison and no allocation.
        if let ::std::option::Option::Some(__usage_answer) =
            Self::spec_request(__usage_all_refs.get(1..).unwrap_or(&[]))
        {
            ::std::print!("{__usage_answer}");
            usage_argv::__usage_process_exit(0);
        }
    };
    (functions, intercept)
}

/// The completion entry points, for a CLI that asked for them.
///
/// Two pieces: a function that answers a request, and the line in `parse` that notices one. Both
/// empty without the opt-in, so a binary carries neither the hidden command nor the protocol —
/// and `completion_script` cannot be called for a CLI whose binary would not answer it.
fn completion_fns(cli: &Cli) -> (TokenStream, TokenStream) {
    if !cli.completion {
        return (TokenStream::new(), TokenStream::new());
    }
    let completion_program = cli
        .runtime_bin
        .as_ref()
        .or(cli.runtime_name.as_ref())
        .map(|program| {
            quote! {
                let __usage_runtime_program: &'static str = #program;
                __usage_runtime_program.to_string()
            }
        })
        .unwrap_or_else(|| {
            quote! {
                let spec = Self::spec();
                spec.bin.unwrap_or(spec.name).to_string()
            }
        });
    let functions = quote! {
        // Says what is missing, where the alternative is `unresolved module complete` — which
        // names the symptom and not the attribute that asked for it.
        usage_argv::__usage_needs_complete_feature!();

        /// This CLI's completion script for `shell`, to be written to a file or sourced.
        ///
        /// Emitted under the same attribute as the command it calls, which is what makes a
        /// script that names a command the binary does not answer a compile error instead of a
        /// silence at the prompt.
        pub fn completion_script(
            shell: usage_argv::complete::Shell,
        ) -> ::std::string::String {
            let __usage_program = { #completion_program };
            usage_argv::script::script(&__usage_program, shell)
        }

        /// Register completion under a shell alias while asking this CLI's real binary.
        pub fn completion_script_for_alias(
            alias: &str,
            shell: usage_argv::complete::Shell,
        ) -> ::std::string::String {
            let __usage_program = { #completion_program };
            usage_argv::script::script_for(&__usage_program, alias, shell)
        }

        /// Where this CLI's completion script for `shell` goes, and what else the user must do.
        ///
        /// Nothing is written: this is the answer a preview prints. `env` is normally
        /// `usage_argv::install::Env::from_process()`; a test describes one instead.
        pub fn completion_install_plan(
            shell: usage_argv::complete::Shell,
            env: &usage_argv::install::Env,
        ) -> ::std::result::Result<
            usage_argv::install::Plan,
            usage_argv::install::Error,
        > {
            let __usage_program = { #completion_program };
            usage_argv::install::plan(&__usage_program, shell, env)
        }

        /// Where an alias's completion script would go. The preview half of
        /// `install_completion_for_alias`.
        pub fn completion_install_plan_for_alias(
            alias: &str,
            shell: usage_argv::complete::Shell,
            env: &usage_argv::install::Env,
        ) -> ::std::result::Result<
            usage_argv::install::Plan,
            usage_argv::install::Error,
        > {
            let __usage_program = { #completion_program };
            usage_argv::install::plan_for(&__usage_program, alias, shell, env)
        }

        /// Write this CLI's completion script where `env` says this shell looks for it.
        ///
        /// Creates the directories above it and nothing else: no shell rc file and no PowerShell
        /// profile is edited, so a shell that needs a line of its own reports it through
        /// `Installed::plan` rather than having it applied.
        pub fn install_completion(
            shell: usage_argv::complete::Shell,
            env: &usage_argv::install::Env,
            on_foreign: usage_argv::install::OnForeign,
        ) -> ::std::result::Result<
            usage_argv::install::Installed,
            usage_argv::install::Error,
        > {
            let __usage_program = { #completion_program };
            usage_argv::install::install(&__usage_program, shell, env, on_foreign)
        }

        /// Install under a shell alias while still asking this CLI's real binary for answers.
        pub fn install_completion_for_alias(
            alias: &str,
            shell: usage_argv::complete::Shell,
            env: &usage_argv::install::Env,
            on_foreign: usage_argv::install::OnForeign,
        ) -> ::std::result::Result<
            usage_argv::install::Installed,
            usage_argv::install::Error,
        > {
            let __usage_program = { #completion_program };
            usage_argv::install::install_for(&__usage_program, alias, shell, env, on_foreign)
        }

        /// A declared executable view's completion script.
        pub fn completion_script_for(
            view: &str,
            shell: usage_argv::complete::Shell,
        ) -> ::std::option::Option<::std::string::String> {
            Self::spec()
                .views
                .iter()
                .find(|declared| declared.id == view)
                .map(|declared| usage_argv::script::script(declared.bin, shell))
        }

        /// The word a shell is completing, answered from this CLI's own tables.
        ///
        /// `None` when argv is an ordinary invocation. The request is recognized before the
        /// parse rather than inside it: a completion is not a command this CLI runs, and putting
        /// it in the tables would make it one — visible to the grammar, the help and the spec.
        pub fn completion_request(
            argv: &[::std::ffi::OsString],
        ) -> ::std::option::Option<::std::string::String> {
            let first = argv.first()?.to_str()?;
            if first != "__complete_word__" {
                return ::std::option::Option::None;
            }
            // Its own flags, read by hand: three of them, and reading them with the parser
            // would mean putting them in the tables this is deliberately outside of.
            let mut shell = usage_argv::complete::Shell::Bash;
            let mut line = ::std::string::String::new();
            let mut cursor = ::std::option::Option::None;
            let mut candidates_for: ::std::option::Option<::std::string::String> =
                ::std::option::Option::None;
            let mut words: ::std::option::Option<::std::vec::Vec<::std::string::String>> =
                ::std::option::Option::None;
            let mut rest = argv[1..].iter();
            while let ::std::option::Option::Some(arg) = rest.next() {
                match arg.to_str().unwrap_or_default() {
                    "--shell" => {
                        if let ::std::option::Option::Some(name) = rest.next() {
                            if let ::std::option::Option::Some(found) =
                                usage_argv::complete::Shell::from_name(
                                    &name.to_string_lossy(),
                                )
                            {
                                shell = found;
                            }
                        }
                    }
                    "--line" => {
                        if let ::std::option::Option::Some(value) = rest.next() {
                            line = value.to_string_lossy().into_owned();
                        }
                    }
                    "--cursor" => {
                        cursor = rest
                            .next()
                            .and_then(|value| value.to_str().and_then(|v| v.parse().ok()));
                    }
                    // What the `run=` in this CLI's own emitted spec asks for: one named
                    // completer's answers, rather than everything the cursor could take. That is
                    // the shape a spec's `complete` block promises, so anything reading the KDL
                    // gets what it expects from the binary the KDL names.
                    "--candidates" => {
                        candidates_for = rest.next().map(|v| v.to_string_lossy().into_owned());
                    }
                    // Elvish already hands its completer losslessly split words. Keeping them as
                    // argv avoids re-quoting text just so the shared line splitter can undo it.
                    "--words" => {
                        words = ::std::option::Option::Some(
                            rest.map(|word| word.to_string_lossy().into_owned()).collect(),
                        );
                        break;
                    }
                    // Anything else is a shell passing something this version does not know
                    // about. Ignored rather than refused: a completion that errors out is a
                    // shell that beeps at every keystroke.
                    _ => {}
                }
            }
            // No cursor means the end of the line, which is where a shell puts it when it has
            // no way to say — nushell, whose completer only ever sees the words.
            let mut split = match words {
                ::std::option::Option::Some(mut words) => {
                    if words.is_empty() {
                        words.push(::std::string::String::new());
                    }
                    let cword = words.len() - 1;
                    let prefix = words[cword].clone();
                    usage_argv::complete::Split { words, cword, prefix }
                }
                ::std::option::Option::None => {
                    let cursor = cursor.unwrap_or(line.len());
                    usage_argv::complete::split(&line, cursor, shell)
                }
            };
            let __usage_selected_view = split.words.first().and_then(|__usage_program| {
                usage_argv::spec::view_for_program(
                    Self::spec(),
                    ::std::ffi::OsStr::new(__usage_program),
                )
            });
            if let ::std::option::Option::Some(name) = candidates_for {
                // Walked here as well, because a `--candidates` request names a completer and
                // says nothing about where the cursor is — and the completer still wants the
                // words its own command was given.
                let position = match __usage_selected_view {
                    ::std::option::Option::Some(view) =>
                        usage_argv::complete::walk_view(
                            Self::spec().root.cmd,
                            split.argv(),
                            view,
                        ),
                    ::std::option::Option::None =>
                        usage_argv::complete::walk(Self::spec().root.cmd, split.argv()),
                };
                let __usage_words = split.argv();
                let __usage_path: ::std::vec::Vec<(
                    &usage_argv::Command<'_>,
                    &[::std::string::String],
                )> = position
                    .path
                    .iter()
                    .map(|(cmd, start)| (*cmd, __usage_words.get(*start..).unwrap_or(&[])))
                    .collect();
                let ctx = usage_argv::complete::CompleteCtx {
                    words: &split.words,
                    cword: split.cword,
                    prefix: &split.prefix,
                    command_words: __usage_words
                        .get(position.command_start..)
                        .unwrap_or(&[]),
                    command_path: &__usage_path,
                };
                // Nothing of that name is an empty answer rather than an error: a spec written
                // against a newer version of this CLI is a stale script, and a stale script
                // should complete nothing rather than print a message into the user's prompt.
                let found = match __usage_selected_view {
                    ::std::option::Option::Some(view) =>
                        usage_argv::complete::for_name_view(Self::spec(), &name, &ctx, view)
                            .unwrap_or_default(),
                    ::std::option::Option::None =>
                        usage_argv::complete::for_name(Self::spec(), &name, &ctx)
                            .unwrap_or_default(),
                };
                let answer = usage_argv::complete::Completions {
                    candidates: found,
                    files: ::std::option::Option::None,
                };
                return ::std::option::Option::Some(usage_argv::complete::render(&answer, shell));
            }
            let answer = match __usage_selected_view {
                ::std::option::Option::Some(view) =>
                    usage_argv::complete::complete_view(Self::spec(), &split, view),
                ::std::option::Option::None =>
                    usage_argv::complete::complete(Self::spec(), &split),
            };
            ::std::option::Option::Some(usage_argv::complete::render(&answer, shell))
        }
    };
    let intercept = quote! {
        // Before anything else, including the parse: a completion request is not this CLI's
        // grammar and must not be measured against it.
        {
            let __usage_args: ::std::vec::Vec<::std::ffi::OsString> =
                ::std::env::args_os().skip(1).collect();
            if let ::std::option::Option::Some(answer) = Self::completion_request(&__usage_args) {
                ::std::print!("{answer}");
                usage_argv::__usage_process_exit(0);
            }
        }
    };
    (functions, intercept)
}

fn flag_table(i: usize, field: &Field) -> TokenStream {
    let name = format_ident!("FLAG_{i}");
    let binding_type_name = format_ident!("FLAG_{i}_BINDING_TYPE");
    let key = key_ident("FLAG", Some(i));
    let field_name = &field.name;
    let binding_key = binding_hash(field);
    let (binding_type_fn, binding_type) = match field.value_ty.as_ref() {
        Some(ty) => (
            quote! {
                fn #binding_type_name() -> &'static str {
                    ::core::any::type_name::<#ty>()
                }
            },
            quote!(::core::option::Option::Some(usage_argv::BindingType(#binding_type_name))),
        ),
        None => (quote!(), quote!(::core::option::Option::None)),
    };
    let Kind::Flag {
        longs,
        hidden_longs: _,
        shorts,
        negate,
        global,
        variadic,
    } = &field.kind
    else {
        unreachable!("filtered by the caller");
    };
    let shorts: Vec<u8> = shorts.iter().map(|c| *c as u8).collect();
    let negate = option_str(negate.as_deref());
    let takes_value = field.takes_value();
    // The bound on one occurrence's values. A repeatable flag's bound counts occurrences
    // instead, which no single token can decide, so that one stays a post-binding check.
    let var_max = match field.value_var_max.filter(|_| *variadic) {
        Some(max) => {
            // Saturating, not `as`: on a 64-bit target a bound above `u32::MAX` would
            // narrow, and `4294967296` narrows to zero — a limit of "none" read as a limit
            // of "stop immediately". A variadic bounded above four billion is unbounded in
            // every practical sense, so clamping says the same thing safely.
            let max = u32::try_from(max).unwrap_or(u32::MAX);
            quote!(::std::option::Option::Some(#max))
        }
        None => quote!(::std::option::Option::None),
    };

    let table_delimiter = table_delimiter(field);
    let allow_hyphen_values = field.allow_hyphen_values;
    let allow_negative_numbers = field.allow_negative_numbers;
    let value_terminator = match field.value_terminator.as_deref() {
        Some(value) => quote!(::core::option::Option::Some(#value.as_bytes())),
        None => quote!(::core::option::Option::None),
    };
    let require_equals = field.require_equals;
    let bool_value = field.bool_value;
    // `value_optional` can be a presentation-only declaration for clap/spec
    // compatibility. Only a nested Option can represent a genuinely bare value
    // in the typed result; `default_missing` turns the bare form into a value
    // before binding.
    let value_optional = field.optional_value_type || field.default_missing.is_some();
    let default_missing = match field.default_missing.as_deref() {
        Some(value) => quote!(::core::option::Option::Some(#value.as_bytes())),
        None => quote!(::core::option::Option::None),
    };
    let action = match field.action {
        crate::model::ArgAction::Set => quote!(usage_argv::ArgAction::Set),
        crate::model::ArgAction::Help => quote!(usage_argv::ArgAction::Help),
        crate::model::ArgAction::HelpShort => quote!(usage_argv::ArgAction::HelpShort),
        crate::model::ArgAction::HelpLong => quote!(usage_argv::ArgAction::HelpLong),
        crate::model::ArgAction::HelpAll => quote!(usage_argv::ArgAction::HelpAll),
        crate::model::ArgAction::Version => quote!(usage_argv::ArgAction::Version),
    };
    quote! {
        #binding_type_fn
        pub static #name: usage_argv::Flag = usage_argv::Flag {
            key: #key,
            binding_key: #binding_key,
            binding_type: #binding_type,
            name: #field_name,
            longs: &[#(#longs),*],
            shorts: &[#(#shorts),*],
            negate: #negate,
            takes_value: #takes_value,
            variadic: #variadic,
            var_max: #var_max,
            delimiter: #table_delimiter,
            allow_hyphen_values: #allow_hyphen_values,
            allow_negative_numbers: #allow_negative_numbers,
            value_terminator: #value_terminator,
            require_equals: #require_equals,
            value_optional: #value_optional,
            bool_value: #bool_value,
            default_missing: #default_missing,
            global: #global,
            action: #action,
        };
    }
}

/// Stable identity of the typed contract that receives a flag event.
///
/// A child redeclaration may share an argument name while changing its shape, Rust type,
/// choices, or validator. Such an event belongs only to the child; mirroring it into the
/// ancestor would either overwrite a valid fallback or fail while building the ancestor.
fn binding_hash(field: &Field) -> u64 {
    let shape = match field.shape {
        Shape::Bool => "bool",
        Shape::Count => "count",
        Shape::Optional => "optional",
        Shape::Required => "required",
        Shape::Many => "many",
    };
    let mut hash = 0xcbf2_9ce4_8422_2325u64;
    hash_binding_part(&mut hash, b"shape", Some(shape.as_bytes()));
    hash_binding_part(
        &mut hash,
        b"bool-value",
        Some(&[u8::from(field.bool_value)]),
    );
    hash_binding_part(
        &mut hash,
        b"optional-value",
        Some(&[u8::from(field.optional_value_type)]),
    );
    let variadic = matches!(field.kind, Kind::Flag { variadic: true, .. });
    hash_binding_part(&mut hash, b"variadic", Some(&[u8::from(variadic)]));
    hash_binding_part(
        &mut hash,
        b"repeatable",
        Some(&[u8::from(field.repeatable)]),
    );
    hash_binding_usize(&mut hash, b"var-min", field.var_min);
    hash_binding_usize(&mut hash, b"var-max", field.var_max);
    hash_binding_usize(&mut hash, b"value-var-min", field.value_var_min);
    hash_binding_usize(&mut hash, b"value-var-max", field.value_var_max);
    hash_binding_part(
        &mut hash,
        b"value-enum",
        Some(&[u8::from(field.value_enum)]),
    );
    hash_binding_part(
        &mut hash,
        b"open-choices",
        Some(&[u8::from(field.allow_unknown_choices)]),
    );
    for choice in &field.choices {
        hash_binding_part(&mut hash, b"choice", Some(choice.as_bytes()));
    }
    hash_binding_part(&mut hash, b"choices-end", None);
    hash_binding_part(
        &mut hash,
        b"validate",
        field.validate.as_deref().map(str::as_bytes),
    );
    hash_binding_part(
        &mut hash,
        b"validate-error",
        field.validate_error.as_deref().map(str::as_bytes),
    );
    let delimiter = field.delimiter.map(|value| value.to_string());
    hash_binding_part(
        &mut hash,
        b"delimiter",
        delimiter.as_deref().map(str::as_bytes),
    );
    hash
}

fn hash_binding_usize(hash: &mut u64, label: &[u8], value: Option<usize>) {
    let value = value.map(|value| (value as u64).to_le_bytes());
    hash_binding_part(hash, label, value.as_ref().map(|value| value.as_slice()));
}

/// Add one labelled, length-delimited part to a binding contract hash.
///
/// Labels keep adjacent properties distinct, while lengths keep values such as `("a", "bc")`
/// from becoming indistinguishable from `("ab", "c")`.
fn hash_binding_part(hash: &mut u64, label: &[u8], value: Option<&[u8]>) {
    for byte in (label.len() as u64)
        .to_le_bytes()
        .into_iter()
        .chain(label.iter().copied())
    {
        *hash ^= u64::from(byte);
        *hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    let (present, value) = match value {
        Some(value) => (1u8, value),
        None => (0u8, &[][..]),
    };
    for byte in [present]
        .into_iter()
        .chain((value.len() as u64).to_le_bytes())
        .chain(value.iter().copied())
    {
        *hash ^= u64::from(byte);
        *hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
}

/// The delimiter as the parser tables want it: a byte, or nothing.
///
/// Validated to one byte where the attribute is read, so a `char` that does not fit is
/// already impossible here rather than silently truncated.
fn table_delimiter(field: &Field) -> TokenStream {
    // ASCII, matching the rule the attribute enforces: splitting is by byte, and a
    // separator that is one byte as a scalar but two as UTF-8 would match the continuation
    // bytes inside unrelated characters.
    match field.delimiter.filter(char::is_ascii).map(|d| d as u8) {
        Some(byte) => quote!(::std::option::Option::Some(#byte)),
        None => quote!(::std::option::Option::None),
    }
}

fn arg_table(i: usize, field: &Field) -> TokenStream {
    let name = format_ident!("ARG_{i}");
    let key = key_ident("ARG", Some(i));
    let field_name = &field.name;
    let var = field.shape == Shape::Many;
    let required =
        (field.shape == Shape::Required || field.required_collection) && !field.has_default();
    let Kind::Arg { double_dash, sigil } = &field.kind else {
        unreachable!("filtered by the caller");
    };
    let sigil = match sigil.as_deref() {
        Some(value) => quote!(::core::option::Option::Some(#value.as_bytes())),
        None => quote!(::core::option::Option::None),
    };
    let double_dash = match double_dash {
        DoubleDash::Optional => quote!(usage_argv::DoubleDash::Optional),
        DoubleDash::Required => quote!(usage_argv::DoubleDash::Required),
        DoubleDash::Preserve => quote!(usage_argv::DoubleDash::Preserve),
        DoubleDash::Automatic => quote!(usage_argv::DoubleDash::Automatic),
    };
    // A bound stops the variadic while binding, so the argument after it is reachable.
    let var_max = match field.var_max.filter(|_| var) {
        Some(max) => {
            // Saturating, for the reason given on the flag above.
            let max = u32::try_from(max).unwrap_or(u32::MAX);
            quote!(::std::option::Option::Some(#max))
        }
        None => quote!(::std::option::Option::None),
    };

    let table_delimiter = table_delimiter(field);
    let allow_negative_numbers = field.allow_negative_numbers;
    let value_terminator = match field.value_terminator.as_deref() {
        Some(value) => quote!(::core::option::Option::Some(#value.as_bytes())),
        None => quote!(::core::option::Option::None),
    };
    quote! {
        pub static #name: usage_argv::Arg = usage_argv::Arg {
            key: #key,
            sigil: #sigil,
            required: #required,
            name: #field_name,
            var: #var,
            var_max: #var_max,
            delimiter: #table_delimiter,
            allow_negative_numbers: #allow_negative_numbers,
            value_terminator: #value_terminator,
            double_dash: #double_dash,
        };
    }
}

/// The completer entry for a field, and the wrapper that gives it a typed partial.
///
/// A table entry has one uniform signature, and the function a CLI writes has the signature that
/// is useful — its own command's half-parsed struct, and the context. The wrapper is what turns
/// the first into the second: it reparses the words that command was given, which the position
/// reports, and hands over the result. So `mise task ls --file other.toml ⌶` can be completed
/// against that file, which is exactly what a `run=` shelling out to `mise tasks ls --complete`
/// cannot see.
fn completer_tokens(
    i: usize,
    field: &Field,
    kind: &str,
    owner: &syn::Ident,
) -> (TokenStream, TokenStream) {
    let Some(path) = &field.complete else {
        return (TokenStream::new(), quote!(::std::option::Option::None));
    };
    let wrapper = format_ident!("__usage_complete_{kind}_{i}");
    // Through the same rewriting a field's *type* goes through: the generated module is one
    // level below where the user wrote the path, so a bare name shifts by one — while
    // `crate::…`, a leading `::` and `self::…` mean something already, and prefixing those
    // produced a path that does not resolve.
    let completer_path = path;
    let decl = quote! {
        fn #wrapper(
            ctx: &usage_argv::complete::CompleteCtx<'_>,
        ) -> ::std::vec::Vec<usage_argv::complete::Candidate<'static>> {
            // The words this command was given, parsed against this command's own tables — so
            // what the callback reads is what the parser would have bound, rather than a slice
            // of the line it has to interpret itself.
            // This command's own words, asked for by this command — not the deepest one the
            // line reached. A global flag is declared on an ancestor, and reparsing the
            // subcommand's words against the ancestor's tables would drop everything the
            // ancestor was given before the subcommand's name.
            let __usage_declaration =
                <#owner as usage_argv::spec::CommandArgs>::COMMAND;
            let (__usage_command, __usage_words) = ctx
                .command_for(__usage_declaration)
                .unwrap_or((__usage_declaration, ctx.command_words));
            let __usage_owned: ::std::vec::Vec<::std::ffi::OsString> = __usage_words
                .iter()
                .map(::std::ffi::OsString::from)
                .collect();
            let __usage_argv: ::std::vec::Vec<&::std::ffi::OsStr> =
                __usage_owned.iter().map(|a| a.as_os_str()).collect();
            let mut partial = <#owner as usage_argv::spec::CommandArgs>::start();
            let mut parser = usage_argv::Parser::new(
                __usage_command,
                &__usage_argv,
            );
            // A line being completed is unfinished by definition, so an error means the grammar
            // ran out — the partial holds what was understood before that, which is the point.
            while let ::std::option::Option::Some(event) = parser.next_event() {
                match event {
                    ::std::result::Result::Ok(event) => {
                        let _ = <#owner as usage_argv::spec::CommandArgs>::apply(
                            &mut partial,
                            &event,
                        );
                    }
                    ::std::result::Result::Err(_) => break,
                }
            }
            #completer_path(&partial, ctx)
        }
    };
    (decl, quote!(::std::option::Option::Some(#wrapper)))
}

fn flag_meta(cli: &Cli, i: usize, field: &Field, owner: &syn::Ident) -> TokenStream {
    let name = format_ident!("FLAG_META_{i}");
    let table = format_ident!("FLAG_{i}");
    let help = option_str(field.help.as_deref());
    let long_help = option_str(field.long_help.as_deref());
    let admonitions = admonitions(field);
    let env = option_str(field.env.as_deref());
    let env_fallback = &field.env_fallback;
    let deprecated_env = &field.deprecated_env;
    let help_heading = option_str(field.help_heading.as_deref());
    let surface = option_str(field.surface.as_deref());
    let available_if = &field.available_if;
    let display_order = option_usize(field.display_order);
    let deprecated = option_str(field.deprecated.as_deref());
    let deprecated_warn_at = option_str(field.deprecated_warn_at.as_deref());
    let deprecated_remove_at = option_str(field.deprecated_remove_at.as_deref());
    let value_name = option_str(field.value_name.as_deref());
    let value_names = &field.value_names;
    let complete_type = option_str(field.complete_type.as_deref());
    let defaults = &field.default;
    let default = quote!(&[#(#defaults),*]);
    let hide = field.hide;
    let hide_default_value = field.hide_default_value;
    let hide_env = field.hide_env;
    let hide_env_values = field.hide_env_values;
    let hide_possible_values = field.hide_possible_values;
    let hide_short_help = field.hide_short_help;
    let hide_long_help = field.hide_long_help;
    let count = field.shape == Shape::Count;
    let repeatable = field.repeatable;
    let hidden_longs = match &field.kind {
        Kind::Flag { hidden_longs, .. } => hidden_longs,
        _ => unreachable!("flag metadata is generated only for flags"),
    };
    // Same rule as an argument: a `String` has nowhere to put "absent". The runtime
    // check already enforced it; the spec has to say it too, or docs and completions
    // describe a different CLI from the one that runs.
    // A collecting field's type cannot say whether one value is needed, so `required` may
    // declare it. Every other shape gets its answer from the type.
    let required =
        (field.shape == Shape::Required || field.required_collection) && !field.has_default();
    // Declared, not inferred: `Option<String>` already says the *flag* is optional and says
    // nothing about whether its value is.
    let value_optional = field.value_optional;
    let (choices, accepted_choices, choice_aliases, choice_details, ignore_case) =
        choices_tokens(cli, field);
    let allow_unknown_choices = field.allow_unknown_choices;
    let validate = option_str(field.validate.as_deref());
    let validate_error = option_str(field.validate_error.as_deref());
    let (var_min, var_max) = bounds_tokens(field);
    let (value_var_min, value_var_max) = value_bounds_tokens(field);
    // clap relationship attributes name Rust argument IDs. The portable spec names
    // flags by their dashed selector, so normalize IDs after the whole command is
    // available (the target may be declared later in the struct).
    let overrides: Vec<String> = field
        .overrides
        .iter()
        .map(|selector| {
            cli.field_for_selector(selector)
                .and_then(Cli::selector_for_field)
                .unwrap_or_else(|| selector.clone())
        })
        .collect();
    let conflicts: Vec<String> = field
        .conflicts
        .iter()
        .map(|selector| {
            cli.field_for_selector(selector)
                .and_then(Cli::selector_for_field)
                .unwrap_or_else(|| selector.clone())
        })
        .collect();
    let canonical = |selector: &String| {
        cli.field_for_selector(selector)
            .and_then(Cli::selector_for_field)
            .unwrap_or_else(|| selector.clone())
    };
    let requires: Vec<String> = field.requires.iter().map(canonical).collect();
    let requires_if = field.requires_if.iter().map(|condition| {
        let value = &condition.value;
        let requires = canonical(&condition.requires);
        quote!(usage_argv::spec::RequiresIf { value: #value, requires: #requires })
    });
    let default_if = field.default_if.iter().map(|condition| {
        let selector = canonical(&condition.selector);
        let value = &condition.value;
        let when = match &condition.when {
            Some(when) => quote!(::core::option::Option::Some(#when)),
            None => quote!(::core::option::Option::None),
        };
        quote!(usage_argv::spec::DefaultIf { selector: #selector, when: #when, value: #value })
    });
    let exclusive = field.exclusive;
    let delimiter = match field.delimiter {
        Some(c) => quote!(::std::option::Option::Some(#c)),
        None => quote!(::std::option::Option::None),
    };
    let required_if: Vec<String> = field
        .required_if
        .iter()
        .map(|selector| {
            cli.field_for_selector(selector)
                .and_then(Cli::selector_for_field)
                .unwrap_or_else(|| selector.clone())
        })
        .collect();
    let required_if_eq = field.required_if_eq.iter().map(|condition| {
        let selector = cli
            .field_for_selector(&condition.selector)
            .and_then(Cli::selector_for_field)
            .unwrap_or_else(|| condition.selector.clone());
        let value = &condition.value;
        quote!(usage_argv::spec::RequiredIfEq { selector: #selector, value: #value })
    });
    let required_if_eq_all = field.required_if_eq_all.iter().map(|condition| {
        let selector = cli
            .field_for_selector(&condition.selector)
            .and_then(Cli::selector_for_field)
            .unwrap_or_else(|| condition.selector.clone());
        let value = &condition.value;
        quote!(usage_argv::spec::RequiredIfEq { selector: #selector, value: #value })
    });
    let required_unless: Vec<String> = field.required_unless.iter().map(canonical).collect();
    let required_unless_all: Vec<String> =
        field.required_unless_all.iter().map(canonical).collect();

    let (completer_decl, completer) = completer_tokens(i, field, "flag", owner);

    // `None` unless declared, and only on a flag: an argument is not something a user
    // supplies to change what happens, it is the thing being acted on.
    let effect = field
        .effect
        .clone()
        .unwrap_or_else(|| quote!(::core::option::Option::None));
    quote! {
        #completer_decl
        pub static #name: usage_argv::spec::FlagMeta = usage_argv::spec::FlagMeta {
            effect: #effect,
            complete: #completer,
            complete_type: #complete_type,
            flag: &#table,
            display_order: #display_order,
            help: #help,
            long_help: #long_help,
            admonitions: #admonitions,
            deprecated: #deprecated,
            deprecated_warn_at: #deprecated_warn_at,
            deprecated_remove_at: #deprecated_remove_at,
            env: #env,
            env_fallback: &[#(#env_fallback),*],
            deprecated_env: &[#(#deprecated_env),*],
            default: #default,
            help_heading: #help_heading,
            surface: #surface,
            available_if: &[#(#available_if),*],
            value_name: #value_name,
            value_names: &[#(#value_names),*],
            hide: #hide,
            hide_default_value: #hide_default_value,
            hide_env: #hide_env,
            hide_env_values: #hide_env_values,
            hide_possible_values: #hide_possible_values,
            hide_short_help: #hide_short_help,
            hide_long_help: #hide_long_help,
            count: #count,
            repeatable: #repeatable,
            hidden_shorts: &[],
            hidden_longs: &[#(#hidden_longs),*],
            required: #required,
            value_optional: #value_optional,
            accepted_choices: #accepted_choices,
            choices: #choices,
            choice_aliases: #choice_aliases,
            choice_details: #choice_details,
            ignore_case: #ignore_case,
            allow_unknown_choices: #allow_unknown_choices,
            validate: #validate,
            validate_error: #validate_error,
            var_min: #var_min,
            var_max: #var_max,
            value_var_min: #value_var_min,
            value_var_max: #value_var_max,
            overrides: &[#(#overrides),*],
            conflicts: &[#(#conflicts),*],
            requires: &[#(#requires),*],
            requires_if: &[#(#requires_if),*],
            default_if: &[#(#default_if),*],
            exclusive: #exclusive,
            delimiter: #delimiter,
            required_if: &[#(#required_if),*],
            required_if_eq: &[#(#required_if_eq),*],
            required_if_eq_all: &[#(#required_if_eq_all),*],
            required_unless: &[#(#required_unless),*],
            required_unless_all: &[#(#required_unless_all),*],
            ..usage_argv::spec::FlagMeta::EMPTY
        };
    }
}

fn arg_meta(cli: &Cli, i: usize, field: &Field, owner: &syn::Ident) -> TokenStream {
    let name = format_ident!("ARG_META_{i}");
    let table = format_ident!("ARG_{i}");
    let help = option_str(field.help.as_deref());
    let long_help = option_str(field.long_help.as_deref());
    let admonitions = admonitions(field);
    let env = option_str(field.env.as_deref());
    let env_fallback = &field.env_fallback;
    let deprecated_env = &field.deprecated_env;
    let help_heading = option_str(field.help_heading.as_deref());
    let surface = option_str(field.surface.as_deref());
    let available_if = &field.available_if;
    let display_order = option_usize(field.display_order);
    let complete_type = option_str(field.complete_type.as_deref());
    let value_names = &field.value_names;
    let defaults = &field.default;
    let default = quote!(&[#(#defaults),*]);
    let hide = field.hide;
    let hide_default_value = field.hide_default_value;
    let hide_env = field.hide_env;
    let hide_env_values = field.hide_env_values;
    let hide_possible_values = field.hide_possible_values;
    let hide_short_help = field.hide_short_help;
    let hide_long_help = field.hide_long_help;
    let conflicts: Vec<String> = field
        .conflicts
        .iter()
        .map(|selector| {
            cli.field_for_selector(selector)
                .and_then(Cli::selector_for_field)
                .unwrap_or_else(|| selector.clone())
        })
        .collect();
    let canonical = |selector: &String| {
        cli.field_for_selector(selector)
            .and_then(Cli::selector_for_field)
            .unwrap_or_else(|| selector.clone())
    };
    let requires: Vec<String> = field.requires.iter().map(canonical).collect();
    let required_if: Vec<String> = field.required_if.iter().map(canonical).collect();
    let required_if_eq = field.required_if_eq.iter().map(|condition| {
        let selector = canonical(&condition.selector);
        let value = &condition.value;
        quote!(usage_argv::spec::RequiredIfEq { selector: #selector, value: #value })
    });
    let required_if_eq_all = field.required_if_eq_all.iter().map(|condition| {
        let selector = canonical(&condition.selector);
        let value = &condition.value;
        quote!(usage_argv::spec::RequiredIfEq { selector: #selector, value: #value })
    });
    let required_unless: Vec<String> = field.required_unless.iter().map(canonical).collect();
    let required_unless_all: Vec<String> =
        field.required_unless_all.iter().map(canonical).collect();
    // `String` must be filled; `Option` and `Vec` need not be.
    // A collecting field's type cannot say whether one value is needed, so `required` may
    // declare it. Every other shape gets its answer from the type.
    let required =
        (field.shape == Shape::Required || field.required_collection) && !field.has_default();
    let (choices, accepted_choices, choice_aliases, choice_details, ignore_case) =
        choices_tokens(cli, field);
    let allow_unknown_choices = field.allow_unknown_choices;
    let validate = option_str(field.validate.as_deref());
    let validate_error = option_str(field.validate_error.as_deref());
    let (var_min, var_max) = if matches!(field.kind, Kind::Flag { .. }) {
        value_bounds_tokens(field)
    } else {
        bounds_tokens(field)
    };
    let delimiter = match field.delimiter {
        Some(c) => quote!(::std::option::Option::Some(#c)),
        None => quote!(::std::option::Option::None),
    };
    let (completer_decl, completer) = completer_tokens(i, field, "arg", owner);

    quote! {
        #completer_decl
        pub static #name: usage_argv::spec::ArgMeta = usage_argv::spec::ArgMeta {
            complete: #completer,
            complete_type: #complete_type,
            arg: &#table,
            display_order: #display_order,
            value_names: &[#(#value_names),*],
            help: #help,
            long_help: #long_help,
            admonitions: #admonitions,
            env: #env,
            env_fallback: &[#(#env_fallback),*],
            deprecated_env: &[#(#deprecated_env),*],
            default: #default,
            help_heading: #help_heading,
            surface: #surface,
            available_if: &[#(#available_if),*],
            hide: #hide,
            hide_default_value: #hide_default_value,
            hide_env: #hide_env,
            hide_env_values: #hide_env_values,
            hide_possible_values: #hide_possible_values,
            hide_short_help: #hide_short_help,
            hide_long_help: #hide_long_help,
            conflicts: &[#(#conflicts),*],
            requires: &[#(#requires),*],
            required_if: &[#(#required_if),*],
            required_if_eq: &[#(#required_if_eq),*],
            required_if_eq_all: &[#(#required_if_eq_all),*],
            required_unless: &[#(#required_unless),*],
            required_unless_all: &[#(#required_unless_all),*],
            required: #required,
            accepted_choices: #accepted_choices,
            choices: #choices,
            choice_aliases: #choice_aliases,
            choice_details: #choice_details,
            ignore_case: #ignore_case,
            allow_unknown_choices: #allow_unknown_choices,
            validate: #validate,
            validate_error: #validate_error,
            var_min: #var_min,
            var_max: #var_max,
            delimiter: #delimiter,
            ..usage_argv::spec::ArgMeta::EMPTY
        };
    }
}

/// A field's declared choices, as the metadata holds them.
fn choices_tokens(
    cli: &Cli,
    field: &Field,
) -> (
    TokenStream,
    TokenStream,
    TokenStream,
    TokenStream,
    TokenStream,
) {
    // From the type when the field says `value_enum`, so the spec, the help and the check
    // all read the list the type declares rather than a copy of it.
    if let (true, Some(ty)) = (field.value_enum, field.value_ty.as_ref()) {
        return (
            quote!(<#ty as usage_argv::spec::ValueEnum>::CHOICES),
            quote!(<#ty as usage_argv::spec::ValueEnum>::ACCEPTED_CHOICES),
            quote!(<#ty as usage_argv::spec::ValueEnum>::ALIASES),
            quote!(<#ty as usage_argv::spec::ValueEnum>::DETAILS),
            quote!(<#ty as usage_argv::spec::ValueEnum>::IGNORE_CASE),
        );
    }
    // The flag that picks among the outputs accepts exactly their names, so it gets them
    // without the author writing the list twice. usage-lib fills the same list in when it
    // parses a spec, and `output.rs`'s byte-identity test is what holds the two together.
    if let Some(outputs) = selector_choices(cli, field) {
        let values: Vec<&str> = outputs
            .iter()
            .filter(|o| !o.hide)
            .map(|o| o.name.as_str())
            .collect();
        let details: Vec<TokenStream> = outputs
            .iter()
            .filter(|o| !o.hide && o.help.is_some())
            .map(|o| {
                let value = &o.name;
                let help = o.help.as_deref().expect("filtered");
                quote! {
                    usage_argv::spec::ChoiceMeta {
                        value: #value,
                        help: ::std::option::Option::Some(#help),
                        hide: false,
                        aliases: &[],
                    }
                }
            })
            .collect();
        let choices = quote!(&[#(#values),*]);
        return (
            choices.clone(),
            choices,
            quote!(&[]),
            quote!(&[#(#details),*]),
            quote!(false),
        );
    }
    let choices = &field.choices;
    let choices = quote!(&[#(#choices),*]);
    (
        choices.clone(),
        choices,
        quote!(&[]),
        quote!(&[]),
        quote!(false),
    )
}

/// The outputs this field selects among, if it is the one doing the selecting.
///
/// [`None`] when the field is not the selector, or when it already declares choices of its
/// own — a hand-written list carries aliases and per-value help that a list of output names
/// does not, so it wins and usage-lib checks the two agree rather than replacing either.
fn selector_choices<'a>(cli: &'a Cli, field: &Field) -> Option<&'a [crate::model::OutputDecl]> {
    let select = cli.select.as_deref()?;
    if cli.outputs.is_empty() || !field.choices.is_empty() {
        return None;
    }
    let selected = Cli::selector_for_field(field).is_some_and(|s| s == select);
    // Also matches when `select = "-f"` names the short spelling of a field whose long is
    // what `selector_for_field` returns.
    let by_field = cli
        .field_for_selector(select)
        .is_some_and(|f| f.ident == field.ident);
    (selected || by_field).then_some(cli.outputs.as_slice())
}

/// A field's declared bounds, as the metadata holds them.
fn bounds_tokens(field: &Field) -> (TokenStream, TokenStream) {
    let render = |bound: Option<usize>| match bound {
        Some(n) => quote!(::std::option::Option::Some(#n)),
        None => quote!(::std::option::Option::None),
    };
    (render(field.var_min), render(field.var_max))
}

/// Bounds on the values consumed by one flag occurrence.
fn value_bounds_tokens(field: &Field) -> (TokenStream, TokenStream) {
    let render = |bound: Option<usize>| match bound {
        Some(n) => quote!(::std::option::Option::Some(#n)),
        None => quote!(::std::option::Option::None),
    };
    (render(field.value_var_min), render(field.value_var_max))
}

/// Which kind of thing a key belongs to, in the bits above its index.
///
/// A command, a flag, and an argument each get their own space, so no two things in
/// one type can share a key even though each counts its own from zero. The parser
/// says which kind it bound, so this is not needed in order to *dispatch* — it is
/// needed so that "every key in the tree is distinct" is true, which is what makes a
/// collision between two types detectable at all.
const KIND_FLAG: u64 = 0;
const KIND_ARG: u64 = 1 << 30;
const KIND_COMMAND: u64 = 2 << 30;

/// A hash of the declaration a derive was handed, which is half of a key.
///
/// The other half is the module the declaration sits in, mixed in by
/// [`usage_argv::key_base`] where `module_path!()` is available — a macro cannot see a
/// module path, and without it two byte-identical declarations in different modules
/// collide. They used to: `Spec::to_kdl` asserts the tree holds no duplicate keys, so a
/// perfectly good CLI with an `add::Op` and a `remove::Op` failed that assertion.
fn declaration_hash(fingerprint: &str) -> u32 {
    // FNV-1a, spelled out rather than taken from a `Hasher`, which is not guaranteed to
    // be stable between compilations — and this ends up baked into generated code.
    let mut hash: u32 = 0x811c_9dc5;
    for byte in fingerprint.as_bytes() {
        hash ^= *byte as u32;
        hash = hash.wrapping_mul(0x0100_0193);
    }
    hash
}

/// The `const` items a generated module needs before it can name a key.
///
/// One base, then one per flag, argument and command, because a key is used as a `match`
/// pattern as well as a table field — and a pattern cannot be an expression, so
/// `BASE | KIND_FLAG | 0` would parse as an or-pattern of three.
fn key_consts(fingerprint: &str, flags: usize, args: usize) -> TokenStream {
    let declaration = declaration_hash(fingerprint);
    let command = key_ident("COMMAND", None);
    let flag_keys = (0..flags).map(|i| {
        let name = key_ident("FLAG", Some(i));
        let index = i as u64;
        quote!(const #name: u64 = __USAGE_KEY_BASE | #KIND_FLAG | #index;)
    });
    let arg_keys = (0..args).map(|i| {
        let name = key_ident("ARG", Some(i));
        let index = i as u64;
        quote!(const #name: u64 = __USAGE_KEY_BASE | #KIND_ARG | #index;)
    });
    quote! {
        const __USAGE_KEY_BASE: u64 =
            usage_argv::key_base(::core::module_path!(), #declaration);
        const #command: u64 = __USAGE_KEY_BASE | #KIND_COMMAND;
        #(#flag_keys)*
        #(#arg_keys)*
    }
}

/// The name of the `const` holding one key.
fn key_ident(kind: &str, index: Option<usize>) -> proc_macro2::Ident {
    match index {
        Some(i) => format_ident!("__USAGE_KEY_{kind}_{i}"),
        None => format_ident!("__USAGE_KEY_{kind}"),
    }
}

/// The table expressions for one command, and whatever has to be declared to build them.
///
/// Without a `flatten` these are the plain slices the derive has always emitted, so nothing
/// about an existing CLI's generated code changes. With one, the flattened struct's tables
/// have to appear inside the parent's — at the position the field was written, because for
/// positional arguments the position is the meaning — which needs the const-concat helpers
/// and a `static` to hold each joined array.
struct Tables {
    /// Declared before the `Command`: the parse-table groups and their joined arrays.
    decls: TokenStream,
    /// Declared after the per-field metadata, which it reads — so it cannot share `decls`.
    meta_decls: TokenStream,
    flags: TokenStream,
    args: TokenStream,
    flag_metas: TokenStream,
    arg_metas: TokenStream,
    /// Where each flattened struct's flags landed, for the emitted spec to write one
    /// `flagset` instead of the same flags under every command that flattens it.
    flatten_groups: TokenStream,
}

/// Build the four expressions, splicing any flattened groups into place.
///
/// Used by both emitters. The first version of the typed-value conversion was wired into only
/// one of them, which compiled in the tests and not in an adopter's crate — so anything that
/// belongs to "what a command's tables are" goes here, once.
fn tables(cli: &Cli) -> Tables {
    // What a group is: a run of this struct's own declarations, or one flattened struct's
    // whole table. Walked in field order so the runs and the splices interleave correctly.
    let mut flag_groups: Vec<TokenStream> = Vec::new();
    let mut arg_groups: Vec<TokenStream> = Vec::new();
    let mut flag_meta_groups: Vec<TokenStream> = Vec::new();
    let mut arg_meta_groups: Vec<TokenStream> = Vec::new();
    let mut own_flags: Vec<usize> = Vec::new();
    let mut own_args: Vec<usize> = Vec::new();
    let (mut flag_at, mut arg_at) = (0usize, 0usize);
    let mut flattened = false;
    // One entry per flattened field, naming the struct and where its flags begin. The
    // offset is written as a sum rather than a number because the lengths that make it up
    // belong to other structs' tables: `.len()` on a const slice is a const expression, so
    // the arithmetic happens where the rest of the table does.
    let mut flatten_groups: Vec<TokenStream> = Vec::new();
    let mut flag_offset: Vec<TokenStream> = Vec::new();
    let mut own_since_flatten = 0usize;

    // Flush the runs collected so far, so that what follows lands after them.
    fn flush_flags(
        own: &mut Vec<usize>,
        groups: &mut Vec<TokenStream>,
        metas: &mut Vec<TokenStream>,
    ) {
        if own.is_empty() {
            return;
        }
        let refs = own.iter().map(|i| {
            let name = format_ident!("FLAG_{i}");
            quote!(&#name)
        });
        groups.push(quote!(&[#(#refs),*]));
        let meta_refs = own.iter().map(|i| format_ident!("FLAG_META_{i}"));
        metas.push(quote!(&[#(#meta_refs),*]));
        own.clear();
    }
    fn flush_args(
        own: &mut Vec<usize>,
        groups: &mut Vec<TokenStream>,
        metas: &mut Vec<TokenStream>,
    ) {
        if own.is_empty() {
            return;
        }
        let refs = own.iter().map(|i| {
            let name = format_ident!("ARG_{i}");
            quote!(&#name)
        });
        groups.push(quote!(&[#(#refs),*]));
        let meta_refs = own.iter().map(|i| format_ident!("ARG_META_{i}"));
        metas.push(quote!(&[#(#meta_refs),*]));
        own.clear();
    }

    for field in &cli.fields {
        match &field.kind {
            Kind::Flag { .. } => {
                own_flags.push(flag_at);
                flag_at += 1;
                own_since_flatten += 1;
            }
            Kind::Arg { .. } => {
                own_args.push(arg_at);
                arg_at += 1;
            }
            Kind::Flatten { ty, help_heading } => {
                flattened = true;
                if own_since_flatten > 0 {
                    flag_offset.push(quote!(#own_since_flatten));
                    own_since_flatten = 0;
                }
                let name = flagset_name(ty);
                let terms = flag_offset.iter();
                let help_heading = option_str(help_heading.as_deref());
                flatten_groups.push(quote! {
                    usage_argv::spec::FlattenGroup {
                        name: #name,
                        start: 0 #(+ #terms)*,
                        meta: <#ty as usage_argv::spec::CommandArgs>::META,
                        help_heading: #help_heading,
                    }
                });
                flag_offset
                    .push(quote!(<#ty as usage_argv::spec::CommandArgs>::COMMAND.flags.len()));
                flush_flags(&mut own_flags, &mut flag_groups, &mut flag_meta_groups);
                flush_args(&mut own_args, &mut arg_groups, &mut arg_meta_groups);
                flag_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::COMMAND.flags));
                arg_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::COMMAND.args));
                flag_meta_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::META.flags));
                arg_meta_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::META.args));
            }
            // An argument group's switches are spliced the same way, and for the same reason:
            // they are this command's flags, and only the enum's own expansion knows them.
            // No `FlattenGroup` for them — the emitted spec writes them inline, since a group
            // is not a set of flags declared once and shared between commands.
            Kind::ArgGroup { ty, .. } => {
                flattened = true;
                if own_since_flatten > 0 {
                    flag_offset.push(quote!(#own_since_flatten));
                    own_since_flatten = 0;
                }
                flag_offset.push(quote!(<#ty as usage_argv::spec::ArgGroup>::FLAGS.len()));
                flush_flags(&mut own_flags, &mut flag_groups, &mut flag_meta_groups);
                flag_groups.push(quote!(<#ty as usage_argv::spec::ArgGroup>::FLAGS));
                flag_meta_groups.push(quote!(<#ty as usage_argv::spec::ArgGroup>::FLAG_METAS));
            }
            Kind::Clause { ty, .. } => {
                flattened = true;
                if own_since_flatten > 0 {
                    flag_offset.push(quote!(#own_since_flatten));
                    own_since_flatten = 0;
                }
                flag_offset
                    .push(quote!(<#ty as usage_argv::spec::CommandArgs>::COMMAND.flags.len()));
                flush_flags(&mut own_flags, &mut flag_groups, &mut flag_meta_groups);
                flag_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::COMMAND.flags));
                flag_meta_groups.push(quote!(<#ty as usage_argv::spec::CommandArgs>::META.flags));
            }
            Kind::Subcommand { .. } | Kind::Skip => {}
        }
    }
    flush_flags(&mut own_flags, &mut flag_groups, &mut flag_meta_groups);
    flush_args(&mut own_args, &mut arg_groups, &mut arg_meta_groups);

    if !flattened {
        // The shape every CLI without a flatten already had.
        let flag_refs = (0..flag_at).map(|i| {
            let name = format_ident!("FLAG_{i}");
            quote!(&#name)
        });
        let arg_refs = (0..arg_at).map(|i| {
            let name = format_ident!("ARG_{i}");
            quote!(&#name)
        });
        let flag_meta_refs = (0..flag_at).map(|i| format_ident!("FLAG_META_{i}"));
        let arg_meta_refs = (0..arg_at).map(|i| format_ident!("ARG_META_{i}"));
        return Tables {
            decls: TokenStream::new(),
            meta_decls: TokenStream::new(),
            flags: quote!(&[#(#flag_refs),*]),
            args: quote!(&[#(#arg_refs),*]),
            flag_metas: quote!(&[#(#flag_meta_refs),*]),
            arg_metas: quote!(&[#(#arg_meta_refs),*]),
            flatten_groups: quote!(&[]),
        };
    }

    Tables {
        decls: quote! {
            const FLAG_GROUPS: &[&[&usage_argv::Flag<'static>]] = &[#(#flag_groups),*];
            const ARG_GROUPS: &[&[&usage_argv::Arg<'static>]] = &[#(#arg_groups),*];
            static FLAGS: [&usage_argv::Flag<'static>;
                usage_argv::table_len(FLAG_GROUPS)] =
                usage_argv::concat_flags(FLAG_GROUPS);
            static ARGS: [&usage_argv::Arg<'static>; usage_argv::table_len(ARG_GROUPS)] =
                usage_argv::concat_args(ARG_GROUPS);
        },
        meta_decls: quote! {
            const FLAG_META_GROUPS: &[&[usage_argv::spec::FlagMeta<'static>]] =
                &[#(#flag_meta_groups),*];
            const ARG_META_GROUPS: &[&[usage_argv::spec::ArgMeta<'static>]] =
                &[#(#arg_meta_groups),*];
            static FLAG_METAS: [usage_argv::spec::FlagMeta<'static>;
                usage_argv::table_len(FLAG_META_GROUPS)] =
                usage_argv::spec::concat_flag_metas(FLAG_META_GROUPS);
            static ARG_METAS: [usage_argv::spec::ArgMeta<'static>;
                usage_argv::table_len(ARG_META_GROUPS)] =
                usage_argv::spec::concat_arg_metas(ARG_META_GROUPS);
            const FLATTEN_GROUPS: &[usage_argv::spec::FlattenGroup<'static>] =
                &[#(#flatten_groups),*];
        },
        flags: quote!(&FLAGS),
        args: quote!(&ARGS),
        flag_metas: quote!(&FLAG_METAS),
        arg_metas: quote!(&ARG_METAS),
        flatten_groups: quote!(FLATTEN_GROUPS),
    }
}

/// The name a flattened struct's flagset is given: its own, in kebab-case.
///
/// The last path segment only, so `cli::CommonArgs` and `super::CommonArgs` name the same
/// set — which they must, since they are the same struct. Two different structs whose names
/// end in the same word collide, and [`usage_argv::spec::Spec::to_kdl`] resolves that by
/// writing neither as a set rather than by guessing which one meant it.
fn flagset_name(ty: &syn::Type) -> String {
    let rendered = type_name(ty);
    let last = rendered
        .rsplit("::")
        .next()
        .unwrap_or(&rendered)
        .trim()
        .to_string();
    to_kebab(&last)
}

fn flag_arm(cli: &Cli, i: usize, field: &Field) -> TokenStream {
    let key = key_ident("FLAG", Some(i));
    let ident = &field.ident;
    let given = format_ident!("__given_{}", ident);
    let direct = mirrored_global_ident(field).map(|mirrored| quote!(partial.#mirrored = false;));
    let displaced = displacements(cli, field);
    let undisplaced = is_displaceable(cli, field).then(|| {
        let overridden = format_ident!("__overridden_{}", ident);
        quote!(partial.#overridden = false;)
    });
    let duplicate = rejects_duplicate(cli, field).then(|| {
        let duplicated = format_ident!("__duplicated_{}", ident);
        if has_negate(field) {
            let negated = format_ident!("__negated_{}", ident);
            // For a global the question is asked per level, exactly as in the arm
            // below: clap accepts `--colour sub --colour` when `--colour` is global
            // and negatable just as when it is plain.
            let (guard, mark) = if duplicates_per_level(cli, field) {
                let here = format_ident!("__here_{}", ident);
                (quote!(partial.#here), quote!(partial.#here = true;))
            } else {
                (quote!(partial.#given), TokenStream::new())
            };
            quote! {
                if #guard {
                    // The positive and negative spellings override one another: the
                    // last of `--color --no-color` wins just like an explicit
                    // `overrides` pair. Repeating the same spelling is still an error.
                    partial.#duplicated |= partial.#negated == negated;
                }
                #mark
                partial.#negated = negated;
            }
        } else if duplicates_per_level(cli, field) {
            let here = format_ident!("__here_{}", ident);
            quote! {
                if partial.#here {
                    partial.#duplicated = true;
                }
                partial.#here = true;
            }
        } else {
            quote! {
                if partial.#given {
                    partial.#duplicated = true;
                }
            }
        }
    });
    let body = flag_binding_body(field);
    let remember_invalid_choice = remember_invalid_flag_choice(field);
    let table = format_ident!("FLAG_{i}");
    quote! {
        // The key gets us to the right arm in one jump; the identity check makes a
        // collision harmless rather than wrong. Two identical declarations in
        // different modules hash alike — a macro cannot see a module path — and
        // without this, one command's flag would fill another's field. `static` items
        // have distinct addresses, so this is exact.
        #key if ::core::ptr::eq(*flag, &#table) => {
            #duplicate
            #remember_invalid_choice
            #body
            partial.#given = true;
            #direct
            // Given again after having lost: it is standing once more, which matters
            // when the flags alternate — `--include a --all --include b`.
            #undisplaced
            // Whatever this flag displaces, undone here rather than after the parse:
            // `overrides` is about which of two flags came last, and the token that
            // just arrived is the last one so far.
            #(#displaced)*
            true
        }
    }
}

fn tracks_invalid_choice(field: &Field) -> bool {
    (!field.choices.is_empty() || field.value_enum) && !field.allow_unknown_choices
}

/// Whether this field's partial has to remember which variable filled it.
///
/// Only a field with a deprecated alias: for every other field the answer could not be
/// interesting, since every name it accepts is a current one.
fn tracks_deprecated_env(field: &Field) -> bool {
    !field.deprecated_env.is_empty()
}

fn deprecated_env_ident(field: &Field) -> proc_macro2::Ident {
    format_ident!("__deprecated_env_{}", field.ident)
}

/// Whether using this field at all is something to warn about.
fn tracks_deprecated(field: &Field) -> bool {
    field.deprecated.is_some()
        || field.deprecated_warn_at.is_some()
        || field.deprecated_remove_at.is_some()
}

fn accepted_choices(field: &Field) -> TokenStream {
    match (field.value_enum, field.value_ty.as_ref()) {
        (true, Some(ty)) => quote!(<#ty as usage_argv::spec::ValueEnum>::ACCEPTED_CHOICES),
        _ => {
            let choices = &field.choices;
            quote!(&[#(#choices),*])
        }
    }
}

fn choice_ignore_case(field: &Field) -> TokenStream {
    match (field.value_enum, field.value_ty.as_ref()) {
        (true, Some(ty)) => quote!(<#ty as usage_argv::spec::ValueEnum>::IGNORE_CASE),
        _ => quote!(false),
    }
}

fn remember_invalid_flag_choice(field: &Field) -> TokenStream {
    if !tracks_invalid_choice(field) {
        return TokenStream::new();
    }
    let invalid = format_ident!("__invalid_choice_{}", field.ident);
    let accepted = accepted_choices(field);
    let ignore_case = choice_ignore_case(field);
    let reset = (!matches!(field.shape, Shape::Many)).then(|| quote!(partial.#invalid = false;));
    let check = quote! {
        if let ::std::result::Result::Ok(__usage_choice_text) =
            ::std::str::from_utf8(__usage_choice_value)
        {
            partial.#invalid |= !usage_argv::spec::choice_matches(
                #accepted,
                __usage_choice_text,
                #ignore_case,
            );
        }
    };
    match field.delimiter {
        Some(delimiter) => {
            let byte =
                u8::try_from(u32::from(delimiter)).expect("the model rejects non-ASCII delimiters");
            quote! {
                #reset
                if let ::std::option::Option::Some(__usage_choice_value) = value {
                    for __usage_choice_value in
                        __usage_choice_value.split(|byte| *byte == #byte)
                    {
                        #check
                    }
                }
            }
        }
        None => quote! {
            #reset
            if let ::std::option::Option::Some(__usage_choice_value) = value {
                #check
            }
        },
    }
}

/// Assign one flag's value without changing the ledgers used by validation.
///
/// Ordinary occurrences wrap this with given/duplicate/relationship bookkeeping. A child
/// redeclaration mirrored into an ancestor needs only this part: clap exposes the value through
/// both typed fields, but the spelling still belongs to the child's declaration and must not
/// acquire the ancestor's `exclusive`, `overrides`, or duplicate policy.
fn flag_binding_body(field: &Field) -> TokenStream {
    let ident = &field.ident;
    match field.shape {
        // `negated` is what distinguishes `--color` from `--no-color`.
        Shape::Bool if field.bool_value => quote! {
            partial.#ident = match value {
                Some(b"true") => !negated,
                Some(b"false") => negated,
                // The binding parser validates explicit boolean values for this declaration.
                // A child may redeclare the same global identity with a non-boolean value;
                // mirroring that event must leave this incompatible ancestor alone.
                Some(_) => return false,
                None => !negated,
            };
        },
        Shape::Bool => quote!(partial.#ident = !negated;),
        // Saturating, because a `u8` field given 256 occurrences would otherwise
        // panic in debug and wrap to zero in release.
        Shape::Count => quote!(partial.#ident = partial.#ident.saturating_add(1);),
        Shape::Optional if field.optional_value_type => quote! {
            partial.#ident = value.map(__usage_text);
        },
        Shape::Optional => quote! {
            partial.#ident = ::std::option::Option::Some(__usage_value_text(value));
        },
        Shape::Required => quote!(partial.#ident = __usage_value_text(value);),
        Shape::Many => match field.delimiter {
            Some(delimiter) => {
                let byte = u8::try_from(u32::from(delimiter))
                    .expect("the model rejects non-ASCII delimiters");
                quote! {
                    let value = __usage_value_text(value);
                    for part in value.split(|b| *b == #byte) {
                        partial.#ident.push(part.to_vec());
                    }
                }
            }
            None => quote!(partial.#ident.push(__usage_value_text(value));),
        },
    }
}

/// The marker needed when a global can receive a child's redeclared value.
fn mirrored_global_ident(field: &Field) -> Option<proc_macro2::Ident> {
    matches!(field.kind, Kind::Flag { global: true, .. })
        .then(|| format_ident!("__mirrored_{}", field.ident))
}

/// Whether this field directly invoked policy declared on this command.
fn policy_given(field: &Field) -> TokenStream {
    let given = format_ident!("__given_{}", field.ident);
    match mirrored_global_ident(field) {
        Some(mirrored) => quote!(partial.#given && !partial.#mirrored),
        None => quote!(partial.#given),
    }
}

/// Whether this field has a value supplied by argv or an environment fallback.
///
/// Unlike [`policy_given`], this includes a child redeclaration mirrored into a global.
/// Such a value does not invoke policy declared on the ancestor, but it can satisfy a
/// requirement imposed by a different, directly given field.
fn semantic_given(field: &Field) -> TokenStream {
    let given = format_ident!("__given_{}", field.ident);
    quote!(partial.#given)
}

fn view_policy_given(field: &Field) -> TokenStream {
    let given = policy_given(field);
    let active = view_field_active(field);
    quote!((#active) && (#given))
}

/// The local holding what the caller already had for this field, on an update.
///
/// A `bool` for an ordinary field, and the nested value itself — as an `Option<&T>` — for a
/// flattened group or a subcommand, since those answer for their own fields.
fn standing_ident(field: &Field) -> proc_macro2::Ident {
    format_ident!("__usage_standing_{}", field.ident)
}

/// Whether a value the caller already holds counts as present for this field.
///
/// Read from the built struct rather than from a partial, because that is all an update has:
/// a parse cannot be run backwards through `FromStr`, so the bytes are gone. Presence is
/// therefore what the type itself can answer — a filled `Option`, a collection with items, a
/// set switch — and a plain value is always present, which is what makes a standing `String`
/// satisfy required-ness.
///
/// `None` for a field with nothing to answer: a skipped field is not parsed, and a flattened
/// group answers for its own fields through its own expansion.
fn standing_presence(field: &Field) -> Option<TokenStream> {
    let ident = &field.ident;
    match &field.kind {
        Kind::Skip | Kind::Flatten { .. } => None,
        Kind::Clause { .. } => Some(quote!(!__usage_s.#ident.is_empty())),
        Kind::ArgGroup { multiple: true, .. } => Some(quote!(!__usage_s.#ident.is_empty())),
        Kind::ArgGroup { optional, .. } | Kind::Subcommand { optional, .. } => Some(if *optional {
            quote!(__usage_s.#ident.is_some())
        } else {
            quote!(true)
        }),
        Kind::Flag { .. } | Kind::Arg { .. } => Some(match field.shape {
            Shape::Bool => quote!(__usage_s.#ident),
            // Name the field's type: `Default::default()` alone is ambiguous when an
            // adopter also brings `serde_json::Value`'s `PartialEq<u8>` into scope
            // (hk's `verbose: u8` count under a workspace that pulls serde_json).
            Shape::Count => {
                let ty = &field.ty;
                quote!(__usage_s.#ident != <#ty as ::std::default::Default>::default())
            }
            Shape::Optional => quote!(__usage_s.#ident.is_some()),
            // Nowhere to put "absent", so the field always holds something. The same
            // reading of the type that makes it required in the first place.
            Shape::Required => quote!(true),
            Shape::Many if field.optional_collection => quote!(__usage_s.#ident.is_some()),
            Shape::Many => quote!(!__usage_s.#ident.is_empty()),
        }),
    }
}

/// What the caller already had, as locals every generated check can read.
///
/// One body serves both entry points: `__usage_standing` is `None` for an ordinary parse, so
/// each of these folds to `false` and the checks below are the ones that were always
/// generated. A second, update-only copy of `check` would double the largest function a CLI
/// generates to serve an entry point most of them never call.
///
/// The names start with an underscore, so a command whose checks ask about none of them does
/// not leave an unused local in the adopter's crate, where nobody can silence it.
fn standing_locals(cli: &Cli) -> TokenStream {
    let locals = cli.fields.iter().filter_map(|field| {
        let name = standing_ident(field);
        let ident = &field.ident;
        Some(match &field.kind {
            Kind::Skip => return None,
            Kind::Flatten { .. } => quote! {
                let #name = __usage_standing.map(|__usage_s| &__usage_s.#ident);
            },
            Kind::Clause { .. } => quote! {
                let #name = __usage_standing.map(|__usage_s| &__usage_s.#ident);
            },
            // The nested value itself, so a parent can ask which member stands — a bool
            // would answer required-ness and nothing about `--json` vs `--yaml`.
            Kind::ArgGroup { multiple: true, .. } => quote! {
                let #name = __usage_standing.map(|__usage_s| &__usage_s.#ident);
            },
            Kind::ArgGroup { optional: true, .. } | Kind::Subcommand { optional: true, .. } => {
                quote! {
                    let #name = __usage_standing.and_then(|__usage_s| __usage_s.#ident.as_ref());
                }
            }
            Kind::ArgGroup {
                optional: false,
                multiple: false,
                ..
            }
            | Kind::Subcommand {
                optional: false, ..
            } => quote! {
                let #name = __usage_standing.map(|__usage_s| &__usage_s.#ident);
            },
            _ => {
                let present = standing_presence(field)?;
                quote!(let #name = __usage_standing.is_some_and(|__usage_s| #present);)
            }
        })
    });
    quote!(#(#locals)*)
}

/// The `bool` saying whether this field already had a value, when it can be asked.
fn standing_flag(field: &Field) -> Option<TokenStream> {
    let name = standing_ident(field);
    match &field.kind {
        Kind::Skip | Kind::Flatten { .. } => None,
        Kind::ArgGroup { .. } | Kind::Subcommand { .. } => Some(quote!(#name.is_some())),
        _ => standing_presence(field).map(|_| quote!(#name)),
    }
}

/// A presence test that also counts a value the caller already had.
fn given_or_standing(field: &Field, given: TokenStream) -> TokenStream {
    match standing_flag(field) {
        Some(standing) => quote!((#given || #standing)),
        None => given,
    }
}

/// `&& !__usage_standing_x`, for a fill or a complaint that a standing value answers.
fn unless_standing(field: &Field) -> TokenStream {
    match standing_flag(field) {
        Some(standing) => quote!(&& !#standing),
        None => quote!(),
    }
}

/// `&& !(...)`, skipping a check about what a value *is* when this argv supplied none.
///
/// A standing value is present but unreadable: an update holds the caller's typed value, not
/// the bytes it was parsed from, so a choice list or a validation expression has nothing to
/// judge. Only a required field needs saying — every other shape holds nothing at all when
/// nothing arrived, and these checks then iterate over nothing.
fn unless_standing_only(field: &Field) -> TokenStream {
    if field.shape != Shape::Required {
        return quote!();
    }
    match standing_flag(field) {
        Some(standing) => {
            let given = format_ident!("__given_{}", field.ident);
            quote!(&& !(#standing && !partial.#given))
        }
        None => quote!(),
    }
}

/// [`view_policy_given`], counting a value the caller already had.
fn standing_policy_given(field: &Field) -> TokenStream {
    given_or_standing(field, view_policy_given(field))
}

/// [`semantic_given`], counting a value the caller already had.
fn standing_semantic_given(field: &Field) -> TokenStream {
    given_or_standing(field, semantic_given(field))
}

/// Whether a root field belongs to the executable surface currently being parsed.
///
/// A view promotes a subcommand and carries only the root globals it names. The selected
/// subcommand is checked through its own generated module, where `__usage_view` is `None`;
/// this predicate therefore filters only policy declared on the omitted root surface.
fn view_field_active(field: &Field) -> TokenStream {
    let Kind::Flag {
        longs,
        hidden_longs,
        shorts,
        negate,
        global: true,
        ..
    } = &field.kind
    else {
        return quote!(__usage_view.is_none());
    };
    let long_selectors = longs
        .iter()
        .chain(hidden_longs)
        // The negation is a spelling of the same flag, and for a negative-only flag it is
        // the *only* one: leaving it out made the selector list empty, and an empty
        // `matches!` does not parse.
        .chain(negate.iter())
        .map(|long| format!("--{long}"));
    let short_selectors = shorts.iter().map(|short| format!("-{short}"));
    let selectors: Vec<String> = long_selectors.chain(short_selectors).collect();
    let named = if selectors.is_empty() {
        quote!(false)
    } else {
        quote! {
            __usage_view.globals.iter().any(|__usage_selector| {
                matches!(*__usage_selector, #(#selectors)|*)
            })
        }
    };
    quote! {
        match __usage_view {
            ::std::option::Option::None => true,
            ::std::option::Option::Some(__usage_view) => {
                __usage_view.all_globals || #named
            }
        }
    }
}

/// Whether a root field is carried into one declared executable view.
///
/// This is the compile-time counterpart of [`view_field_active`]. It is used when an error
/// needs a static slice containing only the group members that the selected view accepts.
fn field_active_in_view(field: &Field, view: &ViewDecl) -> bool {
    let Kind::Flag {
        longs,
        hidden_longs,
        shorts,
        negate,
        global: true,
        ..
    } = &field.kind
    else {
        return false;
    };
    view.all_globals
        || longs
            .iter()
            .chain(hidden_longs)
            .chain(negate.iter())
            .map(|long| format!("--{long}"))
            .chain(shorts.iter().map(|short| format!("-{short}")))
            .any(|selector| view.globals.contains(&selector))
}

/// Whether a repeat of this flag is only a duplicate *within one command*.
///
/// A `global` flag is in scope for every descendant, and clap lets it be given again on a
/// subcommand — the inner occurrence simply wins, which is what makes `mise -y install -y` a
/// line that works today. Repeating it at *one* level is still an error there, so the check
/// cannot simply be dropped: it has to be per level, which is what `__here_` records.
fn duplicates_per_level(cli: &Cli, field: &Field) -> bool {
    rejects_duplicate(cli, field) && matches!(field.kind, Kind::Flag { global: true, .. })
}

/// Clearing those markers, to run when a command word is read: descending starts a new level.
fn reset_per_level(cli: &Cli) -> TokenStream {
    let resets = cli
        .fields
        .iter()
        .filter(|f| duplicates_per_level(cli, f))
        .map(|f| {
            let here = format_ident!("__here_{}", f.ident);
            quote!(partial.#here = false;)
        });
    quote!(#(#resets)*)
}

/// Whether another occurrence is a command-line mistake rather than another value.
///
/// Counts and collections repeat by definition, and `var` explicitly opts a value-taking flag
/// into repetition. Every other flag is strict only when the command opts out of usage's
/// permissive `args_override_self` default. This is a post-binding question: the allocation-free
/// parser reports occurrences, and the generated command decides whether a second one is an
/// error. `differential.rs` pins the permissive default against clap's strict one.
fn rejects_duplicate(cli: &Cli, field: &Field) -> bool {
    (!cli.args_override_self || cli.composable)
        && matches!(field.kind, Kind::Flag { .. })
        && !matches!(field.shape, Shape::Count | Shape::Many)
        && !field.repeatable
}

/// Whether a boolean flag has a negative spelling that overrides its positive one.
fn has_negate(field: &Field) -> bool {
    matches!(
        &field.kind,
        Kind::Flag {
            negate: Some(_),
            ..
        }
    )
}

/// Undoing the flags a flag displaces, as statements to run once it has been bound.
///
/// Both directions. `overrides` is declared on one flag and holds between the two:
/// clap resolves `--file a --stdin` and `--stdin --file a` the same way whichever side
/// declared it, and so does usage-lib.
fn displacements(cli: &Cli, field: &Field) -> Vec<TokenStream> {
    let mut displacements: Vec<TokenStream> = displaced_by(cli, field)
        .into_iter()
        .map(|displaced| displace_statement(cli, displaced))
        .collect();
    for selector in field
        .overrides
        .iter()
        .filter(|selector| cli.field_for_selector(selector).is_none())
    {
        for flattened in &cli.fields {
            let Kind::Flatten { ty, .. } = &flattened.kind else {
                continue;
            };
            let ident = &flattened.ident;
            displacements.push(quote! {
                let _ = <#ty as usage_argv::spec::CommandArgs>::displace(
                    &mut partial.#ident,
                    #selector,
                );
            });
        }
        for grouped in &cli.fields {
            let Kind::ArgGroup { ty, .. } = &grouped.kind else {
                continue;
            };
            let ident = &grouped.ident;
            displacements.push(quote! {
                let _ = <#ty as usage_argv::spec::ArgGroup>::displace(
                    &mut partial.#ident,
                    #selector,
                );
            });
        }
    }
    displacements
}

fn displace_statement(cli: &Cli, field: &Field) -> TokenStream {
    let reset = reset_to_default(field);
    let given = format_ident!("__given_{}", field.ident);
    let overridden = format_ident!("__overridden_{}", field.ident);
    let duplicated = rejects_duplicate(cli, field).then(|| {
        let duplicated = format_ident!("__duplicated_{}", field.ident);
        quote!(partial.#duplicated = false;)
    });
    let mirrored = mirrored_global_ident(field).map(|mirrored| quote!(partial.#mirrored = false;));
    quote! {
        #reset
        partial.#given = false;
        #mirrored
        #duplicated
        // Remembered, not just cleared: without this the environment fallback
        // would refill the flag that lost and mark it given again, and a
        // displaced `String` would be reported missing. usage-lib keeps the
        // same set for the same reason.
        partial.#overridden = true;
    }
}

/// The fields a flag displaces, in both directions.
fn displaced_by<'a>(cli: &'a Cli, field: &Field) -> Vec<&'a Field> {
    let names = |target: &Field, selectors: &[String]| {
        selectors.iter().any(|selector| {
            cli.field_for_selector(selector)
                .is_some_and(|named| named.ident == target.ident)
        })
    };
    cli.fields
        .iter()
        .filter(|other| {
            other.ident != field.ident
                && (names(other, &field.overrides) || names(field, &other.overrides))
        })
        .collect()
}

/// Whether a field is on either side of an `overrides`, and so needs somewhere to
/// record that it lost.
fn is_displaceable(cli: &Cli, field: &Field) -> bool {
    (cli.composable && matches!(field.kind, Kind::Flag { .. }))
        || !field.overrides.is_empty()
        || !displaced_by(cli, field).is_empty()
}

fn arg_arm(i: usize, field: &Field) -> TokenStream {
    let key = key_ident("ARG", Some(i));
    let ident = &field.ident;
    let given = format_ident!("__given_{}", ident);
    let body = match field.shape {
        Shape::Many => match field.delimiter {
            Some(delimiter) => {
                let byte = u8::try_from(u32::from(delimiter))
                    .expect("the model rejects non-ASCII delimiters");
                quote! {
                    if delimit {
                        for part in value.split(|b| *b == #byte) {
                            partial.#ident.push(__usage_text(part));
                        }
                    } else {
                        partial.#ident.push(__usage_text(value));
                    }
                }
            }
            None => quote!(partial.#ident.push(__usage_text(value));),
        },
        Shape::Optional => quote! {
            partial.#ident = ::std::option::Option::Some(__usage_text(value));
        },
        _ => quote!(partial.#ident = __usage_text(value);),
    };
    let remember_invalid_choice = if tracks_invalid_choice(field) {
        let invalid = format_ident!("__invalid_choice_{}", field.ident);
        let accepted = accepted_choices(field);
        let ignore_case = choice_ignore_case(field);
        let reset =
            (!matches!(field.shape, Shape::Many)).then(|| quote!(partial.#invalid = false;));
        let check = quote! {
            if let ::std::result::Result::Ok(__usage_choice_text) =
                ::std::str::from_utf8(__usage_choice_value)
            {
                partial.#invalid |= !usage_argv::spec::choice_matches(
                    #accepted,
                    __usage_choice_text,
                    #ignore_case,
                );
            }
        };
        match field.delimiter {
            Some(delimiter) => {
                let byte = u8::try_from(u32::from(delimiter))
                    .expect("the model rejects non-ASCII delimiters");
                quote! {
                    #reset
                    if delimit {
                        for __usage_choice_value in value.split(|byte| *byte == #byte) {
                            #check
                        }
                    } else {
                        let __usage_choice_value = value;
                        #check
                    }
                }
            }
            None => quote! {
                #reset
                let __usage_choice_value = value;
                #check
            },
        }
    } else {
        TokenStream::new()
    };
    let table = format_ident!("ARG_{i}");
    quote! {
        #key if ::core::ptr::eq(*arg, &#table) => {
            #remember_invalid_choice
            #body
            partial.#given = true;
            true
        }
    }
}

fn option_str(value: Option<&str>) -> TokenStream {
    match value {
        Some(v) => quote!(::std::option::Option::Some(#v)),
        None => quote!(::std::option::Option::None),
    }
}

/// The `examples` slice for a command's metadata.
///
/// A constant expression, so it promotes into the `static CommandMeta` beside the rest
/// of the cold tables; nothing here is reached by a parse that succeeds.
fn examples_table(examples: &[ExampleDecl]) -> TokenStream {
    let entries = examples.iter().map(|example| {
        let code = &example.code;
        let header = option_expr(example.header.as_ref());
        let help = option_expr(example.help.as_ref());
        quote! {
            usage_argv::spec::Example {
                code: #code,
                header: #header,
                help: #help,
            }
        }
    });
    quote!(&[#(#entries),*])
}

/// The `headings` slice for a command's metadata.
///
/// Cold like the examples beside it: a section's prose is read when a page is rendered or a
/// spec written, never by a parse.
fn headings_table(headings: &[HeadingDecl]) -> TokenStream {
    let entries = headings.iter().map(|heading| {
        let title = &heading.title;
        let help = &heading.help;
        quote! {
            usage_argv::spec::HeadingMeta {
                title: #title,
                help: #help,
            }
        }
    });
    quote!(&[#(#entries),*])
}

/// What a command's `output`, `select` and `exit_code` declarations become in its
/// `CommandMeta`, plus the schema functions those refer to.
///
/// Shared by the root and the per-`Args` emission because the three fields are identical
/// on both; only where they are spliced differs.
struct OutputTokens {
    /// `fn` items, declared beside the metas because a `static` cannot call anything.
    decls: Vec<TokenStream>,
    outputs: TokenStream,
    select: TokenStream,
    exit_codes: TokenStream,
}

fn output_tokens(cli: &Cli) -> OutputTokens {
    let mut decls = Vec::new();
    let outputs: Vec<TokenStream> = cli
        .outputs
        .iter()
        .enumerate()
        .map(|(i, output)| {
            let name = &output.name;
            let media_type = option_str(output.media_type.as_deref());
            let framing = match output.framing.as_str() {
                "json" => quote!(usage_argv::spec::Framing::Json),
                "jsonl" => quote!(usage_argv::spec::Framing::Jsonl),
                _ => quote!(usage_argv::spec::Framing::Text),
            };
            let help = option_str(output.help.as_deref());
            let default = output.default;
            let hide = output.hide;
            let select = option_str(output.select.as_deref());
            // A schema is a `fn` pointer rather than a string because `schema_for!` is a
            // call and this initializes a `static`. The literal spelling goes through the
            // same pointer so every consumer reads one field.
            let schema_fn = match &output.schema {
                None => quote!(::std::option::Option::None),
                Some(SchemaSource::Function(path)) => {
                    quote!(::std::option::Option::Some(#path))
                }
                Some(source) => {
                    let wrapper = format_ident!("__usage_output_schema_{i}");
                    let body = match source {
                        SchemaSource::Literal(text) => {
                            quote!(::std::string::ToString::to_string(#text))
                        }
                        SchemaSource::Type(ty) => {
                            let schemars = schemars_path();
                            // Compact rather than pretty: the emitted KDL is compared to
                            // usage-lib's byte for byte, and a value with no newline in it
                            // cannot disagree about how newlines are written.
                            quote!(::std::string::ToString::to_string(
                                &#schemars::schema_for!(#ty)
                            ))
                        }
                        SchemaSource::Function(_) => unreachable!("handled above"),
                    };
                    decls.push(quote! {
                        fn #wrapper() -> ::std::string::String { #body }
                    });
                    quote!(::std::option::Option::Some(#wrapper))
                }
            };
            quote! {
                usage_argv::spec::OutputMeta {
                    name: #name,
                    media_type: #media_type,
                    framing: #framing,
                    help: #help,
                    default: #default,
                    hide: #hide,
                    select: #select,
                    schema: ::std::option::Option::None,
                    schema_fn: #schema_fn,
                }
            }
        })
        .collect();
    let exit_codes: Vec<TokenStream> = cli
        .exit_codes
        .iter()
        .map(|exit_code| {
            let code = exit_code.code;
            let help = &exit_code.help;
            quote! {
                usage_argv::spec::ExitCodeMeta { code: #code, help: #help }
            }
        })
        .collect();
    OutputTokens {
        decls,
        outputs: quote!(&[#(#outputs),*]),
        select: option_str(cli.select.as_deref()),
        exit_codes: quote!(&[#(#exit_codes),*]),
    }
}

fn option_expr(value: Option<&TokenStream>) -> TokenStream {
    match value {
        Some(v) => quote!(::std::option::Option::Some(#v)),
        None => quote!(::std::option::Option::None),
    }
}

fn option_usize(value: Option<usize>) -> TokenStream {
    match value {
        Some(v) => quote!(::std::option::Option::Some(#v)),
        None => quote!(::std::option::Option::None),
    }
}

/// The presence summaries a parent needs to enforce exclusivity across a flattened
/// `CommandArgs` boundary.
fn presence_methods(cli: &Cli) -> TokenStream {
    let direct_given = cli.fields.iter().filter_map(|field| {
        if matches!(
            field.kind,
            Kind::Flatten { .. }
                | Kind::ArgGroup { .. }
                | Kind::Clause { .. }
                | Kind::Subcommand { .. }
                | Kind::Skip
        ) {
            return None;
        }
        let given = policy_given(field);
        let name = &field.name;
        Some(quote! {
            if #given {
                return ::std::option::Option::Some(#name);
            }
        })
    });
    let flattened_given = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(name) =
                <#ty as usage_argv::spec::CommandArgs>::any_given(&partial.#ident)
            {
                return ::std::option::Option::Some(name);
            }
        })
    });
    let grouped_given = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(name) =
                <#ty as usage_argv::spec::ArgGroup>::any_given(&partial.#ident)
            {
                return ::std::option::Option::Some(name);
            }
        })
    });
    let selected = cli.fields.iter().find_map(|field| {
        if !matches!(field.kind, Kind::Subcommand { .. }) {
            return None;
        }
        let name = &field.name;
        Some(quote! {
            if partial.__usage_selected.is_some() {
                return ::std::option::Option::Some(#name);
            }
        })
    });
    let direct_exclusive = cli.fields.iter().filter_map(|field| {
        if !field.exclusive {
            return None;
        }
        let given = policy_given(field);
        let name = &field.name;
        Some(quote! {
            if #given {
                return ::std::option::Option::Some(#name);
            }
        })
    });
    let flattened_exclusive = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(name) =
                <#ty as usage_argv::spec::CommandArgs>::exclusive_given(&partial.#ident)
            {
                return ::std::option::Option::Some(name);
            }
        })
    });
    let selected_exclusive = cli.fields.iter().find_map(|field| {
        let Kind::Subcommand { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            if let ::std::option::Option::Some(name) =
                <#ty as usage_argv::spec::Subcommands>::exclusive_given(
                    &partial.__usage_sub,
                    partial.__usage_selected,
                )
            {
                return ::std::option::Option::Some(name);
            }
        })
    });

    quote! {
        fn any_given(partial: &Self::Partial) -> ::std::option::Option<&'static str> {
            #(#direct_given)*
            #(#flattened_given)*
            #(#grouped_given)*
            #selected
            ::std::option::Option::None
        }

        fn exclusive_given(partial: &Self::Partial) -> ::std::option::Option<&'static str> {
            #(#direct_exclusive)*
            #(#flattened_exclusive)*
            #selected_exclusive
            ::std::option::Option::None
        }

        fn argument_state(
            partial: &Self::Partial,
            selector: &str,
        ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
            argument_state(partial, selector)
        }

        fn canonical_selector(selector: &str) -> ::std::option::Option<&'static str> {
            canonical_selector(selector)
        }

        fn argument_matches(
            partial: &Self::Partial,
            selector: &str,
            value: &[u8],
        ) -> ::std::option::Option<bool> {
            argument_matches(partial, selector, value)
        }

        fn standing_state(
            standing: &Self,
            selector: &str,
        ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
            standing_state(standing, selector)
        }

        fn standing_matches(
            standing: &Self,
            selector: &str,
            value: &[u8],
        ) -> ::std::option::Option<bool> {
            standing_matches(standing, selector, value)
        }

        fn displace(partial: &mut Self::Partial, selector: &str) -> bool {
            displace(partial, selector)
        }

        fn event_matches(
            event: &usage_argv::Event<'_, '_, '_>,
            selector: &str,
        ) -> bool {
            event_matches(event, selector)
        }
    }
}

fn field_selectors(field: &Field) -> Vec<String> {
    match &field.kind {
        Kind::Flag {
            longs,
            shorts,
            negate,
            ..
        } => longs
            .iter()
            .map(|long| format!("--{long}"))
            .chain(shorts.iter().map(|short| format!("-{short}")))
            .chain(negate.iter().map(|long| format!("--{long}")))
            .collect(),
        Kind::Arg { .. } => {
            let inferred = to_kebab(&field.ident.to_string());
            if inferred == field.name {
                vec![field.name.clone()]
            } else {
                vec![field.name.clone(), inferred]
            }
        }
        _ => Vec::new(),
    }
}

/// Selector lookup composed across flattened argument groups.
///
/// A parent cannot inspect another derive expansion's fields, so the flattened type answers
/// through `CommandArgs`. Keeping the lookup beside the partial avoids building a dynamic
/// command graph or allocating on the successful parse path.
fn argument_lookup_functions(cli: &Cli) -> TokenStream {
    let args = &cli.ident;
    let canonical_arms = cli.fields.iter().filter_map(|field| {
        let canonical = Cli::selector_for_field(field)?;
        let selectors = field_selectors(field);
        Some(quote!(#(#selectors)|* => return ::std::option::Option::Some(#canonical),))
    });
    let canonical_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            if let ::std::option::Option::Some(canonical) =
                <#ty as usage_argv::spec::CommandArgs>::canonical_selector(selector)
            {
                return ::std::option::Option::Some(canonical);
            }
        })
    });
    let canonical_clause = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            if let ::std::option::Option::Some(canonical) =
                <#ty as usage_argv::spec::CommandArgs>::canonical_selector(selector)
            {
                return ::std::option::Option::Some(canonical);
            }
        })
    });
    let state_arms = cli.fields.iter().filter_map(|field| {
        if matches!(
            field.kind,
            Kind::Flatten { .. }
                | Kind::ArgGroup { .. }
                | Kind::Clause { .. }
                | Kind::Subcommand { .. }
                | Kind::Skip
        ) {
            return None;
        }
        let selectors = field_selectors(field);
        let given = policy_given(field);
        let satisfied = semantic_given(field);
        let name = &field.name;
        // Look through conditional defaults as well as unconditional ones. This lookup
        // runs after `apply_defaults` during relationship validation, so a predicate
        // that filled the field is still observable even though defaults deliberately
        // do not set `__given_*`.
        let defaulted = field.has_default();
        let conditionally_defaulted =
            default_if_would_apply(cli, field, Lookup::Module).unwrap_or_else(|| quote!(false));
        Some(quote! {
            #(#selectors)|* => return ::std::option::Option::Some(
                usage_argv::spec::ArgumentState {
                    name: #name,
                    given: #given,
                    satisfied: #satisfied || #defaulted || (#conditionally_defaulted),
                },
            ),
        })
    });
    let state_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(state) =
                <#ty as usage_argv::spec::CommandArgs>::argument_state(
                    &partial.#ident,
                    selector,
                )
            {
                return ::std::option::Option::Some(state);
            }
        })
    });
    let state_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(state) =
                <#ty as usage_argv::spec::ArgGroup>::argument_state(
                    &partial.#ident,
                    selector,
                )
            {
                return ::std::option::Option::Some(state);
            }
        })
    });
    let state_clause = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let current = format_ident!("__usage_current_{}", ident);
        Some(quote! {
            let mut __usage_clause_state = ::std::option::Option::None;
            for __usage_instance in partial.#ident.iter().chain(::core::iter::once(&partial.#current)) {
                if let ::std::option::Option::Some(state) =
                    <#ty as usage_argv::spec::CommandArgs>::argument_state(
                        __usage_instance,
                        selector,
                    )
                {
                    if state.given || state.satisfied {
                        return ::std::option::Option::Some(state);
                    }
                    __usage_clause_state = ::std::option::Option::Some(state);
                }
            }
            if __usage_clause_state.is_some() {
                return __usage_clause_state;
            }
        })
    });
    let match_arms = cli.fields.iter().filter_map(|field| {
        if matches!(
            field.kind,
            Kind::Flatten { .. }
                | Kind::ArgGroup { .. }
                | Kind::Clause { .. }
                | Kind::Subcommand { .. }
                | Kind::Skip
        ) {
            return None;
        }
        let selectors = field_selectors(field);
        let ident = &field.ident;
        let given = policy_given(field);
        let matches = match field.shape {
            Shape::Optional => quote!(partial.#ident.as_deref().is_some_and(|v| v == value)),
            Shape::Required => quote!(partial.#ident.as_slice() == value),
            Shape::Many => quote!(partial.#ident.iter().any(|v| v.as_slice() == value)),
            Shape::Bool => quote!(
                (value == b"true" && partial.#ident) || (value == b"false" && !partial.#ident)
            ),
            Shape::Count => quote!(
                (value == b"true" && partial.#ident > 0)
                    || (value == b"false" && partial.#ident == 0)
            ),
        };
        Some(quote!(#(#selectors)|* => return ::std::option::Option::Some(#given && #matches),))
    });
    let match_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(matches) =
                <#ty as usage_argv::spec::CommandArgs>::argument_matches(
                    &partial.#ident,
                    selector,
                    value,
                )
            {
                return ::std::option::Option::Some(matches);
            }
        })
    });
    let match_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(matches) =
                <#ty as usage_argv::spec::ArgGroup>::argument_matches(
                    &partial.#ident,
                    selector,
                    value,
                )
            {
                return ::std::option::Option::Some(matches);
            }
        })
    });
    let match_clause = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let current = format_ident!("__usage_current_{}", ident);
        Some(quote! {
            let mut __usage_clause_recognized = false;
            for __usage_instance in partial.#ident.iter().chain(::core::iter::once(&partial.#current)) {
                match <#ty as usage_argv::spec::CommandArgs>::argument_matches(
                    __usage_instance,
                    selector,
                    value,
                ) {
                    ::std::option::Option::Some(true) => {
                        return ::std::option::Option::Some(true);
                    }
                    ::std::option::Option::Some(false) => {
                        __usage_clause_recognized = true;
                    }
                    ::std::option::Option::None => {}
                }
            }
            if __usage_clause_recognized {
                return ::std::option::Option::Some(false);
            }
        })
    });
    let standing_state_arms = cli.fields.iter().filter_map(|field| {
        if matches!(
            field.kind,
            Kind::Flatten { .. }
                | Kind::ArgGroup { .. }
                | Kind::Clause { .. }
                | Kind::Subcommand { .. }
                | Kind::Skip
        ) {
            return None;
        }
        let selectors = field_selectors(field);
        let present = standing_presence(field)?;
        let name = &field.name;
        Some(quote! {
            #(#selectors)|* => {
                let given = #present;
                return ::std::option::Option::Some(usage_argv::spec::ArgumentState {
                    name: #name,
                    given,
                    satisfied: given,
                });
            }
        })
    });
    let standing_state_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(state) =
                <#ty as usage_argv::spec::CommandArgs>::standing_state(
                    &__usage_s.#ident,
                    selector,
                )
            {
                return ::std::option::Option::Some(state);
            }
        })
    });
    let standing_state_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup {
            ty,
            multiple,
            optional,
            ..
        } = &field.kind
        else {
            return None;
        };
        let ident = &field.ident;
        let values = if *multiple || *optional {
            quote!(__usage_s.#ident.iter())
        } else {
            quote!(::core::iter::once(&__usage_s.#ident))
        };
        Some(quote! {
            let mut __usage_standing_group_state = ::std::option::Option::None;
            for __usage_member in #values {
                if let ::std::option::Option::Some(state) =
                    <#ty as usage_argv::spec::ArgGroup>::standing_state(
                        __usage_member,
                        selector,
                    )
                {
                    if state.given || state.satisfied {
                        return ::std::option::Option::Some(state);
                    }
                    __usage_standing_group_state = ::std::option::Option::Some(state);
                }
            }
            if __usage_standing_group_state.is_some() {
                return __usage_standing_group_state;
            }
        })
    });
    let standing_state_clause = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            let mut __usage_standing_clause_state = ::std::option::Option::None;
            for __usage_instance in &__usage_s.#ident {
                if let ::std::option::Option::Some(state) =
                    <#ty as usage_argv::spec::CommandArgs>::standing_state(
                        __usage_instance,
                        selector,
                    )
                {
                    if state.given || state.satisfied {
                        return ::std::option::Option::Some(state);
                    }
                    __usage_standing_clause_state = ::std::option::Option::Some(state);
                }
            }
            if __usage_standing_clause_state.is_some() {
                return __usage_standing_clause_state;
            }
        })
    });
    let standing_match_arms = cli.fields.iter().filter_map(|field| {
        if matches!(
            field.kind,
            Kind::Flatten { .. }
                | Kind::ArgGroup { .. }
                | Kind::Clause { .. }
                | Kind::Subcommand { .. }
                | Kind::Skip
        ) {
            return None;
        }
        let selectors = field_selectors(field);
        let ident = &field.ident;
        let matches = match field.shape {
            Shape::Bool => quote!(
                (value == b"true" && __usage_s.#ident)
                    || (value == b"false" && !__usage_s.#ident)
            ),
            Shape::Count => quote!(
                (value == b"true" && __usage_s.#ident > 0)
                    || (value == b"false" && __usage_s.#ident == 0)
            ),
            Shape::Optional | Shape::Required | Shape::Many => quote!(false),
        };
        Some(quote!(#(#selectors)|* => return ::std::option::Option::Some(#matches),))
    });
    let standing_match_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if let ::std::option::Option::Some(matches) =
                <#ty as usage_argv::spec::CommandArgs>::standing_matches(
                    &__usage_s.#ident,
                    selector,
                    value,
                )
            {
                return ::std::option::Option::Some(matches);
            }
        })
    });
    let standing_match_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup {
            ty,
            multiple,
            optional,
            ..
        } = &field.kind
        else {
            return None;
        };
        let ident = &field.ident;
        let values = if *multiple || *optional {
            quote!(__usage_s.#ident.iter())
        } else {
            quote!(::core::iter::once(&__usage_s.#ident))
        };
        Some(quote! {
            let mut __usage_standing_group_recognized = false;
            for __usage_member in #values {
                match <#ty as usage_argv::spec::ArgGroup>::standing_matches(
                    __usage_member,
                    selector,
                    value,
                ) {
                    ::std::option::Option::Some(true) => {
                        return ::std::option::Option::Some(true);
                    }
                    ::std::option::Option::Some(false) => {
                        __usage_standing_group_recognized = true;
                    }
                    ::std::option::Option::None => {}
                }
            }
            if __usage_standing_group_recognized {
                return ::std::option::Option::Some(false);
            }
        })
    });
    let standing_match_clause = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            let mut __usage_standing_clause_recognized = false;
            for __usage_instance in &__usage_s.#ident {
                match <#ty as usage_argv::spec::CommandArgs>::standing_matches(
                    __usage_instance,
                    selector,
                    value,
                ) {
                    ::std::option::Option::Some(true) => {
                        return ::std::option::Option::Some(true);
                    }
                    ::std::option::Option::Some(false) => {
                        __usage_standing_clause_recognized = true;
                    }
                    ::std::option::Option::None => {}
                }
            }
            if __usage_standing_clause_recognized {
                return ::std::option::Option::Some(false);
            }
        })
    });
    let displace_arms = cli.fields.iter().filter_map(|field| {
        if !matches!(field.kind, Kind::Flag { .. }) || !is_displaceable(cli, field) {
            return None;
        }
        let selectors = field_selectors(field);
        let statement = displace_statement(cli, field);
        Some(quote! {
            #(#selectors)|* => {
                #statement
                return true;
            }
        })
    });
    let displace_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if <#ty as usage_argv::spec::CommandArgs>::displace(
                &mut partial.#ident,
                selector,
            ) {
                return true;
            }
        })
    });
    let displace_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            if <#ty as usage_argv::spec::ArgGroup>::displace(
                &mut partial.#ident,
                selector,
            ) {
                return true;
            }
        })
    });
    let flags: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|field| matches!(field.kind, Kind::Flag { .. }))
        .collect();
    let event_arms = flags.iter().enumerate().map(|(i, field)| {
        let key = key_ident("FLAG", Some(i));
        let table = format_ident!("FLAG_{i}");
        let selectors = field_selectors(field);
        quote! {
            #key if ::core::ptr::eq(*flag, &#table) => {
                matches!(selector, #(#selectors)|*)
            }
        }
    });
    let event_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            if <#ty as usage_argv::spec::CommandArgs>::event_matches(event, selector) {
                return true;
            }
        })
    });
    let event_grouped = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            if <#ty as usage_argv::spec::ArgGroup>::event_matches(event, selector) {
                return true;
            }
        })
    });
    quote! {
        #[allow(dead_code)]
        pub fn canonical_selector(selector: &str) -> ::std::option::Option<&'static str> {
            match selector {
                #(#canonical_arms)*
                _ => {}
            }
            #(#canonical_flattened)*
            #(#canonical_clause)*
            ::std::option::Option::None
        }

        #[allow(dead_code)]
        pub fn argument_state(
            partial: &Partial,
            selector: &str,
        ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
            match selector {
                #(#state_arms)*
                _ => {}
            }
            #(#state_flattened)*
            #(#state_grouped)*
            #(#state_clause)*
            ::std::option::Option::None
        }

        #[allow(dead_code)]
        pub fn argument_matches(
            partial: &Partial,
            selector: &str,
            value: &[u8],
        ) -> ::std::option::Option<bool> {
            match selector {
                #(#match_arms)*
                _ => {}
            }
            #(#match_flattened)*
            #(#match_grouped)*
            #(#match_clause)*
            ::std::option::Option::None
        }

        #[allow(dead_code)]
        pub fn standing_state(
            __usage_s: &#args,
            selector: &str,
        ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
            match selector {
                #(#standing_state_arms)*
                _ => {}
            }
            #(#standing_state_flattened)*
            #(#standing_state_grouped)*
            #(#standing_state_clause)*
            ::std::option::Option::None
        }

        #[allow(dead_code)]
        pub fn standing_matches(
            __usage_s: &#args,
            selector: &str,
            value: &[u8],
        ) -> ::std::option::Option<bool> {
            match selector {
                #(#standing_match_arms)*
                _ => {}
            }
            #(#standing_match_flattened)*
            #(#standing_match_grouped)*
            #(#standing_match_clause)*
            ::std::option::Option::None
        }

        #[allow(dead_code)]
        pub fn displace(partial: &mut Partial, selector: &str) -> bool {
            match selector {
                #(#displace_arms)*
                _ => {}
            }
            #(#displace_flattened)*
            #(#displace_grouped)*
            false
        }

        #[allow(dead_code)]
        pub fn event_matches(
            event: &usage_argv::Event<'_, '_, '_>,
            selector: &str,
        ) -> bool {
            if let usage_argv::Event::Flag { flag, .. } = event {
                let matched = match flag.key {
                    #(#event_arms)*
                    _ => false,
                };
                if matched {
                    return true;
                }
            }
            #(#event_flattened)*
            #(#event_grouped)*
            false
        }
    }
}

/// The struct that collects values while parsing.
///
/// One field per declared field, of the type that accumulates it: a `bool` for a
/// switch, a `Vec` for something repeatable, and so on. It exists so the same
/// generated `apply` serves a root command and a subcommand's arguments — a
/// subcommand cannot use locals in the root's parse function, because the root
/// cannot see its fields.
fn partial_struct(cli: &Cli) -> TokenStream {
    let sub = subcommand_parts(cli)
        .map(|p| p.partial_fields)
        .unwrap_or_default();
    let fields = cli.fields.iter().filter_map(|f| {
        if matches!(f.kind, Kind::Subcommand { .. } | Kind::Skip) {
            // Its values live in the enum's own partial. A skipped field is not parsed
            // at all, so it has nothing to accumulate.
            return None;
        }
        // A flattened struct accumulates into its own partial, whose shape only its derive
        // knows — reached through the trait, like everything else about it.
        if let Kind::Flatten { ty, .. } = &f.kind {
            let ident = &f.ident;
            return Some(quote! {
                pub #ident: <#ty as usage_argv::spec::CommandArgs>::Partial,
            });
        }
        // An argument group accumulates which of its members were given, reached through its
        // own trait for the same reason a flattened struct's partial is.
        if let Kind::ArgGroup { ty, .. } = &f.kind {
            let ident = &f.ident;
            return Some(quote! {
                pub #ident: <#ty as usage_argv::spec::ArgGroup>::Partial,
            });
        }
        if let Kind::Clause { ty, .. } = &f.kind {
            let ident = &f.ident;
            let current = format_ident!("__usage_current_{}", ident);
            return Some(quote! {
                pub #ident: ::std::vec::Vec<<#ty as usage_argv::spec::CommandArgs>::Partial>,
                pub #current: <#ty as usage_argv::spec::CommandArgs>::Partial,
            });
        }
        let ident = &f.ident;
        let ty = match f.shape {
            Shape::Bool => quote!(bool),
            Shape::Count => {
                let ty = &f.ty;
                quote!(#ty)
            }
            // The bytes as typed, rather than text: `apply` cannot fail — it answers
            // whether an event was this command's — so a word that is not valid UTF-8
            // cannot be reported when it arrives. Keeping the bytes lets `build` report it,
            // and it means no value is quietly mangled on the way in.
            Shape::Optional => quote!(::std::option::Option<::std::vec::Vec<u8>>),
            Shape::Required => quote!(::std::vec::Vec<u8>),
            Shape::Many => quote!(::std::vec::Vec<::std::vec::Vec<u8>>),
        };
        let given = format_ident!("__given_{}", ident);
        // Whether a token supplied this, as opposed to a default sitting in it: an
        // empty string is a value somebody typed, and `--jobs=` has to be able to
        // mean it.
        // Only for a flag that can lose an override: every other field would carry a
        // `bool` nothing ever reads.
        let overridden = is_displaceable(cli, f).then(|| {
            let overridden = format_ident!("__overridden_{}", ident);
            quote!(pub #overridden: bool,)
        });
        let duplicated = rejects_duplicate(cli, f).then(|| {
            let duplicated = format_ident!("__duplicated_{}", ident);
            quote!(pub #duplicated: bool,)
        });
        // Given at *this* level, for a global — see `duplicates_per_level`. Only for those
        // fields, so nothing else carries a `bool` no code reads.
        let here = duplicates_per_level(cli, f).then(|| {
            let here = format_ident!("__here_{}", ident);
            quote!(pub #here: bool,)
        });
        let negated = has_negate(f).then(|| {
            let negated = format_ident!("__negated_{}", ident);
            quote!(pub #negated: bool,)
        });
        let mirrored = mirrored_global_ident(f).map(|mirrored| {
            quote!(pub #mirrored: bool,)
        });
        let invalid_choice = tracks_invalid_choice(f).then(|| {
            let invalid = format_ident!("__invalid_choice_{}", ident);
            quote!(pub #invalid: bool,)
        });
        // Which variable filled this field, when the one that won was a deprecated alias.
        // Recorded by the fallback loop rather than worked out again afterwards: the precedence
        // among a field's variables is decided in exactly one place, and a second reading of it
        // would be free to disagree. Only for fields that declare an alias, so nothing else
        // carries a word no code reads.
        let deprecated_env = tracks_deprecated_env(f).then(|| {
            let recorded = deprecated_env_ident(f);
            quote!(pub #recorded: ::std::option::Option<&'static str>,)
        });
        Some(quote!(pub #ident: #ty, pub #given: bool, #overridden #duplicated #here #negated #mirrored #invalid_choice #deprecated_env))
    });

    // No derived `Default`: `start` is what produces a fresh partial, because a
    // declared default has to be in place before parsing begins and nested state has
    // its own starting values.
    quote! {
        #[expect(clippy::pub_underscore_fields)]
        pub struct Partial {
            pub __usage_view: ::std::option::Option<
                &'static usage_argv::spec::ViewMeta<'static>,
            >,
            pub __usage_omit_own: bool,
            #(#fields)*
            #sub
        }
    }
}

/// The pieces one command contributes to a settings resolution.
///
/// Two of them, and the split is what lets a group declare a setting at all. `given` and
/// `bindings` name nothing outside `usage-argv`, so every command can carry them — a flattened
/// group hands its parent what it was given, in a vocabulary the parser crate owns. Only the root
/// turns that into a `usage_config::CliLayer`, which is why a program with no settings still never
/// mentions the config crate.
struct Settings {
    given: TokenStream,
    bindings: TokenStream,
}

/// One field's value, in usage-argv's vocabulary.
///
/// Text, because that is what the partial holds and what a declared type expects to read:
/// rendering it to something typed here would be a second coercion, disagreeing with the
/// registry's own at the first setting whose type this cannot see. Bytes that are not text are
/// said rather than rendered — an argument can hold them and a setting cannot.
fn given_value(field: &Field) -> TokenStream {
    let ident = &field.ident;
    match field.shape {
        // The bool the parser landed on, which is `false` for a negation and `true` for the flag
        // itself: what the user said, rather than that they said something.
        Shape::Bool => quote! {
            usage_argv::spec::SettingGiven::Bool(partial.#ident)
        },
        Shape::Count => quote! {
            usage_argv::spec::SettingGiven::Int(
                ::std::convert::TryFrom::try_from(partial.#ident)
                    .unwrap_or(::std::primitive::i64::MAX),
            )
        },
        Shape::Optional => quote! {
            match ::std::str::from_utf8(partial.#ident.as_deref().unwrap_or_default()) {
                ::std::result::Result::Ok(__usage_text) => {
                    usage_argv::spec::SettingGiven::Text(
                        ::std::string::ToString::to_string(__usage_text),
                    )
                }
                ::std::result::Result::Err(_) => usage_argv::spec::SettingGiven::NotText,
            }
        },
        Shape::Required => quote! {
            match ::std::str::from_utf8(&partial.#ident) {
                ::std::result::Result::Ok(__usage_text) => {
                    usage_argv::spec::SettingGiven::Text(
                        ::std::string::ToString::to_string(__usage_text),
                    )
                }
                ::std::result::Result::Err(_) => usage_argv::spec::SettingGiven::NotText,
            }
        },
        // Item by item, rather than joined and re-split: an item holding the separator would come
        // back as two. One item that is not text costs the whole list, since contributing the
        // others would quietly drop the one the user typed.
        Shape::Many => quote! {
            match partial
                .#ident
                .iter()
                .map(|__usage_item| {
                    ::std::str::from_utf8(__usage_item)
                        .ok()
                        .map(::std::string::ToString::to_string)
                })
                .collect::<::std::option::Option<::std::vec::Vec<_>>>()
            {
                ::std::option::Option::Some(__usage_items) => {
                    usage_argv::spec::SettingGiven::List(__usage_items)
                }
                ::std::option::Option::None => usage_argv::spec::SettingGiven::NotText,
            }
        },
    }
}

/// Every spelling a bound flag answers to, paired with what it sets.
///
/// A positional has no flag, so it contributes to the layer and not to this: there is nothing for
/// a spec's `cli` node to have declared, and nothing for `drift` to compare.
fn own_bindings(bound: &[&Field]) -> Vec<TokenStream> {
    bound
        .iter()
        .flat_map(|field| {
            let key = field.setting.clone().unwrap_or_default();
            let mut spellings = Vec::new();
            if let Kind::Flag {
                longs,
                shorts,
                negate,
                ..
            } = &field.kind
            {
                spellings.extend(longs.iter().map(|long| format!("--{long}")));
                spellings.extend(shorts.iter().map(|short| format!("-{short}")));
                if let Some(negate) = negate {
                    spellings.push(format!("--{negate}"));
                }
            }
            spellings.into_iter().map(move |flag| quote!((#flag, #key)))
        })
        .collect()
}

/// The commands whose settings this one carries: each flattened group, and the subcommands.
///
/// As `(bindings, given)` pairs, because the two questions differ for a subcommand: its bindings
/// are every variant's, since a table says what the CLI *can* do, and its values are the selected
/// variant's, since those are about one invocation.
fn children(cli: &Cli) -> Vec<(TokenStream, TokenStream)> {
    cli.fields
        .iter()
        .filter_map(|field| {
            let ident = &field.ident;
            match &field.kind {
                Kind::Flatten { ty, .. } => Some((
                    quote!(<#ty as usage_argv::spec::CommandArgs>::SETTINGS_BINDINGS),
                    quote! {
                        <#ty as usage_argv::spec::CommandArgs>::settings_given(
                            &partial.#ident,
                        )
                    },
                )),
                Kind::Subcommand { ty, .. } => Some((
                    quote!(<#ty as usage_argv::spec::Subcommands>::SETTINGS_BINDINGS),
                    quote! {
                        <#ty as usage_argv::spec::Subcommands>::settings_given(
                            &partial.__usage_sub,
                            partial.__usage_selected,
                        )
                    },
                )),
                _ => None,
            }
        })
        .collect()
}

/// Several binding tables as one, joined at compile time.
///
/// The plain slice when there is nothing to join, which is every CLI that flattens nothing: the
/// joined form costs a const block and an array, and reads worse in an expansion.
fn joined_bindings(own: &[TokenStream], children: &[TokenStream]) -> TokenStream {
    if children.is_empty() {
        return quote!(&[#(#own),*]);
    }
    quote! {
        {
            const OWN: &[(&'static str, &'static str)] = &[#(#own),*];
            const PARTS: &[&'static [(&'static str, &'static str)]] = &[OWN #(, #children)*];
            const N: usize = OWN.len() #(+ #children.len())*;
            const JOINED: [(&'static str, &'static str); N] =
                usage_argv::spec::concat_bindings(PARTS);
            &JOINED
        }
    }
}

/// What this command says about settings, or `None` when it has nothing to say.
///
/// A group with no bindings of its own still has something to say when it flattens one that does,
/// which is why this is not simply "does any field declare `setting`".
fn settings(cli: &Cli) -> Option<Settings> {
    let bound: Vec<&Field> = cli.fields.iter().filter(|f| f.setting.is_some()).collect();
    let children = children(cli);
    if bound.is_empty() && children.is_empty() {
        return None;
    }

    // Built from the *partial* rather than from the struct, and gated on `__given_`, because that
    // is the only place the difference between "the flag was not passed" and "the flag was passed
    // and said no" survives. Reading the struct, `--no-colour` is a `false` indistinguishable from
    // absence — and the command line outranks every file on the machine, so guessing either way is
    // a value the user never asked for.
    let contributions = bound.iter().map(|field| {
        let given = format_ident!("__given_{}", &field.ident);
        let key = field.setting.as_deref().unwrap_or_default();
        let value = given_value(field);
        quote! {
            if partial.#given {
                __usage_given.push((#key, #value));
            }
        }
    });
    let from_children = children
        .iter()
        .map(|(_, given)| quote!(__usage_given.extend(#given);));

    let given = quote! {
        /// The settings this command line gave values for.
        pub fn settings_given(
            partial: &Partial,
        ) -> ::std::vec::Vec<(&'static str, usage_argv::spec::SettingGiven)> {
            let mut __usage_given = ::std::vec::Vec::new();
            #(#contributions)*
            #(#from_children)*
            __usage_given
        }
    };

    let child_bindings: Vec<TokenStream> = children.into_iter().map(|(b, _)| b).collect();
    let pairs = own_bindings(&bound);
    let table = joined_bindings(&pairs, &child_bindings);
    let bindings = quote! {
        /// Every flag this CLI reads into a setting, and the setting it sets.
        ///
        /// What `usage_config::Registry::drift` compares against the flags the spec *declares*, so
        /// a documented flag nothing reads — hk has thirteen — fails a test rather than a user.
        pub const SETTINGS_BINDINGS: &'static [(&'static str, &'static str)] = #table;
    };

    Some(Settings { given, bindings })
}

/// The one place a `usage_config` type is named: the root's conversion.
///
/// One loop over what every command contributed, so a flattened group's value and the root's own
/// become entries the same way. A second conversion is the thing this whole stack keeps deleting.
fn settings_layer(config: &TokenStream) -> TokenStream {
    quote! {
        /// This command line as a layer, for `usage_config::resolve`.
        pub fn settings_layer(partial: &Partial) -> #config::CliLayer {
            let mut __usage_layer = #config::CliLayer::new(
                ::std::iter::empty::<(::std::string::String, ::std::string::String)>(),
            );
            for (__usage_key, __usage_given) in settings_given(partial) {
                __usage_layer = match __usage_given {
                    usage_argv::spec::SettingGiven::Bool(__usage_value) => {
                        __usage_layer.with_value(__usage_key, #config::Value::Bool(__usage_value))
                    }
                    usage_argv::spec::SettingGiven::Int(__usage_value) => {
                        __usage_layer.with_value(__usage_key, #config::Value::Int(__usage_value))
                    }
                    usage_argv::spec::SettingGiven::Text(__usage_value) => {
                        __usage_layer
                            .with_value(__usage_key, #config::Value::String(__usage_value))
                    }
                    usage_argv::spec::SettingGiven::List(__usage_items) => __usage_layer.with_value(
                        __usage_key,
                        #config::Value::List(
                            __usage_items
                                .into_iter()
                                .map(#config::Value::String)
                                .collect(),
                        ),
                    ),
                    usage_argv::spec::SettingGiven::NotText => {
                        __usage_layer.with_unrepresentable(__usage_key)
                    }
                };
            }
            __usage_layer
        }
    }
}

/// The check that stands in for a root that never said it has settings.
///
/// A root cannot see another struct's fields, so a CLI whose only bound flags live in a flattened
/// group would generate no settings entry points at all — the flag would parse and set nothing,
/// which is the silence this attribute exists to prevent. Generating them for every CLI instead is
/// not an option: that would make a program with subcommands and no settings depend on
/// `usage-config`. So the root asks each child, at compile time, whether it binds anything it is
/// not going to collect.
fn settings_guard(cli: &Cli) -> Option<TokenStream> {
    let children = children(cli);
    if children.is_empty() {
        return None;
    }
    let checks = children.into_iter().map(|(bindings, _)| {
        quote! {
            const _: () = assert!(
                #bindings.len() == 0,
                "this command flattens or nests a group that binds a setting, and does not \
                 collect it: add `#[usage(settings)]` to the struct deriving `Cli`",
            );
        }
    });
    Some(quote!(#(#checks)*))
}

/// The defaults a partial cannot express as `Default::default()`.
///
/// A declared `default` has to be in place before parsing starts, since nothing
/// later distinguishes "the default" from "what the user typed".
fn partial_defaults(cli: &Cli) -> TokenStream {
    let sub_starts = subcommand_parts(cli)
        .map(|p| p.partial_starts)
        .unwrap_or_default();
    let plain = cli.fields.iter().filter_map(|f| {
        if matches!(f.kind, Kind::Subcommand { .. } | Kind::Skip) {
            return None;
        }
        // `start()` rather than `Default`, so the flattened struct's own defaults are in
        // place before parsing — the same reason this function exists at all.
        if let Kind::Flatten { ty, .. } = &f.kind {
            let ident = &f.ident;
            return Some(quote! {
                #ident: <#ty as usage_argv::spec::CommandArgs>::start(),
            });
        }
        if let Kind::ArgGroup { ty, .. } = &f.kind {
            let ident = &f.ident;
            return Some(quote! {
                #ident: <#ty as usage_argv::spec::ArgGroup>::start(),
            });
        }
        if let Kind::Clause { ty, .. } = &f.kind {
            let ident = &f.ident;
            let current = format_ident!("__usage_current_{}", ident);
            return Some(quote! {
                #ident: ::std::vec::Vec::new(),
                #current: <#ty as usage_argv::spec::CommandArgs>::start(),
            });
        }
        let ident = &f.ident;
        let given = format_ident!("__given_{}", ident);
        let overridden = is_displaceable(cli, f).then(|| {
            let overridden = format_ident!("__overridden_{}", ident);
            quote!(#overridden: false,)
        });
        let duplicated = rejects_duplicate(cli, f).then(|| {
            let duplicated = format_ident!("__duplicated_{}", ident);
            quote!(#duplicated: false,)
        });
        let here = duplicates_per_level(cli, f).then(|| {
            let here = format_ident!("__here_{}", ident);
            quote!(#here: false,)
        });
        let negated = has_negate(f).then(|| {
            let negated = format_ident!("__negated_{}", ident);
            quote!(#negated: false,)
        });
        let mirrored = mirrored_global_ident(f).map(|mirrored| quote!(#mirrored: false,));
        let invalid_choice = tracks_invalid_choice(f).then(|| {
            let invalid = format_ident!("__invalid_choice_{}", ident);
            quote!(#invalid: false,)
        });
        let deprecated_env = tracks_deprecated_env(f).then(|| {
            let recorded = deprecated_env_ident(f);
            quote!(#recorded: ::std::option::Option::None,)
        });
        Some(quote! {
            #ident: ::std::default::Default::default(),
            #given: false,
            #overridden
            #duplicated
            #here
            #negated
            #mirrored
            #invalid_choice
            #deprecated_env
        })
    });
    // Only the fields that declare one: `Partial`'s own initializer has already put
    // everything else at `Default::default()`, and a subcommand field holds a partial
    // that `#sub_starts` builds rather than a value.
    quote! {
        let mut partial = Partial {
            __usage_view: ::std::option::Option::None,
            __usage_omit_own: false,
            #(#plain)*
            #sub_starts
        };
    }
}

/// One field of the finished struct, converted from the text the parse collected.
///
/// The partial holds words, because binding decides where a word lands and not what it
/// means. This is where meaning arrives: a `String` field takes the text as it is, and
/// anything else is built with `FromStr` — which is what lets a field be a `PathBuf`, a
/// number, or a type of the adopter's own.
fn field_final(field: &Field, omitter: Option<&TokenStream>) -> TokenStream {
    let ident = &field.ident;
    let value = field_value(field, omitter);
    quote!(#ident: #value)
}

/// [`field_final`] without the field name, for a merge that assigns one field at a time.
fn field_value(field: &Field, omitter: Option<&TokenStream>) -> TokenStream {
    let ident = &field.ident;
    let given = format_ident!("__given_{}", ident);
    let name = &field.name;
    if matches!(field.kind, Kind::Skip) {
        // clap's skip: not parsed, filled from Default when the struct is built.
        return quote!(::std::default::Default::default());
    }
    if let Kind::Flatten { ty, .. } = &field.kind {
        // Built by its own derive, which is also what makes a nested flatten work: this is
        // the same call at every level.
        return match omitter {
            Some(omitter) => quote! {
                <#ty as usage_argv::spec::ViewCommandArgs<#omitter>>::build_for_view(
                    partial.#ident,
                )?
            },
            None => quote! {
                <#ty as usage_argv::spec::CommandArgs>::build(partial.#ident)?
            },
        };
    }
    if let Kind::Clause { ty, separator } = &field.kind {
        let current = format_ident!("__usage_current_{}", ident);
        let finish_current = if separator.is_some() {
            quote!(__usage_instances.push(partial.#current);)
        } else {
            quote! {
                if <#ty as usage_argv::spec::CommandArgs>::any_given(&partial.#current)
                    .is_some()
                {
                    __usage_instances.push(partial.#current);
                }
            }
        };
        return quote! {
            {
                let mut __usage_instances = partial.#ident;
                #finish_current
                __usage_instances
                    .into_iter()
                    .map(<#ty as usage_argv::spec::CommandArgs>::build)
                    .collect::<::std::result::Result<::std::vec::Vec<_>, _>>()?
            }
        };
    }
    // The group's own `build` says which member was given; the field's type says what "none"
    // means. `check` has already reported both a second member and a required group with none,
    // so this arm is reached only for a group that was satisfied — the error stays for the
    // case where a caller drives `build` without it, rather than being an `unreachable!`.
    if let Kind::ArgGroup {
        ty,
        optional,
        multiple,
    } = &field.kind
    {
        let group = quote!(<#ty as usage_argv::spec::ArgGroup>);
        if *multiple {
            return quote!(#group::try_build_many(&partial.#ident)?);
        }
        return if *optional {
            quote!(#group::try_build(&partial.#ident)?)
        } else {
            quote! {
                match #group::try_build(&partial.#ident)? {
                    ::std::option::Option::Some(__usage_member) => __usage_member,
                    ::std::option::Option::None => {
                        return ::std::result::Result::Err(
                            usage_argv::Error::MissingGroup {
                                group: #group::NAME,
                                members: #group::MEMBERS,
                            },
                        );
                    }
                }
            }
        };
    }
    let active = view_field_active(field);
    let ty = &field.ty;
    let finished = |value: TokenStream| {
        let Some(omitter) = omitter else {
            return value;
        };
        quote! {
            {
                let __usage_view = partial.__usage_view;
                if partial.__usage_omit_own || !(#active) {
                    <#omitter as usage_argv::spec::Omitted<#ty>>::omitted()
                } else {
                    #value
                }
            }
        }
    };
    let Some(ty) = field.value_ty.as_ref() else {
        // A switch or a count: nothing was parsed from a word.
        return finished(quote!(partial.#ident));
    };

    // Every type converts, `String` included: the partial holds the bytes that were typed,
    // and `String::from_utf8` is where a word that is not UTF-8 is reported rather than
    // quietly replaced. That also retires the old hazard of recognising `String` by how it
    // was written — there is no identity case left to recognise, so an adopter who shadows
    // the name is no longer a problem.
    //
    // `from_utf8` takes the `Vec` by value and does not copy, so this costs a check.
    // `String` still skips the *second* step, since `from_utf8` has already produced one.
    // Recognising it by spelling is safe now: if an adopter's own `String` were mistaken for
    // this one, the mismatch is a compile error rather than a value quietly mangled — and
    // the check that matters, the UTF-8 one, happens either way.
    let rendered = rendered_path(ty);
    let is_std_string = matches!(
        rendered.as_str(),
        "String" | "std::string::String" | "::std::string::String" | "alloc::string::String"
    );

    // A field that can hold any byte sequence skips UTF-8 entirely, because for these types
    // rejecting a word would be the wrong answer: the operating system accepts `/tmp/\xff`
    // as a filename, so a CLI has to be able to receive one. Everything else still converts
    // through text, since `FromStr` is the only thing an arbitrary type offers.
    //
    // Recognised by spelling, with the same reasoning as `String` above: an adopter's own
    // `PathBuf` would fail to compile rather than quietly take a mangled value, because what
    // is handed to it is an `OsString` and not a `&str`.
    let os_target = match rendered.as_str() {
        "PathBuf" | "std::path::PathBuf" | "::std::path::PathBuf" => {
            Some(quote!(::std::path::PathBuf::from))
        }
        "OsString" | "std::ffi::OsString" | "::std::ffi::OsString" => {
            Some(quote!(::std::convert::identity))
        }
        _ => None,
    };
    if let Some(build) = os_target {
        // Lossless on Unix, where any byte sequence is a filename. On Windows the encoding
        // is WTF-8 and the conversion is partial, so a value that will not convert is
        // reported the same way any other unconvertible value is — never dropped, and never
        // replaced by a different filename.
        let one = |value: TokenStream| {
            quote! {
                match usage_argv::os_string_from_bytes(#value) {
                    ::std::result::Result::Ok(__usage_os) => #build(__usage_os),
                    ::std::result::Result::Err(__usage_bytes) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_os_value(#name, __usage_bytes),
                        );
                    }
                }
            }
        };
        let converted = one;
        return match field.shape {
            // Unreachable: a switch and a count have no `value_ty`, so the early return
            // above already handled them.
            Shape::Bool | Shape::Count => finished(quote!(partial.#ident)),
            Shape::Required => {
                let value = converted(quote!(partial.#ident));
                finished(value)
            }
            // A `match` rather than `.map`, and a loop rather than `.collect`, for the same
            // reason the text path below uses them: the conversion can fail, and a `return`
            // inside a closure would leave the error in the closure's own return type.
            Shape::Optional if field.optional_value_type => {
                let value = converted(quote!(__usage_value));
                finished(quote! {
                    match partial.#ident {
                        ::std::option::Option::Some(__usage_value) => {
                            ::std::option::Option::Some(::std::option::Option::Some(#value))
                        }
                        ::std::option::Option::None if partial.#given => {
                            ::std::option::Option::Some(::std::option::Option::None)
                        }
                        ::std::option::Option::None => ::std::option::Option::None,
                    }
                })
            }
            Shape::Optional => {
                let value = converted(quote!(__usage_value));
                finished(quote! {
                    match partial.#ident {
                        ::std::option::Option::Some(__usage_value) => {
                            ::std::option::Option::Some(#value)
                        }
                        ::std::option::Option::None => ::std::option::Option::None,
                    }
                })
            }
            Shape::Many => {
                // One shared loop in the runtime rather than one per field — the
                // collecting fields were most of what a large `build` still held.
                let collected = quote! {
                    usage_argv::os_values(partial.#ident, #name)?
                };
                if field.optional_collection {
                    let given = format_ident!("__given_{}", ident);
                    let defaulted = !field.default.is_empty();
                    // Same as below: whether anything arrived is what tells "never given"
                    // from "given nothing", which the `Vec` itself cannot. A `default_if`
                    // that fired has already pushed, so a non-empty vec is a value too.
                    finished(quote! {
                        if partial.#given || #defaulted || !partial.#ident.is_empty() {
                            ::std::option::Option::Some(#collected)
                        } else {
                            ::std::option::Option::None
                        }
                    })
                } else {
                    finished(collected)
                }
            }
        };
    }

    let converted = |value: TokenStream| {
        let text = quote! {
            match ::std::string::String::from_utf8(#value) {
                ::std::result::Result::Ok(text) => text,
                ::std::result::Result::Err(bad) => {
                    return ::std::result::Result::Err(
                        usage_argv::invalid_utf8_value(#name, bad),
                    );
                }
            }
        };
        if field.value_enum {
            return quote! {{
                let __usage_text = #text;
                match <#ty as usage_argv::spec::ValueEnum>::from_choice(&__usage_text) {
                    ::std::option::Option::Some(parsed) => parsed,
                    ::std::option::Option::None => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_choice_value(#name, __usage_text),
                        );
                    }
                }
            }};
        }
        if is_std_string {
            return text;
        }
        quote! {{
            let __usage_text = #text;
            match ::std::str::FromStr::from_str(&__usage_text) {
                ::std::result::Result::Ok(parsed) => parsed,
                ::std::result::Result::Err(reason) => {
                    return ::std::result::Result::Err(
                        usage_argv::invalid_parsed_value(#name, __usage_text, &reason),
                    );
                }
            }
        }}
    };

    match field.shape {
        Shape::Bool | Shape::Count => finished(quote!(partial.#ident)),
        Shape::Required => {
            let one = converted(quote!(partial.#ident));
            finished(one)
        }
        Shape::Optional if field.optional_value_type => {
            let one = converted(quote!(__usage_value));
            finished(quote! {
                match partial.#ident {
                    ::std::option::Option::Some(__usage_value) => {
                        ::std::option::Option::Some(::std::option::Option::Some(#one))
                    }
                    ::std::option::Option::None if partial.#given => {
                        ::std::option::Option::Some(::std::option::Option::None)
                    }
                    ::std::option::Option::None => ::std::option::Option::None,
                }
            })
        }
        Shape::Optional => {
            let one = converted(quote!(__usage_value));
            finished(quote! {
                match partial.#ident {
                    ::std::option::Option::Some(__usage_value) => {
                        ::std::option::Option::Some(#one)
                    }
                    ::std::option::Option::None => ::std::option::Option::None,
                }
            })
        }
        Shape::Many => {
            // One shared loop in the runtime rather than one per field — the collecting
            // fields were most of what a large `build` still held. Each helper converts
            // element by element so the error carries the value that failed.
            let collected = if field.value_enum {
                quote!(usage_argv::spec::choice_values::<#ty>(partial.#ident, #name)?)
            } else if is_std_string {
                quote!(usage_argv::utf8_values(partial.#ident, #name)?)
            } else {
                quote!(usage_argv::parsed_values::<#ty>(partial.#ident, #name)?)
            };
            if field.optional_collection {
                let given = format_ident!("__given_{}", ident);
                // A declared default is a value, so a field that has one is never `None`. It
                // does not set `__given_*` — the environment still has to be able to replace it
                // — so the answer has to come from the declaration rather than from the partial.
                // A `default_if` that matched has already pushed, which a leftover empty vec
                // would not.
                let defaulted = !field.default.is_empty();
                // `Option<Vec<T>>` distinguishes "never given" from "given nothing", which
                // no `Vec` can — so the answer comes from whether anything arrived.
                finished(quote! {
                    if partial.#given || #defaulted || !partial.#ident.is_empty() {
                        ::std::option::Option::Some(#collected)
                    } else {
                        ::std::option::Option::None
                    }
                })
            } else {
                finished(collected)
            }
        }
    }
}

/// Whether this parse produced a value for the field, so a merge should take it.
///
/// Wider than `__given_*` by exactly one case: a declared default that fired. Those do not
/// mark a field given — the environment still has to be able to replace one — but a default
/// only fires on an update when the field was empty on both sides, and dropping it would
/// leave the field emptier than a fresh parse leaves it.
fn merge_present(field: &Field) -> TokenStream {
    let ident = &field.ident;
    let given = format_ident!("__given_{}", ident);
    match field.shape {
        Shape::Bool => quote!(partial.#given || partial.#ident),
        Shape::Count => {
            let ty = &field.ty;
            quote!(partial.#given || partial.#ident != <#ty as ::std::default::Default>::default())
        }
        Shape::Optional => quote!(partial.#given || partial.#ident.is_some()),
        Shape::Required | Shape::Many => quote!(partial.#given || !partial.#ident.is_empty()),
    }
}

/// Overwrite what this command line gave, and leave the rest of the caller's value alone.
///
/// The rule is stated per field rather than inherited from the full-parse path: a collection
/// this argv mentioned is replaced whole, one it said nothing about is untouched, and a
/// subcommand word naming a different variant replaces it rather than merging into fields
/// the new command does not have.
fn merge_fn(cli: &Cli) -> TokenStream {
    let ident = &cli.ident;
    let merges = cli.fields.iter().filter_map(|field| {
        let field_ident = &field.ident;
        match &field.kind {
            // Not parsed, so this command line said nothing about it.
            Kind::Skip => None,
            Kind::Flatten { ty, .. } => Some(quote! {
                <#ty as usage_argv::spec::CommandArgs>::merge(
                    partial.#field_ident,
                    &mut __usage_standing.#field_ident,
                )?;
            }),
            // A group with no member given is this argv saying nothing about the group.
            Kind::ArgGroup {
                ty,
                optional,
                multiple,
            } => {
                let group = quote!(<#ty as usage_argv::spec::ArgGroup>);
                if *multiple {
                    return Some(quote! {
                        if #group::any_given(&partial.#field_ident).is_some() {
                            __usage_standing.#field_ident =
                                #group::try_build_many(&partial.#field_ident)?;
                        }
                    });
                }
                let selected = if *optional {
                    quote!(::std::option::Option::Some(__usage_member))
                } else {
                    quote!(__usage_member)
                };
                Some(quote! {
                    if let ::std::option::Option::Some(__usage_member) =
                        #group::try_build(&partial.#field_ident)?
                    {
                        __usage_standing.#field_ident = #selected;
                    }
                })
            }
            Kind::Subcommand { ty, optional } => Some(if *optional {
                quote! {
                    if let ::std::option::Option::Some(__usage_at) = partial.__usage_selected {
                        match &mut __usage_standing.#field_ident {
                            ::std::option::Option::Some(__usage_existing) => {
                                <#ty as usage_argv::spec::Subcommands>::merge_into(
                                    partial.__usage_sub,
                                    __usage_at,
                                    __usage_existing,
                                )?;
                            }
                            __usage_slot => {
                                *__usage_slot =
                                    <#ty as usage_argv::spec::Subcommands>::select(
                                        partial.__usage_sub,
                                        __usage_at,
                                    )?;
                            }
                        }
                    }
                }
            } else {
                quote! {
                    if let ::std::option::Option::Some(__usage_at) = partial.__usage_selected {
                        <#ty as usage_argv::spec::Subcommands>::merge_into(
                            partial.__usage_sub,
                            __usage_at,
                            &mut __usage_standing.#field_ident,
                        )?;
                    }
                }
            }),
            Kind::Clause { ty, .. } => {
                let current = format_ident!("__usage_current_{}", field_ident);
                let value = field_value(field, None);
                Some(quote! {
                    if !partial.#field_ident.is_empty()
                        || <#ty as usage_argv::spec::CommandArgs>::any_given(&partial.#current).is_some()
                    {
                        __usage_standing.#field_ident = #value;
                    }
                })
            }
            Kind::Flag { .. } | Kind::Arg { .. } => {
                let present = merge_present(field);
                let value = field_value(field, None);
                Some(quote! {
                    if #present {
                        __usage_standing.#field_ident = #value;
                    }
                })
            }
        }
    });
    quote! {
        /// Merge what this parse collected into a value the caller already has.
        pub fn merge<'t, 'v>(
            partial: Partial,
            __usage_standing: &mut #ident,
        ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
            // Read unconditionally, so a command with nothing to merge does not leave its
            // parameters unused in the adopter's crate, where nobody can silence it.
            let _ = (&partial, &*__usage_standing);
            #(#merges)*
            ::std::result::Result::Ok(())
        }
    }
}

/// Which of this command's fields the caller already had a value for.
///
/// The standing half of `any_given`, for a parent enforcing exclusivity across a flattened
/// boundary on an update.
fn any_standing_fn(cli: &Cli) -> TokenStream {
    let held = cli.fields.iter().filter_map(|field| {
        if let Kind::Flatten { ty, .. } = &field.kind {
            let ident = &field.ident;
            return Some(quote! {
                if let ::std::option::Option::Some(__usage_name) =
                    <#ty as usage_argv::spec::CommandArgs>::any_standing(&__usage_s.#ident)
                {
                    return ::std::option::Option::Some(__usage_name);
                }
            });
        }
        let present = standing_presence(field)?;
        let name = &field.name;
        Some(quote! {
            if #present {
                return ::std::option::Option::Some(#name);
            }
        })
    });
    quote! {
        fn any_standing(__usage_s: &Self) -> ::std::option::Option<&'static str> {
            let _ = __usage_s;
            #(#held)*
            ::std::option::Option::None
        }
    }
}

/// Put a field back the way `start()` left it.
///
/// Used twice, and the second use is why it is worth naming: a flag displaced by an
/// `overrides` has to look untouched, and "untouched" means its declared default rather
/// than blank. clap does the same — a boolean that loses an override reads as `false`,
/// not as absent.
fn reset_to_default(field: &Field) -> TokenStream {
    let ident = &field.ident;
    // A collection is cleared rather than replaced, so the field keeps whatever capacity it
    // already allocated — and clearing is also the first half of seeding it, since a default
    // means *these values and no others* however many were bound before.
    let cleared = match field.shape {
        Shape::Many => quote!(partial.#ident.clear();),
        _ => quote!(partial.#ident = ::std::default::Default::default();),
    };
    if !field.has_default() {
        return cleared;
    }
    if let Some(default_fn) = &field.default_fn {
        let value_ty = field
            .value_ty
            .as_ref()
            .expect("a computed default belongs to a value-taking field");
        let bytes = quote!({
            let __usage_default: #value_ty = #default_fn();
            ::std::string::ToString::to_string(&__usage_default).into_bytes()
        });
        return match field.shape {
            Shape::Optional => quote! {
                partial.#ident = ::std::option::Option::Some(#bytes);
            },
            Shape::Required => quote!(partial.#ident = #bytes;),
            // The model rejects these shapes before codegen.
            _ => cleared,
        };
    }
    if let Some(value) = &field.default_value_t {
        let value_ty = field
            .value_ty
            .as_ref()
            .expect("a typed default belongs to a value-taking field");
        let bytes = quote!({
            let __usage_default: #value_ty = #value;
            ::std::string::ToString::to_string(&__usage_default).into_bytes()
        });
        return match field.shape {
            Shape::Optional => quote! {
                partial.#ident = ::std::option::Option::Some(#bytes);
            },
            Shape::Required => quote!(partial.#ident = #bytes;),
            // The model rejects these shapes before codegen.
            _ => cleared,
        };
    }
    // Every shape but a collection was checked in the model to have at most one.
    assign_literal(field, &field.default[0], field.default.as_slice())
}

/// Put `value` into the field the way a declared default does.
fn assign_literal(field: &Field, first: &str, all: &[String]) -> TokenStream {
    let ident = &field.ident;
    let cleared = match field.shape {
        Shape::Many => quote!(partial.#ident.clear();),
        _ => quote!(),
    };
    match field.shape {
        Shape::Bool => {
            let on = matches!(first, "1" | "true" | "True" | "TRUE");
            quote!(partial.#ident = #on;)
        }
        Shape::Optional => quote! {
            partial.#ident = ::std::option::Option::Some(#first.as_bytes().to_vec());
        },
        Shape::Required => quote!(partial.#ident = #first.as_bytes().to_vec();),
        Shape::Count => quote!(partial.#ident = ::std::default::Default::default();),
        Shape::Many => {
            let defaults = all;
            match field.delimiter {
                Some(delimiter) => {
                    let byte = u8::try_from(u32::from(delimiter))
                        .expect("the model rejects non-ASCII delimiters");
                    quote! {
                        #cleared
                        #(
                            for part in #defaults.as_bytes().split(|b| *b == #byte) {
                                partial.#ident.push(part.to_vec());
                            }
                        )*
                    }
                }
                None => quote! {
                    #cleared
                    #(partial.#ident.push(#defaults.as_bytes().to_vec());)*
                },
            }
        }
    }
}

/// Which pair of lookup helpers a generated predicate may call.
///
/// The standing-aware pair is a closure over locals only `check` and `apply_declared_defaults`
/// hold, so a predicate inlined into the module-level `argument_state` has to name the plain
/// functions instead — the same predicate, minus the value an update already had.
#[derive(Clone, Copy, PartialEq)]
enum Lookup {
    Module,
    Standing,
}

impl Lookup {
    fn state(self) -> TokenStream {
        match self {
            Lookup::Module => quote!(argument_state),
            Lookup::Standing => quote!(__usage_argument_state),
        }
    }

    fn matches(self) -> TokenStream {
        match self {
            Lookup::Module => quote!(argument_matches),
            Lookup::Standing => quote!(__usage_argument_matches),
        }
    }
}

fn default_if_predicate(cli: &Cli, condition: &ConditionalDefault, lookup: Lookup) -> TokenStream {
    let Some(other) = cli.field_for_selector(&condition.selector) else {
        let selector = &condition.selector;
        let state = lookup.state();
        let matches = lookup.matches();
        return match &condition.when {
            None => quote!(
                #state(partial, #selector).is_some_and(|state| state.given)
            ),
            Some(when) => quote!(
                #matches(partial, #selector, #when.as_bytes())
                    == ::std::option::Option::Some(true)
            ),
        };
    };
    let other_given = policy_given(other);
    let ident = &other.ident;
    match &condition.when {
        None => quote!(#other_given),
        Some(when) => {
            let matches = match other.shape {
                Shape::Optional => quote!(
                    partial.#ident.as_deref().is_some_and(|v| v == #when.as_bytes())
                ),
                Shape::Required => quote!(partial.#ident.as_slice() == #when.as_bytes()),
                Shape::Many => quote!(
                    partial.#ident.iter().any(|v| v.as_slice() == #when.as_bytes())
                ),
                Shape::Bool => match when.as_str() {
                    "true" => quote!(partial.#ident),
                    "false" => quote!(!partial.#ident),
                    _ => quote!(false),
                },
                Shape::Count => match when.as_str() {
                    "true" => quote!(partial.#ident > 0),
                    "false" => quote!(partial.#ident == 0),
                    _ => quote!(false),
                },
            };
            quote!(#other_given && #matches)
        }
    }
}

fn default_if_would_apply(cli: &Cli, field: &Field, lookup: Lookup) -> Option<TokenStream> {
    if field.default_if.is_empty() {
        return None;
    }
    let preds: Vec<TokenStream> = field
        .default_if
        .iter()
        .map(|condition| default_if_predicate(cli, condition, lookup))
        .collect();
    Some(quote!(#(#preds)||*))
}

/// The `apply` arm for a field whose flags were keyed in another expansion.
///
/// A flattened struct and an argument group are the same shape of problem: their flags sit in
/// this command's table, but the keys were minted where the type was declared, so only that
/// type can recognize an event. One helper for both, so the displacement rule cannot drift
/// between them — `trait_path` is all that differs.
fn opaque_apply_arm(cli: &Cli, ident: &syn::Ident, trait_path: &TokenStream) -> TokenStream {
    let reverse_displacements = cli.fields.iter().flat_map(|field| {
        field
            .overrides
            .iter()
            .filter(|selector| cli.field_for_selector(selector).is_none())
            .map(move |selector| {
                let statement = displace_statement(cli, field);
                quote! {
                    if #trait_path::event_matches(event, #selector) {
                        #statement
                    }
                }
            })
    });
    quote! {
        if #trait_path::apply(&mut partial.#ident, event) {
            #(#reverse_displacements)*
            return true;
        }
    }
}

/// Take one event and say whether it belonged to this command.
fn apply_fn(cli: &Cli) -> TokenStream {
    let route = subcommand_parts(cli).map(|p| p.route).unwrap_or_default();
    let per_level_resets = reset_per_level(cli);
    // A flattened struct's flags are in this command's table, but its *keys* were minted in
    // its own expansion — so they cannot be matched here. Its `apply` recognises them, and
    // says whether it took the event.
    let flattened: Vec<TokenStream> = cli
        .fields
        .iter()
        .filter_map(|f| {
            let Kind::Flatten { ty, .. } = &f.kind else {
                return None;
            };
            Some(opaque_apply_arm(
                cli,
                &f.ident,
                &quote!(<#ty as usage_argv::spec::CommandArgs>),
            ))
        })
        .collect();
    // An argument group's switches are in this command's table with keys minted in the enum's
    // own expansion, exactly as a flattened struct's are, so the enum is what recognizes them.
    let grouped: Vec<TokenStream> = cli
        .fields
        .iter()
        .filter_map(|f| {
            let Kind::ArgGroup { ty, .. } = &f.kind else {
                return None;
            };
            Some(opaque_apply_arm(
                cli,
                &f.ident,
                &quote!(<#ty as usage_argv::spec::ArgGroup>),
            ))
        })
        .collect();
    let clauses: Vec<TokenStream> = cli
        .fields
        .iter()
        .filter_map(|f| {
            let Kind::Clause { ty, .. } = &f.kind else {
                return None;
            };
            let ident = &f.ident;
            let current = format_ident!("__usage_current_{}", ident);
            Some(quote! {
                if let usage_argv::Event::ClauseSeparator { .. } = event {
                    let __usage_finished = ::core::mem::replace(
                        &mut partial.#current,
                        <#ty as usage_argv::spec::CommandArgs>::start(),
                    );
                    partial.#ident.push(__usage_finished);
                    return true;
                }
                if <#ty as usage_argv::spec::CommandArgs>::apply(&mut partial.#current, event) {
                    return true;
                }
            })
        })
        .collect();
    let mirrored_flattened = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        let ident = &f.ident;
        Some(quote! {
            if <#ty as usage_argv::spec::CommandArgs>::apply_mirrored_global(
                &mut partial.#ident,
                event,
            ) {
                return true;
            }
        })
    });
    let flags: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Flag { .. }))
        .collect();
    let args: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Arg { .. }))
        .collect();
    let flag_arms = flags.iter().enumerate().map(|(i, f)| flag_arm(cli, i, f));
    let mirrored_flag_arms = flags.iter().enumerate().filter_map(|(i, field)| {
        if !matches!(field.kind, Kind::Flag { global: true, .. }) {
            return None;
        }
        let key = key_ident("FLAG", Some(i));
        let table = format_ident!("FLAG_{i}");
        let body = flag_binding_body(field);
        let given = format_ident!("__given_{}", field.ident);
        let mirrored = mirrored_global_ident(field).map(|mirrored| {
            quote! {
                if !partial.#given {
                    partial.#mirrored = true;
                }
            }
        });
        Some(quote! {
            #key if ::core::ptr::eq(*flag, &#table) => {
                #body
                #mirrored
                partial.#given = true;
                true
            }
        })
    });
    let arg_arms = args.iter().enumerate().map(|(i, f)| arg_arm(i, f));

    quote! {
        pub fn apply(
            partial: &mut Partial,
            event: &usage_argv::Event<'_, '_, '_>,
        ) -> bool {
            use usage_argv::Event;
            #route
            #(#flattened)*
            #(#grouped)*
            #(#clauses)*
            // Each arm evaluates to whether it claimed the event, rather than
            // returning: a command with no flags of its own would otherwise have every
            // arm diverge, leaving an unreachable tail.
            match event {
                Event::Flag { flag, value, negated } => {
                    let (value, negated) = (*value, *negated);
                    let _ = (value, negated);
                    match flag.key {
                        #(#flag_arms)*
                        // Another command's flag, left for whoever owns it.
                        _ => false,
                    }
                }
                Event::Arg {
                    arg,
                    value,
                    delimit,
                } => {
                    let (value, delimit) = (*value, *delimit);
                    let _ = (value, delimit);
                    match arg.key {
                        #(#arg_arms)*
                        _ => false,
                    }
                }
                // Descending is the caller's business: it is what decides which
                // command's fields the following events belong to. But any command
                // word — not only a child of ours — begins a level at which this
                // struct's globals may be given again, and this arm is the one
                // place every partial sees the word, whether it belongs to a root,
                // a subcommand, or a flattened group.
                Event::Command(_) => {
                    #per_level_resets
                    false
                }
                // Forwarded argv belongs to the catch-all variant, which the
                // subcommand route claims; this command's own flags do not.
                Event::External { .. } => false,
                Event::ClauseSeparator { .. } => false,
            }
        }

        pub fn apply_mirrored_global(
            partial: &mut Partial,
            event: &usage_argv::Event<'_, '_, '_>,
        ) -> bool {
            #(#mirrored_flattened)*
            match event {
                usage_argv::Event::Flag { flag, value, negated } => {
                    let (value, negated) = (*value, *negated);
                    let _ = (value, negated);
                    match flag.key {
                        #(#mirrored_flag_arms)*
                        _ => false,
                    }
                }
                _ => false,
            }
        }
    }
}

/// What a command with subcommands needs, wherever it sits in the tree.
///
/// The root and a nested command differ only in how they are entered, so they share
/// this: the tables to splice, the state to carry, how an event is routed, and how
/// the field is finally built.
struct SubcommandParts {
    /// `subcommands:` for the `Command` table.
    commands: TokenStream,
    /// `default_subcommand:` for the `Command` table, when one is declared.
    default: TokenStream,
    /// `external_subcommand:` for the `Command` table.
    external: TokenStream,
    /// `subcommands:` for the `CommandMeta`.
    metas: TokenStream,
    /// Fields the partial needs to carry.
    partial_fields: TokenStream,
    /// Their starting values.
    partial_starts: TokenStream,
    /// Routing an event that this command did not claim.
    route: TokenStream,
    /// Checking whichever subcommand was selected.
    check: TokenStream,
    /// Building the field.
    build: TokenStream,
    /// Building the field while an executable view omits injected parents.
    view_build: TokenStream,
    /// The process entry point's concrete view build.
    default_view_build: TokenStream,
}

fn subcommand_parts(cli: &Cli) -> Option<SubcommandParts> {
    let (field, ty) = cli.fields.iter().find_map(|f| match &f.kind {
        Kind::Subcommand { ty, .. } => Some((f, ty)),
        _ => None,
    })?;
    let ident = &field.ident;
    let optional = matches!(&field.kind, Kind::Subcommand { optional: true, .. });
    let command_table = if cli.composable {
        quote!(COMMAND)
    } else {
        quote!(ROOT)
    };

    let selected = |omitter: Option<TokenStream>| {
        let select = match omitter {
            Some(omitter) => quote! {
                <#ty as usage_argv::spec::ViewSubcommands<#omitter>>::select_for_view(
                    partial.__usage_sub,
                    __usage_at,
                )?
            },
            None => quote! {
                <#ty as usage_argv::spec::Subcommands>::select(
                    partial.__usage_sub,
                    __usage_at,
                )?
            },
        };
        quote! {
            match partial.__usage_selected {
                ::std::option::Option::Some(__usage_at) => #select,
                ::std::option::Option::None => ::std::option::Option::None,
            }
        }
    };
    let build = |omitter: Option<TokenStream>| {
        let selected = selected(omitter);
        if optional {
            quote!(#ident: #selected,)
        } else {
            quote! {
                #ident: match #selected {
                    ::std::option::Option::Some(__usage_cmd) => __usage_cmd,
                    ::std::option::Option::None => {
                        return ::std::result::Result::Err(
                            usage_argv::Error::MissingSubcommand,
                        );
                    }
                },
            }
        }
    };

    Some(SubcommandParts {
        commands: quote!(subcommands: <#ty as usage_argv::spec::Subcommands>::COMMANDS,),
        external: quote!(
            external_subcommand: <#ty as usage_argv::spec::Subcommands>::HAS_EXTERNAL,
        ),
        // Resolved from the name at compile time. The variants are another expansion, so the
        // name is all there is to go on here — but `find_subcommand` searches the list during
        // const evaluation, which means a name no subcommand answers to fails to compile
        // rather than being emitted into a spec that nothing checks.
        default: match cli.default_subcommand.as_deref() {
            ::std::option::Option::Some(name) => quote! {
                default_subcommand: ::std::option::Option::Some(
                    usage_argv::find_subcommand(
                        <#ty as usage_argv::spec::Subcommands>::COMMANDS,
                        #name,
                    ),
                ),
            },
            ::std::option::Option::None => TokenStream::new(),
        },
        metas: quote!(subcommands: <#ty as usage_argv::spec::Subcommands>::METAS,),
        partial_fields: quote! {
            pub __usage_sub: <#ty as usage_argv::spec::Subcommands>::Partial,
            /// Which of this command's subcommands was reached, as a variant index.
            /// Found from the table's own address, then mapped through `VARIANT_OF`
            /// when a catch-all sits among the named commands.
            pub __usage_selected: ::std::option::Option<usize>,
        },
        partial_starts: quote! {
            __usage_sub: ::std::default::Default::default(),
            __usage_selected: ::std::option::Option::None,
        },
        route: quote! {
            // A command word only counts as *this* command's if one of its own
            // subcommands answers to it: a deeper descent belongs to whoever owns
            // that command, and recording it here would make the wrong variant look
            // selected. `COMMANDS` holds named commands only, so the position is
            // mapped through `VARIANT_OF` when a catch-all variant sits beside them.
            if let usage_argv::Event::Command(__usage_cmd) = event {
                if let ::std::option::Option::Some(__usage_named) =
                    <#ty as usage_argv::spec::Subcommands>::COMMANDS
                        .iter()
                        .position(|candidate| ::core::ptr::eq(*candidate, *__usage_cmd))
                {
                    let __usage_at = if <#ty as usage_argv::spec::Subcommands>::HAS_EXTERNAL {
                        <#ty as usage_argv::spec::Subcommands>::VARIANT_OF[__usage_named]
                    } else {
                        __usage_named
                    };
                    partial.__usage_selected = ::std::option::Option::Some(__usage_at);
                    // The one place the selection and the storage are tied together: from
                    // here on, `__usage_selected` naming a variant means `__usage_sub`
                    // holds that variant. Everything downstream relies on it.
                    <#ty as usage_argv::spec::Subcommands>::begin(
                        &mut partial.__usage_sub,
                        __usage_at,
                    );
                }
            }
            if let usage_argv::Event::External { .. } = event {
                if let ::std::option::Option::Some(__usage_at) =
                    <#ty as usage_argv::spec::Subcommands>::EXTERNAL
                {
                    partial.__usage_selected = ::std::option::Option::Some(__usage_at);
                    <#ty as usage_argv::spec::Subcommands>::begin(
                        &mut partial.__usage_sub,
                        __usage_at,
                    );
                }
            }
            // Only the selected one is asked — see `Subcommands::apply`. The selection is
            // set just above, so a command word reaches the command it named on the same
            // event that selected it.
            let __usage_routed = <#ty as usage_argv::spec::Subcommands>::apply(
                &mut partial.__usage_sub,
                partial.__usage_selected,
                event,
            );
            if __usage_routed {
                // clap propagates a global value into the ancestor even when the
                // selected subcommand redeclares the same spelling. The parser
                // correctly chooses the nearer flag; mirror that event onto the
                // ancestor's global table so both typed fields observe it.
                if let usage_argv::Event::Flag { flag, value, negated } = event {
                    if let ::std::option::Option::Some(__usage_global) = #command_table
                        .flags
                        .iter()
                        .copied()
                        .find(|candidate| {
                            candidate.global
                                && candidate.key != flag.key
                                && candidate.binding_key != 0
                                && candidate.binding_key == flag.binding_key
                                && candidate.binding_type == flag.binding_type
                                // A shared alias is not a redeclaration. clap mirrors a
                                // global when the child declares the same argument identity;
                                // `name` is the portable canonical identity while the table
                                // key identifies the two Rust fields separately.
                                && candidate.name == flag.name
                        })
                    {
                        let __usage_global_event = usage_argv::Event::Flag {
                            flag: __usage_global,
                            value: *value,
                            negated: *negated,
                        };
                        apply_mirrored_global(partial, &__usage_global_event);
                    }
                }
                return true;
            }
        },
        check: {
            let standing = standing_ident(field);
            quote! {
                if let ::std::option::Option::Some(__usage_at) = partial.__usage_selected {
                    match (#standing, __usage_view) {
                        // An update's standing command, whose own fields answer for the
                        // ones this argv did not repeat — but only when the selection is
                        // the same one, which the enum's own expansion decides.
                        (::std::option::Option::Some(__usage_s), _) => {
                            <#ty as usage_argv::spec::Subcommands>::check_update(
                                &mut partial.__usage_sub,
                                __usage_at,
                                __usage_s,
                            )?;
                        }
                        (
                            ::std::option::Option::None,
                            ::std::option::Option::Some(__usage_view),
                        ) => {
                            <#ty as usage_argv::spec::Subcommands>::check_for_view_path(
                                &mut partial.__usage_sub,
                                __usage_at,
                                __usage_view.root.split_ascii_whitespace().count(),
                            )?;
                        }
                        (::std::option::Option::None, ::std::option::Option::None) => {
                            <#ty as usage_argv::spec::Subcommands>::check(
                                &mut partial.__usage_sub,
                                __usage_at,
                            )?;
                        }
                    }
                }
            }
        },
        build: build(None),
        view_build: build(Some(quote!(__UsageOmitter))),
        default_view_build: build(Some(quote!(usage_argv::spec::DefaultViewOmitter))),
    })
}

/// A subcommand's argument struct: tables, metadata, and the trait that lets a
/// parent reach them.
pub fn emit_args(cli: &Cli) -> TokenStream {
    let ident = &cli.ident;
    let runtime = runtime_path();
    let dispatch = emit_command_dispatch(cli, &runtime);
    let validation = validation_path();
    let validation_import = cli
        .fields
        .iter()
        .any(|field| field.validate.is_some())
        .then(|| quote!(use #validation as usage_validation;));
    let presence = presence_methods(cli);
    let any_standing = any_standing_fn(cli);
    let standing_locals = standing_locals(cli);
    let argument_state_standing = argument_state_standing(cli);
    let apply_defaults = {
        let defaults = declared_defaults(cli, true);
        quote!(#standing_locals #argument_state_standing #defaults)
    };
    let apply_env = {
        let env = env_fallbacks(cli, true);
        quote!(#standing_locals #env)
    };
    // A group carries settings the same way a root does, minus the layer: `SettingGiven` is
    // usage-argv's own vocabulary, so a flattened group can hand its parent what it was given
    // without either of them naming the config crate. Emitted whenever it has anything to say —
    // its own bindings, or a group of its own that has some.
    let parts = settings(cli);
    let settings_defs = parts.as_ref().map(|s| {
        let given = &s.given;
        let bindings = &s.bindings;
        quote!(#given #bindings)
    });
    let settings_impl = parts.as_ref().map(|_| {
        quote! {
            const SETTINGS_BINDINGS: &'static [(&'static str, &'static str)] =
                SETTINGS_BINDINGS;

            fn settings_given(
                partial: &Self::Partial,
            ) -> ::std::vec::Vec<(&'static str, usage_argv::spec::SettingGiven)> {
                settings_given(partial)
            }
        }
    });
    let command_key = key_ident("COMMAND", None);
    let restart_token = option_str(cli.restart_token.as_deref());
    let mount = option_str(cli.mount.as_deref());
    let OutputTokens {
        decls: output_schema_decls,
        outputs,
        select,
        exit_codes,
    } = output_tokens(cli);
    // A bare `T` subcommand field says the command cannot run alone; an `Option<T>` says it
    // can. The parser already refuses the invocation from the type — this is so the emitted
    // spec says it too, since help, docs and completions read that rather than the type.
    let flatten_checks = flatten_checks(cli);
    let subcommand_required = cli.fields.iter().any(|f| {
        matches!(
            f.kind,
            Kind::Subcommand {
                optional: false,
                ..
            }
        )
    });
    let subcommand_help_heading = option_str(cli.subcommand_help_heading.as_deref());
    let subcommand_value_name = option_str(cli.subcommand_value_name.as_deref());
    let next_line_help = cli.next_line_help;
    let flatten_help = cli.flatten_help;
    let term_width = option_usize(cli.term_width);
    let max_term_width = option_usize(cli.max_term_width);
    let unknown_flags = unknown_flags_tokens(cli);
    let arg_required_else_help = cli.arg_required_else_help;
    let dont_delimit_trailing_values = cli.dont_delimit_trailing_values;
    let args_override_self = cli.args_override_self;
    let subcommand_negates_reqs = cli.subcommand_negates_reqs;
    let args_conflicts_with_subcommands = cli.args_conflicts_with_subcommands;
    let subcommand_precedence_over_arg = cli.subcommand_precedence_over_arg;
    let allow_missing_positional = cli.allow_missing_positional;
    let disable_help_flag = cli.disable_help_flag;
    let disable_help_subcommand = cli.disable_help_subcommand;
    let disable_version_flag = cli.disable_version_flag;
    let before_help = option_expr(cli.before_help.as_ref());
    let before_long_help = option_expr(cli.before_long_help.as_ref());
    let after_help = option_expr(cli.after_help.as_ref());
    let after_long_help = option_expr(cli.after_long_help.as_ref());
    let examples = examples_table(&cli.examples);
    let headings = headings_table(&cli.headings);

    let flags: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Flag { .. }))
        .collect();
    let args: Vec<&Field> = cli
        .fields
        .iter()
        .filter(|f| matches!(f.kind, Kind::Arg { .. }))
        .collect();

    let keys = key_consts(&cli.fingerprint, flags.len(), args.len());
    let flag_tables = flags.iter().enumerate().map(|(i, f)| flag_table(i, f));
    let arg_tables = args.iter().enumerate().map(|(i, f)| arg_table(i, f));
    let flag_metas = flags
        .iter()
        .enumerate()
        .map(|(i, f)| flag_meta(cli, i, f, &cli.ident));
    let arg_metas = args
        .iter()
        .enumerate()
        .map(|(i, f)| arg_meta(cli, i, f, &cli.ident));
    let clause_field = cli.fields.iter().find_map(|field| match &field.kind {
        Kind::Clause { ty, separator } => Some((field, ty, separator)),
        _ => None,
    });
    let clause_table = clause_field.map_or_else(
        || quote!(::core::option::Option::None),
        |(field, ty, separator)| {
            let name = proc_macro2::Literal::string(&field.name);
            let separator = separator.as_ref().map_or_else(
                || quote!(::core::option::Option::None),
                |value| {
                    let value = proc_macro2::Literal::byte_string(value.as_bytes());
                    quote!(::core::option::Option::Some(#value))
                },
            );
            quote!(::core::option::Option::Some(usage_argv::Clause {
                key: 0, name: #name, separator: #separator,
                flags: <#ty as usage_argv::spec::CommandArgs>::COMMAND.flags,
                args: <#ty as usage_argv::spec::CommandArgs>::COMMAND.args,
            }))
        },
    );
    let clause_meta = clause_field.map_or_else(
        || quote!(::core::option::Option::None),
        |(field, ty, separator)| {
            let name = proc_macro2::Literal::string(&field.name);
            let separator = option_str(separator.as_deref());
            quote!(::core::option::Option::Some(usage_argv::spec::ClauseMeta {
                name: #name, separator: #separator, help: ::core::option::Option::None,
                long_help: ::core::option::Option::None,
                flags: <#ty as usage_argv::spec::CommandArgs>::META.flags,
                args: <#ty as usage_argv::spec::CommandArgs>::META.args,
                canonical_selector: <#ty as usage_argv::spec::CommandArgs>::canonical_selector,
            }))
        },
    );
    let implicit_clause_assertions = clause_field
        .filter(|(_, _, separator)| separator.is_none())
        .map(|(_, ty, _)| {
            quote! {
                const _: () = {
                    const INNER: &usage_argv::Command<'static> =
                        <#ty as usage_argv::spec::CommandArgs>::COMMAND;
                    assert!(INNER.args.len() == 1,
                        "an implicit clause needs exactly one positional argument");
                    assert!(INNER.args[0].required && !INNER.args[0].var,
                        "an implicit clause positional must be required and non-variadic");
                    assert!(INNER.subcommands.is_empty(),
                        "an implicit clause cannot contain subcommands");
                    assert!(INNER.args[0].sigil.is_none(),
                        "an implicit clause positional cannot use a sigil");
                };
            }
        });
    // Both the plain slices and, when a field is flattened, the joined arrays.
    let tables = tables(cli);
    let table_decls = &tables.decls;
    let meta_table_decls = &tables.meta_decls;
    let (group_meta_decl, group_meta_table_ref) = group_meta_table(cli);
    let flag_table_ref = &tables.flags;
    let arg_table_ref = &tables.args;
    let flag_meta_table_ref = &tables.flag_metas;
    let arg_meta_table_ref = &tables.arg_metas;
    let flatten_group_table_ref = &tables.flatten_groups;

    let name = &cli.name;
    let aliases = cli.aliases.iter().chain(&cli.hidden_aliases);
    let hidden_aliases = &cli.hidden_aliases;
    let about = cli
        .about_attr
        .as_ref()
        .map(|value| option_expr(Some(value)))
        .unwrap_or_else(|| option_str(cli.about.as_deref()));
    let long_about = cli
        .long_about_attr
        .as_ref()
        .map(|value| option_expr(Some(value)))
        .unwrap_or_else(|| option_str(cli.long_about.as_deref()));
    let deprecated = option_str(cli.deprecated.as_deref());
    let deprecated_warn_at = option_str(cli.deprecated_warn_at.as_deref());
    let deprecated_remove_at = option_str(cli.deprecated_remove_at.as_deref());
    let surface = option_str(cli.surface.as_deref());
    let available_if = &cli.available_if;
    let partial = partial_struct(cli);
    let argument_lookup = argument_lookup_functions(cli);
    let deprecations = deprecations_fn(cli);
    let defaults = partial_defaults(cli);
    let apply = apply_fn(cli);
    let post = post_binding(cli);
    let merge = merge_fn(cli);
    let parts = subcommand_parts(cli);
    let sub_commands = parts
        .as_ref()
        .map(|p| p.commands.clone())
        .unwrap_or_default();
    let sub_external = parts
        .as_ref()
        .map(|p| p.external.clone())
        .unwrap_or_default();
    let sub_metas = parts.as_ref().map(|p| p.metas.clone()).unwrap_or_default();
    let sub_build = parts.as_ref().map(|p| p.build.clone()).unwrap_or_default();
    let sub_view_build = parts
        .as_ref()
        .map(|p| p.view_build.clone())
        .unwrap_or_default();
    // The same conversion the root gets. Two emitters producing one `build` is what let
    // this diverge: a typed field on a subcommand compiled here and not there, which is
    // every command mise has.
    let field_finals: Vec<_> = cli
        .fields
        .iter()
        .filter(|f| !matches!(f.kind, Kind::Subcommand { .. }))
        .map(|field| field_final(field, None))
        .collect();
    let built = built_value(cli, &sub_build, &field_finals);
    let view_omitter = quote!(__UsageOmitter);
    let view_field_finals: Vec<_> = cli
        .fields
        .iter()
        .filter(|f| !matches!(f.kind, Kind::Subcommand { .. }))
        .map(|field| field_final(field, Some(&view_omitter)))
        .collect();
    let built_for_view = built_value(cli, &sub_view_build, &view_field_finals);
    let view_bounds: Vec<_> = cli
        .fields
        .iter()
        .filter_map(|field| match &field.kind {
            Kind::Flatten { ty, .. } => {
                Some(quote!(#ty: usage_argv::spec::ViewCommandArgs<__UsageOmitter>))
            }
            Kind::Subcommand { ty, .. } => {
                Some(quote!(#ty: usage_argv::spec::ViewSubcommands<__UsageOmitter>))
            }
            // A group is built from what its own members were given either way, so a view
            // never omits it — and imposing `Default` on the enum for a projection that does
            // not need one would be a bound an adopter cannot see the reason for.
            Kind::ArgGroup { .. } => None,
            _ => {
                let ty = &field.ty;
                Some(quote!(__UsageOmitter: usage_argv::spec::Omitted<#ty>))
            }
        })
        .collect();
    let view_where = (!view_bounds.is_empty()).then(|| quote!(where #(#view_bounds,)*));

    let view_path_methods = cli
        .fields
        .iter()
        .find_map(|field| {
            let Kind::Subcommand { ty, .. } = &field.kind else {
                return None;
            };
            Some(quote! {
                fn apply_env_for_view_path(
                    partial: &mut Self::Partial,
                    remaining_descendants: usize,
                ) {
                    if remaining_descendants == 0 {
                        <Self as usage_argv::spec::CommandArgs>::apply_env(partial);
                    } else if let ::std::option::Option::Some(__usage_at) =
                        partial.__usage_selected
                    {
                        <#ty as usage_argv::spec::Subcommands>::apply_env_for_view_path(
                            &mut partial.__usage_sub,
                            ::std::option::Option::Some(__usage_at),
                            remaining_descendants,
                        );
                    }
                }

                fn deprecations_for_view_path(
                    partial: &Self::Partial,
                    remaining_descendants: usize,
                    out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) {
                    if remaining_descendants == 0 {
                        <Self as usage_argv::spec::CommandArgs>::deprecations(partial, out);
                    } else if let ::std::option::Option::Some(__usage_at) =
                        partial.__usage_selected
                    {
                        // Structural under this view, like `check_for_view_path`: an injected
                        // parent's own declarations are not the promoted executable's surface,
                        // so nothing about them is reported.
                        <#ty as usage_argv::spec::Subcommands>::deprecations_for_view_path(
                            &partial.__usage_sub,
                            ::std::option::Option::Some(__usage_at),
                            remaining_descendants,
                            out,
                        );
                    }
                }

                fn check_for_view_path<'t, 'v>(
                    partial: &mut Self::Partial,
                    remaining_descendants: usize,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    if remaining_descendants == 0 {
                        <Self as usage_argv::spec::CommandArgs>::check(partial)
                    } else if let ::std::option::Option::Some(__usage_at) =
                        partial.__usage_selected
                    {
                        <Self as usage_argv::spec::CommandArgs>::omit_own_for_view(partial);
                        <#ty as usage_argv::spec::Subcommands>::check_for_view_path(
                            &mut partial.__usage_sub,
                            __usage_at,
                            remaining_descendants,
                        )
                    } else {
                        ::std::result::Result::Ok(())
                    }
                }
            })
        })
        .unwrap_or_default();
    let omit_flattened = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            <#ty as usage_argv::spec::CommandArgs>::omit_own_for_view(&mut partial.#ident);
        })
    });
    let omit_own = quote! {
        fn omit_own_for_view(partial: &mut Self::Partial) {
            partial.__usage_omit_own = true;
            #(#omit_flattened)*
        }
    };

    // The root cannot carry one — the spec writer asserts it — so this is the non-root
    // path's alone, which is also the only path a command's own declaration reaches.
    let effect = cli
        .effect
        .clone()
        .unwrap_or_else(|| quote!(::core::option::Option::None));
    let hide = cli.hide;
    quote! {
        #[doc(hidden)]
        #[allow(
            non_upper_case_globals,
            non_snake_case,
            unused_imports,
            // Fires when a metadata struct happens to be fully specified. `..EMPTY`
            // is kept on purpose: it is what lets usage-argv gain a metadata field
            // without breaking every crate that derives.
            clippy::needless_update
        )]
        const _: () = {
            use #runtime as usage_argv;
            #validation_import

            #flatten_checks
            #keys
            #(#flag_tables)*
            #(#arg_tables)*
            #table_decls

            pub static COMMAND: usage_argv::Command = usage_argv::Command {
                name: #name,
                aliases: &[#(#aliases),*],
                key: #command_key,
                unknown_flags: #unknown_flags,
                arg_required_else_help: #arg_required_else_help,
                subcommand_negates_reqs: #subcommand_negates_reqs,
                args_conflicts_with_subcommands: #args_conflicts_with_subcommands,
                subcommand_precedence_over_arg: #subcommand_precedence_over_arg,
                allow_missing_positional: #allow_missing_positional,
                disable_help_flag: #disable_help_flag,
                disable_help_subcommand: #disable_help_subcommand,
                disable_version_flag: #disable_version_flag,
                dont_delimit_trailing_values: #dont_delimit_trailing_values,
                flags: #flag_table_ref,
                args: #arg_table_ref,
                clause: #clause_table,
                #sub_commands
                #sub_external
                ..usage_argv::Command::EMPTY
            };
            #implicit_clause_assertions
            const _: () = usage_argv::assert_clause_flag_spellings(&COMMAND);

            #(#flag_metas)*
            #(#arg_metas)*
            #meta_table_decls

            #group_meta_decl

            #(#output_schema_decls)*

            pub static COMMAND_META: usage_argv::spec::CommandMeta = usage_argv::spec::CommandMeta {
                cmd: &COMMAND,
                outputs: #outputs,
                select: #select,
                exit_codes: #exit_codes,
                effect: #effect,
                about: #about,
                long_about: #long_about,
                deprecated: #deprecated,
                deprecated_warn_at: #deprecated_warn_at,
                deprecated_remove_at: #deprecated_remove_at,
                surface: #surface,
                available_if: &[#(#available_if),*],
                hidden_aliases: &[#(#hidden_aliases),*],
                hide: #hide,
                restart_token: #restart_token,
                subcommand_required: #subcommand_required,
                subcommand_help_heading: #subcommand_help_heading,
                subcommand_value_name: #subcommand_value_name,
                next_line_help: #next_line_help,
                flatten_help: #flatten_help,
                term_width: #term_width,
                max_term_width: #max_term_width,
                args_override_self: #args_override_self,
                mount: #mount,
                before_help: #before_help,
                before_long_help: #before_long_help,
                after_help: #after_help,
                after_long_help: #after_long_help,
                examples: #examples,
                headings: #headings,
                flags: #flag_meta_table_ref,
                args: #arg_meta_table_ref,
                clause: #clause_meta,
                groups: #group_meta_table_ref,
                flatten_groups: #flatten_group_table_ref,
                #sub_metas
                ..usage_argv::spec::CommandMeta::EMPTY
            };

            pub fn __usage_text(value: &[u8]) -> ::std::vec::Vec<u8> {
                value.to_vec()
            }

            pub fn __usage_value_text(
                value: ::std::option::Option<&[u8]>,
            ) -> ::std::vec::Vec<u8> {
                value.map(__usage_text).unwrap_or_default()
            }

            #partial
            #apply
            #argument_lookup
            #deprecations

            pub fn start() -> Partial {
                #defaults
                partial
            }

            /// Every declared default this command has, filling what nothing else did.
            ///
            /// `__usage_standing` is what an update already had, and `None` for an ordinary
            /// parse: a default does not overwrite a value the caller set deliberately.
            fn apply_declared_defaults(
                partial: &mut Partial,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
                __usage_standing: ::std::option::Option<&#ident>,
            ) {
                let _ = __usage_standing.is_some();
                #apply_defaults
            }

            /// [`apply_declared_defaults`], for the environment rather than for declared
            /// defaults.
            fn apply_env_fallbacks(
                partial: &mut Partial,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
                __usage_standing: ::std::option::Option<&#ident>,
            ) {
                let _ = __usage_standing.is_some();
                #apply_env
            }

            /// Everything decided after the last token, for this command.
            ///
            /// Separate from `build` because only the *selected* command's
            /// requirements apply: a flag that `install` requires says nothing about
            /// an invocation that ran `run`.
            ///
            /// `__usage_standing` is what an update already had: `None` for an ordinary
            /// parse, which folds every question about it away. One body rather than an
            /// update-only copy, because this is the largest function a command generates.
            fn check_with_args_override_self_for_view_standing<'t, 'v>(
                partial: &mut Partial,
                args_override_self: bool,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
                __usage_standing: ::std::option::Option<&#ident>,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                partial.__usage_view = __usage_view;
                // Read unconditionally: a command that declares nothing to check would
                // otherwise leave the parameter unused in the user's crate, where
                // nobody can silence it.
                let _ = (&partial, __usage_standing.is_some());
                #post
                ::std::result::Result::Ok(())
            }

            fn check_with_args_override_self_for_view<'t, 'v>(
                partial: &mut Partial,
                args_override_self: bool,
                __usage_view: ::std::option::Option<
                    &'static usage_argv::spec::ViewMeta<'static>,
                >,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_args_override_self_for_view_standing(
                    partial,
                    args_override_self,
                    __usage_view,
                    ::std::option::Option::None,
                )
            }

            pub fn check_with_args_override_self<'t, 'v>(
                partial: &mut Partial,
                args_override_self: bool,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_args_override_self_for_view(
                    partial,
                    args_override_self,
                    ::std::option::Option::None,
                )
            }

            pub fn check<'t, 'v>(
                partial: &mut Partial,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_args_override_self(partial, #args_override_self)
            }

            /// `check`, against the union of this command line and what the caller had.
            pub fn check_update_with_args_override_self<'t, 'v>(
                partial: &mut Partial,
                args_override_self: bool,
                __usage_standing: &#ident,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_with_args_override_self_for_view_standing(
                    partial,
                    args_override_self,
                    ::std::option::Option::None,
                    ::std::option::Option::Some(__usage_standing),
                )
            }

            pub fn check_update<'t, 'v>(
                partial: &mut Partial,
                __usage_standing: &#ident,
            ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                check_update_with_args_override_self(
                    partial,
                    #args_override_self,
                    __usage_standing,
                )
            }

            #merge

            #settings_defs

            impl usage_argv::spec::CommandArgs for #ident {
                type Partial = Partial;

                const COMMAND: &'static usage_argv::Command<'static> = &COMMAND;
                const META: &'static usage_argv::spec::CommandMeta<'static> =
                    &COMMAND_META;

                fn start() -> Self::Partial {
                    start()
                }

                fn apply(
                    partial: &mut Self::Partial,
                    event: &usage_argv::Event<'_, '_, '_>,
                ) -> bool {
                    apply(partial, event)
                }

                fn apply_mirrored_global(
                    partial: &mut Self::Partial,
                    event: &usage_argv::Event<'_, '_, '_>,
                ) -> bool {
                    apply_mirrored_global(partial, event)
                }

                fn deprecations(
                    partial: &Self::Partial,
                    out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) {
                    deprecations(partial, out)
                }

                fn check<'t, 'v>(
                    partial: &mut Self::Partial,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    check(partial)
                }

                fn check_with_args_override_self<'t, 'v>(
                    partial: &mut Self::Partial,
                    args_override_self: bool,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    check_with_args_override_self(partial, args_override_self)
                }

                fn check_with_args_override_self_for_view<'t, 'v>(
                    partial: &mut Self::Partial,
                    args_override_self: bool,
                    view: ::std::option::Option<
                        &'static usage_argv::spec::ViewMeta<'static>,
                    >,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    check_with_args_override_self_for_view(partial, args_override_self, view)
                }

                fn check_update<'t, 'v>(
                    partial: &mut Self::Partial,
                    standing: &Self,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    check_update(partial, standing)
                }

                fn check_update_with_args_override_self<'t, 'v>(
                    partial: &mut Self::Partial,
                    args_override_self: bool,
                    standing: &Self,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    check_update_with_args_override_self(
                        partial,
                        args_override_self,
                        standing,
                    )
                }

                #presence
                #any_standing

                fn apply_defaults(partial: &mut Self::Partial) {
                    apply_declared_defaults(
                        partial,
                        ::std::option::Option::None,
                        ::std::option::Option::None,
                    )
                }

                fn apply_defaults_for_view(
                    partial: &mut Self::Partial,
                    __usage_view: ::std::option::Option<
                        &'static usage_argv::spec::ViewMeta<'static>,
                    >,
                ) {
                    apply_declared_defaults(
                        partial,
                        __usage_view,
                        ::std::option::Option::None,
                    )
                }

                fn apply_defaults_update(partial: &mut Self::Partial, standing: &Self) {
                    apply_declared_defaults(
                        partial,
                        ::std::option::Option::None,
                        ::std::option::Option::Some(standing),
                    )
                }

                fn apply_env(partial: &mut Self::Partial) {
                    apply_env_fallbacks(
                        partial,
                        ::std::option::Option::None,
                        ::std::option::Option::None,
                    )
                }

                fn apply_env_for_view(
                    partial: &mut Self::Partial,
                    __usage_view: ::std::option::Option<
                        &'static usage_argv::spec::ViewMeta<'static>,
                    >,
                ) {
                    apply_env_fallbacks(
                        partial,
                        __usage_view,
                        ::std::option::Option::None,
                    )
                }

                fn apply_env_update(partial: &mut Self::Partial, standing: &Self) {
                    apply_env_fallbacks(
                        partial,
                        ::std::option::Option::None,
                        ::std::option::Option::Some(standing),
                    )
                }

                #view_path_methods
                #omit_own

                #settings_impl

                fn build<'t, 'v>(
                    partial: Self::Partial,
                ) -> ::std::result::Result<Self, usage_argv::Error<'t, 'v>> {
                    ::std::result::Result::Ok(#built)
                }

                fn merge<'t, 'v>(
                    partial: Self::Partial,
                    standing: &mut Self,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    merge(partial, standing)
                }
            }

            impl<__UsageOmitter> usage_argv::spec::ViewCommandArgs<__UsageOmitter>
                for #ident
                #view_where
            {
                fn build_for_view<'t, 'v>(
                    partial: Self::Partial,
                ) -> ::std::result::Result<Self, usage_argv::Error<'t, 'v>> {
                    ::std::result::Result::Ok(#built_for_view)
                }
            }
        };

        #dispatch
    }
}

/// The enum a `subcommand` field holds: its variants' tables, and the trait a
/// parent uses to route events into them.
fn rewrite_inline_arg_meta(meta: &mut syn::Meta) {
    if matches!(meta, syn::Meta::Path(path) if path.is_ident("arg")) {
        *meta = syn::parse_quote!(usage(arg));
        return;
    }
    let path = match meta {
        syn::Meta::Path(path) => path,
        syn::Meta::List(list) => &mut list.path,
        syn::Meta::NameValue(value) => &mut value.path,
    };
    if path.is_ident("arg") {
        *path = syn::parse_quote!(usage);
        return;
    }
    if !path.is_ident("cfg_attr") {
        return;
    }
    let syn::Meta::List(list) = meta else {
        return;
    };
    let parser = syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated;
    let Ok(mut nested) = syn::parse::Parser::parse2(parser, list.tokens.clone()) else {
        return;
    };
    for value in nested.iter_mut().skip(1) {
        rewrite_inline_arg_meta(value);
    }
    list.tokens = quote!(#nested);
}

fn inline_field_meta(meta: &syn::Meta) -> Option<syn::Meta> {
    if meta.path().is_ident("arg") {
        let mut meta = meta.clone();
        rewrite_inline_arg_meta(&mut meta);
        return Some(meta);
    }
    if meta.path().is_ident("usage") || meta.path().is_ident("doc") || meta.path().is_ident("cfg") {
        return Some(meta.clone());
    }
    let syn::Meta::List(list) = meta else {
        return None;
    };
    if !list.path.is_ident("cfg_attr") {
        return None;
    }
    let parser = syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated;
    let nested = syn::parse::Parser::parse2(parser, list.tokens.clone()).ok()?;
    let mut nested = nested.into_iter();
    let condition = nested.next()?;
    let kept = nested
        .filter_map(|meta| inline_field_meta(&meta))
        .collect::<Vec<_>>();
    if kept.is_empty() {
        return None;
    }
    syn::parse2(quote!(cfg_attr(#condition, #(#kept),*))).ok()
}

fn inline_field_attr(attr: syn::Attribute) -> Option<syn::Attribute> {
    let meta = inline_field_meta(&attr.meta)?;
    Some(syn::Attribute { meta, ..attr })
}

fn meta_controls_field_presence(meta: &syn::Meta) -> bool {
    if meta.path().is_ident("cfg") {
        return true;
    }
    let syn::Meta::List(list) = meta else {
        return false;
    };
    if !list.path.is_ident("cfg_attr") {
        return false;
    }
    let parser = syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated;
    syn::parse::Parser::parse2(parser, list.tokens.clone())
        .is_ok_and(|nested| nested.iter().skip(1).any(meta_controls_field_presence))
}

/// One of the four dispatch traits, as the generated code needs to speak about it.
///
/// They differ in two bits — whether the command is handed a context, and whether it is
/// awaited — and in nothing else, so they are described here rather than written out four
/// times over.
struct DispatchTrait {
    /// Whether the enum or struct asked for this one.
    wanted: bool,
    /// `Run`, `RunWith`, `RunAsync`, `RunAsyncWith`.
    name: &'static str,
    /// `run`, `run_with`, `run_async`, `run_async_with`.
    method: &'static str,
    /// Whether the trait takes a context, which is what makes the generated implementation
    /// generic — and, being generic, inert until something calls it.
    ctx: bool,
    /// Whether the implementation is an `async fn` whose arms are awaited.
    is_async: bool,
}

impl DispatchTrait {
    /// The four, in the order a CLI meets them.
    fn all(dispatch: Dispatch) -> [Self; 4] {
        [
            DispatchTrait {
                wanted: dispatch.run,
                name: "Run",
                method: "run",
                ctx: false,
                is_async: false,
            },
            DispatchTrait {
                wanted: dispatch.run_with,
                name: "RunWith",
                method: "run_with",
                ctx: true,
                is_async: false,
            },
            DispatchTrait {
                wanted: dispatch.run_async,
                name: "RunAsync",
                method: "run_async",
                ctx: false,
                is_async: true,
            },
            DispatchTrait {
                wanted: dispatch.run_async_with,
                name: "RunAsyncWith",
                method: "run_async_with",
                ctx: true,
                is_async: true,
            },
        ]
    }

    /// `usage_argv::Run`, or `usage_argv::RunWith<__UsageCtx>` for one that takes a context.
    fn path(&self) -> TokenStream {
        let name = format_ident!("{}", self.name);
        if self.ctx {
            quote!(usage_argv::#name<__UsageCtx>)
        } else {
            quote!(usage_argv::#name)
        }
    }

    /// The same, of another type: `<Install as usage_argv::Run>`.
    fn as_of(&self, ty: &TokenStream) -> TokenStream {
        let path = self.path();
        quote!(<#ty as #path>)
    }

    /// The trait with the output it has to produce, which is one variant's whole bound.
    ///
    /// The binding goes inside the same angle brackets as the context, since
    /// `RunWith<__UsageCtx><Output = …>` is two generic lists rather than one bound.
    fn path_with_output(&self, output: &TokenStream) -> TokenStream {
        let name = format_ident!("{}", self.name);
        if self.ctx {
            quote!(usage_argv::#name<__UsageCtx, Output = #output>)
        } else {
            quote!(usage_argv::#name<Output = #output>)
        }
    }

    /// `impl`, or `impl<__UsageCtx>` for one that takes a context.
    fn impl_generics(&self) -> TokenStream {
        if self.ctx {
            quote!(impl<__UsageCtx>)
        } else {
            quote!(impl)
        }
    }

    /// The method's declaration, up to its body.
    ///
    /// The async traits declare `-> impl Future<Output = Self::Output>` and an implementation
    /// answers with an `async fn`, which is the same signature and imposes no `Send` bound.
    fn signature(&self) -> TokenStream {
        let method = format_ident!("{}", self.method);
        let asyncness = self.is_async.then(|| quote!(async));
        if self.ctx {
            quote!(#asyncness fn #method(self, __usage_ctx: __UsageCtx) -> Self::Output)
        } else {
            quote!(#asyncness fn #method(self) -> Self::Output)
        }
    }

    /// A call into this trait for one command's value.
    ///
    /// The context's type is turbofished rather than written as `RunWith<__UsageCtx>::run_with`,
    /// which is a chain of comparisons in expression position rather than a path.
    fn call(&self, value: TokenStream) -> TokenStream {
        let name = format_ident!("{}", self.name);
        let method = format_ident!("{}", self.method);
        let call = if self.ctx {
            quote!(usage_argv::#name::<__UsageCtx>::#method(#value, __usage_ctx))
        } else {
            quote!(usage_argv::#name::#method(#value))
        };
        if self.is_async {
            quote!(#call.await)
        } else {
            call
        }
    }
}

/// Which trait one variant actually implements, which may differ from the enum's.
///
/// A `#[usage(run)]` variant in an async enum is synchronous; `#[usage(no_ctx)]` skips
/// the context the rest of the match is handed. The generated arm and its bound both
/// read this so they cannot disagree.
fn arm_kind(kind: &DispatchTrait, v: &Variant) -> DispatchTrait {
    let is_async = kind.is_async && !v.run_sync;
    let ctx = kind.ctx && !v.no_ctx;
    match (is_async, ctx) {
        (false, false) => DispatchTrait {
            wanted: true,
            name: "Run",
            method: "run",
            ctx: false,
            is_async: false,
        },
        (false, true) => DispatchTrait {
            wanted: true,
            name: "RunWith",
            method: "run_with",
            ctx: true,
            is_async: false,
        },
        (true, false) => DispatchTrait {
            wanted: true,
            name: "RunAsync",
            method: "run_async",
            ctx: false,
            is_async: true,
        },
        (true, true) => DispatchTrait {
            wanted: true,
            name: "RunAsyncWith",
            method: "run_async_with",
            ctx: true,
            is_async: true,
        },
    }
}

fn first_command(subs: &Subcommands) -> Option<&Variant> {
    subs.variants.iter().find(|v| !v.external)
}

fn dispatch_output_ty(subs: &Subcommands, kind: &DispatchTrait) -> TokenStream {
    if let Some(ty) = &subs.dispatch_output {
        return quote!(#ty);
    }
    let first = first_command(subs).expect("a dispatched enum names a command");
    let ty = &first.ty;
    let of = arm_kind(kind, first).as_of(&quote!(#ty));
    quote!(#of::Output)
}

fn dispatch_pat(enum_ident: &syn::Ident, v: &Variant) -> TokenStream {
    let variant = &v.ident;
    if v.unit {
        quote!(#enum_ident::#variant)
    } else if let Some(fields) = &v.inline_fields {
        let bindings = fields.iter().map(|field| {
            let name = field
                .ident
                .as_ref()
                .expect("named variant fields have names");
            let cfg_attrs = field
                .attrs
                .iter()
                .filter(|attr| meta_controls_field_presence(&attr.meta));
            quote! { #(#cfg_attrs)* #name }
        });
        quote!(#enum_ident::#variant { #(#bindings),* })
    } else {
        quote!(#enum_ident::#variant(__usage_inner))
    }
}

fn dispatch_value(v: &Variant) -> TokenStream {
    if v.unit {
        let ty = &v.ty;
        quote!(#ty {})
    } else if let Some(fields) = &v.inline_fields {
        let ty = &v.ty;
        let bindings = fields.iter().map(|field| {
            let name = field
                .ident
                .as_ref()
                .expect("named variant fields have names");
            let cfg_attrs = field
                .attrs
                .iter()
                .filter(|attr| meta_controls_field_presence(&attr.meta));
            quote! { #(#cfg_attrs)* #name }
        });
        quote!(#ty { #(#bindings),* })
    } else if v.boxed {
        quote!(*__usage_inner)
    } else {
        quote!(__usage_inner)
    }
}

fn dispatch_arm_call(
    kind: &DispatchTrait,
    v: &Variant,
    ident: &syn::Ident,
    external: Option<&syn::Path>,
) -> TokenStream {
    let pat = dispatch_pat(ident, v);
    let value = dispatch_value(v);
    let call = if v.external {
        let path = external.expect("external variants name a function");
        let call = if kind.ctx {
            quote!(#path(#value, __usage_ctx))
        } else {
            quote!(#path(#value))
        };
        if kind.is_async {
            quote!(#call.await)
        } else {
            call
        }
    } else {
        let arm = arm_kind(kind, v);
        let mut call = arm.call(value);
        if kind.ctx && !arm.ctx {
            call = quote! {{
                let _ = __usage_ctx;
                #call
            }};
        }
        call
    };
    quote!(#pat => #call,)
}

fn variant_bound(
    kind: &DispatchTrait,
    v: &Variant,
    i: usize,
    first_non_external: usize,
    output: &TokenStream,
    named_output: bool,
) -> Option<TokenStream> {
    if v.external {
        return None;
    }
    let ty = &v.ty;
    let arm = arm_kind(kind, v);
    if named_output || i != first_non_external {
        let bound = arm.path_with_output(output);
        Some(quote!(#ty: #bound))
    } else {
        let path = arm.path();
        Some(quote!(#ty: #path))
    }
}

fn lazy_arm_call(
    kind: &DispatchTrait,
    v: &Variant,
    ident: &syn::Ident,
    external: Option<&syn::Path>,
) -> TokenStream {
    let pat = dispatch_pat(ident, v);
    let value = dispatch_value(v);
    let arm = arm_kind(kind, v);
    let call = if v.external {
        let path = external.expect("external variants name a function");
        let invoked = if kind.ctx {
            quote!(#path(#value, __usage_load()))
        } else {
            quote! {{
                let _ = __usage_load;
                #path(#value)
            }}
        };
        if kind.is_async {
            quote!(#invoked.await)
        } else {
            invoked
        }
    } else if arm.ctx {
        let name = format_ident!("{}", arm.name);
        let method = format_ident!("{}", arm.method);
        let invoked = quote!(usage_argv::#name::<__UsageCtx>::#method(#value, __usage_load()));
        if arm.is_async {
            quote!(#invoked.await)
        } else {
            invoked
        }
    } else {
        let mut call = arm.call(value);
        call = quote! {{
            let _ = __usage_load;
            #call
        }};
        call
    };
    quote!(#pat => #call,)
}

/// The dispatch a `#[usage(run)]` enum gets: the `match` every CLI writes by hand.
///
/// One arm per variant, handing the command's own struct to the trait that carries it out.
/// Nothing here reaches the spec, the parse tables, or help: which Rust function runs a
/// command is not part of what the CLI *is*, and a spec recording it could be read by nothing
/// but this program. `#[usage(skip)]` follows the same rule.
///
/// The output type is the first command's, unless the enum names it, and every other variant
/// is required to agree — stated as a bound naming that variant's type, so a command returning
/// something else is reported on the command rather than inside a generated arm. Both bounds
/// are written as `where` clauses rather than checked here, which is also what lets the enum
/// be declared before the implementations it dispatches to exist.
fn emit_subcommands_dispatch(subs: &Subcommands, runtime: &TokenStream) -> TokenStream {
    if !subs.dispatch.any() {
        return TokenStream::new();
    }
    let ident = &subs.ident;
    let external = subs.dispatch_external.as_ref();
    let named_output = subs.dispatch_output.is_some();
    let first_non_external = subs.variants.iter().position(|v| !v.external).unwrap_or(0);
    let wants_lazy = subs.variants.iter().any(|v| v.no_ctx)
        && (subs.dispatch.run_with || subs.dispatch.run_async_with);

    let impls = DispatchTrait::all(subs.dispatch)
        .into_iter()
        .filter(|kind| kind.wanted)
        .map(|kind| {
            let generics = kind.impl_generics();
            let path = kind.path();
            let signature = kind.signature();
            let output = dispatch_output_ty(subs, &kind);
            let bounds = subs.variants.iter().enumerate().filter_map(|(i, v)| {
                variant_bound(&kind, v, i, first_non_external, &output, named_output)
            });
            let arms = subs
                .variants
                .iter()
                .map(|v| dispatch_arm_call(&kind, v, ident, external));
            quote! {
                #generics #path for #ident
                where
                    #(#bounds,)*
                {
                    type Output = #output;

                    #signature {
                        match self {
                            #(#arms)*
                        }
                    }
                }
            }
        });

    let lazy = DispatchTrait::all(subs.dispatch)
        .into_iter()
        .filter(|kind| kind.wanted && kind.ctx && wants_lazy)
        .map(|kind| {
            let output = dispatch_output_ty(subs, &kind);
            let arms = subs
                .variants
                .iter()
                .map(|v| lazy_arm_call(&kind, v, ident, external));
            let (name, asyncness) = if kind.is_async {
                (format_ident!("run_async_with_lazy"), quote!(async))
            } else {
                (format_ident!("run_with_lazy"), TokenStream::new())
            };
            let bounds = subs.variants.iter().enumerate().filter_map(|(i, v)| {
                variant_bound(&kind, v, i, first_non_external, &output, named_output)
            });
            quote! {
                impl #ident {
                    pub #asyncness fn #name<__UsageCtx, __UsageLoad>(
                        self,
                        __usage_load: __UsageLoad,
                    ) -> #output
                    where
                        __UsageLoad: ::core::ops::FnOnce() -> __UsageCtx,
                        #(#bounds,)*
                    {
                        match self {
                            #(#arms)*
                        }
                    }
                }
            }
        });

    quote! {
        #[doc(hidden)]
        const _: () = {
            use #runtime as usage_argv;

            #(#impls)*
            #(#lazy)*
        };
    }
}

/// The dispatch a `#[usage(run)]` struct gets: a forward to its subcommands.
///
/// A container that holds only that field implements the trait. A root that also
/// declares flags gets `run_command`, which moves the subcommand out and leaves the
/// flags for whoever parsed them.
fn emit_command_dispatch(cli: &Cli, runtime: &TokenStream) -> TokenStream {
    if !cli.dispatch.any() {
        return TokenStream::new();
    }
    let ident = &cli.ident;
    let Some((field, held_ty)) = cli.fields.iter().find_map(|field| match &field.kind {
        Kind::Subcommand {
            ty,
            optional: false,
        } => Some((&field.ident, ty)),
        _ => None,
    }) else {
        return TokenStream::new();
    };
    let held_ty = quote!(#held_ty);
    let extras = cli.fields.iter().any(|field| {
        !matches!(
            field.kind,
            Kind::Subcommand {
                optional: false,
                ..
            }
        )
    });

    if extras {
        let methods = DispatchTrait::all(cli.dispatch)
            .into_iter()
            .filter(|kind| kind.wanted)
            .map(|kind| {
                let held = kind.as_of(&held_ty);
                let output = quote!(#held::Output);
                let value = quote!(#field);
                let call = kind.call(value);
                let name = if kind.is_async && kind.ctx {
                    format_ident!("run_command_async_with")
                } else if kind.is_async {
                    format_ident!("run_command_async")
                } else if kind.ctx {
                    format_ident!("run_command_with")
                } else {
                    format_ident!("run_command")
                };
                let asyncness = kind.is_async.then(|| quote!(async));
                let generics = kind.ctx.then(|| quote!(<__UsageCtx>));
                let ctx_arg = kind.ctx.then(|| quote!(, __usage_ctx: __UsageCtx));
                let path = kind.path();
                quote! {
                    pub #asyncness fn #name #generics(self #ctx_arg) -> #output
                    where
                        #held_ty: #path,
                    {
                        let Self { #field, .. } = self;
                        #call
                    }
                }
            });
        return quote! {
            #[doc(hidden)]
            const _: () = {
                use #runtime as usage_argv;

                impl #ident {
                    #(#methods)*
                }
            };
        };
    }

    let impls = DispatchTrait::all(cli.dispatch)
        .into_iter()
        .filter(|kind| kind.wanted)
        .map(|kind| {
            let generics = kind.impl_generics();
            let path = kind.path();
            let signature = kind.signature();
            let held = kind.as_of(&held_ty);
            let call = kind.call(quote!(self.#field));
            quote! {
                #generics #path for #ident
                where
                    #held_ty: #path,
                {
                    type Output = #held::Output;

                    #signature {
                        #call
                    }
                }
            }
        });

    quote! {
        #[doc(hidden)]
        const _: () = {
            use #runtime as usage_argv;

            #(#impls)*
        };
    }
}

pub fn emit_subcommands(subs: &Subcommands) -> TokenStream {
    let ident = &subs.ident;
    let runtime = runtime_path();
    let derive = derive_path();
    let dispatch = emit_subcommands_dispatch(subs, &runtime);

    // The structs bare and inline variants imply, written here so everything downstream keeps
    // speaking to one Args struct. Clap-shaped `arg` attributes are rewritten to the native
    // spelling while copying inline fields, which lets a migration keep its enum layout.
    let generated_structs = subs
        .variants
        .iter()
        .filter(|v| v.unit || v.inline_fields.is_some())
        .map(|v| {
            let name = &v.ty;
            // Whatever the variant said about the command, written where the command's
            // metadata is actually built — and read there by the same code that reads it on
            // any other `Args`.
            let effect = v
                .effect
                .as_ref()
                .map(|word| quote!(#[usage(effect = #word)]));
            let hidden = quote!(#name).to_string().contains("__Usage");
            let fields = v.inline_fields.iter().flatten().cloned().map(|mut field| {
                field.attrs = field
                    .attrs
                    .into_iter()
                    .filter_map(inline_field_attr)
                    .collect();
                if !hidden {
                    field.vis = syn::parse_quote!(pub);
                }
                field
            });
            let doc = if hidden {
                quote!(#[doc(hidden)])
            } else {
                let variant = v.ident.to_string();
                let enum_name = ident.to_string();
                let doc = format!(
                    "Parsed arguments for `{enum_name}::{variant}`. Implement `usage::Run` \
                     (or the context / async pair) on this type."
                );
                quote!(#[doc = #doc])
            };
            quote! {
                #doc
                #[derive(#derive::Args)]
                #effect
                pub struct #name {
                    #(#fields),*
                }
            }
        })
        .collect::<Vec<_>>();
    let generated_structs = generated_structs.into_iter();

    // One *variant* per subcommand, not one field: a parse fills exactly one of them, and a
    // struct with room for all of them is the whole CLI's accumulator whichever command ran —
    // 11KB of it at mise's scale, of which 210 commands' worth is never touched. The variant
    // comes into being when a command word selects it, in `begin`.
    let partial_variants = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote!(#variant(::std::vec::Vec<::std::vec::Vec<u8>>),)
        } else {
            let ty = &v.ty;
            quote!(#variant(<#ty as usage_argv::spec::CommandArgs>::Partial),)
        }
    });
    // Idempotent, as the trait requires: a restart token can re-announce the command that is
    // already selected, and starting it again there would throw away the parse so far.
    let begins = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                #i => {
                    if !::std::matches!(partial, Partial::#variant(_)) {
                        *partial = Partial::#variant(::std::vec::Vec::new());
                    }
                }
            }
        } else {
            let ty = &v.ty;
            quote! {
                #i => {
                    if !::std::matches!(partial, Partial::#variant(_)) {
                        *partial = Partial::#variant(
                            <#ty as usage_argv::spec::CommandArgs>::start(),
                        );
                    }
                }
            }
        }
    });
    let applies = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        if let usage_argv::Event::External { values } = event {
                            __usage_p.extend(
                                values.iter().map(|v| v.as_encoded_bytes().to_vec()),
                            );
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                }
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::apply(__usage_p, event)
                    } else {
                        // `begin` put this variant here on the event that selected it, so the
                        // partial always matches the selection. An event with nowhere to go was
                        // not this command's.
                        false
                    }
                }
            }
        }
    });
    // The enum is where the command set is declared, so the variant names the
    // command — its own kebab-case name, or whatever `name` says. Splicing the
    // struct's table unchanged would have used the *struct's* name instead, which
    // only looks right when the two happen to match.
    let command_overrides = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, v)| {
            let name = format_ident!("COMMAND_{i}");
            let alias_groups = format_ident!("ALIAS_GROUPS_{i}");
            let aliases_name = format_ident!("ALIASES_{i}");
            let ty = &v.ty;
            let cmd_name = &v.name;
            // Both kinds of alias go in the table, because the parser matches both; which of
            // them help and completions mention is the metadata's business, below.
            let aliases = v.aliases.iter().chain(&v.hidden_aliases);
            quote! {
                const #alias_groups: &[&[&str]] = &[
                    <#ty as usage_argv::spec::CommandArgs>::COMMAND.aliases,
                    &[#(#aliases),*],
                ];
                static #aliases_name: [&str; usage_argv::table_len(#alias_groups)] =
                    usage_argv::spec::concat_aliases(#alias_groups);
                pub static #name: usage_argv::Command = usage_argv::Command {
                    name: #cmd_name,
                    aliases: &#aliases_name,
                    ..*<#ty as usage_argv::spec::CommandArgs>::COMMAND
                };
            }
        });
    let commands = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, _)| {
            let name = format_ident!("COMMAND_{i}");
            quote!(&#name)
        });
    let unique_commands = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, _)| {
            let name = format_ident!("COMMAND_{i}");
            quote!(&#name)
        });
    let variant_of = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, _)| quote!(#i));
    let has_external = subs.variants.iter().any(|v| v.external);
    let external_const = match subs.variants.iter().position(|v| v.external) {
        Some(i) => quote!(::std::option::Option::Some(#i)),
        None => quote!(::std::option::Option::None),
    };
    // A doc comment on the variant wins over the struct's, since that is where a
    // reader of the enum expects to describe the command — and ignoring it would lose
    // the description without saying so. Overriding one field of the struct's
    // metadata is possible in a const, so the tables stay static.
    let meta_overrides = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, v)| {
            let name = format_ident!("META_{i}");
            let cmd = format_ident!("COMMAND_{i}");
            let hidden_groups = format_ident!("HIDDEN_ALIAS_GROUPS_{i}");
            let hidden_name = format_ident!("HIDDEN_ALIASES_{i}");
            let ty = &v.ty;
            // A doc comment on the variant wins over the struct's, since that is where a
            // reader of the enum expects to describe the command. Absent one, the
            // struct's own description carries through.
            // Each falls back on its own. A variant that gives a short description was suppressing
            // the struct's long one, which is exactly how a generated CLI is shaped: the enum says
            // what the command is for in a line, and the struct's own comment carries the rest. The
            // long form went missing from help for every command written that way.
            let about = match v.help.as_ref() {
                Some(help) => option_expr(Some(help)),
                None => quote!(<#ty as usage_argv::spec::CommandArgs>::META.about),
            };
            let long_about = match v.long_help.as_ref() {
                Some(long) => option_expr(Some(long)),
                None => quote!(<#ty as usage_argv::spec::CommandArgs>::META.long_about),
            };
            let deprecated = v
                .deprecated
                .as_deref()
                .map(|value| option_str(Some(value)))
                .unwrap_or_else(|| quote!(<#ty as usage_argv::spec::CommandArgs>::META.deprecated));
            let deprecated_warn_at = v
                .deprecated_warn_at
                .as_deref()
                .map(|value| option_str(Some(value)))
                .unwrap_or_else(
                    || quote!(<#ty as usage_argv::spec::CommandArgs>::META.deprecated_warn_at),
                );
            let deprecated_remove_at = v
                .deprecated_remove_at
                .as_deref()
                .map(|value| option_str(Some(value)))
                .unwrap_or_else(
                    || quote!(<#ty as usage_argv::spec::CommandArgs>::META.deprecated_remove_at),
                );
            let before_help = v
                .before_help
                .as_ref()
                .map(|value| option_expr(Some(value)))
                .unwrap_or_else(
                    || quote!(<#ty as usage_argv::spec::CommandArgs>::META.before_help),
                );
            let before_long_help = v
                .before_long_help
                .as_ref()
                .map(|value| option_expr(Some(value)))
                .unwrap_or_else(
                    || quote!(<#ty as usage_argv::spec::CommandArgs>::META.before_long_help),
                );
            let after_help = v
                .after_help
                .as_ref()
                .map(|value| option_expr(Some(value)))
                .unwrap_or_else(|| quote!(<#ty as usage_argv::spec::CommandArgs>::META.after_help));
            let after_long_help = v
                .after_long_help
                .as_ref()
                .map(|value| option_expr(Some(value)))
                .unwrap_or_else(
                    || quote!(<#ty as usage_argv::spec::CommandArgs>::META.after_long_help),
                );
            // A variant that declares examples speaks for the command; one that does not
            // leaves the held type's own standing, as `after_help` does.
            let examples = if v.examples.is_empty() {
                quote!(<#ty as usage_argv::spec::CommandArgs>::META.examples)
            } else {
                examples_table(&v.examples)
            };
            // Which of the table's aliases are hidden. The visible ones are not listed
            // anywhere: `cmd.aliases` minus these is what help and completions show.
            let hidden = &v.hidden_aliases;
            // A hidden command still answers to its name; it is simply not offered. Declared on
            // the variant, which is where the command itself is declared.
            let hide = v.hide;
            let help_heading = option_str(v.help_heading.as_deref());
            let surface = v
                .surface
                .as_deref()
                .map(|surface| option_str(Some(surface)))
                .unwrap_or_else(|| quote!(<#ty as usage_argv::spec::CommandArgs>::META.surface));
            let available_if = if v.available_if.is_empty() {
                quote!(<#ty as usage_argv::spec::CommandArgs>::META.available_if)
            } else {
                let conditions = &v.available_if;
                quote!(&[#(#conditions),*])
            };
            let display_order = option_usize(v.display_order);
            quote! {
                const #hidden_groups: &[&[&str]] = &[
                    <#ty as usage_argv::spec::CommandArgs>::META.hidden_aliases,
                    &[#(#hidden),*],
                ];
                static #hidden_name: [&str; usage_argv::table_len(#hidden_groups)] =
                    usage_argv::spec::concat_aliases(#hidden_groups);
                pub static #name: usage_argv::spec::CommandMeta =
                    usage_argv::spec::CommandMeta {
                        cmd: &#cmd,
                        about: #about,
                        long_about: #long_about,
                        deprecated: #deprecated,
                        deprecated_warn_at: #deprecated_warn_at,
                        deprecated_remove_at: #deprecated_remove_at,
                        before_help: #before_help,
                        before_long_help: #before_long_help,
                        after_help: #after_help,
                        after_long_help: #after_long_help,
                        examples: #examples,
                        hide: #hide || <#ty as usage_argv::spec::CommandArgs>::META.hide,
                        help_heading: #help_heading,
                        surface: #surface,
                        available_if: #available_if,
                        display_order: #display_order,
                        hidden_aliases: &#hidden_name,
                        ..*<#ty as usage_argv::spec::CommandArgs>::META
                    };
            }
        });
    let metas = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external)
        .map(|(i, _)| {
            let name = format_ident!("META_{i}");
            quote!(&#name)
        });
    // Matched on the command's key rather than its name, so selecting a variant is
    // an integer comparison and cannot be confused by an alias.
    let checks = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                #i => ::std::result::Result::Ok(()),
            }
        } else {
            let ty = &v.ty;
            quote! {
                #i => match partial {
                    Partial::#variant(__usage_p) => {
                        <#ty as usage_argv::spec::CommandArgs>::check(__usage_p)
                    }
                    // Selected but unfilled cannot happen — see `Subcommands::begin`.
                    _ => ::std::result::Result::Ok(()),
                },
            }
        }
    });
    let view_checks = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! { #i => ::std::result::Result::Ok(()), }
        } else {
            let ty = &v.ty;
            quote! {
                #i => match partial {
                    Partial::#variant(__usage_p) => {
                        if remaining_commands <= 1 {
                            <#ty as usage_argv::spec::CommandArgs>::check(__usage_p)
                        } else {
                            <#ty as usage_argv::spec::CommandArgs>::check_for_view_path(
                                __usage_p,
                                remaining_commands - 1,
                            )
                        }
                    }
                    _ => ::std::result::Result::Ok(()),
                },
            }
        }
    });
    // Every variant's bindings, because a table says what the CLI *can* do and is compared
    // against a spec that documents all of them — but only the selected variant's values, since
    // those are about one invocation. A command nobody ran did not give anything.
    let binding_parts = subs.variants.iter().filter(|v| !v.external).map(|v| {
        let ty = &v.ty;
        quote!(<#ty as usage_argv::spec::CommandArgs>::SETTINGS_BINDINGS)
    });
    let binding_lens = binding_parts.clone().map(|part| quote!(+ #part.len()));
    let givens = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => ::std::vec::Vec::new(),
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::settings_given(__usage_p)
                    } else {
                        ::std::vec::Vec::new()
                    }
                }
            }
        }
    });
    // The partial holds only the selected subcommand's own, so every one of these asks the
    // variant rather than a field: an unselected arm has nothing to have been given.
    let any_givens = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => ::std::option::Option::None,
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::any_given(__usage_p)
                    } else {
                        ::std::option::Option::None
                    }
                }
            }
        }
    });
    let exclusive_givens = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => ::std::option::Option::None,
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::exclusive_given(__usage_p)
                    } else {
                        ::std::option::Option::None
                    }
                }
            }
        }
    });
    // Read from the variant's own metadata rather than from the attributes it was written with:
    // a variant that says nothing inherits its struct's declaration, and `META_i` is where that
    // fallback has already been resolved. Help reads the same fields, so the two cannot disagree
    // about whether a command is deprecated.
    let deprecations = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            // An unmatched word is not a declared command, so there is nothing to deprecate.
            quote! {
                ::std::option::Option::Some(#i) => {}
            }
        } else {
            let ty = &v.ty;
            let meta = format_ident!("META_{i}");
            quote! {
                ::std::option::Option::Some(#i) => {
                    if #meta.deprecated.is_some()
                        || #meta.deprecated_warn_at.is_some()
                        || #meta.deprecated_remove_at.is_some()
                    {
                        out.push(usage_argv::warn::Warning::command(
                            #meta.cmd.name,
                            #meta.deprecated,
                            #meta.deprecated_warn_at,
                            #meta.deprecated_remove_at,
                        ));
                    }
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::deprecations(__usage_p, out);
                    }
                }
            }
        }
    });
    let view_deprecations = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => {}
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        if remaining_commands <= 1 {
                            // The promoted command itself is not reported — under this view it
                            // is the program — but its own flags were still typed by somebody,
                            // and so was anything selected below it.
                            <#ty as usage_argv::spec::CommandArgs>::deprecations(__usage_p, out);
                        } else {
                            <#ty as usage_argv::spec::CommandArgs>::deprecations_for_view_path(
                                __usage_p,
                                remaining_commands - 1,
                                out,
                            );
                        }
                    }
                }
            }
        }
    });
    let apply_envs = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! {
                ::std::option::Option::Some(#i) => {}
            }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        <#ty as usage_argv::spec::CommandArgs>::apply_env(__usage_p);
                    }
                }
            }
        }
    });
    let view_apply_envs = subs.variants.iter().enumerate().map(|(i, v)| {
        let variant = format_ident!("V{i}");
        if v.external {
            quote! { ::std::option::Option::Some(#i) => {} }
        } else {
            let ty = &v.ty;
            quote! {
                ::std::option::Option::Some(#i) => {
                    if let Partial::#variant(__usage_p) = partial {
                        if remaining_commands <= 1 {
                            <#ty as usage_argv::spec::CommandArgs>::apply_env(__usage_p);
                        } else {
                            <#ty as usage_argv::spec::CommandArgs>::apply_env_for_view_path(
                                __usage_p,
                                remaining_commands - 1,
                            );
                        }
                    }
                }
            }
        }
    });
    let select_arms = |for_view: bool| {
        subs.variants.iter().enumerate().map(move |(i, v)| {
            let held = format_ident!("V{i}");
            let variant = &v.ident;
            if v.external {
                let name = &v.name;
                let collected = if v.external_os {
                    quote! {{
                        let mut __usage_values = ::std::vec::Vec::with_capacity(__usage_p.len());
                        for __usage_item in __usage_p {
                            match usage_argv::os_string_from_bytes(__usage_item) {
                                ::std::result::Result::Ok(__usage_os) => {
                                    __usage_values.push(__usage_os)
                                }
                                ::std::result::Result::Err(__usage_bytes) => {
                                    return ::std::result::Result::Err(
                                        usage_argv::Error::InvalidValue(::std::boxed::Box::new(
                                            usage_argv::InvalidValue {
                                                name: #name,
                                                value: ::std::string::String::from_utf8_lossy(
                                                    &__usage_bytes,
                                                )
                                                .into_owned(),
                                                reason: ::std::string::ToString::to_string(
                                                    &"this platform cannot hold these bytes",
                                                ),
                                            },
                                        )),
                                    );
                                }
                            }
                        }
                        __usage_values
                    }}
                } else {
                    quote! {{
                        let mut __usage_values = ::std::vec::Vec::with_capacity(__usage_p.len());
                        for __usage_item in __usage_p {
                            match ::std::string::String::from_utf8(__usage_item) {
                                ::std::result::Result::Ok(__usage_text) => {
                                    __usage_values.push(__usage_text)
                                }
                                ::std::result::Result::Err(__usage_bad) => {
                                    return ::std::result::Result::Err(
                                        usage_argv::invalid_utf8_value(#name, __usage_bad),
                                    );
                                }
                            }
                        }
                        __usage_values
                    }}
                };
                let made = quote!(#ident::#variant(#collected));
                quote! {
                    #i => match partial {
                        Partial::#held(__usage_p) => {
                            ::std::result::Result::Ok(::std::option::Option::Some(#made))
                        }
                        _ => ::std::result::Result::Ok(::std::option::Option::None),
                    },
                }
            } else {
                let ty = &v.ty;
                // The one place the box matters: everything else — tables, partial, `build` —
                // speaks to the struct itself.
                let built = if for_view {
                    quote!(
                        <#ty as usage_argv::spec::ViewCommandArgs<__UsageOmitter>>::build_for_view(
                            __usage_p,
                        )?
                    )
                } else {
                    quote!(<#ty as usage_argv::spec::CommandArgs>::build(__usage_p)?)
                };
                let built = if v.boxed {
                    quote!(::std::boxed::Box::new(#built))
                } else {
                    built
                };
                // A bare variant has nowhere to put what was built, and nothing was declared to go in
                // it — but the build still runs, because that is where the command's own checks live.
                let made = if v.unit {
                    quote! {{
                        let _ = #built;
                        #ident::#variant
                    }}
                } else if let Some(fields) = &v.inline_fields {
                    let assignments = fields.iter().map(|field| {
                        let name = field
                            .ident
                            .as_ref()
                            .expect("named variant fields have names");
                        let cfg_attrs = field
                            .attrs
                            .iter()
                            .filter(|attr| meta_controls_field_presence(&attr.meta));
                        quote! {
                            #(#cfg_attrs)*
                            #name: __usage_built.#name
                        }
                    });
                    quote! {{
                        let __usage_built = #built;
                        // An empty named variant, or one whose fields were all removed by cfg,
                        // still has to run `build` for the command's checks. Mark the result used
                        // without changing the field moves below.
                        let _ = &__usage_built;
                        #ident::#variant {
                            #(#assignments),*
                        }
                    }}
                } else {
                    quote!(#ident::#variant(#built))
                };
                quote! {
                    #i => match partial {
                        Partial::#held(__usage_p) => {
                            ::std::result::Result::Ok(::std::option::Option::Some(#made))
                        }
                        // Selected but unfilled cannot happen — see `Subcommands::begin`.
                        _ => ::std::result::Result::Ok(::std::option::Option::None),
                    },
                }
            }
        })
    };
    let selects = select_arms(false);
    let view_selects = select_arms(true);

    // The variants an update can merge into: one holding a single `Args` value, which is the
    // only shape whose fields this enum can hand to the struct that owns them. A unit variant
    // has no fields to keep, an external one is a list of words that argv replaces whole, and
    // a variant with inline fields has no `Args` value to lend — those are replaced, which is
    // what selecting a different command does anyway.
    let mergeable: Vec<(usize, &crate::model::Variant)> = subs
        .variants
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.external && !v.unit && v.inline_fields.is_none())
        .collect();
    let standing_inner = |v: &crate::model::Variant| {
        if v.boxed {
            quote!(&**__usage_inner)
        } else {
            quote!(__usage_inner)
        }
    };
    let standing_inner_mut = |v: &crate::model::Variant| {
        if v.boxed {
            quote!(&mut **__usage_inner)
        } else {
            quote!(__usage_inner)
        }
    };
    let update_checks = mergeable.iter().map(|(i, v)| {
        let held = format_ident!("V{i}");
        let variant = &v.ident;
        let ty = &v.ty;
        let inner = standing_inner(v);
        quote! {
            (#i, #ident::#variant(__usage_inner)) => {
                if let Partial::#held(__usage_p) = partial {
                    return <#ty as usage_argv::spec::CommandArgs>::check_update(
                        __usage_p,
                        #inner,
                    );
                }
            }
        }
    });
    let update_envs = mergeable.iter().map(|(i, v)| {
        let held = format_ident!("V{i}");
        let variant = &v.ident;
        let ty = &v.ty;
        let inner = standing_inner(v);
        quote! {
            (::std::option::Option::Some(#i), #ident::#variant(__usage_inner)) => {
                if let Partial::#held(__usage_p) = partial {
                    <#ty as usage_argv::spec::CommandArgs>::apply_env_update(
                        __usage_p,
                        #inner,
                    );
                    return;
                }
            }
        }
    });
    let merges = mergeable.iter().map(|(i, v)| {
        let held = format_ident!("V{i}");
        let variant = &v.ident;
        let ty = &v.ty;
        let inner = standing_inner_mut(v);
        quote! {
            if selected == #i {
                if let #ident::#variant(__usage_inner) = &mut *standing {
                    if let Partial::#held(__usage_p) = partial {
                        return <#ty as usage_argv::spec::CommandArgs>::merge(
                            __usage_p,
                            #inner,
                        );
                    }
                    // Selected but unfilled cannot happen — see `Subcommands::begin`.
                    return ::std::result::Result::Ok(());
                }
            }
        }
    });
    let view_bounds: Vec<_> = subs
        .variants
        .iter()
        .filter(|v| !v.external)
        .map(|v| {
            let ty = &v.ty;
            quote!(#ty: usage_argv::spec::ViewCommandArgs<__UsageOmitter>)
        })
        .collect();
    let view_where = (!view_bounds.is_empty()).then(|| quote!(where #(#view_bounds,)*));

    quote! {
        // Beside the enum rather than inside the generated module: the variants name these
        // types, and a type a variant cannot see is no use to it.
        #(#generated_structs)*

        #[doc(hidden)]
        #[allow(
            non_upper_case_globals,
            non_snake_case,
            unused_imports,
            // Fires when a metadata struct happens to be fully specified. `..EMPTY`
            // is kept on purpose: it is what lets usage-argv gain a metadata field
            // without breaking every crate that derives.
            clippy::needless_update
        )]
        const _: () = {
            use #runtime as usage_argv;

            pub enum Partial {
                /// No command word has selected a variant yet, so there is nothing to fill.
                Unselected,
                #(#partial_variants)*
            }

            impl ::std::default::Default for Partial {
                fn default() -> Self {
                    Partial::Unselected
                }
            }

            #(#command_overrides)*
            #(#meta_overrides)*

            const _: () = usage_argv::assert_unique_subcommand_names(&[#(#unique_commands),*]);

            impl usage_argv::spec::Subcommands for #ident {
                type Partial = Partial;

                const COMMANDS: &'static [&'static usage_argv::Command<'static>] =
                    &[#(#commands),*];
                const METAS: &'static [&'static usage_argv::spec::CommandMeta<'static>] =
                    &[#(#metas),*];
                const HAS_EXTERNAL: bool = #has_external;
                const EXTERNAL: ::std::option::Option<usize> = #external_const;
                const VARIANT_OF: &'static [usize] = &[#(#variant_of),*];

                fn apply(
                    partial: &mut Self::Partial,
                    selected: ::std::option::Option<usize>,
                    event: &usage_argv::Event<'_, '_, '_>,
                ) -> bool {
                    match selected {
                        #(#applies)*
                        // Nothing selected yet, or a position that cannot be produced: the event
                        // is not one of these commands'.
                        _ => false,
                    }
                }

                fn begin(partial: &mut Self::Partial, selected: usize) {
                    match selected {
                        #(#begins)*
                        // Not a position `COMMANDS` can produce, so there is no variant to
                        // make room for.
                        _ => {}
                    }
                }

                const SETTINGS_BINDINGS: &'static [(&'static str, &'static str)] = {
                    const PARTS: &[&'static [(&'static str, &'static str)]] = &[#(#binding_parts),*];
                    const N: usize = 0 #(#binding_lens)*;
                    const JOINED: [(&'static str, &'static str); N] =
                        usage_argv::spec::concat_bindings(PARTS);
                    &JOINED
                };

                fn settings_given(
                    partial: &Self::Partial,
                    selected: ::std::option::Option<usize>,
                ) -> ::std::vec::Vec<(&'static str, usage_argv::spec::SettingGiven)> {
                    match selected {
                        #(#givens)*
                        // No subcommand was reached, so none of them was given anything.
                        _ => ::std::vec::Vec::new(),
                    }
                }

                fn any_given(
                    partial: &Self::Partial,
                    selected: ::std::option::Option<usize>,
                ) -> ::std::option::Option<&'static str> {
                    match selected {
                        #(#any_givens)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn exclusive_given(
                    partial: &Self::Partial,
                    selected: ::std::option::Option<usize>,
                ) -> ::std::option::Option<&'static str> {
                    match selected {
                        #(#exclusive_givens)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn deprecations(
                    partial: &Self::Partial,
                    selected: ::std::option::Option<usize>,
                    out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) {
                    match selected {
                        #(#deprecations)*
                        // No subcommand was reached, so none of them was used.
                        _ => {}
                    }
                }

                fn deprecations_for_view_path(
                    partial: &Self::Partial,
                    selected: ::std::option::Option<usize>,
                    remaining_commands: usize,
                    out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
                ) {
                    match selected {
                        #(#view_deprecations)*
                        _ => {}
                    }
                }

                fn apply_env(
                    partial: &mut Self::Partial,
                    selected: ::std::option::Option<usize>,
                ) {
                    match selected {
                        #(#apply_envs)*
                        _ => {}
                    }
                }

                fn apply_env_for_view_path(
                    partial: &mut Self::Partial,
                    selected: ::std::option::Option<usize>,
                    remaining_commands: usize,
                ) {
                    match selected {
                        #(#view_apply_envs)*
                        _ => {}
                    }
                }

                fn check<'t, 'v>(
                    partial: &mut Self::Partial,
                    selected: usize,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    match selected {
                        #(#checks)*
                        // A position that is not one of these cannot be produced: it comes
                        // from finding a table's own address in COMMANDS.
                        _ => ::std::result::Result::Ok(()),
                    }
                }

                fn check_for_view_path<'t, 'v>(
                    partial: &mut Self::Partial,
                    selected: usize,
                    remaining_commands: usize,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    match selected {
                        #(#view_checks)*
                        _ => ::std::result::Result::Ok(()),
                    }
                }

                fn select<'t, 'v>(
                    partial: Self::Partial,
                    selected: usize,
                ) -> ::std::result::Result<
                    ::std::option::Option<Self>,
                    usage_argv::Error<'t, 'v>,
                > {
                    match selected {
                        #(#selects)*
                        _ => ::std::result::Result::Ok(::std::option::Option::None),
                    }
                }

                fn check_update<'t, 'v>(
                    partial: &mut Self::Partial,
                    selected: usize,
                    standing: &Self,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    match (selected, standing) {
                        #(#update_checks)*
                        // A different command than the one standing: what the old variant
                        // holds says nothing about this one's requirements.
                        _ => {}
                    }
                    Self::check(partial, selected)
                }

                fn apply_env_update(
                    partial: &mut Self::Partial,
                    selected: ::std::option::Option<usize>,
                    standing: &Self,
                ) {
                    match (selected, standing) {
                        #(#update_envs)*
                        _ => {}
                    }
                    Self::apply_env(partial, selected)
                }

                fn merge_into<'t, 'v>(
                    partial: Self::Partial,
                    selected: usize,
                    standing: &mut Self,
                ) -> ::std::result::Result<(), usage_argv::Error<'t, 'v>> {
                    #(#merges)*
                    // A different command replaces the variant wholesale: selecting one is
                    // a routing decision rather than a value to merge, so the fields of the
                    // command that was standing go with it.
                    if let ::std::option::Option::Some(__usage_built) =
                        Self::select(partial, selected)?
                    {
                        *standing = __usage_built;
                    }
                    ::std::result::Result::Ok(())
                }
            }

            impl<__UsageOmitter> usage_argv::spec::ViewSubcommands<__UsageOmitter>
                for #ident
                #view_where
            {
                fn select_for_view<'t, 'v>(
                    partial: Self::Partial,
                    selected: usize,
                ) -> ::std::result::Result<
                    ::std::option::Option<Self>,
                    usage_argv::Error<'t, 'v>,
                > {
                    match selected {
                        #(#view_selects)*
                        _ => ::std::result::Result::Ok(::std::option::Option::None),
                    }
                }
            }
        };

        #dispatch
    }
}

/// `&& !partial.__overridden_x`, for a field that can lose an override.
///
/// Empty for every other field, so a CLI that declares no `overrides` generates exactly
/// what it did before.
fn displaced_guard(cli: &Cli, field: &Field) -> TokenStream {
    if !is_displaceable(cli, field) {
        return quote!();
    }
    let overridden = format_ident!("__overridden_{}", field.ident);
    quote!(&& !partial.#overridden)
}

/// The groups a command declares, in the order their first member is written.
///
/// Membership lives on the fields and properties on the struct, so this is where the two
/// are joined — and it is the only place both are visible, which is why the emitted
/// metadata is built here rather than in the model.
fn declared_groups(cli: &Cli) -> Vec<(String, bool, bool, Vec<String>)> {
    let mut groups: Vec<(String, bool, bool, Vec<String>)> = Vec::new();
    for field in &cli.fields {
        let Some(selector) = Cli::selector_for_field(field) else {
            continue;
        };
        let names = field.group.iter().map(String::as_str);
        for name in names {
            match groups.iter_mut().find(|(n, _, _, _)| n == name) {
                Some((_, _, _, members)) => {
                    if !members.contains(&selector) {
                        members.push(selector.clone());
                    }
                }
                None => {
                    // An undeclared group takes the defaults, which is the common case: "at
                    // most one of these" needs no properties, and making it say so anyway
                    // would be ceremony.
                    let decl = cli.groups.iter().find(|d| d.name == name);
                    groups.push((
                        name.to_string(),
                        decl.is_some_and(|d| d.required),
                        decl.is_some_and(|d| d.multiple),
                        vec![selector.clone()],
                    ));
                }
            }
        }
    }
    groups
}

/// The `static` array of group metadata, and the expression referring to it.
///
/// A flattened struct's groups are joined in, the way its flags and their metadata are:
/// the child enforces them through its own `check`, and its flags are in *this* command's
/// table, so its groups describe this command and belong in this command's emitted KDL.
/// Leaving them out would enforce a rule the spec does not mention — the drift the
/// spec-as-definition rule exists to prevent.
fn group_meta_table(cli: &Cli) -> (TokenStream, TokenStream) {
    let declared: Vec<_> = declared_groups(cli)
        .into_iter()
        .filter(|(_, required, multiple, members)| members.len() >= 2 && (*required || !*multiple))
        .collect();
    // Where each group belongs: a declared one at its first member, which is the position
    // `declared_groups` already orders them by, and an argument group at the field holding it.
    // A group whose members straddle a flattened field still belongs where it *starts*, so it
    // keeps its whole member list rather than being split in two.
    let mut entries: Vec<(usize, TokenStream)> = declared
        .iter()
        .map(|(name, required, multiple, members)| {
            let at = cli
                .fields
                .iter()
                .position(|f| Cli::selector_for_field(f).is_some_and(|s| members.contains(&s)))
                .unwrap_or(usize::MAX);
            (
                at,
                quote! {
                    usage_argv::spec::GroupMeta {
                        name: #name,
                        members: &[#(#members),*],
                        required: #required,
                        multiple: #multiple,
                    }
                },
            )
        })
        .collect();
    // Read from the enum rather than copied out of it: the members are its variants, and the
    // field's type says whether one or many results are built.
    for (at, field) in cli.fields.iter().enumerate() {
        let Kind::ArgGroup {
            ty,
            optional,
            multiple,
        } = &field.kind
        else {
            continue;
        };
        let required = !optional && !multiple;
        entries.push((
            at,
            quote! {
                usage_argv::spec::GroupMeta {
                    name: <#ty as usage_argv::spec::ArgGroup>::NAME,
                    members: <#ty as usage_argv::spec::ArgGroup>::MEMBERS,
                    required: #required,
                    multiple: {
                        assert!(
                            <#ty as usage_argv::spec::ArgGroup>::MULTIPLE == #multiple,
                            "an ArgGroup marked multiple must be held by Vec<T>, and Vec<T> needs #[usage(multiple)] on the ArgGroup"
                        );
                        #multiple
                    },
                }
            },
        ));
    }
    entries.sort_by_key(|(at, _)| *at);

    // One walk over the fields, so a flattened struct's groups land where the field was
    // written rather than after everything this struct declares — the same interleaving the
    // flag and argument tables are built with, and visible in the same places their order is.
    let mut parts: Vec<TokenStream> = Vec::new();
    let mut run: Vec<TokenStream> = Vec::new();
    let mut emitted = vec![false; entries.len()];
    let mut any_flattened = false;
    for (i, field) in cli.fields.iter().enumerate() {
        let Kind::Flatten { ty, .. } = &field.kind else {
            continue;
        };
        any_flattened = true;
        for (e, (at, group)) in entries.iter().enumerate() {
            if !emitted[e] && *at < i {
                emitted[e] = true;
                run.push(group.clone());
            }
        }
        if !run.is_empty() {
            let run = std::mem::take(&mut run);
            parts.push(quote!(&[#(#run),*]));
        }
        // Named directly, as the flag and argument tables beside this one are: the
        // generated items live in the user's own scope now rather than in a module
        // above it, so there is no path to rewrite.
        parts.push(quote!(<#ty as usage_argv::spec::CommandArgs>::META.groups));
    }
    for (e, (_, group)) in entries.iter().enumerate() {
        if !emitted[e] {
            run.push(group.clone());
        }
    }
    if !run.is_empty() {
        parts.push(quote!(&[#(#run),*]));
    }

    if parts.is_empty() {
        return (quote!(), quote!(&[]));
    }
    if !any_flattened {
        let len = entries.len();
        let entries = entries.iter().map(|(_, group)| group);
        return (
            quote! {
                pub static GROUP_METAS: [usage_argv::spec::GroupMeta; #len] = [#(#entries),*];
            },
            quote!(&GROUP_METAS),
        );
    }
    (
        quote! {
            const GROUP_META_GROUPS: &[&[usage_argv::spec::GroupMeta<'static>]] =
                &[#(#parts),*];
            static GROUP_METAS: [usage_argv::spec::GroupMeta<'static>;
                usage_argv::table_len(GROUP_META_GROUPS)] =
                usage_argv::spec::concat_group_metas(GROUP_META_GROUPS);
        },
        quote!(&GROUP_METAS),
    )
}

/// Apply declared defaults to this command and every argument group flattened into it.
///
/// Separate from the rest of `check` because exclusivity suppresses requiredness, not values a
/// CLI promised to provide by default. A parent can therefore prepare an opaque flattened partial
/// without also asking it to report a missing sibling.
fn declared_defaults(cli: &Cli, filter_view: bool) -> TokenStream {
    let own = cli.fields.iter().filter_map(|f| {
        if matches!(f.kind, Kind::Subcommand { .. } | Kind::Skip) {
            return None;
        }
        if !f.has_default() && f.default_if.is_empty() {
            return None;
        }
        let given = format_ident!("__given_{}", f.ident);
        let standing = displaced_guard(cli, f);
        let mut fills: Vec<TokenStream> = f
            .default_if
            .iter()
            .map(|condition| {
                let pred = default_if_predicate(cli, condition, Lookup::Standing);
                let assign =
                    assign_literal(f, &condition.value, std::slice::from_ref(&condition.value));
                quote!(if !__usage_filled && (#pred) {
                    #assign
                    __usage_filled = true;
                })
            })
            .collect();
        if f.has_default() {
            let assign = reset_to_default(f);
            fills.push(quote!(if !__usage_filled {
                #assign
            }));
        }
        let active = if filter_view {
            let active = view_field_active(f);
            quote!((#active) &&)
        } else {
            quote!()
        };
        // A value the caller already had is not a field waiting to be filled: an update
        // never overwrites what somebody set deliberately.
        let standing_held = unless_standing(f);
        Some(quote! {
            if #active !partial.#given #standing #standing_held {
                let mut __usage_filled = false;
                #(#fills)*
            }
        })
    });
    let flattened = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        let ident = &f.ident;
        let standing = standing_ident(f);
        Some(if filter_view {
            quote! {
                match #standing {
                    ::std::option::Option::Some(__usage_s) => {
                        <#ty as usage_argv::spec::CommandArgs>::apply_defaults_update(
                            &mut partial.#ident,
                            __usage_s,
                        );
                    }
                    ::std::option::Option::None => {
                        <#ty as usage_argv::spec::CommandArgs>::apply_defaults_for_view(
                            &mut partial.#ident,
                            __usage_view,
                        );
                    }
                }
            }
        } else {
            quote! {
                <#ty as usage_argv::spec::CommandArgs>::apply_defaults(&mut partial.#ident);
            }
        })
    });
    quote! {
        #(#own)*
        #(#flattened)*
    }
}

/// Environment fallbacks for this command and every argument group flattened into it.
///
/// Kept separate from the rest of post-binding validation because a parent must apply these
/// before it can enforce a relationship whose other side lives across a flatten boundary.
fn env_fallbacks(cli: &Cli, filter_view: bool) -> TokenStream {
    let own = cli.fields.iter().filter_map(|f| {
        let ident = &f.ident;
        let given = format_ident!("__given_{}", ident);
        let vars: Vec<&str> = f
            .env
            .iter()
            .map(String::as_str)
            .chain(f.env_fallback.iter().map(String::as_str))
            .chain(f.deprecated_env.iter().map(String::as_str))
            .collect();
        if vars.is_empty() {
            return None;
        }
        let assign = match f.shape {
            // `env::var` gives text, which is right for an environment variable: the
            // partial holds bytes because *argv* may not be UTF-8, and this is not argv.
            Shape::Optional => quote! {
                partial.#ident = ::std::option::Option::Some(value.into_bytes());
            },
            Shape::Required => quote!(partial.#ident = value.into_bytes();),
            // Cleared first, so the environment *replaces* a declared default instead of
            // adding to it — which is what every other shape does by assigning.
            Shape::Many => match f.delimiter {
                Some(delimiter) => {
                    let byte = u8::try_from(u32::from(delimiter))
                        .expect("the model rejects non-ASCII delimiters");
                    quote! {
                        partial.#ident.clear();
                        for part in value.as_bytes().split(|b| *b == #byte) {
                            partial.#ident.push(part.to_vec());
                        }
                    }
                }
                None => quote! {
                    partial.#ident.clear();
                    partial.#ident.push(value.into_bytes());
                },
            },
            Shape::Bool => quote! {
                partial.#ident = !matches!(
                    value.as_str(),
                    "" | "0" | "false" | "no" | "off"
                );
            },
            // An unparseable count leaves the field alone rather than counting as given.
            Shape::Count => {
                let ty = &f.ty;
                quote! {
                    match value.parse::<#ty>() {
                        ::std::result::Result::Ok(count) => partial.#ident = count,
                        ::std::result::Result::Err(_) => continue_unset = true,
                    }
                }
            }
        };
        // A flag that lost an override is not merely unset: filling it from the
        // environment would undo the last-one-wins the command line asked for.
        let standing = displaced_guard(cli, f);
        let active = if filter_view {
            let active = view_field_active(f);
            quote!((#active) &&)
        } else {
            quote!()
        };
        // A deprecated alias is remembered where it won, rather than worked out again later:
        // the order these names are tried in is the whole rule, and asking a second time
        // whether an alias "would have" won is a copy of that rule free to disagree with it.
        // `vars` puts the aliases last, so the winner is deprecated exactly when its index
        // reaches the tail.
        let record_deprecated = tracks_deprecated_env(f).then(|| {
            let recorded = deprecated_env_ident(f);
            let first_deprecated = vars.len() - f.deprecated_env.len();
            // A field whose only names are deprecated needs no comparison, and emitting
            // `>= 0` would be a lint in the adopter's crate rather than here.
            if first_deprecated == 0 {
                quote!(partial.#recorded = ::std::option::Option::Some(__usage_env);)
            } else {
                quote! {
                    if __usage_index >= #first_deprecated {
                        partial.#recorded = ::std::option::Option::Some(__usage_env);
                    }
                }
            }
        });
        let names = if record_deprecated.is_some() {
            quote!([#(#vars),*].into_iter().enumerate())
        } else {
            quote!([#(#vars),*])
        };
        let bind = if record_deprecated.is_some() {
            quote!((__usage_index, __usage_env))
        } else {
            quote!(__usage_env)
        };
        // The environment fills what is empty. On an update a field the caller already
        // filled is not empty, however little this argv said about it.
        let standing_held = unless_standing(f);
        Some(quote! {
            if #active !partial.#given #standing #standing_held {
                for #bind in #names {
                    if let ::std::result::Result::Ok(value) = ::std::env::var(__usage_env) {
                        let mut continue_unset = false;
                        #assign
                        if !continue_unset {
                            partial.#given = true;
                            #record_deprecated
                            break;
                        }
                    }
                }
            }
        })
    });
    let flattened = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        let ident = &f.ident;
        let standing = standing_ident(f);
        Some(if filter_view {
            quote! {
                match #standing {
                    ::std::option::Option::Some(__usage_s) => {
                        <#ty as usage_argv::spec::CommandArgs>::apply_env_update(
                            &mut partial.#ident,
                            __usage_s,
                        );
                    }
                    ::std::option::Option::None => {
                        <#ty as usage_argv::spec::CommandArgs>::apply_env_for_view(
                            &mut partial.#ident,
                            __usage_view,
                        );
                    }
                }
            }
        } else {
            quote! {
                <#ty as usage_argv::spec::CommandArgs>::apply_env(&mut partial.#ident);
            }
        })
    });
    let selected = cli.fields.iter().find_map(|f| {
        let Kind::Subcommand { ty, .. } = &f.kind else {
            return None;
        };
        let standing = standing_ident(f);
        Some(if filter_view {
            quote! {
                match (#standing, __usage_view) {
                    (::std::option::Option::Some(__usage_s), _) => {
                        <#ty as usage_argv::spec::Subcommands>::apply_env_update(
                            &mut partial.__usage_sub,
                            partial.__usage_selected,
                            __usage_s,
                        );
                    }
                    (::std::option::Option::None, ::std::option::Option::Some(__usage_view)) => {
                        <#ty as usage_argv::spec::Subcommands>::apply_env_for_view_path(
                            &mut partial.__usage_sub,
                            partial.__usage_selected,
                            __usage_view.root.split_ascii_whitespace().count(),
                        );
                    }
                    (::std::option::Option::None, ::std::option::Option::None) => {
                        <#ty as usage_argv::spec::Subcommands>::apply_env(
                            &mut partial.__usage_sub,
                            partial.__usage_selected,
                        );
                    }
                }
            }
        } else {
            quote! {
                <#ty as usage_argv::spec::Subcommands>::apply_env(
                    &mut partial.__usage_sub,
                    partial.__usage_selected,
                );
            }
        })
    });
    quote! {
        #(#own)*
        #(#flattened)*
        #selected
    }
}

/// Everything the invocation used that its own declaration says not to use any more.
///
/// Read from the filled partial, so this runs after `check`: the environment has had its turn by
/// then, and a value that arrived through a variable used the deprecated declaration just as much
/// as a typed word did. A declared default does not — it fills a field without marking it given,
/// which is exactly the distinction this needs and the one that already exists.
///
/// Nothing here consults `deprecated_warn_at`. A nested command's tables say nothing about the
/// root's version, so the gate is applied once by the entry point that knows it.
fn deprecations_fn(cli: &Cli) -> TokenStream {
    let own = cli.fields.iter().filter_map(|f| {
        // Flags only, because the spec has `deprecated` on a flag and on a command and not on a
        // positional: warning about one would be a behaviour the emitted KDL cannot express.
        let Kind::Flag { longs, shorts, .. } = &f.kind else {
            return None;
        };
        if !tracks_deprecated(f) {
            return None;
        }
        let given = format_ident!("__given_{}", f.ident);
        // Named the way the user names it. `Field::name` is the spec's name for the flag, which
        // has no dashes, and a warning that said `old-flag is deprecated` would be about a word
        // nobody typed.
        let spelling = match (longs.first(), shorts.first()) {
            (Some(long), _) => format!("--{long}"),
            (None, Some(short)) => format!("-{short}"),
            (None, None) => f.name.clone(),
        };
        let message = option_str(f.deprecated.as_deref());
        let warn_at = option_str(f.deprecated_warn_at.as_deref());
        let remove_at = option_str(f.deprecated_remove_at.as_deref());
        Some(quote! {
            if partial.#given {
                out.push(usage_argv::warn::Warning::flag(
                    #spelling,
                    #message,
                    #warn_at,
                    #remove_at,
                ));
            }
        })
    });
    let aliases = cli.fields.iter().filter_map(|f| {
        if !tracks_deprecated_env(f) {
            return None;
        }
        let recorded = deprecated_env_ident(f);
        // What to use instead: the name this field reads first. A field whose only variable is
        // the deprecated one has nothing to suggest, and says only that it is deprecated.
        let replacement = option_str(
            f.env
                .as_deref()
                .or_else(|| f.env_fallback.first().map(String::as_str)),
        );
        Some(quote! {
            if let ::std::option::Option::Some(__usage_env) = partial.#recorded {
                out.push(usage_argv::warn::Warning::env(__usage_env, #replacement));
            }
        })
    });
    let flattened = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        let ident = &f.ident;
        Some(quote! {
            <#ty as usage_argv::spec::CommandArgs>::deprecations(&partial.#ident, out);
        })
    });
    let selected = cli.fields.iter().find_map(|f| {
        let Kind::Subcommand { ty, .. } = &f.kind else {
            return None;
        };
        Some(quote! {
            if let ::std::option::Option::Some(__usage_at) = partial.__usage_selected {
                // `check_with_view` recorded the view on the partial, so this reads the same
                // answer the rest of the post-binding work did.
                match partial.__usage_view {
                    // Under an executable view the words the view injected are not a selection
                    // the user made — they are what the program is — so they are not reported,
                    // for the same reason the root never is.
                    ::std::option::Option::Some(__usage_view) => {
                        <#ty as usage_argv::spec::Subcommands>::deprecations_for_view_path(
                            &partial.__usage_sub,
                            ::std::option::Option::Some(__usage_at),
                            __usage_view.root.split_ascii_whitespace().count(),
                            out,
                        );
                    }
                    ::std::option::Option::None => {
                        <#ty as usage_argv::spec::Subcommands>::deprecations(
                            &partial.__usage_sub,
                            ::std::option::Option::Some(__usage_at),
                            out,
                        );
                    }
                }
            }
        })
    });
    quote! {
        /// What this command line used that the spec says not to use any more.
        ///
        /// Collected rather than printed, and only when an entry point was asked for it: a
        /// `parse_from` that takes no sink never walks this at all.
        pub fn deprecations(
            partial: &Partial,
            out: &mut ::std::vec::Vec<usage_argv::warn::Warning<'static>>,
        ) {
            // Read unconditionally, so a command with nothing deprecated does not leave its
            // parameters unused in the adopter's crate, where nobody can silence it.
            let _ = (&partial, &mut *out);
            #(#own)*
            #(#aliases)*
            #(#flattened)*
            #selected
        }
    }
}

/// [`argument_state`] that also counts a standing `ArgGroup` member.
///
/// Only when this argv said nothing about the group: a fresh member on the command line
/// replaces the standing variant, so relationships must not keep reading the old one.
fn argument_state_standing(cli: &Cli) -> TokenStream {
    let overlays = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, multiple, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let standing = standing_ident(field);
        let group = quote!(<#ty as usage_argv::spec::ArgGroup>);
        let read_standing = if *multiple {
            quote! {
                for __usage_member in __usage_s {
                    if let ::std::option::Option::Some(__usage_standing_state) =
                        #group::standing_state(__usage_member, selector)
                    {
                        if __usage_standing_state.given {
                            return ::std::option::Option::Some(__usage_standing_state);
                        }
                    }
                }
            }
        } else {
            quote! {
                if let ::std::option::Option::Some(__usage_standing_state) =
                    #group::standing_state(__usage_s, selector)
                {
                    if __usage_standing_state.given {
                        return ::std::option::Option::Some(__usage_standing_state);
                    }
                }
            }
        };
        Some(quote! {
            if #group::any_given(&partial.#ident).is_none() {
                if let ::std::option::Option::Some(__usage_s) = #standing {
                    #read_standing
                }
            }
        })
    });
    let match_overlays = cli.fields.iter().filter_map(|field| {
        let Kind::ArgGroup { ty, multiple, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let standing = standing_ident(field);
        let group = quote!(<#ty as usage_argv::spec::ArgGroup>);
        let read_standing = if *multiple {
            quote! {
                for __usage_member in __usage_s {
                    if #group::standing_matches(__usage_member, selector, value)
                        == ::std::option::Option::Some(true)
                    {
                        return ::std::option::Option::Some(true);
                    }
                }
            }
        } else {
            quote! {
                if #group::standing_matches(__usage_s, selector, value)
                    == ::std::option::Option::Some(true)
                {
                    return ::std::option::Option::Some(true);
                }
            }
        };
        Some(quote! {
            if #group::any_given(&partial.#ident).is_none() {
                if let ::std::option::Option::Some(__usage_s) = #standing {
                    #read_standing
                }
            }
        })
    });
    let clause_overlays = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let current = format_ident!("__usage_current_{}", ident);
        let standing = standing_ident(field);
        Some(quote! {
            if !partial.#ident.iter().chain(::core::iter::once(&partial.#current)).any(
                |__usage_instance| {
                    <#ty as usage_argv::spec::CommandArgs>::any_given(__usage_instance).is_some()
                },
            ) {
                if let ::std::option::Option::Some(__usage_s) = #standing {
                    for __usage_instance in __usage_s {
                        if let ::std::option::Option::Some(__usage_standing_state) =
                            <#ty as usage_argv::spec::CommandArgs>::standing_state(
                                __usage_instance,
                                selector,
                            )
                        {
                            if __usage_standing_state.given
                                || __usage_standing_state.satisfied
                            {
                                return ::std::option::Option::Some(__usage_standing_state);
                            }
                        }
                    }
                }
            }
        })
    });
    let clause_match_overlays = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let current = format_ident!("__usage_current_{}", ident);
        let standing = standing_ident(field);
        Some(quote! {
            if !partial.#ident.iter().chain(::core::iter::once(&partial.#current)).any(
                |__usage_instance| {
                    <#ty as usage_argv::spec::CommandArgs>::any_given(__usage_instance).is_some()
                },
            ) {
                if let ::std::option::Option::Some(__usage_s) = #standing {
                    for __usage_instance in __usage_s {
                        if <#ty as usage_argv::spec::CommandArgs>::standing_matches(
                            __usage_instance,
                            selector,
                            value,
                        ) == ::std::option::Option::Some(true)
                        {
                            return ::std::option::Option::Some(true);
                        }
                    }
                }
            }
        })
    });
    quote! {
        // Shadow the module helper for every check below: an update's standing group
        // member has to answer `requires` / `conflicts` the same way a standing flag does,
        // and only this scope holds the standing locals.
        #[allow(dead_code)]
        let __usage_argument_state =
            |partial: &Partial, selector: &str| -> ::std::option::Option<
                usage_argv::spec::ArgumentState,
            > {
                match argument_state(partial, selector) {
                    ::std::option::Option::Some(state) if state.given || state.satisfied => {
                        ::std::option::Option::Some(state)
                    }
                    recognized => {
                        #(#overlays)*
                        #(#clause_overlays)*
                        recognized
                    }
                }
            };
        // And the same for a check about what a member *is*: `required_if_eq` and a
        // three-argument `default_if` name a value, not only a presence.
        #[allow(dead_code)]
        let __usage_argument_matches =
            |partial: &Partial, selector: &str, value: &[u8]|
                -> ::std::option::Option<bool> {
                match argument_matches(partial, selector, value) {
                    ::std::option::Option::Some(true) => ::std::option::Option::Some(true),
                    recognized => {
                        #(#match_overlays)*
                        #(#clause_match_overlays)*
                        recognized
                    }
                }
            };
    }
}

/// Everything decided once the last token has been read.
///
/// Ordered deliberately. The environment fills what argv left out, so it runs
/// before required-ness — a flag with `env` set is not missing. Choices and bounds
/// come last, because they judge a value however it arrived, including one that came
/// from the environment or a default.
fn post_binding(cli: &Cli) -> TokenStream {
    // Shadow the general presence helpers in this generator only. A projected executable
    // validates carried root globals; policy on every other root field belongs to the
    // surface the view omitted. Selected commands run their own checker with no view. On an
    // update both also count a value the caller already had, so a relationship is judged on
    // the union of what stands and what this command line said.
    let policy_given = standing_policy_given;
    let semantic_given = standing_semantic_given;
    let standing_locals = standing_locals(cli);
    let argument_state_standing = argument_state_standing(cli);
    let sub_check = subcommand_parts(cli).map(|p| p.check).unwrap_or_default();
    let subcommand_satisfies_requirements = if cli.subcommand_negates_reqs
        && cli
            .fields
            .iter()
            .any(|field| matches!(field.kind, Kind::Subcommand { .. }))
    {
        let standing = cli
            .fields
            .iter()
            .find(|field| matches!(field.kind, Kind::Subcommand { .. }))
            .and_then(standing_flag)
            .unwrap_or_else(|| quote!(false));
        quote!((partial.__usage_selected.is_some() || #standing))
    } else {
        quote!(false)
    };
    let direct_exclusive_present = cli.fields.iter().filter_map(|field| {
        if !field.exclusive {
            return None;
        }
        Some(policy_given(field))
    });
    let flattened_exclusive_present = cli.fields.iter().filter_map(|field| {
        let Kind::Flatten { ty, .. } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        Some(quote! {
            <#ty as usage_argv::spec::CommandArgs>::exclusive_given(&partial.#ident).is_some()
        })
    });
    let selected_exclusive_present = cli.fields.iter().filter_map(|field| {
        let Kind::Subcommand { ty, .. } = &field.kind else {
            return None;
        };
        Some(quote! {
            <#ty as usage_argv::spec::Subcommands>::exclusive_given(
                &partial.__usage_sub,
                partial.__usage_selected,
            ).is_some()
        })
    });
    let exclusive_present = quote! {
        false
            #(|| #direct_exclusive_present)*
            #(|| #flattened_exclusive_present)*
            #(|| #selected_exclusive_present)*
    };
    // A flattened struct declares its own required-ness and choices, and only it knows them.
    //
    // Run before this command's own required-ness, on the same principle that puts conflicts
    // first: what the user typed wrong is more useful to hear about than what they left out.
    // `config --format yaml` should say `yaml` is not one of the choices, even if `--file` is
    // also missing.
    //
    // No finer promise than that. These checks are grouped by kind rather than by field, so
    // there is no "in declaration order" to offer — a flattened group's errors interleave with
    // this command's by kind, not by where the field was written.
    let flattened_checks = cli.fields.iter().filter_map(|f| {
        let Kind::Flatten { ty, .. } = &f.kind else {
            return None;
        };
        let ident = &f.ident;
        let standing = standing_ident(f);
        Some(quote! {
            if !__usage_exclusive_present
                || <#ty as usage_argv::spec::CommandArgs>::exclusive_given(&partial.#ident)
                    .is_some()
            {
                match #standing {
                    ::std::option::Option::Some(__usage_s) => {
                        <#ty as usage_argv::spec::CommandArgs>
                            ::check_update_with_args_override_self(
                                &mut partial.#ident,
                                args_override_self,
                                __usage_s,
                            )?;
                    }
                    ::std::option::Option::None => {
                        <#ty as usage_argv::spec::CommandArgs>
                            ::check_with_args_override_self_for_view(
                                &mut partial.#ident,
                                args_override_self,
                                __usage_view,
                            )?;
                    }
                }
            }
        })
    });
    let clause_checks = cli.fields.iter().filter_map(|field| {
        let Kind::Clause { ty, separator } = &field.kind else {
            return None;
        };
        let ident = &field.ident;
        let current = format_ident!("__usage_current_{}", ident);
        let check_current = if separator.is_some() {
            quote!(true)
        } else {
            quote!(
                <#ty as usage_argv::spec::CommandArgs>::any_given(&partial.#current).is_some()
            )
        };
        Some(quote! {
            if !__usage_exclusive_present
                || <#ty as usage_argv::spec::CommandArgs>::exclusive_given(&partial.#current)
                    .is_some()
            {
                for __usage_instance in &mut partial.#ident {
                    <#ty as usage_argv::spec::CommandArgs>::check_with_args_override_self(
                        __usage_instance,
                        false,
                    )?;
                }
                if #check_current {
                    <#ty as usage_argv::spec::CommandArgs>::check_with_args_override_self(
                        &mut partial.#current,
                        false,
                    )?;
                }
            }
        })
    });
    let duplicate_checks = cli
        .fields
        .iter()
        .filter(|f| rejects_duplicate(cli, f))
        .map(|f| {
            let duplicated = format_ident!("__duplicated_{}", f.ident);
            let name = &f.name;
            quote! {
                if !args_override_self && partial.#duplicated {
                    return ::std::result::Result::Err(
                        usage_argv::Error::DuplicateFlag { name: #name },
                    );
                }
            }
        });
    // Applied here rather than in `start`, and this is not a detail: `start` builds the
    // partial for *every* command in the CLI, selected or not, so a declared default was
    // costing a `String` per default per command — 60 allocations to parse a bare `mise`,
    // which is the CLI's size leaking into the invocation. `check` runs for the selected
    // command only. The helper also prepares flattened defaults before an exclusive flag can
    // suppress those groups' requiredness checks.
    let declared_defaults = declared_defaults(cli, true);

    let env_fallbacks = env_fallbacks(cli, true);

    let required_checks = cli.fields.iter().filter_map(|f| {
        // A `String` has nowhere to put "absent", so the type is the declaration; a collection
        // has nothing in its type to say it and declares `required` instead.
        //
        // The same expression the metadata is built from, deliberately: checking only the shape
        // meant a `Vec` marked `required` was reported as one-or-more by the spec, the help, the
        // manpage and the completions, and accepted zero values from the CLI that actually ran.
        // One expression cannot disagree with itself.
        if !(f.shape == Shape::Required || f.required_collection) || f.has_default() {
            return None;
        }
        let given = format_ident!("__given_{}", f.ident);
        let active = view_field_active(f);
        let name = &f.name;
        // Same reason as the environment: a displaced flag was answered by the one that
        // displaced it, so it is not missing. Nor is one an update did not have to repeat.
        let standing = displaced_guard(cli, f);
        let standing_held = unless_standing(f);
        Some(quote! {
            if #active && !partial.#given #standing #standing_held {
                return ::std::result::Result::Err(
                    usage_argv::Error::MissingRequired { name: #name },
                );
            }
        })
    });

    let choice_checks = cli.fields.iter().filter_map(|f| {
        if (f.choices.is_empty() && !f.value_enum) || f.allow_unknown_choices {
            return None;
        }
        let ident = &f.ident;
        let name = &f.name;
        // A `value_enum`'s words live on the type. Checking against them here rather than
        // letting the conversion fail is what makes a wrong word an `InvalidChoice` that
        // lists what was expected, instead of a message about a type the user did not name.
        let choices: TokenStream = match (f.value_enum, f.value_ty.as_ref()) {
            (true, Some(ty)) => {
                quote!(<#ty as usage_argv::spec::ValueEnum>::CHOICES)
            }
            _ => {
                let list = &f.choices;
                quote!(&[#(#list),*])
            }
        };
        let accepted_choices = accepted_choices(f);
        let ignore_case = choice_ignore_case(f);
        let invalid = format_ident!("__invalid_choice_{}", ident);
        let values = match f.shape {
            Shape::Optional => quote!(partial.#ident.iter()),
            Shape::Required => quote!(::std::iter::once(&partial.#ident)),
            Shape::Many => quote!(partial.#ident.iter()),
            // Rejected in the model: there is no value to check.
            Shape::Bool | Shape::Count => return None,
        };
        let active = view_field_active(f);
        let standing_only = unless_standing_only(f);
        let given = format_ident!("__given_{}", ident);
        Some(quote! {
            // Asked outside the `given` guard below, because a flag that lost an `overrides`
            // is no longer given and its value has gone back to its default — so the loop has
            // nothing left to look at, and without this the word would go unreported.
            // `overrides` settles which of two flags is in effect; it does not make a word
            // that was never one of the choices into one. usage-lib and clap both refuse
            // `--log-level=v --trace` for that reason, and mise's spec is where the
            // divergence showed up. A repeat of the *same* flag clears this ledger itself,
            // so what reaches here is a word nothing later replaced.
            if #active && partial.#invalid {
                return ::std::result::Result::Err(
                    usage_argv::Error::InvalidChoice {
                        name: #name,
                        choices: #choices,
                    },
                );
            }
            // Choices validate lexical input. A typed computed default is already a value of
            // the field's type; its `Display` form exists only so the partial can carry it to
            // the final conversion and need not itself be one of the advertised CLI words.
            // Environment values mark the field given, so they still take this path.
            if #active && partial.#given #standing_only {
                for value in #values {
                    // Compared as text, since a choice is a word.
                //
                // Bytes that are not UTF-8 are passed over rather than reported here. They
                // are not any of the choices, but saying so would answer the wrong question:
                // `InvalidChoice` lists words, and this value is not a word at all. Left
                // alone, it reaches `build`, which reports the UTF-8 failure with the value
                // in it. Comparing the empty string instead — which is what `unwrap_or_default`
                // did — made every such value collide with the choices check first.
                    let ::std::result::Result::Ok(__usage_text) = ::std::str::from_utf8(value)
                    else {
                        continue;
                    };
                    if !usage_argv::spec::choice_matches(#accepted_choices, __usage_text, #ignore_case) {
                        return ::std::result::Result::Err(
                            usage_argv::Error::InvalidChoice {
                                name: #name,
                                choices: #choices,
                            },
                        );
                    }
                }
            }
        })
    });

    let validation_checks = cli.fields.iter().filter_map(|f| {
        let expression = f.validate.as_ref()?;
        let ident = &f.ident;
        let name = &f.name;
        let message = f
            .validate_error
            .as_deref()
            .unwrap_or("does not satisfy the validation expression");
        let values = match f.shape {
            Shape::Optional => quote!(partial.#ident.iter()),
            Shape::Required => quote!(::std::iter::once(&partial.#ident)),
            Shape::Many => quote!(partial.#ident.iter()),
            Shape::Bool | Shape::Count => return None,
        };
        let active = view_field_active(f);
        let standing_only = unless_standing_only(f);
        Some(quote! {
            if #active #standing_only {
                for value in #values {
                    let ::std::result::Result::Ok(__usage_text) = ::std::str::from_utf8(value)
                    else {
                    // The field conversion reports non-UTF-8 with the original bytes. An expr
                    // variable is text, so claiming the validation failed would hide that more
                    // precise error.
                        continue;
                    };
                    let __usage_reason = match usage_validation::validate(#expression, __usage_text) {
                        ::std::result::Result::Ok(true) => continue,
                        ::std::result::Result::Ok(false) => #message.to_string(),
                        ::std::result::Result::Err(error) =>
                            ::std::format!("validation expression failed: {error}"),
                    };
                    return ::std::result::Result::Err(
                        usage_argv::Error::InvalidValue(::std::boxed::Box::new(
                            usage_argv::InvalidValue {
                                name: #name,
                                value: __usage_text.to_string(),
                                reason: __usage_reason,
                            },
                        )),
                    );
                }
            }
        })
    });

    let bound_checks = cli.fields.iter().filter_map(|f| {
        let (var_min, var_max) = if matches!(f.kind, Kind::Flag { variadic: true, .. }) {
            (f.value_var_min, f.value_var_max)
        } else {
            (f.var_min, f.var_max)
        };
        if (var_min.is_none() && var_max.is_none()) || f.shape != Shape::Many {
            return None;
        }
        let ident = &f.ident;
        let name = &f.name;
        let min = match var_min {
            Some(min) => quote! {
                if got < #min {
                    return ::std::result::Result::Err(
                        usage_argv::Error::VarTooFew { name: #name, min: #min, got },
                    );
                }
            },
            None => quote!(),
        };
        // `var_max` is a binding limit for anything that *collects*: a variadic stops at it
        // and the next field takes the rest, so a total above it cannot arise and this
        // check would be unreachable. Worse than unreachable for a repeatable flag whose
        // argument is variadic — each occurrence respects the limit, and the total across
        // occurrences would fail a check the invocation never broke.
        //
        // What is left is the repeatable flag with a single-value argument, where the bound
        // counts occurrences: nothing about one token can decide that, so it stays here.
        let counts_occurrences = matches!(
            &f.kind,
            Kind::Flag {
                variadic: false,
                ..
            }
        ) && f.repeatable;
        let max = match var_max.filter(|_| counts_occurrences) {
            Some(max) => quote! {
                if got > #max {
                    return ::std::result::Result::Err(
                        usage_argv::Error::VarTooMany { name: #name, max: #max, got },
                    );
                }
            },
            None => quote!(),
        };
        let given = format_ident!("__given_{}", ident);
        let active = view_field_active(f);
        Some(quote! {
            // Only when the field was used. A bound says "if you give values, give
            // this many" — reading an unused optional flag as a violation would make
            // `var_min` a second way to spell required-ness, and there would then be
            // no way to say "at least two, if you use it at all".
            if #active && partial.#given {
                let got = partial.#ident.len();
                #min
                #max
            }
        })
    });

    // A conflict asks whether two flags both ended up with a value, which is why it
    // reads `__given_*` rather than the fields themselves: a `bool` flag that was given
    // as `false` is still a flag the user asked for. Env fallback has already run, so a
    // value from the environment counts the same as a typed one — clap does that too,
    // and an asymmetric rule would make the same pair a conflict or not depending on
    // which side happened to be typed.
    // Judge flag/flag conflicts before relationships involving positionals. clap reports the
    // two switches the user explicitly combined before a positional that happens to conflict
    // with either one, regardless of where the positional field was declared. That is also the
    // actionable pair: `start --all --local id` should point at `--all` and `--local`, not let
    // the trailing `id` hide their contradiction.
    let conflict_fields = cli
        .fields
        .iter()
        .filter(|field| matches!(field.kind, Kind::Flag { .. }))
        .chain(
            cli.fields
                .iter()
                .filter(|field| !matches!(field.kind, Kind::Flag { .. })),
        );
    let conflict_checks = conflict_fields.flat_map(move |f| {
        let given = policy_given(f);
        let name = &f.name;
        f.conflicts.iter().map(move |selector| {
            if let Some(other) = cli.field_for_selector(selector) {
                let other_given = policy_given(other);
                let other_name = &other.name;
                quote! {
                    if #given && #other_given {
                        return ::std::result::Result::Err(
                            usage_argv::Error::ConflictingFlags {
                                name: #name,
                                other: #other_name,
                            },
                        );
                    }
                }
            } else {
                quote! {
                    if #given {
                        if let ::std::option::Option::Some(other) =
                            __usage_argument_state(partial, #selector)
                        {
                            if other.given {
                                return ::std::result::Result::Err(
                                    usage_argv::Error::ConflictingFlags {
                                        name: #name,
                                        other: other.name,
                                    },
                                );
                            }
                        }
                    }
                }
            }
        })
    });

    // The positive form, and the same `__given_*` reading for the same reasons: a `bool`
    // given as `false` is still a flag the user asked for, and env fallback has already
    // run, so a requirement satisfied from the environment is satisfied.
    //
    // Reported as the *other* flag being missing rather than as something wrong with the
    // one that named it, which is what clap says: an unmet `requires` is a required
    // argument that was not provided. That also means no new `Error` variant — the hot
    // path's `Result` does not grow to carry a check that only ever fires on the cold one.
    //
    // A target with a default is skipped outright, since it can never be missing.
    let requirement_checks = cli.fields.iter().flat_map(move |f| {
        let given = policy_given(f);
        f.requires.iter().map(move |selector| {
            let Some(other) = cli.field_for_selector(selector) else {
                return quote! {
                    if #given {
                        match __usage_argument_state(partial, #selector) {
                            ::std::option::Option::Some(other) if other.satisfied => {}
                            ::std::option::Option::Some(other) => {
                                return ::std::result::Result::Err(
                                    usage_argv::Error::MissingRequired { name: other.name },
                                );
                            }
                            ::std::option::Option::None => {}
                        }
                    }
                };
            };
            // A flag with a default always has a value, so the requirement it satisfies
            // can never fail — the same reason plain required-ness skips such a field.
            // Decided at compile time, so the check is not merely always-true at run
            // time, it is not there.
            if other.has_default() {
                return quote!();
            }
            let other_given = semantic_given(other);
            let other_name = &other.name;
            let missing = quote! {
                return ::std::result::Result::Err(
                    usage_argv::Error::MissingRequired { name: #other_name },
                );
            };
            match default_if_would_apply(cli, other, Lookup::Standing) {
                Some(pred) => quote! {
                    if #given && !(#other_given) && !(#pred) {
                        #missing
                    }
                },
                None => quote! {
                    if #given && !(#other_given) {
                        #missing
                    }
                },
            }
        })
    });

    // Only an explicit matching value activates this form. Defaults are applied above
    // without setting `__given_*`; argv and environment fallback set it. The partial
    // still holds bytes, so matching does not parse or otherwise reinterpret a value.
    let conditional_requirement_checks = cli.fields.iter().flat_map(move |f| {
        let given = policy_given(f);
        let ident = &f.ident;
        f.requires_if.iter().map(move |condition| {
            let external = cli.field_for_selector(&condition.requires).is_none();
            let other = cli.field_for_selector(&condition.requires);
            if external {
                let selector = &condition.requires;
                let value = &condition.value;
                let matches = match f.shape {
                    Shape::Optional => {
                        quote!(partial.#ident.as_deref().is_some_and(|v| v == #value.as_bytes()))
                    }
                    Shape::Required => quote!(partial.#ident.as_slice() == #value.as_bytes()),
                    Shape::Many => {
                        quote!(partial.#ident.iter().any(|v| v.as_slice() == #value.as_bytes()))
                    }
                    Shape::Bool => match value.as_str() {
                        "true" => quote!(partial.#ident),
                        "false" => quote!(!partial.#ident),
                        _ => quote!(false),
                    },
                    Shape::Count => match value.as_str() {
                        "true" => quote!(partial.#ident > 0),
                        "false" => quote!(partial.#ident == 0),
                        _ => quote!(false),
                    },
                };
                return quote! {
                    if #given && #matches {
                        match __usage_argument_state(partial, #selector) {
                            ::std::option::Option::Some(other) if other.satisfied => {}
                            ::std::option::Option::Some(other) => {
                                return ::std::result::Result::Err(
                                    usage_argv::Error::MissingRequired { name: other.name },
                                );
                            }
                            ::std::option::Option::None => {}
                        }
                    }
                };
            }
            let other = other.expect("the local relationship was resolved above");
            if other.has_default() {
                return quote!();
            }
            let other_given = semantic_given(other);
            let other_name = &other.name;
            let value = &condition.value;
            let matches = match f.shape {
                Shape::Optional => quote!(
                    partial.#ident.as_deref().is_some_and(|v| v == #value.as_bytes())
                ),
                Shape::Required => quote!(partial.#ident.as_slice() == #value.as_bytes()),
                Shape::Many => quote!(
                    partial.#ident.iter().any(|v| v.as_slice() == #value.as_bytes())
                ),
                Shape::Bool => match value.as_str() {
                    "true" => quote!(partial.#ident),
                    "false" => quote!(!partial.#ident),
                    _ => quote!(false),
                },
                Shape::Count => match value.as_str() {
                    "true" => quote!(partial.#ident > 0),
                    "false" => quote!(partial.#ident == 0),
                    _ => quote!(false),
                },
            };
            let unless_default_if = match default_if_would_apply(cli, other, Lookup::Standing) {
                Some(pred) => quote!(&& !(#pred)),
                None => quote!(),
            };
            quote! {
                if #given && #matches && !(#other_given) #unless_default_if {
                    return ::std::result::Result::Err(
                        usage_argv::Error::MissingRequired { name: #other_name },
                    );
                }
            }
        })
    });

    // An exclusive flag is a conflict with the whole command rather than with a named
    // flag, so it is written as one check per *other* declaration — positionals included,
    // which is what makes it more than being in a group with every other flag.
    //
    // Only what was given counts, as `conflicts` reads it: a defaulted field standing
    // beside an exclusive flag is nobody saying anything, and counting it would make the
    // flag unusable on any command that has a default.
    let exclusive_checks = cli
        .fields
        .iter()
        .filter(|f| f.exclusive)
        .flat_map(move |f| {
            let given = policy_given(f);
            let name = &f.name;
            cli.fields
                .iter()
                .filter(move |other| other.ident != f.ident)
                .filter(|other| {
                    !matches!(
                        other.kind,
                        Kind::Subcommand { .. }
                            | Kind::Flatten { .. }
                            | Kind::ArgGroup { .. }
                            | Kind::Skip
                    )
                })
                .map(move |other| {
                    let other_given = policy_given(other);
                    let other_name = &other.name;
                    quote! {
                        if #given && #other_given {
                            return ::std::result::Result::Err(
                                usage_argv::Error::ConflictingFlags {
                                    name: #other_name,
                                    other: #name,
                                },
                            );
                        }
                    }
                })
                .collect::<Vec<_>>()
        });

    // A flattened partial is intentionally opaque to its parent. Ask through
    // `CommandArgs` whether either side of an exclusive relationship was given, so the
    // relationship does not disappear merely because the declarations live in reusable
    // `Args`. A selected subcommand is itself another declaration in this command; its
    // contents remain in the child command's own scope.
    let direct_given = cli
        .fields
        .iter()
        .filter(|field| {
            !matches!(
                field.kind,
                Kind::Flatten { .. } | Kind::ArgGroup { .. } | Kind::Subcommand { .. } | Kind::Skip
            )
        })
        .rev()
        .fold(quote!(::std::option::Option::None), |rest, field| {
            let given = policy_given(field);
            let name = &field.name;
            quote!(if #given { ::std::option::Option::Some(#name) } else { #rest })
        });
    let direct_exclusive = cli
        .fields
        .iter()
        .filter(|field| field.exclusive)
        .rev()
        .fold(quote!(::std::option::Option::None), |rest, field| {
            let given = policy_given(field);
            let name = &field.name;
            quote!(if #given { ::std::option::Option::Some(#name) } else { #rest })
        });
    let has_flatten = cli
        .fields
        .iter()
        .any(|field| matches!(field.kind, Kind::Flatten { .. } | Kind::ArgGroup { .. }));
    let flattened_segments = cli.fields.iter().filter_map(|field| {
        let ident = &field.ident;
        let standing = standing_ident(field);
        match &field.kind {
            Kind::Flatten { ty, .. } => Some(quote! {
                (
                    <#ty as usage_argv::spec::CommandArgs>::any_given(&partial.#ident)
                        .or_else(|| {
                            #standing.and_then(
                                <#ty as usage_argv::spec::CommandArgs>::any_standing,
                            )
                        }),
                    <#ty as usage_argv::spec::CommandArgs>::exclusive_given(&partial.#ident),
                ),
            }),
            // A group declares no `exclusive` member of its own — exclusivity within the
            // group is what a group *is* — so it contributes only what it was given, which
            // is what an exclusive flag elsewhere on the command collides with.
            Kind::ArgGroup { ty, .. } => {
                // Which member an update already had is the enum's business rather than
                // this command's; the group's own name is what it can say about it.
                let name = &field.name;
                Some(quote! {
                    (
                        <#ty as usage_argv::spec::ArgGroup>::any_given(&partial.#ident)
                            .or_else(|| #standing.map(|_| #name)),
                        ::std::option::Option::None,
                    ),
                })
            }
            _ => None,
        }
    });
    let subcommand_segment = cli.fields.iter().find_map(|field| {
        let Kind::Subcommand { ty, .. } = &field.kind else {
            return None;
        };
        let name = &field.name;
        let standing = standing_ident(field);
        Some(quote! {
            (
                partial
                    .__usage_selected
                    .map(|_| #name)
                    .or_else(|| #standing.map(|_| #name)),
                <#ty as usage_argv::spec::Subcommands>::exclusive_given(
                    &partial.__usage_sub,
                    partial.__usage_selected,
                ),
            ),
        })
    });
    let exclusive_cross_checks = (has_flatten || subcommand_segment.is_some()).then(|| {
        quote! {
            let __usage_exclusive_segments = [
                (#direct_given, #direct_exclusive),
                #(#flattened_segments)*
                #subcommand_segment
            ];
            for __usage_i in 0..__usage_exclusive_segments.len() {
                if let ::std::option::Option::Some(exclusive) =
                    __usage_exclusive_segments[__usage_i].1
                {
                    for __usage_j in 0..__usage_exclusive_segments.len() {
                        if __usage_i == __usage_j {
                            continue;
                        }
                        if let ::std::option::Option::Some(other) =
                            __usage_exclusive_segments[__usage_j].0
                        {
                            return ::std::result::Result::Err(
                                usage_argv::Error::ConflictingFlags {
                                    name: other,
                                    other: exclusive,
                                },
                            );
                        }
                    }
                }
            }
        }
    });

    // Groups, checked once per group rather than per member: both questions a group asks
    // — how many members were given, and whether that is enough — are about the set.
    //
    // The two halves read a default differently, deliberately, and the same way
    // usage-lib does. Exclusivity counts what was supplied, or a defaulted member would
    // collide with the sibling the user typed; requiredness asks whether a member ended
    // up with a value, and a default is a value.
    let group_checks = declared_groups(cli)
        .into_iter()
        .map(|(name, required, multiple, members)| {
            let fields: Vec<&Field> = members
                .iter()
                .filter_map(|selector| cli.field_for_selector(selector))
                .collect();
            let given: Vec<TokenStream> = fields.iter().map(|f| policy_given(f)).collect();
            let exclusivity = (!multiple).then(|| {
                // Reported as the first two that were given, which is the pair the user has
                // to choose between. `ConflictingFlags` rather than a group-shaped error:
                // what went wrong is that two flags were given together, which is exactly
                // what that error says.
                let names: Vec<&String> = fields.iter().map(|f| &f.name).collect();
                let pairs = (0..fields.len()).flat_map(|i| {
                    let (later, earlier) = (given.clone(), given.clone());
                    let (later_names, earlier_names) = (names.clone(), names.clone());
                    ((i + 1)..fields.len())
                        .map(move |j| {
                            let (a, b) = (&earlier[i], &later[j]);
                            let (name_a, name_b) = (earlier_names[i], later_names[j]);
                            quote! {
                                if #a && #b {
                                    return ::std::result::Result::Err(
                                        usage_argv::Error::ConflictingFlags {
                                            name: #name_b,
                                            other: #name_a,
                                        },
                                    );
                                }
                            }
                        })
                        .collect::<Vec<_>>()
                });
                quote!(#(#pairs)*)
            });
            let requiredness = required.then(|| {
                let selectors = &members;
                let active: Vec<TokenStream> =
                    fields.iter().map(|f| view_field_active(f)).collect();
                let view_members = cli.views.iter().map(|view| {
                    let id = &view.id;
                    let carried: Vec<&String> = fields
                        .iter()
                        .zip(&members)
                        .filter_map(|(field, selector)| {
                            field_active_in_view(field, view).then_some(selector)
                        })
                        .collect();
                    quote!(#id => &[#(#carried),*])
                });
                let filled: Vec<TokenStream> = fields
                    .iter()
                    .zip(&given)
                    .zip(&active)
                    .map(|((field, given), active)| {
                        if !field.has_default() {
                            quote!((#active) && (#given))
                        } else {
                            quote!(#active)
                        }
                    })
                    .collect();
                quote! {
                    if (#(#active)||*) && !(#(#filled)||*) {
                        let __usage_group_members: &'static [&'static str] =
                            match __usage_view {
                                ::std::option::Option::None => &[#(#selectors),*],
                                ::std::option::Option::Some(__usage_group_view) => {
                                    match __usage_group_view.id {
                                        #(#view_members,)*
                                        _ => &[#(#selectors),*],
                                    }
                                }
                            };
                        return ::std::result::Result::Err(
                            usage_argv::Error::MissingGroup {
                                group: #name,
                                members: __usage_group_members,
                            },
                        );
                    }
                }
            });
            (exclusivity, requiredness)
        })
        .collect::<Vec<_>>();
    // Two passes rather than one block per group, because the order between *kinds* of
    // check is the one this function promises: what the user typed wrong before what
    // they left out. Emitted together, an earlier group's `MissingGroup` would answer
    // before a later group's `ConflictingFlags` — and before a flattened child's, since
    // those run later still.
    let mut group_exclusivity_checks: Vec<TokenStream> =
        group_checks.iter().filter_map(|(e, _)| e.clone()).collect();
    let mut group_required_checks: Vec<TokenStream> =
        group_checks.iter().filter_map(|(_, r)| r.clone()).collect();

    // An argument group asks the same two questions of a partial only its own expansion can
    // read, so it answers them and this command reports them — in the same two phases, so a
    // conflict here still comes before an unsatisfied group anywhere on the command.
    for field in &cli.fields {
        let Kind::ArgGroup {
            ty,
            optional,
            multiple,
        } = &field.kind
        else {
            continue;
        };
        let ident = &field.ident;
        let group = quote!(<#ty as usage_argv::spec::ArgGroup>);
        if !multiple {
            group_exclusivity_checks.push(quote! {
                if let ::std::option::Option::Some((__usage_earlier, __usage_later)) =
                    #group::conflict(&partial.#ident)
                {
                    return ::std::result::Result::Err(
                        usage_argv::Error::ConflictingFlags {
                            name: __usage_later,
                            other: __usage_earlier,
                        },
                    );
                }
            });
        }
        if *optional || *multiple {
            continue;
        }
        // A bare `T` has nowhere to put "no member", which is the whole declaration — the
        // same reading of a type that makes a `String` field required.
        let active = view_field_active(field);
        let standing_held = unless_standing(field);
        group_required_checks.push(quote! {
            if #active && #group::any_given(&partial.#ident).is_none() #standing_held {
                return ::std::result::Result::Err(
                    usage_argv::Error::MissingGroup {
                        group: #group::NAME,
                        members: #group::MEMBERS,
                    },
                );
            }
        });
    }

    // `required_if` and `required_unless` are the same question asked two ways: which
    // other flags decide whether this one had to be given. Neither needs to know the
    // order they arrived in — only whether they arrived — so both are answered here,
    // beside plain required-ness, from the same `__given_*` flags.
    let relationship_required_checks = cli.fields.iter().filter_map(move |f| {
        if f.required_if.is_empty()
            && f.required_if_eq.is_empty()
            && f.required_if_eq_all.is_empty()
            && f.required_unless.is_empty()
            && f.required_unless_all.is_empty()
        {
            return None;
        }
        // A field with a default is already filled, so no condition can make it
        // missing. Plain required-ness skips these too, and so does usage-lib.
        if f.has_default() {
            return None;
        }
        let given = format_ident!("__given_{}", f.ident);
        let active = view_field_active(f);
        let name = &f.name;
        let selector_given = |selector: &String| {
            Some(match cli.field_for_selector(selector) {
                Some(other) => policy_given(other),
                None => quote!(
                    __usage_argument_state(partial, #selector).is_some_and(|state| state.given)
                ),
            })
        };
        let if_given: Vec<_> = f.required_if.iter().filter_map(selector_given).collect();
        let unless_given: Vec<_> = f
            .required_unless
            .iter()
            .filter_map(selector_given)
            .collect();
        let if_eq: Vec<_> = f
            .required_if_eq
            .iter()
            .map(|condition| {
                let selector = cli
                    .field_for_selector(&condition.selector)
                    .and_then(Cli::selector_for_field)
                    .unwrap_or_else(|| condition.selector.clone());
                let value = &condition.value;
                quote!(
                    __usage_argument_matches(partial, #selector, #value.as_bytes())
                        .unwrap_or(false)
                )
            })
            .collect();
        let if_eq_all: Vec<_> = f
            .required_if_eq_all
            .iter()
            .map(|condition| {
                let selector = cli
                    .field_for_selector(&condition.selector)
                    .and_then(Cli::selector_for_field)
                    .unwrap_or_else(|| condition.selector.clone());
                let value = &condition.value;
                quote!(
                    __usage_argument_matches(partial, #selector, #value.as_bytes())
                        .unwrap_or(false)
                )
            })
            .collect();
        let unless_all_given: Vec<_> = f
            .required_unless_all
            .iter()
            .filter_map(selector_given)
            .collect();
        // Absent, with nothing standing in for it: a default or an environment
        // variable has already filled the field and set `__given_*`.
        let missing = quote! {
            return ::std::result::Result::Err(
                usage_argv::Error::MissingRequired { name: #name },
            );
        };
        let required_if = (!if_given.is_empty()).then(|| {
            quote! {
                if #(#if_given)||* {
                    #missing
                }
            }
        });
        let required_if_eq = (!if_eq.is_empty()).then(|| {
            quote! {
                if #(#if_eq)||* {
                    #missing
                }
            }
        });
        let required_if_eq_all = (!if_eq_all.is_empty()).then(|| {
            quote! {
                if #(#if_eq_all)&&* {
                    #missing
                }
            }
        });
        let required_unless =
            (!unless_given.is_empty() || !unless_all_given.is_empty()).then(|| {
                let any = if unless_given.is_empty() {
                    quote!(false)
                } else {
                    quote!(#(#unless_given)||*)
                };
                let all = if unless_all_given.is_empty() {
                    quote!(false)
                } else {
                    quote!(#(#unless_all_given)&&*)
                };
                quote! {
                    if !(#any || #all) {
                        #missing
                    }
                }
            });
        let standing_held = unless_standing(f);
        Some(quote! {
            if #active && !partial.#given #standing_held {
                #required_if
                #required_if_eq
                #required_if_eq_all
                #required_unless
            }
        })
    });

    quote! {
        // What the caller already had, read once. `None` for an ordinary parse, which
        // folds every one of these to `false`.
        #standing_locals
        #argument_state_standing
        // Environment first, so a `default_if` can see a sibling filled from
        // env, and so the environment still overrides an unconditional default.
        #env_fallbacks
        #declared_defaults
        let __usage_exclusive_present = #exclusive_present;
        #(#duplicate_checks)*
        // Before required-ness: "you gave two flags that cannot go together" is the
        // more useful of the two answers when a conflict has also left something
        // unfilled, and it is the one usage-lib reports.
        #(#conflict_checks)*
        #(#exclusive_checks)*
        #exclusive_cross_checks
        #(#group_exclusivity_checks)*
        #(#flattened_checks)*
        #(#clause_checks)*
        // An exclusive occurrence is the command's escape from requiredness, just as in clap:
        // `--version` remains usable on a command that otherwise requires an input. Conflicts
        // and other validation still ran above; only errors about absent siblings are skipped.
        if !__usage_exclusive_present && !(#subcommand_satisfies_requirements) {
            #(#requirement_checks)*
            #(#conditional_requirement_checks)*
            #(#required_checks)*
            #(#group_required_checks)*
            #(#relationship_required_checks)*
        }
        #(#choice_checks)*
        #(#validation_checks)*
        #(#bound_checks)*
        #sub_check
    }
}

/// The word list for a value enum.
///
/// Conversion is generated from the same canonical words and aliases as the metadata, so
/// parsing, help, and completion cannot drift. A separate domain `FromStr` implementation
/// may still coexist; value-enum fields do not call it.
pub fn emit_value_enum(value_enum: &ValueEnum) -> TokenStream {
    let ident = &value_enum.ident;
    let runtime = runtime_path();
    let words = value_enum.variants.iter().flat_map(|value| {
        let cfg = &value.cfg_attrs;
        ::std::iter::once((!value.hide).then_some(&value.name))
            .chain(
                value
                    .aliases
                    .iter()
                    .map(|alias| (!alias.hide).then_some(&alias.name)),
            )
            .flatten()
            .map(move |word| quote!(#(#cfg)* #word))
    });
    let accepted = value_enum.variants.iter().flat_map(|value| {
        let cfg = &value.cfg_attrs;
        ::std::iter::once(&value.name)
            .chain(value.aliases.iter().map(|alias| &alias.name))
            .map(move |word| quote!(#(#cfg)* #word))
    });
    let aliases = value_enum.variants.iter().flat_map(|value| {
        let canonical = &value.name;
        let cfg = &value.cfg_attrs;
        value.aliases.iter().map(move |alias| {
            let alias = &alias.name;
            quote!(#(#cfg)* (#canonical, #alias))
        })
    });
    let details = value_enum.variants.iter().map(|value| {
        let canonical = &value.name;
        let help = option_str(value.help.as_deref());
        let hide = value.hide;
        let cfg = &value.cfg_attrs;
        let aliases = value.aliases.iter().map(|alias| {
            let name = &alias.name;
            let hide = alias.hide;
            quote!(usage_argv::spec::ChoiceAliasMeta { value: #name, hide: #hide })
        });
        quote!(
            #(#cfg)* usage_argv::spec::ChoiceMeta {
                value: #canonical,
                help: #help,
                hide: #hide,
                aliases: &[#(#aliases),*],
            }
        )
    });
    let ignore_case = value_enum.ignore_case;
    let parse_arms = value_enum.variants.iter().map(|value| {
        let ident = &value.ident;
        let cfg = &value.cfg_attrs;
        let names = ::std::iter::once(&value.name).chain(value.aliases.iter().map(|a| &a.name));
        quote! {
            #(#cfg)*
            if [#(#names),*].iter().any(|candidate| {
                *candidate == value || #ignore_case && candidate.eq_ignore_ascii_case(value)
            }) {
                return ::std::option::Option::Some(Self::#ident);
            }
        }
    });

    quote! {
        #[doc(hidden)]
        const _: () = {
            use #runtime as usage_argv;

            impl usage_argv::spec::ValueEnum for #ident {
                const CHOICES: &'static [&'static str] = &[#(#words),*];
                const ACCEPTED_CHOICES: &'static [&'static str] = &[#(#accepted),*];
                const ALIASES: &'static [(&'static str, &'static str)] = &[#(#aliases),*];
                const DETAILS: &'static [usage_argv::spec::ChoiceMeta<'static>] = &[#(#details),*];
                const IGNORE_CASE: bool = #ignore_case;

                fn from_choice(value: &str) -> ::std::option::Option<Self> {
                    #(#parse_arms)*
                    ::std::option::Option::None
                }
            }
        };
    }
}

/// The switches an argument group's variants are, and the state that collects them.
///
/// The same shape as a command's own tables — `static` flags, `static` metadata, and a
/// partial an event is applied to — so a holding command splices them into its own tables at
/// compile time exactly as it splices a flattened `Args`. Which of them was given is decided
/// here; whether that is *acceptable* is the holding command's `check`, because required-ness
/// is a property of the field rather than of the enum.
pub fn emit_arg_group(group: &ArgGroup) -> TokenStream {
    let ident = &group.ident;
    let runtime = runtime_path();
    let name = &group.name;
    let multiple = group.multiple;

    // Minted from this declaration and the module it sits in, like a command's: two argument
    // groups in different modules cannot hand a parse the same key, and the arm that claims an
    // event verifies it came from this table.
    let declaration = declaration_hash(&group.fingerprint);
    let key_decls = group.variants.iter().enumerate().map(|(i, member)| {
        let key = key_ident("FLAG", Some(i));
        let index = i as u64;
        let cfg = &member.cfg_attrs;
        quote!(#(#cfg)* const #key: u64 = __USAGE_KEY_BASE | #KIND_FLAG | #index;)
    });

    let flags = group.variants.iter().enumerate().map(|(i, member)| {
        let table = format_ident!("FLAG_{i}");
        let key = key_ident("FLAG", Some(i));
        let cfg = &member.cfg_attrs;
        let long = &member.name;
        let shorts: Vec<u8> = member.short.map(|short| short as u8).into_iter().collect();
        let shape = if member.value_ty.is_some() {
            quote!(usage_argv::Flag::VALUE)
        } else {
            quote!(usage_argv::Flag::BOOL)
        };
        quote! {
            #(#cfg)*
            pub static #table: usage_argv::Flag = usage_argv::Flag {
                key: #key,
                name: #long,
                longs: &[#long],
                shorts: &[#(#shorts),*],
                ..#shape
            };
        }
    });

    let flag_refs = group.variants.iter().enumerate().map(|(i, member)| {
        let table = format_ident!("FLAG_{i}");
        let cfg = &member.cfg_attrs;
        quote!(#(#cfg)* &#table)
    });
    let flag_metas = group.variants.iter().enumerate().map(|(i, member)| {
        let table = format_ident!("FLAG_{i}");
        let cfg = &member.cfg_attrs;
        let help = option_str(member.help.as_deref());
        let long_help = option_str(member.long_help.as_deref());
        let hide = member.hide;
        let value_name = option_str(member.value_name.as_deref());
        let (accepted_choices, choices, choice_aliases, choice_details, ignore_case) =
            match (&member.value_ty, member.value_enum) {
                (Some(ty), true) => (
                    quote!(<#ty as usage_argv::spec::ValueEnum>::ACCEPTED_CHOICES),
                    quote!(<#ty as usage_argv::spec::ValueEnum>::CHOICES),
                    quote!(<#ty as usage_argv::spec::ValueEnum>::ALIASES),
                    quote!(<#ty as usage_argv::spec::ValueEnum>::DETAILS),
                    quote!(<#ty as usage_argv::spec::ValueEnum>::IGNORE_CASE),
                ),
                _ => (
                    quote!(&[]),
                    quote!(&[]),
                    quote!(&[]),
                    quote!(&[]),
                    quote!(false),
                ),
            };
        quote! {
            #(#cfg)*
            usage_argv::spec::FlagMeta {
                flag: &#table,
                help: #help,
                long_help: #long_help,
                hide: #hide,
                repeatable: #multiple,
                value_name: #value_name,
                accepted_choices: #accepted_choices,
                choices: #choices,
                choice_aliases: #choice_aliases,
                choice_details: #choice_details,
                ignore_case: #ignore_case,
                ..usage_argv::spec::FlagMeta::EMPTY
            }
        }
    });
    let members = group.variants.iter().map(|member| {
        let cfg = &member.cfg_attrs;
        let selector = format!("--{}", member.name);
        quote!(#(#cfg)* #selector)
    });

    let ordered_field = multiple.then(|| {
        quote!(pub ordered: ::std::vec::Vec<(usize, ::std::option::Option<::std::vec::Vec<u8>>)> ,)
    });
    let partial_fields = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        if member.value_ty.is_some() {
            quote!(#(#cfg)* pub #given: ::std::option::Option<::std::vec::Vec<u8>>,)
        } else {
            quote!(#(#cfg)* pub #given: bool,)
        }
    });
    let apply_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let table = format_ident!("FLAG_{i}");
        let key = key_ident("FLAG", Some(i));
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let record = if multiple {
            if member.value_ty.is_some() {
                quote!(partial.ordered.push((#i, value.map(<[u8]>::to_vec)));)
            } else {
                quote!(partial.ordered.push((#i, ::std::option::Option::None));)
            }
        } else {
            quote!()
        };
        let assign = if member.value_ty.is_some() {
            quote! {
                if let ::std::option::Option::Some(value) = value {
                    partial.#given = ::std::option::Option::Some(value.to_vec());
                }
            }
        } else {
            quote!(partial.#given = true;)
        };
        quote! {
            #(#cfg)*
            #key if ::core::ptr::eq(*flag, &#table) => {
                #record
                #assign
                true
            }
        }
    });
    let given_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let name = &member.name;
        let is_given = if member.value_ty.is_some() {
            quote!(partial.#given.is_some())
        } else {
            quote!(partial.#given)
        };
        quote! {
            #(#cfg)*
            if #is_given {
                return ::std::option::Option::Some(#name);
            }
        }
    });
    // The first two given, in declaration order, which is the pair the user has to choose
    // between — and the same pair a hand-written group's pairwise check reports.
    let conflict_arms: Vec<_> = group
        .variants
        .iter()
        .enumerate()
        .filter_map(|(i, member)| {
            if multiple {
                return None;
            }
            let given = format_ident!("given_{i}");
            let cfg = &member.cfg_attrs;
            let name = &member.name;
            let is_given = if member.value_ty.is_some() {
                quote!(partial.#given.is_some())
            } else {
                quote!(partial.#given)
            };
            Some(quote! {
                #(#cfg)*
                if #is_given {
                    if let ::std::option::Option::Some(__usage_earlier) = __usage_first {
                        return ::std::option::Option::Some((__usage_earlier, #name));
                    }
                    __usage_first = ::std::option::Option::Some(#name);
                }
            })
        })
        .collect();
    let build_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let variant = &member.ident;
        let Some(ty) = &member.value_ty else {
            return quote! {
                #(#cfg)*
                if partial.#given {
                    return ::std::result::Result::Ok(
                        ::std::option::Option::Some(Self::#variant),
                    );
                }
            };
        };
        let name = &member.name;
        let rendered = rendered_path(ty);
        let converted = match rendered.as_str() {
            "PathBuf" | "std::path::PathBuf" | "::std::path::PathBuf" => quote! {
                match usage_argv::os_string_from_bytes(__usage_value) {
                    ::std::result::Result::Ok(value) => ::std::path::PathBuf::from(value),
                    ::std::result::Result::Err(bytes) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_os_value(#name, bytes),
                        );
                    }
                }
            },
            "OsString" | "std::ffi::OsString" | "::std::ffi::OsString" => quote! {
                match usage_argv::os_string_from_bytes(__usage_value) {
                    ::std::result::Result::Ok(value) => value,
                    ::std::result::Result::Err(bytes) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_os_value(#name, bytes),
                        );
                    }
                }
            },
            _ if member.value_enum => quote! {{
                let __usage_text = match ::std::string::String::from_utf8(__usage_value) {
                    ::std::result::Result::Ok(text) => text,
                    ::std::result::Result::Err(bad) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_utf8_value(#name, bad),
                        );
                    }
                };
                match <#ty as usage_argv::spec::ValueEnum>::from_choice(&__usage_text) {
                    ::std::option::Option::Some(value) => value,
                    ::std::option::Option::None => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_choice_value(#name, __usage_text),
                        );
                    }
                }
            }},
            _ => quote! {{
                let __usage_text = match ::std::string::String::from_utf8(__usage_value) {
                    ::std::result::Result::Ok(text) => text,
                    ::std::result::Result::Err(bad) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_utf8_value(#name, bad),
                        );
                    }
                };
                match ::std::str::FromStr::from_str(&__usage_text) {
                    ::std::result::Result::Ok(value) => value,
                    ::std::result::Result::Err(reason) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_parsed_value(#name, __usage_text, &reason),
                        );
                    }
                }
            }},
        };
        quote! {
            #(#cfg)*
            if let ::std::option::Option::Some(__usage_value) = partial.#given.clone() {
                let __usage_value: #ty = #converted;
                return ::std::result::Result::Ok(
                    ::std::option::Option::Some(Self::#variant(__usage_value)),
                );
            }
        }
    });
    let build_many_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let cfg = &member.cfg_attrs;
        let variant = &member.ident;
        let Some(ty) = &member.value_ty else {
            return quote! {
                #(#cfg)*
                #i => Self::#variant,
            };
        };
        let name = &member.name;
        let rendered = rendered_path(ty);
        let converted = match rendered.as_str() {
            "PathBuf" | "std::path::PathBuf" | "::std::path::PathBuf" => quote! {
                match usage_argv::os_string_from_bytes(__usage_value) {
                    ::std::result::Result::Ok(value) => ::std::path::PathBuf::from(value),
                    ::std::result::Result::Err(bytes) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_os_value(#name, bytes),
                        );
                    }
                }
            },
            "OsString" | "std::ffi::OsString" | "::std::ffi::OsString" => quote! {
                match usage_argv::os_string_from_bytes(__usage_value) {
                    ::std::result::Result::Ok(value) => value,
                    ::std::result::Result::Err(bytes) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_os_value(#name, bytes),
                        );
                    }
                }
            },
            _ if member.value_enum => quote! {{
                let __usage_text = match ::std::string::String::from_utf8(__usage_value) {
                    ::std::result::Result::Ok(text) => text,
                    ::std::result::Result::Err(bad) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_utf8_value(#name, bad),
                        );
                    }
                };
                match <#ty as usage_argv::spec::ValueEnum>::from_choice(&__usage_text) {
                    ::std::option::Option::Some(value) => value,
                    ::std::option::Option::None => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_choice_value(#name, __usage_text),
                        );
                    }
                }
            }},
            _ => quote! {{
                let __usage_text = match ::std::string::String::from_utf8(__usage_value) {
                    ::std::result::Result::Ok(text) => text,
                    ::std::result::Result::Err(bad) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_utf8_value(#name, bad),
                        );
                    }
                };
                match ::std::str::FromStr::from_str(&__usage_text) {
                    ::std::result::Result::Ok(value) => value,
                    ::std::result::Result::Err(reason) => {
                        return ::std::result::Result::Err(
                            usage_argv::invalid_parsed_value(#name, __usage_text, &reason),
                        );
                    }
                }
            }},
        };
        quote! {
            #(#cfg)*
            #i => {
                let __usage_value = __usage_value.clone().unwrap_or_default();
                let __usage_value: #ty = #converted;
                Self::#variant(__usage_value)
            }
        }
    });
    // Long and short spellings a member answers to, for relationship lookups from a parent.
    let member_selectors = |member: &ArgGroupMember| -> Vec<String> {
        let mut selectors = vec![format!("--{}", member.name)];
        if let Some(short) = member.short {
            selectors.push(format!("-{short}"));
        }
        selectors
    };
    let state_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let name = &member.name;
        let selectors = member_selectors(member);
        let is_given = if member.value_ty.is_some() {
            quote!(partial.#given.is_some())
        } else {
            quote!(partial.#given)
        };
        quote! {
            #(#cfg)*
            #(#selectors)|* => {
                ::std::option::Option::Some(usage_argv::spec::ArgumentState {
                    name: #name,
                    given: #is_given,
                    satisfied: #is_given,
                })
            }
        }
    });
    let standing_state_arms = group.variants.iter().map(|member| {
        let cfg = &member.cfg_attrs;
        let name = &member.name;
        let variant = &member.ident;
        let selectors = member_selectors(member);
        let standing = if member.value_ty.is_some() {
            quote!(::core::matches!(standing, Self::#variant(_)))
        } else {
            quote!(::core::matches!(standing, Self::#variant))
        };
        quote! {
            #(#cfg)*
            #(#selectors)|* => {
                let __usage_given = #standing;
                ::std::option::Option::Some(usage_argv::spec::ArgumentState {
                    name: #name,
                    given: __usage_given,
                    satisfied: __usage_given,
                })
            }
        }
    });
    let match_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let selectors = member_selectors(member);
        let matches = if member.value_enum {
            let ty = member
                .value_ty
                .as_ref()
                .expect("value_enum members were checked to carry a value");
            quote! {
                partial.#given.as_deref().is_some_and(|given| {
                    if <#ty as usage_argv::spec::ValueEnum>::IGNORE_CASE {
                        given.eq_ignore_ascii_case(value)
                    } else {
                        given == value
                    }
                })
            }
        } else if member.value_ty.is_some() {
            quote!(partial.#given.as_deref().is_some_and(|given| given == value))
        } else {
            // Switch presence is the value. Wrap like an ordinary bool flag so a missing
            // member does not "match" `"false"`.
            quote!(partial.#given && value == b"true")
        };
        quote! {
            #(#cfg)*
            #(#selectors)|* => {
                return ::std::option::Option::Some(#matches);
            }
        }
    });
    let standing_match_arms = group.variants.iter().map(|member| {
        let cfg = &member.cfg_attrs;
        let variant = &member.ident;
        let selectors = member_selectors(member);
        let Some(_) = &member.value_ty else {
            return quote! {
                #(#cfg)*
                #(#selectors)|* => {
                    return ::std::option::Option::Some(
                        ::core::matches!(standing, Self::#variant) && value == b"true",
                    );
                }
            };
        };
        quote! {
            #(#cfg)*
            #(#selectors)|* => {
                // `FromStr` has no inverse. An update can retain the selected payload, but
                // cannot reconstruct the bytes needed for a value-equality relationship.
                return ::std::option::Option::None;
            }
        }
    });
    let displace_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let given = format_ident!("given_{i}");
        let cfg = &member.cfg_attrs;
        let selectors = member_selectors(member);
        // Recognition, not mutation: every other `displace` returns true once the
        // selector is known to this type, so a parent that short-circuits on the
        // first true does not fall through to "unresolved" when the member was
        // simply not given. Clearing is what happens when it *was* given.
        let clear_ordered =
            multiple.then(|| quote!(partial.ordered.retain(|(__usage_at, _)| *__usage_at != #i);));
        let clear = if member.value_ty.is_some() {
            quote!(partial.#given = ::std::option::Option::None;)
        } else {
            quote!(partial.#given = false;)
        };
        quote! {
            #(#cfg)*
            #(#selectors)|* => {
                #clear_ordered
                #clear
                return true;
            }
        }
    });
    let event_arms = group.variants.iter().enumerate().map(|(i, member)| {
        let table = format_ident!("FLAG_{i}");
        let key = key_ident("FLAG", Some(i));
        let cfg = &member.cfg_attrs;
        let selectors = member_selectors(member);
        quote! {
            #(#cfg)*
            #key if ::core::ptr::eq(*flag, &#table) => {
                matches!(selector, #(#selectors)|*)
            }
        }
    });
    let build_many_impl = multiple.then(|| {
        quote! {
            fn try_build_many(
                partial: &Self::Partial,
            ) -> ::std::result::Result<
                ::std::vec::Vec<Self>,
                usage_argv::Error<'static, 'static>,
            > {
                let mut __usage_members = ::std::vec::Vec::with_capacity(partial.ordered.len());
                for (__usage_at, __usage_value) in &partial.ordered {
                    let __usage_member = match *__usage_at {
                        #(#build_many_arms)*
                        _ => continue,
                    };
                    __usage_members.push(__usage_member);
                }
                ::std::result::Result::Ok(__usage_members)
            }
        }
    });

    quote! {
        #[doc(hidden)]
        #[allow(
            non_upper_case_globals,
            non_snake_case,
            unused_imports,
            clippy::needless_update
        )]
        const _: () = {
            use #runtime as usage_argv;

            const __USAGE_KEY_BASE: u64 =
                usage_argv::key_base(::core::module_path!(), #declaration);
            #(#key_decls)*

            #(#flags)*

            #[derive(Default)]
            pub struct Partial {
                #ordered_field
                #(#partial_fields)*
            }

            impl usage_argv::spec::ArgGroup for #ident {
                const NAME: &'static str = #name;
                const FLAGS: &'static [&'static usage_argv::Flag<'static>] = &[#(#flag_refs),*];
                const FLAG_METAS: &'static [usage_argv::spec::FlagMeta<'static>] =
                    &[#(#flag_metas),*];
                const MEMBERS: &'static [&'static str] = &[#(#members),*];
                const MULTIPLE: bool = #multiple;

                type Partial = Partial;

                fn apply(
                    partial: &mut Self::Partial,
                    event: &usage_argv::Event<'_, '_, '_>,
                ) -> bool {
                    match event {
                        usage_argv::Event::Flag { flag, value, .. } => match flag.key {
                            #(#apply_arms)*
                            // Another declaration's flag, left for whoever owns it.
                            _ => false,
                        },
                        _ => false,
                    }
                }

                fn any_given(partial: &Self::Partial) -> ::std::option::Option<&'static str> {
                    #(#given_arms)*
                    ::std::option::Option::None
                }

                fn conflict(
                    partial: &Self::Partial,
                ) -> ::std::option::Option<(&'static str, &'static str)> {
                    let mut __usage_first: ::std::option::Option<&'static str> =
                        ::std::option::Option::None;
                    #(#conflict_arms)*
                    // Read so the last member's assignment is not a store nobody looks at,
                    // which the adopter's crate is where the lint would land.
                    let _ = __usage_first;
                    ::std::option::Option::None
                }

                fn build(partial: &Self::Partial) -> ::std::option::Option<Self> {
                    Self::try_build(partial).ok().flatten()
                }

                fn try_build(
                    partial: &Self::Partial,
                ) -> ::std::result::Result<
                    ::std::option::Option<Self>,
                    usage_argv::Error<'static, 'static>,
                > {
                    #(#build_arms)*
                    ::std::result::Result::Ok(::std::option::Option::None)
                }

                #build_many_impl

                fn argument_state(
                    partial: &Self::Partial,
                    selector: &str,
                ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
                    match selector {
                        #(#state_arms)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn standing_state(
                    standing: &Self,
                    selector: &str,
                ) -> ::std::option::Option<usage_argv::spec::ArgumentState> {
                    match selector {
                        #(#standing_state_arms)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn argument_matches(
                    partial: &Self::Partial,
                    selector: &str,
                    value: &[u8],
                ) -> ::std::option::Option<bool> {
                    match selector {
                        #(#match_arms)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn standing_matches(
                    standing: &Self,
                    selector: &str,
                    value: &[u8],
                ) -> ::std::option::Option<bool> {
                    match selector {
                        #(#standing_match_arms)*
                        _ => ::std::option::Option::None,
                    }
                }

                fn displace(partial: &mut Self::Partial, selector: &str) -> bool {
                    match selector {
                        #(#displace_arms)*
                        _ => false,
                    }
                }

                fn event_matches(
                    event: &usage_argv::Event<'_, '_, '_>,
                    selector: &str,
                ) -> bool {
                    match event {
                        usage_argv::Event::Flag { flag, .. } => match flag.key {
                            #(#event_arms)*
                            _ => false,
                        },
                        _ => false,
                    }
                }
            }
        };
    }
}

#[cfg(test)]
mod binding_hash_tests {
    use super::hash_binding_part;

    fn contract(validate: &str, validate_error: &str) -> u64 {
        let mut hash = 0xcbf2_9ce4_8422_2325u64;
        hash_binding_part(&mut hash, b"validate", Some(validate.as_bytes()));
        hash_binding_part(
            &mut hash,
            b"validate-error",
            Some(validate_error.as_bytes()),
        );
        hash
    }

    #[test]
    fn adjacent_binding_properties_cannot_alias_by_concatenation() {
        assert_ne!(contract("a", "bc"), contract("ab", "c"));
    }
}