autumn-cli 0.6.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
//! `autumn a11y verify` — a build-time accessibility audit of raw `html!`
//! markup.
//!
//! The typed primitives in [`autumn_web::a11y`] (`Img`,
//! `Button`, `Link`, `MenuItem`, `TextField`) 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).
//!
//! # 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;

/// 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,
}

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.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)]
pub struct Summary {
    pub critical: usize,
    pub serious: usize,
    pub moderate: usize,
    pub total: 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,
    /// Findings, sorted by file then line.
    pub findings: Vec<Finding>,
    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 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,
            }
        }
        summary.total = scan.findings.len();
        Self {
            files_scanned: scan.files_scanned,
            html_blocks: scan.html_blocks,
            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)]
struct Scan {
    findings: Vec<Finding>,
    files_scanned: usize,
    html_blocks: usize,
}

impl Scan {
    fn push(&mut self, rule: Rule, element: &str, line: 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(),
        });
    }
}

/// 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`.
fn scan_project(root: &Path) -> std::io::Result<Scan> {
    std::fs::read_dir(root)?;
    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(&src, &rel, &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);
        }
    }
}

/// Tokenize one source string and analyze every `html!` block within it.
fn scan_source(src: &str, file: &str, scan: &mut Scan) {
    let Ok(stream) = TokenStream::from_str(src) else {
        return;
    };
    find_html_blocks(&stream, file, scan);
}

/// 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
}

// ── 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,
    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;
    // 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,
            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, file);
        }
        name @ ("input" | "select" | "textarea") => {
            check_field(el, name, file, ctx, scan);
        }
        "button" if !named_content(el) => {
            scan.push(Rule::ButtonName, "button", el.line, file);
        }
        "a" if el.has_attr("href") && !named_content(el) => {
            scan.push(Rule::LinkName, "a", el.line, 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, 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 (Img, Button, \
Link, MenuItem, TextField) is proven accessible at compile time and is \
intentionally not re-scanned. This pass targets raw html! markup that bypasses \
those primitives.";

/// 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.
#[must_use]
pub fn run_in(root: &Path, opts: A11yVerifyOptions) -> 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(root) {
        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) {
    println!("autumn a11y verify");
    println!(
        "  scanned {} html! block(s) across {} .rs file(s)",
        report.html_blocks, report.files_scanned
    );
    println!("  {PRIMITIVE_NOTE}");

    if report.findings.is_empty() {
        println!("\nResult: PASS — no accessibility violations in raw html! markup.");
        return;
    }

    println!("\n  findings:");
    for f in &report.findings {
        println!(
            "    {}:{}: <{}> [WCAG {}] {} — {}",
            f.file, f.line, f.element, f.wcag, f.severity, f.message
        );
        println!("        hint: {}", f.hint);
    }

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

#[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",
        );
    }
}