autumn-cli 0.9.0

CLI tool for the Autumn web framework
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
//! `autumn a11y verify` — a build-time accessibility audit of raw `html!`
//! markup.
//!
//! The typed primitives in [`autumn_web::a11y`] discharge every accessible-name
//! obligation **at compile time**: an alt-less image or an unlabeled field
//! written through them does not compile. Code that uses those primitives is
//! therefore already proven and is intentionally *not* re-scanned here.
//!
//! This pass covers the escape hatch the type system cannot see: raw markup
//! written directly in a `maud::html! { … }` block, which bypasses the typed
//! primitives entirely. There is no walkable widget tree at runtime, so this is
//! an honest best-effort **static** scan of the `html!` token streams found in
//! the project's `.rs` files — the same token-descent strategy `autumn i18n
//! check` uses to find `t!` calls nested inside `html!`.
//!
//! # Scope and limitations
//!
//! `verify` is a build-time **static** scanner over raw `maud::html!` bodies
//! that applies the WCAG rules below (`image-alt` 1.1.1, `label` 1.3.1 / 3.3.2,
//! `button-name` / `link-name` 4.1.2). It is **best-effort and advisory**: it
//! parses maud markup heuristically at the token level and deliberately errs
//! toward *not* failing on anything it cannot statically resolve — unresolved
//! splices, complex Rust expressions, and non-maud `html!` macros are skipped
//! rather than guessed at. It should never fail valid markup, but it can
//! therefore *miss* a defect in exotic markup (a miss is acceptable by design),
//! so its raw-`html!` findings are advisory-grade signal, not a proof of
//! accessibility. The complete, by-construction guarantee lives in the typed
//! primitives in [`autumn_web::a11y`], where an accessible
//! name is a compile-time type obligation proven by `trybuild`; this scanner is
//! only the escape-hatch net over raw hand-written `html!`.
//!
//! # Ruleset (first slice)
//!
//! Findings reuse the WCAG success-criterion numbers, rule identifiers, and
//! [`Severity`] semantics of the runtime [`autumn check --a11y`](crate::check)
//! lint, applied to static source instead of rendered HTML:
//!
//! - **`image-alt`** — an `<img>` with no `alt` attribute (WCAG 1.1.1, Serious).
//! - **`label`** — an `<input>`/`<select>`/`<textarea>` with no associated
//!   `<label for=…>`, `aria-label`, or `aria-labelledby` (WCAG 1.3.1 / 3.3.2 /
//!   4.1.2, Serious).
//! - **`button-name`** — a `<button>` with no text content and no
//!   `aria-label`/`aria-labelledby` (WCAG 4.1.2, Serious).
//! - **`link-name`** — an `<a>` with an `href` but no text content and no
//!   `aria-label`/`aria-labelledby` (WCAG 2.4.4 / 4.1.2, Serious).
//!
//! # Route attribution
//!
//! A file and a line say where a defect is; a route says which page it breaks.
//! The scan reads the route attribute macros (`#[get("/settings")]`,
//! `#[post(..)]`, …) out of the same token stream, indexes every function and
//! the free functions it calls, then walks out from each handler to the markup
//! it reaches — so a defect in a shared partial names the routes that reach it. The manifest carries the result three ways: a `routes` array of
//! per-route `pass`/`fail`, a `routes` list on each finding, and a `wcag`
//! rollup keyed by success criterion.
//!
//! The walk is as conservative as the scanner: a call is followed only when the
//! called name is defined exactly once in the scope the call can see — the
//! helpers at the top of the caller's body, then the free items. A turbofish
//! call and a function passed by name are followed. Method calls,
//! type-qualified associated calls and names that the function binds are not
//! resolved. An item or a statement under a `cfg` that is false for the crate's
//! features is skipped. The path is the one
//! **declared** on the handler (mount-time
//! prefixes are applied at runtime). So `status: "pass"` means no finding was
//! attributed to that route, not that the page is proven clean — the summary's
//! `unrouted` count qualifies it. An unattributed finding is still a finding:
//! the exit code is computed from severities alone, so attribution reports and
//! never gates.
//!
//! # Known heuristic limits
//!
//! Like `autumn i18n check`, the scanner reads tokens rather than a
//! type-resolved AST, and deliberately errs toward *not* flagging anything it
//! cannot statically resolve — so it never breaks CI on a false positive:
//!
//! - A **spliced** value (`(expr)`) is unknowable, so an element whose relevant
//!   attribute/content is a splice is skipped. In particular a typed primitive
//!   spliced in as `(Img::new(src, alt))` is a `(expr)` group, not an `img`
//!   element, and is never flagged.
//! - Markup inside a `@if` / `@for` / `@match` control block is still scanned
//!   for elements, but a `<label for=…>`/`id` association that a splice makes
//!   unresolvable suppresses the corresponding `label` finding rather than
//!   risking a false positive.
//! - Only maud/autumn `html!` markup is analyzed. A different `html!` macro
//!   (e.g. a Yew/JSX island using `<tag>…</tag>` angle-bracket syntax) is
//!   detected and skipped wholesale — maud never uses JSX tags, so parsing such
//!   a body as maud would misread `<button></button>` as an empty `button` and
//!   fire a false `button-name`.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::str::FromStr as _;

use proc_macro2::{Delimiter, Literal, TokenStream, TokenTree};
use serde::Serialize;

use crate::check::Severity;
use crate::routes::CargoFeatures;

/// Output format for `autumn a11y verify`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable text (default).
    Text,
    /// Machine-readable JSON conformance manifest.
    Json,
}

/// Options parsed from CLI flags.
#[derive(Debug, Clone, Copy)]
pub struct A11yVerifyOptions {
    pub format: OutputFormat,
    /// Lower the failure threshold so any finding (Moderate and above) fails.
    /// The current ruleset only emits Serious findings, so a clean run stays
    /// green either way; the flag is honored for forward compatibility and CI
    /// consistency with `autumn i18n check` / `autumn check --a11y`.
    pub strict: bool,
}

/// An accessibility rule in the raw-`html!` catalog. Each maps to a runtime
/// [`autumn check --a11y`](crate::check) rule id and a WCAG success criterion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rule {
    /// `<img>` with no `alt` attribute.
    ImageAlt,
    /// Form control with no associated label or accessible name.
    Label,
    /// `<button>` with no accessible name.
    ButtonName,
    /// `<a href>` with no accessible name.
    LinkName,
}

impl Rule {
    /// axe-core-style rule id, shared with the runtime lint in [`crate::check`].
    const fn rule_id(self) -> &'static str {
        match self {
            Self::ImageAlt => "image-alt",
            Self::Label => "label",
            Self::ButtonName => "button-name",
            Self::LinkName => "link-name",
        }
    }

    /// The WCAG 2.1 success criterion (or criteria) this rule enforces.
    const fn wcag(self) -> &'static str {
        match self {
            Self::ImageAlt => "1.1.1",
            Self::Label => "1.3.1 / 3.3.2 / 4.1.2",
            Self::ButtonName => "4.1.2",
            Self::LinkName => "2.4.4 / 4.1.2",
        }
    }

    /// Human-readable description of the violation.
    const fn message(self) -> &'static str {
        match self {
            Self::ImageAlt => "raw <img> has no alt attribute",
            Self::Label => {
                "raw form control has no associated <label for=…>, aria-label, or aria-labelledby"
            }
            Self::ButtonName => {
                "raw <button> has no text content and no aria-label/aria-labelledby"
            }
            Self::LinkName => "raw <a href> has no link text and no aria-label/aria-labelledby",
        }
    }

    /// The typed primitive that discharges this obligation at compile time.
    const fn hint(self) -> &'static str {
        match self {
            Self::ImageAlt => "use autumn_web::a11y::Img::new(src, alt) / Img::decorative(src)",
            Self::Label => "use autumn_web::a11y::TextField::new(..).label(..)",
            Self::ButtonName => {
                "use autumn_web::a11y::Button::new(name) / Button::icon(icon, name)"
            }
            Self::LinkName => "use autumn_web::a11y::Link::new(href, text) / Link::icon(..)",
        }
    }
}

/// A single accessibility finding, keyed to a WCAG success criterion.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Finding {
    /// Source file, relative to the project root.
    pub file: String,
    /// 1-based line number of the offending element.
    pub line: usize,
    /// The HTML element that triggered the finding (e.g. `img`, `button`).
    pub element: String,
    /// axe-core-style rule id, shared with `autumn check --a11y`.
    pub rule_id: &'static str,
    /// WCAG 2.1 success criterion (or criteria).
    pub wcag: &'static str,
    /// Violation severity.
    #[serde(serialize_with = "serialize_severity")]
    pub severity: Severity,
    /// Human-readable description of what is wrong.
    pub message: &'static str,
    /// The typed primitive that fixes it at compile time.
    pub hint: &'static str,
    /// Routes that statically reach this markup, as `"METHOD /path"`. Empty
    /// when no route handler reaches it (a partial nothing renders, or a call
    /// chain the scan could not resolve). Always serialized, empty included:
    /// an unattributed finding is the one a reader most needs to notice.
    pub routes: Vec<String>,
    /// 0-based column of the element, for attribution only.
    #[serde(skip)]
    column: usize,
}

fn serialize_severity<S>(severity: &Severity, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&severity.to_string())
}

/// Aggregate counts by severity, plus route coverage.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)]
pub struct Summary {
    pub critical: usize,
    pub serious: usize,
    pub moderate: usize,
    pub total: usize,
    /// Routes declared in the scanned source. A handler carrying two route
    /// attributes declares two.
    pub routes: usize,
    /// Routes carrying at least one finding.
    pub routes_failing: usize,
    /// Findings no route statically reaches.
    pub unrouted: usize,
}

/// Per-route conformance, one entry per declared route handler.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RouteConformance {
    /// HTTP method from the route attribute (`GET`, `POST`, …).
    pub method: String,
    /// Path **as declared** on the handler. Mount-time prefixes (a `scope`, a
    /// nested router) are applied at runtime and are not resolved here.
    pub path: String,
    /// Handler function name.
    pub handler: String,
    /// Source file, relative to the project root.
    pub file: String,
    /// 1-based line of the handler.
    pub line: usize,
    /// Findings in markup this route statically reaches.
    pub findings: usize,
    /// `"pass"` when the route reaches no finding, else `"fail"`.
    pub status: &'static str,
}

/// Findings rolled up by WCAG success criterion — the conformance view.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct WcagCriterion {
    /// WCAG 2.1 success criterion, e.g. `"1.1.1"`.
    pub criterion: String,
    /// Rule ids that breached it, sorted.
    pub rules: Vec<&'static str>,
    /// Findings breaching it.
    pub findings: usize,
}

/// The full result of a verify run — the JSON conformance manifest.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Report {
    /// Number of `.rs` files scanned.
    pub files_scanned: usize,
    /// Number of `html!` blocks discovered and analyzed.
    pub html_blocks: usize,
    /// Declared routes with their conformance status, sorted by path.
    pub routes: Vec<RouteConformance>,
    /// Findings, sorted by file then line.
    pub findings: Vec<Finding>,
    /// Findings rolled up by WCAG success criterion, sorted by criterion.
    pub wcag: Vec<WcagCriterion>,
    pub summary: Summary,
}

impl Report {
    /// Build a report from a completed scan, sorting findings deterministically.
    fn from_scan(mut scan: Scan) -> Self {
        scan.findings
            .sort_by(|a, b| (a.file.as_str(), a.line).cmp(&(b.file.as_str(), b.line)));
        let graph = RouteGraph::build(&scan.fns);
        let reaching: Vec<Vec<usize>> = scan
            .findings
            .iter()
            .map(|f| graph.routes_reaching(&f.file, (f.line, f.column)))
            .collect();
        for (finding, hit) in scan.findings.iter_mut().zip(&reaching) {
            finding.routes = graph.display_keys(hit);
        }
        let routes = graph.conformance(&reaching);

        let mut summary = Summary::default();
        for finding in &scan.findings {
            match finding.severity {
                Severity::Critical => summary.critical += 1,
                Severity::Serious => summary.serious += 1,
                Severity::Moderate => summary.moderate += 1,
            }
            if finding.routes.is_empty() {
                summary.unrouted += 1;
            }
        }
        summary.total = scan.findings.len();
        summary.routes = routes.len();
        summary.routes_failing = routes.iter().filter(|r| r.findings > 0).count();

        Self {
            files_scanned: scan.files_scanned,
            html_blocks: scan.html_blocks,
            routes,
            wcag: roll_up_wcag(&scan.findings),
            findings: scan.findings,
            summary,
        }
    }

    /// Process exit code. Non-zero when any finding meets the failure
    /// threshold — Serious by default, lowered to Moderate under `--strict`.
    #[must_use]
    pub fn exit_code(&self, strict: bool) -> i32 {
        let threshold = if strict {
            Severity::Moderate
        } else {
            Severity::Serious
        };
        i32::from(self.findings.iter().any(|f| f.severity >= threshold))
    }
}

// ── Scanner ────────────────────────────────────────────────────────────────

/// Accumulator threaded through the source scan.
#[derive(Debug, Default)]
pub struct Scan {
    pub findings: Vec<Finding>,
    files_scanned: usize,
    html_blocks: usize,
    /// Every function declaration seen, for route attribution.
    fns: Vec<FnDecl>,
}

impl Scan {
    fn push(&mut self, rule: Rule, element: &str, line: usize, column: usize, file: &str) {
        self.findings.push(Finding {
            file: file.to_owned(),
            line,
            element: element.to_owned(),
            rule_id: rule.rule_id(),
            wcag: rule.wcag(),
            severity: Severity::Serious,
            message: rule.message(),
            hint: rule.hint(),
            routes: Vec::new(),
            column,
        });
    }
}

/// [`scan_project_with`], with the default features of each crate only.
#[cfg(test)]
pub fn scan_project(root: &Path) -> std::io::Result<Scan> {
    scan_project_with(root, &CargoFeatures::default())
}

/// Walk `root` recursively and scan every `.rs` file for raw-`html!` markup.
///
/// The scan ROOT read is fatal: a misspelled/unreadable/nonexistent path must
/// fail hard, not silently yield zero findings — a zero-findings run prints
/// PASS and would let a CI typo disable the whole audit. `std::fs::read_dir`
/// surfaces all three failure modes (path absent, path is not a directory, or
/// the directory is unreadable). A genuinely empty-but-readable directory reads
/// fine here and legitimately produces an empty file list (zero findings, exit
/// 0). Nested subdir read errors *during recursion* remain best-effort
/// (swallowed by [`collect_rs_files`]), mirroring `autumn i18n check`.
///
/// `cfg(feature = "…")` reads the default features of each crate plus
/// `features`.
pub fn scan_project_with(root: &Path, features: &CargoFeatures) -> std::io::Result<Scan> {
    std::fs::read_dir(root)?;
    let mut crates = CrateFeatures::new(features);
    let mut scan = Scan::default();
    let mut files = Vec::new();
    collect_rs_files(root, &mut files);
    files.sort();
    for path in files {
        let Ok(src) = std::fs::read_to_string(&path) else {
            continue;
        };
        let rel = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .to_string_lossy()
            .into_owned();
        scan_source_with(&src, &rel, crates.for_file(&path), &mut scan);
        scan.files_scanned += 1;
    }
    Ok(scan)
}

fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        // Never follow symlinks: a symlinked directory cycle would otherwise
        // recurse forever and hang this CI tool.
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if file_type.is_symlink() {
            continue;
        }
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if file_type.is_dir() {
            // Skip build output, dot-dirs, and any `tests` directory. Test code
            // (integration tests, system-test scaffolding, committed fixtures)
            // is not shipped product markup, so a raw-`html!` defect there is not
            // a product accessibility bug (issue #1934). The skip is scan-root
            // RELATIVE: the a11y-verify integration test passes a fixture dir as
            // the scan root itself, so no `tests` path component exists below
            // that root and the fixture is still scanned/flagged there.
            if name == "target" || name == "tests" || name.starts_with('.') {
                continue;
            }
            collect_rs_files(&path, out);
        } else if file_type.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

/// The features that `cfg(feature = "…")` reads as on in each crate of a scan.
///
/// A call edge or an item under a `cfg` that is false for these features is
/// dropped (issue #2666). A predicate the scan cannot decide keeps it.
struct CrateFeatures<'a> {
    selection: &'a CargoFeatures,
    /// The nearest `Cargo.toml` of each directory.
    manifest_of: std::collections::HashMap<PathBuf, Option<PathBuf>>,
    /// The enabled features of each manifest.
    by_manifest: std::collections::HashMap<PathBuf, Option<BTreeSet<String>>>,
}

impl<'a> CrateFeatures<'a> {
    fn new(selection: &'a CargoFeatures) -> Self {
        Self {
            selection,
            manifest_of: std::collections::HashMap::new(),
            by_manifest: std::collections::HashMap::new(),
        }
    }

    /// The enabled features of the crate that holds `file`: the crate of the
    /// nearest `Cargo.toml`, as Cargo finds it. `None` when there is no such
    /// manifest, or it has no package: the scan then decides no feature
    /// predicate.
    fn for_file(&mut self, file: &Path) -> Option<&BTreeSet<String>> {
        let dir = std::path::absolute(file).ok()?.parent()?.to_path_buf();
        let manifest = self
            .manifest_of
            .entry(dir)
            .or_insert_with_key(|dir| {
                dir.ancestors()
                    .map(|dir| dir.join("Cargo.toml"))
                    .find(|path| path.is_file())
            })
            .clone()?;
        let selection = self.selection;
        self.by_manifest
            .entry(manifest)
            .or_insert_with_key(|path| {
                let text = std::fs::read_to_string(path).ok()?;
                enabled_features(&text, selection)
            })
            .as_ref()
    }
}

/// The features that `selection` turns on for the package in `manifest`.
/// `None` for a manifest with no `[package]` (a virtual workspace).
///
/// `--features` names apply to every crate of the scan.
fn enabled_features(manifest: &str, selection: &CargoFeatures) -> Option<BTreeSet<String>> {
    let table = toml::from_str::<toml::Table>(manifest).ok()?;
    table.get("package")?;
    let mut requested: Vec<String> = selection
        .features
        .iter()
        .flat_map(|entry| entry.split([',', ' ']))
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .collect();
    if selection.all {
        if let Some(features) = table.get("features").and_then(toml::Value::as_table) {
            requested.extend(features.keys().cloned());
        }
        // An optional dependency is also a feature of the same name, unless
        // a `dep:name` entry suppresses that implicit feature.
        let features = table.get("features").and_then(toml::Value::as_table);
        let targets = table
            .get("target")
            .and_then(toml::Value::as_table)
            .into_iter()
            .flat_map(|targets| targets.values());
        let optional = std::iter::once(table.get("dependencies"))
            .chain(targets.map(|target| target.get("dependencies")))
            .filter_map(|deps| deps.and_then(toml::Value::as_table))
            .flat_map(|deps| deps.iter())
            .filter(|(_, dep)| dep.get("optional").and_then(toml::Value::as_bool) == Some(true))
            .filter(|(name, _)| !crate::edge_scan::implicit_feature_is_suppressed(features, name))
            .map(|(name, _)| name.clone());
        requested.extend(optional);
    }
    let requested: Vec<&str> = requested.iter().map(String::as_str).collect();
    // `true`: an optional dependency of any target table counts. With `false`,
    // the edge scan keeps only the edge capsule's targets.
    Some(crate::edge_scan::enabled_features_with_defaults(
        manifest,
        &requested,
        true,
        !selection.no_default,
    ))
}

/// Tokenize one source string and analyze every `html!` block within it. No
/// `cfg` predicate is decided.
#[cfg(test)]
fn scan_source(src: &str, file: &str, scan: &mut Scan) {
    scan_source_with(src, file, None, scan);
}

/// Tokenize one source string and analyze every `html!` block within it,
/// with `cfg(feature = "…")` read against `features`.
fn scan_source_with(src: &str, file: &str, features: Option<&BTreeSet<String>>, scan: &mut Scan) {
    let Ok(stream) = TokenStream::from_str(src) else {
        return;
    };
    find_html_blocks(&stream, file, scan);
    let trees: Vec<TokenTree> = stream.into_iter().collect();
    collect_fns(&trees, file, features, &mut scan.fns);
}

/// Recursively walk a token stream, analyzing each `html! { … }` macro body and
/// descending into every group so nested `html!` invocations (e.g. spliced into
/// another block) are found too.
fn find_html_blocks(stream: &TokenStream, file: &str, scan: &mut Scan) {
    let trees: Vec<TokenTree> = stream.clone().into_iter().collect();
    let mut i = 0;
    while i < trees.len() {
        // A `#[cfg(test)]`-annotated item (`mod tests { … }`, a test `fn`) is
        // test-only scaffolding, not shipped product markup — an inline
        // `html!` defect inside it is intentional test data, not a product
        // accessibility bug (issue #1934, the #1930 `form.rs` case). Skip the
        // whole item without descending into its body.
        if is_cfg_test_attr(&trees, i) {
            i = skip_cfg_test_item(&trees, i + 2);
            continue;
        }
        if let TokenTree::Ident(ident) = &trees[i]
            && *ident == "html"
            && matches!(trees.get(i + 1), Some(TokenTree::Punct(p)) if p.as_char() == '!')
            && let Some(TokenTree::Group(group)) = trees.get(i + 2)
        {
            let body: Vec<TokenTree> = group.stream().into_iter().collect();
            // Only maud/autumn `html!` markup is analyzed. A project may define a
            // DIFFERENT `html!` (e.g. a Yew/JSX island using `<tag>…</tag>`
            // syntax); handing such a body to the maud parser would strip the
            // angle brackets and misread `<button></button>` as an empty maud
            // `button`, a false `button-name`. maud never uses JSX angle-bracket
            // tags, so a body that does is a different macro — skip it entirely.
            if looks_like_jsx(&body) {
                i += 3;
                continue;
            }
            let nodes = parse_nodes(&body);
            scan.html_blocks += 1;
            analyze_block(&nodes, file, scan);
            // Descend into the body for nested `html!` splices.
            find_html_blocks(&group.stream(), file, scan);
            i += 3;
            continue;
        }
        if let TokenTree::Group(group) = &trees[i] {
            find_html_blocks(&group.stream(), file, scan);
        }
        i += 1;
    }
}

/// Whether `trees[i]` begins a `#[cfg(test)]` outer attribute — a `#` punct
/// immediately followed by a `[cfg(test)]` bracket group. Such an attribute
/// precedes a test-only item whose body is scaffolding the scanner must not
/// descend into (issue #1934). Matching is deliberately precise (`cfg` then a
/// parenthesized single `test` ident): it never fires on `#[cfg(not(test))]`
/// (production code) or `#[cfg(feature = "…")]`, so it can only ever exclude a
/// genuine test item.
fn is_cfg_test_attr(trees: &[TokenTree], i: usize) -> bool {
    let Some(TokenTree::Punct(p)) = trees.get(i) else {
        return false;
    };
    if p.as_char() != '#' {
        return false;
    }
    let Some(TokenTree::Group(g)) = trees.get(i + 1) else {
        return false;
    };
    if g.delimiter() != Delimiter::Bracket {
        return false;
    }
    let inner: Vec<TokenTree> = g.stream().into_iter().collect();
    matches!(inner.first(), Some(TokenTree::Ident(id)) if *id == "cfg")
        && matches!(
            inner.get(1),
            Some(TokenTree::Group(paren))
                if paren.delimiter() == Delimiter::Parenthesis
                    && is_single_test_ident(&paren.stream())
        )
}

