cargo-judge 0.7.0

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

use std::path::{Path, PathBuf};

use quote::quote;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use syn::{
    Arm, Attribute, Block, Expr, ExprLit, ExprMethodCall, GenericArgument, ImplItemFn, ItemFn,
    ItemImpl, ItemMod, ItemTrait, Lit, Local, Macro, Meta, Pat, Path as SynPath, PathArguments,
    ReturnType, Stmt, Token, TraitItemFn, Type, TypeParamBound, Visibility,
};

use crate::finding::{Finding, Severity};
use crate::functions::{has_test_attr, qualified_item_path, read_and_parse_source, type_name};
use crate::ingest::SourceFile;
use crate::rules::api_surface::{build_finding, has_doc_comment};

/// Rule id for a discarded fallible result: `let _ = fallible();` or a bare
/// `.ok();` statement (see todo.md §G1).
pub const SWALLOWED_RESULT_RULE: &str = "swallowed-result";
/// Bump when the swallowed-result rule's logic changes (see todo.md §5
/// "Regelversions-Schutz").
pub const SWALLOWED_RESULT_RULE_REVISION: u32 = 1;

/// Rule id for an empty `Err(_)`/`Err(..)` match arm, or an `if let Err(_) =
/// ... { }` with no `else` (see todo.md §G1).
pub const EMPTY_ERROR_ARM_RULE: &str = "empty-error-arm";
pub const EMPTY_ERROR_ARM_RULE_REVISION: u32 = 1;

/// Rule id for a `pub fn` whose error type is erased (`Box<dyn Error>` /
/// `anyhow::Error`) at a public API boundary *and* whose body discards the
/// original error via a wildcard-parameter `.map_err(|_| ..)` (see todo.md
/// §G1, [`discards_error_via_map_err`]).
pub const CATCH_ALL_ERROR_RULE: &str = "catch-all-error";
/// Bump when the catch-all-error rule's logic changes (see todo.md §5
/// "Regelversions-Schutz"). v2 (2026-07-24, GitHub issue #11): added the
/// `discards_error_via_map_err` body check — a type-erased return type
/// alone no longer fires; plain `?`/`anyhow!(..)` propagation is idiomatic,
/// not evidence of discarded error information.
pub const CATCH_ALL_ERROR_RULE_REVISION: u32 = 2;

/// Rule id for an `#[allow(...)]`/`#[expect(...)]` attribute occurrence — the
/// "wichtigster Rust-Slop-Marker" per todo.md §G1.
pub const SUPPRESSION_DEBT_RULE: &str = "suppression-debt";
pub const SUPPRESSION_DEBT_RULE_REVISION: u32 = 1;

/// Rule id for `todo!()`/`unimplemented!()` outside a `#[cfg(feature =
/// ...)]`-gated scope (see todo.md §G2).
pub const MERGED_STUB_RULE: &str = "merged-stub";
pub const MERGED_STUB_RULE_REVISION: u32 = 1;

/// Rule id for a function/method/trait-default with a doc comment and a
/// literally empty body (see todo.md §G2).
pub const EMPTY_IMPL_RULE: &str = "empty-impl";
pub const EMPTY_IMPL_RULE_REVISION: u32 = 1;

/// Rule id for a `#[test]` fn (without `#[should_panic]`) whose body has no
/// visible assertion path (see todo.md §G2).
pub const ASSERTION_FREE_TEST_RULE: &str = "assertion-free-test";
pub const ASSERTION_FREE_TEST_RULE_REVISION: u32 = 1;

/// Rule id for `assert!(true)` / `assert_eq!(x, x)` (see todo.md §G2).
pub const TAUTOLOGICAL_TEST_RULE: &str = "tautological-test";
pub const TAUTOLOGICAL_TEST_RULE_REVISION: u32 = 1;

/// Rule id for an `#[ignore]`/`#[ignore = "..."]` attribute occurrence (see
/// todo.md §G2).
pub const IGNORED_TEST_ACCUMULATION_RULE: &str = "ignored-test-accumulation";
pub const IGNORED_TEST_ACCUMULATION_RULE_REVISION: u32 = 1;

/// Rule id for a phrase leaking AI-assistant framing into a plain comment
/// (see todo.md §G3). Implemented in [`crate::rules::slop_text`].
pub const CONVERSATIONAL_ARTIFACT_RULE: &str = "conversational-artifact";
pub const CONVERSATIONAL_ARTIFACT_RULE_REVISION: u32 = 1;

/// Rule id for a comment that only paraphrases the code line it precedes
/// (see todo.md §G3). Implemented in [`crate::rules::slop_text`].
pub const RESTATING_COMMENT_RULE: &str = "restating-comment";
pub const RESTATING_COMMENT_RULE_REVISION: u32 = 1;

/// Rule id for a `// Step N:` comment chain of three or more (see todo.md
/// §G3). Implemented in [`crate::rules::slop_text`].
pub const STEP_COMMENT_INFLATION_RULE: &str = "step-comment-inflation";
pub const STEP_COMMENT_INFLATION_RULE_REVISION: u32 = 1;

/// Rule id for an identifier that is exactly a generic placeholder word
/// (`data`, `temp`, `handler`, ...), see todo.md §G3.
pub const GENERIC_NAMING_RULE: &str = "generic-naming";
pub const GENERIC_NAMING_RULE_REVISION: u32 = 1;

/// Rule id for a doc comment that is a pure signature echo (see todo.md
/// §G3).
pub const DOC_RESTATES_SIGNATURE_RULE: &str = "doc-restates-signature";
pub const DOC_RESTATES_SIGNATURE_RULE_REVISION: u32 = 1;

/// Rule id for `.unwrap_or_default()` / `.unwrap_or_else(|_| ..default())`
/// on a function whose body has no error-observing call anywhere (see
/// todo.md §G1). A narrow syntax-only proxy, not a taint proof — see
/// [`check_silent_default`] and the module doc comment above.
pub const SILENT_DEFAULT_RULE: &str = "silent-default";
pub const SILENT_DEFAULT_RULE_REVISION: u32 = 1;

/// Rule id for a function whose written return type is a recognized opaque
/// error idiom (`anyhow::Error`/`anyhow::Result`, `eyre::Report`/
/// `eyre::Result`, `Box<dyn std::error::Error ..>`) and whose body has 2+
/// distinct `?`-sites but zero `.context(`/`.with_context(` calls (see
/// todo.md §G1). See [`check_context_free_propagation`] and the module doc
/// comment above.
pub const CONTEXT_FREE_PROPAGATION_RULE: &str = "context-free-propagation";
pub const CONTEXT_FREE_PROPAGATION_RULE_REVISION: u32 = 1;

/// Rule id for a `{:?}`/`{:#?}` placeholder inside a `write!`/`format!` call
/// within a manual `impl std::fmt::Display for T` block's body (see todo.md
/// §K2). See [`SlopVisitor::visit_item_impl`] and the module doc comment
/// above.
pub const DEBUG_FORMAT_LEAK_RULE: &str = "debug-format-leak";
pub const DEBUG_FORMAT_LEAK_RULE_REVISION: u32 = 1;

#[derive(Debug)]
pub enum SlopError {
    Io(PathBuf, std::io::Error),
    Parse(PathBuf, syn::Error),
}

impl std::fmt::Display for SlopError {
    // judge-dupe-ignore: explicit per-domain error rendering; variants and messages are intentionally distinct
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(path, err) => write!(f, "{}: failed to read file: {err}", path.display()),
            Self::Parse(path, err) => write!(f, "{}: failed to parse: {err}", path.display()),
        }
    }
}

impl std::error::Error for SlopError {}

/// Aggregated slop findings across a set of files, keeping findings separate
/// from files that could not be parsed.
#[derive(Debug, Default)]
pub struct WorkspaceSlop {
    pub findings: Vec<Finding>,
    pub errors: Vec<SlopError>,
    /// Generated files skipped because `include_generated` was `false` (see
    /// todo.md §3.A "Generated-Code-Policy").
    pub excluded_generated: usize,
}

/// Parses a single Rust source file and returns every slop finding in it.
/// See [`contains_catch_all_error`] for `allow_anyhow_at_boundary`.
pub fn analyze_file(
    path: &Path,
    allow_anyhow_at_boundary: bool,
) -> Result<Vec<Finding>, SlopError> {
    let (source, ast) = read_and_parse_source(
        path,
        |err| SlopError::Io(path.to_path_buf(), err),
        |err| SlopError::Parse(path.to_path_buf(), err),
    )?;

    let mut visitor = SlopVisitor {
        file: path,
        path: Vec::new(),
        findings: Vec::new(),
        feature_gated_depth: 0,
        item_spans: Vec::new(),
        allow_anyhow_at_boundary,
        display_impl_type_stack: Vec::new(),
        visitor_trait_impl_stack: Vec::new(),
        drop_impl_stack: Vec::new(),
        in_drop_drop_body: false,
    };
    visitor.visit_file(&ast);
    let mut findings = visitor.findings;
    findings.extend(crate::rules::slop_text::scan_comments(
        &source,
        &visitor.item_spans,
        path,
    ));
    Ok(findings)
}

/// Runs [`analyze_file`] over every file in `source_files` and aggregates the
/// results. Generated files are skipped unless `include_generated` is set
/// (see todo.md §3.A) — slop signals on generated code aren't actionable the
/// way they are on authored code. See [`contains_catch_all_error`] for
/// `allow_anyhow_at_boundary`.
pub fn analyze_workspace<'a>(
    source_files: impl IntoIterator<Item = &'a SourceFile>,
    include_generated: bool,
    allow_anyhow_at_boundary: bool,
) -> WorkspaceSlop {
    let mut report = WorkspaceSlop::default();
    for file in source_files {
        if !include_generated && !file.kind.is_locally_reportable() {
            report.excluded_generated += 1;
            continue;
        }
        match analyze_file(&file.path, allow_anyhow_at_boundary) {
            Ok(mut findings) => report.findings.append(&mut findings),
            Err(err) => report.errors.push(err),
        }
    }
    report
}

/// The line range and qualified item path of one `fn`/method, indexed so
/// [`crate::rules::slop_text`]'s raw-text findings (which have no `syn` span to
/// derive an item path from) can attribute a comment to its nearest
/// enclosing function (see todo.md §3.G G3).
pub(crate) struct ItemSpan {
    pub start_line: usize,
    pub end_line: usize,
    pub item_path: String,
}

/// Walks a whole parsed file (not just function bodies — attributes and
/// public fn signatures can appear anywhere at item level), tracking the
/// enclosing `mod`/`impl`/`trait`/`fn` path for a finding's `item_path` (same
/// idea as [`crate::functions::walk_functions`], but broader: this visitor
/// doesn't stop at function boundaries since `suppression-debt` attributes
/// can sit on any item, statement, or expression).
struct SlopVisitor<'a> {
    file: &'a Path,
    path: Vec<String>,
    findings: Vec<Finding>,
    /// Depth of nesting inside a `#[cfg(feature = ...)]`-gated `mod`/`impl`/
    /// `fn` — `merged-stub` doesn't flag `todo!()`/`unimplemented!()` while
    /// this is non-zero (see [`has_feature_cfg`]).
    feature_gated_depth: usize,
    /// Every `fn`/method's line range and item path, collected while
    /// walking — feeds [`crate::rules::slop_text::scan_comments`]'s attribution of
    /// raw-text findings (see [`ItemSpan`]).
    pub(crate) item_spans: Vec<ItemSpan>,
    /// Whether `catch-all-error` exempts `anyhow::Result`/`anyhow::Error`
    /// return types (see [`contains_catch_all_error`], GitHub issue #5).
    allow_anyhow_at_boundary: bool,
    /// The `T` in `impl std::fmt::Display for T`, pushed while walking such
    /// an impl block's body — `debug-format-leak` consults the top of this
    /// stack from `visit_macro` (see todo.md §K2). A trait impl only ever
    /// contains that trait's own items, so any `write!`/`format!` call
    /// inside a `Display` impl block is inside its `fmt` method by
    /// construction; no separate "are we inside `fmt`" tracking is needed.
    display_impl_type_stack: Vec<String>,
    /// Whether the innermost currently-entered `impl` block implements one of
    /// the standard `syn` AST-visitor traits (`Visit`/`VisitMut`/`Fold`) —
    /// pushed/popped once per `impl` block, unlike
    /// [`Self::display_impl_type_stack`], so a nested non-matching `impl`
    /// correctly shadows an outer matching one. `empty-impl` consults the
    /// top of this stack from `visit_impl_item_fn` (see todo.md §G2
    /// `empty-impl`, [`is_ast_visitor_trait_impl`]).
    visitor_trait_impl_stack: Vec<bool>,
    /// Whether the innermost currently-entered `impl` block is `impl Drop for
    /// _` — same push/pop-per-`impl` shape as
    /// [`Self::visitor_trait_impl_stack`]. `swallowed-result` consults this,
    /// combined with the method name, from `visit_impl_item_fn` to detect
    /// `Drop::drop`'s body (see [`is_drop_trait_impl`]).
    drop_impl_stack: Vec<bool>,
    /// Whether the body currently being walked is `Drop::drop`'s own — set
    /// while visiting an `impl Drop for _ { fn drop(&mut self) { .. } }`
    /// method body, consulted by `visit_local`/`visit_stmt` to exempt the
    /// idiomatic `let _ = ...;` there (see todo.md §G1 `swallowed-result`:
    /// `drop` cannot return a `Result`, so discarding is the only option).
    in_drop_drop_body: bool,
}