/// Whether a token stream is exactly the single ident `test` (the body of a
/// `cfg(test)` predicate).
fn is_single_test_ident(stream: &TokenStream) -> bool {
    let trees: Vec<TokenTree> = stream.clone().into_iter().collect();
    trees.len() == 1 && matches!(&trees[0], TokenTree::Ident(id) if *id == "test")
}

/// Advance past a `#[cfg(test)]`-annotated item without descending into its
/// body, starting at `start` (the token just past the attribute's bracket
/// group). The item body is the first top-level brace group (`mod tests { … }`,
/// `fn … { … }`); a body-less item (`#[cfg(test)] use …;`) ends at its `;`.
/// Not descending into that brace is the whole point — any `html!` markup
/// inside is intentionally excluded from the scan.
fn skip_cfg_test_item(trees: &[TokenTree], start: usize) -> usize {
    let mut i = start;
    while i < trees.len() {
        match &trees[i] {
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => return i + 1,
            TokenTree::Punct(p) if p.as_char() == ';' => return i + 1,
            _ => i += 1,
        }
    }
    i
}

/// Whether an `html!` body is JSX/Yew-style angle-bracket markup rather than
/// maud. Detection keys ONLY on token pairs that maud never emits but that every
/// JSX/Yew element carries: a closing tag `</…>` (a `<` immediately followed by
/// `/`) or a self-closing tag `<…/>` (a `/` immediately followed by `>`). maud
/// markup uses `{}`/`;`, never angle-bracket tags, so neither pair can appear in
/// valid maud. A bare `<`/`>` is NOT treated as JSX: it is an ordinary Rust
/// comparison inside a control head (`@if count < limit { … }`, `@if a > b { … }`),
/// and misreading it as JSX would skip — and thus stop analyzing — the entire
/// `html!` body. A JSX body is skipped rather than parsed as maud, which would
/// drop the angle brackets and misread `<button></button>` as an empty maud
/// `button` (a false `button-name`). When in doubt we do NOT classify as JSX: a
/// missed check on non-maud markup is acceptable, disabling the scanner on valid
/// maud is not.
fn looks_like_jsx(trees: &[TokenTree]) -> bool {
    for (idx, tree) in trees.iter().enumerate() {
        let TokenTree::Punct(p) = tree else {
            continue;
        };
        let next_is =
            |c: char| matches!(trees.get(idx + 1), Some(TokenTree::Punct(q)) if q.as_char() == c);
        match p.as_char() {
            // `</…>` — a closing tag. maud never emits `<` followed by `/`.
            '<' if next_is('/') => return true,
            // `<…/>` — a self-closing tag. maud never emits `/` followed by `>`.
            '/' if next_is('>') => return true,
            _ => {}
        }
    }
    false
}

// ── Route attribution ──────────────────────────────────────────────────────
//
// A finding is only actionable if the developer knows which page it breaks.
// Autumn declares routes with attribute macros on the handler
// (`#[get("/settings")] async fn settings()`), so the routes a piece of markup
// serves can be read from the same token stream the scanner already walks: index
// every `fn`, record the free functions each one calls, then walk out from each
// handler to the markup it reaches.
//
// The walk is deliberately conservative, like the scanner itself. It resolves a
// call only when the called name is defined EXACTLY once in the scope the call
// can see (the helpers at the top of the caller's body, then every free item);
// two functions sharing a name cannot be told apart from tokens, and guessing
// would key a defect to a route that never renders it. Method calls
// (`page.sidebar()`) are not resolved at all. Attribution is therefore a
// best-effort lower bound: an unattributed finding is still a finding.

/// Route declared by an attribute macro on a handler.
#[derive(Debug, Clone, PartialEq, Eq)]
struct RouteDecl {
    method: &'static str,
    /// Path as written in the attribute; mount-time prefixes are not resolved.
    path: String,
}

/// A function declaration and the call edges leaving it.
#[derive(Debug)]
struct FnDecl {
    name: String,
    file: String,
    /// `(line, column)` of the `fn` keyword and of the body's closing brace.
    start: (usize, usize),
    end: (usize, usize),
    /// Names of free functions called in the body, unresolved.
    calls: BTreeSet<String>,
    /// Route attributes on this function, if any.
    routes: Vec<RouteDecl>,
    /// Whether a bare `name()` anywhere can reach this function. A nested item
    /// is visible only inside its enclosing block (see `owner`), and an
    /// associated function is reached through a receiver or a type-qualified
    /// path, which this scan does not resolve. So neither is a free target.
    callable: bool,
    /// The function whose body declares this one at its top level. A bare call
    /// in that body (or in a sibling it declares) can reach this one.
    owner: Option<usize>,
    /// The outermost function whose body holds this one, at any depth.
    top: Option<usize>,
}

/// `(line, column)` of the first and the last token of a range.
type Span = ((usize, usize), (usize, usize));

/// The span of `trees[from..to]`.
fn span_of(trees: &[TokenTree], from: usize, to: usize) -> Span {
    let start = trees[from].span().start();
    let end = trees[to.max(from + 1) - 1].span().end();
    ((start.line, start.column), (end.line, end.column))
}

impl FnDecl {
    /// A range that is not in the build: an item or a statement under a `cfg`
    /// that is off. It holds no calls and no routes, and no call reaches it,
    /// so markup inside it has no route.
    fn excluded(file: &str, (start, end): Span) -> Self {
        Self {
            name: String::new(),
            file: file.to_owned(),
            start,
            end,
            calls: BTreeSet::new(),
            routes: Vec::new(),
            callable: false,
            owner: None,
            top: None,
        }
    }
}

/// Route attribute macros that serve markup. `#[static_get]` is one of them —
/// it pre-renders a page, so an alt-less image in it is as broken as in any
/// other. `#[ws]` is not: a WebSocket upgrade serves no document.
const ROUTE_ATTRS: [(&str, &str); 6] = [
    ("get", "GET"),
    ("post", "POST"),
    ("put", "PUT"),
    ("patch", "PATCH"),
    ("delete", "DELETE"),
    ("static_get", "GET"),
];

/// Rust keywords that can precede a parenthesized group without being a call.
const CALL_KEYWORDS: [&str; 6] = ["if", "while", "match", "return", "for", "in"];

/// Item keywords whose following identifier is a declaration, not a call.
const DECL_KEYWORDS: [&str; 6] = ["fn", "struct", "enum", "union", "trait", "mod"];

/// Index every function in `trees`, recording its span, call edges, and any
/// route attributes, appending to `out`.
///
/// `#[cfg(test)]` items are skipped wholesale, mirroring the scanner: test
/// scaffolding is neither a route nor a rendering path, and indexing it would
/// only create name collisions that suppress real attribution.
fn collect_fns(
    trees: &[TokenTree],
    file: &str,
    features: Option<&BTreeSet<String>>,
    out: &mut Vec<FnDecl>,
) {
    let level = Level {
        file,
        features,
        callable: true,
        owner: None,
        top: None,
    };
    collect_fns_in(trees, &level, out);
}

/// Where [`collect_fns_in`] is in the token tree.
#[derive(Clone, Copy)]
struct Level<'a> {
    file: &'a str,
    features: Option<&'a BTreeSet<String>>,
    /// Whether items at this level are reachable by a bare name. Free items in
    /// a module are; items inside a function body or an `impl`/`trait` block
    /// are not.
    callable: bool,
    /// The function whose body is this level, if this is the top of a body.
    owner: Option<usize>,
    /// The outermost function whose body holds this level.
    top: Option<usize>,
}

/// [`collect_fns`] at one level of the token tree.
fn collect_fns_in(trees: &[TokenTree], level: &Level<'_>, out: &mut Vec<FnDecl>) {
    let Level {
        file,
        features,
        callable,
        owner,
        top,
    } = *level;
    let mut pending: Vec<RouteDecl> = Vec::new();
    // Set when an `impl`/`trait` head is seen, so its block is descended as
    // associated items.
    let mut assoc_block = false;
    let mut i = 0;
    while i < trees.len() {
        if let Some(next) = skip_unindexed_item(trees, i, features) {
            out.push(FnDecl::excluded(file, span_of(trees, i, next)));
            i = next;
            pending.clear();
            continue;
        }
        if let Some((route, next)) = read_attr(trees, i) {
            pending.extend(route);
            i = next;
            continue;
        }
        if let TokenTree::Ident(ident) = &trees[i] {
            if *ident == "fn"
                && let Some(TokenTree::Ident(name)) = trees.get(i + 1)
                && let Some(body_at) = find_fn_body(trees, i + 2)
                && let TokenTree::Group(body) = &trees[body_at]
            {
                let inner: Vec<TokenTree> = body.stream().into_iter().collect();
                let (calls, excluded) = fn_calls(&trees[i + 2..body_at], &inner, features);
                let start = trees[i].span().start();
                let end = body.span().end();
                out.push(FnDecl {
                    name: name.to_string(),
                    file: file.to_owned(),
                    start: (start.line, start.column),
                    end: (end.line, end.column),
                    calls,
                    routes: std::mem::take(&mut pending),
                    callable,
                    owner,
                    top,
                });
                let index = out.len() - 1;
                out.extend(
                    excluded
                        .into_iter()
                        .map(|span| FnDecl::excluded(file, span)),
                );
                let body = Level {
                    callable: false,
                    owner: Some(index),
                    top: top.or(Some(index)),
                    ..*level
                };
                collect_fns_in(&inner, &body, out);
                i = body_at + 1;
                continue;
            }
            // An attribute binds to the next item. If that item is not a
            // function, the route attributes seen so far are not ours.
            if matches!(ident.to_string().as_str(), "impl" | "trait") {
                assoc_block = true;
            }
            if !matches!(
                ident.to_string().as_str(),
                "pub" | "async" | "unsafe" | "extern"
            ) {
                pending.clear();
            }
        }
        match &trees[i] {
            // A brace group reached here closes an item that was not a
            // function (an `extern "C" { … }` block, a `struct` body), so a
            // route attribute seen before it was not ours.
            TokenTree::Group(group) => {
                let brace = group.delimiter() == Delimiter::Brace;
                if brace {
                    pending.clear();
                }
                let inner: Vec<TokenTree> = group.stream().into_iter().collect();
                let nested = Level {
                    callable: callable && !(brace && assoc_block),
                    owner: None,
                    ..*level
                };
                collect_fns_in(&inner, &nested, out);
                if brace {
                    assoc_block = false;
                }
            }
            // Likewise a literal: `extern "C"` leads with one.
            TokenTree::Literal(_) => pending.clear(),
            _ => {}
        }
        i += 1;
    }
}

/// The call edges of a function, and the ranges of its body that a `cfg`
/// takes out of the build. `head` is the tokens between the name and the
/// body; `body` is the body.
fn fn_calls(
    head: &[TokenTree],
    body: &[TokenTree],
    features: Option<&BTreeSet<String>>,
) -> (BTreeSet<String>, Vec<Span>) {
    let mut calls = BTreeSet::new();
    let mut excluded = Vec::new();
    collect_calls(body, features, &mut calls, &mut excluded);
    // A name bound in this function — a parameter, a local, a closure
    // argument — shadows any free function that shares it, so calling it does
    // not reach that function.
    let mut bound = BTreeSet::new();
    // The parameter list is the first parenthesized group after the name; a
    // return type or a `where` clause can sit between it and the body.
    if let Some(params) = head.iter().find_map(|tree| match tree {
        TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis => Some(g),
        _ => None,
    }) {
        collect_idents(&params.stream().into_iter().collect::<Vec<_>>(), &mut bound);
    }
    collect_bindings(body, &mut bound);
    calls.retain(|call| !bound.contains(call));
    (calls, excluded)
}

/// The index past an item at `trees[i]` that [`collect_fns_in`] does not
/// index, or `None` when the item is indexed.
///
/// - A `#[cfg(test)]` item: test scaffolding is neither a route nor a
///   rendering path.
/// - An item under a `cfg` that is off for `features`: it is not in the build.
/// - A `macro_rules!` body: it holds templates, not definitions. Indexing the
///   `fn` inside one would make a real helper of the same name look defined
///   twice, and every call edge to it would be dropped.
fn skip_unindexed_item(
    trees: &[TokenTree],
    i: usize,
    features: Option<&BTreeSet<String>>,
) -> Option<usize> {
    // A gated item can be a match arm or a field inside a body, so it ends
    // where `skip_gated` says, not at the next brace group.
    if matches!(
        (trees.get(i), trees.get(i + 1)),
        (Some(TokenTree::Punct(p)), Some(TokenTree::Group(attr)))
            if p.as_char() == '#'
                && attr.delimiter() == Delimiter::Bracket
                && !is_cfg_test_attr(trees, i)
                && cfg_is_off(attr, features)
    ) {
        return Some(skip_gated(trees, i + 2));
    }
    let off = is_cfg_test_attr(trees, i)
        || (matches!(&trees[i], TokenTree::Ident(ident) if *ident == "macro_rules")
            && matches!(trees.get(i + 1), Some(TokenTree::Punct(p)) if p.as_char() == '!'));
    off.then(|| skip_cfg_test_item(trees, i + 2))
}

/// Read the attribute starting at `trees[i]` (a `#` followed by a bracket
/// group), returning any route it declares and the index just past it.
fn read_attr(trees: &[TokenTree], i: usize) -> Option<(Option<RouteDecl>, usize)> {
    let TokenTree::Punct(p) = trees.get(i)? else {
        return None;
    };
    if p.as_char() != '#' {
        return None;
    }
    let TokenTree::Group(group) = trees.get(i + 1)? else {
        return None;
    };
    if group.delimiter() != Delimiter::Bracket {
        return None;
    }
    Some((route_from_attr(&group.stream()), i + 2))
}

/// Parse a route attribute body (`get("/settings", …)`, or a path-qualified
/// `autumn_web::get("/settings")`) into a [`RouteDecl`].
fn route_from_attr(stream: &TokenStream) -> Option<RouteDecl> {
    let trees: Vec<TokenTree> = stream.clone().into_iter().collect();
    // The macro name is the last ident before the argument group.
    let group_at = trees.iter().position(
        |t| matches!(t, TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis),
    )?;
    let TokenTree::Ident(name) = trees.get(group_at.checked_sub(1)?)? else {
        return None;
    };
    let name = name.to_string();
    let method = ROUTE_ATTRS
        .iter()
        .find(|(attr, _)| *attr == name)
        .map(|(_, method)| *method)?;
    let TokenTree::Group(args) = &trees[group_at] else {
        return None;
    };
    // The path is the first POSITIONAL string literal: `#[get(crate = "…",
    // "/a")]` is accepted by the route macros, so a literal that follows `=` is
    // a named argument's value, not the path.
    let arg_trees: Vec<TokenTree> = args.stream().into_iter().collect();
    let path = arg_trees.iter().enumerate().find_map(|(at, tree)| {
        let TokenTree::Literal(lit) = tree else {
            return None;
        };
        let named = matches!(
            at.checked_sub(1).and_then(|prev| arg_trees.get(prev)),
            Some(TokenTree::Punct(p)) if p.as_char() == '='
        );
        if named {
            None
        } else {
            string_literal_value(lit)
        }
    })?;
    Some(RouteDecl { method, path })
}

/// Index of the brace group holding a function body, searching from `start`
/// (just past the function name). Returns `None` for a body-less declaration
/// (a trait method signature), whose `;` is reached first.
fn find_fn_body(trees: &[TokenTree], start: usize) -> Option<usize> {
    for (offset, tree) in trees.iter().enumerate().skip(start) {
        match tree {
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => return Some(offset),
            TokenTree::Punct(p) if p.as_char() == ';' => return None,
            _ => {}
        }
    }
    None
}

/// Collect the names of free functions called anywhere in `trees`.
///
/// A call is an identifier immediately followed by a parenthesized group, which
/// already excludes a macro (`html!(…)`, whose `!` sits between the two). Four
/// shapes that match that pattern are still not calls this scan can resolve,
/// and each is skipped rather than guessed at:
///
/// - `page.sidebar()` — a method on a receiver whose type is unknown.
/// - `Widget::new()` — an associated function on a type. Rust names types in
///   `UpperCamelCase` and modules in `snake_case`, so an upper-case qualifier
///   marks the call as type-qualified; `views::sidebar()` stays resolvable.
/// - `fn helper(…)` / `struct Row(…)` — a declaration, not a call.
/// - a nested `fn` item — its body belongs to that function, which is indexed
///   in its own right; folding its calls into the enclosing one would attribute
///   markup to a function that never calls it.
///
/// Attribute bodies are skipped for the same reason: `#[cfg(test)]` would
/// otherwise register a call to `cfg`. A statement, match arm or field under a
/// `cfg` that is false for `features` is skipped whole.
///
/// Two more shapes are calls (issue #2666):
///
/// - `sidebar::<Html>()` — a turbofish sits between the name and the group.
/// - `rows.map(render_row)` — a function passed by name. An argument that is
///   only a path is recorded like a call; [`collect_bindings`] removes a name
///   that the function binds itself.
fn collect_calls(
    trees: &[TokenTree],
    features: Option<&BTreeSet<String>>,
    out: &mut BTreeSet<String>,
    excluded: &mut Vec<Span>,
) {
    let mut i = 0;
    while i < trees.len() {
        // Skip a nested `fn NAME … { … }` item whole, name included.
        if let TokenTree::Ident(ident) = &trees[i]
            && *ident == "fn"
            && matches!(trees.get(i + 1), Some(TokenTree::Ident(_)))
        {
            i = find_fn_body(trees, i + 2).map_or(trees.len(), |body| body + 1);
            continue;
        }
        // Skip an attribute (`#` + bracket group) without descending into it.
        if let TokenTree::Punct(p) = &trees[i]
            && p.as_char() == '#'
            && let Some(TokenTree::Group(attr)) = trees.get(i + 1)
            && attr.delimiter() == Delimiter::Bracket
        {
            i = if cfg_is_off(attr, features) {
                let end = skip_gated(trees, i + 2);
                excluded.push(span_of(trees, i, end));
                end
            } else {
                i + 2
            };
            continue;
        }
        if let TokenTree::Ident(ident) = &trees[i] {
            let name = ident.to_string();
            let args_at = turbofish_end(trees, i + 1).map_or(i + 1, |end| end + 1);
            if is_paren(trees.get(args_at))
                && is_resolvable_call(trees, i)
                && !CALL_KEYWORDS.contains(&name.as_str())
            {
                out.insert(call_key(trees, i, &name));
            }
            // The arguments of a call or a method call: a function can be
            // passed by name. A macro (`format!(…)`) has a `!` here instead.
            if let Some(TokenTree::Group(args)) = trees.get(args_at)
                && args.delimiter() == Delimiter::Parenthesis
                && !NOT_CALL_HEADS.contains(&name.as_str())
            {
                collect_paths_passed(args, out);
            }
            if args_at > i + 1 {
                // Past the turbofish: its type arguments hold no calls.
                i = args_at;
                continue;
            }
        }
        if let TokenTree::Group(group) = &trees[i] {
            let inner: Vec<TokenTree> = group.stream().into_iter().collect();
            collect_calls(&inner, features, out, excluded);
        }
        i += 1;
    }
}

/// The key of a call to `name` at `trees[i]`: the bare name, or `::name` for
/// a path (`views::sidebar`). A path names a free item, so neither a local
/// helper nor a local binding of the same name can shadow it.
fn call_key(trees: &[TokenTree], i: usize, name: &str) -> String {
    let path = i
        .checked_sub(1)
        .is_some_and(|prev| matches!(&trees[prev], TokenTree::Punct(p) if p.as_char() == ':'));
    if path {
        format!("::{name}")
    } else {
        name.to_owned()
    }
}

/// Keywords that can precede a parenthesized group that is not an argument
/// list: a condition, a pattern, a returned tuple.
const NOT_CALL_HEADS: [&str; 9] = [
    "if", "while", "match", "return", "for", "in", "let", "fn", "struct",
];