impl SlopVisitor<'_> {
    /// The qualified name of the innermost enclosing named item, or the file
    /// path if there is none.
    fn current_item_path(&self) -> String {
        qualified_item_path(self.file, &self.path)
    }

    fn record(
        &mut self,
        rule: &'static str,
        span: proc_macro2::Span,
        severity: Severity,
        item_path: String,
    ) {
        self.record_with_evidence(rule, span, severity, item_path, None);
    }

    fn record_with_evidence(
        &mut self,
        rule: &'static str,
        span: proc_macro2::Span,
        severity: Severity,
        item_path: String,
        evidence: Option<serde_json::Value>,
    ) {
        self.findings.push(build_finding(
            self.file, rule, span, severity, item_path, evidence,
        ));
    }

    /// Whether `attrs` gate their item on `#[cfg(feature = ...)]`,
    /// incrementing [`Self::feature_gated_depth`] when they do — pairs with
    /// [`Self::exit_feature_gated`], called once per visited item so
    /// `merged-stub` can tell whether it's currently inside such a scope
    /// (see [`has_feature_cfg`]).
    fn enter_feature_gated(&mut self, attrs: &[Attribute]) -> bool {
        let gated = has_feature_cfg(attrs);
        if gated {
            self.feature_gated_depth += 1;
        }
        gated
    }

    /// Undoes [`Self::enter_feature_gated`]'s increment, if any.
    fn exit_feature_gated(&mut self, gated: bool) {
        if gated {
            self.feature_gated_depth -= 1;
        }
    }

    /// Bookkeeping shared verbatim by `visit_item_fn` and
    /// `visit_impl_item_fn`: records this fn/method's [`ItemSpan`] and runs
    /// the checks whose call shape doesn't differ between a free fn and a
    /// method (see [`Self::check_catch_all_error`],
    /// [`Self::check_doc_restates_signature`], [`Self::check_silent_default`],
    /// [`Self::check_context_free_propagation`]). Returns whether `attrs` is
    /// `#[cfg(feature = ...)]`-gated (see [`Self::enter_feature_gated`]).
    fn enter_fn(
        &mut self,
        vis: &Visibility,
        attrs: &[Attribute],
        sig: &syn::Signature,
        block: &Block,
        span: proc_macro2::Span,
    ) -> bool {
        self.item_spans.push(ItemSpan {
            start_line: span.start().line,
            end_line: span.end().line,
            item_path: self.current_item_path(),
        });
        self.check_catch_all_error(vis, sig, block, span);
        self.check_doc_restates_signature(attrs, sig, span);
        self.check_silent_default(block);
        self.check_context_free_propagation(sig, block, span);
        self.enter_feature_gated(attrs)
    }

    fn check_catch_all_error(
        &mut self,
        vis: &Visibility,
        sig: &syn::Signature,
        block: &Block,
        span: proc_macro2::Span,
    ) {
        if !matches!(vis, Visibility::Public(_)) {
            return;
        }
        let Some(ty) = return_type(&sig.output) else {
            return;
        };
        if !contains_catch_all_error(ty, self.allow_anyhow_at_boundary) {
            return;
        }
        if !discards_error_via_map_err(block) {
            return;
        }
        let item_path = self.current_item_path();
        self.record(CATCH_ALL_ERROR_RULE, span, Severity::Warn, item_path);
    }

    /// A doc-commented function/method/trait-default with a literally empty
    /// body (see todo.md §G2 `empty-impl`). Restricted to a *literally*
    /// empty block deliberately — a one-liner like `{ Config::default() }`
    /// never matches, since that's a legitimate (if terse) implementation,
    /// not a stub.
    fn check_empty_impl(&mut self, attrs: &[Attribute], block: &Block, span: proc_macro2::Span) {
        if has_doc_comment(attrs) && block.stmts.is_empty() {
            let item_path = self.current_item_path();
            self.record(EMPTY_IMPL_RULE, span, Severity::Warn, item_path);
        }
    }

    /// A `#[test]` fn (without `#[should_panic]`) whose body has no visible
    /// assertion path (see todo.md §G2 `assertion-free-test`).
    fn check_assertion_free_test(&mut self, node: &ItemFn) {
        if !has_test_attr(&node.attrs)
            || node
                .attrs
                .iter()
                .any(|attr| attr.path().is_ident("should_panic"))
        {
            return;
        }
        let returns_result = returns_result_type(&node.sig.output);
        let mut scanner = AssertionScanner {
            found: false,
            returns_result,
        };
        scanner.visit_block(&node.block);
        if !scanner.found {
            let item_path = self.current_item_path();
            self.record(
                ASSERTION_FREE_TEST_RULE,
                node.span(),
                Severity::Warn,
                item_path,
            );
        }
    }

    /// `let data1 = ...;` / `let temp2 = ...;` — a `let` binding whose name
    /// is a generic placeholder word plus a numeric suffix (see todo.md §G3
    /// `generic-naming`). Deliberately does NOT check the bare
    /// (non-suffixed) local name — `let result = do_thing()?;` is completely
    /// idiomatic Rust, and flagging every private local named `data` or
    /// `result` would be pure noise. The numeric-suffix shape (`data1`,
    /// `data2`, ...) is a distinctive enough signal on its own that it
    /// doesn't need that mitigation.
    fn check_generic_naming_local(&mut self, pat: &Pat, span: proc_macro2::Span) {
        let Pat::Ident(pat_ident) = pat else {
            return;
        };
        let name = pat_ident.ident.to_string();
        let stripped = strip_trailing_digits(&name);
        if stripped.len() == name.len() {
            return;
        }
        if is_generic_word(stripped) {
            let item_path = self.current_item_path();
            self.record(GENERIC_NAMING_RULE, span, Severity::Info, item_path);
        }
    }

    /// A `pub` named item (fn, struct, or enum) whose own name is exactly a
    /// generic placeholder word (see todo.md §G3 `generic-naming`) — the
    /// identical "is this `pub` name generic" check shared by
    /// [`check_generic_naming_item_fn`](Self::check_generic_naming_item_fn),
    /// [`check_generic_naming_item_struct`](Self::check_generic_naming_item_struct),
    /// and [`check_generic_naming_item_enum`](Self::check_generic_naming_item_enum).
    fn check_generic_naming_named_item(
        &mut self,
        vis: &Visibility,
        ident: &syn::Ident,
        span: proc_macro2::Span,
    ) {
        if matches!(vis, Visibility::Public(_)) && is_generic_word(&ident.to_string()) {
            let item_path = self.current_item_path();
            self.record(GENERIC_NAMING_RULE, span, Severity::Info, item_path);
        }
    }

    /// A top-level `pub fn` whose name is exactly a generic placeholder word
    /// (see todo.md §G3 `generic-naming`). Scoped to free `pub fn`s only —
    /// not called from `visit_impl_item_fn`, since a method's name reads
    /// very differently in context of its receiver type (`Cache::get` isn't
    /// generic the way a free function named `get` would be); the public,
    /// free-standing API surface is where a generic name is the clearest
    /// naming problem.
    fn check_generic_naming_item_fn(&mut self, node: &ItemFn) {
        self.check_generic_naming_named_item(&node.vis, &node.sig.ident, node.span());
    }

    /// A `pub struct` whose name, or one of whose `pub` field names, is
    /// exactly a generic placeholder word (see todo.md §G3 `generic-naming`).
    fn check_generic_naming_item_struct(&mut self, node: &syn::ItemStruct) {
        self.check_generic_naming_named_item(&node.vis, &node.ident, node.span());
        for field in &node.fields {
            if let Some(ident) = &field.ident {
                self.check_generic_naming_named_item(&field.vis, ident, field.span());
            }
        }
    }

    /// A `pub enum` whose name is exactly a generic placeholder word (see
    /// todo.md §G3 `generic-naming`).
    fn check_generic_naming_item_enum(&mut self, node: &syn::ItemEnum) {
        self.check_generic_naming_named_item(&node.vis, &node.ident, node.span());
    }

    /// A doc comment that is a pure echo of the fn's signature — e.g.
    /// `/// Returns the result.` over `fn f() -> Result<...>` (see todo.md
    /// §G3 `doc-restates-signature`). Deliberately narrow: only fires when
    /// the whole doc text is short (≤6 tokens) AND every content word in it
    /// also appears in the signature, so real prose describing *what* or
    /// *why* never matches.
    fn check_doc_restates_signature(
        &mut self,
        attrs: &[Attribute],
        sig: &syn::Signature,
        span: proc_macro2::Span,
    ) {
        let doc_text = doc_comment_text(attrs);
        let Some(doc_text) = doc_text else {
            return;
        };
        let doc_tokens = tokenize(&doc_text);
        if doc_tokens.is_empty() || doc_tokens.len() > 6 {
            return;
        }
        const STOPWORDS: &[&str] = &[
            "returns", "return", "get", "gets", "the", "a", "an", "of", "for",
        ];
        let content_tokens: Vec<&String> = doc_tokens
            .iter()
            .filter(|token| !STOPWORDS.contains(&token.as_str()))
            .collect();
        if content_tokens.is_empty() {
            return;
        }
        let sig_tokens = signature_tokens(sig);
        if content_tokens
            .iter()
            .all(|token| sig_tokens.contains(token.as_str()))
        {
            let item_path = self.current_item_path();
            self.record(DOC_RESTATES_SIGNATURE_RULE, span, Severity::Info, item_path);
        }
    }

    /// `.unwrap_or_default()` / `.unwrap_or_else(|_| ..default())` calls
    /// (see [`SilentDefaultVisitor`]), corroborated by a function-wide
    /// absence of any error-observing call (see [`error_observation_present`]
    /// — see todo.md §G1 `silent-default`). Both signals are required: the
    /// structural call shape alone doesn't distinguish "the error was never
    /// worth observing" from "it's observed elsewhere in this function, just
    /// not at this call site" — the absence check is function-granularity,
    /// not proof this specific call site is unobserved (see
    /// [`SILENT_DEFAULT_RULE`]'s registry `exclusions`).
    fn check_silent_default(&mut self, block: &Block) {
        let mut collector = SilentDefaultVisitor { sites: Vec::new() };
        collector.visit_block(block);
        if collector.sites.is_empty() || error_observation_present(block) {
            return;
        }
        let item_path = self.current_item_path();
        for (span, method) in collector.sites {
            self.record_with_evidence(
                SILENT_DEFAULT_RULE,
                span,
                Severity::Warn,
                item_path.clone(),
                Some(serde_json::json!({
                    "file": self.file.display().to_string(),
                    "line": span.start().line,
                    "method": method,
                })),
            );
        }
    }

    /// A function whose written return type is a recognized opaque-error
    /// idiom, with 2+ distinct `?`-sites and zero `.context(`/
    /// `.with_context(` calls anywhere in its body (see todo.md §G1
    /// `context-free-propagation`, [`is_opaque_error_return_type`]). Fires
    /// only when this function's own body contains not a single
    /// `.context(`/`.with_context(` call — a function that already uses
    /// `.context()` for *some* of its `?`-sites but not all of them is not
    /// flagged, since the author is clearly already following that practice
    /// in this function (see [`CONTEXT_FREE_PROPAGATION_RULE`]'s registry
    /// `exclusions` for the precise semantics chosen here).
    fn check_context_free_propagation(
        &mut self,
        sig: &syn::Signature,
        block: &Block,
        span: proc_macro2::Span,
    ) {
        let Some(ty) = return_type(&sig.output) else {
            return;
        };
        if !is_opaque_error_return_type(ty) {
            return;
        }
        let mut scanner = TrySiteScanner {
            try_site_keys: std::collections::HashSet::new(),
            has_context_call: false,
        };
        scanner.visit_block(block);
        if scanner.try_site_keys.len() < 2 || scanner.has_context_call {
            return;
        }
        let item_path = self.current_item_path();
        self.record_with_evidence(
            CONTEXT_FREE_PROPAGATION_RULE,
            span,
            Severity::Warn,
            item_path,
            Some(serde_json::json!({
                "file": self.file.display().to_string(),
                "function": sig.ident.to_string(),
                "line": span.start().line,
                "try_site_count": scanner.try_site_keys.len(),
            })),
        );
    }
}

impl<'ast> Visit<'ast> for SlopVisitor<'_> {
    fn visit_item_mod(&mut self, node: &'ast ItemMod) {
        let gated = self.enter_feature_gated(&node.attrs);
        if node.content.is_some() {
            self.path.push(node.ident.to_string());
            visit::visit_item_mod(self, node);
            self.path.pop();
        } else {
            visit::visit_item_mod(self, node);
        }
        self.exit_feature_gated(gated);
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        let gated = self.enter_feature_gated(&node.attrs);
        let type_ident = type_name(&node.self_ty);
        self.path.push(type_ident.clone());
        let is_display_impl = is_display_trait_impl(node);
        if is_display_impl {
            self.display_impl_type_stack.push(type_ident);
        }
        self.visitor_trait_impl_stack
            .push(is_ast_visitor_trait_impl(node));
        self.drop_impl_stack.push(is_drop_trait_impl(node));
        visit::visit_item_impl(self, node);
        self.drop_impl_stack.pop();
        self.visitor_trait_impl_stack.pop();
        if is_display_impl {
            self.display_impl_type_stack.pop();
        }
        self.path.pop();
        self.exit_feature_gated(gated);
    }

    fn visit_item_trait(&mut self, node: &'ast ItemTrait) {
        self.path.push(node.ident.to_string());
        visit::visit_item_trait(self, node);
        self.path.pop();
    }

    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
        self.path.push(node.ident.to_string());
        self.check_generic_naming_item_struct(node);
        visit::visit_item_struct(self, node);
        self.path.pop();
    }

    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
        self.path.push(node.ident.to_string());
        self.check_generic_naming_item_enum(node);
        visit::visit_item_enum(self, node);
        self.path.pop();
    }

    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        self.path.push(node.sig.ident.to_string());
        self.check_empty_impl(&node.attrs, &node.block, node.span());
        self.check_assertion_free_test(node);
        self.check_generic_naming_item_fn(node);
        let gated = self.enter_fn(&node.vis, &node.attrs, &node.sig, &node.block, node.span());
        visit::visit_item_fn(self, node);
        self.exit_feature_gated(gated);
        self.path.pop();
    }

    fn visit_impl_item_fn(&mut self, node: &'ast ImplItemFn) {
        self.path.push(node.sig.ident.to_string());
        let is_visitor_trait_override = self
            .visitor_trait_impl_stack
            .last()
            .copied()
            .unwrap_or(false);
        if !is_visitor_trait_override {
            self.check_empty_impl(&node.attrs, &node.block, node.span());
        }
        let gated = self.enter_fn(&node.vis, &node.attrs, &node.sig, &node.block, node.span());
        let is_drop_drop =
            self.drop_impl_stack.last().copied().unwrap_or(false) && node.sig.ident == "drop";
        let prev_in_drop_drop_body = self.in_drop_drop_body;
        self.in_drop_drop_body = is_drop_drop;
        visit::visit_impl_item_fn(self, node);
        self.in_drop_drop_body = prev_in_drop_drop_body;
        self.exit_feature_gated(gated);
        self.path.pop();
    }

    fn visit_trait_item_fn(&mut self, node: &'ast TraitItemFn) {
        self.path.push(node.sig.ident.to_string());
        if let Some(default) = &node.default {
            self.check_empty_impl(&node.attrs, default, node.span());
        }
        visit::visit_trait_item_fn(self, node);
        self.path.pop();
    }

    /// `let _ = <call-expression>;` — a call whose result is explicitly bound
    /// to `_` rather than a real name (see todo.md §G1 `swallowed-result`).
    /// Exempt inside `Drop::drop`'s own body (see [`Self::in_drop_drop_body`]):
    /// `drop` cannot return a `Result`, so `let _ = fallible();` is the only
    /// correct idiom there, not a discarded error.
    fn visit_local(&mut self, node: &'ast Local) {
        if !self.in_drop_drop_body
            && matches!(node.pat, Pat::Wild(_))
            && let Some(init) = &node.init
            && matches!(init.expr.as_ref(), Expr::Call(_) | Expr::MethodCall(_))
        {
            let item_path = self.current_item_path();
            self.record(
                SWALLOWED_RESULT_RULE,
                node.span(),
                Severity::Warn,
                item_path,
            );
        }
        self.check_generic_naming_local(&node.pat, node.span());
        visit::visit_local(self, node);
    }

    /// A bare expression-statement ending in `.ok()` — converts a `Result` to
    /// an `Option` and immediately discards it (see todo.md §G1
    /// `swallowed-result`). Only statements with a trailing `;` count: a tail
    /// expression's value isn't discarded. Exempt inside `Drop::drop`'s own
    /// body, same rationale as [`Self::visit_local`] above.
    fn visit_stmt(&mut self, stmt: &'ast Stmt) {
        if !self.in_drop_drop_body
            && let Stmt::Expr(Expr::MethodCall(call), Some(_)) = stmt
            && call.method == "ok"
        {
            let item_path = self.current_item_path();
            self.record(
                SWALLOWED_RESULT_RULE,
                call.span(),
                Severity::Warn,
                item_path,
            );
        }
        visit::visit_stmt(self, stmt);
    }

    /// `match ... { Err(_) => {}, ... }` — an empty error-handling arm (see
    /// todo.md §G1 `empty-error-arm`).
    fn visit_arm(&mut self, arm: &'ast Arm) {
        if is_err_wildcard_pat(&arm.pat) && is_empty_block_expr(&arm.body) {
            let item_path = self.current_item_path();
            self.record(EMPTY_ERROR_ARM_RULE, arm.span(), Severity::Warn, item_path);
        }
        visit::visit_arm(self, arm);
    }

    /// `if let Err(_) = ... { }` with no `else` — the `if let` sibling of
    /// `empty-error-arm`.
    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Some((if_expr, pat)) = if_let_cond_pat(expr)
            && if_expr.else_branch.is_none()
            && if_expr.then_branch.stmts.is_empty()
            && is_err_wildcard_pat(pat)
        {
            let item_path = self.current_item_path();
            self.record(
                EMPTY_ERROR_ARM_RULE,
                if_expr.span(),
                Severity::Warn,
                item_path,
            );
        }
        visit::visit_expr(self, expr);
    }

    /// Every `#[allow(...)]`/`#[expect(...)]` attribute, anywhere (see
    /// todo.md §G1 `suppression-debt`), and every `#[ignore]`/`#[ignore =
    /// "..."]` attribute, anywhere (see todo.md §G2
    /// `ignored-test-accumulation`).
    fn visit_attribute(&mut self, attr: &'ast Attribute) {
        if attr.path().is_ident("allow") || attr.path().is_ident("expect") {
            let item_path = attr
                .parse_args_with(Punctuated::<SynPath, Token![,]>::parse_terminated)
                .ok()
                .map(|paths| {
                    paths
                        .iter()
                        .map(path_to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .filter(|names| !names.is_empty())
                .unwrap_or_else(|| self.file.display().to_string());
            self.record(
                SUPPRESSION_DEBT_RULE,
                attr.span(),
                Severity::Info,
                item_path,
            );
        } else if attr.path().is_ident("ignore") {
            let reason = meta_name_value_str(&attr.meta);
            let item_path = self.current_item_path();
            self.record_with_evidence(
                IGNORED_TEST_ACCUMULATION_RULE,
                attr.span(),
                Severity::Info,
                item_path,
                reason.map(|reason| serde_json::json!({ "reason": reason })),
            );
        }
        visit::visit_attribute(self, attr);
    }

    /// `todo!()`/`unimplemented!()` outside a `#[cfg(feature = ...)]`-gated
    /// scope (see todo.md §G2 `merged-stub`), and tautological `assert!`s
    /// (see todo.md §G2 `tautological-test`).
    fn visit_macro(&mut self, mac: &'ast Macro) {
        if (mac.path.is_ident("todo") || mac.path.is_ident("unimplemented"))
            && self.feature_gated_depth == 0
        {
            let item_path = self.current_item_path();
            self.record(MERGED_STUB_RULE, mac.span(), Severity::Warn, item_path);
        } else if mac.path.is_ident("assert") {
            if let Some(args) = parse_macro_expr_args(mac)
                && let Some(Expr::Lit(ExprLit {
                    lit: Lit::Bool(value),
                    ..
                })) = args.first()
                && value.value
            {
                let item_path = self.current_item_path();
                self.record(
                    TAUTOLOGICAL_TEST_RULE,
                    mac.span(),
                    Severity::Warn,
                    item_path,
                );
            }
        } else if mac.path.is_ident("assert_eq")
            && let Some(args) = parse_macro_expr_args(mac)
            && let (Some(lhs), Some(rhs)) = (args.first(), args.get(1))
            // Token-string comparison, not `Expr: PartialEq` (`syn`'s
            // `extra-traits` feature isn't enabled here). This is an
            // accepted false-positive trap: two expressions with identical
            // source text can still differ at runtime if they have side
            // effects — an accepted, documented imprecision of this syntax fact.
            && quote!(#lhs).to_string() == quote!(#rhs).to_string()
        {
            let item_path = self.current_item_path();
            self.record(
                TAUTOLOGICAL_TEST_RULE,
                mac.span(),
                Severity::Warn,
                item_path,
            );
        } else if (mac.path.is_ident("write") || mac.path.is_ident("format"))
            && let Some(type_name) = self.display_impl_type_stack.last()
            && macro_format_string_has_debug_placeholder(mac)
        {
            let item_path = self.current_item_path();
            self.record_with_evidence(
                DEBUG_FORMAT_LEAK_RULE,
                mac.span(),
                Severity::Warn,
                item_path,
                Some(serde_json::json!({
                    "file": self.file.display().to_string(),
                    "type_name": type_name,
                    "line": mac.span().start().line,
                })),
            );
        }
        visit::visit_macro(self, mac);
    }
}

fn path_to_string(path: &SynPath) -> String {
    path.segments
        .iter()
        .map(|segment| segment.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

/// Whether `pat` is any `Err(..)` tuple-struct pattern, regardless of the
/// inner pattern — the shared match both [`is_err_wildcard_pat`] (which
/// additionally requires a wildcard/rest inner pattern) and [`is_err_pat`]
/// build on.
fn as_err_tuple_struct(pat: &Pat) -> Option<&syn::PatTupleStruct> {
    match pat {
        Pat::TupleStruct(tuple_struct)
            if tuple_struct
                .path
                .segments
                .last()
                .is_some_and(|segment| segment.ident == "Err") =>
        {
            Some(tuple_struct)
        }
        _ => None,
    }
}

/// Whether `pat` is `Err(_)` or `Err(..)`.
fn is_err_wildcard_pat(pat: &Pat) -> bool {
    as_err_tuple_struct(pat).is_some_and(|tuple_struct| {
        tuple_struct.elems.len() == 1
            && matches!(tuple_struct.elems[0], Pat::Wild(_) | Pat::Rest(_))
    })
}

/// Whether `expr` is a literally empty block (`{}`).
fn is_empty_block_expr(expr: &Expr) -> bool {
    matches!(expr, Expr::Block(block) if block.block.stmts.is_empty())
}

/// Whether `expr` is `if let <pat> = .. { .. }`, returning the `if`'s own
/// `Expr::If` node and the condition's pattern when it matches — the shared
/// `if let` destructuring both `SlopVisitor::visit_expr`'s `empty-error-arm`
/// check and [`error_observation_present`]'s `ErrorObservationScanner::visit_expr`
/// check start from.
fn if_let_cond_pat(expr: &Expr) -> Option<(&syn::ExprIf, &Pat)> {
    let Expr::If(if_expr) = expr else {
        return None;
    };
    let Expr::Let(let_expr) = if_expr.cond.as_ref() else {
        return None;
    };
    Some((if_expr, &let_expr.pat))
}

/// Whether `ty`, written syntactically, is or contains `Box<dyn ... Error
/// ...>` or a path ending in `anyhow::Error`/`anyhow::Result` (see todo.md
/// §G1 `catch-all-error`). Recurses into generic arguments so both a bare
/// `Box<dyn Error>` return type and `Result<_, Box<dyn Error>>` match. When
/// `allow_anyhow_at_boundary` is set, `anyhow::Error`/`anyhow::Result` no
/// longer match — but `Box<dyn Error>` still does (see GitHub issue #5:
/// anyhow is the documented propagation convention, `Box<dyn Error>` has no
/// comparable exemption).
fn contains_catch_all_error(ty: &Type, allow_anyhow_at_boundary: bool) -> bool {
    match ty {
        Type::TraitObject(trait_object) => is_error_trait_object(trait_object),
        Type::Path(type_path) => {
            let segments = &type_path.path.segments;
            if !allow_anyhow_at_boundary && segments.len() >= 2 {
                let last = segments.last().unwrap();
                let prev = &segments[segments.len() - 2];
                if prev.ident == "anyhow" && (last.ident == "Error" || last.ident == "Result") {
                    return true;
                }
            }
            segments.iter().any(|segment| {
                let PathArguments::AngleBracketed(args) = &segment.arguments else {
                    return false;
                };
                args.args.iter().any(|arg| match arg {
                    GenericArgument::Type(inner) => {
                        contains_catch_all_error(inner, allow_anyhow_at_boundary)
                    }
                    _ => false,
                })
            })
        }
        _ => false,
    }
}

/// Whether a `dyn Trait [+ Trait ...]` object has a bound ending in `Error`
/// (`dyn Error`, `dyn std::error::Error`, `dyn Error + Send + Sync`, ...).
fn is_error_trait_object(trait_object: &syn::TypeTraitObject) -> bool {
    trait_object.bounds.iter().any(|bound| {
        if let TypeParamBound::Trait(trait_bound) = bound {
            trait_bound
                .path
                .segments
                .last()
                .is_some_and(|segment| segment.ident == "Error")
        } else {
            false
        }
    })
}

/// Whether `block` contains a `.map_err(|_| ..)` call whose closure takes
/// exactly one wildcard parameter (`_` or `_: T`) — the body-level signal
/// `check_catch_all_error` requires alongside a type-erased return type
/// (see todo.md §F "Praxisbeleg", auditmysite 2026-07-24, GitHub issue #11):
/// a closure that never binds the original error value discards it, rather
/// than merely converting or propagating it. Plain `?`/`anyhow!(..)`
/// propagation — which preserves the source error chain
/// (`std::error::Error::source()`) — does not match this and is not
/// flagged; that precision audit found 0 of 8 `catch-all-error` findings
/// real in a codebase that only ever used exactly that idiomatic style
/// through a type-erased boundary. A syntax-only proxy, not a completeness
/// proof: a `.map_err` closure that *does* bind its parameter but never
/// uses it, or some other information-discarding shape (e.g. a `match`
/// collapsing distinct arms to the same message), is not distinguished
/// either way.
fn discards_error_via_map_err(block: &Block) -> bool {
    struct MapErrDiscardVisitor {
        found: bool,
    }

    impl<'ast> Visit<'ast> for MapErrDiscardVisitor {
        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
            if node.method == "map_err" && first_arg_is_wildcard_closure(&node.args).is_some() {
                self.found = true;
            }
            visit::visit_expr_method_call(self, node);
        }

        fn visit_item_fn(&mut self, _node: &'ast ItemFn) {}
    }

    let mut visitor = MapErrDiscardVisitor { found: false };
    visitor.visit_block(block);
    visitor.found
}

/// Whether `pat` is a wildcard (`_`) or a type-ascribed wildcard (`_: T`) —
/// shared by [`discards_error_via_map_err`]'s `.map_err(|_| ..)` match and
/// [`SilentDefaultVisitor`]'s `.unwrap_or_else(|_| ..)` match: both need "the
/// closure never binds the original error value" as their signal.
fn pat_is_wildcard(pat: &Pat) -> bool {
    match pat {
        Pat::Wild(_) => true,
        Pat::Type(pat_type) => pat_is_wildcard(&pat_type.pat),
        _ => false,
    }
}

/// Whether `args`' first argument is a closure taking exactly one wildcard
/// parameter (`_` or `_: T`) — the "closure discards the bound value" call
/// shape shared by [`discards_error_via_map_err`]'s `.map_err(|_| ..)` match
/// and [`SilentDefaultVisitor`]'s `.unwrap_or_else(|_| ..)` match.
fn first_arg_is_wildcard_closure(args: &Punctuated<Expr, Token![,]>) -> Option<&syn::ExprClosure> {
    let Some(Expr::Closure(closure)) = args.first() else {
        return None;
    };
    if closure.inputs.len() == 1 && pat_is_wildcard(&closure.inputs[0]) {
        Some(closure)
    } else {
        None
    }
}

/// Whether `expr` is (optionally through a single-tail-expression block) a
/// call to `Default::default()` or `<SomeType>::default()` with zero
/// arguments — the fallback shape [`SilentDefaultVisitor`] requires for
/// `.unwrap_or_else(|_| ..)` to count as `silent-default` (see todo.md §G1).
fn is_default_call(expr: &Expr) -> bool {
    let expr = match expr {
        Expr::Block(block) if block.block.stmts.len() == 1 => match &block.block.stmts[0] {
            Stmt::Expr(inner, None) => inner,
            _ => return false,
        },
        other => other,
    };
    let Expr::Call(call) = expr else {
        return false;
    };
    if !call.args.is_empty() {
        return false;
    }
    let Expr::Path(path) = call.func.as_ref() else {
        return false;
    };
    path.path
        .segments
        .last()
        .is_some_and(|segment| segment.ident == "default")
}

/// Collects every `.unwrap_or_default()` / `.unwrap_or_else(|_| ..default())`
/// call site in a function body (see todo.md §G1 `silent-default`,
/// [`SlopVisitor::check_silent_default`]). Does not descend into nested `fn`
/// items — same scoping as [`discards_error_via_map_err`]'s
/// `MapErrDiscardVisitor`.
struct SilentDefaultVisitor {
    /// `(call span, matched method name)` per call site.
    sites: Vec<(proc_macro2::Span, &'static str)>,
}

impl<'ast> Visit<'ast> for SilentDefaultVisitor {
    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
        if node.method == "unwrap_or_default" && node.args.is_empty() {
            self.sites.push((node.span(), "unwrap_or_default"));
        } else if node.method == "unwrap_or_else"
            && let Some(closure) = first_arg_is_wildcard_closure(&node.args)
            && is_default_call(&closure.body)
        {
            self.sites.push((node.span(), "unwrap_or_else"));
        }
        visit::visit_expr_method_call(self, node);
    }

    fn visit_item_fn(&mut self, _node: &'ast ItemFn) {}
}

/// Whether `block` contains, anywhere, a call shape that observes/surfaces an
/// error — the corroborating absence signal for `silent-default` (see
/// [`SlopVisitor::check_silent_default`], todo.md §G1). A function-wide
/// check, not scoped to any one call site: `.inspect_err(`, a `log::`/
/// `tracing::`-qualified macro or path call, an unqualified `eprintln!`/
/// `warn!`/`error!` macro call, or an `if let Err(..) = ..` pattern. Does not
/// descend into nested `fn` items.
fn error_observation_present(block: &Block) -> bool {
    struct ErrorObservationScanner {
        found: bool,
    }

    impl<'ast> Visit<'ast> for ErrorObservationScanner {
        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
            if node.method == "inspect_err" {
                self.found = true;
            }
            visit::visit_expr_method_call(self, node);
        }

        fn visit_macro(&mut self, mac: &'ast Macro) {
            let first_segment = mac.path.segments.first().map(|s| s.ident.to_string());
            let last_segment = mac.path.segments.last().map(|s| s.ident.to_string());
            let is_log_or_tracing_qualified =
                matches!(first_segment.as_deref(), Some("log") | Some("tracing"))
                    && mac.path.segments.len() >= 2;
            let is_direct_observation_macro = matches!(
                last_segment.as_deref(),
                Some("eprintln") | Some("warn") | Some("error")
            );
            if is_log_or_tracing_qualified || is_direct_observation_macro {
                self.found = true;
            }
            visit::visit_macro(self, mac);
        }

        fn visit_expr(&mut self, expr: &'ast Expr) {
            if let Some((_, pat)) = if_let_cond_pat(expr)
                && is_err_pat(pat)
            {
                self.found = true;
            }
            visit::visit_expr(self, expr);
        }

        fn visit_item_fn(&mut self, _node: &'ast ItemFn) {}
    }

    let mut scanner = ErrorObservationScanner { found: false };
    scanner.visit_block(block);
    scanner.found
}

/// Whether `pat` is `Err(..)` with any inner pattern — broader than
/// [`is_err_wildcard_pat`] (which requires a wildcard/rest inner pattern):
/// [`error_observation_present`] counts an `if let Err(e) = ..` that binds
/// and uses the error as an observation attempt too, not just the
/// `empty-error-arm`-shaped wildcard case.
fn is_err_pat(pat: &Pat) -> bool {
    as_err_tuple_struct(pat).is_some()
}

/// Whether `ty`, written syntactically, is a recognized opaque-error return
/// type — `anyhow::Result<_>`/`eyre::Result<_>` sugar, or `Result<_, E>`
/// where `E` is `anyhow::Error`, `eyre::Report`, or `Box<dyn
/// std::error::Error ..>` (see todo.md §G1 `context-free-propagation`,
/// [`SlopVisitor::check_context_free_propagation`]). A syntax-only match
/// against the function's own written return type, never a type-checker-
/// resolved type — a type alias that resolves to one of these shapes without
/// spelling it out is not recognized.
fn is_opaque_error_return_type(ty: &Type) -> bool {
    let Type::Path(type_path) = ty else {
        return false;
    };
    let segments = &type_path.path.segments;
    let Some(last) = segments.last() else {
        return false;
    };
    if last.ident != "Result" {
        return false;
    }
    if segments.len() >= 2 {
        let prev = &segments[segments.len() - 2];
        if prev.ident == "anyhow" || prev.ident == "eyre" {
            return true;
        }
    }
    let PathArguments::AngleBracketed(args) = &last.arguments else {
        return false;
    };
    args.args
        .iter()
        .filter_map(|arg| match arg {
            GenericArgument::Type(inner) => Some(inner),
            _ => None,
        })
        .nth(1)
        .is_some_and(is_opaque_error_type)
}

/// Whether `ty` is `anyhow::Error`, `eyre::Report`, or `Box<dyn
/// std::error::Error ..>` — the `E` shapes [`is_opaque_error_return_type`]
/// recognizes inside `Result<_, E>`.
fn is_opaque_error_type(ty: &Type) -> bool {
    match ty {
        Type::TraitObject(trait_object) => is_error_trait_object(trait_object),
        Type::Path(type_path) => {
            let segments = &type_path.path.segments;
            let Some(last) = segments.last() else {
                return false;
            };
            if last.ident == "Box" {
                let PathArguments::AngleBracketed(args) = &last.arguments else {
                    return false;
                };
                return args.args.iter().any(|arg| match arg {
                    GenericArgument::Type(Type::TraitObject(trait_object)) => {
                        is_error_trait_object(trait_object)
                    }
                    _ => false,
                });
            }
            if segments.len() >= 2 {
                let prev = &segments[segments.len() - 2];
                return (prev.ident == "anyhow" && last.ident == "Error")
                    || (prev.ident == "eyre" && last.ident == "Report");
            }
            false
        }
        _ => false,
    }
}

/// Collects every distinct `?`-site's dedup key (the underlying expression's
/// token string — same idiom as `tautological-test`'s
/// `quote!(#lhs).to_string()` comparison above) and whether `.context(`/
/// `.with_context(` is called anywhere in the block (see todo.md §G1
/// `context-free-propagation`, [`SlopVisitor::check_context_free_propagation`]).
/// Does not descend into nested `fn` items.
struct TrySiteScanner {
    try_site_keys: std::collections::HashSet<String>,
    has_context_call: bool,
}

impl<'ast> Visit<'ast> for TrySiteScanner {
    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Expr::Try(try_expr) = expr {
            self.try_site_keys.insert(quote!(#try_expr).to_string());
        }
        visit::visit_expr(self, expr);
    }

    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
        if node.method == "context" || node.method == "with_context" {
            self.has_context_call = true;
        }
        visit::visit_expr_method_call(self, node);
    }

    fn visit_item_fn(&mut self, _node: &'ast ItemFn) {}
}

/// Whether `node`'s trait path's last segment satisfies `predicate` (and the
/// impl isn't a negative `impl !Trait for T`) — the shared "is this impl a
/// `impl SomeTrait for T`" check behind [`is_display_trait_impl`],
/// [`is_ast_visitor_trait_impl`], and [`is_drop_trait_impl`].
fn impl_trait_ident_matches(node: &ItemImpl, predicate: impl Fn(&str) -> bool) -> bool {
    node.trait_.as_ref().is_some_and(|(bang, path, _)| {
        bang.is_none()
            && path
                .segments
                .last()
                .is_some_and(|segment| predicate(&segment.ident.to_string()))
    })
}

/// Whether `node` is a manual `impl std::fmt::Display for T` block (matched
/// on the trait path's last segment, so both `impl Display for T` and `impl
/// std::fmt::Display for T` match; `impl Debug for T` never does) — see
/// todo.md §K2 `debug-format-leak`.
fn is_display_trait_impl(node: &ItemImpl) -> bool {
    impl_trait_ident_matches(node, |ident| ident == "Display")
}

/// Whether `node` implements one of the standard `syn` AST-visitor traits
/// (`Visit`, `VisitMut`, `Fold`) — matched on the trait path's last segment
/// only, like [`is_display_trait_impl`]. An empty, doc-commented override of
/// one of these traits' methods (e.g. `fn visit_attribute(&mut self, _node:
/// &Attribute) {}`) is a deliberate "skip descending into this AST node
/// type" choice constrained by the trait's own contract, not a stub — see
/// todo.md §G2 `empty-impl`'s registry `exclusions`.
fn is_ast_visitor_trait_impl(node: &ItemImpl) -> bool {
    impl_trait_ident_matches(node, |ident| matches!(ident, "Visit" | "VisitMut" | "Fold"))
}

/// Whether `node` is `impl Drop for _` — matched on the trait path's last
/// segment only, like [`is_display_trait_impl`]. Consulted together with the
/// method name (`drop`) to detect `Drop::drop`'s body, where `let _ =
/// fallible();` is the only correct idiom since `drop` cannot return a
/// `Result` (see todo.md §G1 `swallowed-result`'s registry `exclusions`).
fn is_drop_trait_impl(node: &ItemImpl) -> bool {
    impl_trait_ident_matches(node, |ident| ident == "Drop")
}

/// Parses `mac`'s body as a comma-separated expression list — the
/// `assert!(..)`/`assert_eq!(..)`/`write!`/`format!` argument-list shape
/// [`SlopVisitor::visit_macro`] and [`macro_format_string_has_debug_placeholder`]
/// both parse identically.
fn parse_macro_expr_args(mac: &Macro) -> Option<Punctuated<Expr, Token![,]>> {
    mac.parse_body_with(Punctuated::<Expr, Token![,]>::parse_terminated)
        .ok()
}

/// Whether `expr` is a string-literal expression, returning its value —
/// shared by [`macro_format_string_has_debug_placeholder`]'s search for a
/// macro's string-literal format-string argument and
/// [`meta_name_value_str`]'s `#[name = "..."]` attribute-value extraction.
fn expr_str_lit(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Lit(ExprLit {
            lit: Lit::Str(text),
            ..
        }) => Some(text.value()),
        _ => None,
    }
}

/// Extracts the string-literal value from a `#[name = "value"]` attribute
/// (a `Meta::NameValue` whose value is a string-literal expression) — shared
/// by `#[ignore = "..."]`'s reason extraction in `visit_attribute` and
/// [`doc_comment_text`]'s `#[doc = "..."]` extraction.
fn meta_name_value_str(meta: &Meta) -> Option<String> {
    match meta {
        Meta::NameValue(name_value) => expr_str_lit(&name_value.value),
        _ => None,
    }
}

/// Whether `mac`'s first string-literal argument (the format string, for
/// both `write!(f, "..")` and `format!("..")`) contains a `{:?}`/`{:#?}`
/// placeholder — a plain substring match, per todo.md §K2
/// `debug-format-leak`: a captured/positional debug placeholder written as
/// `{value:?}`/`{0:?}` is not recognized, only the literal `{:?}`/`{:#?}`
/// tokens are.
fn macro_format_string_has_debug_placeholder(mac: &Macro) -> bool {
    let Some(args) = parse_macro_expr_args(mac) else {
        return false;
    };
    args.iter()
        .find_map(expr_str_lit)
        .is_some_and(|text| text.contains("{:?}") || text.contains("{:#?}"))
}

/// Whether any attribute in `attrs` is a `#[cfg(...)]` whose contents
/// mention `feature` (see todo.md §G2 `merged-stub`). Only recognizes
/// `cfg(feature = ...)`, not `cfg(test)` — a `todo!()` inside `#[cfg(test)]`
/// is still flagged, matching the literal "Nicht-Feature-Branches" wording.
fn has_feature_cfg(attrs: &[Attribute]) -> bool {
    attrs
        .iter()
        .any(|attr| attr.path().is_ident("cfg") && quote!(#attr).to_string().contains("feature"))
}

/// The `T` in a fn's `-> T` return type, or `None` for `-> ()` (no arrow) —
/// shared by [`SlopVisitor::check_catch_all_error`],
/// [`SlopVisitor::check_context_free_propagation`], and
/// [`returns_result_type`].
fn return_type(output: &ReturnType) -> Option<&Type> {
    match output {
        ReturnType::Type(_, ty) => Some(ty.as_ref()),
        ReturnType::Default => None,
    }
}

/// Whether a fn's return type's last path segment is `Result` (mirrors how
/// [`contains_catch_all_error`] inspects types, but shallow — no need to
/// recurse into generic arguments here).
fn returns_result_type(output: &ReturnType) -> bool {
    let Some(ty) = return_type(output) else {
        return false;
    };
    let Type::Path(type_path) = ty else {
        return false;
    };
    type_path
        .path
        .segments
        .last()
        .is_some_and(|segment| segment.ident == "Result")
}

/// Placeholder words common in template/boilerplate naming (see todo.md §G3
/// `generic-naming`). Matched as an exact, case-insensitive, whole-identifier
/// comparison everywhere this list is used — never a substring match, so
/// `ConnectionManager` never matches `manager`.
const GENERIC_WORDS: &[&str] = &[
    "data",
    "result",
    "temp",
    "handler",
    "manager",
    "processor",
    "helper",
    "utils",
];

/// Whether `word`, lowercased, exactly equals one of [`GENERIC_WORDS`].
fn is_generic_word(word: &str) -> bool {
    let lower = word.to_lowercase();
    GENERIC_WORDS.contains(&lower.as_str())
}

/// Strips a trailing run of ASCII digits from `name`, if any (`"data1"` ->
/// `"data"`, `"data"` -> `"data"`).
fn strip_trailing_digits(name: &str) -> &str {
    name.trim_end_matches(|c: char| c.is_ascii_digit())
}

/// Collects every `#[doc = "..."]` attribute's string literal (covers both
/// `///` doc comments and explicit `#[doc]` attributes, which `syn` desugars
/// the same way — see [`has_doc_comment`]), joins them with spaces, and
/// trims. `None` if there's no doc comment at all. Reuses
/// [`meta_name_value_str`], the same extraction already used for
/// `#[ignore = "..."]` in `visit_attribute`.
fn doc_comment_text(attrs: &[Attribute]) -> Option<String> {
    let parts: Vec<String> = attrs
        .iter()
        .filter(|attr| attr.path().is_ident("doc"))
        .filter_map(|attr| meta_name_value_str(&attr.meta))
        .collect();
    if parts.is_empty() {
        return None;
    }
    let joined = parts.join(" ").trim().to_string();
    if joined.is_empty() {
        None
    } else {
        Some(joined)
    }
}

/// Lowercases `text` and splits it on non-alphanumeric boundaries (used by
/// [`SlopVisitor::check_doc_restates_signature`]; `crate::rules::slop_text` has its
/// own copy since it has no reason to depend on this module for a
/// three-line helper).
fn tokenize(text: &str) -> Vec<String> {
    text.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|token| !token.is_empty())
        .map(str::to_string)
        .collect()
}

/// The token set a doc comment is compared against in
/// [`SlopVisitor::check_doc_restates_signature`]: the fn's own name, its
/// return type's last path segment name, and — if there's exactly one
/// non-`self` parameter — that parameter's identifier and its type's last
/// path segment, all lowercased.
fn signature_tokens(sig: &syn::Signature) -> std::collections::HashSet<String> {
    let mut tokens = std::collections::HashSet::new();
    tokens.insert(sig.ident.to_string().to_lowercase());
    if let ReturnType::Type(_, ty) = &sig.output {
        tokens.insert(type_name(ty).to_lowercase());
    }
    let non_self_params: Vec<&syn::PatType> = sig
        .inputs
        .iter()
        .filter_map(|arg| match arg {
            syn::FnArg::Typed(pat_type) => Some(pat_type),
            syn::FnArg::Receiver(_) => None,
        })
        .collect();
    if let [pat_type] = non_self_params.as_slice() {
        if let Pat::Ident(pat_ident) = pat_type.pat.as_ref() {
            tokens.insert(pat_ident.ident.to_string().to_lowercase());
        }
        tokens.insert(type_name(&pat_type.ty).to_lowercase());
    }
    tokens
}

/// Nested scanner run over a `#[test]` fn's body to find a visible assertion
/// path (see todo.md §G2 `assertion-free-test`). Recurses into closures like
/// any other `Visit` implementation, so an assert-free closure body still
/// counts as "no assertion found" rather than being skipped.
struct AssertionScanner {
    found: bool,
    /// Whether the enclosing fn's return type is `Result<..>` — a bare `?`
    /// only counts as "the assertion" when the fn can actually propagate an
    /// `Err` out as a test failure.
    returns_result: bool,
}

impl<'ast> Visit<'ast> for AssertionScanner {
    fn visit_macro(&mut self, mac: &'ast Macro) {
        const ASSERT_MACROS: [&str; 16] = [
            "assert",
            "assert_eq",
            "assert_ne",
            "debug_assert",
            "debug_assert_eq",
            "debug_assert_ne",
            "panic",
            "unreachable",
            "assert_snapshot",
            "assert_json_snapshot",
            "assert_debug_snapshot",
            "assert_display_snapshot",
            "assert_yaml_snapshot",
            "assert_ron_snapshot",
            "assert_csv_snapshot",
            "assert_toml_snapshot",
        ];
        // Matches the last path segment, not just single-segment paths via
        // `is_ident` — otherwise a qualified call like
        // `insta::assert_snapshot!(...)` or `pretty_assertions::assert_eq!`
        // is invisible to this scanner (see GitHub issue #6).
        if mac
            .path
            .segments
            .last()
            .is_some_and(|segment| ASSERT_MACROS.contains(&segment.ident.to_string().as_str()))
        {
            self.found = true;
        }
        visit::visit_macro(self, mac);
    }

    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
        if matches!(
            node.method.to_string().as_str(),
            "unwrap" | "expect" | "unwrap_err" | "expect_err"
        ) {
            self.found = true;
        }
        visit::visit_expr_method_call(self, node);
    }

    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Expr::Try(_) = expr
            && self.returns_result
        {
            self.found = true;
        }
        visit::visit_expr(self, expr);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::EvidenceClass;
    use crate::ingest::SourceKind;
    use crate::test_util::TempDir;

    fn authored(path: PathBuf) -> SourceFile {
        SourceFile {
            path,
            kind: SourceKind::Authored,
        }
    }

    fn findings_for(source: &str, name: &str) -> Vec<Finding> {
        findings_for_with_config(source, name, false)
    }

    fn findings_for_with_config(
        source: &str,
        name: &str,
        allow_anyhow_at_boundary: bool,
    ) -> Vec<Finding> {
        let dir = TempDir::new(name);
        let file = dir.join("lib.rs");
        std::fs::write(&file, source).unwrap();
        analyze_file(&file, allow_anyhow_at_boundary).unwrap()
    }

    fn rule_findings<'a>(findings: &'a [Finding], rule: &str) -> Vec<&'a Finding> {
        findings.iter().filter(|f| f.rule == rule).collect()
    }

    #[test]
    fn let_underscore_call_is_flagged() {
        let findings = findings_for(
            "fn f() { let _ = some_call(); }\nfn some_call() -> i32 { 1 }\n",
            "slop-let-underscore",
        );
        let hits = rule_findings(&findings, SWALLOWED_RESULT_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn swallowed_result_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(SWALLOWED_RESULT_RULE)
            .expect("swallowed-result has a registry entry")
            .example
            .expect("swallowed-result has a curated example")
            .before;
        let findings = findings_for(example, "slop-swallowed-result-registry-example");
        assert_eq!(rule_findings(&findings, SWALLOWED_RESULT_RULE).len(), 1);
    }

    #[test]
    fn let_bound_to_a_real_name_is_not_flagged() {
        let findings = findings_for(
            "fn f() { let x = some_call(); let _ = x; }\nfn some_call() -> i32 { 1 }\n",
            "slop-let-real-name",
        );
        assert!(rule_findings(&findings, SWALLOWED_RESULT_RULE).is_empty());
    }

    /// `let _ = fallible();` inside `Drop::drop` is the only correct idiom —
    /// `drop` cannot return a `Result`, so discarding it here is not
    /// evidence of a swallowed error. Must not fire.
    #[test]
    fn let_underscore_inside_drop_drop_is_not_flagged() {
        let findings = findings_for(
            "struct S(String);\nimpl Drop for S {\n    fn drop(&mut self) {\n        let _ = std::fs::remove_dir_all(&self.0);\n    }\n}\n",
            "slop-swallowed-result-drop-drop",
        );
        assert!(rule_findings(&findings, SWALLOWED_RESULT_RULE).is_empty());
    }

    /// The same `let _ = ...;` pattern in a normal (non-`Drop::drop`)
    /// function must still be flagged — the exclusion is scoped to
    /// `Drop::drop` only.
    #[test]
    fn let_underscore_inside_normal_fn_still_flagged() {
        let findings = findings_for(
            "fn cleanup() {\n    let _ = std::fs::remove_dir_all(\"/tmp/x\");\n}\n",
            "slop-swallowed-result-normal-fn",
        );
        let hits = rule_findings(&findings, SWALLOWED_RESULT_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn bare_dot_ok_statement_is_flagged() {
        let findings = findings_for(
            "fn f() -> Result<i32, ()> { Ok(1) }\nfn g() { f().ok(); }\n",
            "slop-dot-ok",
        );
        let hits = rule_findings(&findings, SWALLOWED_RESULT_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn dot_ok_bound_to_a_name_is_not_flagged() {
        let findings = findings_for(
            "fn f() -> Result<i32, ()> { Ok(1) }\nfn g() { let x = f().ok(); let _ = x; }\n",
            "slop-dot-ok-bound",
        );
        assert!(rule_findings(&findings, SWALLOWED_RESULT_RULE).is_empty());
    }

    /// `swallowed-result` — unentscheidbar (same mechanism as
    /// `stringly-error-boundary`'s cfg-gated golden test in `pattern.rs`):
    /// the `let _ = ...;` sits inside a `#[cfg(feature =
    /// "not-enabled-by-default")]`-gated fn. `syn::parse_file` has no cfg
    /// resolution and parses every `cfg` branch regardless of actual
    /// feature activation, so a real build without that feature would never
    /// contain this statement at all — yet it is still flagged.
    /// `feature_gated_depth` exists in `SlopVisitor` but `visit_local`
    /// never consults it (only `merged-stub`'s `visit_macro` does), so this
    /// is consistent, documented Fast-Tier behavior, not a bug: making
    /// `swallowed-result` respect cfg-gating while `catch-all-error` (see
    /// below) doesn't would be the inconsistent choice, and todo.md's G1
    /// entry promises nothing about cfg resolution ("rein syntaktisch").
    #[test]
    fn swallowed_result_inside_cfg_gated_fn_still_flagged() {
        let findings = findings_for(
            "#[cfg(feature = \"not-enabled-by-default\")]\nfn f() { let _ = some_call(); }\nfn some_call() -> i32 { 1 }\n",
            "slop-swallowed-result-cfg-gated",
        );
        let hits = rule_findings(&findings, SWALLOWED_RESULT_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn empty_err_arm_is_flagged() {
        let findings = findings_for(
            r#"
fn f(r: Result<i32, ()>) {
    match r {
        Err(_) => {}
        Ok(_) => {}
    }
}
"#,
            "slop-empty-err-arm",
        );
        let hits = rule_findings(&findings, EMPTY_ERROR_ARM_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn non_empty_err_arm_is_not_flagged() {
        let findings = findings_for(
            r#"
fn f(r: Result<i32, ()>) {
    match r {
        Err(e) => log::warn!("{:?}", e),
        Ok(_) => {}
    }
}
"#,
            "slop-non-empty-err-arm",
        );
        assert!(rule_findings(&findings, EMPTY_ERROR_ARM_RULE).is_empty());
    }

    #[test]
    fn empty_if_let_err_is_flagged() {
        let findings = findings_for(
            "fn f() -> Result<(), ()> { Ok(()) }\nfn g() { if let Err(_) = f() { } }\n",
            "slop-if-let-empty",
        );
        let hits = rule_findings(&findings, EMPTY_ERROR_ARM_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn non_empty_if_let_err_is_not_flagged() {
        let findings = findings_for(
            "fn f() -> Result<(), ()> { Ok(()) }\nfn g() { if let Err(_) = f() { return; } }\n",
            "slop-if-let-non-empty",
        );
        assert!(rule_findings(&findings, EMPTY_ERROR_ARM_RULE).is_empty());
    }

    /// `empty-error-arm` — unentscheidbar, same class as `boolean-state-
    /// cluster`'s `macro_rules!` golden test in `pattern.rs`: the actual
    /// empty `Err(_) => {}` arm only exists inside a `macro_rules!` body,
    /// never written out as source `syn` parses into an AST. `syn` treats a
    /// macro definition's body as an opaque token stream, and the
    /// invocation `handle_it!(r);` is an opaque `Stmt::Macro` too — neither
    /// is expanded, so `visit_arm` never sees the `match` this rule would
    /// otherwise flag. A real build would 100% contain the empty arm this
    /// rule targets, but it is structurally invisible to a syntax-only
    /// scanner: the rule stays silent rather than guessing at an
    /// unexpanded macro body's contents.
    #[test]
    fn empty_error_arm_inside_macro_body_produces_no_finding() {
        let findings = findings_for(
            r#"
macro_rules! handle_it {
    ($r:expr) => {
        match $r {
            Err(_) => {}
            Ok(_) => {}
        }
    };
}
fn f(r: Result<i32, ()>) {
    handle_it!(r);
}
"#,
            "slop-empty-error-arm-macro-body",
        );
        assert!(rule_findings(&findings, EMPTY_ERROR_ARM_RULE).is_empty());
    }

    #[test]
    fn pub_fn_with_boxed_dyn_error_is_flagged() {
        let findings = findings_for(
            "pub fn f() -> Result<(), Box<dyn std::error::Error>> {\n    std::fs::read_to_string(\"x\").map_err(|_| \"failed\".into())?;\n    Ok(())\n}\n",
            "slop-catch-all-boxed",
        );
        let hits = rule_findings(&findings, CATCH_ALL_ERROR_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    /// See todo.md §F "Praxisbeleg" (GitHub issue #11): a type-erased return
    /// type alone is not enough — plain `?` propagation preserves the
    /// source error chain and is idiomatic `anyhow`/`thiserror` style, not
    /// evidence of discarded error information.
    #[test]
    fn pub_fn_with_boxed_dyn_error_and_plain_propagation_is_not_flagged() {
        let findings = findings_for(
            "pub fn f() -> Result<(), Box<dyn std::error::Error>> {\n    std::fs::read_to_string(\"x\")?;\n    Ok(())\n}\n",
            "slop-catch-all-boxed-plain-propagation",
        );
        assert!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).is_empty());
    }

    /// A `.map_err` closure that binds and uses its parameter converts the
    /// error but does not discard it — still not flagged.
    #[test]
    fn map_err_with_a_bound_parameter_is_not_flagged() {
        let findings = findings_for(
            "pub fn f() -> Result<(), Box<dyn std::error::Error>> {\n    std::fs::read_to_string(\"x\").map_err(|e| format!(\"failed: {e}\").into())?;\n    Ok(())\n}\n",
            "slop-catch-all-boxed-bound-map-err",
        );
        assert!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).is_empty());
    }

    #[test]
    fn pub_fn_with_concrete_error_type_is_not_flagged() {
        let findings = findings_for(
            "struct MyError;\npub fn f() -> Result<(), MyError> { Ok(()) }\n",
            "slop-catch-all-concrete",
        );
        assert!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).is_empty());
    }

    #[test]
    fn private_fn_with_boxed_dyn_error_is_not_flagged() {
        let findings = findings_for(
            "fn f() -> Result<(), Box<dyn std::error::Error>> { Ok(()) }\n",
            "slop-catch-all-private",
        );
        assert!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).is_empty());
    }

    #[test]
    fn anyhow_result_is_flagged() {
        let findings = findings_for(
            "pub fn f() -> anyhow::Result<()> {\n    std::fs::read_to_string(\"x\").map_err(|_| anyhow::anyhow!(\"failed\"))?;\n    Ok(())\n}\n",
            "slop-catch-all-anyhow",
        );
        let hits = rule_findings(&findings, CATCH_ALL_ERROR_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn anyhow_result_is_not_flagged_when_allowed_at_boundary() {
        let findings = findings_for_with_config(
            "pub fn f() -> anyhow::Result<()> {\n    std::fs::read_to_string(\"x\").map_err(|_| anyhow::anyhow!(\"failed\"))?;\n    Ok(())\n}\n",
            "slop-catch-all-anyhow-allowed",
            true,
        );
        assert!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).is_empty());
    }

    #[test]
    fn boxed_dyn_error_is_still_flagged_when_anyhow_allowed_at_boundary() {
        let findings = findings_for_with_config(
            "pub fn f() -> Result<(), Box<dyn std::error::Error>> {\n    std::fs::read_to_string(\"x\").map_err(|_| \"failed\".into())?;\n    Ok(())\n}\n",
            "slop-catch-all-boxed-allowed",
            true,
        );
        let hits = rule_findings(&findings, CATCH_ALL_ERROR_RULE);
        assert_eq!(hits.len(), 1);
    }

    /// `catch-all-error` — unentscheidbar, same mechanism as
    /// `stringly-error-boundary`'s cfg-gated golden test in `pattern.rs`:
    /// the `pub fn` itself sits behind `#[cfg(feature =
    /// "not-enabled-by-default")]`, so a real build without that feature
    /// would never expose this boundary at all. `check_catch_all_error` is
    /// called unconditionally from `visit_item_fn` — `feature_gated_depth`
    /// is tracked but only `merged-stub` consults it — so the finding still
    /// fires. Documented, honest Fast-Tier limitation (`syn::parse_file`
    /// has no cfg resolution), not a bug.
    #[test]
    fn catch_all_error_inside_cfg_gated_pub_fn_still_flagged() {
        let findings = findings_for(
            "#[cfg(feature = \"not-enabled-by-default\")]\npub fn f() -> Result<(), Box<dyn std::error::Error>> {\n    std::fs::read_to_string(\"x\").map_err(|_| \"failed\".into())?;\n    Ok(())\n}\n",
            "slop-catch-all-error-cfg-gated",
        );
        let hits = rule_findings(&findings, CATCH_ALL_ERROR_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn allow_and_expect_each_produce_one_finding() {
        let findings = findings_for(
            "#[allow(dead_code)]\nfn f() {}\n\n#[expect(clippy::foo)]\nfn g() {}\n",
            "slop-suppression-debt",
        );
        let hits = rule_findings(&findings, SUPPRESSION_DEBT_RULE);
        assert_eq!(hits.len(), 2);
        for hit in &hits {
            assert_eq!(hit.severity, Severity::Info);
            assert_eq!(hit.evidence_class, EvidenceClass::DerivedFact);
        }
        let item_paths: Vec<_> = hits.iter().map(|f| f.location.item_path.as_str()).collect();
        assert!(item_paths.contains(&"dead_code"));
        assert!(item_paths.contains(&"clippy::foo"));
    }

    #[test]
    fn no_suppressions_produces_zero_findings() {
        let findings = findings_for("fn f() {}\n", "slop-no-suppression-debt");
        assert!(rule_findings(&findings, SUPPRESSION_DEBT_RULE).is_empty());
    }

    /// `suppression-debt` — unentscheidbar, but the inverse of the other
    /// three rules' cfg/macro blind spots: here macro-blindness
    /// *undercounts* rather than overcounts. The `#[allow(dead_code)]`
    /// exists only inside a `macro_rules!` body, which `syn` treats as an
    /// opaque token stream, never expanded into a real `Item::Fn` with a
    /// visible `Attribute` — and the invocation `define_it!();` is itself
    /// an opaque `Item::Macro`. A real build's expanded code would contain
    /// this `#[allow(...)]` and count against the suppression-debt trend,
    /// but `visit_attribute` never sees it, so it silently doesn't count.
    /// Documented, honest Fast-Tier limitation (no macro expansion
    /// available without a real compiler), not a bug: undercounting a
    /// trend metric is a materially different (and here, unavoidable)
    /// failure mode than misreporting a specific finding's location.
    #[test]
    fn suppression_debt_inside_macro_body_is_not_counted() {
        let findings = findings_for(
            "macro_rules! define_it {\n    () => {\n        #[allow(dead_code)]\n        fn generated() {}\n    };\n}\ndefine_it!();\n",
            "slop-suppression-debt-macro-body",
        );
        assert!(rule_findings(&findings, SUPPRESSION_DEBT_RULE).is_empty());
    }

    #[test]
    fn generated_files_are_excluded_unless_included() {
        let dir = TempDir::new("slop-generated");
        let file = dir.join("schema.rs");
        std::fs::write(
            &file,
            "fn f() { let _ = some_call(); }\nfn some_call() -> i32 { 1 }\n",
        )
        .unwrap();

        let files = [SourceFile {
            path: file,
            kind: SourceKind::Generated,
        }];

        let excluded = analyze_workspace(files.iter(), false, false);
        assert!(excluded.findings.is_empty());
        assert_eq!(excluded.excluded_generated, 1);

        let included = analyze_workspace(files.iter(), true, false);
        assert_eq!(included.findings.len(), 1);
        assert_eq!(included.excluded_generated, 0);
    }

    #[test]
    fn analyze_workspace_reports_parse_errors() {
        let dir = TempDir::new("slop-parse-error");
        let file = dir.join("broken.rs");
        std::fs::write(&file, "fn broken( {").unwrap();

        let files = [authored(file)];
        let report = analyze_workspace(files.iter(), false, false);

        assert_eq!(report.errors.len(), 1);
        assert!(report.findings.is_empty());
    }

    #[test]
    fn ignored_test_is_flagged() {
        let findings = findings_for(
            "#[test]\n#[ignore]\nfn f() { assert_eq!(1 + 1, 2); }\n",
            "slop-ignored-test",
        );
        let hits = rule_findings(&findings, IGNORED_TEST_ACCUMULATION_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Info);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
        assert_eq!(hits[0].evidence, None);
    }

    #[test]
    fn ignored_test_with_reason_captures_evidence() {
        let findings = findings_for(
            "#[test]\n#[ignore = \"slow\"]\nfn f() { assert_eq!(1 + 1, 2); }\n",
            "slop-ignored-test-reason",
        );
        let hits = rule_findings(&findings, IGNORED_TEST_ACCUMULATION_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(
            hits[0].evidence,
            Some(serde_json::json!({ "reason": "slow" }))
        );
    }

    #[test]
    fn test_without_ignore_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { assert_eq!(1 + 1, 2); }\n",
            "slop-not-ignored-test",
        );
        assert!(rule_findings(&findings, IGNORED_TEST_ACCUMULATION_RULE).is_empty());
    }

    #[test]
    fn assert_true_is_flagged() {
        let findings = findings_for("fn f() { assert!(true); }\n", "slop-assert-true");
        let hits = rule_findings(&findings, TAUTOLOGICAL_TEST_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn assert_condition_is_not_flagged() {
        let findings = findings_for(
            "fn f() { assert!(condition()); }\nfn condition() -> bool { true }\n",
            "slop-assert-condition",
        );
        assert!(rule_findings(&findings, TAUTOLOGICAL_TEST_RULE).is_empty());
    }

    #[test]
    fn assert_eq_same_expr_is_flagged() {
        let findings = findings_for(
            "fn f(x: i32) { assert_eq!(x, x); }\n",
            "slop-assert-eq-same",
        );
        let hits = rule_findings(&findings, TAUTOLOGICAL_TEST_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn assert_eq_different_exprs_is_not_flagged() {
        let findings = findings_for(
            "fn f(a: i32, b: i32) { assert_eq!(a, b); }\n",
            "slop-assert-eq-different",
        );
        assert!(rule_findings(&findings, TAUTOLOGICAL_TEST_RULE).is_empty());
    }

    #[test]
    fn doc_commented_empty_fn_is_flagged() {
        let findings = findings_for("/// Does nothing yet.\nfn f() {}\n", "slop-empty-impl-fn");
        let hits = rule_findings(&findings, EMPTY_IMPL_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn doc_commented_nonempty_fn_is_not_flagged() {
        let findings = findings_for(
            "/// Returns a default.\nfn f() -> i32 { some_default() }\nfn some_default() -> i32 { 1 }\n",
            "slop-empty-impl-nonempty",
        );
        assert!(rule_findings(&findings, EMPTY_IMPL_RULE).is_empty());
    }

    #[test]
    fn empty_fn_without_doc_comment_is_not_flagged() {
        let findings = findings_for("fn f() {}\n", "slop-empty-impl-no-doc");
        assert!(rule_findings(&findings, EMPTY_IMPL_RULE).is_empty());
    }

    #[test]
    fn doc_commented_empty_impl_method_is_flagged() {
        let findings = findings_for(
            "struct S;\nimpl S {\n    /// Does nothing yet.\n    fn f(&self) {}\n}\n",
            "slop-empty-impl-method",
        );
        let hits = rule_findings(&findings, EMPTY_IMPL_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn doc_commented_empty_trait_default_is_flagged() {
        let findings = findings_for(
            "trait T {\n    /// Does nothing yet.\n    fn f(&self) {}\n}\n",
            "slop-empty-impl-trait-default",
        );
        let hits = rule_findings(&findings, EMPTY_IMPL_RULE);
        assert_eq!(hits.len(), 1);
    }

    /// A doc-commented empty override of `syn::visit::Visit` (matched by the
    /// trait path's last segment, `Visit`) is a deliberate "skip descending
    /// into this AST node type" choice, not a stub — must not fire.
    #[test]
    fn doc_commented_empty_visit_trait_override_is_not_flagged() {
        let findings = findings_for(
            "struct V;\nimpl Visit for V {\n    /// Never descends into an attribute.\n    fn visit_attribute(&mut self, _node: &Attribute) {}\n}\n",
            "slop-empty-impl-visit-override",
        );
        assert!(rule_findings(&findings, EMPTY_IMPL_RULE).is_empty());
    }

    /// A doc-commented empty override of a non-visitor trait must still be
    /// flagged — the exclusion is narrowly scoped to `Visit`/`VisitMut`/
    /// `Fold` only, not every trait-impl override.
    #[test]
    fn doc_commented_empty_non_visitor_trait_override_is_flagged() {
        let findings = findings_for(
            "trait Handler {\n    fn handle(&self);\n}\nstruct S;\nimpl Handler for S {\n    /// Does nothing yet.\n    fn handle(&self) {}\n}\n",
            "slop-empty-impl-non-visitor-override",
        );
        let hits = rule_findings(&findings, EMPTY_IMPL_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn todo_macro_is_flagged() {
        let findings = findings_for("fn f() { todo!() }\n", "slop-merged-stub-todo");
        let hits = rule_findings(&findings, MERGED_STUB_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn unimplemented_macro_is_flagged() {
        let findings = findings_for(
            "fn f() { unimplemented!() }\n",
            "slop-merged-stub-unimplemented",
        );
        assert_eq!(rule_findings(&findings, MERGED_STUB_RULE).len(), 1);
    }

    #[test]
    fn feature_gated_fn_todo_is_not_flagged() {
        let findings = findings_for(
            "#[cfg(feature = \"wip\")]\nfn f() { todo!() }\n",
            "slop-merged-stub-gated-fn",
        );
        assert!(rule_findings(&findings, MERGED_STUB_RULE).is_empty());
    }

    #[test]
    fn feature_gated_mod_todo_is_not_flagged() {
        let findings = findings_for(
            "#[cfg(feature = \"wip\")]\nmod m {\n    fn f() { todo!() }\n}\n",
            "slop-merged-stub-gated-mod",
        );
        assert!(rule_findings(&findings, MERGED_STUB_RULE).is_empty());
    }

    #[test]
    fn test_without_assertion_is_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { let x = 1 + 1; }\n",
            "slop-assertion-free-test",
        );
        let hits = rule_findings(&findings, ASSERTION_FREE_TEST_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn test_with_assert_eq_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { assert_eq!(1 + 1, 2); }\n",
            "slop-assertion-free-with-assert",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn test_with_unwrap_only_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { let x: Option<i32> = Some(1); x.unwrap(); }\n",
            "slop-assertion-free-unwrap",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn test_returning_result_with_try_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() -> Result<(), String> { might_fail()?; Ok(()) }\nfn might_fail() -> Result<(), String> { Ok(()) }\n",
            "slop-assertion-free-try",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn should_panic_test_without_assertion_is_not_flagged() {
        let findings = findings_for(
            "#[test]\n#[should_panic]\nfn f() { let x = 1 + 1; }\n",
            "slop-assertion-free-should-panic",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn test_with_assert_free_closure_is_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { let closure = || { let y = 1 + 1; }; closure(); }\n",
            "slop-assertion-free-closure",
        );
        assert_eq!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).len(), 1);
    }

    #[test]
    fn test_with_qualified_insta_snapshot_macro_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { insta::assert_snapshot!(\"value\"); }\n",
            "slop-assertion-free-insta-snapshot",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn test_with_qualified_insta_json_snapshot_macro_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { insta::assert_json_snapshot!(value); }\n",
            "slop-assertion-free-insta-json-snapshot",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn test_with_qualified_pretty_assertions_assert_eq_is_not_flagged() {
        let findings = findings_for(
            "#[test]\nfn f() { pretty_assertions::assert_eq!(1 + 1, 2); }\n",
            "slop-assertion-free-pretty-assertions",
        );
        assert!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).is_empty());
    }

    #[test]
    fn generic_naming_numeric_suffix_locals_are_flagged() {
        let findings = findings_for(
            "fn f() { let data1 = 1; let data2 = 2; }\n",
            "slop-generic-naming-numeric-suffix",
        );
        let hits = rule_findings(&findings, GENERIC_NAMING_RULE);
        assert_eq!(hits.len(), 2);
        for hit in &hits {
            assert_eq!(hit.evidence_class, EvidenceClass::DerivedFact);
        }
    }

    #[test]
    fn generic_naming_private_bare_local_is_not_flagged() {
        let findings = findings_for(
            "fn g() -> Result<i32, String> { let result = do_thing()?; Ok(result) }\nfn do_thing() -> Result<i32, String> { Ok(1) }\n",
            "slop-generic-naming-private-result",
        );
        assert!(rule_findings(&findings, GENERIC_NAMING_RULE).is_empty());
    }

    #[test]
    fn generic_naming_pub_struct_exact_word_is_flagged() {
        let findings = findings_for("pub struct Manager;\n", "slop-generic-naming-struct");
        let hits = rule_findings(&findings, GENERIC_NAMING_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn generic_naming_pub_struct_substring_is_not_flagged() {
        let findings = findings_for(
            "pub struct ConnectionManager;\n",
            "slop-generic-naming-struct-substring",
        );
        assert!(rule_findings(&findings, GENERIC_NAMING_RULE).is_empty());
    }

    #[test]
    fn generic_naming_pub_fn_exact_word_is_flagged() {
        let findings = findings_for("pub fn helper() {}\n", "slop-generic-naming-fn");
        let hits = rule_findings(&findings, GENERIC_NAMING_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn generic_naming_pub_impl_method_is_not_flagged() {
        let findings = findings_for(
            "struct S;\nimpl S {\n    pub fn helper(&self) {}\n}\n",
            "slop-generic-naming-impl-method",
        );
        assert!(rule_findings(&findings, GENERIC_NAMING_RULE).is_empty());
    }

    #[test]
    fn doc_restates_signature_pure_echo_is_flagged() {
        let findings = findings_for(
            "/// Returns the result.\npub fn f() -> Result<(), String> { Ok(()) }\n",
            "slop-doc-restates-signature-echo",
        );
        let hits = rule_findings(&findings, DOC_RESTATES_SIGNATURE_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn doc_restates_signature_real_prose_is_not_flagged() {
        let findings = findings_for(
            "/// Parses the config file and validates required fields.\nfn f() {}\n",
            "slop-doc-restates-signature-prose",
        );
        assert!(rule_findings(&findings, DOC_RESTATES_SIGNATURE_RULE).is_empty());
    }

    #[test]
    fn conversational_artifact_tier1_phrase_is_flagged() {
        let findings = findings_for(
            "fn f() {\n    // As an AI, I can't do that.\n}\n",
            "slop-conversational-artifact-tier1",
        );
        let hits = rule_findings(&findings, CONVERSATIONAL_ARTIFACT_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    #[test]
    fn conversational_artifact_doc_comment_is_excluded() {
        let findings = findings_for(
            "/// In a real implementation, this would also validate input.\nfn f() {}\n",
            "slop-conversational-artifact-doc",
        );
        assert!(rule_findings(&findings, CONVERSATIONAL_ARTIFACT_RULE).is_empty());
    }

    #[test]
    fn conversational_artifact_tier2_phrase_past_word_eight_is_not_flagged() {
        let findings = findings_for(
            "fn f() {\n    // This example function shows some basic arithmetic logic in a real implementation context.\n    let _ = 1;\n}\n",
            "slop-conversational-artifact-tier2-position",
        );
        assert!(rule_findings(&findings, CONVERSATIONAL_ARTIFACT_RULE).is_empty());
    }

    #[test]
    fn conversational_artifact_tier2_phrase_is_not_flagged_inside_an_unrelated_word() {
        // Two of CONVERSATIONAL_TIER2's short entries are a raw substring of
        // this sentence's opening word — a plain `.contains()` would
        // misclassify ordinary prose as AI-assistant leakage.
        let findings = findings_for(
            "fn f() {\n    // There is no other way to express this invariant.\n}\n",
            "slop-conversational-artifact-tier2-word-boundary",
        );
        assert!(rule_findings(&findings, CONVERSATIONAL_ARTIFACT_RULE).is_empty());
    }

    #[test]
    fn step_comment_inflation_three_step_chain_is_flagged() {
        let findings = findings_for(
            "fn f() {\n    // Step 1: initialize\n    let x = 1;\n    // Step 2: compute\n    let y = x + 1;\n    // Step 3: finish\n    let _ = y;\n}\n",
            "slop-step-comment-inflation-chain",
        );
        let hits = rule_findings(&findings, STEP_COMMENT_INFLATION_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(
            hits[0].evidence,
            Some(serde_json::json!({ "chain_length": 3, "lines": [2, 4, 6] }))
        );
    }

    #[test]
    fn step_comment_inflation_single_step_is_not_flagged() {
        let findings = findings_for(
            "fn f() {\n    // Step 1: initialize\n    let x = 1;\n    let _ = x;\n}\n",
            "slop-step-comment-inflation-single",
        );
        assert!(rule_findings(&findings, STEP_COMMENT_INFLATION_RULE).is_empty());
    }

    #[test]
    fn restating_comment_short_comment_is_not_flagged() {
        let findings = findings_for(
            "fn f(counter: &mut i32) {\n    // increment counter\n    *counter += 1;\n}\n",
            "slop-restating-comment-short",
        );
        assert!(rule_findings(&findings, RESTATING_COMMENT_RULE).is_empty());
    }

    #[test]
    fn restating_comment_verbose_paraphrase_is_flagged() {
        let findings = findings_for(
            "struct S { user_name_field: String }\nimpl S {\n    fn set(&mut self, given_value: String) {\n        // set the user name field to the given value\n        self.user_name_field = given_value;\n    }\n}\n",
            "slop-restating-comment-verbose",
        );
        let hits = rule_findings(&findings, RESTATING_COMMENT_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
    }

    /// `merged-stub` — unentscheidbar, macro-blindness (companion to the
    /// existing `feature_gated_fn_todo_is_not_flagged` cfg-blindness tests
    /// above, which already confirm `feature_gated_depth` suppresses a
    /// cfg-gated `todo!()`): here the `todo!()` exists only inside a
    /// `macro_rules!` body. `syn` treats a macro definition's body as an
    /// opaque token stream — `visit_macro` never sees the inner `todo!()`
    /// as a real `Macro` node — and the invocation `define_it!();` is
    /// itself an opaque `Item::Macro`, never expanded. A real build's
    /// expanded code would contain this `todo!()`, but it's structurally
    /// invisible to a syntax-only scanner: an undercount, not a bug.
    #[test]
    fn merged_stub_inside_macro_body_produces_no_finding() {
        let findings = findings_for(
            "macro_rules! define_it {\n    () => {\n        fn generated() { todo!() }\n    };\n}\ndefine_it!();\n",
            "slop-merged-stub-macro-body",
        );
        assert!(rule_findings(&findings, MERGED_STUB_RULE).is_empty());
    }

    /// `empty-impl` — unentscheidbar, macro-blindness: the doc-commented,
    /// literally-empty fn only exists inside a `macro_rules!` body. `syn`
    /// parses the macro definition's body as an opaque token stream, never
    /// as a real `ItemFn` — `check_empty_impl` is never called on it — and
    /// the invocation `define_stub!();` is itself an opaque `Item::Macro`,
    /// never expanded into the real stub it produces. Same undercount class
    /// as `merged_stub_inside_macro_body_produces_no_finding` above.
    #[test]
    fn empty_impl_inside_macro_body_produces_no_finding() {
        let findings = findings_for(
            "macro_rules! define_stub {\n    () => {\n        /// Does nothing yet.\n        fn generated() {}\n    };\n}\ndefine_stub!();\n",
            "slop-empty-impl-macro-body",
        );
        assert!(rule_findings(&findings, EMPTY_IMPL_RULE).is_empty());
    }

    /// `assertion-free-test` — unentscheidbar: the test's only assertion
    /// goes through a local `macro_rules! check { ... }` wrapper that
    /// itself calls `assert!` internally. `AssertionScanner::visit_macro`
    /// only recognizes a fixed list of assertion-macro names (plus
    /// qualified paths ending in one of them, per the `insta`/
    /// `pretty_assertions` fix) — `check` isn't on that list, and `syn`
    /// never expands the wrapper to see the `assert!` inside it, so the
    /// scanner finds nothing and flags a test that does, in fact, assert.
    /// Documented false positive, not a bug: recognizing arbitrary
    /// user-defined wrapper macros isn't solvable without macro expansion.
    #[test]
    fn test_using_custom_assertion_wrapper_macro_is_still_flagged() {
        let findings = findings_for(
            "macro_rules! check {\n    ($cond:expr) => {\n        assert!($cond);\n    };\n}\n#[test]\nfn f() { check!(1 + 1 == 2); }\n",
            "slop-assertion-free-custom-wrapper",
        );
        let hits = rule_findings(&findings, ASSERTION_FREE_TEST_RULE);
        assert_eq!(hits.len(), 1);
    }

    /// `tautological-test` — confirms the rule is purely syntactic (token
    /// comparison), not semantic: `VALUE` is a `const` whose value is
    /// produced by a `macro_rules!` invocation, not written out literally,
    /// yet `assert_eq!(VALUE, VALUE)` is flagged exactly the same as
    /// `assert_eq!(x, x)` would be. The rule never looks at how `VALUE` was
    /// defined — it only compares the two macro arguments' token strings —
    /// so a macro-generated definition changes nothing about detectability
    /// here (unlike the other rules in this block, this one has no blind
    /// spot to demonstrate; the golden test documents that fact).
    #[test]
    fn assert_eq_macro_generated_const_is_flagged_syntactically() {
        let findings = findings_for(
            "macro_rules! define_const {\n    ($name:ident, $val:expr) => {\n        const $name: i32 = $val;\n    };\n}\ndefine_const!(VALUE, 42);\nfn f() { assert_eq!(VALUE, VALUE); }\n",
            "slop-tautological-macro-const",
        );
        let hits = rule_findings(&findings, TAUTOLOGICAL_TEST_RULE);
        assert_eq!(hits.len(), 1);
    }

    /// `ignored-test-accumulation` — unentscheidbar, macro-blindness
    /// (undercount, same class as `suppression_debt_inside_macro_body_is_
    /// not_counted` above): the `#[ignore]` attribute exists only inside a
    /// `macro_rules!` body. `visit_attribute` never sees it — the macro
    /// definition's body is an opaque token stream, and the invocation
    /// `define_ignored_test!();` is itself an opaque `Item::Macro`, never
    /// expanded — so a real build's ignored test doesn't count toward this
    /// rule's total.
    #[test]
    fn ignored_test_inside_macro_body_is_not_counted() {
        let findings = findings_for(
            "macro_rules! define_ignored_test {\n    () => {\n        #[test]\n        #[ignore]\n        fn generated() { assert!(true); }\n    };\n}\ndefine_ignored_test!();\n",
            "slop-ignored-test-macro-body",
        );
        assert!(rule_findings(&findings, IGNORED_TEST_ACCUMULATION_RULE).is_empty());
    }

    /// `generic-naming` — unentscheidbar, cfg-blindness: `check_generic_
    /// naming_item_fn` is called unconditionally from `visit_item_fn`, the
    /// same as `check_catch_all_error` — `feature_gated_depth` is tracked
    /// but this check never consults it. A `pub fn` named `manager` behind
    /// `#[cfg(feature = "wip")]` is still flagged even though a build
    /// without that feature would never compile it in. Same class as
    /// `catch_all_error_inside_cfg_gated_pub_fn_still_flagged` above.
    #[test]
    fn generic_naming_pub_fn_inside_cfg_gated_mod_still_flagged() {
        let findings = findings_for(
            "#[cfg(feature = \"wip\")]\nmod m {\n    pub fn manager() {}\n}\n",
            "slop-generic-naming-cfg-gated",
        );
        let hits = rule_findings(&findings, GENERIC_NAMING_RULE);
        assert_eq!(hits.len(), 1);
    }

    /// `doc-restates-signature` — unentscheidbar, macro-blindness
    /// (undercount): the pure-echo doc comment and its fn signature exist
    /// only inside a `macro_rules!` body. `check_doc_restates_signature` is
    /// never called on it — the macro definition's body is an opaque token
    /// stream, and the invocation `define_getter!();` is itself an opaque
    /// `Item::Macro`, never expanded into the real, matching fn it
    /// produces.
    #[test]
    fn doc_restates_signature_inside_macro_body_produces_no_finding() {
        let findings = findings_for(
            "macro_rules! define_getter {\n    () => {\n        /// Returns the result.\n        pub fn f() -> Result<(), String> { Ok(()) }\n    };\n}\ndefine_getter!();\n",
            "slop-doc-restates-signature-macro-body",
        );
        assert!(rule_findings(&findings, DOC_RESTATES_SIGNATURE_RULE).is_empty());
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn empty_error_arm_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(EMPTY_ERROR_ARM_RULE)
            .expect("empty-error-arm has a registry entry")
            .example
            .expect("empty-error-arm has a curated example")
            .before;
        let findings = findings_for(example, "slop-empty-error-arm-registry-example");
        assert_eq!(rule_findings(&findings, EMPTY_ERROR_ARM_RULE).len(), 1);
    }

    #[test]
    fn catch_all_error_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(CATCH_ALL_ERROR_RULE)
            .expect("catch-all-error has a registry entry")
            .example
            .expect("catch-all-error has a curated example")
            .before;
        let findings = findings_for(example, "slop-catch-all-error-registry-example");
        assert_eq!(rule_findings(&findings, CATCH_ALL_ERROR_RULE).len(), 1);
    }

    #[test]
    fn suppression_debt_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(SUPPRESSION_DEBT_RULE)
            .expect("suppression-debt has a registry entry")
            .example
            .expect("suppression-debt has a curated example")
            .before;
        let findings = findings_for(example, "slop-suppression-debt-registry-example");
        assert_eq!(rule_findings(&findings, SUPPRESSION_DEBT_RULE).len(), 1);
    }

    #[test]
    fn merged_stub_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(MERGED_STUB_RULE)
            .expect("merged-stub has a registry entry")
            .example
            .expect("merged-stub has a curated example")
            .before;
        let findings = findings_for(example, "slop-merged-stub-registry-example");
        assert_eq!(rule_findings(&findings, MERGED_STUB_RULE).len(), 1);
    }

    #[test]
    fn empty_impl_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(EMPTY_IMPL_RULE)
            .expect("empty-impl has a registry entry")
            .example
            .expect("empty-impl has a curated example")
            .before;
        let findings = findings_for(example, "slop-empty-impl-registry-example");
        assert_eq!(rule_findings(&findings, EMPTY_IMPL_RULE).len(), 1);
    }

    #[test]
    fn assertion_free_test_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(ASSERTION_FREE_TEST_RULE)
            .expect("assertion-free-test has a registry entry")
            .example
            .expect("assertion-free-test has a curated example")
            .before;
        let findings = findings_for(example, "slop-assertion-free-test-registry-example");
        assert_eq!(rule_findings(&findings, ASSERTION_FREE_TEST_RULE).len(), 1);
    }

    #[test]
    fn tautological_test_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(TAUTOLOGICAL_TEST_RULE)
            .expect("tautological-test has a registry entry")
            .example
            .expect("tautological-test has a curated example")
            .before;
        let findings = findings_for(example, "slop-tautological-test-registry-example");
        assert_eq!(rule_findings(&findings, TAUTOLOGICAL_TEST_RULE).len(), 1);
    }

    #[test]
    fn ignored_test_accumulation_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(IGNORED_TEST_ACCUMULATION_RULE)
            .expect("ignored-test-accumulation has a registry entry")
            .example
            .expect("ignored-test-accumulation has a curated example")
            .before;
        let findings = findings_for(example, "slop-ignored-test-accumulation-registry-example");
        assert_eq!(
            rule_findings(&findings, IGNORED_TEST_ACCUMULATION_RULE).len(),
            1
        );
    }

    #[test]
    fn conversational_artifact_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(CONVERSATIONAL_ARTIFACT_RULE)
            .expect("conversational-artifact has a registry entry")
            .example
            .expect("conversational-artifact has a curated example")
            .before;
        let findings = findings_for(example, "slop-conversational-artifact-registry-example");
        assert_eq!(
            rule_findings(&findings, CONVERSATIONAL_ARTIFACT_RULE).len(),
            1
        );
    }

    #[test]
    fn restating_comment_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(RESTATING_COMMENT_RULE)
            .expect("restating-comment has a registry entry")
            .example
            .expect("restating-comment has a curated example")
            .before;
        let findings = findings_for(example, "slop-restating-comment-registry-example");
        assert_eq!(rule_findings(&findings, RESTATING_COMMENT_RULE).len(), 1);
    }

    #[test]
    fn step_comment_inflation_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(STEP_COMMENT_INFLATION_RULE)
            .expect("step-comment-inflation has a registry entry")
            .example
            .expect("step-comment-inflation has a curated example")
            .before;
        let findings = findings_for(example, "slop-step-comment-inflation-registry-example");
        assert_eq!(
            rule_findings(&findings, STEP_COMMENT_INFLATION_RULE).len(),
            1
        );
    }

    #[test]
    fn generic_naming_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(GENERIC_NAMING_RULE)
            .expect("generic-naming has a registry entry")
            .example
            .expect("generic-naming has a curated example")
            .before;
        let findings = findings_for(example, "slop-generic-naming-registry-example");
        assert_eq!(rule_findings(&findings, GENERIC_NAMING_RULE).len(), 1);
    }

    #[test]
    fn doc_restates_signature_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(DOC_RESTATES_SIGNATURE_RULE)
            .expect("doc-restates-signature has a registry entry")
            .example
            .expect("doc-restates-signature has a curated example")
            .before;
        let findings = findings_for(example, "slop-doc-restates-signature-registry-example");
        assert_eq!(
            rule_findings(&findings, DOC_RESTATES_SIGNATURE_RULE).len(),
            1
        );
    }

    #[test]
    fn unwrap_or_default_without_error_observation_is_flagged() {
        let findings = findings_for(
            "fn f(input: Option<i32>) -> i32 {\n    input.unwrap_or_default()\n}\n",
            "slop-silent-default-unwrap-or-default",
        );
        let hits = rule_findings(&findings, SILENT_DEFAULT_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::Heuristic);
        assert_eq!(
            hits[0].evidence.as_ref().unwrap()["method"],
            "unwrap_or_default"
        );
    }

    #[test]
    fn unwrap_or_else_default_closure_without_error_observation_is_flagged() {
        let findings = findings_for(
            "fn f(input: Result<i32, String>) -> i32 {\n    input.unwrap_or_else(|_| Default::default())\n}\n",
            "slop-silent-default-unwrap-or-else",
        );
        let hits = rule_findings(&findings, SILENT_DEFAULT_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(
            hits[0].evidence.as_ref().unwrap()["method"],
            "unwrap_or_else"
        );
    }

    #[test]
    fn unwrap_or_else_non_default_closure_is_not_flagged() {
        let findings = findings_for(
            "fn f(input: Result<i32, String>) -> i32 {\n    input.unwrap_or_else(|_| 0)\n}\n",
            "slop-silent-default-unwrap-or-else-non-default",
        );
        assert!(rule_findings(&findings, SILENT_DEFAULT_RULE).is_empty());
    }

    /// The absence signal is function-granularity: an error-observation call
    /// anywhere in the function suppresses `silent-default` even though it
    /// doesn't observe *this* call's error (see the rule's registry
    /// `exclusions`).
    #[test]
    fn unwrap_or_default_with_error_observation_elsewhere_in_function_is_not_flagged() {
        let findings = findings_for(
            "fn f(input: Option<i32>, other: Result<i32, String>) -> i32 {\n    if let Err(e) = other {\n        tracing::warn!(\"failed: {:?}\", e);\n    }\n    input.unwrap_or_default()\n}\n",
            "slop-silent-default-observed-elsewhere",
        );
        assert!(rule_findings(&findings, SILENT_DEFAULT_RULE).is_empty());
    }

    #[test]
    fn silent_default_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(SILENT_DEFAULT_RULE)
            .expect("silent-default has a registry entry")
            .example
            .expect("silent-default has a curated example")
            .before;
        let findings = findings_for(example, "slop-silent-default-registry-example");
        assert_eq!(rule_findings(&findings, SILENT_DEFAULT_RULE).len(), 1);
    }

    #[test]
    fn two_distinct_try_sites_with_no_context_calls_on_anyhow_result_is_flagged() {
        let findings = findings_for(
            "pub fn load(path: &str) -> anyhow::Result<String> {\n    let raw = std::fs::read_to_string(path)?;\n    let parsed = raw.parse::<i32>()?;\n    Ok(parsed.to_string())\n}\n",
            "slop-context-free-propagation-anyhow",
        );
        let hits = rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::Heuristic);
        assert_eq!(hits[0].evidence.as_ref().unwrap()["try_site_count"], 2);
    }

    #[test]
    fn single_try_site_is_not_flagged() {
        let findings = findings_for(
            "pub fn load(path: &str) -> anyhow::Result<String> {\n    let raw = std::fs::read_to_string(path)?;\n    Ok(raw)\n}\n",
            "slop-context-free-propagation-single-site",
        );
        assert!(rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE).is_empty());
    }

    /// The "zero `.context()`/`.with_context()` calls anywhere in the
    /// function" semantics chosen for this rule: a function that already
    /// calls `.context()` for *some* of its `?`-sites but not all of them is
    /// not flagged, since the author is clearly already following that
    /// practice in this function (see the rule's registry `exclusions`).
    #[test]
    fn two_distinct_try_sites_with_a_context_call_on_only_one_is_not_flagged() {
        let findings = findings_for(
            "pub fn load(path: &str) -> anyhow::Result<String> {\n    let raw = std::fs::read_to_string(path).context(\"failed to read\")?;\n    let parsed = raw.parse::<i32>()?;\n    Ok(parsed.to_string())\n}\n",
            "slop-context-free-propagation-partial-context",
        );
        assert!(rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE).is_empty());
    }

    /// Dedup key is the underlying call's token text: the exact same call
    /// written twice counts as one distinct `?`-site, not two.
    #[test]
    fn same_call_site_twice_counts_as_one_distinct_try_site_and_is_not_flagged() {
        let findings = findings_for(
            "pub fn load(path: &str) -> anyhow::Result<String> {\n    let a = std::fs::read_to_string(path)?;\n    let b = std::fs::read_to_string(path)?;\n    Ok(a + &b)\n}\n",
            "slop-context-free-propagation-duplicate-call",
        );
        assert!(rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE).is_empty());
    }

    #[test]
    fn two_distinct_try_sites_on_boxed_dyn_error_return_is_flagged() {
        let findings = findings_for(
            "fn load(path: &str) -> Result<String, Box<dyn std::error::Error>> {\n    let raw = std::fs::read_to_string(path)?;\n    let parsed = raw.parse::<i32>()?;\n    Ok(parsed.to_string())\n}\n",
            "slop-context-free-propagation-boxed",
        );
        let hits = rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn two_distinct_try_sites_on_concrete_error_return_is_not_flagged() {
        let findings = findings_for(
            "struct MyError;\nfn load(path: &str) -> Result<String, MyError> {\n    let raw = std::fs::read_to_string(path)?;\n    let parsed = raw.parse::<i32>()?;\n    Ok(parsed.to_string())\n}\n",
            "slop-context-free-propagation-concrete",
        );
        assert!(rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE).is_empty());
    }

    #[test]
    fn context_free_propagation_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(CONTEXT_FREE_PROPAGATION_RULE)
            .expect("context-free-propagation has a registry entry")
            .example
            .expect("context-free-propagation has a curated example")
            .before;
        let findings = findings_for(example, "slop-context-free-propagation-registry-example");
        assert_eq!(
            rule_findings(&findings, CONTEXT_FREE_PROPAGATION_RULE).len(),
            1
        );
    }

    #[test]
    fn debug_placeholder_inside_display_write_is_flagged() {
        let findings = findings_for(
            "struct Money(i64);\nimpl std::fmt::Display for Money {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(f, \"{:?}\", self.0)\n    }\n}\n",
            "slop-debug-format-leak-write",
        );
        let hits = rule_findings(&findings, DEBUG_FORMAT_LEAK_RULE);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::Heuristic);
        assert_eq!(hits[0].evidence.as_ref().unwrap()["type_name"], "Money");
    }

    #[test]
    fn debug_placeholder_inside_display_format_macro_is_flagged() {
        let findings = findings_for(
            "struct Money(i64);\nimpl std::fmt::Display for Money {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_str(&format!(\"{:#?}\", self.0))\n    }\n}\n",
            "slop-debug-format-leak-format-macro",
        );
        let hits = rule_findings(&findings, DEBUG_FORMAT_LEAK_RULE);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn debug_placeholder_inside_debug_impl_is_not_flagged() {
        let findings = findings_for(
            "struct Money(i64);\nimpl std::fmt::Debug for Money {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(f, \"{:?}\", self.0)\n    }\n}\n",
            "slop-debug-format-leak-debug-impl",
        );
        assert!(rule_findings(&findings, DEBUG_FORMAT_LEAK_RULE).is_empty());
    }

    #[test]
    fn display_impl_without_debug_placeholder_is_not_flagged() {
        let findings = findings_for(
            "struct Money(i64);\nimpl std::fmt::Display for Money {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(f, \"{}\", self.0)\n    }\n}\n",
            "slop-debug-format-leak-no-placeholder",
        );
        assert!(rule_findings(&findings, DEBUG_FORMAT_LEAK_RULE).is_empty());
    }

    #[test]
    fn debug_format_leak_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(DEBUG_FORMAT_LEAK_RULE)
            .expect("debug-format-leak has a registry entry")
            .example
            .expect("debug-format-leak has a curated example")
            .before;
        let findings = findings_for(example, "slop-debug-format-leak-registry-example");
        assert_eq!(rule_findings(&findings, DEBUG_FORMAT_LEAK_RULE).len(), 1);
    }
}