/// Whether `tree` is a parenthesized group.
fn is_paren(tree: Option<&TokenTree>) -> bool {
    matches!(tree, Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
}

/// The index of the `>` that closes a turbofish `::<…>` starting at
/// `trees[start]`, or `None` when no turbofish starts there.
fn turbofish_end(trees: &[TokenTree], start: usize) -> Option<usize> {
    let punct =
        |at: usize, c: char| matches!(trees.get(at), Some(TokenTree::Punct(p)) if p.as_char() == c);
    if !(punct(start, ':') && punct(start + 1, ':') && punct(start + 2, '<')) {
        return None;
    }
    let mut depth = 0usize;
    for (at, tree) in trees.iter().enumerate().skip(start + 2) {
        let TokenTree::Punct(p) = tree else {
            continue;
        };
        match p.as_char() {
            '<' => depth += 1,
            // The `>` of a `->` in `Fn() -> T` closes nothing.
            '>' if !matches!(trees.get(at - 1), Some(TokenTree::Punct(q))
                    if q.as_char() == '-' && q.spacing() == proc_macro2::Spacing::Joint) =>
            {
                depth -= 1;
                if depth == 0 {
                    return Some(at);
                }
            }
            _ => {}
        }
    }
    None
}

/// Record each argument in `args` that is only a path to a free function:
/// `render_row`, or `views::render_row`. A type-qualified path
/// (`Widget::render`) is skipped, as for a call.
fn collect_paths_passed(args: &proc_macro2::Group, out: &mut BTreeSet<String>) {
    let trees: Vec<TokenTree> = args.stream().into_iter().collect();
    for arg in trees.split(|t| matches!(t, TokenTree::Punct(p) if p.as_char() == ',')) {
        // A path alternates an ident and a `::` (two `:` puncts).
        let is_path = !arg.is_empty()
            && arg.len() % 3 == 1
            && arg.iter().enumerate().all(|(at, tree)| match at % 3 {
                0 => matches!(tree, TokenTree::Ident(_)),
                _ => matches!(tree, TokenTree::Punct(p) if p.as_char() == ':'),
            });
        if !is_path {
            continue;
        }
        let last = arg.len() - 1;
        if last == 0 || qualifier_is_module(arg, last) {
            out.insert(call_key(arg, last, &arg[last].to_string()));
        }
    }
}

/// Whether the attribute body `attr` (`cfg(…)`) is false for `features`. A
/// predicate the scan cannot decide, or no known features, is not false.
fn cfg_is_off(attr: &proc_macro2::Group, features: Option<&BTreeSet<String>>) -> bool {
    let Some(features) = features else {
        return false;
    };
    // Most attributes are not a `cfg` (a doc comment, a derive): skip the parse.
    if !matches!(attr.stream().into_iter().next(), Some(TokenTree::Ident(id)) if id == "cfg") {
        return false;
    }
    syn::parse2::<syn::Meta>(attr.stream())
        .is_ok_and(|meta| crate::edge_scan::eval_cfg_meta(&meta, features) == Some(false))
}

/// Skip the statement, match arm, field or item after an attribute, from
/// `start`.
///
/// - An `fn` item ends after its body.
/// - A match arm (a `=>` comes before any `;`) ends after its body: a block,
///   or an expression up to its `,`. Its pattern (`A | B`, `V { a } if …`)
///   does not matter.
/// - Anything else ends as [`skip_expr`] says.
fn skip_gated(trees: &[TokenTree], start: usize) -> usize {
    let mut i = start;
    // Skip the other attributes and qualifiers of the item.
    while let Some(tree) = trees.get(i) {
        match tree {
            TokenTree::Punct(p) if p.as_char() == '#' => i += 2,
            TokenTree::Ident(id)
                if ["pub", "async", "const", "unsafe"]
                    .iter()
                    .any(|kw| id == kw) =>
            {
                i += 1;
            }
            // `pub(crate)`.
            TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis && i > start => i += 1,
            _ => break,
        }
    }
    if matches!(trees.get(i), Some(TokenTree::Ident(id)) if *id == "fn") {
        return find_fn_body(trees, i + 1).map_or(trees.len(), |body| body + 1);
    }
    if let Some(arrow) = arm_arrow(trees, i) {
        let body = arrow + 2;
        // A block body ends the arm, unless a postfix expression goes on
        // past it (`{ rows }.into_iter()`, `{ x }?`).
        let block_ends_arm = matches!(trees.get(body), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace)
            && !matches!(trees.get(body + 1), Some(TokenTree::Punct(p)) if p.as_char() == '.' || p.as_char() == '?');
        if block_ends_arm {
            let end = body + 1;
            return end
                + usize::from(
                    matches!(trees.get(end), Some(TokenTree::Punct(p)) if p.as_char() == ','),
                );
        }
        return skip_expr(trees, body, false);
    }
    // A `<` opens generics after these keywords; elsewhere it can be a `<`
    // comparison.
    let has_generics = matches!(trees.get(i), Some(TokenTree::Ident(id))
        if ["let", "impl", "struct", "enum", "union", "trait", "type"].iter().any(|kw| id == kw));
    skip_expr(trees, i, has_generics)
}

/// The index of the `=>` of a match arm that starts at `trees[start]`: the
/// first `=>` at this level before any `;`. A statement or a field has none.
fn arm_arrow(trees: &[TokenTree], start: usize) -> Option<usize> {
    for at in start..trees.len() {
        let TokenTree::Punct(p) = &trees[at] else {
            continue;
        };
        match p.as_char() {
            ';' => return None,
            '=' if p.spacing() == proc_macro2::Spacing::Joint
                && matches!(trees.get(at + 1), Some(TokenTree::Punct(q)) if q.as_char() == '>') =>
            {
                return Some(at);
            }
            _ => {}
        }
    }
    None
}

/// The index past a statement, a field or an arm body that starts at
/// `trees[start]`.
///
/// It ends after a `;` or `,`, or after a brace group that closes it. A `,`
/// does not end it inside generics (`has_generics`, or a turbofish `::<`) or
/// a closure argument list. A brace group that an expression goes on past
/// (`{ … } else`, `S { .. } = …`, `unsafe { … } + x`) does not end it either.
fn skip_expr(trees: &[TokenTree], start: usize, has_generics: bool) -> usize {
    let punct = |at: usize| match trees.get(at) {
        Some(TokenTree::Punct(p)) => Some(p.as_char()),
        _ => None,
    };
    let mut i = start;
    let mut angles = 0usize;
    let mut in_closure_args = false;
    while let Some(tree) = trees.get(i) {
        let at = i;
        i += 1;
        match tree {
            TokenTree::Punct(p) => match p.as_char() {
                ';' => break,
                ',' if angles == 0 && !in_closure_args => break,
                '<' if has_generics || (at >= 1 && punct(at - 1) == Some(':')) => angles += 1,
                '>' if angles > 0 && (at == 0 || punct(at - 1) != Some('-')) => angles -= 1,
                // A closure list opens where an expression starts; a `|` after
                // an operand is a bitwise or.
                '|' if angles == 0
                    && (in_closure_args
                        || at == start
                        || matches!(&trees[at - 1], TokenTree::Punct(_))
                        || matches!(&trees[at - 1], TokenTree::Ident(id) if id == "move")) =>
                {
                    in_closure_args = !in_closure_args;
                }
                _ => {}
            },
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => {
                let goes_on = match trees.get(i) {
                    Some(TokenTree::Punct(p)) => ![';', ',', '#'].contains(&p.as_char()),
                    Some(TokenTree::Ident(id)) => ["else", "in", "as"].iter().any(|kw| id == kw),
                    Some(TokenTree::Group(_) | TokenTree::Literal(_)) | None => false,
                };
                if !goes_on {
                    if matches!(punct(i), Some(';' | ',')) {
                        i += 1;
                    }
                    break;
                }
            }
            _ => {}
        }
    }
    i
}

/// Every identifier in `trees`, at any depth.
///
/// Used on a parameter list, where the binding names are mixed with type names.
/// Collecting both over-approximates what is shadowed, which only ever drops a
/// call edge — the safe direction — and type names are `UpperCamelCase` while
/// function names are `snake_case`, so they rarely collide in practice.
fn collect_idents(trees: &[TokenTree], out: &mut BTreeSet<String>) {
    for tree in trees {
        match tree {
            TokenTree::Ident(ident) => {
                out.insert(ident.to_string());
            }
            TokenTree::Group(group) => {
                collect_idents(&group.stream().into_iter().collect::<Vec<_>>(), out);
            }
            _ => {}
        }
    }
}

/// Names bound anywhere in `trees`: by a `let`, a closure argument list, a
/// `for` loop, a match arm, or a `matches!` pattern.
///
/// All are read loosely — every identifier in the pattern, at any depth —
/// because over-collecting only drops a call edge, while under-collecting
/// would let a shadowed name resolve to an unrelated function.
fn collect_bindings(trees: &[TokenTree], out: &mut BTreeSet<String>) {
    let is_punct =
        |at: usize, c: char| matches!(trees.get(at), Some(TokenTree::Punct(p)) if p.as_char() == c);
    let is_ident =
        |at: usize, name: &str| matches!(trees.get(at), Some(TokenTree::Ident(id)) if *id == name);
    // `=>` at `trees[at]`.
    let is_fat_arrow = |at: usize| {
        matches!(trees.get(at), Some(TokenTree::Punct(p)) if p.as_char() == '=' && p.spacing() == proc_macro2::Spacing::Joint)
            && is_punct(at + 1, '>')
    };
    // Where the current match-arm pattern starts.
    let mut arm_start = 0;
    let mut i = 0;
    while i < trees.len() {
        match &trees[i] {
            // `for PATTERN in …`. A `for` with no `in` before the next `;` or
            // block (`impl X for Y { … }`, `for<'a>`) binds nothing.
            TokenTree::Ident(ident) if *ident == "for" && !is_punct(i + 1, '<') => {
                let end = trees[i + 1..]
                    .iter()
                    .position(|t| match t {
                        TokenTree::Ident(id) => *id == "in",
                        TokenTree::Punct(p) => p.as_char() == ';',
                        TokenTree::Group(g) => g.delimiter() == Delimiter::Brace,
                        TokenTree::Literal(_) => false,
                    })
                    .map(|at| i + 1 + at);
                if let Some(end) = end.filter(|end| is_ident(*end, "in")) {
                    collect_idents(&trees[i + 1..end], out);
                    i = end;
                }
            }
            // `PATTERN =>` binds every name in the pattern. A guard
            // (`PATTERN if cond =>`) binds nothing, so it is left out.
            TokenTree::Punct(_) if is_fat_arrow(i) => {
                let guard = (arm_start..i).find(|at| is_ident(*at, "if")).unwrap_or(i);
                collect_idents(&trees[arm_start..guard], out);
                i += 1;
                arm_start = i + 1;
            }
            TokenTree::Punct(p) if p.as_char() == ',' || p.as_char() == ';' => {
                arm_start = i + 1;
            }
            // `matches!(value, PATTERN)`.
            TokenTree::Ident(ident) if *ident == "matches" && is_punct(i + 1, '!') => {
                if let Some(TokenTree::Group(args)) = trees.get(i + 2) {
                    let args: Vec<TokenTree> = args.stream().into_iter().collect();
                    if let Some(comma) = args
                        .iter()
                        .position(|t| matches!(t, TokenTree::Punct(p) if p.as_char() == ','))
                    {
                        collect_idents(&args[comma + 1..], out);
                    }
                }
            }
            TokenTree::Ident(ident) if *ident == "let" => {
                i += 1;
                while let Some(tree) = trees.get(i) {
                    match tree {
                        TokenTree::Punct(p) if p.as_char() == '=' || p.as_char() == ';' => break,
                        TokenTree::Ident(id) => {
                            out.insert(id.to_string());
                        }
                        TokenTree::Group(group) => {
                            collect_idents(&group.stream().into_iter().collect::<Vec<_>>(), out);
                        }
                        TokenTree::Punct(_) | TokenTree::Literal(_) => {}
                    }
                    i += 1;
                }
            }
            // A closure argument list, patterns included (`|(id, row)|`).
            TokenTree::Punct(p) if p.as_char() == '|' => {
                if let Some(end) = closure_args_end(trees, i, out) {
                    i = end;
                }
            }
            TokenTree::Group(group) => {
                collect_bindings(&group.stream().into_iter().collect::<Vec<_>>(), out);
                // A brace group ends an arm body, unless it is part of the
                // pattern (`V { row } =>`, `V { a } | W { b } =>`).
                let in_pattern = group.delimiter() != Delimiter::Brace
                    || is_fat_arrow(i + 1)
                    || is_punct(i + 1, '|')
                    || is_ident(i + 1, "if");
                if !in_pattern {
                    arm_start = i + 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
}

/// The index of the `|` that closes a closure argument list opened by the `|`
/// at `trees[open]`, after adding every name in it to `out`. `None`, and
/// nothing added, when `trees[open]` does not open one.
///
/// A list opens where an expression starts: at the start of a group, after a
/// punct (`=`, `,`, `=>`), or after `move`. A `|` after an operand is a
/// bitwise or or a pattern alternative (`A | B`). A list ends before a `;` or
/// a `=>`.
fn closure_args_end(trees: &[TokenTree], open: usize, out: &mut BTreeSet<String>) -> Option<usize> {
    let opens = open.checked_sub(1).is_none_or(|prev| match &trees[prev] {
        TokenTree::Punct(_) => true,
        TokenTree::Ident(id) => ["move", "return", "async"].iter().any(|kw| id == kw),
        _ => false,
    });
    if !opens {
        return None;
    }
    let mut names = BTreeSet::new();
    for (at, tree) in trees.iter().enumerate().skip(open + 1) {
        match tree {
            TokenTree::Punct(q) if q.as_char() == '|' => {
                out.extend(names);
                return Some(at);
            }
            TokenTree::Punct(q) if q.as_char() == ';' => return None,
            TokenTree::Punct(q)
                if q.as_char() == '='
                    && q.spacing() == proc_macro2::Spacing::Joint
                    && matches!(trees.get(at + 1), Some(TokenTree::Punct(r)) if r.as_char() == '>') =>
            {
                return None;
            }
            TokenTree::Ident(id) => {
                names.insert(id.to_string());
            }
            TokenTree::Group(group) => {
                collect_idents(&group.stream().into_iter().collect::<Vec<_>>(), &mut names);
            }
            TokenTree::Punct(_) | TokenTree::Literal(_) => {}
        }
    }
    None
}

/// Whether the identifier at `trees[i]` names a free function this scan can
/// resolve by name — see [`collect_calls`] for the shapes this rejects.
fn is_resolvable_call(trees: &[TokenTree], i: usize) -> bool {
    let Some(prev) = i.checked_sub(1).and_then(|at| trees.get(at)) else {
        return true;
    };
    match prev {
        // `page.sidebar()`.
        TokenTree::Punct(p) if p.as_char() == '.' => false,
        // `fn helper(…)`, `struct Row(…)`.
        TokenTree::Ident(id) if DECL_KEYWORDS.contains(&id.to_string().as_str()) => false,
        // A path: resolvable only when the qualifier is a module.
        TokenTree::Punct(p) if p.as_char() == ':' => qualifier_is_module(trees, i),
        _ => true,
    }
}

/// Whether the path segment before the `::` at `trees[i - 2]` is a module
/// of this project rather than a type. Rust names modules in `snake_case` and
/// types in `UpperCamelCase`, so the leading character decides. Anything that
/// is not a plain identifier (a turbofish, `<Foo as Bar>::baz`) is not
/// resolvable. A primitive type (`str::trim`, `u32::from`) and a path into the
/// standard library (`std::mem::drop`) are not modules of this project.
fn qualifier_is_module(trees: &[TokenTree], i: usize) -> bool {
    let segment = |at: Option<usize>| match at.and_then(|at| trees.get(at)) {
        Some(TokenTree::Ident(id)) => Some(id.to_string()),
        _ => None,
    };
    let Some(qualifier) = segment(i.checked_sub(3)) else {
        return false;
    };
    if !qualifier.chars().next().is_some_and(char::is_lowercase)
        || qualifier == "Self"
        || PRIMITIVE_TYPES.contains(&qualifier.as_str())
    {
        return false;
    }
    // Walk back to the first segment of the path.
    let mut root = (qualifier, i - 3);
    while root.1 >= 3
        && matches!(&trees[root.1 - 1], TokenTree::Punct(p) if p.as_char() == ':')
        && let Some(prev) = segment(Some(root.1 - 3))
    {
        root = (prev, root.1 - 3);
    }
    !["std", "core", "alloc"].contains(&root.0.as_str())
}

/// The primitive types, which have lower-case names like a module.
const PRIMITIVE_TYPES: [&str; 18] = [
    "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64",
    "i128", "isize", "f32", "f64", "f16",
];

/// The call graph rooted at each declared route.
struct RouteGraph<'a> {
    fns: &'a [FnDecl],
    /// One entry per route: its declaration, its handler, and every function it
    /// statically reaches.
    routes: Vec<(RouteDecl, usize, BTreeSet<usize>)>,
}

impl<'a> RouteGraph<'a> {
    fn build(fns: &'a [FnDecl]) -> Self {
        // A name defined more than once is unresolvable, so it is not indexed.
        let mut by_name: std::collections::HashMap<&str, Option<usize>> =
            std::collections::HashMap::new();
        for (index, decl) in fns.iter().enumerate().filter(|(_, d)| d.callable) {
            by_name
                .entry(decl.name.as_str())
                .and_modify(|slot| *slot = None)
                .or_insert(Some(index));
        }
        // The same per body: the helpers a function declares at its top level.
        let mut local: std::collections::HashMap<(usize, &str), Option<usize>> =
            std::collections::HashMap::new();
        for (index, decl) in fns.iter().enumerate() {
            if let Some(owner) = decl.owner {
                local
                    .entry((owner, decl.name.as_str()))
                    .and_modify(|slot| *slot = None)
                    .or_insert(Some(index));
            }
        }
        // A helper in an inner block (or an `impl` in a body) can shadow the
        // name anywhere in its outermost function, and the scan does not track
        // blocks: such a name resolves to nothing there.
        let hidden: BTreeSet<(usize, &str)> = fns
            .iter()
            .filter(|decl| decl.owner.is_none())
            .filter_map(|decl| decl.top.map(|top| (top, decl.name.as_str())))
            .collect();
        // A bare call reaches the nearest helper of that name: one declared in
        // the caller's body, then in each enclosing body, then a free item.
        let resolve = |from: usize, name: &str| -> Option<usize> {
            if let Some(path) = name.strip_prefix("::") {
                return by_name.get(path).copied().flatten();
            }
            if hidden.contains(&(fns[from].top.unwrap_or(from), name)) {
                return None;
            }
            let mut scope = Some(from);
            while let Some(owner) = scope {
                if let Some(slot) = local.get(&(owner, name)) {
                    return *slot;
                }
                scope = fns[owner].owner;
            }
            by_name.get(name).copied().flatten()
        };

        let mut routes = Vec::new();
        for (index, decl) in fns.iter().enumerate() {
            for route in &decl.routes {
                let mut reached = BTreeSet::new();
                let mut stack = vec![index];
                while let Some(current) = stack.pop() {
                    if !reached.insert(current) {
                        continue;
                    }
                    for call in &fns[current].calls {
                        if let Some(target) = resolve(current, call) {
                            stack.push(target);
                        }
                    }
                }
                routes.push((route.clone(), index, reached));
            }
        }
        Self { fns, routes }
    }

    /// The innermost function whose span contains `file:line:column`.
    ///
    /// Position is compared with the column, not the line alone: two functions
    /// can share a line (`fn a() { … } fn b() { … }`), and a line-only
    /// comparison would hand one of them the other's markup.
    fn enclosing_fn(&self, file: &str, at: (usize, usize)) -> Option<usize> {
        self.fns
            .iter()
            .enumerate()
            .filter(|(_, decl)| decl.file == file && decl.start <= at && at <= decl.end)
            .min_by_key(|(_, decl)| (decl.end.0 - decl.start.0, decl.end.1))
            .map(|(index, _)| index)
    }

    /// Indices of the routes reaching the markup at `file:line:column`.
    ///
    /// Routes are identified by index, not by their `"METHOD /path"` key: paths
    /// are declared rather than mounted, so two handlers can legitimately
    /// declare the same one, and keying by the string would report a clean
    /// handler as failing for its namesake's defect.
    fn routes_reaching(&self, file: &str, at: (usize, usize)) -> Vec<usize> {
        let Some(target) = self.enclosing_fn(file, at) else {
            return Vec::new();
        };
        self.routes
            .iter()
            .enumerate()
            .filter(|(_, (_, _, reached))| reached.contains(&target))
            .map(|(index, _)| index)
            .collect()
    }

    /// The display keys for a set of route indices, sorted and deduplicated.
    fn display_keys(&self, indices: &[usize]) -> Vec<String> {
        let mut keys: Vec<String> = indices
            .iter()
            .map(|index| route_key(&self.routes[*index].0))
            .collect();
        keys.sort();
        keys.dedup();
        keys
    }

    /// Per-route conformance, sorted by path then method. `reaching` holds the
    /// route indices of each finding, in finding order.
    fn conformance(&self, reaching: &[Vec<usize>]) -> Vec<RouteConformance> {
        let mut out: Vec<RouteConformance> = self
            .routes
            .iter()
            .enumerate()
            .map(|(index, (route, handler, _))| {
                let count = reaching.iter().filter(|hit| hit.contains(&index)).count();
                RouteConformance {
                    method: route.method.to_owned(),
                    path: route.path.clone(),
                    handler: self.fns[*handler].name.clone(),
                    file: self.fns[*handler].file.clone(),
                    line: self.fns[*handler].start.0,
                    findings: count,
                    status: if count == 0 { "pass" } else { "fail" },
                }
            })
            .collect();
        out.sort_by(|a, b| (&a.path, &a.method, &a.handler).cmp(&(&b.path, &b.method, &b.handler)));
        out
    }
}

/// `"GET /settings"` — the display key a finding and a route agree on.
fn route_key(route: &RouteDecl) -> String {
    format!("{} {}", route.method, route.path)
}

/// Roll findings up by WCAG success criterion, splitting the multi-criterion
/// rules (`label` covers 1.3.1, 3.3.2 and 4.1.2) so each criterion reports on
/// its own — the view a conformance claim is written against.
fn roll_up_wcag(findings: &[Finding]) -> Vec<WcagCriterion> {
    let mut by_criterion: std::collections::BTreeMap<&str, (BTreeSet<&'static str>, usize)> =
        std::collections::BTreeMap::new();
    for finding in findings {
        for criterion in finding.wcag.split('/').map(str::trim) {
            let entry = by_criterion.entry(criterion).or_default();
            entry.0.insert(finding.rule_id);
            entry.1 += 1;
        }
    }
    by_criterion
        .into_iter()
        .map(|(criterion, (rules, findings))| WcagCriterion {
            criterion: criterion.to_owned(),
            rules: rules.into_iter().collect(),
            findings,
        })
        .collect()
}

// ── Maud markup model ──────────────────────────────────────────────────────

/// A parsed attribute value.
#[derive(Debug, Clone)]
enum AttrValue {
    /// A static string literal, e.g. `alt="logo"` → `logo`.
    Literal(String),
    /// A spliced/runtime value, e.g. `alt=(expr)` — unresolvable.
    Dynamic,
    /// A boolean/presence-only or optional attribute, e.g. `disabled`,
    /// `required[cond]`.
    Boolean,
}

/// A parsed HTML attribute.
#[derive(Debug, Clone)]
struct Attr {
    name: String,
    value: AttrValue,
}

/// A parsed HTML element (best-effort).
#[derive(Debug, Clone)]
struct Element {
    name: String,
    line: usize,
    /// 0-based column of the element, used only to pick the innermost enclosing
    /// function when two of them share a line.
    column: usize,
    attrs: Vec<Attr>,
    children: Vec<Node>,
}

impl Element {
    /// The value of the first attribute named `name` (ASCII-case-insensitive).
    fn attr(&self, name: &str) -> Option<&AttrValue> {
        self.attrs
            .iter()
            .find(|a| a.name.eq_ignore_ascii_case(name))
            .map(|a| &a.value)
    }

    /// Whether an attribute named `name` is present in any form.
    fn has_attr(&self, name: &str) -> bool {
        self.attr(name).is_some()
    }

    /// Whether this element carries a non-empty `aria-label`/`aria-labelledby`.
    /// A spliced value counts as a name (unresolvable → assume present).
    fn has_aria_name(&self) -> bool {
        ["aria-label", "aria-labelledby"]
            .iter()
            .any(|n| attr_is_present_name(self.attr(n)))
    }

    /// Whether this element carries a non-empty `title`. Per the ARIA
    /// accessible-name computation `title` is a last-resort name source, so a
    /// control (or descendant) with a non-empty/dynamic `title` is named. A
    /// spliced `title=(…)` counts (unresolvable → assume present).
    fn has_title_name(&self) -> bool {
        attr_is_present_name(self.attr("title"))
    }
}

/// Whether an element is removed from the accessibility tree by an explicit
/// presentational role (`role="presentation"`/`role="none"`). A spliced
/// `role=(…)` is unresolvable and could be one of those, so it is treated as
/// presentational (non-failing convention — skip rather than misfire). Note this
/// is only honored for non-focusable elements (e.g. `<img>`): ARIA conflict
/// resolution restores the implicit role on focusable controls, so it is not
/// applied to `<button>`/`<a href>`/form controls.
fn is_presentational(el: &Element) -> bool {
    match el.attr("role") {
        Some(AttrValue::Dynamic) => true,
        Some(AttrValue::Literal(r)) => {
            let r = r.to_ascii_lowercase();
            r == "presentation" || r == "none"
        }
        _ => false,
    }
}

/// Whether an attribute value supplies a non-empty accessible name: a spliced
/// value (unresolvable → assume present) or a string literal that is non-blank
/// after `.trim()`. A whitespace-only literal (`aria-label="   "`, `title=" "`,
/// `alt="  "`) collapses to an empty accessible name — mirroring how text nodes
/// are trimmed — so it does NOT count as a present name.
fn attr_is_present_name(value: Option<&AttrValue>) -> bool {
    match value {
        Some(AttrValue::Dynamic) => true,
        Some(AttrValue::Literal(s)) => !s.trim().is_empty(),
        _ => false,
    }
}

/// Whether an `<img>` carries an `alt` that is a valid decorative marker or a
/// real textual name. An explicitly empty `alt=""` is the accepted decorative
/// marker (kept clean). A literal `alt` counts as a name only when it is
/// non-blank after `.trim()`: a whitespace-only `alt="   "` collapses to an
/// empty accessible name and is neither a name nor a valid decorative marker, so
/// it does NOT satisfy the check. A dynamic/boolean `alt` is unresolvable and
/// treated as present (non-failing convention).
fn has_alt_marker(el: &Element) -> bool {
    match el.attr("alt") {
        None => false,
        // Exact-empty is decorative; otherwise it must be non-blank after trim.
        Some(AttrValue::Literal(s)) => s.is_empty() || !s.trim().is_empty(),
        Some(_) => true,
    }
}

/// A parsed markup node.
#[derive(Debug, Clone)]
enum Node {
    Element(Element),
    /// A non-empty static text node.
    Text(String),
    /// A splice `(expr)` or a control block — an unresolvable dynamic value.
    /// `splice` records whether it is a genuine `(expr)`/`[..]` splice (which
    /// could render a `<label>` fragment beside a control) rather than an
    /// `@`-control head; only the former marks a block as possibly-labeled.
    Dynamic {
        splice: bool,
    },
}

/// Parse a maud markup token stream into a best-effort node list.
fn parse_markup(stream: &TokenStream) -> Vec<Node> {
    let trees: Vec<TokenTree> = stream.clone().into_iter().collect();
    parse_nodes(&trees)
}

fn parse_nodes(trees: &[TokenTree]) -> Vec<Node> {
    let mut nodes = Vec::new();
    let mut i = 0;
    while i < trees.len() {
        match &trees[i] {
            TokenTree::Ident(_) => {
                let (element, next) = parse_element(trees, i);
                nodes.push(Node::Element(element));
                i = next;
            }
            TokenTree::Literal(lit) => {
                let text = literal_text(lit);
                if !text.trim().is_empty() {
                    nodes.push(Node::Text(text));
                }
                i += 1;
            }
            // A leading `.`/`#` shorthand with NO explicit tag name is maud's
            // implicit `div`: `.input { … }` renders `<div class="input">` and
            // `#button { … }` renders `<div id="button">`. The class/id token is
            // a VALUE, not a tag, so parse it as a `div` element (which triggers
            // no rule) rather than letting the next iteration read `input`/`button`
            // as a phantom element (false positive).
            TokenTree::Punct(p) if matches!(p.as_char(), '#' | '.') => {
                let (element, next) = parse_element(trees, i);
                nodes.push(Node::Element(element));
                i = next;
            }
            TokenTree::Punct(p) if p.as_char() == '@' => {
                // Control flow (`@if`/`@for`/`@match`/`@let`): dynamic, but still
                // descend into any block so elements inside are analyzed. Not a
                // spliced fragment, so it never marks the block as possibly-labeled.
                nodes.push(Node::Dynamic { splice: false });
                if matches!(trees.get(i + 1), Some(TokenTree::Ident(id)) if *id == "match") {
                    // `@match` is special: the brace group after the scrutinee is
                    // an arm LIST, not markup. Parsing it as markup would treat
                    // each arm's pattern (e.g. `input => …`) as an element and
                    // fire a false positive. Skip past `@match`, then parse arms.
                    i = skip_match(trees, i + 2, &mut nodes);
                } else if matches!(trees.get(i + 1), Some(TokenTree::Ident(id)) if *id == "let") {
                    // `@let` is special: it binds a Rust expression, so any brace
                    // group in its initializer (`Field { input: true }`) is
                    // struct-literal syntax, NEVER markup. Unlike `@if`/`@for`,
                    // descending into it would misread a Rust field named `input`
                    // as an `<input>`. Skip the whole binding up to its `;`.
                    i = skip_let(trees, i + 2);
                } else {
                    i = skip_control(trees, i + 1, &mut nodes);
                }
            }
            TokenTree::Group(g) => {
                if g.delimiter() == Delimiter::Brace {
                    nodes.extend(parse_markup(&g.stream()));
                } else {
                    // A `(expr)` splice or `[..]` — an unresolvable dynamic value
                    // that could render a `<label>` fragment beside a control.
                    nodes.push(Node::Dynamic { splice: true });
                }
                i += 1;
            }
            TokenTree::Punct(_) => i += 1,
        }
    }
    nodes
}

/// Skip a `@if`/`@for`/`@while` head and fold each body block's children into
/// `nodes` as siblings, following a trailing `@else` chain.
///
/// The body of these controls is a brace `Block`, but a brace can also appear in
/// the HEAD and must NOT be parsed as markup:
///
/// - a `let`/`for` **pattern** may be a struct/enum-struct pattern
///   (`@for Foo { x } in xs`, `@if let Foo { x } = e`); its braces are pattern
///   syntax, and
/// - the condition/iterator is parsed with `parse_without_eager_brace`, which
///   accepts a **block-expression** condition (`@if { cond } { body }`); the
///   leading brace is then the condition, not the body.
///
/// The body is the FINAL top-level brace of the clause. Two kinds of earlier
/// brace are part of the condition and must NOT be parsed as markup:
///
/// - a **leading** block-expression condition (`@if { cond } { body }`): a brace
///   seen before any condition token, immediately followed by the body brace, and
/// - a **block-bearing keyword** expression inside the condition — `match`/`loop`/
///   `unsafe` (`@if match s { … } { body }`): the keyword owns the next top-level
///   brace (its block), which belongs to the condition, not the body.
///
/// A plain `@if a { body } { sibling }` is different: `a` is a complete condition,
/// `{ body }` is the markup body, and `{ sibling }` is a following sibling block —
/// both are scanned. So a brace-followed-by-brace is only skipped when it is a
/// leading block condition or a pending keyword block; otherwise it is the body.
fn skip_control(trees: &[TokenTree], start: usize, nodes: &mut Vec<Node>) -> usize {
    let mut i = start;
    // Inside a `let`/`for` pattern region, where braces are pattern syntax.
    let mut in_pattern = false;
    // Whether a non-brace condition token has been seen (so a following brace is
    // the body, not a leading block-expression condition).
    let mut saw_cond = false;
    // A `match`/`loop`/`unsafe` expression in the condition owns the next
    // top-level brace (its block), which is part of the condition, not the body.
    let mut pending_block = false;
    while i < trees.len() {
        match &trees[i] {
            TokenTree::Ident(id) => {
                // A Rust macro call in the condition: `ident! { … }` /
                // `ident!(…)` / `ident![…]` (e.g. `@if ready! { input } { body }`).
                // The condition is parsed with `parse_without_eager_brace`, which
                // accepts a macro invocation, so the `!`-delimited group is macro
                // input — part of the condition, NOT markup. Skip the ident, the
                // `!`, and the group together (any delimiter), the same way
                // `match`/`loop`/`unsafe` keep their block out of the body;
                // otherwise the macro's brace group is misparsed as markup (a
                // phantom `<input>`) and the real body brace is missed. Requiring a
                // delimiter group right after `!` excludes the `!=` operator (whose
                // `!` is followed by `=`, not a group).
                if !in_pattern
                    && matches!(trees.get(i + 1), Some(TokenTree::Punct(p)) if p.as_char() == '!')
                    && matches!(trees.get(i + 2), Some(TokenTree::Group(_)))
                {
                    saw_cond = true;
                    i += 3;
                    continue;
                }
                match id.to_string().as_str() {
                    // Leading control keywords: not condition tokens.
                    "if" | "while" | "else" => {}
                    // `let`/`for` open a pattern region.
                    "let" | "for" => in_pattern = true,
                    // `in` closes a `@for pat in …` pattern region.
                    "in" if in_pattern => in_pattern = false,
                    // A block-bearing keyword expression in the condition: the
                    // next top-level brace is its block, part of the condition.
                    "match" | "loop" | "unsafe" if !in_pattern => {
                        saw_cond = true;
                        pending_block = true;
                    }
                    // Any other ident is part of the condition/iterator expression.
                    _ => {
                        if !in_pattern {
                            saw_cond = true;
                        }
                    }
                }
                i += 1;
            }
            // `=` closes a `@if let pat = …` / `@while let pat = …` pattern region.
            TokenTree::Punct(p) if in_pattern && p.as_char() == '=' => {
                in_pattern = false;
                i += 1;
            }
            // `@let x = …;` (defensive) ends at a semicolon with no block.
            TokenTree::Punct(p) if p.as_char() == ';' => {
                i += 1;
                break;
            }
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => {
                if in_pattern {
                    // Struct/enum-struct pattern brace — skip, not markup.
                    i += 1;
                    continue;
                }
                if pending_block {
                    // The block of a `match`/`loop`/`unsafe` condition expression
                    // (e.g. the arm-list of `@if match s { … } { body }`). Part of
                    // the condition — skip; the body is a later brace.
                    pending_block = false;
                    i += 1;
                    continue;
                }
                if !saw_cond
                    && matches!(trees.get(i + 1), Some(TokenTree::Group(n)) if n.delimiter() == Delimiter::Brace)
                {
                    // Leading block-expression condition; body is the next brace.
                    i += 1;
                    continue;
                }
                nodes.extend(parse_markup(&g.stream()));
                i += 1;
                // Only `@else` continues this chain. Any other `@`-control
                // (`@let`/`@if`/`@for`/`@match`) is a sibling that must be
                // returned to `parse_nodes` so it hits its proper handler —
                // consuming it here would misparse e.g. a following `@let`'s
                // struct-literal initializer as markup.
                if matches!(trees.get(i), Some(TokenTree::Punct(p)) if p.as_char() == '@')
                    && matches!(trees.get(i + 1), Some(TokenTree::Ident(id)) if *id == "else")
                {
                    i += 1;
                    // Reset for the `@else` / `@else if …` continuation.
                    in_pattern = false;
                    saw_cond = false;
                    pending_block = false;
                    continue;
                }
                break;
            }
            // Any other token (paren/bracket group, operator, literal) is part of
            // the condition/iterator expression.
            _ => {
                if !in_pattern {
                    saw_cond = true;
                }
                i += 1;
            }
        }
    }
    i
}

/// Skip an `@let` binding, consuming every token up to and including its
/// terminating top-level `;`. Unlike `@if`/`@for`/`@match` — whose braces are
/// markup — an `@let` binds a Rust expression, so any brace group in its
/// initializer (`Field { input: true }`) is struct-literal syntax and must NOT
/// be parsed as markup; descending into it would misread a Rust field named
/// `input` as an `<input>` element and fire a false positive. `start` points
/// just past `@let`. Group token trees are atomic, so the `;` seen at this
/// level is always the binding terminator, never one nested in a brace.
fn skip_let(trees: &[TokenTree], start: usize) -> usize {
    let mut i = start;
    while i < trees.len() {
        if matches!(&trees[i], TokenTree::Punct(p) if p.as_char() == ';') {
            return i + 1;
        }
        i += 1;
    }
    i
}

/// Skip a `@match` head and scan only the arm BODIES. `start` points just past
/// `@match`, at the scrutinee expression. The arm list is the brace group after
/// the scrutinee; its contents are handed to [`parse_match_arms`].
///
/// A bare struct-literal scrutinee needs parens (a paren group, skipped), but the
/// scrutinee is parsed with `parse_without_eager_brace`, so it MAY be a leading
/// block expression (`@match { x } { arms }`). In that case the first brace is
/// the scrutinee and the arm list is the next brace: skip a leading brace that is
/// immediately followed by another brace when no scrutinee token precedes it.
fn skip_match(trees: &[TokenTree], start: usize, nodes: &mut Vec<Node>) -> usize {
    let mut i = start;
    let mut saw_scrut = false;
    while i < trees.len() {
        if let TokenTree::Group(g) = &trees[i]
            && g.delimiter() == Delimiter::Brace
        {
            if !saw_scrut
                && matches!(trees.get(i + 1), Some(TokenTree::Group(n)) if n.delimiter() == Delimiter::Brace)
            {
                // Leading block-expression scrutinee; the arm list is next.
                i += 1;
                continue;
            }
            let arms: Vec<TokenTree> = g.stream().into_iter().collect();
            parse_match_arms(&arms, nodes);
            return i + 1;
        }
        saw_scrut = true;
        i += 1;
    }
    i
}

/// Parse a maud `@match` arm list. For each arm, skip the pattern tokens (and
/// any `if <guard>`) up to and including `=>`, then scan ONLY the arm body as
/// markup. This keeps arm patterns from being misread as elements while still
/// analyzing the real markup each arm renders.
fn parse_match_arms(trees: &[TokenTree], nodes: &mut Vec<Node>) {
    let mut i = 0;
    while i < trees.len() {
        // Locate the `=>` that separates this arm's pattern/guard from its body.
        // A fat arrow is two joined puncts `=` `>`; the first one after the arm
        // start delimits the body (guards use `>=`/`==`, never `=>`).
        let Some(arrow) = find_fat_arrow(trees, i) else {
            break;
        };
        i = parse_arm_body(trees, arrow + 2, nodes);
    }
}

/// The index of the `=` token of the first `=>` at or after `start`, if any.
fn find_fat_arrow(trees: &[TokenTree], start: usize) -> Option<usize> {
    let mut i = start;
    while i < trees.len() {
        if let TokenTree::Punct(p) = &trees[i]
            && p.as_char() == '='
            && matches!(trees.get(i + 1), Some(TokenTree::Punct(q)) if q.as_char() == '>')
        {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Scan a single `@match` arm body starting at `start` (just past `=>`) and
/// return the index of the next arm. A brace-group body is parsed as markup; any
/// other shape (`(splice)`, string literal, single element) is collected up to
/// the next top-level comma and parsed as markup. An unrecognized/ambiguous
/// shape is simply skipped — a missed check is acceptable here, a false positive
/// is not.
fn parse_arm_body(trees: &[TokenTree], start: usize, nodes: &mut Vec<Node>) -> usize {
    if let Some(TokenTree::Group(g)) = trees.get(start)
        && g.delimiter() == Delimiter::Brace
    {
        nodes.extend(parse_markup(&g.stream()));
        let mut next = start + 1;
        if matches!(trees.get(next), Some(TokenTree::Punct(p)) if p.as_char() == ',') {
            next += 1;
        }
        return next;
    }
    // Non-brace body: collect up to the next top-level comma (group contents are
    // atomic token trees, so any comma seen here is an arm separator).
    let mut j = start;
    while j < trees.len() {
        if matches!(&trees[j], TokenTree::Punct(p) if p.as_char() == ',') {
            break;
        }
        j += 1;
    }
    nodes.extend(parse_nodes(&trees[start..j]));
    if j < trees.len() { j + 1 } else { j }
}

/// Parse a single element starting at `trees[start]` (an ident, or a leading
/// `.`/`#` shorthand denoting maud's implicit `div`). Returns the element and the
/// index just past it.
fn parse_element(trees: &[TokenTree], start: usize) -> (Element, usize) {
    let line = trees[start].span().start().line;
    let column = trees[start].span().start().column;
    // A leading `.`/`#` with no explicit tag name is an implicit `div`; the
    // shorthand class/id begins AT `start` and the tag is `div`. Otherwise the
    // tag name is a full maud `HtmlName` (`Punctuated<HtmlNameFragment, '-' | ':'>`),
    // so a custom/namespaced tag like `x-input`, `x-button`, or `svg:rect` must be
    // read via the SAME `read_name` logic used for attribute names — consuming only
    // the first identifier would leave the `-`/`:` + suffix in the stream, where the
    // next pass would misread the `input`/`button`/`rect` suffix as a separate plain
    // control element and fire a false `label`/`button-name`. Shorthands begin just
    // past the whole name.
    let (name, shorthand_start) = match &trees[start] {
        TokenTree::Punct(p) if matches!(p.as_char(), '#' | '.') => ("div".to_owned(), start),
        _ => read_name(trees, start),
    };
    let mut attrs = Vec::new();
    let mut i = parse_shorthand(trees, shorthand_start, &mut attrs);
    let mut children = Vec::new();
    while i < trees.len() {
        match &trees[i] {
            TokenTree::Punct(p) if p.as_char() == ';' => {
                i += 1;
                break;
            }
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => {
                children = parse_markup(&g.stream());
                i += 1;
                break;
            }
            TokenTree::Punct(p) if matches!(p.as_char(), '#' | '.') => {
                i = parse_shorthand(trees, i, &mut attrs);
            }
            TokenTree::Ident(_) => {
                let (attr, next) = parse_attr(trees, i);
                attrs.push(attr);
                i = next;
            }
            // A quoted (string-literal) attribute name, e.g.
            // `button "@click"="save" { … }` or `input "aria-label"="Search";`.
            // maud accepts a `LitStr` as an attribute-name fragment, so route it
            // through `parse_attr` like an ident name: its `="value"` (or bare /
            // `[toggler]`) is consumed and the element body that follows is still
            // parsed. `read_name` records the unquoted text, so a quoted
            // accessible-name source (`"aria-label"`, `"title"`, `"alt"`) counts
            // toward the accessible name exactly like the ident form. A non-string
            // literal is not a valid name here and ends the element (best-effort:
            // a missed check is acceptable, a false positive is not).
            TokenTree::Literal(lit) if string_literal_value(lit).is_some() => {
                let (attr, next) = parse_attr(trees, i);
                attrs.push(attr);
                i = next;
            }
            // Anything else (a stray splice, operator, …) ends the element.
            _ => break,
        }
    }
    (
        Element {
            name,
            line,
            column,
            attrs,
            children,
        },
        i,
    )
}

/// Parse maud `#id` / `.class` shorthands, recording `#id` as an `id` attribute.
///
/// Each shorthand's value is a maud `HtmlNameOrMarkup`: a static name (`#bar`,
/// `.foo`), a dynamic splice (`#(expr)`, `.(expr)` — a paren-group Markup), a
/// braced markup group (`.{ … }`), or a MARKUP control value
/// (`.@if primary { "primary" }`); a class may then carry a `[cond]` toggler
/// (`.foo[active]`). A dynamic/markup id value is recorded as `Dynamic`
/// (unresolvable, like `id=(expr)`). Consuming the value and toggler is
/// essential: leaving a `(expr)`/`{ … }`/`@…`/`[cond]` group unconsumed ends the
/// element early, orphaning its real `{ … }` body and firing false positives on
/// the parent (e.g. `button.(cls) { "Save" }` or `button.@if c { "x" } { "Save" }`
/// losing its text).
fn parse_shorthand(trees: &[TokenTree], start: usize, attrs: &mut Vec<Attr>) -> usize {
    let mut i = start;
    while let Some(TokenTree::Punct(p)) = trees.get(i) {
        let sym = p.as_char();
        if sym != '#' && sym != '.' {
            break;
        }
        let is_id = sym == '#';
        i += 1; // consume the `#`/`.` — guarantees progress even with no name.
        match trees.get(i) {
            // Dynamic shorthand value: `#(expr)` / `.(expr)`, or a braced markup
            // group `#{ … }` / `.{ … }` — an unresolvable markup value. (A body
            // brace never follows a `#`/`.` directly, so this is the class/id
            // value, never the element body.)
            Some(TokenTree::Group(g))
                if matches!(g.delimiter(), Delimiter::Parenthesis | Delimiter::Brace) =>
            {
                if is_id {
                    attrs.push(Attr {
                        name: "id".to_owned(),
                        value: AttrValue::Dynamic,
                    });
                }
                i += 1;
            }
            // Markup-valued shorthand via a maud control:
            // `.@if c { "x" }` / `#@match … { … }`. Fully consume the control
            // (head + brace group(s) + any `@else` chain) so the element's real
            // body that follows is still parsed. The value is unresolvable, so an
            // id records as `Dynamic`.
            Some(TokenTree::Punct(q)) if q.as_char() == '@' => {
                if is_id {
                    attrs.push(Attr {
                        name: "id".to_owned(),
                        value: AttrValue::Dynamic,
                    });
                }
                i = skip_shorthand_control(trees, i + 1);
            }
            // Static shorthand value: `#bar` / `.foo` (possibly hyphenated).
            _ => {
                let (name, next) = read_name(trees, i);
                if next > i {
                    if is_id {
                        attrs.push(Attr {
                            name: "id".to_owned(),
                            value: AttrValue::Literal(name),
                        });
                    }
                    i = next;
                }
            }
        }
        // Optional `[cond]` toggler (`.foo[active]`).
        if matches!(trees.get(i), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket)
        {
            i += 1;
        }
    }
    i
}

/// Consume a markup-valued class/id control value (`.@if c { "x" }`), returning
/// the index just past it. `start` points just past the `@`, at the control
/// keyword. Reuses the same control/match/let skippers as node parsing; any
/// markup they descend into is discarded — a class/id value is a maud
/// `NoElement` context and can render no element to scan.
fn skip_shorthand_control(trees: &[TokenTree], start: usize) -> usize {
    let mut discard = Vec::new();
    if matches!(trees.get(start), Some(TokenTree::Ident(id)) if *id == "match") {
        skip_match(trees, start + 1, &mut discard)
    } else if matches!(trees.get(start), Some(TokenTree::Ident(id)) if *id == "let") {
        skip_let(trees, start + 1)
    } else {
        skip_control(trees, start, &mut discard)
    }
}

/// Parse one attribute (`name`, `name="v"`, `name=(expr)`, `name[cond]`, …).
fn parse_attr(trees: &[TokenTree], start: usize) -> (Attr, usize) {
    let (name, i) = read_name(trees, start);
    match trees.get(i) {
        Some(TokenTree::Punct(p)) if p.as_char() == '=' => {
            let (value, next) = read_attr_value(trees, i + 1);
            (Attr { name, value }, next)
        }
        Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => (
            Attr {
                name,
                value: AttrValue::Boolean,
            },
            i + 1,
        ),
        Some(TokenTree::Punct(p)) if p.as_char() == '?' => {
            let next = if matches!(trees.get(i + 1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket)
            {
                i + 2
            } else {
                i + 1
            };
            (
                Attr {
                    name,
                    value: AttrValue::Boolean,
                },
                next,
            )
        }
        _ => (
            Attr {
                name,
                value: AttrValue::Boolean,
            },
            i,
        ),
    }
}

/// Read an attribute value token following `=`.
fn read_attr_value(trees: &[TokenTree], i: usize) -> (AttrValue, usize) {
    match trees.get(i) {
        Some(TokenTree::Literal(lit)) => string_literal_value(lit)
            .map_or((AttrValue::Dynamic, i + 1), |v| {
                (AttrValue::Literal(v), i + 1)
            }),
        Some(TokenTree::Group(_) | TokenTree::Ident(_)) => (AttrValue::Dynamic, i + 1),
        // A control-flow / markup value: `attr=@if c { "x" }`,
        // `attr=@match s { _ => "c" }`. maud allows an attribute value to be a
        // `Markup` control; consume the control head + its brace group(s) (via the
        // same skipper the shorthand path uses) so the element body that follows
        // is still parsed rather than orphaned (which would fire a false
        // `button-name`/`link-name` on the parent). The value is unresolvable, so
        // it is recorded as `Dynamic` (non-failing).
        Some(TokenTree::Punct(p)) if p.as_char() == '@' => {
            (AttrValue::Dynamic, skip_shorthand_control(trees, i + 1))
        }
        _ => (AttrValue::Dynamic, i),
    }
}

/// Read a (possibly hyphenated or colon-qualified) name — `aria-label`,
/// `hx-post`, `x-on:click`, `svg:path`, `for` — starting at `start`. Returns the
/// joined name and the index just past it. maud names are a
/// `Punctuated<HtmlNameFragment, ':' | '-'>`, so both `-` and `:` continue the
/// name; consuming the whole name (including a colon-qualified suffix like
/// `x-on:click`) is essential — otherwise the leftover `:` ends the element
/// early and orphans its real `{ … }` body, firing a false `button-name`/
/// `link-name` on the parent.
fn read_name(trees: &[TokenTree], start: usize) -> (String, usize) {
    let Some(mut name) = name_segment(trees.get(start)) else {
        return (String::new(), start);
    };
    let mut i = start + 1;
    while let Some(TokenTree::Punct(p)) = trees.get(i) {
        let sep = p.as_char();
        if sep != '-' && sep != ':' {
            break;
        }
        let Some(seg) = name_segment(trees.get(i + 1)) else {
            break;
        };
        name.push(sep);
        name.push_str(&seg);
        i += 2;
    }
    (name, i)
}

/// The text of a single name segment. maud's `HtmlNameFragment` is an
/// identifier, an integer literal, or a string literal (`.col-12`, `data-1`,
/// `x-2` all use the integer variant), so all three continue a name. A
/// non-integer non-string literal (e.g. a float) is not a valid fragment and
/// ends the name.
fn name_segment(tree: Option<&TokenTree>) -> Option<String> {
    match tree {
        Some(TokenTree::Ident(id)) => Some(id.to_string()),
        Some(TokenTree::Literal(lit)) => {
            string_literal_value(lit).or_else(|| int_literal_text(lit))
        }
        _ => None,
    }
}

/// The digits of an integer literal (e.g. the `12` in `.col-12`), or `None` if
/// the literal is not an integer. maud accepts an integer as an `HtmlName`
/// fragment, so it must be consumed as part of the name.
fn int_literal_text(lit: &Literal) -> Option<String> {
    syn::parse2::<syn::LitInt>(TokenStream::from(TokenTree::Literal(lit.clone())))
        .ok()
        .map(|n| n.base10_digits().to_string())
}

/// The unescaped value of a string literal, or `None` for a non-string literal.
fn string_literal_value(lit: &Literal) -> Option<String> {
    syn::parse2::<syn::LitStr>(TokenStream::from(TokenTree::Literal(lit.clone())))
        .ok()
        .map(|s| s.value())
}

/// The text of a literal node — the string value if it is a string literal,
/// otherwise its raw token text (e.g. a bare number).
fn literal_text(lit: &Literal) -> String {
    string_literal_value(lit).unwrap_or_else(|| lit.to_string())
}

// ── Analysis ───────────────────────────────────────────────────────────────

/// Analyze one `html!` block's node tree, applying every rule.
fn analyze_block(nodes: &[Node], file: &str, scan: &mut Scan) {
    let mut label_fors = BTreeSet::new();
    let mut dynamic_label_for = false;
    collect_labels(nodes, &mut label_fors, &mut dynamic_label_for);
    walk(nodes, file, &label_fors, dynamic_label_for, false, scan);
}

/// Gather every `<label for="…">` literal in the block, and note whether any
/// label's `for` is a splice (which makes association unresolvable).
fn collect_labels(nodes: &[Node], fors: &mut BTreeSet<String>, dynamic: &mut bool) {
    for node in nodes {
        match node {
            Node::Element(el) => {
                // A `<label>` inside an `aria-hidden="true"` (or natively
                // `hidden`) subtree is not in the accessibility tree, so its
                // `for` association contributes no accessible name — skip the
                // element and its subtree entirely, consistent with `walk`'s
                // name derivation. A dynamic/spliced `aria-hidden=(…)`/`hidden=(…)`
                // stays non-hidden (conservative).
                if is_hidden(el) {
                    continue;
                }
                if el.name.eq_ignore_ascii_case("label") {
                    match el.attr("for") {
                        // Only a label that actually provides a name satisfies the
                        // association: an empty `<label for=..>` contributes no
                        // accessible name, so recording it would let an unlabeled
                        // control pass. A dynamic (spliced) body still counts, per
                        // the non-failing-splice convention (`label_provides_name`).
                        Some(AttrValue::Literal(v)) if label_provides_name(el) => {
                            fors.insert(v.clone());
                        }
                        Some(AttrValue::Dynamic) if label_provides_name(el) => *dynamic = true,
                        _ => {}
                    }
                }
                collect_labels(&el.children, fors, dynamic);
            }
            // A spliced fragment `(expr)` could render a `<label for=..>`, but
            // only one that is a DIRECT SIBLING of a control can label it. That
            // sibling-scoped suppression is handled in `walk`; recording it here
            // would (wrongly) mark the WHOLE block possibly-labeled, so an
            // unrelated nested splice like `p { (user.name) }` would suppress the
            // rule for every control in the block (false negative).
            Node::Dynamic { .. } | Node::Text(_) => {}
        }
    }
}

/// Label-association context threaded through the rule walk.
struct LabelCtx<'a> {
    /// Static `<label for="…">` ids collected across the block.
    fors: &'a BTreeSet<String>,
    /// A `<label for=(…)>` with a dynamic (spliced) target exists somewhere in
    /// the block — it could associate with any control, so it is block-wide.
    dynamic_for: bool,
    /// A splice that is a DIRECT SIBLING of the control could render a `<label>`
    /// fragment for it — sibling-scoped, recomputed per node list.
    sibling_splice: bool,
    /// We are inside a `<label>` that provides a name (which wraps the control).
    in_named_label: bool,
}

/// Recursively apply rules, tracking whether we are inside a `<label>` that
/// provides a name (so a control it wraps is considered labeled).
fn walk(
    nodes: &[Node],
    file: &str,
    fors: &BTreeSet<String>,
    dynamic_for: bool,
    in_named_label: bool,
    scan: &mut Scan,
) {
    // A splice that is a DIRECT SIBLING of a control could render a `<label>`
    // fragment for it, so its presence in THIS sibling list makes the
    // association unresolvable. A splice nested inside another element belongs to
    // a different sibling list and must not suppress controls here.
    let sibling_splice = nodes
        .iter()
        .any(|n| matches!(n, Node::Dynamic { splice: true }));
    let ctx = LabelCtx {
        fors,
        dynamic_for,
        sibling_splice,
        in_named_label,
    };
    for node in nodes {
        let Node::Element(el) = node else {
            continue;
        };
        // An element removed from the accessibility tree by `aria-hidden="true"`
        // or a native boolean `hidden` on ITSELF needs no accessible name, and
        // neither does its subtree — skip both rule application and recursion.
        if is_hidden(el) {
            continue;
        }
        apply_rules(el, file, &ctx, scan);
        let child_named_label =
            in_named_label || (el.name.eq_ignore_ascii_case("label") && label_provides_name(el));
        walk(
            &el.children,
            file,
            fors,
            dynamic_for,
            child_named_label,
            scan,
        );
    }
}

fn apply_rules(el: &Element, file: &str, ctx: &LabelCtx, scan: &mut Scan) {
    match el.name.to_ascii_lowercase().as_str() {
        // An `<img>` is named by `alt` (even empty `alt=""`, the decorative
        // marker), or — per the axe `image-alt` checks — by an
        // `aria-label`/`aria-labelledby`, a non-empty `title`, or an explicit
        // presentational role. Only a bare image with none of these is flagged.
        "img"
            if !has_alt_marker(el)
                && !el.has_aria_name()
                && !el.has_title_name()
                && !is_presentational(el) =>
        {
            scan.push(Rule::ImageAlt, "img", el.line, el.column, file);
        }
        name @ ("input" | "select" | "textarea") => {
            check_field(el, name, file, ctx, scan);
        }
        "button" if !named_content(el) => {
            scan.push(Rule::ButtonName, "button", el.line, el.column, file);
        }
        "a" if el.has_attr("href") && !named_content(el) => {
            scan.push(Rule::LinkName, "a", el.line, el.column, file);
        }
        _ => {}
    }
}

/// Rule 2: a form control needs an associated label or accessible name.
fn check_field(el: &Element, name: &str, file: &str, ctx: &LabelCtx, scan: &mut Scan) {
    // `<input type=…>` handling. Literal submit/hidden/button/reset/image
    // controls need no visible label. A spliced `type=(…)` is unresolvable —
    // it could be one of those non-labeling types, so skip rather than misfire
    // on valid markup (per the non-failing-splice convention).
    if name == "input" {
        match el.attr("type") {
            Some(AttrValue::Literal(ty))
                if ["hidden", "submit", "button", "reset", "image"]
                    .contains(&ty.to_ascii_lowercase().as_str()) =>
            {
                return;
            }
            Some(AttrValue::Dynamic) => return,
            _ => {}
        }
    }
    if el.has_aria_name() || el.has_title_name() || ctx.in_named_label {
        return;
    }
    match el.attr("id") {
        // A static id resolves against the collected `<label for>` set. A
        // dynamic `<label for=(…)>` elsewhere (`dynamic_for`) could target it,
        // and a splice that is a DIRECT SIBLING of this control could render a
        // `<label for=..>` fragment for it — either makes the association
        // unresolvable, so skip rather than risk a false positive.
        Some(AttrValue::Literal(id)) => {
            if ctx.fors.contains(id) || ctx.dynamic_for || ctx.sibling_splice {
                return;
            }
        }
        // A spliced id cannot be matched to a label — skip rather than misfire.
        Some(AttrValue::Dynamic) => return,
        _ => {}
    }
    scan.push(Rule::Label, name, el.line, el.column, file);
}

/// Whether an element has an accessible name from its own attributes or content:
/// an `aria-label`/`aria-labelledby` on the control itself, or — among the
/// descendants that are not hidden from the accessibility tree — visible text, a
/// dynamic (spliced) body, or a named child image. A dynamic subtree is
/// unresolvable, so it is treated as named (skip rather than misfire).
fn named_content(el: &Element) -> bool {
    el.has_aria_name() || el.has_title_name() || content_provides_name(&el.children)
}

/// Whether an element is hidden from the accessibility tree, either via a
/// literal `aria-hidden="true"` or via the native boolean `hidden` attribute.
/// Per ARIA/HTML such a subtree contributes nothing to an ancestor's accessible
/// name and its controls need no name. A dynamic/spliced `aria-hidden=(…)` or
/// `hidden=(…)` is unresolvable and treated as *not* hidden (conservative —
/// don't suppress a name on an unresolved splice); `aria-hidden="false"` or an
/// absent attribute are likewise not hidden. A present static `hidden` — bare
/// (`hidden`) or with any literal value (`hidden="until-found"`) — counts as
/// hidden, matching HTML's boolean-attribute semantics.
fn is_hidden(el: &Element) -> bool {
    let aria_hidden = matches!(
        el.attr("aria-hidden"),
        Some(AttrValue::Literal(v)) if v.eq_ignore_ascii_case("true")
    );
    let native_hidden = matches!(
        el.attr("hidden"),
        Some(AttrValue::Boolean | AttrValue::Literal(_))
    );
    aria_hidden || native_hidden
}

/// Whether descendant content contributes an accessible name to an enclosing
/// control: a dynamic (spliced) node, non-empty visible text, or a named
/// `<img>`. Subtrees hidden via a literal `aria-hidden="true"` or a native
/// boolean `hidden` are excluded — per ARIA/HTML their text does not count
/// toward the ancestor's accessible name.
fn content_provides_name(nodes: &[Node]) -> bool {
    nodes.iter().any(|n| match n {
        // Only a genuine `(expr)`/`[..]` splice renders text that could name the
        // control; an `@`-control head (`splice: false`) renders nothing itself
        // (its branch bodies were already parsed out), so it is not a name.
        Node::Dynamic { splice } => *splice,
        Node::Text(t) => !t.trim().is_empty(),
        Node::Element(e) if is_hidden(e) => false,
        Node::Element(e) => {
            // A descendant contributes a name via its own `aria-label`/
            // `aria-labelledby`/`title` (used during the name-from-content
            // traversal), a named child `<img alt>`, or its own descendants.
            e.has_aria_name()
                || e.has_title_name()
                || (e.name.eq_ignore_ascii_case("img") && attr_is_present_name(e.attr("alt")))
                || content_provides_name(&e.children)
        }
    })
}

/// Whether a `<label>` provides an accessible name to a control (whether it
/// wraps the control or associates via `for`). This uses the SAME accessible-
/// name walk as buttons and links (`content_provides_name`): visible text or a
/// dynamic (spliced) body counts, a named child `<img alt>` counts, and an
/// `aria-hidden="true"` subtree does NOT — its text is not an accessible name.
fn label_provides_name(el: &Element) -> bool {
    content_provides_name(&el.children)
}

// ── Output ─────────────────────────────────────────────────────────────────

const PRIMITIVE_NOTE: &str = "Note: code using the typed autumn_web::a11y primitives is proven \
accessible at compile time and is intentionally not re-scanned. This pass \
targets raw html! markup that bypasses those primitives.";

/// [`run_in_with`], with the default features of each crate only.
#[cfg(test)]
#[must_use]
pub fn run_in(root: &Path, opts: A11yVerifyOptions) -> i32 {
    run_in_with(root, opts, &CargoFeatures::default())
}

/// Verify `root`, print a report, and return the process exit code (non-zero
/// when findings meet the failure threshold). The `autumn a11y verify` command
/// calls this with the resolved project path and `std::process::exit`s on it.
/// `features` are read as on in addition to each crate's default features.
#[must_use]
pub fn run_in_with(root: &Path, opts: A11yVerifyOptions, features: &CargoFeatures) -> i32 {
    // An unreadable scan root is a hard failure, not an empty (PASS) audit:
    // surface the io error on stderr and exit non-zero so a CI path typo cannot
    // silently disable the whole check.
    let scan = match scan_project_with(root, features) {
        Ok(scan) => scan,
        Err(err) => {
            eprintln!("error: cannot read scan path '{}': {err}", root.display());
            return 1;
        }
    };
    let report = Report::from_scan(scan);
    match opts.format {
        OutputFormat::Json => print_json(&report),
        OutputFormat::Text => print_text(&report, opts.strict),
    }
    report.exit_code(opts.strict)
}

fn print_json(report: &Report) {
    match serde_json::to_string_pretty(report) {
        Ok(json) => println!("{json}"),
        Err(err) => eprintln!("autumn a11y verify: failed to serialize report: {err}"),
    }
}

fn print_text(report: &Report, strict: bool) {
    print!("{}", format_text(report, strict));
}

/// Render the human-readable report.
fn format_text(report: &Report, strict: bool) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(out, "autumn a11y verify");
    let _ = writeln!(
        out,
        "  scanned {} html! block(s) across {} .rs file(s)",
        report.html_blocks, report.files_scanned
    );
    let _ = writeln!(
        out,
        "  {} route(s) discovered, {} carrying findings",
        report.summary.routes, report.summary.routes_failing
    );
    let _ = writeln!(out, "  {PRIMITIVE_NOTE}");

    if report.findings.is_empty() {
        let _ = writeln!(
            out,
            "\nResult: PASS — no accessibility violations in raw html! markup."
        );
        return out;
    }

    let _ = writeln!(out, "\n  findings:");
    for f in &report.findings {
        let _ = writeln!(
            out,
            "    {}:{}: <{}> [WCAG {}] {} — {}",
            f.file, f.line, f.element, f.wcag, f.severity, f.message
        );
        if !f.routes.is_empty() {
            let _ = writeln!(out, "        routes: {}", f.routes.join(", "));
        }
        let _ = writeln!(out, "        hint: {}", f.hint);
    }

    let failing: Vec<&RouteConformance> = report.routes.iter().filter(|r| r.findings > 0).collect();
    if !failing.is_empty() {
        let _ = writeln!(out, "\n  failing routes:");
        for route in failing {
            let _ = writeln!(
                out,
                "    {} {} ({}) — {} finding(s)",
                route.method, route.path, route.handler, route.findings
            );
        }
    }

    let _ = writeln!(out, "\n  WCAG success criteria breached:");
    for criterion in &report.wcag {
        let _ = writeln!(
            out,
            "    WCAG {} — {} finding(s) [{}]",
            criterion.criterion,
            criterion.findings,
            criterion.rules.join(", ")
        );
    }

    let _ = writeln!(
        out,
        "\n  summary: {} Critical, {} Serious, {} Moderate ({} total, {} not reached by any route)",
        report.summary.critical,
        report.summary.serious,
        report.summary.moderate,
        report.summary.total,
        report.summary.unrouted,
    );
    if report.exit_code(strict) == 0 {
        let _ = writeln!(
            out,
            "Result: PASS with findings — below the failure threshold."
        );
    } else {
        let _ = writeln!(
            out,
            "Result: FAIL — fix the accessibility violations above (or use the typed primitives)."
        );
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Scan a single `html!`-bearing source snippet and return its findings.
    fn findings_for(src: &str) -> Vec<Finding> {
        let mut scan = Scan::default();
        scan_source(src, "view.rs", &mut scan);
        scan.findings
    }

    /// The set of rule ids flagged for a snippet.
    fn rule_ids(src: &str) -> Vec<&'static str> {
        let mut ids: Vec<&'static str> = findings_for(src).iter().map(|f| f.rule_id).collect();
        ids.sort_unstable();
        ids
    }

    fn wrap(markup: &str) -> String {
        format!("fn view() {{ let _ = html! {{ {markup} }}; }}")
    }

    // ── Rule 1: image-alt ──────────────────────────────────────────────────

    #[test]
    fn alt_less_img_is_flagged() {
        let src = wrap(r#"img src="x.png";"#);
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "image-alt");
        assert_eq!(f[0].wcag, "1.1.1");
        assert_eq!(f[0].severity, Severity::Serious);
    }

    #[test]
    fn img_with_alt_is_clean() {
        let src = wrap(r#"img src="x.png" alt="A logo";"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn img_with_empty_alt_is_clean() {
        // An explicit decorative alt="" is a valid accessible marker.
        let src = wrap(r#"img src="divider.png" alt="";"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn img_with_dynamic_alt_is_clean() {
        let src = wrap(r#"img src="x.png" alt=(caption);"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn img_with_whitespace_alt_is_flagged() {
        // A whitespace-only `alt="  "` collapses to an empty accessible name and
        // is not a valid decorative marker (only exact `alt=""` is) — flagged.
        let src = wrap(r#"img src="x" alt="  ";"#);
        assert_eq!(
            rule_ids(&src),
            vec!["image-alt"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn button_with_whitespace_aria_label_is_flagged() {
        // A whitespace-only static `aria-label="   "` supplies no accessible name.
        let src = wrap(r#"button aria-label="   " { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn button_with_real_aria_label_is_clean() {
        // A non-blank static `aria-label` is a present accessible name — clean.
        let src = wrap(r#"button aria-label="Close" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_whitespace_title_and_no_label_is_flagged() {
        // A whitespace-only `title=" "` is not a name; with no label the field is
        // flagged.
        let src = wrap(r#"input title=" " id="q";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── Rule 2: label ──────────────────────────────────────────────────────

    #[test]
    fn unlabeled_input_is_flagged() {
        let src = wrap(r#"input type="text" id="name";"#);
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "label");
        assert_eq!(f[0].wcag, "1.3.1 / 3.3.2 / 4.1.2");
        assert_eq!(f[0].element, "input");
    }

    #[test]
    fn input_with_matching_label_for_is_clean() {
        let src = wrap(r#"label for="name" { "Name" } input type="text" id="name";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_aria_label_is_clean() {
        let src = wrap(r#"input type="text" aria-label="Search";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_empty_aria_label_is_flagged() {
        let src = wrap(r#"input type="text" aria-label="";"#);
        assert_eq!(rule_ids(&src), vec!["label"]);
    }

    #[test]
    fn wrapped_label_with_text_is_clean() {
        let src = wrap(r#"label { "Name" input type="text"; }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn hidden_input_needs_no_label() {
        let src = wrap(r#"input type="hidden" name="_csrf";"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn unlabeled_select_and_textarea_are_flagged() {
        let src = wrap(r#"select id="role" { } textarea id="bio" { }"#);
        assert_eq!(rule_ids(&src), vec!["label", "label"]);
    }

    #[test]
    fn input_with_dynamic_id_is_not_flagged() {
        // A spliced id cannot be matched to a label — skip rather than misfire.
        let src = wrap(r#"input type="text" id=(field_id);"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn empty_label_for_does_not_satisfy_association() {
        // An empty `<label for=..>` provides no accessible name, so the
        // associated control must still be flagged (regression: false negative).
        let src = wrap(r#"label for="email" { } input type="text" id="email";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn labeled_input_via_for_with_text_is_clean() {
        // A `<label for=..>` with real text satisfies the association.
        let src = wrap(r#"label for="email" { "Email" } input type="text" id="email";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn label_for_with_dynamic_body_is_clean() {
        // A spliced label body is unresolvable and counts as providing a name.
        let src = wrap(r#"label for="email" { (title) } input type="text" id="email";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn dynamic_for_label_with_empty_body_does_not_satisfy_association() {
        // A spliced-`for` label with a statically EMPTY body provides no
        // accessible name, so a static-id control must still be flagged. The
        // dynamic-`for` marker must carry the same `label_provides_name` guard as
        // the literal-`for` path (regression: false negative).
        let src = wrap(r#"label for=(id) { } input type="text" id="email";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn dynamic_for_label_with_dynamic_body_is_clean() {
        // A spliced-`for` label with a dynamic (spliced) body counts as providing
        // a name, per the non-failing-splice convention.
        let src = wrap(r#"label for=(id) { (title) } input type="text" id="email";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn dynamic_for_label_with_text_body_is_clean() {
        // A spliced-`for` label with real text provides a name.
        let src = wrap(r#"label for=(id) { "Email" } input type="text" id="email";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_dynamic_type_is_not_flagged() {
        // A spliced `type=(…)` is unresolvable — it may be a non-labeling type
        // like submit/button, so skip rather than misfire (regression: false
        // positive).
        let src = wrap(r#"input type=(kind) value="Save";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_literal_text_type_still_flagged() {
        // A literal text-like type with no label is still flagged.
        let src = wrap(r#"input type="text";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn spliced_label_fragment_beside_control_is_not_flagged() {
        // A label composed as a separate fragment and spliced next to the raw
        // control could render a `<label for=..>`; the association is
        // unresolvable, so per the non-failing-splice convention the control is
        // treated as possibly-labeled (regression: false positive).
        let src = wrap(r#"(field_label) input id="email";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn unlabeled_input_with_no_splice_is_still_flagged() {
        // With no spliced fragment anywhere in the block, an unlabeled control
        // must still be flagged — the fragment marker must not suppress unrelated
        // static controls.
        let src = wrap(r#"input id="x";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── Rule 3: button-name ────────────────────────────────────────────────

    #[test]
    fn empty_button_is_flagged() {
        let src = wrap(r"button { }");
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "button-name");
        assert_eq!(f[0].wcag, "4.1.2");
    }

    #[test]
    fn button_with_text_is_clean() {
        let src = wrap(r#"button { "Save" }"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn button_with_aria_label_is_clean() {
        let src = wrap(r#"button aria-label="Close" { }"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn icon_button_with_alt_image_is_clean() {
        let src = wrap(r#"button { img src="trash.svg" alt="Delete"; }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_dynamic_content_is_not_flagged() {
        let src = wrap(r"button { (label_text) }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_only_control_head_is_flagged() {
        // The only child is an `@if` control HEAD (`splice: false`), whose branch
        // bodies were parsed out — it renders no accessible text. A definitively
        // nameless button must still be flagged (regression: false negative — a
        // control head was wrongly counted as a name).
        let src = wrap(r"button { @if disabled { } }");
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "button-name");
    }

    #[test]
    fn button_with_real_splice_content_is_clean() {
        // A genuine `(expr)` splice body could render the button's name, so it is
        // treated as named (unchanged; guards against over-correcting the head fix).
        let src = wrap(r"button { (label) }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    // ── Rule 4: link-name ──────────────────────────────────────────────────

    #[test]
    fn textless_anchor_is_flagged() {
        let src = wrap(r#"a href="/x" { }"#);
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "link-name");
        assert_eq!(f[0].wcag, "2.4.4 / 4.1.2");
    }

    #[test]
    fn anchor_with_text_is_clean() {
        let src = wrap(r#"a href="/x" { "About us" }"#);
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn anchor_without_href_is_not_flagged() {
        // Rule 4 only fires for anchors that carry an href.
        let src = wrap(r"a { }");
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn icon_anchor_with_aria_label_is_clean() {
        let src = wrap(r#"a href="https://example.com" aria-label="GitHub" { }"#);
        assert!(findings_for(&src).is_empty());
    }

    // ── aria-hidden subtrees don't count toward the accessible name ─────────

    #[test]
    fn icon_button_with_aria_hidden_glyph_is_flagged() {
        // The only content is an `aria-hidden="true"` glyph, which per ARIA does
        // not contribute an accessible name — the button is effectively nameless.
        let src = wrap(r#"button { span aria-hidden="true" { "×" } }"#);
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "button-name");
    }

    #[test]
    fn icon_anchor_with_aria_hidden_glyph_is_flagged() {
        let src = wrap(r#"a href="/x" { span aria-hidden="true" { "🔍" } }"#);
        let f = findings_for(&src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "link-name");
    }

    #[test]
    fn button_with_hidden_glyph_and_visible_text_is_clean() {
        // The visible "Close" text still provides an accessible name.
        let src = wrap(r#"button { span aria-hidden="true" { "×" } "Close" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_hidden_glyph_and_aria_label_is_clean() {
        // The `aria-label` on the control itself provides the name.
        let src = wrap(r#"button aria-label="Close" { span aria-hidden="true" { "×" } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_dynamic_aria_hidden_glyph_is_not_flagged() {
        // A spliced `aria-hidden=(…)` is unresolvable, so the subtree is treated
        // as not hidden and its text still counts — conservative, no new false
        // positive on valid dynamic markup.
        let src = wrap(r#"button { span aria-hidden=(flag) { "×" } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn label_with_only_aria_hidden_text_does_not_satisfy_association() {
        // The `<label>` body is entirely `aria-hidden="true"`, which per ARIA
        // contributes no accessible name — the label check must use the same
        // hidden-excluding name walk as buttons/links, so the field is FLAGGED
        // (regression: false negative — hidden text was wrongly accepted).
        let src = wrap(r#"label for="q" { span aria-hidden="true" { "Search" } } input id="q";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn label_with_only_control_head_does_not_satisfy_association() {
        // The `<label>` body is only an `@if` control HEAD (`splice: false`),
        // which renders no accessible name — so the associated field must still be
        // FLAGGED (regression: false negative — a control head was wrongly counted
        // as a name).
        let src = wrap(r#"label for="q" { @if show { } } input id="q";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn label_with_alt_image_satisfies_association() {
        // A `<label>` whose only content is an `<img alt=..>` has an accessible
        // name via the alt text, so the associated field is CLEAN (regression:
        // false positive — the img alt was previously ignored).
        let src = wrap(r#"label for="q" { img src="s.svg" alt="Search"; } input id="q";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn label_with_plain_text_still_satisfies_association() {
        // Unchanged: a `<label for=..>` with real visible text names the field.
        let src = wrap(r#"label for="e" { "Email" } input id="e";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn empty_label_body_still_does_not_satisfy_association() {
        // Unchanged: an empty `<label for=..>` provides no accessible name, so
        // the associated field is FLAGGED.
        let src = wrap(r#"label for="e" { } input id="e";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn label_in_aria_hidden_container_does_not_satisfy_association() {
        // Regression (false negative): a `<label for=..>` that only exists inside
        // an `aria-hidden="true"` subtree is not in the accessibility tree, so it
        // provides no accessible name. `collect_labels` must stop descending into
        // hidden subtrees (like `walk`), so the visible input is FLAGGED.
        let src = wrap(r#"div aria-hidden="true" { label for="q" { "Search" } } input id="q";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn label_in_visible_container_satisfies_association() {
        // Unchanged: a `<label for=..>` inside a visible container is in the
        // accessibility tree and names the associated input, so it is CLEAN.
        let src = wrap(r#"div { label for="q" { "Search" } } input id="q";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    // ── Escape-hatch / dynamic limits ──────────────────────────────────────

    #[test]
    fn typed_primitive_splice_is_not_flagged() {
        // `(Img::new(..))` is a splice, not an `img` element, so the compile-time
        // guarantee is respected and nothing is re-scanned.
        let src = wrap(r"(autumn_web::a11y::Img::new(src, alt))");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn fully_dynamic_splice_is_not_flagged() {
        let src = wrap(r"(rendered_widget)");
        assert!(findings_for(&src).is_empty());
    }

    #[test]
    fn element_inside_control_block_is_still_scanned() {
        let src = wrap(r#"@if show { img src="x.png"; }"#);
        assert_eq!(rule_ids(&src), vec!["image-alt"]);
    }

    #[test]
    fn match_arm_pattern_named_input_is_not_flagged() {
        // Regression: an `@match` arm whose PATTERN is named `input` must not be
        // read as an `<input>` element. Parsing the arm list as markup produced a
        // false `label` finding on valid views.
        let src = wrap(r#"@match field { input => { "text" } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn match_arm_body_real_input_is_still_flagged() {
        // The arm PATTERN is skipped, but the arm BODY is still scanned: a real
        // unlabeled `<input>` inside an arm body must still be flagged.
        let src = wrap(r"@match x { A => { input; } }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn match_arm_with_guard_does_not_misparse() {
        // A guard (`Pattern if cond => …`) sits between the pattern and `=>` and
        // must be skipped along with the pattern — no crash, no false finding.
        let src = wrap(r#"@match x { A if ready => { "ok" } B => { "no" } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn match_multiple_arms_scan_each_body() {
        // Several arms, mixed body shapes: only the real markup in bodies counts.
        // The `input` pattern must not flag; the alt-less `<img>` body must.
        let src = wrap(r#"@match k { input => { "a" } other => { img src="x.png"; } }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["image-alt"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn let_initializer_struct_literal_is_not_parsed_as_markup() {
        // Regression: `@let props = Field { input: true };` binds a Rust
        // expression, so its brace group is struct-literal syntax, not markup.
        // Parsing it as markup misread the Rust field `input` as an `<input>`
        // element and fired a false `label` finding on valid views.
        let src = wrap(r#"@let props = Field { input: true }; div { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn let_binding_does_not_suppress_real_input_elsewhere() {
        // The `@let` initializer is skipped wholesale, but a real unlabeled
        // `<input>` later in the same markup must still be flagged.
        let src = wrap(r#"@let props = Field { input: true }; input type="text" id="name";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn let_with_plain_initializer_does_not_crash() {
        // A plain (non-struct) `@let` initializer parses without panicking.
        let src = wrap(r#"@let x = foo(); div { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn let_after_control_reaches_its_skip_handler() {
        // Regression: only `@else` continues a control chain. A `@let` following a
        // parsed control block must be returned to `parse_nodes` so it hits
        // `skip_let` — otherwise its `Field { input: true }` struct literal is
        // misparsed as markup and fires a bogus `<input>` finding (false positive).
        let src = wrap(r#"@if show { "ok" } @let props = Field { input: true };"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_else_chain_still_parses_and_flags_real_input() {
        // A genuine `@if … @else …` chain still parses across the `@else`, and a
        // real unlabeled `<input>` in the `@if` body is still flagged.
        let src = wrap(r#"@if c { input; } @else { "x" }"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn while_body_element_is_scanned() {
        // `@while cond { body }`: the body is markup and is scanned, so a real
        // unlabeled `<input>` in a `@while` body is still flagged.
        let src = wrap(r"@while more { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn for_struct_pattern_is_not_parsed_as_markup() {
        // Regression (false positive): a `@for` loop destructuring a struct
        // pattern (`@for Field { input, .. } in fields`) has BRACES in the
        // pattern that are NOT markup. Parsing them misread the Rust field
        // `input` as an `<input>` element.
        let src = wrap(r#"@for Field { input, label } in fields { "row" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn for_body_real_input_is_still_flagged() {
        // The `@for` pattern is skipped, but the body is still scanned.
        let src = wrap(r"@for x in items { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn if_let_struct_pattern_is_not_parsed_as_markup() {
        // Regression (false positive): `@if let Field { input } = props { .. }`
        // has a struct PATTERN brace that is not markup.
        let src = wrap(r#"@if let Field { input } = props { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn while_let_struct_pattern_is_not_parsed_as_markup() {
        let src = wrap(r#"@while let Field { input } = next() { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_let_body_real_input_is_still_flagged() {
        // The `if let` pattern is skipped, but the body is scanned.
        let src = wrap(r"@if let Some(x) = maybe { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn if_block_expression_condition_is_not_parsed_as_markup() {
        // Regression (false positive): maud parses the condition with
        // `parse_without_eager_brace`, so a block-expression condition
        // (`@if { input } { body }`) is valid — the FIRST brace is the condition,
        // the LAST is the markup body. The condition must NOT be parsed as markup.
        let src = wrap(r#"@if { input } { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_block_expression_condition_body_is_still_scanned() {
        // The block-expression condition is skipped, but the body IS scanned: a
        // real unlabeled `<input>` in the body must still be flagged.
        let src = wrap(r"@if { ready } { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn else_if_block_expression_condition_is_not_parsed_as_markup() {
        // The block-expression handling also applies across an `@else if` chain.
        let src = wrap(r#"@if a { "a" } @else if { input } { "b" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_body_then_sibling_block_still_scans_body() {
        // `@if a { body } { sibling }`: the first brace is the body (a condition
        // token `a` precedes it), the second is a sibling markup block. Both are
        // scanned, so a real `<input>` in EITHER is flagged.
        let src = wrap(r"@if a { input; } { button { } }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name", "label"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn match_block_expression_scrutinee_is_not_parsed_as_markup() {
        // Regression (false positive): a `@match` scrutinee is parsed with
        // `parse_without_eager_brace`, so a block-expression scrutinee
        // (`@match { input } { arms }`) is valid — the first brace is the
        // scrutinee, the second is the arm list. The scrutinee must not be markup.
        let src = wrap(r#"@match { input } { A => { "a" } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn match_block_expression_scrutinee_arm_body_still_scanned() {
        let src = wrap(r"@match { flag } { A => { input; } }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn if_match_condition_arm_list_is_not_parsed_as_markup() {
        // Regression (false positive): a `match` expression IN the `@if` condition
        // owns its arm-list brace — that brace is part of the condition, and the
        // real markup body is the FINAL `{ "ok" }`. The arm pattern `input` must
        // NOT be misread as an `<input>`, and the body must be scanned.
        let src = wrap(r#"@if match state { input => true, _ => false } { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_simple_condition_body_input_still_flagged() {
        // A plain `@if cond { body }` still parses the body: a real unlabeled
        // `<input>` is flagged (no match brace to confuse the head).
        let src = wrap(r"@if cond { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn while_comparison_condition_body_is_scanned() {
        // `@while x > 0 { button { } }`: the comparison is the condition and the
        // body is scanned — the empty button is flagged.
        let src = wrap(r"@while x > 0 { button { } }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn if_macro_condition_is_not_parsed_as_markup() {
        // Regression (false positive): a Rust macro call in the `@if` condition
        // (`@if ready! { input } { "ok" }`) owns its `!`-delimited brace group —
        // that group is macro input, part of the condition, and the real markup
        // body is the FINAL `{ "ok" }`. The macro's `input` token must NOT be
        // misread as a phantom `<input>`, and the body must be scanned.
        let src = wrap(r#"@if ready! { input } { "ok" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_macro_condition_body_is_still_scanned() {
        // The macro condition is skipped, but the body IS scanned: an empty
        // `<button>` in the body is still flagged (the body brace was correctly
        // identified past the macro's group).
        let src = wrap(r"@if ready! { input } { button { } }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn if_non_macro_condition_body_input_still_flagged() {
        // A plain `@if cond { input; }` (no macro) still parses the body, so a
        // real unlabeled `<input>` is flagged — the macro handling does not
        // change the macro-free path.
        let src = wrap(r"@if cond { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── element tag names: custom `-` / namespaced `:` ──────────────────────

    #[test]
    fn custom_hyphenated_tag_is_not_flagged() {
        // Regression (false positive): a maud element name is a full `HtmlName`
        // (`Punctuated<HtmlNameFragment, '-' | ':'>`), so `x-input` is ONE custom
        // tag that matches no rule. Reading only the first ident (`x`) would leave
        // `-input` in the stream and misfire a `label` on a phantom `<input>`.
        let src = wrap(r"x-input;");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn custom_hyphenated_tag_with_body_is_not_flagged() {
        // `x-button { }` is a single custom tag (no `button-name` rule applies),
        // not a `<button>` — its `{ }` body is parsed normally.
        let src = wrap(r"x-button { }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn namespaced_colon_tag_is_not_flagged() {
        // A colon-namespaced tag `svg:rect` is one `HtmlName`, matching no rule.
        let src = wrap(r"svg:rect;");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn plain_input_tag_is_still_flagged() {
        // A plain `input;` (no `-`/`:` continuation) is a real `<input>` and is
        // still flagged — the full-name read does not affect simple tag names.
        let src = wrap(r"input;");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn plain_button_tag_is_still_flagged() {
        // A plain empty `button { }` is still flagged for a missing name.
        let src = wrap(r"button { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── maud class/id shorthand (dynamic + toggled) ─────────────────────────

    #[test]
    fn dynamic_class_shorthand_does_not_orphan_body() {
        // Regression (false positive): a dynamic class shorthand `.(expr)` must
        // be consumed, else the element ends early and its `{ … }` body is
        // orphaned — here the button would lose its "Save" text and be flagged.
        let src = wrap(r#"button.(cls) { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn dynamic_class_shorthand_empty_button_still_flagged() {
        // The shorthand is consumed, but a genuinely empty button is still caught.
        let src = wrap(r"button.(cls) { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn toggled_class_shorthand_does_not_orphan_body() {
        // A toggled class `.name[cond]` must be consumed along with its bracket.
        let src = wrap(r#"a.icon[active] href="/x" { "Home" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn toggled_class_shorthand_empty_link_still_flagged() {
        let src = wrap(r#"a.icon[active] href="/x" { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["link-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn dynamic_id_shorthand_is_treated_as_dynamic() {
        // A dynamic id `#(expr)` cannot be matched to a label — skip like
        // `id=(expr)` rather than misfire.
        let src = wrap(r#"input#(field_id) type="text";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn static_id_shorthand_matches_label_for() {
        // A static `#id` shorthand records an id that a `<label for>` can match.
        let src = wrap(r#"label for="name" { "Name" } input#name type="text";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn unlabeled_id_shorthand_input_is_flagged() {
        // A static `#id` shorthand with no matching label is still flagged.
        let src = wrap(r#"input#name type="text";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── maud implicit-div leading shorthand (no explicit tag) ───────────────

    #[test]
    fn leading_class_shorthand_is_implicit_div_not_input() {
        // Regression (false positive): `.input { }` is an implicit `<div
        // class="input">`, NOT an `<input>` element — the class token is a VALUE,
        // not a tag. A `<div>` triggers no rule, so nothing is flagged.
        let src = wrap(r".input { }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn leading_id_shorthand_is_implicit_div_not_button() {
        // `#button { }` is an implicit `<div id="button">`, not a `<button>`.
        let src = wrap(r"#button { }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn leading_class_shorthand_with_text_is_implicit_div() {
        // `.input { "x" }` is still an implicit `<div>`; its text body is not a
        // control name obligation.
        let src = wrap(r#".input { "x" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn implicit_div_wrapping_real_input_still_flags_inner_input() {
        // The implicit `<div class="card">` triggers no rule itself, but its body
        // is still scanned: a real unlabeled `<input>` inside is STILL flagged.
        let src = wrap(r".card { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── maud markup-valued class shorthand (`.@if c { "x" }`) ────────────────

    #[test]
    fn markup_valued_class_shorthand_does_not_truncate_button() {
        // Regression (false positive): `.@if primary { "primary" }` is a
        // MARKUP-valued class value; the button's real body is the FOLLOWING
        // `{ "Save" }`. The class control must be fully consumed so the body is
        // parsed — otherwise the button is analyzed as empty and falsely flagged.
        let src = wrap(r#"button.@if primary { "primary" } { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn markup_valued_class_shorthand_empty_button_still_flagged() {
        // The markup class value is consumed, but a genuinely empty body is still
        // caught (no over-correction into a false negative).
        let src = wrap(r#"button.@if primary { "primary" } { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn markup_valued_class_shorthand_before_attr_and_body_is_clean() {
        // A markup class value followed by a real attribute and body: the anchor
        // keeps its `href` and its `{ "Link" }` text, so it is not flagged.
        let src = wrap(r#"a.@if c { "x" } href="/y" { "Link" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn splice_valued_class_shorthand_stays_clean() {
        // A splice-valued class `.(dynamic_class)` was already handled; it must
        // stay clean (the button keeps its "Save" body).
        let src = wrap(r#"button.(dynamic_class) { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    // ── colon-qualified maud names (x-on:click, data:foo, svg:path) ─────────

    #[test]
    fn colon_qualified_attr_name_does_not_orphan_button_body() {
        // Regression (false positive): maud names allow `:` (and `-`), so an
        // Alpine/Vue-style `x-on:click` attribute must be read as ONE name. If the
        // scanner stopped at the `:`, the leftover token ends the element early and
        // orphans its `{ "Save" }` body — the button is analyzed as empty and
        // falsely flagged.
        let src = wrap(r#"button x-on:click="save" { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn colon_qualified_attr_name_empty_button_still_flagged() {
        // The colon-qualified name is consumed, but a genuinely empty button is
        // still caught (no over-correction into a false negative).
        let src = wrap(r#"button x-on:click="save" { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn colon_qualified_attr_on_link_is_clean() {
        // A colon-qualified `data:foo` attribute must not truncate the anchor: it
        // keeps its `href` and its `{ "Link" }` text, so it is not flagged.
        let src = wrap(r#"a href="/x" data:foo="y" { "Link" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    // ── numeric maud name fragments (.col-12, data-1, x-2) ──────────────────

    #[test]
    fn numeric_class_shorthand_does_not_orphan_button_body() {
        // Regression (false positive): maud `HtmlName` fragments may be integers,
        // so `.col-12` is ONE class name. If the reader stopped at the numeric
        // fragment the leftover `-12` ends the element early and orphans its
        // `{ "Save" }` body — the button is analyzed as empty and falsely flagged.
        let src = wrap(r#"button.col-12 { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn numeric_attr_name_does_not_orphan_button_body() {
        // A numeric attribute-name fragment (`data-1`) must be read as one name so
        // the button's `{ "Save" }` body is still parsed.
        let src = wrap(r#"button data-1="x" { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn numeric_class_shorthand_on_link_is_clean() {
        // An anchor with a numeric class shorthand keeps its `href` and `{ "Link" }`
        // text, so it is not flagged.
        let src = wrap(r#"a.col-6 href="/x" { "Link" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn numeric_class_shorthand_empty_button_still_flagged() {
        // The numeric class name is consumed correctly, but a genuinely empty body
        // is still caught (no over-correction into a false negative).
        let src = wrap(r"button.col-12 { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn plain_empty_button_without_numeric_name_still_flagged() {
        // A plain nameless button is unaffected by the numeric-fragment fix.
        let src = wrap(r"button { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── quoted (string-literal) attribute names ─────────────────────────────

    #[test]
    fn quoted_attr_name_does_not_orphan_button_body() {
        // Regression (false positive): maud accepts a STRING-LITERAL attribute
        // name (`"@click"`). If it is not recognized as an attribute name the
        // element ends early and orphans its `{ "Save" }` body — the button is
        // analyzed as empty and falsely flagged.
        let src = wrap(r#"button "@click"="save" { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn quoted_aria_label_provides_accessible_name() {
        // A quoted `"aria-label"` name is recorded like the ident form, so its
        // static value supplies the accessible name — a labelless `<input>` with
        // an `aria-label` is not flagged.
        let src = wrap(r#"input "aria-label"="Search";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn quoted_non_name_attr_consumed_empty_button_still_flagged() {
        // The quoted attribute is consumed, but it supplies no accessible name and
        // the body is empty — a genuinely nameless button is still caught.
        let src = wrap(r#"button "data-x"="y" { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── control-valued / markup-valued attributes (`attr=@if …`) ────────────

    #[test]
    fn match_valued_attr_does_not_truncate_button() {
        // Regression (false positive): a maud attribute value may be a control
        // (`class=@match state { _ => "primary" }`). The control must be fully
        // consumed so the button's real `{ "Save" }` body is parsed — otherwise
        // the button is analyzed as empty and falsely flagged.
        let src = wrap(r#"button class=@match state { _ => "primary" } { "Save" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_valued_attr_after_real_attr_stays_clean() {
        // An `@if`-valued attribute following a real `href` must not truncate the
        // anchor: it keeps its `{ "Link" }` text, so it is not flagged.
        let src = wrap(r#"a href="/x" class=@if hot { "hot" } { "Link" }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn if_valued_attr_empty_button_still_flagged() {
        // The control value is consumed, but a genuinely empty body is still
        // caught (no over-correction into a false negative).
        let src = wrap(r#"button class=@if c { "x" } { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn match_valued_attr_then_id_unlabeled_input_still_flagged() {
        // The control value is consumed and the following `id="q"` attribute is
        // parsed, but with no matching label the input is still flagged.
        let src = wrap(r#"input class=@match s { _ => "c" } id="q";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── aria-hidden on the control itself ───────────────────────────────────

    #[test]
    fn aria_hidden_button_needs_no_name() {
        // A `<button aria-hidden="true">` is removed from the accessibility tree,
        // so it needs no accessible name (regression: false positive).
        let src = wrap(r#"button aria-hidden="true" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn aria_hidden_link_needs_no_name() {
        let src = wrap(r#"a href="/x" aria-hidden="true" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn aria_hidden_img_needs_no_alt() {
        let src = wrap(r#"img src="x.png" aria-hidden="true";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn aria_hidden_subtree_control_is_exempt() {
        // A control nested inside an `aria-hidden="true"` subtree is hidden too.
        let src = wrap(r#"div aria-hidden="true" { input type="text"; }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn visible_sibling_of_aria_hidden_control_still_flagged() {
        // The hidden button is exempt; the visible empty button beside it is not.
        let src = wrap(r#"button aria-hidden="true" { } button { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn dynamic_aria_hidden_control_is_still_checked() {
        // A spliced `aria-hidden=(…)` is unresolvable → treated as NOT hidden, so
        // a nameless button is still flagged (no new false negative).
        let src = wrap(r"button aria-hidden=(flag) { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── native boolean `hidden` attribute ───────────────────────────────────

    #[test]
    fn native_hidden_button_needs_no_name() {
        // A `<button hidden>` is removed from the accessibility tree, so it needs
        // no accessible name (regression: false positive on valid markup).
        let src = wrap(r"button hidden { }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn native_hidden_subtree_control_is_exempt() {
        // A control nested inside a natively `hidden` subtree is hidden too, so its
        // subtree is skipped and the inner input is not flagged.
        let src = wrap(r"div hidden { input; }");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn native_hidden_with_literal_value_needs_no_name() {
        // `hidden="until-found"` is a present static boolean `hidden` (HTML treats
        // any value as hidden), so the button is exempt.
        let src = wrap(r#"button hidden="until-found" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_without_hidden_still_flagged() {
        // A nameless button with no `hidden` attribute is unaffected by the fix.
        let src = wrap(r"button { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn visible_subtree_control_without_hidden_still_flagged() {
        // A `<div>` without `hidden` does not hide its input — the labelless input
        // is still flagged (no new false negative).
        let src = wrap(r"div { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn dynamic_hidden_control_is_still_checked() {
        // A spliced `hidden=(…)` is unresolvable → treated as NOT hidden, so a
        // nameless button is still flagged (conservative, no new false negative).
        let src = wrap(r"button hidden=(flag) { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── title as a last-resort accessible name ──────────────────────────────

    #[test]
    fn button_with_title_is_clean() {
        // Per the ARIA accessible-name computation `title` is a last-resort name.
        let src = wrap(r#"button title="Close" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_empty_title_is_flagged() {
        // An empty `title` provides no name, so the button is still flagged.
        let src = wrap(r#"button title="" { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn link_with_title_is_clean() {
        let src = wrap(r#"a href="/x" title="Home" { }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_title_is_clean() {
        let src = wrap(r#"input type="text" title="Full name";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn input_with_empty_title_is_flagged() {
        let src = wrap(r#"input type="text" title="";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    // ── img named via aria/title/role, not just alt ─────────────────────────

    #[test]
    fn img_with_aria_label_is_clean() {
        // An `<img>` named by `aria-label` has an accessible name (regression:
        // false positive — only `alt` was previously accepted).
        let src = wrap(r#"img src="x.png" aria-label="Logo";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn img_with_presentation_role_is_clean() {
        // A decorative `role="presentation"`/`role="none"` image needs no alt.
        let src = wrap(r#"img src="divider.png" role="presentation";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
        let src = wrap(r#"img src="divider.png" role="none";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn img_with_dynamic_role_is_clean() {
        // A spliced `role=(…)` is unresolvable and could be presentational — skip.
        let src = wrap(r"img src=(s) role=(r);");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn img_with_title_is_clean() {
        let src = wrap(r#"img src="x.png" title="Logo";"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn img_with_no_name_source_is_still_flagged() {
        // Baseline: an image with a non-presentational role and no name is caught.
        let src = wrap(r#"img src="x.png" role="img";"#);
        assert_eq!(
            rule_ids(&src),
            vec!["image-alt"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── name from a descendant's aria-label ──────────────────────────────────

    #[test]
    fn button_named_by_child_aria_label_is_clean() {
        // A descendant's `aria-label` contributes to the name-from-content walk.
        let src = wrap(r#"button { span aria-label="Close" { } }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn button_with_nameless_child_is_still_flagged() {
        // A child with no name of its own leaves the button nameless.
        let src = wrap(r"button { span { } }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    // ── sibling-scoped splice suppression (not block-wide) ──────────────────

    #[test]
    fn nested_splice_does_not_suppress_unrelated_control() {
        // Regression (false negative): a splice nested inside another element
        // (`p { (user.name) }`) is unrelated to labeling and must NOT suppress the
        // unlabeled-control rule for a control elsewhere in the block.
        let src = wrap(r#"p { (user.name) } input type="text" id="email";"#);
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn direct_sibling_splice_still_suppresses_nested_control() {
        // A splice that is a DIRECT SIBLING of the control (even nested one level
        // deep) could render a `<label>` fragment for it — still suppressed.
        let src = wrap(r#"div { (field_label) input type="text" id="email"; }"#);
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn multiple_findings_across_one_block() {
        let src = wrap(r#"img src="a.png"; button { } a href="/x" { }"#);
        assert_eq!(
            rule_ids(&src),
            vec!["button-name", "image-alt", "link-name"]
        );
    }

    #[test]
    fn json_report_is_keyed_to_wcag() {
        let src = wrap(r#"img src="x.png";"#);
        let mut scan = Scan::default();
        scan_source(&src, "view.rs", &mut scan);
        let report = Report::from_scan(scan);
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("\"wcag\":\"1.1.1\""), "{json}");
        assert!(json.contains("\"severity\":\"Serious\""), "{json}");
        assert!(json.contains("\"rule_id\":\"image-alt\""), "{json}");
    }

    // ── non-maud html! (JSX/Yew island) is skipped, not misparsed ───────────

    #[test]
    fn jsx_html_button_is_skipped() {
        // Regression (false positive): a DIFFERENT `html!` (e.g. a Yew/JSX island)
        // uses `<tag>…</tag>` angle-bracket syntax that maud never uses. Parsing it
        // as maud would strip the brackets and misread `<button></button>` as an
        // empty maud `button`. The body is detected as JSX and skipped — no finding.
        let src = wrap(r"<button>{label}</button>");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn jsx_html_div_input_is_skipped() {
        // A JSX island with self-closing tags (`<input/>`) is likewise skipped.
        let src = wrap(r"<div><input/></div>");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn real_maud_button_still_analyzed_after_jsx_skip() {
        // The JSX skip must not silence real maud: an empty maud `button { }` (no
        // angle brackets) is STILL parsed and flagged.
        let src = wrap(r"button { }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn maud_comparison_in_if_head_is_not_misread_as_jsx() {
        // Regression (false negative): a `<`/`>` comparison in a control head is a
        // normal Rust comparison, NOT a JSX tag start. Misreading it as JSX would
        // skip the WHOLE `html!` body. The body must still be scanned — a real
        // unlabeled `<input>` inside `@if count < limit { … }` is still flagged.
        let src = wrap(r"@if count < limit { input; }");
        assert_eq!(rule_ids(&src), vec!["label"], "{:?}", findings_for(&src));
    }

    #[test]
    fn maud_greater_than_comparison_is_not_misread_as_jsx() {
        // `@if a > b { button { } }`: `>` is a comparison, not a self-closing tag.
        // The body is scanned and the empty button flagged.
        let src = wrap(r"@if a > b { button { } }");
        assert_eq!(
            rule_ids(&src),
            vec!["button-name"],
            "{:?}",
            findings_for(&src)
        );
    }

    #[test]
    fn jsx_close_tag_is_still_skipped() {
        // A JSX closing tag `</button>` marks the body as non-maud — skipped.
        let src = wrap(r"<button>{label}</button>");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    #[test]
    fn jsx_self_closing_tag_is_still_skipped() {
        // A JSX self-closing tag `<input/>` marks the body as non-maud — skipped.
        let src = wrap(r"<input/>");
        assert!(findings_for(&src).is_empty(), "{:?}", findings_for(&src));
    }

    // ── End-to-end: red project → fix → green ──────────────────────────────

    #[test]
    fn end_to_end_red_then_green() {
        let dir = tempfile::tempdir().unwrap();
        let view = dir.path().join("view.rs");

        // Red: an alt-less image in raw html! ships silently until now.
        std::fs::write(&view, wrap(r#"img src="/logo.png";"#)).unwrap();
        let opts = A11yVerifyOptions {
            format: OutputFormat::Text,
            strict: false,
        };
        assert_eq!(run_in(dir.path(), opts), 1, "red project must fail CI");

        // Fix: add the alt attribute (or switch to Img::new).
        std::fs::write(&view, wrap(r#"img src="/logo.png" alt="Logo";"#)).unwrap();
        assert_eq!(run_in(dir.path(), opts), 0, "fixed project must pass CI");
    }

    #[test]
    fn exit_code_zero_when_clean() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("view.rs"), wrap(r#"button { "Ok" }"#)).unwrap();
        let opts = A11yVerifyOptions {
            format: OutputFormat::Json,
            strict: false,
        };
        assert_eq!(run_in(dir.path(), opts), 0);
    }

    #[test]
    fn nonexistent_scan_root_fails_hard() {
        // A misspelled/unreadable scan root must be a hard non-zero failure, not
        // a zero-findings PASS — otherwise a CI path typo silently disables the
        // whole audit.
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("does-not-exist");
        let opts = A11yVerifyOptions {
            format: OutputFormat::Text,
            strict: false,
        };
        assert_eq!(
            run_in(&missing, opts),
            1,
            "an unreadable scan root must fail, not report an empty clean audit"
        );
    }

    #[test]
    fn empty_but_readable_root_passes() {
        // A genuinely empty-but-readable directory has no findings and must still
        // pass (exit 0) — distinct from the unreadable-root failure above.
        let dir = tempfile::tempdir().unwrap();
        let opts = A11yVerifyOptions {
            format: OutputFormat::Text,
            strict: false,
        };
        assert_eq!(run_in(dir.path(), opts), 0);
    }

    // ── Test-scaffolding skips (issue #1934) ───────────────────────────────

    #[test]
    fn defect_in_inline_cfg_test_module_is_not_flagged() {
        // A raw-`html!` defect inside a `#[cfg(test)] mod tests { … }` is test
        // scaffolding, not shipped product markup, so it must not be flagged —
        // while a real product defect in the same file still is (issue #1934,
        // the #1930 `form.rs` case).
        let src = r#"
            fn view() { let _ = html! { img src="product.png"; }; }
            #[cfg(test)]
            mod tests {
                fn t() { let _ = html! { img src="scaffold.png"; }; }
            }
        "#;
        let f = findings_for(src);
        assert_eq!(f.len(), 1, "only the product defect should flag: {f:?}");
        assert_eq!(f[0].rule_id, "image-alt");
    }

    #[test]
    fn defect_in_inline_cfg_test_fn_is_not_flagged() {
        // The `#[cfg(test)]` skip also covers a bare test `fn`, not just `mod`.
        let src = r"
            #[cfg(test)]
            fn helper() { let _ = html! { button { } }; }
        ";
        assert!(findings_for(src).is_empty(), "{:?}", findings_for(src));
    }

    #[test]
    fn cfg_not_test_module_is_still_scanned() {
        // The skip is precise: `#[cfg(not(test))]` is production code and its
        // defects must still be flagged (only a literal `cfg(test)` is skipped).
        let src = r#"
            #[cfg(not(test))]
            mod prod {
                fn v() { let _ = html! { img src="x.png"; }; }
            }
        "#;
        let f = findings_for(src);
        assert_eq!(f.len(), 1, "{f:?}");
        assert_eq!(f[0].rule_id, "image-alt");
    }

    #[test]
    fn defect_under_tests_subdir_is_skipped_but_flagged_at_root() {
        // The `tests/`-directory skip is scan-root RELATIVE: the SAME defect is
        // ignored under a `tests/` subdir of the scan root but flagged when it
        // sits at the root — proving the skip never neuters the fixture-dir
        // integration test, which passes a fixture dir AS the scan root
        // (issue #1934).
        let dir = tempfile::tempdir().unwrap();
        let opts = A11yVerifyOptions {
            format: OutputFormat::Text,
            strict: false,
        };

        let tests_dir = dir.path().join("tests");
        std::fs::create_dir(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("view.rs"), wrap(r#"img src="x.png";"#)).unwrap();
        assert_eq!(
            run_in(dir.path(), opts),
            0,
            "a defect under a tests/ subdir must not be flagged",
        );

        std::fs::write(dir.path().join("view.rs"), wrap(r#"img src="x.png";"#)).unwrap();
        assert_eq!(
            run_in(dir.path(), opts),
            1,
            "the same defect at the scan root must be flagged",
        );
    }

    // ── Route attribution (issue #1706, AC3) ───────────────────────────────

    /// Build a full report from one or more in-memory `(file, source)` pairs.
    fn report_for(files: &[(&str, &str)]) -> Report {
        let mut scan = Scan::default();
        for (name, src) in files {
            scan_source(src, name, &mut scan);
            scan.files_scanned += 1;
        }
        Report::from_scan(scan)
    }

    /// The routes attributed to the single finding of a one-file report.
    fn routes_of_only_finding(files: &[(&str, &str)]) -> Vec<String> {
        let report = report_for(files);
        assert_eq!(report.findings.len(), 1, "{:?}", report.findings);
        report.findings[0].routes.clone()
    }

    #[test]
    fn finding_in_a_route_handler_is_keyed_to_that_route() {
        let src = r#"
            #[get("/settings")]
            async fn settings() -> Markup {
                html! { img src="/logo.png"; }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /settings".to_owned()]
        );
    }

    #[test]
    fn finding_in_a_called_helper_inherits_the_route() {
        let src = r#"
            #[get("/settings")]
            async fn settings() -> Markup {
                html! { main { (sidebar()) } }
            }

            fn sidebar() -> Markup {
                html! { img src="/logo.png"; }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /settings".to_owned()]
        );
    }

    #[test]
    fn attribution_crosses_files() {
        let handler = r#"
            #[post("/settings")]
            async fn save() -> Markup {
                html! { main { (sidebar()) } }
            }
        "#;
        let partial = r#"
            fn sidebar() -> Markup {
                html! { img src="/logo.png"; }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("routes.rs", handler), ("partials.rs", partial)]),
            vec!["POST /settings".to_owned()]
        );
    }

    #[test]
    fn a_helper_reached_from_two_routes_lists_both() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }

            #[get("/b")]
            async fn b() -> Markup { html! { (sidebar()) } }

            fn sidebar() -> Markup {
                html! { img src="/logo.png"; }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned(), "GET /b".to_owned()]
        );
    }

    #[test]
    fn an_ambiguous_helper_name_is_not_traversed() {
        // Two functions share a name, so a bare `sidebar()` call cannot be
        // resolved to one of them. Guessing would key the finding to a route
        // that never renders it, so the call edge is dropped instead.
        let handler = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }
        "#;
        let one = r#"
            fn sidebar() -> Markup { html! { img src="/logo.png"; } }
        "#;
        let two = r#"
            fn sidebar() -> Markup { html! { span { "hi" } } }
        "#;
        assert!(
            routes_of_only_finding(&[("a.rs", handler), ("one.rs", one), ("two.rs", two)])
                .is_empty()
        );
    }

    #[test]
    fn a_finding_outside_any_route_has_no_route() {
        let src = r#"
            fn orphan() -> Markup { html! { img src="/logo.png"; } }
        "#;
        let report = report_for(&[("views.rs", src)]);
        assert!(
            report.findings[0].routes.is_empty(),
            "{:?}",
            report.findings
        );
        assert_eq!(report.summary.unrouted, 1);
    }

    #[test]
    fn mutually_recursive_helpers_terminate() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (left()) } }

            fn left() -> Markup { html! { (right()) } }

            fn right() -> Markup { html! { (left()) img src="/logo.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn method_calls_are_not_resolved_as_helpers() {
        // `self.sidebar()` is a method call, not a call to the free function
        // `sidebar`; treating it as one would attribute the finding to a route
        // that cannot reach it.
        let src = r#"
            #[get("/a")]
            async fn a(page: Page) -> Markup { html! { (page.sidebar()) } }

            fn sidebar() -> Markup { html! { img src="/logo.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn routes_section_reports_per_route_status() {
        let src = r#"
            #[get("/settings")]
            async fn settings() -> Markup { html! { img src="/logo.png"; } }

            #[get("/about")]
            async fn about() -> Markup { html! { img src="/logo.png" alt="Logo"; } }
        "#;
        let report = report_for(&[("views.rs", src)]);
        let paths: Vec<_> = report
            .routes
            .iter()
            .map(|r| (r.path.as_str(), r.findings, r.status))
            .collect();
        assert_eq!(paths, vec![("/about", 0, "pass"), ("/settings", 1, "fail")]);
        assert_eq!(report.routes[1].method, "GET");
        assert_eq!(report.routes[1].handler, "settings");
        assert_eq!(report.routes[1].file, "views.rs");
        assert_eq!(report.summary.routes, 2);
        assert_eq!(report.summary.routes_failing, 1);
    }

    #[test]
    fn a_route_without_markup_is_still_listed_as_passing() {
        let src = r#"
            #[get("/api/todos")]
            async fn list() -> Json<Vec<Todo>> { Json(vec![]) }
        "#;
        let report = report_for(&[("api.rs", src)]);
        assert_eq!(report.routes.len(), 1);
        assert_eq!(report.routes[0].status, "pass");
    }

    #[test]
    fn a_nested_fn_is_not_a_target_for_a_bare_call() {
        // Rust makes a nested item visible only inside its enclosing block, so
        // an unrelated route's bare `render()` cannot reach it.
        let src = r#"
            fn outer() -> Markup {
                fn render() -> Markup { html! { img src="/x.png"; } }
                html! { span { "hi" } }
            }

            #[get("/a")]
            async fn a() -> Markup { html! { (render()) } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn an_associated_fn_is_not_a_target_for_a_bare_call() {
        // A method is reached through a receiver or a type-qualified path,
        // neither of which this scan resolves.
        let src = r#"
            impl Card {
                fn render(&self) -> Markup { html! { img src="/x.png"; } }
            }

            #[get("/a")]
            async fn a() -> Markup { html! { (render()) } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_module_level_fn_is_still_a_target_for_a_bare_call() {
        // Items in a module are reachable by a bare name through a `use`, so
        // scoping must not cost the ordinary case.
        let src = r#"
            mod views {
                fn sidebar() -> Markup { html! { img src="/x.png"; } }
            }

            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_route_on_an_associated_fn_is_still_a_route() {
        let src = r#"
            impl Dashboard {
                #[get("/a")]
                async fn show(&self) -> Markup { html! { img src="/x.png"; } }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_shadowing_parameter_is_not_resolved_as_a_helper() {
        // The handler calls its own parameter, not the free function that
        // happens to share the name.
        let src = r#"
            #[get("/a")]
            async fn a(view: impl Fn() -> Markup) -> Markup { html! { (view()) } }

            fn view() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_shadowing_local_is_not_resolved_as_a_helper() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                let view = || html! { span { "local" } };
                html! { (view()) }
            }

            fn view() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_shadowing_closure_parameter_is_not_resolved_as_a_helper() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Row>) -> Markup {
                html! { @for row in rows { (rows.iter().map(|view| view()).count()) } }
            }

            fn view() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn shadowing_in_one_handler_does_not_hide_a_real_call_in_another() {
        // Bindings are per function: `b` really does call the free `sidebar`.
        let src = r#"
            #[get("/a")]
            async fn a(sidebar: impl Fn() -> Markup) -> Markup { html! { (sidebar()) } }

            #[get("/b")]
            async fn b() -> Markup { html! { (sidebar()) } }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /b".to_owned()]
        );
    }

    #[test]
    fn type_qualified_associated_calls_are_not_resolved_as_helpers() {
        // `Metrics::render()` is an associated function on a type this scan
        // cannot see. Resolving its bare name would blame the route for markup
        // in an unrelated free `render`.
        let src = r#"
            #[get("/dash")]
            async fn dash() -> Markup { html! { (Metrics::render()) } }

            fn render() -> Markup { html! { img src="/logo.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn module_qualified_calls_are_resolved_as_helpers() {
        // A module path is the ordinary way to reach a view helper, so it must
        // still resolve — only type-qualified calls are dropped.
        let src = r#"
            #[get("/dash")]
            async fn dash() -> Markup { html! { (crate::views::sidebar()) } }

            fn sidebar() -> Markup { html! { img src="/logo.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /dash".to_owned()]
        );
    }

    // ── Call shapes from issue #2666 ───────────────────────────────────────

    /// [`report_for`], with `cfg(feature = "…")` read against `features`.
    fn report_with_features(files: &[(&str, &str)], features: &[&str]) -> Report {
        let features: BTreeSet<String> = features.iter().map(|f| (*f).to_owned()).collect();
        let mut scan = Scan::default();
        for (name, src) in files {
            scan_source_with(src, name, Some(&features), &mut scan);
            scan.files_scanned += 1;
        }
        Report::from_scan(scan)
    }

    /// The routes of the single finding, with `features` on.
    fn routes_with_features(src: &str, features: &[&str]) -> Vec<String> {
        let report = report_with_features(&[("views.rs", src)], features);
        assert_eq!(report.findings.len(), 1, "{:?}", report.findings);
        report.findings[0].routes.clone()
    }

    #[test]
    fn a_turbofish_call_is_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar::<Html>()) } }

            fn sidebar<T>() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_module_qualified_turbofish_call_is_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (views::sidebar::<Vec<Box<dyn Fn() -> u8>>>()) } }

            fn sidebar<T>() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_type_qualified_turbofish_call_is_not_resolved() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (Widget::render::<Html>()) } }

            fn render<T>() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_turbofish_type_is_not_a_call() {
        // `Vec::<u8>::new()` calls `new` on a type, not a free fn `Vec`.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { let _v = Vec::<u8>::new(); html! { span { "a" } } }

            fn new() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_function_passed_by_name_is_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Row>) -> Markup {
                let cells: Vec<Markup> = rows.into_iter().map(render_row).collect();
                html! { @for c in cells { (c) } }
            }

            fn render_row(r: Row) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_module_qualified_function_passed_by_name_is_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Row>) -> Markup {
                html! { (rows.iter().map_or_else(empty, views::render_row)) }
            }

            fn render_row(r: Row) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_type_qualified_function_passed_by_name_is_not_resolved() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Row>) -> Markup { html! { (rows.iter().map(Widget::render)) } }

            fn render(r: Row) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_name_in_a_larger_argument_is_not_passed_by_name() {
        // `render_row + 1` and `&render_row` are values, not a fn passed on.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (total(render_row + 1)) (show(&render_row)) } }

            fn render_row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_macro_argument_is_not_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (format!("{}", render_row)) } }

            fn render_row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_for_loop_binding_shadows_a_function_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Markup>) -> Markup {
                let mut out = Vec::new();
                for render_row in rows { out.push(render_row); }
                html! { span { "a" } }
            }

            fn render_row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_match_arm_binding_shadows_a_function_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(row: Option<Markup>) -> Markup {
                let mut out = Vec::new();
                match row { Some(render_row) => out.push(render_row), None => {} }
                html! { span { "a" } }
            }

            fn render_row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_nested_helper_called_by_its_enclosing_fn_is_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn row() -> Markup { html! { img src="/x.png"; } }
                html! { (row()) }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_nested_helper_can_call_its_sibling() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn outer() -> Markup { inner() }
                fn inner() -> Markup { html! { img src="/x.png"; } }
                html! { (outer()) }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_nested_helper_shadows_a_free_fn_of_the_same_name() {
        // `a` calls its own clean `sidebar`, not the free one with the defect.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn sidebar() -> Markup { html! { span { "clean" } } }
                html! { (sidebar()) }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn same_named_nested_helpers_in_two_handlers_stay_apart() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn row() -> Markup { html! { img src="/x.png"; } }
                html! { (row()) }
            }

            #[get("/b")]
            async fn b() -> Markup {
                fn row() -> Markup { html! { span { "clean" } } }
                html! { (row()) }
            }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_helper_in_an_inner_block_stays_unresolved() {
        // An item in an inner block is visible in that block only, and this
        // scan does not track blocks.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                { fn row() -> Markup { html! { img src="/x.png"; } } }
                html! { (row()) }
            }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    const CFG_GATED: &str = r#"
        #[get("/a")]
        async fn a() -> Markup {
            #[cfg(feature = "admin")]
            let side = sidebar();
            html! { span { "a" } }
        }

        fn sidebar() -> Markup { html! { img src="/x.png"; } }
    "#;

    #[test]
    fn a_call_gated_on_an_off_feature_is_not_a_call_edge() {
        assert!(routes_with_features(CFG_GATED, &["db"]).is_empty());
    }

    #[test]
    fn a_call_gated_on_an_on_feature_is_a_call_edge() {
        assert_eq!(
            routes_with_features(CFG_GATED, &["admin"]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_call_gated_with_no_known_features_is_kept() {
        // No manifest: the predicate is unknown, so the edge stays.
        assert_eq!(
            routes_of_only_finding(&[("views.rs", CFG_GATED)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_call_gated_on_an_unknown_predicate_is_kept() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(target_os = "linux")]
                sidebar();
                html! { span { "a" } }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(routes_with_features(src, &[]), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn a_gated_statement_drops_only_its_own_calls() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(not(feature = "db"))]
                let side = clean();
                let main = sidebar();
                html! { (main) }
            }

            fn clean() -> Markup { html! { span { "clean" } } }
            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_with_features(src, &["db"]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_gated_match_arm_is_not_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a(k: Kind) -> Markup {
                match k {
                    #[cfg(feature = "admin")]
                    Kind::Admin => sidebar(),
                    _ => html! { span { "a" } },
                }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    /// A crate in a temp dir: a manifest with `default = ["db"]` and an
    /// `admin` feature, and [`CFG_GATED`] as its only view.
    fn cfg_crate() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\
             [features]\ndefault = [\"db\"]\ndb = []\nadmin = []\n",
        )
        .unwrap();
        std::fs::create_dir(dir.path().join("src")).unwrap();
        std::fs::write(dir.path().join("src/views.rs"), CFG_GATED).unwrap();
        dir
    }

    fn routes_in(root: &Path, features: &CargoFeatures) -> Vec<String> {
        let report = Report::from_scan(scan_project_with(root, features).unwrap());
        assert_eq!(report.findings.len(), 1, "{:?}", report.findings);
        report.findings[0].routes.clone()
    }

    #[test]
    fn a_gated_if_else_drops_both_branches() {
        let src = r#"
            #[get("/a")]
            async fn a(x: bool) -> Markup {
                #[cfg(feature = "admin")]
                if x { clean() } else { sidebar() }
                html! { span { "a" } }
            }

            fn clean() -> Markup { html! { span { "clean" } } }
            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    const MANIFEST: &str = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\
        [features]\ndefault = [\"db\"]\ndb = []\nadmin = []\nbilling = []\n\n\
        [dependencies]\nredis = { version = \"1\", optional = true }\n";

    #[test]
    fn requested_features_split_on_commas() {
        let selection = CargoFeatures {
            features: vec!["admin, billing".to_owned()],
            ..CargoFeatures::default()
        };
        let on = enabled_features(MANIFEST, &selection).expect("a package");
        assert!(
            on.contains("db") && on.contains("admin") && on.contains("billing"),
            "{on:?}"
        );
        assert!(!on.contains("redis"), "{on:?}");
    }

    #[test]
    fn all_features_turns_on_optional_dependencies() {
        let selection = CargoFeatures {
            all: true,
            ..CargoFeatures::default()
        };
        let on = enabled_features(MANIFEST, &selection).expect("a package");
        for name in ["db", "admin", "billing", "redis"] {
            assert!(on.contains(name), "{name} is off: {on:?}");
        }
    }

    #[test]
    fn a_virtual_workspace_manifest_decides_no_feature() {
        let manifest = "[workspace]\nmembers = [\"app\"]\n";
        assert!(enabled_features(manifest, &CargoFeatures::default()).is_none());
    }

    #[test]
    fn an_impl_for_in_a_body_does_not_hide_later_calls() {
        // `impl … for …` has no `in`: it binds nothing.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                impl Render for Row { fn render(&self) -> Markup { html! {} } }
                html! { (sidebar()) }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_higher_ranked_bound_does_not_hide_later_calls() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn apply<F>(f: F) where F: for<'x> Fn(&'x str) {}
                html! { (sidebar()) }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_gated_generic_nested_fn_is_skipped_whole() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(feature = "admin")]
                fn helper<A, B>(a: A) -> Markup { sidebar() }
                html! { span { "a" } }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn a_gated_let_with_a_generic_type_is_skipped_whole() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(feature = "admin")]
                let m: HashMap<K, V> = sidebar();
                html! { span { "a" } }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn a_gated_fn_item_is_not_indexed() {
        // One of the two `sidebar`s is off, so the call is no longer ambiguous.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }

            #[cfg(feature = "admin")]
            fn sidebar() -> Markup { html! { span { "admin" } } }
            #[cfg(not(feature = "admin"))]
            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(routes_with_features(src, &[]), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn a_gated_route_is_not_listed() {
        let src = r#"
            #[cfg(feature = "admin")]
            #[get("/admin")]
            async fn admin() -> Markup { html! { img src="/x.png"; } }
        "#;
        let report = report_with_features(&[("views.rs", src)], &[]);
        assert!(report.routes.is_empty(), "{:?}", report.routes);
        assert_eq!(report.findings.len(), 1, "the finding stays");
    }

    #[test]
    fn a_matches_pattern_is_not_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Option<u8>) -> Markup {
                let _ = matches!(x, Some(render_row));
                html! { span { "a" } }
            }

            fn render_row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_match_guard_call_is_still_a_call_edge() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Option<u8>) -> Markup {
                match x { Some(v) if is_ready(v) => html! {}, _ => html! {} }
            }

            fn is_ready(v: u8) -> bool { let _ = html! { img src="/x.png"; }; true }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn no_default_features_turns_the_defaults_off() {
        let selection = CargoFeatures {
            features: vec!["admin".to_owned()],
            all: false,
            no_default: true,
        };
        let on = enabled_features(MANIFEST, &selection).expect("a package");
        assert!(on.contains("admin") && !on.contains("db"), "{on:?}");
    }

    #[test]
    fn no_default_features_still_expands_an_explicit_default() {
        // Cargo turns on `default` and its members when `--features default`
        // is asked for, even with `--no-default-features`.
        let selection = CargoFeatures {
            features: vec!["default".to_owned()],
            all: false,
            no_default: true,
        };
        let on = enabled_features(MANIFEST, &selection).expect("a package");
        assert!(on.contains("default") && on.contains("db"), "{on:?}");
    }

    #[test]
    fn all_features_with_no_default_features_turns_on_default() {
        let selection = CargoFeatures {
            features: Vec::new(),
            all: true,
            no_default: true,
        };
        let on = enabled_features(MANIFEST, &selection).expect("a package");
        assert!(on.contains("default") && on.contains("db"), "{on:?}");
    }

    #[test]
    fn all_features_skips_an_optional_dependency_named_by_dep() {
        // `dep:redis` suppresses the implicit `redis` feature, so Cargo's
        // `--all-features` does not turn it on.
        let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\
            [features]\nadmin = [\"dep:redis\"]\n\n\
            [dependencies]\nredis = { version = \"1\", optional = true }\n";
        let selection = CargoFeatures {
            all: true,
            ..CargoFeatures::default()
        };
        let on = enabled_features(manifest, &selection).expect("a package");
        assert!(on.contains("admin") && !on.contains("redis"), "{on:?}");
    }

    #[test]
    fn all_features_turns_on_target_optional_dependencies() {
        let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\
            [target.'cfg(unix)'.dependencies]\nnix = { version = \"1\", optional = true }\n";
        let selection = CargoFeatures {
            all: true,
            ..CargoFeatures::default()
        };
        let on = enabled_features(manifest, &selection).expect("a package");
        assert!(on.contains("nix"), "{on:?}");
    }

    #[test]
    fn a_closure_tuple_pattern_shadows_a_function_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<(u32, Row)>) -> Markup {
                html! { @for x in rows.iter().map(|(id, row)| cell(*id, row)) { (x) } }
            }

            fn row(r: &Row) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_closure_tuple_struct_pattern_shadows_a_function_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(rows: Vec<Wrapper>) -> Markup {
                let n: usize = rows.iter().map(|Wrapper(row)| row.len()).sum();
                html! { (n) }
            }

            fn row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_struct_pattern_match_arm_shadows_a_function_passed_by_name() {
        let src = r#"
            #[get("/a")]
            async fn a(ev: Msg) -> Markup {
                match ev {
                    Msg::Row { row } => html! { (render(row)) },
                    Msg::Wrapped { inner: Some(row) } | Msg::Other { row } => html! { (render(row)) },
                    _ => html! {},
                }
            }

            fn row() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_std_path_passed_by_name_is_not_resolved() {
        let src = r#"
            #[get("/a")]
            async fn a(names: Vec<String>) -> Markup {
                let _t: Vec<&str> = names.iter().map(String::as_str).map(str::trim).collect();
                let _n: Vec<u32> = names.iter().map(|_| 1u8).map(u32::from).collect();
                names.into_iter().for_each(std::mem::drop);
                html! { span { "a" } }
            }

            fn trim() -> Markup { html! { img src="/x.png"; } }
            fn from() -> Markup { html! { img src="/x.png"; } }
            fn drop() -> Markup { html! { img src="/x.png"; } }
        "#;
        let report = report_for(&[("views.rs", src)]);
        assert_eq!(report.findings.len(), 3, "{:?}", report.findings);
        for finding in &report.findings {
            assert!(finding.routes.is_empty(), "{finding:?}");
        }
    }

    #[test]
    fn an_inner_block_helper_shadows_a_body_level_one() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn row() -> Markup { html! { img src="/x.png"; } }
                { fn row() -> Markup { html! { span { "clean" } } } html! { (row()) } }
            }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn an_inner_block_helper_shadows_a_free_fn() {
        let src = r#"
            #[get("/a")]
            async fn a(x: bool) -> Markup {
                if x { fn sidebar() -> Markup { html! { span { "clean" } } } html! { (sidebar()) } } else { html! {} }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    /// A handler with one gated statement `stmt` that calls `admin`.
    fn gated(stmt: &str) -> String {
        format!(
            r#"
            #[get("/a")]
            async fn a(x: Page) -> Markup {{
                #[cfg(feature = "admin")]
                {stmt}
                html! {{ span {{ "a" }} }}
            }}

            fn admin() -> Markup {{ html! {{ img src="/x.png"; }} }}
            "#
        )
    }

    #[test]
    fn a_gated_statement_is_skipped_past_its_generics_closures_and_patterns() {
        for stmt in [
            "let m: HashMap<String, Markup> = admin();",
            "let f = |a, b| admin();",
            "let v = foo::<A, B>(admin());",
            "let Ctx { .. } = admin();",
            "for Row { id } in rows { admin(); }",
            "if let Foo { a } = x { admin(); }",
            "let y = unsafe { a() } + admin();",
        ] {
            let src = gated(stmt);
            assert!(routes_with_features(&src, &[]).is_empty(), "{stmt}");
        }
    }

    #[test]
    fn a_gated_struct_pattern_arm_is_skipped_whole() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Page) -> Markup {
                match x {
                    #[cfg(feature = "admin")]
                    Page::Admin { user } => admin(user),
                    _ => html! {},
                }
            }

            fn admin(u: User) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn markup_in_a_gated_nested_fn_is_not_the_handler_s() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(feature = "admin")]
                fn unused() -> Markup { html! { img src="/x.png"; } }
                html! { span { "a" } }
            }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn a_gated_arm_does_not_exclude_the_next_arm() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Kind) -> Markup {
                match x {
                    #[cfg(feature = "admin")]
                    Kind::Admin => clean(),
                    _ => html! { img src="/x.png"; },
                }
            }

            fn clean() -> Markup { html! { span { "clean" } } }
        "#;
        assert_eq!(routes_with_features(src, &[]), vec!["GET /a".to_owned()]);
    }

    /// A handler whose `match` has one gated arm `arm`, then an active arm
    /// with a defect.
    fn gated_arm(arm: &str) -> String {
        format!(
            r#"
            #[get("/a")]
            async fn a(x: Page) -> Markup {{
                match x {{
                    #[cfg(feature = "admin")]
                    {arm}
                    _ => html! {{ img src="/x.png"; }},
                }}
            }}

            fn clean() -> Markup {{ html! {{ span {{ "clean" }} }} }}
            "#
        )
    }

    #[test]
    fn a_gated_arm_ends_at_its_own_end_for_every_pattern_shape() {
        for arm in [
            "Page::Admin => clean(),",
            "Page::Admin | Page::Legacy => clean(),",
            "Page::Admin { user } if user.active => clean(),",
            "Page::Admin(a, b) if a < b => clean(),",
            "Page::Admin => { clean() }",
            "Page::Admin => foo::<A, B>(clean()),",
            "Page::Admin => rows.map(|a, b| clean()),",
            "Page::Admin => { rows }.into_iter().map(clean).count(),",
        ] {
            let src = gated_arm(arm);
            assert_eq!(
                routes_with_features(&src, &[]),
                vec!["GET /a".to_owned()],
                "{arm}"
            );
        }
    }

    #[test]
    fn a_method_chain_after_a_gated_arm_block_is_skipped() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Page, rows: Vec<Row>) -> Markup {
                match x {
                    #[cfg(feature = "admin")]
                    Page::Admin => { rows }.into_iter().map(sidebar).count(),
                    _ => html! { span { "a" } },
                }
            }

            fn sidebar(r: Row) -> Markup { html! { img src="/x.png"; } }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn markup_in_a_gated_guarded_arm_is_not_the_handler_s() {
        let src = r#"
            #[get("/a")]
            async fn a(x: Page) -> Markup {
                match x {
                    #[cfg(feature = "admin")]
                    Page::Admin { user } if user.active => html! { img src="/x.png"; },
                    _ => html! { span { "a" } },
                }
            }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn a_gated_statement_with_a_bitwise_or_still_ends_at_its_comma() {
        // A `|` after an operand is not a closure; the field ends at its `,`.
        let src = r#"
            #[get("/a")]
            async fn a(a: u8, b: u8) -> Markup {
                let _f = Flags {
                    #[cfg(feature = "admin")]
                    mask: a | b,
                    page: html! { img src="/x.png"; },
                };
                html! { span { "a" } }
            }
        "#;
        assert_eq!(routes_with_features(src, &[]), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn a_gated_generic_impl_is_skipped_whole() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }

            #[cfg(feature = "admin")]
            impl<A, B> Render for Pair<A, B> { fn render(&self) -> Markup { sidebar() } }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(routes_with_features(src, &[]), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn markup_in_a_gated_statement_is_not_the_handler_s() {
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                #[cfg(feature = "admin")]
                let _x = html! { img src="/x.png"; };
                html! { span { "a" } }
            }
        "#;
        assert!(routes_with_features(src, &[]).is_empty());
    }

    #[test]
    fn a_module_qualified_call_skips_a_local_helper() {
        // `views::sidebar()` names the free fn, not the uncalled local one.
        let local_bad = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn sidebar() -> Markup { html! { img src="/x.png"; } }
                html! { (views::sidebar()) }
            }

            fn sidebar() -> Markup { html! { span { "clean" } } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", local_bad)]).is_empty());
        let free_bad = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn sidebar() -> Markup { html! { span { "clean" } } }
                html! { (views::sidebar()) }
            }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", free_bad)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn a_local_binding_does_not_shadow_a_module_qualified_call() {
        let src = r#"
            #[get("/a")]
            async fn a(sidebar: bool) -> Markup { html! { (views::sidebar()) } }

            fn sidebar() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn the_manifest_default_features_gate_call_edges() {
        let dir = cfg_crate();
        assert!(routes_in(dir.path(), &CargoFeatures::default()).is_empty());
    }

    #[test]
    fn a_requested_feature_turns_a_gated_call_edge_on() {
        let dir = cfg_crate();
        let features = CargoFeatures {
            features: vec!["admin".to_owned()],
            ..CargoFeatures::default()
        };
        assert_eq!(routes_in(dir.path(), &features), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn all_features_turns_every_gated_call_edge_on() {
        let dir = cfg_crate();
        let features = CargoFeatures {
            all: true,
            ..CargoFeatures::default()
        };
        assert_eq!(routes_in(dir.path(), &features), vec!["GET /a".to_owned()]);
    }

    #[test]
    fn a_scan_root_below_the_manifest_still_reads_it() {
        let dir = cfg_crate();
        assert!(routes_in(&dir.path().join("src"), &CargoFeatures::default()).is_empty());
    }

    #[test]
    fn a_nested_fn_declaration_is_not_a_call_edge() {
        // Declaring a function inside a handler is not calling it, and neither
        // is it calling what that function calls.
        let src = r#"
            #[get("/a")]
            async fn a() -> Markup {
                fn never_called() -> Markup { sidebar() }
                html! { span { "hi" } }
            }

            fn sidebar() -> Markup { html! { img src="/logo.png"; } }
        "#;
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_macro_rules_template_is_not_an_ambiguous_definition() {
        // A `fn` inside a `macro_rules!` body is a template, not a definition.
        // Indexing it would make the real helper look defined twice and drop
        // the call edge to it.
        let src = r#"
            macro_rules! decl {
                () => { fn sidebar() -> Markup { html! { span { "gen" } } } };
            }

            #[get("/a")]
            async fn a() -> Markup { html! { (sidebar()) } }

            fn sidebar() -> Markup { html! { img src="/logo.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn two_handlers_sharing_a_path_do_not_share_findings() {
        // Paths are declared, not mounted, so two handlers can legitimately
        // declare the same one. Counting by the display key would report the
        // clean handler as failing.
        let src = r#"
            #[get("/a")]
            async fn one() -> Markup { html! { img src="/logo.png"; } }

            #[get("/a")]
            async fn two() -> Markup { html! { span { "ok" } } }
        "#;
        let report = report_for(&[("views.rs", src)]);
        let rows: Vec<_> = report
            .routes
            .iter()
            .map(|r| (r.handler.as_str(), r.findings, r.status))
            .collect();
        assert_eq!(rows, vec![("one", 1, "fail"), ("two", 0, "pass")]);
        assert_eq!(report.summary.routes_failing, 1);
    }

    #[test]
    fn two_fns_on_one_line_do_not_steal_each_others_findings() {
        // Line-range containment alone ties on single-line functions; the
        // finding belongs to whichever function actually encloses its column.
        let src = concat!(
            "#[get(\"/a\")] fn a() -> Markup { html! { span {} } } ",
            "fn b() -> Markup { html! { img src=\"/x.png\"; } }",
        );
        assert!(routes_of_only_finding(&[("views.rs", src)]).is_empty());
    }

    #[test]
    fn a_route_attribute_does_not_leak_past_a_non_fn_item() {
        // An attribute binds to the item that follows it. When that item is not
        // a function, the route must not attach to the next function instead.
        let src = r#"
            #[get("/a")]
            extern "C" { }

            pub async fn helper() -> Markup { html! { img src="/x.png"; } }
        "#;
        let report = report_for(&[("views.rs", src)]);
        assert!(report.routes.is_empty(), "{:?}", report.routes);
        assert!(
            report.findings[0].routes.is_empty(),
            "{:?}",
            report.findings
        );
    }

    #[test]
    fn a_leading_crate_override_is_not_read_as_the_path() {
        // `#[get(crate = "…", "/a")]` puts a string literal before the path.
        let src = r#"
            #[get(crate = "autumn_web", "/a")]
            async fn a() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned()]
        );
    }

    #[test]
    fn every_http_route_macro_is_recognised() {
        let src = r#"
            #[get("/a")] async fn a() -> Markup { html! { span {} } }
            #[post("/b")] async fn b() -> Markup { html! { span {} } }
            #[put("/c")] async fn c() -> Markup { html! { span {} } }
            #[patch("/d")] async fn d() -> Markup { html! { span {} } }
            #[delete("/e")] async fn e() -> Markup { html! { span {} } }
            #[static_get("/f")] async fn f() -> Markup { html! { span {} } }
        "#;
        let keys: Vec<String> = report_for(&[("views.rs", src)])
            .routes
            .iter()
            .map(|r| format!("{} {}", r.method, r.path))
            .collect();
        assert_eq!(
            keys,
            vec![
                "GET /a",
                "POST /b",
                "PUT /c",
                "PATCH /d",
                "DELETE /e",
                "GET /f",
            ]
        );
    }

    #[test]
    fn one_handler_can_serve_several_routes() {
        let src = r#"
            #[get("/a")]
            #[post("/a")]
            async fn a() -> Markup { html! { img src="/x.png"; } }
        "#;
        assert_eq!(
            routes_of_only_finding(&[("views.rs", src)]),
            vec!["GET /a".to_owned(), "POST /a".to_owned()]
        );
    }

    #[test]
    fn route_conformance_points_at_the_handler_line() {
        let src = "\n\n#[get(\"/a\")]\nasync fn a() -> Markup { html! { span {} } }\n";
        let report = report_for(&[("views.rs", src)]);
        assert_eq!(report.routes[0].line, 4);
    }

    #[test]
    fn an_unrouted_finding_still_fails_the_build() {
        // Attribution reports; it never gates. A defect in a partial no route
        // reaches must still fail CI.
        let src = r#"fn orphan() -> Markup { html! { img src="/l.png"; } }"#;
        let report = report_for(&[("partials.rs", src)]);
        assert_eq!(report.summary.unrouted, 1);
        assert_ne!(report.exit_code(false), 0, "{report:?}");
    }

    #[test]
    fn unrouted_findings_serialize_an_empty_route_list() {
        // The key must not vanish for exactly the findings a consumer most
        // needs to notice.
        let src = r#"fn orphan() -> Markup { html! { img src="/l.png"; } }"#;
        let json = serde_json::to_string(&report_for(&[("partials.rs", src)])).unwrap();
        assert!(json.contains(r#""routes":[]"#), "{json}");
    }

    #[test]
    fn wcag_rollup_splits_multi_criterion_rules() {
        let src = r#"
            fn view() -> Markup {
                html! { img src="/logo.png"; input type="text" name="email"; }
            }
        "#;
        let report = report_for(&[("views.rs", src)]);
        let rollup: Vec<_> = report
            .wcag
            .iter()
            .map(|c| (c.criterion.as_str(), c.findings))
            .collect();
        // `label` maps to three criteria; each is reported on its own.
        assert_eq!(
            rollup,
            vec![("1.1.1", 1), ("1.3.1", 1), ("3.3.2", 1), ("4.1.2", 1),]
        );
        assert_eq!(report.wcag[0].rules, vec!["image-alt"]);
        for criterion in &report.wcag[1..] {
            assert_eq!(criterion.rules, vec!["label"], "{criterion:?}");
        }
    }

    #[test]
    fn wcag_rollup_is_empty_when_clean() {
        let src = r#"fn view() -> Markup { html! { img src="/l.png" alt="Logo"; } }"#;
        assert!(report_for(&[("views.rs", src)]).wcag.is_empty());
    }

    #[test]
    fn text_output_names_failing_routes_and_criteria() {
        let src = r#"
            #[get("/settings")]
            async fn settings() -> Markup { html! { img src="/logo.png"; } }
        "#;
        let text = format_text(&report_for(&[("views.rs", src)]), false);
        assert!(
            text.contains("1 route(s) discovered, 1 carrying findings"),
            "{text}"
        );
        assert!(text.contains("\n  failing routes:\n"), "{text}");
        assert!(
            text.contains("    GET /settings (settings) — 1 finding(s)"),
            "{text}"
        );
        assert!(
            text.contains("\n  WCAG success criteria breached:\n"),
            "{text}"
        );
        assert!(
            text.contains("    WCAG 1.1.1 — 1 finding(s) [image-alt]"),
            "{text}"
        );
        assert!(
            text.contains("1 total, 0 not reached by any route"),
            "{text}"
        );
        assert!(text.contains("Result: FAIL"), "{text}");
    }

    #[test]
    fn text_output_passes_clean() {
        let src = r#"fn view() -> Markup { html! { img src="/l.png" alt="Logo"; } }"#;
        let text = format_text(&report_for(&[("views.rs", src)]), false);
        assert!(
            text.contains("0 route(s) discovered, 0 carrying findings"),
            "{text}"
        );
        assert!(
            text.contains("Result: PASS — no accessibility violations in raw html! markup."),
            "{text}"
        );
    }

    #[test]
    fn route_attribution_ignores_cfg_test_handlers() {
        // A `#[cfg(test)]` handler is test scaffolding: it must not appear in
        // the route manifest, mirroring the scanner's cfg(test) skip.
        let src = r#"
            #[cfg(test)]
            mod tests {
                #[get("/fixture")]
                async fn fixture() -> Markup { html! { img src="/logo.png"; } }
            }
        "#;
        let report = report_for(&[("views.rs", src)]);
        assert!(report.routes.is_empty(), "{:?}", report.routes);
        assert!(report.findings.is_empty(), "{:?}", report.findings);
    }
}