cpp_code_analysis 0.4.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
//! **What the checks say, and what they refuse to say.**
//!
//! One positive per rule — the smallest fixture that must produce a finding — and a negative beside it, because
//! this layer's contract is not "find problems" but "**never invent one**": an editor that underlines correct code
//! is one the user turns off, and then it reports nothing at all, forever.
//!
//! The fixtures are asked through [`Session::diagnostics`] rather than through a check called directly, so that
//! what is asserted is what a client is shown: the run, the codes, and the two filters a finding passes on its way
//! out (the config, and the model's three-valued answers).

use cpp_code_analysis::sema::check::{RuleSeverity, RuleTag};
use cpp_code_analysis::{
    CompilerConfig, DiagnosticCode, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};

/// **The codes a file produces** — through the whole session, exactly as a diagnostics request does.
///
/// The ask and the pump are both here because a rendering is built when something asks for it: see
/// `tests/completion.rs`'s `cooked_view` for the note every fixture in this workspace shares.
fn codes_of(source: &str) -> Vec<DiagnosticCode> {
    codes_of_a_file("/p/a.cpp", source)
}

/// [`codes_of`] with the **file name the caller chooses**, because the language a file is read as depends on it: a
/// `.c` file is C, and a rule that is only about C++ must not fire there.
fn codes_of_a_file(path: &str, source: &str) -> Vec<DiagnosticCode> {
    let files = MemoryFiles::new().with_file(path, source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from(path)]);
    session.want_cooked_reading(std::path::Path::new(path));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new(path))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| finding.code)
                .chain(found.errors.iter().map(|error| error.code))
                .collect()
        })
        .unwrap_or_default()
}

/// **A template's body is not checked until it is instantiated, and it must not be.**
///
/// Reported from an editor: this file produced several errors, and none of them is a fact about it. A template is
/// checked when it is *instantiated*, with the arguments written at that call site — so inside the body of a template
/// nothing is known about `C` and `Fn` at all:
///
/// ```text
/// C x{42};        `C` could be anything; whether `{42}` fits is decided per instantiation
/// op(x);          `Fn` could be any callable, or a function pointer, or a member pointer
/// return x.n;     `x.n` is the canonical dependent name — it exists only for the C it is instantiated with
/// ```
///
/// Every one of those is a **false positive** if reported, and this layer's whole contract is that it never invents
/// a finding: an editor that underlines correct code is one the user turns off, and then it reports nothing at all,
/// forever (see this file's header). A template is the place that matters most, because dependent code is exactly
/// what a compiler refuses to diagnose and what a reader most needs *not* underlined.
#[test]
fn a_template_body_is_not_checked() {
    let codes = codes_of(TEMPLATE);
    assert!(
        codes.is_empty(),
        "nothing in a template body is knowable before instantiation: {codes:?}"
    );
}

/// **The suppression is about the type being a parameter, not about the member access.**
///
/// The fix for [`a_template_body_is_not_checked`] is a `continue` in `undefined-field`, and a `continue` that fires
/// too often is how the check stops working without anything going red. So the same shape is written twice, once
/// with a template parameter and once with a real class:
///
/// ```text
/// template <class C> void f() { C x; x.n; }   nothing — `C` is decided at instantiation
/// struct C { int n; };  void g() { C x; x.n; } nothing — `n` is declared
/// struct C { int n; };  void g() { C x; x.m; } UndefinedField — `C` is a class with no `m`
/// ```
///
/// The third is the one that matters: it is the check's whole reason to exist, and it goes through every step the
/// template case now skips past except the last.
#[test]
fn a_real_class_still_reports_an_undefined_member() {
    let declares_it = codes_of("struct C { int n; };\nvoid g() { C x; x.n; }\n");
    assert!(
        declares_it.is_empty(),
        "`C` declares `n`, so there is nothing to say: {declares_it:?}"
    );

    let does_not = codes_of("struct C { int n; };\nvoid g() { C x; x.m; }\n");
    assert!(
        does_not.contains(&DiagnosticCode::UndefinedField),
        "`C` is a class that declares no `m`, which is the finding this check exists for: {does_not:?}"
    );

    // **And the name is not what decides it.** A file that has both a parameter called `C` and a class called `C`
    // asks the question the suppression has to get right, and it is the *type* that answers it: inside the template
    // `C` is the parameter, so `x.m` is unknown; outside it `C` is the class, so `x.m` is a finding. A suppression
    // keyed on the name would be silent in both, and this is the case that says so.
    let both = codes_of(
        "template <class C> void f() { C x; x.m; return; }\n\
         struct C { int n; };\n\
         void g() { C x; x.m; return; }\n",
    );
    assert!(
        both.contains(&DiagnosticCode::UndefinedField),
        "the class `C` outside the template still declares no `m`: {both:?}"
    );
}

/// The reported file, verbatim.
const TEMPLATE: &str = r#"template <class C, class Fn>
constexpr int consteval_validate_destruction(Fn op) {
    C x{42};
    op(x);
    return x.n;
}
"#;

/// **What the reported file actually produces, and why it is not `Unused`.**
///
/// Reported from an editor: this file produced no diagnostic at all, twice — first with a `return 0` that had no
/// `;` (a real parser defect, fixed: `return` was the one statement that said nothing when its terminator was
/// missing), and then with the semicolons written, where the server correctly published an **empty list**.
///
/// The second report is the one this test documents, and the answer is not a bug: the file parses, so
/// `syntax-error` is absent, and the only thing the checks have to say about it is that its three `#include`s do not
/// resolve — which is a fact about the machine the analysis runs on, not about the code:
///
/// ```text
/// in the tests:      [IncludeNotFound, IncludeNotFound, IncludeNotFound]   no compiler search paths exist
/// on a real server:  []                                                    the machine's own paths find them
/// ```
///
/// So a server reporting nothing for this file is **right**, and the expectation that it should say something was
/// wrong. `full.size();` discarding its result is the thing a reader would want underlined, and **no check covers
/// it** — that is a missing rule rather than a broken channel, and it is recorded here rather than asserted, because
/// a test that demanded it would be asserting a rule this layer does not have.
#[test]
fn the_reported_file_reports_only_its_unresolved_includes() {
    let codes = codes_of(REPORTED);
    assert_eq!(
        codes,
        vec![
            DiagnosticCode::IncludeNotFound,
            DiagnosticCode::IncludeNotFound,
            DiagnosticCode::IncludeNotFound
        ],
        "the file parses; the only claim the checks make about it is about the machine's include paths"
    );
}

/// The reported file, verbatim.
const REPORTED: &str = r#"#include <iostream>
#include <string>
#include <cstdio>
int main() {
    int a = 1, b = 2;
    int sum = a + b;
    std::cout << "The sum of " << a << " and " << b << " is: " << sum << std::endl;
    std::string full;
    std::cout << "Full name: " << full << std::endl;
    std::cout << "hello world " << std::endl;
    full.size();
    full.length();
    full.size();
    printf("Full name Length: %zu\n", full.size());
    // printf("Full name Length using length(): %zu\n", full.length());
    return 0;
}
"#;

/// **A file that is correct produces nothing.** The contract of the layer, and the first assertion of every rule
/// below — a check that cannot be quiet about this file is a check that will fire on a real one.
#[test]
fn a_file_with_nothing_wrong_reports_nothing() {
    let codes = codes_of("int add(int a, int b) { return a + b; }\n");
    assert!(
        codes.is_empty(),
        "a plain function is not a finding: {codes:?}"
    );
}

#[test]
fn syntax_error_is_reported() {
    let codes = codes_of("int main( { return 0; }\n");
    assert!(
        codes.contains(&DiagnosticCode::SyntaxError),
        "an unclosed parameter list does not parse: {codes:?}"
    );
}

#[test]
fn unused_is_reported_for_a_local_nothing_reads() {
    let codes = codes_of("int main() { int never_used = 1; return 0; }\n");
    assert!(
        codes.contains(&DiagnosticCode::Unused),
        "`never_used` is written once in the file: {codes:?}"
    );
}

#[test]
fn unused_is_not_reported_for_a_local_that_is_used() {
    let codes = codes_of("int main() { int used = 1; return used; }\n");
    assert!(
        !codes.contains(&DiagnosticCode::Unused),
        "`used` is read on the next line: {codes:?}"
    );
}

#[test]
fn unused_is_not_reported_for_a_name_that_says_it_is_deliberate() {
    // `_name` is how a reader says "I know" — the convention, and the reason the rule stays off those names.
    let codes = codes_of("int main() { int _unused = 1; return 0; }\n");
    assert!(
        !codes.contains(&DiagnosticCode::Unused),
        "a leading underscore is a deliberate choice: {codes:?}"
    );
}

#[test]
fn include_not_found_is_reported_for_a_header_nobody_has() {
    let codes = codes_of("#include <vectr>\nint main() { return 0; }\n");
    assert!(
        codes.contains(&DiagnosticCode::IncludeNotFound),
        "`<vectr>` is not a header: {codes:?}"
    );
}

/// **The underline is the `#include` line, not the line after it.**
///
/// Reported from an editor with a screenshot: `#include <asio.hpp>` on line 4 and a URL comment on line 5 were
/// squiggled by **one** `include-not-found`, so the message looked like it was about the comment. The range came from
/// the directive's tree span, which runs through the trailing trivia to the next real token — the newline, blank
/// lines and the comment under them — where the directive's own line ends at its last real token.
#[test]
fn an_unresolved_include_is_underlined_on_its_own_line() {
    const SOURCE: &str = "#include <asio.hpp>\n// https://stackoverflow.com/questions/1598985/c-read-binary-stdin\n\
                          #ifdef _WIN32\n#include <fcntl.h>\n#endif\nint main() { return 0; }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", SOURCE);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    let path = std::path::Path::new("/p/a.cpp");
    session.add_project_files([std::path::PathBuf::from(path)]);
    session.want_cooked_reading(path);
    session.index_everything();
    let found = session.diagnostics(path).expect("a cooked reading");

    let underlined: Vec<&str> = found
        .checks
        .iter()
        .filter(|finding| finding.code == DiagnosticCode::IncludeNotFound)
        .map(|finding| &SOURCE[finding.range.start_offset..finding.range.end_offset()])
        .collect();
    assert_eq!(
        underlined,
        vec!["#include <asio.hpp>", "#include <fcntl.h>"],
        "one finding per directive, each on its own line — and never the comment under it: {underlined:?}"
    );
}

#[test]
fn macro_redefined_is_reported_for_a_second_different_definition() {
    let codes = codes_of("#define MAX 10\n#define MAX 20\nint main() { return MAX; }\n");
    assert!(
        codes.contains(&DiagnosticCode::MacroRedefined),
        "one name, two bodies, no `#undef`: {codes:?}"
    );
}

#[test]
fn macro_redefined_is_not_reported_for_an_identical_definition() {
    // The one shape the language permits, and it is what a header included twice produces.
    let codes = codes_of("#define MAX 10\n#define MAX 10\nint main() { return MAX; }\n");
    assert!(
        !codes.contains(&DiagnosticCode::MacroRedefined),
        "an identical redefinition is legal: {codes:?}"
    );
}

/// **`>=` is not an assignment**, and the reason a token-kind test cannot tell is worth writing down.
///
/// The lexer **splits** `>=` into two one-byte tokens on purpose, so that `>>` can collapse in
/// `vector<vector<int>>` (see `CppLexer::push`). So the `=` of a `>=` arrives as
/// [`CppTokenKind::Assign`] — the same kind a real assignment has. Measured on
///
/// ```cpp
/// if (a >= b) { … }   →  Greater@32..33 ">"   Assign@33..34 "="   ← one operator, two tokens
/// if (a = b)  { … }   →                          Assign@74..75 "="  ← the real thing
/// ```
///
/// so `is_an_assignment`, which asked only for the kind, reported **both** as `if (a >= b) assigns rather than
/// compares`. The distinction is positional: a real assignment's `=` is the **first** token of the condition, while
/// a split `>=` has its `>` before it. Asking for that is asking the tree what the operator was.
#[test]
fn a_greater_equal_is_not_an_assignment() {
    let source = "\
int f(int a, int b) {
    if (a >= b) {
        return 1;
    }
    if (a <= b) {
        return 2;
    }
    if (a == b) {
        return 3;
    }
    if (a = b) {
        return 4;
    }
    return 0;
}
";
    let found = codes_with_lines(source);
    let lines: Vec<usize> = found
        .iter()
        .filter(|(code, _)| *code == DiagnosticCode::AssignmentInCondition)
        .map(|(_, line)| *line)
        .collect();

    // **Every comparison the lexer splits**, which is the whole family: `>=` and `<=` are each two one-byte tokens
    // so that `>>` can collapse in `vector<vector<int>>` (see `CppLexer::push`), and the `=` half arrives as an
    // `Assign` — the same kind a real assignment has. `==` is not split and was never affected.
    for (line, written) in [(1, "a >= b"), (4, "a <= b"), (7, "a == b")] {
        assert!(
            !lines.contains(&line),
            "`if ({written})` is a comparison, not an assignment: {found:?}"
        );
    }
    assert!(
        lines.contains(&10),
        "`if (a = b)` is the defect this check exists for: {found:?}"
    );
}

/// **The same regression, and the same cause** — see `assignment_in_condition_is_reported_and_the_deliberate_idiom_is_not`.
#[test]
fn unnecessary_branch_is_reported_for_a_literal_condition() {
    let codes = codes_of("int main() { if (false) { return 1; } return 0; }\n");
    assert!(
        codes.contains(&DiagnosticCode::UnnecessaryBranch),
        "`if (false)` cannot run: {codes:?}"
    );
}

#[test]
fn unnecessary_branch_is_not_reported_for_a_name() {
    // A name is a question, not a fact about the text: folding it is another layer's job.
    let codes = codes_of("int main() { if (DEBUG) { return 1; } return 0; }\n");
    assert!(
        !codes.contains(&DiagnosticCode::UnnecessaryBranch),
        "`DEBUG` is not a literal: {codes:?}"
    );
}

/// **A finding lands on the line the reader wrote**, not on the line its offset means in the rendering.
///
/// This is the test for the crossing [`CheckContext::add`] makes. A rendering has no comments and a header inlined
/// in place of its `#include`, so a range read from the **tree** is a different offset in a different text — and
/// before the crossing existed, `unused`'s finding for a local written after a comment was published **on the
/// comment's line**, because the same number was read against the file.
#[test]
fn a_finding_after_a_comment_lands_on_the_line_the_reader_wrote() {
    // Line 0 is a comment the cook removes; the local is on line 1.
    let source = "// a comment the cook removes\nint main() { int never_used = 1; return 0; }\n";
    let lines = lines_of(&codes_with_lines(source));

    assert_eq!(
        lines,
        vec![(DiagnosticCode::Unused, 1)],
        "the unused local is on line 1, where it is written"
    );

    // **And the assertion can fail**, which is what makes it worth having: the same construct sits at a *smaller*
    // offset in the rendering — the comment is not there — so an untranslated finding would have been published at
    // `rendering_at` and read against the file as **line 0**. The two numbers are asserted to differ, so this test
    // fails if the crossing is ever removed.
    let file_at = source.find("never_used").expect("the fixture writes it");
    let rendering = cpp_parser::CppParser::parse(
        "int main() { int never_used = 1; return 0; }\n",
        cpp_parser::ParserConfig::default(),
    );
    let rendering_at = rendering
        .get_red_root()
        .descendants_with_tokens()
        .filter_map(|element| element.into_token())
        .find(|token| token.text() == "never_used")
        .map(|token| usize::from(token.text_range().start()))
        .expect("the local is in the rendering too");
    assert!(
        rendering_at < file_at,
        "the rendering is shorter than the file ({rendering_at} vs {file_at}), which is why the crossing exists"
    );
}

/// The codes, each with the **file** line its range starts on.
fn codes_with_lines(source: &str) -> Vec<(DiagnosticCode, usize)> {
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| {
                    let at = finding.range.start_offset.min(source.len());
                    (finding.code, source[..at].matches('\n').count())
                })
                .collect()
        })
        .unwrap_or_default()
}

fn lines_of(codes: &[(DiagnosticCode, usize)]) -> Vec<(DiagnosticCode, usize)> {
    codes.to_vec()
}

/// **The severity and the tag come from the rule**, not from the finding: `unused` is the quietest thing this
/// analysis says, and a client is told so — a hint, with the code greyed out as unnecessary.
#[test]
fn unused_is_a_hint_that_a_client_may_grey_out() {
    assert_eq!(DiagnosticCode::Unused.severity(), RuleSeverity::Hint);
    assert_eq!(DiagnosticCode::Unused.tags(), &[RuleTag::Unnecessary]);

    // …and the loud ones stay loud, so that the table is a decision rather than a default.
    assert_eq!(DiagnosticCode::SyntaxError.severity(), RuleSeverity::Error);
    assert_eq!(
        DiagnosticCode::UnnecessaryBranch.severity(),
        RuleSeverity::Warning
    );
    assert!(DiagnosticCode::ParamTypeCheck.tags().is_empty());

    // **A header this analysis could not find is a warning** — the claim is about its search (compile database,
    // toolchain discovery, include graph), not about the language; a build can pass `-I` paths a reader's editor
    // cannot see.
    assert_eq!(
        DiagnosticCode::IncludeNotFound.severity(),
        RuleSeverity::Warning
    );
}

/// **A value that cannot convert to a written builtin type is reported** at both places a value enters an object
/// whose type is written down: the declaration and the assignment.
/// **Known not to work, and the test is the record of it.**
///
/// The declaration half passes and the assignment half reports nothing, and the reason is *not* the shape: the tree
/// of `count = "four"` is
///
/// ```text
/// BinaryExpr@28..42
///   IdentifierExpr@28..34   (its text is "count " - the trailing space is inside the node)
///   Token(Assign)@34..35    "="
///   LiteralExpr@36..42      "\\"four\\""
/// ```
///
/// — one `BinaryExpr`, two operand nodes, and the operator as a token between them, which is what the walk looks
/// for. So the cause is downstream of the shape and has not been found yet; the failure is asserted out loud rather
/// than left as a red test, and this note is what the next round starts from.
#[test]
fn assign_type_check_reports_both_places_a_value_is_assigned() {
    let declared = "int count = \"three\";\nint main() { return count; }\n";
    assert!(
        codes_of(declared).contains(&DiagnosticCode::AssignTypeCheck),
        "a string is not an int: {:?}",
        codes_of(declared)
    );

    let assigned = "int main() { int count = 0; count = \"four\"; return count; }\n";
    assert!(
        codes_of(assigned).contains(&DiagnosticCode::AssignTypeCheck),
        "and the same question at an assignment: {:?}",
        codes_of(assigned)
    );
}

/// **A name the file declares two ways is not judged** — and the report that made this a rule.
///
/// Reported from an editor as *"an extremely wrong diagnostic"*. `LuaSource.cpp` reads
///
/// ```cpp
/// std::size_t LuaSource::GetColumn(std::size_t offset) const {
///     auto line = GetLine(offset);
///     auto lineStartOffset = _lineOffsetVec[line];
/// ```
///
/// and the check said "`line` is initialised with a value that does not convert to `std::size_t`" about the **deduced**
/// `line`, because its map was keyed by the bare name over every variable the file declares and another function
/// writes `std::size_t line;`. Measured on that file: seven `line`s whose `type_of` is `auto` and two whose is
/// `std::size_t`.
#[test]
fn assign_type_check_stays_quiet_about_a_name_the_file_declares_two_ways() {
    // Two functions, both declaring `line`: one deduced, one written. The deduced one must not be judged against the
    // written one's type, and neither may the reverse (the two values are compatible here, so this is only about the
    // name collision — a *wrong* pair is the fixture below).
    let source = "struct Source { std::size_t GetLine(std::size_t offset); };\n\
                  void one(Source &s, std::size_t offset) {\n\
                  \x20   auto line = s.GetLine(offset);\n\
                  \x20   auto next = line;\n\
                  }\n\
                  void two() {\n\
                  \x20   std::size_t line = 1;\n\
                  \x20   line = 2;\n\
                  }\n";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
        "neither `line` is judged"
    );

    // **And a single written declaration is still judged**, which is the check's whole job.
    let wrong = "void f() {\n    int count = \"zero\";\n}\n";
    assert!(
        codes_of(wrong).contains(&DiagnosticCode::AssignTypeCheck),
        "one written type is one answer"
    );
}

/// **A class target stays quiet, and this test is the record of why.** `std::string line = 1231;` is not legal C++,
/// and this layer does not report it: "does `std::string` have a constructor taking an `int`" is a question whose
/// answer is in a header the analysis has not read, so `convertible_to` answers `Unknown` — and `Unknown` is never
/// a finding. The alternative is a rule that reports conversions it cannot see, which is what this layer is written
/// against.
#[test]
fn assign_type_check_stays_quiet_when_the_target_is_a_class_it_cannot_see_into() {
    let source =
        "#include <string>\nstd::string line = 1231;\nint main() { return (int)line.size(); }\n";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
        "a conversion nobody modelled is not a fact about the program: {:?}",
        codes_of(source)
    );
}
/// **Known not to fire yet, and this test is the record of it.**
///
/// The two negatives pass — a public member and a member read from inside the class are correctly quiet — so the
/// member lookup, the access specifier reading and the "inside the class" question all work. What is missing is the
/// positive: a private member reached from `main` is not reported, and the cause has not been found. The next round
/// starts here, with the same method that found the last two: print what the check sees, one level closer to the
/// decision than the last probe.
#[test]
fn access_invisible_is_reported_outside_the_class() {
    let source = "class Widget {\n    int secret;\npublic:\n    int size;\n};\n\nint main() { Widget w; return w.secret; }\n";
    assert!(
        codes_of(source).contains(&DiagnosticCode::AccessInvisible),
        "`secret` is private and `main` is not Widget: {:?}",
        codes_of(source)
    );
}

#[test]
fn access_invisible_is_not_reported_for_a_public_member_or_from_inside() {
    let public_member =
        "class Widget {\npublic:\n    int size;\n};\n\nint main() { Widget w; return w.size; }\n";
    assert!(
        !codes_of(public_member).contains(&DiagnosticCode::AccessInvisible),
        "`size` is public: {:?}",
        codes_of(public_member)
    );

    let from_inside =
        "class Widget {\n    int secret;\npublic:\n    int mine() { return secret; }\n};\n";
    assert!(
        !codes_of(from_inside).contains(&DiagnosticCode::AccessInvisible),
        "a member function may read its own class private member: {:?}",
        codes_of(from_inside)
    );
}

/// **Known not to fire yet, and this test is the record of it.**
///
/// The negatives pass. The positive does not, and the reason is *not* the shape of a definition any more: the
/// predicate was fixed to match the tree this grammar actually builds — a `Declaration` whose `CompoundStat` is a
/// child while its `ParameterList` is a grandchild inside `InitDeclarator > Declarator` — and the finding still does
/// not come out. So the cause is downstream of the shape.
#[test]
fn missing_return_is_reported_for_a_body_that_never_returns() {
    assert!(
        codes_of("int count() { }\nint main() { return count(); }\n")
            .contains(&DiagnosticCode::MissingReturn),
        "the body returns nothing and the type is not void"
    );
}

/// **The rule asks whether a path reaches the closing brace** — not whether the body contains a `return`, and not by
/// searching the text.
///
/// The old rule was "no `return` anywhere", which was silent for `int only_one(int x) { if (x) return 1; }` — the shape a
/// reader writes by accident — and it decided the exceptions by searching the body's **text**: `throw ` anywhere silenced it
/// (`int sometimes(int x) { if (x) throw x; }` falls through and was not reported), and a `while (true)` in a nested loop did
/// the same. The shapes below are the two directions of that mistake.
#[test]
fn missing_return_is_a_control_flow_question() {
    let reported = [
        // A `return` exists and only one path uses it.
        "int only_one(int x) { if (x) return 1; }",
        // A `throw` in a branch does not make the other branch return.
        "int sometimes(int x) { if (x) throw x; }",
        // A loop that can be left falls through, and so does a loop with a condition.
        "int breaks() { while (true) { break; } }",
        "int counted(int n) { for (int i = 0; i < n; ++i) { } }",
        // A literal `false` condition takes the branch that does not exist.
        "int never() { if (false) return 1; }",
    ];
    for source in reported {
        assert!(
            codes_of(source).contains(&DiagnosticCode::MissingReturn),
            "this body can reach its closing brace: {source}"
        );
    }

    let silent = [
        // Every path returns.
        "int both(int x) { if (x) return 1; else return 2; }",
        // **A `switch` whose every label returns, and which has a `default`.** Reported from
        // `EmmyLuaCodeStyle`'s `LuaParser::BlockFollow`, whose body is exactly this shape: reported "this function
        // is declared to return `bool` and its body has no `return`" with four `return`s in it. A `switch` with a
        // `default`, no `break`, and a last statement that does not complete cannot leave through its end: fallthrough
        // carries every path that enters a label down to the same terminator.
        "int by_switch(int x) { switch (x) { case 1: return 1; case 2: return 2; default: return 0; } }",
        "int by_switch_with_blocks(int x) { switch (x) { case 1: { return 1; } default: { return 0; } } }",
        "int by_switch_that_throws(int x) { switch (x) { case 1: return 1; default: throw x; } }",
        // A body that always throws never returns and needs no `return`: the user's own case.
        "int throws() { throw 1; }",
        "int throws_in_else(int x) { if (x) return 1; else throw 1; }",
        // Endless loops.
        "int forever() { while (true) { } }",
        "int for_ever() { for (;;) { } }",
        "int do_forever() { do { } while (true); }",
        // A literal `true` condition decides which branch exists.
        "int always() { if (true) return 1; }",
        // A deduced type promises nothing, and a constructor asks nothing.
        "auto deduced(int x) { if (x) return 1; }",
        "struct S { S(int x) { if (x) { } } };",
    ];
    for source in silent {
        assert!(
            !codes_of(source).contains(&DiagnosticCode::MissingReturn),
            "no path reaches the end here: {source}"
        );
    }
}

/// **A decorated constructor and a decorated destructor promise no return.**
///
/// `explicit A(int x) : x_(x) {}`, `virtual ~A() {}` and `constexpr C(int x) : x_(x) {}` all write a **specifier
/// sequence** — `explicit`, `virtual`, `constexpr`, and the first and third keep the constructor's own name in it — so
/// the rule's old guard ("a declaration with no specifier sequence is a constructor") let all three through, and each
/// was reported as *"this function is declared to return `` and its body has no `return`"*. Measured with `inspect
/// diagnostics` on this fixture: three findings, now none.
///
/// The functions beside them are the other half, because a rule that stopped reporting altogether would pass this test
/// and be useless: `int broken()` and `int S::f()` still report, with the type they actually write.
#[test]
fn missing_return_is_silent_for_a_decorated_constructor_and_destructor() {
    let decorated = "\
struct A {
    explicit A(int x) : x_(x) {}
    virtual ~A() {}
    A() = default;
    int x_;
};
struct B : A {
    B() : A(0) {}
    ~B() override {}
};
struct C {
    inline C() {}
    constexpr C(int x) : x_(x) {}
    ~C() noexcept {}
    int x_;
};
";
    assert_eq!(
        codes_of(decorated),
        [],
        "a constructor and a destructor promise nothing, whatever they are written with"
    );

    let written = "\
struct S { int f() { } };
int broken() { }
";
    let found = codes_of(written);
    assert!(
        found
            .iter()
            .filter(|code| **code == DiagnosticCode::MissingReturn)
            .count()
            == 2,
        "and the functions that do write a return type still report: {found:?}"
    );
}

/// **What the return type promises is a question about the type, not about the word `void`.**
///
/// Three defects of the keyword test this replaces, each measured with `inspect diagnostics` on the fixtures below:
///
/// ```text
///   void *p() { }                        silent before — a pointer returns a value, and `void` is in its spelling
///   typedef void nothing; nothing t()    reported before — the name *is* `void`
///   static UNRESOLVED_TYPE v() { }       reported — and a name the reading cannot resolve is not evidence of a value
/// ```
///
/// The third is the shape reported from Lua 5.5.0's `ldebug.c`: `static l_noret typeerror(…)` is declared to return
/// `l_noret`, which is `void __declspec(noreturn)` (or `void __attribute__((noreturn))`, or plain `void`), and in a
/// reading that does not carry that `#define` the rule called a function whose whole purpose is not to return
/// incomplete.
#[test]
fn missing_return_reads_the_declared_type_rather_than_the_word_void() {
    let reported = [
        // A pointer is a value whatever precedes it.
        "void *buffer() { }",
        // A name that resolves to something with a size.
        "struct W { int x; };\nstatic W make() { }",
        // A `typedef` for a value.
        "typedef int myint;\nstatic myint count() { }",
    ];
    for source in reported {
        assert!(
            codes_of(source).contains(&DiagnosticCode::MissingReturn),
            "something is promised here: {source}"
        );
    }

    let silent = [
        // A `typedef` of `void` is `void`: the reported shape.
        "typedef void nothing;\nstatic nothing stop() { }",
        // **A name this reading cannot resolve is not a value.** The reading may not have expanded a macro, and the
        // safe direction is silence — the rule's other arms still report what they are sure of.
        "static UNRESOLVED_TYPE stop() { }",
    ];
    for source in silent {
        assert!(
            !codes_of(source).contains(&DiagnosticCode::MissingReturn),
            "nothing is proven to be promised here: {source}"
        );
    }
}

#[test]
fn missing_return_is_not_reported_for_void_or_for_a_returning_body() {
    assert!(
        !codes_of("void stop() { }\nint main() { return 0; }\n")
            .contains(&DiagnosticCode::MissingReturn),
        "void expects nothing"
    );
    assert!(
        !codes_of("int count() { return 1; }\nint main() { return count(); }\n")
            .contains(&DiagnosticCode::MissingReturn),
        "a body that returns is the ordinary case"
    );
}

/// **A condition with a comparison in it is not an assignment**, and this is the user's own line: a `<` is not a
/// bracket, and treating it as one is how the condition's text was read past its own `)` and into the body, where
/// the first statement `const auto message = readMessage();` has an `=` of its own. Reported from a real session as
/// `assigns rather than compares` on a line whose condition is two comparisons.
/// **The line this check was reported on, verbatim.** A condition that is a compound — `&&`, a string literal, a
/// `<` — is refused before anything inside it is looked at, so no reading of the text can make it an assignment.
#[test]
fn the_users_own_condition_is_not_reported() {
    let source = "\
int main(int argc, char** argv) {
    if (arg == \"--port\" && i + 1 < argc) {
        return 2;
    }
    const auto message = readMessage();
    return (int)message;
}
";
    let codes = codes_of(source);
    assert!(
        !codes.contains(&DiagnosticCode::AssignmentInCondition),
        "a compound condition is not this rule: {codes:?}"
    );
}
#[test]
fn a_less_than_in_a_condition_is_not_an_assignment() {
    let source = "\
int main(int argc, char** argv) {
    if (argc == 2 && argc + 1 < argc) {
        const auto message = argc;
        return message;
    }
    return 0;
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::AssignmentInCondition),
        "two comparisons are not an assignment: {:?}",
        codes_of(source)
    );
}
/// **A regression this round, left visible rather than hidden.**
///
/// The check went quiet when its condition test was rewritten onto tokens: `CppTokenKind` is a **nested** enum — an
/// operator is `Operator(OperatorKind::…)`, a bracket is `Punctuation(Punct::…)` — so a flat `match` against
/// `Assign` **compiles and never matches**. That is the same shape as the defects this whole round is about: a
/// hand-written comparison of a type the layer does not own, failing silently instead of failing to build. The
/// **A class declared in this file, and a value that cannot build it.**
///
/// The class is written **here** rather than included, and that is the lesson of three fixtures before this one: an
/// `#include` in a fixture does not resolve (see the guard test below), so a class "from a header" is a class that
/// does not exist — and the check that asks about it has nothing to find. With the definition in the file, the
/// question this rule exists for is actually put: `MyString` declares no constructor, so an `int` cannot build it.
///
/// The conversion relation itself cannot answer this — `convertible_to` lives in the type engine and cannot see a
/// declaration, so it answers `Unknown("a conversion between these two types is not decided by their shapes")` for
/// any class target. Deciding it needs the class's own definition, which is exactly what a check may read when the
/// class is in the file it is checking.
#[test]
fn a_class_in_this_file_that_no_value_can_build_is_reported() {
    let source = "\
struct MyString {
    int size;
};

int main() {
    MyString line = 1231;
    return line.size;
}
";
    let codes = codes_of(source);
    assert!(
        codes.contains(&DiagnosticCode::AssignTypeCheck),
        "`MyString` is defined here, declares no constructor, and an `int` cannot build it: {codes:?}"
    );
}
/// **A finding underlines what it is about and nothing more**, which is a claim about the *range* rather than about
/// the message — and the range is where a crossing can go wrong quietly: the start is a position and the end is the
/// end of the last byte covered, and asking the same question for both walks the end forward over the punctuation
/// and the newline that the next span owns.
#[test]
fn a_finding_underlines_only_the_construct_it_is_about() {
    // A builtin target, because `assign-type-check` fires there — see
    // `a_string_initialised_from_an_int_is_measured_here` for the class target, which it does not answer yet.
    // **No constructor declared**, which is the whole question: a class with one might take the value, and deciding
    // whether it does is overload resolution rather than a walk over a tree.
    let header = "struct MyString { int size; };\n";
    let source = "#include \"mystring.h\"\n\nint main() {\n    int count = \"three\";\n    return count;\n}\n";
    let (_, range) = first_finding_of(source, header, DiagnosticCode::AssignTypeCheck);

    assert_eq!(
        &source[range.start_offset..range.end_offset()],
        "\"three\"",
        "the finding is about the value, not about the statement it is written in"
    );
}

/// **A member of a `using` alias is the member of the class it names.**
///
/// Reported from an editor: `undefined-field` underlined `result.size()` on a `std::string`, and the measurement
/// behind it is `members_of(std::string) -> 0 member(s), unlisted []` — an *empty but complete* list, which the
/// check reads as "this class has no members". The empty answer came from the alias being treated as a class with
/// no members instead of being followed to the class it names.
#[test]
fn a_member_reached_through_a_using_alias_is_not_undefined() {
    let source = "\
struct Base { int size; };
using Alias = Base;
void use() {
    Alias a;
    (void)a.size;
}
";
    let codes = codes_of(source);
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedField),
        "the alias names `Base`, and `Base` has `size`: {codes:?}"
    );
}

/// **A deduced `auto` is not a conversion question** — `auto&` least of all.
///
/// Reported from an editor: `auto& config = configs.emplace_back(…);` was underlined with "`config` is initialised
/// with a value that does not convert to `auto&`". The type written there is not a type: it is an instruction to
/// deduce one from the initialiser, so every spelling of it — `auto`, `auto&`, `const auto&`, `auto&&`, `auto*` —
/// is outside this check's question. See `assign_type_check::is_a_deduced_auto`.
#[test]
fn a_deduced_auto_is_not_a_conversion_question() {
    let source = "\
struct Widget { int n; };
Widget& make();
void use() {
    int value = 1;
    auto plain = value;
    auto* pointer = &value;
    auto& reference = make();
    const auto& constant = make();
    auto&& forwarded = make();
    (void)plain; (void)pointer; (void)reference; (void)constant; (void)forwarded;
}
";
    let codes = codes_of(source);
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "a deduced type is not a written one, so nothing here can fail to convert: {codes:?}"
    );
}

/// The first finding of one code in a two-file fixture, with its range in the **file's** coordinates.
fn first_finding_of(
    source: &str,
    header: &str,
    code: DiagnosticCode,
) -> (usize, cpp_parser::SourceRange) {
    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", source)
        .with_file("/p/mystring.h", header);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/mystring.h"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();

    for finding in session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| found.checks)
        .unwrap_or_default()
    {
        if finding.code == code {
            return (0, finding.range);
        }
    }
    panic!("no `{}` finding", code.name());
}
/// **A member a class does not have is reported** — and this test did not exist, which is why the check was blind to
/// `a.b` for as long as it has: it filtered on `MemberExpr`, a kind this grammar does not produce for a dot
/// (`w.secret` parses as an `IndexExpr`; see `CheckContext::member_accesses`).
#[test]
fn undefined_field_is_reported_for_a_name_the_class_does_not_have() {
    let source = "\
struct Widget {
    int size;
};

int main() {
    Widget w;
    return w.sizze;
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "`sizze` is not a member of `Widget`: {:?}",
        codes_of(source)
    );
}

/// **And a member it does have is not reported** — the negative that keeps the positive honest.
#[test]
fn undefined_field_is_not_reported_for_a_member_that_is_there() {
    let source = "\
struct Widget {
    int size;
};

int main() {
    Widget w;
    return w.size;
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "`size` is a member of `Widget`: {:?}",
        codes_of(source)
    );
}
/// **An `#include` in a fixture does not resolve, and a test that assumes it does measures nothing.**
///
/// This is the trap this workspace has fallen into three times — an angle include with no search path, a class whose
/// header was never inlined, and this test in its first two versions, which asserted that a check sees "the file and
/// not the header" while the header was never read in the first place.
///
/// What the measurement says: with `MemoryFiles`, a quoted include beside the file, the header registered as a
/// project file **and** `CompilerConfig::with_include_path("/p")`, the view's text comes out **shorter than the
/// file** — the `#include` line and the comment are gone and nothing is inlined, i.e. the header was not found.
///
/// So the assertion is the honest one, and it is a guard rather than a claim:
///
/// ```text
///   a fixture that means to exercise an include MUST first prove the include resolved,
///   by asserting that the rendering's text contains something only the header has
/// ```
#[test]
fn an_include_in_a_fixture_does_not_resolve_unless_the_test_proves_it_does() {
    let header = "// a header\nstruct FromTheHeader { int size; };\n";
    let source =
        "#include \"big.h\"\n\nint main() {\n    int never_used = 1;\n    return never_used;\n}\n";

    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", source)
        .with_file("/p/big.h", header);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default().with_include_path("/p"),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/big.h"),
    ]);
    // The pump, the ask, the pump — the contract `tests/completion.rs` states once for the workspace.
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    let view = session.view("/p/a.cpp").expect("a view");
    eprintln!(
        "INCLUDE: view text {} bytes, file {} bytes, inlined={}",
        view.source.len(),
        source.len(),
        view.source.contains("FromTheHeader")
    );
    assert!(
        !view.source.contains("FromTheHeader"),
        "if this ever starts passing, every test that assumed an include resolves needs revisiting"
    );
}
/// **A class from another file, judged from the index** — which is the whole point of "the finding is about this
/// file, the knowledge is the project's".
///
/// The class is declared in a **second project file** and the including file's `#include` is deliberately not relied
/// on: a fixture include does not resolve (see the guard test above), and it does not have to, because the answer is
/// a **fact the cook produced** — `DeclFact::parameter_list`, stored in the index's own words *"because a query holds
/// one file and the parameters are written in another"*.
///
/// Two files, two constructors, two answers:
///
/// ```text
///   Widget(Widget&&)      and no way to take an `int`   -> reported, from the index
///   Widget(int)                                        -> not reported, from the index
/// ```
/// **What the index answers today about a class in another file** — measured, and not what it needs to be.
///
/// The intent of this test is the architecture: a class declared in a **second project file** should be judged from
/// the facts the cook produced — `DeclFact::parameter_list`, stored in the index's own words *"because a query holds
/// one file and the parameters are written in another"* — so that `std::string x = 123;` is answerable from a `.cpp`
/// whose `<string>` is not its own text.
///
/// What it measures instead is the blocker: `members_of("Widget")` answers **`Yes` with an empty member list** for a
/// class whose definition is only in the other file, so nothing can be concluded about its constructors. Two things
/// follow, and both are in the code:
///
/// ```text
///   the guard     an empty member list answers `None` (unknown), never "no constructors" — reading it the other way
///                 reported `Widget(int size)` as unbuildable, which is a false positive from a missing fact
///   the gap       why the list is empty is the next question. `unlisted` exists to say what a truncated list is
///                 missing, and the probe here printed `0 members []` with nothing in it
/// ```
#[test]
fn a_class_from_another_file_answers_unknown_rather_than_wrong() {
    let cannot = "struct Widget {\n    Widget(Widget&& other);\n    int size;\n};\n";
    let can = "struct Widget {\n    Widget(int size);\n    int size;\n};\n";
    let source = "\
int main() {
    Widget w = 1231;
    return 0;
}
";

    // **Nothing is reported either way**, which is the honest answer for a fact this layer does not have: a missed
    // finding rather than an invented one. When `members_of` answers with members for another file's class, the
    // second of these two becomes a finding and this test is the one to change.
    assert!(
        !codes_with_two_files(source, cannot).contains(&DiagnosticCode::AssignTypeCheck),
        "a class whose members are not in the index is not judged: {:?}",
        codes_with_two_files(source, cannot)
    );
    assert!(
        !codes_with_two_files(source, can).contains(&DiagnosticCode::AssignTypeCheck),
        "and the one with the right constructor is not reported either: {:?}",
        codes_with_two_files(source, can)
    );
}
/// The codes a file produces, in a session where a **second file** is part of the project — so that the index holds
/// its declarations, which is what a check reads facts about another file from.
fn codes_with_two_files(source: &str, other: &str) -> Vec<DiagnosticCode> {
    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", source)
        .with_file("/p/other.h", other);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/other.h"),
    ]);
    // The pump, the ask, the pump — `tests/completion.rs` states the contract once for the workspace.
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| found.checks.iter().map(|finding| finding.code).collect())
        .unwrap_or_default()
}
/// **The arity question for a callee declared in another file** — the architecture, and its measured state today.
///
/// The intent: `argument-count` reads a callee's parameter list as a **fact** (`DeclFact::parameter_list`, stored
/// *"because a query holds one file and the parameters are written in another"*), so `v.reserve(1, 2)` is judged
/// without parsing a header per keystroke. `callee_from_the_index` implements exactly that, refusing an overload set
/// whole.
///
/// What is measured: it does not resolve yet. On the real corpus —
/// `cargo run --example one_check -- target/std-cook target/std-cook/arity-case.cpp argument-count` — a file calling
/// `v.reserve(1, 2)` and `s.append("a", "b", "c")` reports **zero**, so `definitions(name, path)` is answering
/// something other than the single visible declaration. This fixture says the same thing through a second file, and
/// asserts the honest answer for a fact the layer does not have: **no finding**, rather than a wrong one.
#[test]
fn a_callee_from_another_file_is_not_judged_until_the_lookup_answers() {
    let other = "int scale(int value, int factor);\n";
    let too_many = "\
int main() {
    int x = scale(1, 2, 3);
    return x;
}
";
    // **In this file** the same arity question is judged, which is what makes the line above a gap rather than a
    // hole in the rule: the machinery works, the cross-file lookup is what does not answer yet.
    let here = "\
int scale(int value, int factor) { return value * factor; }

int main() {
    int x = scale(1, 2, 3);
    return x;
}
";
    // **And measured, the in-file case does not fire either**, which is the real finding of this round: `scale(1, 2,
    // 3)` beside its own declaration reports nothing. So `argument-count` is not "missing the cross-file lookup" —
    // its basic case is quiet too, and the next round starts there: the same shape as every other defect in this
    // layer (`FunctionDef` is not how this grammar records a file-scope definition; a parameter list and an argument
    // list are not where a `children()` walk expects them), and the same method fixes it — print what the check
    // sees, one level closer to the decision than the last probe.
    assert!(
        codes_of(here).contains(&DiagnosticCode::ArgumentCount),
        "a callee declared in this file is judged: {:?}",
        codes_of(here)
    );
    assert!(
        !codes_with_two_files(too_many, other).contains(&DiagnosticCode::ArgumentCount),
        "and one declared in another file is not judged yet: {:?}",
        codes_with_two_files(too_many, other)
    );
}
/// **A function template whose return-type spelling carries its header is not judged for a missing return.**
///
/// Measured on EmmyLuaCodeStyle: `template<ServiceClass Service, typename... ARGS> void
/// LanguageServer::AddService(ARGS &&...args) { … }` was reported as returning something with no `return` in its body —
/// the fact carried the **template header and the return type** in one string, and the check compared it to `"void"`
/// exactly.
#[test]
fn a_function_templates_type_that_carries_its_header_is_not_judged() {
    let source = "\
template<class Service>
void AddService(Service service) {
    int unused_index = 0;
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::MissingReturn),
        "`void` after a template header is still `void`: {:?}",
        codes_of(source)
    );

    let really_missing = "\
int AddService(int service) {
    int unused_index = 0;
}
";
    assert!(
        codes_of(really_missing).contains(&DiagnosticCode::MissingReturn),
        "and an `int` function with no return is still a finding: {:?}",
        codes_of(really_missing)
    );
}
/// **A construction and a parameter's default are not conversions to judge.**
///
/// Both shapes are from EmmyLuaCodeStyle, and between them they were all twelve of the project's `assign-type-check`
/// findings: `LineSpace x = LineSpace(LineSpaceType::Keep);` ten times, and `Range(Position _start = Position(0, 0))`
/// twice. The second half says a real mismatch is still reported, so neither guard becomes a blanket silence.
#[test]
fn a_construction_and_a_default_argument_are_not_conversions_to_judge() {
    let constructions = "\
enum class LineSpaceType { Keep };
struct LineSpace { LineSpace(LineSpaceType); };
LineSpace line_space_after_if_statement = LineSpace(LineSpaceType::Keep);
";
    assert!(
        !codes_of(constructions).contains(&DiagnosticCode::AssignTypeCheck),
        "the initialiser names the target type: {:?}",
        codes_of(constructions)
    );

    let defaults = "\
struct Position { Position(int line, int character); };
struct Range { Range(Position start = Position(0, 0)); };
";
    assert!(
        !codes_of(defaults).contains(&DiagnosticCode::AssignTypeCheck),
        "a default argument is the parameter's declaration, not a variable's: {:?}",
        codes_of(defaults)
    );

    // The module's own example, which is the shape this check exists for. (A *class* target with a string initialiser
    // is not one: `convertible_to` answers `Unknown` there, and the check is quiet — which is the second assertion
    // above, seen from the other side.)
    let real_mismatch = "\
void g() {
    int count = \"four\";
}
";
    assert!(
        codes_of(real_mismatch).contains(&DiagnosticCode::AssignTypeCheck),
        "and a string assigned to an int is still a finding: {:?}",
        codes_of(real_mismatch)
    );
}
/// **A call whose name is also a type is a constructor call, and is not judged as a free function's arity.**
///
/// The shape is the one EmmyLuaCodeStyle has 16 times: `NameStyleRule(NameStyleType::SnakeCase)` — one argument — beside
/// a *function* fact named `NameStyleRule` with two parameters, which made the check report "needs 2 … passes fewer" on
/// code that compiles. Which constructor a call means is overload resolution among constructors, which this check does
/// not do; a name that names a type is silence instead.
#[test]
fn a_call_whose_name_is_also_a_type_is_not_judged_for_arity() {
    // The struct and the function share a spelling in **one** file, which is the real project's shape: the name is a
    // type, so the call constructs, and the function's arity says nothing about it.
    let source = "\
struct NameStyleRule {
    int value;
};
void NameStyleRule(int first, int second) {}
void g() {
    NameStyleRule(1);
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::ArgumentCount),
        "the name is a type here, so the call constructs rather than calls: {:?}",
        codes_of(source)
    );
}
/// **An arrow is judged against the class it reaches**, and only when the engine can follow it.
///
/// Measured on EmmyLuaCodeStyle: `_session->Send(std::move(message))` was once reported as "`_session` has no member
/// `Send`" — the receiver is a `std::shared_ptr<Session>`, whose member list is `shared_ptr`'s, and the member the
/// program means is behind `operator->`. The answer was to skip arrows, which then missed `p->Missing()` on a plain
/// `Session*` — a class whose member list *is* the answer. Both halves are pinned here: the pointee's members are
/// judged, and an arrow nothing can follow is silence.
#[test]
fn an_arrow_is_judged_against_the_class_it_reaches() {
    let through_a_pointer = "\
struct Session {
    void Run();
};
void g(Session *session) {
    session->Run();
}
";
    assert_eq!(codes_of(through_a_pointer), [], "`Run` is the pointee's");

    let a_missing_member = "\
struct Session {
    void Run();
};
void g(Session *session) {
    session->Missing();
}
";
    assert_eq!(
        codes_of(a_missing_member),
        [DiagnosticCode::UndefinedField],
        "`Session` has no `Missing`, and the arrow reaches `Session`"
    );

    // **The receiver's own class is not the answer**: a class whose `operator->` returns something this layer
    // cannot type is silence, not a finding about the memb* its own list does not have either.
    let an_untraceable_arrow = "\
struct Session {
    void Run();
};
struct Pointer {
    Missing *operator->();
};
void g(Pointer pointer) {
    pointer->Run();
}
";
    assert_eq!(
        codes_of(an_untraceable_arrow),
        [],
        "the pointee cannot be typed, so nothing is said"
    );
}
/// **A member call is not judged against a free function of the same name.**
///
/// Measured on EmmyLuaCodeStyle: `_session.Run(…)` was judged against a free `Run()` taking no arguments and reported as
/// "takes 0 argument(s) and this call passes more" — the wrong declaration, with the wrong arity, on code that compiles.
/// Resolving the member needs the object's type; until that answer is trusted here, the check says nothing, which is the
/// direction this layer documents.
#[test]
fn a_member_call_is_not_judged_against_a_free_function_of_the_same_name() {
    let source = "\
struct Session {
    void Run();
};
void Run(int value, int other) {}
void g(Session session) {
    session.Run();
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::ArgumentCount),
        "`session.Run()` is the member, not the free `Run(int, int)`: {:?}",
        codes_of(source)
    );
}
/// **A template's parameter is silent to the argument checks, and that is the right answer rather than a gap.**
///
/// Deduction turns `f(T)` into `f(std::string)` for a `std::string` argument, and a parameter that *is* the argument's
/// own type is convertible by construction — so inferring the template arguments cannot make `param-type-check` report
/// anything it does not report today. The check that *can* see a template is the arity one, and it does: `written` and
/// `required` come from the declaration's tokens, not from its types.
///
/// Written as a test so that "no finding" is a decision with a reason rather than an accident, and so that a future
/// change that makes this report is a deliberate one.
#[test]
fn a_templates_own_parameter_is_silent_to_the_type_check_and_the_arity_check_still_judges_it() {
    let silent = "\
template <typename T>
void take(T value);
void g() {
    take(1);
    take(\"one\");
}
";
    assert!(
        !codes_of(silent).contains(&DiagnosticCode::ParamTypeCheck),
        "a `T` parameter is the argument's own type however it was deduced: {:?}",
        codes_of(silent)
    );

    let wrong_arity = "\
template <typename T>
void take(T value);
void g() {
    take(1, 2);
}
";
    assert!(
        codes_of(wrong_arity).contains(&DiagnosticCode::ArgumentCount),
        "the arity of a template is in its tokens, so it is judged: {:?}",
        codes_of(wrong_arity)
    );
}
/// **An overload set is resolved, not judged against its last declaration.**
///
/// Before the resolver existed, this check kept one `Callee` per name — a later declaration **overwrote** an earlier
/// one — so `f(1)` beside `f(int)` and `f(int, int)` was judged against whichever was read last and reported *"takes 2
/// argument(s) and this call passes fewer"* about a program that is perfectly well-formed. The set is now ranked
/// against the call's own argument types, and a call that **some** candidate takes is silence.
#[test]
fn an_overload_set_is_resolved_rather_than_judged_against_its_last_declaration() {
    let well_formed = "\
void f(int) {}
void f(int, int) {}
void g() {
    f(1);
    f(1, 2);
}
";
    assert!(
        !codes_of(well_formed).contains(&DiagnosticCode::ArgumentCount),
        "every call fits a declaration: {:?}",
        codes_of(well_formed)
    );

    // **And the case that is still a finding**: no candidate takes this shape, so the call cannot be right about any
    // of them. This is the only arity report the resolution leaves, and it is the one that is a fact about the file.
    let nothing_fits = "\
void f(int) {}
void f(int, int) {}
void g() {
    f(1, 2, 3);
}
";
    assert!(
        codes_of(nothing_fits).contains(&DiagnosticCode::ArgumentCount),
        "no declaration takes three arguments: {:?}",
        codes_of(nothing_fits)
    );
}
/// **Every code has a name, and the name round-trips** — the property a client's filter and a config file both
/// depend on, asserted here because it is the one thing that cannot be checked by looking at a fixture.
#[test]
fn every_code_has_a_name_and_the_name_comes_back() {
    for code in DiagnosticCode::ALL {
        let name = code.name();
        assert!(!name.is_empty(), "{code:?} has no name");
        assert_eq!(
            DiagnosticCode::from_name(name),
            Some(code),
            "`{name}` does not come back as {code:?}"
        );
    }
}
/// **A parameter pack is not a fixed arity, and neither is a C-style `...`.**
///
/// `template <class... Args> void f(Args&&... args)` may be called with as many arguments as the caller likes, and the
/// cross-file half of `argument-count` counted it as **one written, one required** parameter: a call passing three was
/// reported as *"takes 1 argument(s) and this call passes more"*. The test was `parameter.ends_with("...")`, which is
/// true of the C-style `...` and of `Args...` and of **nothing else people write** — `Args&&... args` and `Args... args`
/// are the two spellings the standard library is actually full of. The file-scope half of the same check was already
/// right, because it asks each parameter's **tokens** for an `Ellipsis`; only the text half was wrong.
///
/// Measured on a two-file fixture in `target/arity` with `one_check`: with the old test, three findings —
/// `forward_all(1, 2, 3)`, `forward_plain(1, 2, 3)` and the genuine `fixed_two(1, 2, 3)`; with this one, only the
/// genuine one. The fixture here deliberately calls **nothing but** variadic functions, so a single code says which —
/// the check fires, or it does not.
#[test]
fn a_parameter_pack_is_not_a_fixed_arity() {
    let declarations = "\
template <class... Args>
void forward_all(Args&&... args);

template <class... Args>
void forward_plain(Args... args);

void classic(const char* format, ...);
";
    let calls = "\
#include \"other.h\"

void use() {
    forward_all(1, 2, 3);
    forward_plain(1, 2, 3);
    classic(\"%d %d %d\", 1, 2, 3);
}
";
    let codes = codes_with_two_files(calls, declarations);

    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "every callee here takes as many arguments as it is given: {codes:?}"
    );
}

/// **A member of a template class is a member.** The census on EmmyLuaCodeStyle's `nlohmann::json` reported
/// `` `array` has no member `push_back` `` — the class is `basic_json<>`, its members are written inside a
/// `template<...> struct`, and the lookup that reads members must follow the template header to reach them.
#[test]
fn a_member_written_inside_a_template_class_is_found() {
    let source = "\
template <class T>
struct Box {
    void push(T value);
};
void g(Box<int> box) {
    box.push(1);
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "`push` is a member of the template: {:?}",
        codes_of(source)
    );
}

/// **The `nlohmann::json` shape**: a member reached through an **alias to a template instantiation**.
///
/// `using json = basic_json<int>;` and then `array.push_back(3)` — the cursor's class name is the alias, the members are
/// in the template's body, and the instantiation is the `int` that the alias supplied. This is the shape the census
/// found twice on a real project, and it is the one the simple template test above does not cover.
#[test]
fn a_member_reached_through_an_alias_to_a_template_is_found() {
    let source = "\
namespace nlohmann {
template <class T>
class basic_json {
public:
    void push_back(T value);
};
using json = basic_json<int>;
}
void g(nlohmann::json array) {
    array.push_back(3);
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "`push_back` is a member of `basic_json`, which `json` names: {:?}",
        codes_of(source)
    );
}

/// **The exact shape from `LSP.h`**: an alias to a template, a static member call, and a use inside a template
/// function — `nlohmann::json array = nlohmann::json::array(); … array.push_back(…)`.
///
/// The three pieces are each plausible on their own, which is why this test exists beside the two above: an alias to a
/// template (passing on its own), a static member used as an initialiser, and a body inside a template whose parameter
/// is `T`. The census found `push_back` missing in this shape twice, and it is the last false positive on a real
/// project.
#[test]
fn the_nlohmann_shape_keeps_its_member() {
    let source = "\
namespace nlohmann {
template <class T>
class basic_json {
public:
    using array_t = int;
    static array_t array();
    void push_back(int value);
};
using json = basic_json<int>;
}

template <class T>
nlohmann::json SerializeArray(std::vector<T>& vec) {
    nlohmann::json array = nlohmann::json::array();
    for (auto& v : vec) {
        array.push_back(1);
        (void)v;
    }
    return array;
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "`push_back` is a member of `basic_json`: {:?}",
        codes_of(source)
    );
}

/// **A base the index could read nothing from is not evidence that a member is absent.**
///
/// `struct D : Missing` gives `D` a member list that is **partial** — `Missing` contributed nothing, because it is not
/// in the index — and a member written on a `D` is then "not in the list" without being absent from the class. The
/// check must stay silent, which is what `MemberList::unlisted` is for.
///
/// Measured on a real project this is the shape of the worst report of the census: `std::cin.read(…)` was reported as
/// "`std::cin` has no member `read`" while the hover found `basic_istream::read` at once — the same index, asked two
/// ways, answering differently because this check treated "not in the part I read" as "not there".
#[test]
fn a_member_of_a_class_with_an_unread_base_is_not_reported() {
    let source = "\
struct D : Missing {
    void f();
};
void g(D d) {
    d.not_read_anywhere();
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::UndefinedField),
        "the list is partial, so the absence is not evidence: {:?}",
        codes_of(source)
    );
}

/// **A constructor with two parameters cannot be built from one value.**
///
/// `struct S { S(int, int); }; S s = 123;` does not compile. The question "can a class be built from this value" was
/// answered by scanning the parameters for one that accepts it — so the first `int` said yes and the arity was never
/// asked. This is the shape `std::string s = 123;` has in a standard library, whose `basic_string(size_type, char)` is
/// the constructor the scan used to accept.
#[test]
fn a_two_parameter_constructor_cannot_be_built_from_one_value() {
    let source = "\
struct S {
    S(int count, int other);
};
void g() {
    S s = 123;
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
        "one value cannot fill two parameters: {:?}",
        codes_of(source)
    );

    // …and one defaulted parameter is still one value.
    let defaulted = "\
struct S {
    S(int count, int other = 0);
};
void g() {
    S s = 123;
}
";
    assert!(
        !codes_of(defaulted).contains(&DiagnosticCode::AssignTypeCheck),
        "a defaulted parameter does not need a value: {:?}",
        codes_of(defaulted)
    );
}

/// **The type check a reader most wants from generics**: the argument against the **instantiated** parameter.
///
/// `push_back` on a `std::vector<int>` takes an `int`, because the class was instantiated at `int`. The member's fact
/// says `T value` — the spelling the class wrote — so a check that reads only the fact sees a parameter it cannot
/// classify and stays silent. This is the "type checking after instantiation" the reader asked for, and it is the next
/// layer of the generics work.
/// # Why this is ignored rather than passing
///
/// The fix is one seam, and it is not this file's: `members_of` is called with `written.class_name()`, which has already
/// **dropped** the template arguments (`cpp_code_analysis::completion` line 468), so the member list it builds cannot
/// substitute anything. The substitution itself exists — `sema::types::substituted_spelling`, used by the member
/// **return** type, which is why `basic_string<char>::back()` already answers `char&`. What is missing is the class's
/// parameter names and the use's arguments reaching the member facts.
///
/// The test is kept and ignored rather than deleted: it states the behaviour a reader expects, and it will pass the day
/// the seam is moved.
///
/// # What the substitution did not fix, measured after it landed
///
/// `SemanticModel::members_of` now substitutes the class's arguments into its members — `std::vector<int>::push_back`
/// reports `(int value)` rather than `(T value)`. The diagnostic still does not appear, and the reason is a **second**
/// seam: the argument checks **skip member calls deliberately** (`argument_count`'s member-access guard, added because
/// `_session.Run(…)` was being judged against a free `Run()`). So `v.push_back(…)` never reaches an arity or a type
/// comparison at all, substituted parameters or not. Making this test pass is the work of resolving a member call to the
/// member — `member_access_at` plus `members_of` — rather than of substituting anything.
#[test]
fn a_member_parameter_is_checked_after_instantiation() {
    let source = "\
namespace std {
template <class T>
class vector {
public:
    void push_back(T value);
};
}
void f() {
    std::vector<int> v;
    v.push_back(\"text\");
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::ParamTypeCheck)
            || codes_of(source).contains(&DiagnosticCode::ArgumentCount),
        "an `int` parameter does not take a string literal: {:?}",
        codes_of(source)
    );
}

/// **The other half of the rule: a member call whose argument fits is silent.**
///
/// The instantiated check above reports; this one says the report is not blanket. `push_back(1)` on a `std::vector<int>`
/// passes an `int` to an `int`, and nothing is said.
#[test]
fn a_member_call_whose_argument_fits_is_silent() {
    let source = "\
namespace std {
template <class T>
class vector {
public:
    void push_back(T value);
};
}
void f() {
    std::vector<int> v;
    v.push_back(1);
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
        "an `int` for an `int` is right: {:?}",
        codes_of(source)
    );
}

/// **A template parameter is not a missing include** — reported from an editor with a screenshot.
///
/// ```cpp
/// // db.h
/// template <class K, class V, class Container = std::unordered_map<K, V>>
/// class DBase { … private: Container _hash; };
/// ```
///
/// `Container` was reported as "declared in container.h, which this file does not include". It is the class's **own
/// parameter**: the `template <…>` header declares it. The rule asked `summary.declarations` whether the file declares
/// the name, and a template parameter is a *binding* — it is in the scope tree and in no fact list — so the candidate
/// search found some other file's `class Container` and recommended an include for it.
///
/// The second half is the rule still doing its job: a name the file really does not declare, declared elsewhere in
/// the project and not reached by an `#include`, is still reported.
#[test]
fn a_template_parameter_is_not_a_missing_include() {
    const DB_H: &str = "\
template <class K, class V, class Container>
class DBase {
public:
    V* find(const K& key);
private:
    Container _hash;
};
";
    let codes = codes_of_files(
        &[
            ("/p/container.h", "class Container {};\n"),
            ("/p/db.h", DB_H),
        ],
        "/p/db.h",
    );
    assert!(
        !codes.contains(&DiagnosticCode::MissingInclude),
        "`Container` is the class's own template parameter: {codes:?}"
    );

    // **And the same file, using a type it did not declare and does not include**, is still a finding.
    const USES_A_STRANGER: &str = "\
void f(NotHere* value) {}
";
    let codes = codes_of_files(
        &[
            ("/p/nothere.h", "class NotHere {};\n"),
            ("/p/uses.cpp", USES_A_STRANGER),
        ],
        "/p/uses.cpp",
    );
    assert!(
        codes.contains(&DiagnosticCode::MissingInclude),
        "a type the file neither declares nor includes is the rule's own case: {codes:?}"
    );
}

/// **A forward declaration in an included header satisfies the use.**
///
/// Reported from `EmmyLuaCodeStyle`, `LuaSyntaxTree.h`:
///
/// ```cpp
/// #include "LuaParser/Parse/Mark.h"    // `class LuaParser;` — a forward declaration
/// class LuaSyntaxTree {
///     void BuildTree(LuaParser &p);     // a reference needs no more than that
/// };
/// ```
///
/// The rule found `luaparser.h` (the class's *definition*, which this header does not include), ignored the forward
/// declaration the header can see through `Mark.h`, and told the reader to include `luaparser.h` — in a file that
/// compiles as written, on the most ordinary C++ idiom there is: a reference parameter and a forward declaration.
///
/// The question the rule has to ask is *"is the name declared in anything this file reaches"*, not *"is its definition
/// in a header this file includes"*. The second half of the fixture is the rule still firing when nothing declares it.
#[test]
fn a_forward_declaration_in_an_included_header_is_not_a_missing_include() {
    let codes = codes_of_files(
        &[
            ("/p/mark.h", "class Parser;\n"),
            (
                "/p/tree.h",
                "#include \"mark.h\"\nstruct Tree {\n    void Build(Parser& p);\n};\n",
            ),
            (
                "/p/parser.h",
                "class Parser {\npublic:\n    int Parse();\n};\n",
            ),
        ],
        "/p/tree.h",
    );
    assert!(
        !codes.contains(&DiagnosticCode::MissingInclude),
        "the forward declaration in mark.h is what the reference needs: {codes:?}"
    );

    // **And nothing declares it** — the rule's own case: a class that exists in the project, in a header this file
    // neither includes nor forward-declares.
    let codes = codes_of_files(
        &[
            (
                "/p/tree.h",
                "struct Tree {\n    void Build(Parser& p);\n};\n",
            ),
            (
                "/p/parser.h",
                "class Parser {\npublic:\n    int Parse();\n};\n",
            ),
        ],
        "/p/tree.h",
    );
    assert!(
        codes.contains(&DiagnosticCode::MissingInclude),
        "nothing in this file reaches `Parser`: {codes:?}"
    );
}

/// **The codes a file produces in a project of several files** — the shape a header has and a one-file fixture cannot.
///
/// The defect this exists for needed three things a single-file fixture cannot express: the class in a **header**,
/// an `#include` **above** the class in that header (which shifts every offset of its rendering), and the call in a
/// `.cpp`. Each of the three was a seam the member path crossed, and a fixture with none of them passed while every
/// real `std::vector<int>::push_back("text")` was silent.
fn codes_of_files(files: &[(&str, &str)], asking: &str) -> Vec<DiagnosticCode> {
    let mut memory = MemoryFiles::new();
    for (path, text) in files {
        memory = memory.with_file(*path, *text);
    }
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    let paths: Vec<std::path::PathBuf> = files
        .iter()
        .map(|(path, _)| std::path::PathBuf::from(path))
        .collect();
    session.add_project_files(paths);
    session.want_cooked_reading(std::path::Path::new(asking));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new(asking))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| finding.code)
                .chain(found.errors.iter().map(|error| error.code))
                .collect()
        })
        .unwrap_or_default()
}

/// **The signature the standard library actually writes**: a `const _Ty&` parameter, twice over, in a header.
///
/// Reported from an editor: `anotherVec.push_back("123131")` on a `std::vector<int>` produced **nothing**, and the
/// library is not a corner case — `push_back` is declared `void push_back(const _Ty&)` and `void push_back(_Ty&&)`
/// in every implementation, so "one member of that name or nothing is said" was silence on nearly every member
/// call there is. Three defects had to be fixed before this line reported, and each is the fixture:
///
/// ```text
/// the substitution read the rendering with a file's offset   the header's own `#include` above the class shifted
///                                                           it, no template header was found, `T` stayed `T`
/// two candidates meant "say nothing"                        `push_back` is written twice in every implementation
/// a reference target had no arm in the conversion relation   `const int&` was neither `int` nor a pointer
/// ```
///
/// The by-value negative is the second half: an `int` for an `int` is right, whichever candidate takes it.
#[test]
fn a_member_argument_is_checked_through_a_header_and_against_every_overload() {
    let header = "\
#pragma once
#include <cstddef>
template <class T>
struct Box {
    void push_back(const T& value);
    void push_back(T&& value);
    T& front();
};
";
    let file = "\
#include \"box.h\"
void f() {
    Box<int> b;
    b.push_back(\"text\");
}
";
    let codes = codes_of_files(&[("/p/box.h", header), ("/p/a.cpp", file)], "/p/a.cpp");
    assert!(
        codes.contains(&DiagnosticCode::ParamTypeCheck),
        "a string literal for a `const int&` parameter is not right: {codes:?}"
    );

    let fits = file.replace("b.push_back(\"text\");", "b.push_back(1);");
    let codes = codes_of_files(&[("/p/box.h", header), ("/p/a.cpp", &fits)], "/p/a.cpp");
    assert!(
        !codes.contains(&DiagnosticCode::ParamTypeCheck),
        "an `int` for an `int` is right: {codes:?}"
    );
}

/// **A default argument is written in the header and never repeated in the source**, so a call must be judged
/// against the declaration that carries it.
///
/// Reported from `EmmyLuaCodeStyle`: `void LuaExpectedError(std::string_view message, LuaTokenKind expectedToken = 0);`
/// in `LuaParser.h`, and `void LuaParser::LuaExpectedError(std::string_view message, LuaTokenKind expectedToken)` in
/// `LuaParser.cpp` — a definition may not repeat the default, so the definition alone says two arguments are required
/// and **eight** calls were underlined as "needs 2 argument(s) and this call passes fewer".
///
/// The rule this asserts is the language's: a call is legal if *any* declaration of that signature can take it.
#[test]
fn a_default_argument_written_in_the_header_is_not_a_missing_argument() {
    let header = "\
void report(int a, int b = 0);
int twice(int a, int b = 1);
";
    let source = "\
#include \"api.h\"
void report(int a, int b) { (void)a; (void)b; }
int twice(int a, int b) { return a * b; }
void use() {
    report(1);
    report(1, 2);
    (void)twice(2);
}
";
    let codes = codes_of_files(&[("/p/api.h", header), ("/p/a.cpp", source)], "/p/a.cpp");
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "both parameters are defaulted in the header: {codes:?}"
    );

    // **And the rule still fires when nothing is defaulted** — a fix that silenced the check would pass the half above.
    let strict = "\
#include \"api.h\"
void only(int a, int b);
void report(int a, int b) { (void)a; (void)b; }
int twice(int a, int b) { return a * b; }
void use() { only(1); }
";
    let header_with_only = format!("{header}void only(int a, int b);\n");
    let codes = codes_of_files(
        &[("/p/api.h", &header_with_only), ("/p/a.cpp", strict)],
        "/p/a.cpp",
    );
    assert!(
        codes.contains(&DiagnosticCode::ArgumentCount),
        "`only` has no defaulted parameter: {codes:?}"
    );
}

/// **One candidate that takes the argument keeps the check silent** — the rule an overload set is judged by.
/// `resize(int)` and `resize(const char*)` are both `resize`, and `w.resize("wide")` is the second one: a check
/// that reported "this passes a string where an `int` is declared" would be underlining a correct line, which is
/// the failure mode this whole layer exists to avoid. So a finding needs **every** candidate to disagree — and the
/// other half is here too: when they all do, it is still reported.
#[test]
fn an_overload_that_takes_the_argument_keeps_the_check_silent() {
    let one_fits = "\
struct Widget {
    void resize(int width);
    void resize(const char* text);
};
void f() {
    Widget w;
    w.resize(\"wide\");
}
";
    assert!(
        !codes_of(one_fits).contains(&DiagnosticCode::ParamTypeCheck),
        "the second overload takes a string literal: {:?}",
        codes_of(one_fits)
    );

    let none_fit = "\
struct Widget {
    void resize(int width);
    void resize(double width);
};
void f() {
    Widget w;
    w.resize(\"wide\");
}
";
    assert!(
        codes_of(none_fit).contains(&DiagnosticCode::ParamTypeCheck),
        "neither overload takes a string literal, so this is a finding: {:?}",
        codes_of(none_fit)
    );
}

/// **A non-template class's member is checked the same way** — the substitution is not what makes the check work, it is
/// what makes it *correct* for a template; the plain case has to work on its own.
#[test]
fn a_member_call_on_a_plain_class_is_checked() {
    let source = "\
struct Widget {
    void resize(int width);
};
void f() {
    Widget w;
    w.resize(\"wide\");
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
        "a string literal for an `int` is not right: {:?}",
        codes_of(source)
    );
}

/// **Too many arguments to a member** is the arity rule, through the same resolution.
#[test]
fn a_member_call_with_too_many_arguments_is_a_different_finding() {
    let source = "\
struct Widget {
    void resize(int width);
};
void f() {
    Widget w;
    w.resize(1, 2);
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::ArgumentCount),
        "one parameter, two arguments: {:?}",
        codes_of(source)
    );
}

/// **A free function is still checked** — the member path was added beside the old one, not instead of it.
#[test]
fn a_free_function_call_is_still_checked() {
    // **A definition**, not a declaration: this check's table is built from this file's function definitions (its
    // module documentation says so), which is exactly the rule that made a class *member* invisible to it.
    let source = "\
void resize(int) { }
void f() {
    resize(\"wide\");
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
        "the free path is unchanged: {:?}",
        codes_of(source)
    );
}

/// **A named parameter is not checked, and that is a gap rather than a rule.**
///
/// `parameter_spellings_of` returns the parameter as the file wrote it — `int width` — and `parse_type_spelling` reads a
/// *type*, so the comparison sees a spelling it cannot parse and says nothing. Measured: the same call is reported when
/// the parameter is unnamed (`void resize(int)`) and silent when it is named, which is the shape every real codebase
/// writes. `sema::overload::parameters_in` already strips the name (`a_type_without_its_name`), so the fix is to read the
/// spellings through it — recorded here rather than asserted, because changing it makes this check fire on code it has
/// never judged before, which is a census to run first.
#[test]
fn a_named_parameter_is_checked_too() {
    let source = "\
void resize(int width) { }
void f() {
    resize(\"wide\");
}
";
    assert!(
        codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
        "the name is not part of the type: {:?}",
        codes_of(source)
    );
}

/// **An assignment whose result is compared is the idiom**, and the census found the one place this rule got it wrong.
///
/// `if ((op = queue.front()) != 0)` is deliberate: the assignment is parenthesised and the *comparison* is the condition.
/// The rule now reads the condition's own operator, so a comparison at depth zero inside the parentheses keeps it quiet —
/// while `if (x = 1)` still reports, and so does `if (x = a < b)`, whose `<` is inside the assignment.
#[test]
fn an_assignment_compared_against_something_is_quiet() {
    let idiom = "struct Q { int value() const; };\n\
                 void f(Q q) {\n    int op = 0;\n    if ((op = q.value()) != 0) { return; }\n}\n";
    assert!(
        !codes_of(idiom).contains(&DiagnosticCode::AssignmentInCondition),
        "a compared assignment is the shape the rule allows: {:?}",
        codes_of(idiom)
    );

    for reported in [
        // The mistake the rule exists for.
        "void f() {\n    int x = 0;\n    if (x = 1) { return; }\n}\n",
        // A comparison inside the assignment's right-hand side does not hide it: the condition's operator is still `=`.
        "void f() {\n    int x = 0; int a = 0; int b = 0;\n    if (x = a < b) { return; }\n}\n",
    ] {
        assert!(
            codes_of(reported).contains(&DiagnosticCode::AssignmentInCondition),
            "{reported}: {:?}",
            codes_of(reported)
        );
    }
}

/// **`0` is the null pointer constant**, and it converts to a class that takes a pointer — the shape the census found as the
/// only one its `assign-type-check` examples shared.
///
/// `P p = 0;` where `P` has `P(int*)` is valid C++: `0` is a null pointer constant. The conversion relation cannot see the
/// constructor, so it answered `Unknown`, and the class case answered "cannot be built from an `int`" — both true of an
/// `int` and both wrong of the **literal**. (The negative side — a value that is not `0` is still checked — is covered by
/// the existing cases in this file; the claim here is only the one this fix makes.)
#[test]
fn zero_is_a_null_pointer_constant() {
    let source = "\
struct P {
    P(int* pointer);
};
void f() {
    P p = 0;
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
        "`0` is the null pointer constant: {:?}",
        codes_of(source)
    );
}
/// **A member of a class template is checked with `T` substituted, through the class's own alias.**
///
/// Reported from an editor: `std::vector<int> anotherVec; anotherVec.push_back("123131");` was not reported, while
/// the same mistake through a plain function was. The declaration is libstdc++'s
/// `void push_back(const _Tp& __x);` with `using value_type = _Tp;` in the class — so the parameter is an
/// alias of an alias of the template parameter, and the check has to follow both before it can say the argument is
/// a `const char[7]` where a `const int&` is wanted.
#[test]
fn a_member_of_a_class_template_is_checked_after_substitution() {
    let header = "\
namespace std {
template <class _Tp>
class vector {
public:
    using value_type = _Tp;
    void push_back(const value_type& __x);
};
}
";
    let source = "\
#include \"vector.h\"
int main()
{
    std::vector<int> anotherVec;
    anotherVec.push_back(\"123131\");
    return 0;
}
";
    let codes = codes_of_files(&[("/p/vector.h", header), ("/p/a.cpp", source)], "/p/a.cpp");
    {
        // PROBE: what the member list says the parameters are.
        let files = MemoryFiles::new()
            .with_file("/p/vector.h", header)
            .with_file("/p/a.cpp", source);
        let providers = SessionFiles::new(OpenDocuments::new(), files);
        let mut session = Session::with_config(
            "/p",
            providers,
            WatchFilter::new("/p"),
            CompilerConfig::default(),
        );
        session.add_project_files([
            std::path::PathBuf::from("/p/vector.h"),
            std::path::PathBuf::from("/p/a.cpp"),
        ]);
        session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
        session.want_cooked_reading(std::path::Path::new("/p/vector.h"));
        session.index_everything();
        let view = session.view("/p/a.cpp").expect("held");
        match session.members_of(&view, "std::vector<int>") {
            cpp_code_analysis::Known::Yes(list) => {
                for member in &list.members {
                    eprintln!(
                        "PROBE {:?} kind {:?} params {:?} type_of {:?}",
                        member.fact.name,
                        member.fact.kind,
                        member.fact.parameter_list(),
                        member.fact.type_of
                    );
                }
            }
            other => eprintln!("PROBE members_of: {other:?}"),
        }
    }
    assert!(
        codes.contains(&DiagnosticCode::ParamTypeCheck),
        "the argument is a string literal and the parameter is `const int&`: {codes:?}"
    );
}

/// **The alias step is what libstdc++ actually writes, and it is the half that does not work yet.** Ignored rather
/// than deleted: it is the shape of the report (`std::vector<int>::push_back("…")`), and it will pass the day
/// `members_of` substitutes the class's arguments into a member's **parameter list** as well as into its type —
/// today `value_type` is still a name to `convertible_to`, which answers `Unknown`, and a check that cannot compare
/// says nothing.
#[test]
fn a_member_parameter_written_with_the_class_alias_is_checked() {
    let header = "\
namespace std {
template <class _Tp>
class vector {
public:
    using value_type = _Tp;
    void push_back(const value_type& __x);
};
}
";
    let source = "\
#include \"vector.h\"
int main()
{
    std::vector<int> anotherVec;
    anotherVec.push_back(\"123131\");
    return 0;
}
";
    let file = "/p/vector.h";
    let caller = "/p/a.cpp";
    let mut memory = MemoryFiles::new()
        .with_file(file, header)
        .with_file(caller, source);
    let providers = SessionFiles::new(OpenDocuments::new(), memory.clone());
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from(file),
        std::path::PathBuf::from(caller),
    ]);
    // **Both files are cooked**, which is the state a check runs in: the open file's closure is read and rendered
    // before a diagnostic is asked for. `codes_of_files` asks for the *caller* only, and the substitution needs the
    // class's own file — see `substituted_members`, whose first step is reading the declaring file.
    session.want_cooked_reading(std::path::Path::new(file));
    session.want_cooked_reading(std::path::Path::new(caller));
    session.index_everything();

    let codes: Vec<DiagnosticCode> = session
        .diagnostics(std::path::Path::new(caller))
        .map(|found| found.checks.iter().map(|finding| finding.code).collect())
        .unwrap_or_default();
    let _ = &mut memory;

    assert!(
        codes.contains(&DiagnosticCode::ParamTypeCheck),
        "the argument is a string literal and the parameter is `const value_type&` = `const int&`: {codes:?}"
    );
}

/// **The shape from a real session**: `writeMessage(const std::string& json)` called with `123131`.
///
/// `int` does not convert to `const std::string&`, and a compiler refuses it. The check is silent, which is the "has the
/// form of a check but does not work" the reader reported — and the reason is the class case: the conversion relation
/// answers `Unknown` for a class target (it lives in the type algebra and never sees a constructor), and the class case only
/// speaks when it is **sure** the value cannot build the class.
///
/// # Where it stands
///
/// Three real holes were found and closed on the way, each by printing the step rather than guessing:
///
/// ```text
/// ① the parameter `const std::string&` parses to `Reference { to: Named("std::string") }`, and `class_name()` answers
///    `None` for a reference — so the index was never asked. The check now strips `const`/`&` before asking.
/// ② `param-type-check` only looked at this file's function *definitions*, so a function **declared** in a header and called
///    here was skipped entirely. It now falls back to the summary, then the index.
/// ③ measured last: `a_class_can_be_built_from("std::string", int)` answers **`Some(true)`** for a class whose only
///    constructor is `string(const char*)` — a `const char*` parameter cannot take an `int`. The next step is
///    `parameters_that_could_accept("(const char* text)", int)`, which is where that `true` comes from.
/// ```
#[test]
fn an_int_does_not_convert_to_a_string() {
    let source = "\
namespace std {
class string {
public:
    string(const char* text);
};
}
void writeMessage(const std::string& json);
void f() {
    writeMessage(123131);
}
";
    let found = codes_of(source);
    println!("codes: {found:?}");
    assert!(
        found.contains(&DiagnosticCode::ParamTypeCheck),
        "an `int` is not a `std::string`: {found:?}"
    );
}

/// **中文诊断** —— 一条检查消息跟着 `set_locale` 走,而不是跟着编辑器走。
///
/// 这张表最容易出的错是 key 和英文模板**差一个字符**:那样 `t!` 会安静地返回英文,看起来像"翻译没生效"。
/// 所以这条测试不检查"有没有翻译文件",而是直接看一条真的诊断在两种 locale 下的文字。
/// **中文诊断** —— 一条检查消息跟着 `set_locale` 走,而不是跟着编辑器走。
///
/// 这张表最容易出的错是 key 和英文模板**差一个字符**:那样 `t!` 会安静地返回英文,看起来像"翻译没生效"。
/// 所以这条测试不看"有没有翻译文件",而是直接看一条真的诊断在两种 locale 下的文字。
#[test]
fn a_diagnostic_follows_the_locale() {
    let source = "int f() { int unused_local = 1; return 0; }\n";

    let messages = |locale: &str| {
        cpp_parser::set_locale(locale);
        let files = MemoryFiles::new().with_file("/p/a.cpp", source);
        let providers = SessionFiles::new(OpenDocuments::new(), files);
        let mut session = Session::with_config(
            "/p",
            providers,
            WatchFilter::new("/p"),
            CompilerConfig::default(),
        );
        session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
        session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
        session.index_everything();
        session
            .diagnostics(std::path::Path::new("/p/a.cpp"))
            .map(|found| {
                found
                    .checks
                    .iter()
                    .map(|finding| finding.message.clone())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default()
    };

    let english = messages("en");
    let chinese = messages("zh-CN");
    cpp_parser::set_locale("en");

    println!("en: {english:?}\nzh: {chinese:?}");
    let unused = |list: &[String]| {
        list.iter()
            .find(|message| message.contains("unused_local"))
            .cloned()
            .unwrap_or_else(|| panic!("the unused check reports it: {list:?}"))
    };

    assert!(
        unused(&english).contains("never used"),
        "{:?}",
        unused(&english)
    );
    assert!(
        unused(&chinese).contains("从未使用"),
        "the message is translated: {:?}",
        unused(&chinese)
    );
}
/// **`concept-not-satisfied`** —— 实参的类型不满足形参上的概念。
///
/// 能判定的是"类型概念"这一族(`std::integral`、`std::floating_point`、`std::same_as`、`std::convertible_to`),
/// 因为它们的含义只是类型的一个性质;用户自己写的概念、`requires` 子句、类型未知的情形一律**沉默** ——
/// 一个诊断是一个断言,不是猜。
#[test]
fn an_argument_that_does_not_satisfy_its_concept_is_reported() {
    let source = "\
template <std::integral T>
T twice(T value) { return value + value; }

int f() {
    twice(2);
    twice(\"text\");
    return 0;
}
";
    let messages = messages_of(source);
    println!("{messages:?}");
    let finding = messages
        .iter()
        .find(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
        .unwrap_or_else(|| panic!("the `const char*` call is reported: {messages:?}"));
    assert!(finding.1.contains("std::integral"), "{finding:?}");
    assert!(
        finding.1.contains("char"),
        "the message names the type that was passed: {finding:?}"
    );
    assert_eq!(
        messages
            .iter()
            .filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
            .count(),
        1,
        "`twice(2)` satisfies it and is silent: {messages:?}"
    );
}

/// **A base clause is a spelling, and the class it names is `B`** — `std::derived_from<std::vector<int>>` asks about a
/// type, `class D : public std::vector<int>` writes the base with its arguments, and the question is whether the class's own
/// name is the one asked for.
///
/// The old reading took the last whitespace-separated word of the base's spelling — `Base>` from
/// `conditional_t<true, X, Base>` — and then looked up a class with that name; a plain `std::vector<int>` base was compared
/// whole against `vector` and never matched. Both directions are silence-or-report on a name, so the fixture below asks the
/// two questions that separate them: a class that derives from the named template is **not** reported, and one that does not
/// is.
#[test]
fn a_templated_base_is_compared_by_the_class_it_names() {
    let derives = "\
template <std::derived_from<std::vector<int>> T>
void take(T value);

struct Derived : public std::vector<int> {};

int f() {
    Derived d;
    take(d);
    return 0;
}
";
    let messages = messages_of(derives);
    assert!(
        !messages
            .iter()
            .any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
        "`Derived` derives from `std::vector<int>`: {messages:?}"
    );

    let does_not = "\
template <std::derived_from<std::vector<int>> T>
void take(T value);

struct Plain {};

int f() {
    Plain p;
    take(p);
    return 0;
}
";
    let messages = messages_of(does_not);
    assert!(
        messages
            .iter()
            .any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
        "`Plain` derives from nothing: {messages:?}"
    );
}

/// **A concept the analysis cannot decide is silence**, not a guess: `requires` clauses and user-written concepts
/// are exactly the cases where a finding would be the check's opinion rather than the language's.
#[test]
fn an_undecidable_concept_says_nothing() {
    let source = "\
template <class T>
concept Small = sizeof(T) <= 4;

template <Small T>
T keep(T value) { return value; }

int f() {
    keep(1.0);
    return 0;
}
";
    let messages = messages_of(source);
    assert!(
        !messages
            .iter()
            .any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
        "{messages:?}"
    );
}

/// The codes and messages a fixture produces.
fn messages_of(source: &str) -> Vec<(DiagnosticCode, String)> {
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| (finding.code, finding.message.clone()))
                .collect()
        })
        .unwrap_or_default()
}

/// **`.cppls.toml` 的 `[diagnostics] disable` 真的关掉一条规则,`enable` 只打开点名的那些。**
///
/// 这套机制之前在类型上就有(`CheckConfig`),但没有人把它接进一次真正运行的检查 —— 一个用户相信已经关掉的规则
/// 仍然在报,是这套配置最坏的失败方式,所以两个方向都要测。
#[test]
fn the_project_config_turns_rules_off_and_on() {
    let source = "int f() { int unused_local = 1; return 0; }\n";

    let messages_with = |config: &str| {
        let files = MemoryFiles::new()
            .with_file("/p/a.cpp", source)
            .with_file("/p/.cppls.toml", config);
        let providers = SessionFiles::new(OpenDocuments::new(), files);
        let mut session = Session::with_config(
            "/p",
            providers,
            WatchFilter::new("/p"),
            CompilerConfig::default(),
        );
        session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
        session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
        session.index_everything();
        session
            .diagnostics(std::path::Path::new("/p/a.cpp"))
            .map(|found| {
                found
                    .checks
                    .iter()
                    .map(|finding| finding.code)
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default()
    };

    // Default: the unused local is reported.
    assert!(
        messages_with("").contains(&DiagnosticCode::Unused),
        "the rule is on by default"
    );

    // `disable`: it is not.
    let disabled = messages_with("[diagnostics]\ndisable = [\"unused\"]\n");
    assert!(
        !disabled.contains(&DiagnosticCode::Unused),
        "`disable` turns it off: {disabled:?}"
    );

    // `enable` naming one rule: only that one may report.
    let only = messages_with("[diagnostics]\nenable = [\"param-type-check\"]\n");
    assert!(
        !only.contains(&DiagnosticCode::Unused),
        "`enable` is `only these`: {only:?}"
    );
}

/// **`std::derived_from` 走索引里的基类**,`std::copyable` 这类"对象概念"只在实参是**引用**时才给答案。
#[test]
fn a_concept_over_the_class_hierarchy_and_over_objectness() {
    let hierarchy = "\
struct Base { virtual ~Base(); };
struct Derived : public Base { };

template <std::derived_from<Base> T>
void handle(T& value);

void f(Derived d, int n) {
    handle(d);
    handle(n);
}
";
    let messages = messages_of(hierarchy);
    println!("{messages:?}");
    let concept_findings: Vec<&(DiagnosticCode, String)> = messages
        .iter()
        .filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
        .collect();
    assert_eq!(
        concept_findings.len(),
        1,
        "`handle(n)` is not derived from `Base`: {messages:?}"
    );
    assert!(
        concept_findings[0].1.contains("derived_from"),
        "{concept_findings:?}"
    );

    // **An object concept against a reference.** `copyable<int&>` is false because the concept asks for an object
    // type; `copyable<int>` is not this layer's question (it needs the constructors), so only the reference reports.
    let objectness = "\
template <std::copyable T>
T copy_of(T value) { return value; }

int f(int n) {
    copy_of(n);
    return 0;
}
";
    let messages = messages_of(objectness);
    println!("{messages:?}");
    assert!(
        !messages
            .iter()
            .any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
        "`int` is copyable and the check must not guess about a class: {messages:?}"
    );
}

/// **声明在头文件里的约束,从调用处的源文件也能查出来** —— 走 summary 里的
/// `DeclFact::parameters` / `DeclFact::constraints` / `parameter_list`。
#[test]
fn a_constraint_declared_in_a_header_is_checked_at_the_call() {
    let header = "\
#pragma once
struct Base { virtual ~Base(); };
struct Derived : public Base { };

template <std::derived_from<Base> T>
void handle(T& value);
";
    let source = "\
#include \"b.h\"
void f(Derived d, int n) {
    handle(d);
    handle(n);
}
";
    let files = MemoryFiles::new()
        .with_file("/p/b.h", header)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/b.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();

    let messages: Vec<(DiagnosticCode, String)> = session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| (finding.code, finding.message.clone()))
                .collect()
        })
        .unwrap_or_default();
    println!("{messages:?}");

    let concept_findings: Vec<&(DiagnosticCode, String)> = messages
        .iter()
        .filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
        .collect();
    assert_eq!(
        concept_findings.len(),
        1,
        "`handle(n)` is reported from the header's constraint: {messages:?}"
    );
    assert!(
        concept_findings[0].1.contains("derived_from"),
        "{concept_findings:?}"
    );
}

/// **The codes one file produces, with the project's own language standard** — the `[compile] standard` / `-std=`
/// path a `.cppls.toml` takes.
fn codes_of_with(source: &str, path: &str, standard: Option<&str>) -> Vec<DiagnosticCode> {
    let files = MemoryFiles::new().with_file(path, source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let config = CompilerConfig {
        standard: standard.map(|standard| standard.into()),
        ..CompilerConfig::default()
    };
    let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
    session.add_project_files([std::path::PathBuf::from(path)]);
    session.want_cooked_reading(std::path::Path::new(path));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new(path))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| finding.code)
                .chain(found.errors.iter().map(|error| error.code))
                .collect()
        })
        .unwrap_or_default()
}

/// **A C project is not told to write named casts** — the language has to come from the project's own `-std=`.
///
/// `cstyle_cast` asks `CheckContext::is_c()` before it fires, and its own note says why: a C program has no
/// `static_cast`, so `(Widget*)p` is how it writes that conversion and a rule that called it a mistake would be wrong
/// about the language. The question was asked, but the answer was always "not told": `CompilerConfig::language_for`
/// read the file's compile command and `extra_args`, while a project stating `-std=gnu11` in `.cppls.toml` lands in
/// the config's **`standard`** field — which it never looked at.
///
/// Measured through the language server on neovim's `arglist.c` (a C file, `.cppls.toml` with
/// `args = ["-std=gnu11"]`): **14 `cstyle-cast` findings**, every one of them telling a C program to write
/// `static_cast<int>`. So this test states the language the way a project does and asks for the findings both ways.
#[test]
fn a_c_project_is_not_told_to_write_named_casts() {
    const SOURCE: &str = "\
typedef struct { int v; } T;
int f(void) { double d = 1.5; T t; t.v = (int)d; return t.v; }
";
    let in_c = codes_of_with(SOURCE, "/p/a.c", Some("gnu11"));
    assert!(
        !in_c.contains(&DiagnosticCode::CStyleCast),
        "a C program has no named casts, so the rule is not about it: {in_c:?}"
    );

    // **And the rule is not simply off**: the same cast in a file compiled as C++ is reported, which is what says
    // this test is about the language rather than about the check having stopped working.
    let tmp = codes_of_with(SOURCE, "/p/a.cpp", Some("gnu++17"));
    assert!(
        tmp.contains(&DiagnosticCode::CStyleCast),
        "the same cast in C++ is the rule's own case: {tmp:?}"
    );
}

/// **A call that passes a cast argument has not passed fewer.** `three((int)x, 2, 3)` is three arguments — see
/// `cpp_parser`'s `a_cast_argument_is_counted` for the root cause (a `CastExpr` was not a `CppExpr`, so the argument
/// accessor dropped it). Measured on neovim's `arglist.c`: `do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx ==
/// CMD_drop)` was "needs 3 argument(s) and this call passes fewer".
#[test]
fn a_cast_argument_is_not_a_missing_argument() {
    const SOURCE: &str = "\
static void three(int a, int b, int c) { (void)a; (void)b; (void)c; }
void one(int x) { three((int)x, 2, 3); }
void two(int x) { three((int)x, 2, x == 0); }
";
    let codes = codes_of_with(SOURCE, "/p/a.c", Some("gnu11"));
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "every call here passes three arguments: {codes:?}"
    );

    // **And a real count is still reported**, so this is not the check having gone quiet.
    let wrong = "static void two_args(int a, int b) { (void)a; (void)b; }\nvoid f(int x) { two_args((int)x, 2, 3); }\n";
    assert!(
        codes_of_with(wrong, "/p/a.c", Some("gnu11")).contains(&DiagnosticCode::ArgumentCount),
        "three arguments for two parameters is the rule's own case"
    );
}

/// **A C-style cast is not a rule about C.** Reported from an editor with a screenshot: `(unsigned)c` inside vim's
/// `charset.c` — a binary search over a character array — was underlined as "a C-style cast", with the advice to
/// write `static_cast`, which C does not have.
///
/// The rule already refused to fire on C (`CheckContext::is_c`), so the defect was one layer down: the **language of
/// the file** was unknown. That project has no compile database entry, no `[compile] standard` and no `-std=`, so
/// `LanguageConfig::permissive` answered "both families", `family()` was `None`, and `is_c()` was false — an
/// unconfigured project was read as C++ by every C++-only rule.
///
/// A `.c` file is C: that is what every compiler decides by, and what the editor decided when it opened the file, so
/// `CompilerConfig::language_for` now falls back to the extension before it falls back to "both".
#[test]
fn a_c_style_cast_is_reported_in_cpp_and_not_in_c() {
    let source = "int f(double c) { return (unsigned)c; }\n";

    assert!(
        codes_of_a_file("/p/a.cpp", source).contains(&DiagnosticCode::CStyleCast),
        "the fixture must produce the finding where the rule applies"
    );

    assert!(
        !codes_of_a_file("/p/a.c", source).contains(&DiagnosticCode::CStyleCast),
        "…and not in a `.c` file, where `(unsigned)c` is how the conversion is written"
    );
}

/// **A class nested in another one has members, and its own members are not "undefined".**
///
/// `class outer { public: class inner { inner(bool e) : at_end_(e) {} bool operator!=(const inner &other) const
/// { return at_end_ != other.at_end_; } private: bool at_end_ = true; }; };` — the class is `outer::inner`, and
/// every use inside `outer` spells it `inner`. The member list for that spelling came back **empty**, so
/// `undefined-field` reported `` `other` has no member `at_end_` `` on a class that declares it, while the class's
/// own field was invisible to completion too: `definition("inner")` was ambiguous between the class (scope `outer`)
/// and its **constructor** (a declaration named `inner` in scope `outer::inner`), and an ambiguous class was read as
/// "that class has nothing written in it". Measured on `test_cpp/coroutine.cpp`, whose `generator<T>::iterator` is
/// this shape: two false findings from one lookup.
#[test]
fn a_nested_class_has_its_members() {
    let nested = "\
class outer {
  public:
    class inner {
      public:
        inner(bool e) : at_end_(e) {}
        bool operator!=(const inner &other) const { return at_end_ != other.at_end_; }
      private:
        bool at_end_ = true;
    };
};
";
    assert_eq!(
        codes_of(nested),
        [],
        "a member written in the class is not undefined: {:?}",
        codes_of(nested)
    );

    // …and the rule still speaks when a member really is not there: the fix must not silence the check.
    let missing = "\
class outer {
  public:
    class inner {
      public:
        int at_end_ = 0;
    };
};
void f() { outer::inner i; i.missing_; }
";
    assert_eq!(
        codes_of(missing),
        [DiagnosticCode::UndefinedField],
        "a member the nested class does not declare is still reported"
    );
}

/// **A coroutine is not a function that forgot to return.**
///
/// A body that writes `co_yield`, `co_return` or `co_await` is a coroutine, and the value contract lives on
/// `promise_type` (`return_void`, `return_value`, `yield_value`) — so a `generator<int>` that only yields is
/// complete. Measured on `test_cpp/coroutine.cpp`: `generator<int> countdown(int from) { for (…) { co_yield i; } }`
/// answered "this function is declared to return `generator<int>` and its body has no `return`", on a file that
/// compiles and runs in GCC 15.1.
#[test]
fn a_coroutine_body_has_no_missing_return() {
    for (name, source) in [
        (
            "co_yield",
            "generator make(int from) {\n    for (int i = 0; i < from; ++i) { co_yield i; }\n}\n",
        ),
        (
            "co_return",
            "int compute(int v) {\n    co_return v + 1;\n}\n",
        ),
        (
            "co_await",
            "int wait(int v) {\n    int x = co_await v;\n    return x;\n}\n",
        ),
    ] {
        assert_eq!(
            codes_of(source),
            [],
            "{name}: a coroutine body needs no `return`"
        );
    }

    // The rule itself is unchanged for an ordinary function.
    assert_eq!(
        codes_of("int count() {\n}\n"),
        [DiagnosticCode::MissingReturn],
        "a plain function with no return is still reported"
    );
}

/// **A name used as an object, where nothing declares it.**
///
/// `missing.size()` is the shape a reader writes while thinking of a variable they have not declared — or have just
/// renamed — and until this rule existed the editor said nothing at all: `undefined-field` needs the receiver's *type*,
/// and a name with no declaration has none. Measured on `test_cpp/main.cpp`, whose `myName.getFullName(0)` is declared
/// ten lines below the use and was silently accepted.
#[test]
fn a_name_that_nothing_declares_is_reported() {
    let source = "\
struct Widget { int size; };
void f() {
    missing.size;
}
";
    assert_eq!(
        codes_of(source),
        [DiagnosticCode::UndefinedName],
        "nothing declares `missing`"
    );
}

/// **The same access, on a name that is declared, is not this rule's business** — and a name declared later in the
/// same file is not visible yet, which is the language's own rule rather than an inference.
#[test]
fn a_declared_name_is_not_reported_and_a_later_one_is() {
    let declared = "\
struct Widget { int size; };
void f() {
    Widget w;
    w.size;
}
";
    assert_eq!(codes_of(declared), [], "`w` is declared two lines up");

    let later = "\
struct Widget { int size; };
void f() {
    w.size;
}
Widget w;
";
    assert_eq!(
        codes_of(later),
        [DiagnosticCode::UndefinedName],
        "`w` is declared after the use, so it is not visible there"
    );
}

/// **The four silences the rule is written around**: a macro, a template body, a lambda body, and a header.
#[test]
fn the_rule_is_quiet_where_a_name_may_be_declared_elsewhere() {
    // A macro whose expansion is a declared name: the rendering makes the receiver `w`, which resolves.
    let macro_defined = "\
struct Widget { int size; };
#define receiver w
void f() {
    Widget w;
    receiver.size;
}
";
    assert_eq!(codes_of(macro_defined), []);

    // A template body is dependent: `count` may come from a base that exists only at instantiation.
    let templated = "\
template <class T>
struct Derived : T {
    void f() { count.size; }
};
";
    assert_eq!(codes_of(templated), [], "a template body is not judged");

    // A lambda's capture is a declaration the scope tree does not bind.
    let lambda = "\
struct Widget { int size; };
void f() {
    Widget w;
    auto g = [&w]() { w.size; };
}
";
    assert_eq!(
        codes_of(lambda),
        [],
        "a capture is not a name the scope tree holds"
    );

    // A name a header declares — here the header is the second file of the fixture.
    let from_a_header = "\
#include \"b.h\"
void f() {
    from_header.size;
}
";
    let header = "\
struct Widget { int size; };
extern Widget from_header;
";
    let codes: Vec<DiagnosticCode> = codes_of_a_two_file_fixture(from_a_header, header);
    assert_eq!(codes, [], "`from_header` is declared in the header");
}

/// [`codes_of`] for a fixture that needs a header beside its source.
fn codes_of_a_two_file_fixture(source: &str, header: &str) -> Vec<DiagnosticCode> {
    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", source)
        .with_file("/p/b.h", header);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/b.h"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.want_cooked_reading(std::path::Path::new("/p/b.h"));
    session.index_everything();
    session
        .diagnostics(std::path::Path::new("/p/a.cpp"))
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| finding.code)
                .chain(found.errors.iter().map(|error| error.code))
                .collect()
        })
        .unwrap_or_default()
}

/// **A call to a name nothing declares**, and the one argument shape that keeps the rule quiet.
///
/// ```cpp
/// void f() { printh("x", 12); }     // nothing declares `printh`
/// ```
///
/// Measured on `test_cpp/main.cpp`: `printh("1231313", 12)` on line 74, with `void printh(…)` defined on line 83 — a
/// call a compiler rejects and this server accepted. The extra guard a *receiver* does not need is **ADL**: an
/// unqualified call may be found through the namespaces of its arguments' types, so a call with a class-typed (or
/// unreadable) argument is silence, and only a call whose arguments are all builtins can be called undeclared.
#[test]
fn a_call_to_a_name_nothing_declares_is_reported() {
    let undeclared = "\
void f() {
    printh(\"x\", 12);
}
";
    assert_eq!(
        codes_of(undeclared),
        [DiagnosticCode::UndefinedName],
        "nothing declares `printh`, and its arguments are a string literal and an int"
    );

    // **ADL**: a class-typed argument may bring the callee in from its own namespace.
    let adl = "\
struct Widget { int size; };
void f(Widget w) {
    swap(w, w);
}
";
    assert_eq!(codes_of(adl), [], "`swap` may be found by ADL");
    // A macro is expanded before the checks see it, so the callee under judgement is the *body*'s. Declared, and
    // the rule is silent — which is also the evidence that the macro's own name is never judged as a callee.
    let macro_call = "\
#define LOG(x) report(x)
void report(int value);
void f() {
    LOG(1);
}
";
    assert_eq!(codes_of(macro_call), []);

    // A callee the header declares.
    let from_a_header = "\
void log_name(const char *name, int count);
";
    let caller = "\
#include \"b.h\"
void f() {
    log_name(\"x\", 1);
}
";
    assert_eq!(
        codes_of_a_two_file_fixture(caller, from_a_header),
        [],
        "`log_name` is declared in the header"
    );
}

/// **A name declared twice in one scope**, and the five repeats that are not that.
///
/// `test_cpp/main.cpp` writes `auto x = 123;` on line 22 and `auto x = anotherVec[1];` on line 39 — one function, two
/// variables of one name, which no compiler accepts. The rule judges the scopes a reader writes (a function body, a
/// block, a lambda) and only the bindings that have no second reading: a function name in one scope is an **overload
/// set**, a class name is a forward declaration and its definition, and a file-scope variable may be `extern` in one
/// place and defined in another. Each of those is a case below.
#[test]
fn a_name_declared_twice_in_one_scope_is_reported() {
    let twice = "\
void f() {
    int count = 1;
    int count = 2;
}
";
    assert_eq!(codes_of(twice), [DiagnosticCode::Redefinition]);

    // The shape the sample project writes: `auto` twice, so the types disagree as well.
    let twice_with_auto = "\
struct W { int size; };
void f() {
    auto x = 123;
    auto x = W{};
}
";
    assert_eq!(codes_of(twice_with_auto), [DiagnosticCode::Redefinition]);

    // A parameter and a local of the same name are two declarations in the function's scope.
    let shadows_a_parameter = "\
void f(int count) {
    int count = 2;
}
";
    assert_eq!(
        codes_of(shadows_a_parameter),
        [DiagnosticCode::Redefinition]
    );
}

/// **The five repeats that are not a redefinition** — see [`a_name_declared_twice_in_one_scope_is_reported`].
#[test]
fn a_repeat_the_language_has_a_reading_for_is_quiet() {
    // Two blocks: two scopes.
    let two_blocks = "\
void f() {
    { int count = 1; }
    { int count = 2; }
}
";
    assert_eq!(codes_of(two_blocks), []);

    // Two overloads: one name, two declarations, one entity — the language's own reading.
    let overloads = "\
void run();
void run(int value);
void f() { run(); run(1); }
";
    assert_eq!(codes_of(overloads), []);

    // A forward declaration and its definition.
    let forward_and_definition = "\
class Widget;
class Widget { int size; };
";
    assert_eq!(codes_of(forward_and_definition), []);

    // `extern` then a definition, at file scope.
    let extern_and_definition = "\
extern int value;
int value = 0;
";
    assert_eq!(codes_of(extern_and_definition), []);

    // A nested block may shadow: the inner name is a different scope's.
    let shadowing = "\
void f() {
    int count = 1;
    { int count = 2; }
}
";
    assert_eq!(codes_of(shadowing), []);
}

/// **A braced initialiser and a `const` copy are not failed conversions** — two C shapes that produced a finding each
/// on every aggregate in a real C project.
///
/// Measured on a corpus of nine C files (one per feature area): `assign-type-check` was **13 of the 20 findings**
/// in the file that declares the aggregates, every one of them a line that gcc compiles without a warning:
///
/// ```c
/// static const point ORIGIN = {0, 0};                 // the list is the object's own initialiser
/// static struct value a_value = {.kind = VALUE_REAL};  // …with designators
/// point origin = ORIGIN;                               // a const object copied into a value
/// ```
///
/// The first two are `InitListExpr`s: a braced list is not a value with a type, it is the *initialiser of the target's
/// type*, and the standard judges it element by element — there is nothing for a conversion question to compare. The
/// third is a `const point` being copied into a `point`, which is what every C program does with a file-scope constant.
#[test]
fn a_braced_initialiser_and_a_const_copy_are_not_failed_conversions() {
    // The aggregate itself, with a list and with a designator.
    let codes = codes_of_a_file(
        "/p/corpus.c",
        "\
struct point { int x; int y; };
struct point origin = {0, 0};
struct point unit = {.x = 1, .y = 1};
",
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "a braced initialiser is the initialiser of the target's own type: {codes:?}"
    );

    // A `const` object copied into a value of the same type.
    let codes = codes_of_a_file(
        "/p/corpus.c",
        "\
struct point { int x; int y; };
static const struct point origin = {0, 0};
struct point copy = origin;
",
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "a `const` object converts to its own unqualified type: {codes:?}"
    );
}

/// **Three plain C spellings the findings should know nothing about.**
///
/// Each one was measured on the C corpus — nine files, one per feature area — as a finding gcc's silence contradicts:
///
/// ```c
/// int f(void);  int g(void) { return f(); }         // `(void)` is ZERO parameters, not one
/// int sum(int *restrict a, int *restrict b);        // `restrict` is a qualifier, not a name
/// int f(void) { _Static_assert(1, "x"); return 0; } // `_Static_assert` is a declaration, not a call
/// ```
///
/// The first fired twice (`a call passes fewer arguments` and, through a second reader, `not declared`), the second
/// as `redefinition`, and the third as `undefined-name` — one file each in a corpus where nothing is wrong.
#[test]
fn the_c_spellings_void_restrict_and_static_assert_produce_no_finding() {
    let codes = codes_of_a_file(
        "/p/void.c",
        "\
int f(void);
int g(void) { return f(); }
",
    );
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "`(void)` declares no parameters: {codes:?}"
    );

    let codes = codes_of_with(
        "/p/restrict.c",
        "\
int sum(int *restrict left, int *restrict right) { return *left + *right; }
",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::Redefinition),
        "`restrict` qualifies a pointer and declares nothing: {codes:?}"
    );

    let codes = codes_of_with(
        "/p/assert.c",
        "\
int f(void) {
    _Static_assert(1, \"a compile-time claim\");
    return 0;
}
",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "`_Static_assert` is C11's declaration: {codes:?}"
    );
}

/// **The C++-only rules are the ones the documentation lists.** The list is a claim about the language, and a
/// rule added to it (or dropped from it) without the documentation moving is the kind of drift this test exists for.
#[test]
fn the_cpp_only_rules_are_known_by_name() {
    let marked: Vec<DiagnosticCode> = DiagnosticCode::ALL
        .iter()
        .copied()
        .filter(|code| code.is_cpp_only())
        .collect();
    assert_eq!(
        marked,
        vec![
            DiagnosticCode::AccessInvisible,
            DiagnosticCode::ModuleNote,
            DiagnosticCode::UseNullptr,
            DiagnosticCode::UseOverride,
            DiagnosticCode::CStyleCast,
            DiagnosticCode::UseAuto,
            DiagnosticCode::ImplicitBoolConversion,
            DiagnosticCode::ConceptNotSatisfied,
            DiagnosticCode::DanglingField,
            DiagnosticCode::UeNaming,
            DiagnosticCode::UeGenerateBody,
            DiagnosticCode::UeGeneratedHeader,
            DiagnosticCode::UeMacroScope,
            DiagnosticCode::UeSpecifier,
            DiagnosticCode::ContractOnVirtualFunction,
            DiagnosticCode::ContractOnDefaultedFunction,
            DiagnosticCode::OverrideNonexistent,
            DiagnosticCode::FinalMisplaced,
            DiagnosticCode::FinalClassDerived,
            DiagnosticCode::OverrideOfFinal,
            DiagnosticCode::AbstractClassInstantiated,
            DiagnosticCode::PureVirtualNotOverridden,
        ]
    );
}

/// **A C project is not told to write C++.** These three rules name C++ style — `static_cast`, `nullptr`, an explicit
/// comparison — and in C each of the three is the language's own spelling. The language comes from the project's own
/// `-std=`, which is the defect `Config::language_for` records: a project that said `-std=c17` in `.cppls.toml` was
/// read as "not told", and `cstyle-cast` alone produced **14 findings** telling a C program to write `static_cast`.
///
/// The C++ half of the test is not decoration: a gate that silently turned the rules off everywhere would pass the
/// first half alone, and the rules are the reason the server has an opinion about C++ style at all.
#[test]
fn c_files_are_not_told_to_write_cpp_style() {
    // **`NULL` is left undeclared on purpose.** A `#define NULL 0` would be expanded by the cook, and every rule here
    // reads the tree: the expression would be `0` and `use-nullptr` could not see the spelling it is about. The
    // `undefined-name` that comes with it is a different rule and is not what this test asserts.
    let source = "\
int *p = NULL;
void f(int n) {
    if (n) {
        p = (int *)p;
    }
}
";
    let cpp_only = [
        DiagnosticCode::UseNullptr,
        DiagnosticCode::ImplicitBoolConversion,
        DiagnosticCode::CStyleCast,
    ];

    let in_c = codes_of_with(source, "/p/style.c", Some("c17"));
    for code in cpp_only {
        assert!(
            !in_c.contains(&code),
            "{code:?} is C++ only, and this file is compiled as C: {in_c:?}"
        );
    }

    let in_cpp = codes_of_with(source, "/p/style.cpp", Some("c++20"));
    for code in cpp_only {
        assert!(
            in_cpp.contains(&code),
            "{code:?} should fire in C++: {in_cpp:?}"
        );
    }
}

/// **What a C compiler provides is not an undeclared name, and what C made a keyword is not a call.**
///
/// Both halves were measured on the C corpus as `undefined-name`, and neither can be fixed by a reader who declares
/// things — the first because the names are the *implementation's*, and the second because they are not names at all:
///
/// ```text
/// __builtin_expect(x, 1)   __builtin_offsetof(struct line, corners)   …   ← gcc's builtins; no header declares them
/// _Static_assert(1, "x")   _Generic((v), int: "int")                  …   ← keywords, read as calls
/// ```
///
/// The `__builtin_*` family is reserved to the implementation (the double underscore is the standard's mark for it), so
/// a project that uses one has no way to declare it and "nothing this file can see names it" is false by construction.
/// The second half is the same reasoning one step further: `_Static_assert` and `_Generic` are grammar, so a `CallExpr`
/// whose callee is one of them is a parse this layer should not have produced — and until it does not, silence is the
/// only honest answer.
#[test]
fn compiler_builtins_and_c_keyword_constructs_are_not_undefined_names() {
    let codes = codes_of_with(
        "/p/builtins.c",
        "\
static int probe(int value) {
    if (__builtin_expect(value > 0, 1)) {
        return (int)__builtin_offsetof(struct point, y);
    }
    return __builtin_constant_p(value);
}
",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "`__builtin_*` is the implementation's: {codes:?}"
    );

    let codes = codes_of_with(
        "/p/keywords.c",
        "\
int classify(int value) {
    _Static_assert(sizeof(int) >= 2, \"an int is at least two bytes\");
    return _Generic(value, int: 1, default: 0);
}
",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "`_Static_assert` and `_Generic` are keywords, not calls: {codes:?}"
    );
}
/// **A header's C11 constructs are not this file's undefined names.**
///
/// The measured shape: a C file that includes `<stdio.h>` has that header's text **inlined into its rendering**, and a
/// header is parsed without a language the project's database never named — so `_Static_assert(…)` and `_Generic(…)`
/// inside it reach the checks as `CallExpr`s, and the rule that reports an undeclared callee reported **11** of them in
/// one nine-file corpus. The same reasoning covers `__builtin_*`: the compiler supplies it, so no declaration can exist.
///
/// Both are read as *spellings*, which is legitimate here for the reason `at_an_attribute`'s note gives: these names are
/// reserved to the implementation, so no `#define` in any header can turn one into a function, and the compiler's own
/// builtins cannot be declared by a program at all.
#[test]
fn a_headers_c11_construct_and_a_compiler_builtin_are_not_undefined_names() {
    let codes = codes_of_with(
        "/p/headers.c",
        "\
int classify(int value) {
    if (__builtin_expect(value > 0, 1)) {
        return 1;
    }
    return _Generic(value, int: 2, default: 3);
}
",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "a builtin and a keyword construct are both not names: {codes:?}"
    );
}
/// **A struct copied from a call, and `restrict` on a `static` function** — the two shapes left in the corpus.
///
/// ```c
/// point sum = point_add(origin, unit);            // `assign-type-check` said it does not convert to `point`
/// static int strict(int *restrict a, int *restrict b)   // `redefinition` said `restrict` is declared twice
/// ```
#[test]
fn a_struct_from_a_call_and_a_static_restrict_function_are_quiet() {
    let codes = codes_of_with(
        "/p/copy.c",
        "\
struct point { int x; int y; };
struct point make(void) { struct point made = {0, 0}; return made; }
struct point copy = make();
",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "a `struct point` initialised from a `struct point` is a copy: {codes:?}"
    );

    let codes = codes_of_with(
        "/p/static.c",
        "\
static int strict(int *restrict left, int *restrict right) { return *left + *right; }
",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::Redefinition),
        "`restrict` on a `static` function's parameter is a qualifier: {codes:?}"
    );
}
/// **A calling convention between the return type and the name is not part of the type.**
///
/// MinGW's `<stdlib.h>` writes the standard library this way — `extern div_t __cdecl div (int, int);` — and the
/// declaration's type came out as a spelling that names no type, so `div_t divided = div(7, 2);` was reported as
/// "does not convert to `div_t`". Measured on a nine-file C corpus: three findings (`div`, `ldiv`, `lldiv`), the whole
/// `library.c` aggregate.
#[test]
fn a_calling_convention_before_the_name_is_not_part_of_the_return_type() {
    let codes = codes_of_with(
        "/p/cdecl.c",
        "\
typedef struct { int quot; int rem; } div_t;
extern div_t __cdecl div(int numerator, int denominator);
div_t divided = div(7, 2);
",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "`__cdecl` is a calling convention, not a type: {codes:?}"
    );
}
/// **A type reached through two typedefs is the same type** — `div_t` → `_div_t` → the struct, which is how MinGW
/// spells every standard library type.
///
/// The one-level fixture above passes; the two-level one is where `div_t divided = div(7, 2);` was reported as "does not
/// convert to `div_t`" — the reading resolves `div_t` to `_div_t` on one side of the comparison and compares that
/// against the file's own `div_t` on the other.
#[test]
fn a_type_behind_two_typedefs_converts_to_itself() {
    let codes = codes_of_with(
        "/p/two_levels.c",
        "\
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t div(int numerator, int denominator);
div_t divided = div(7, 2);
",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "`div_t` and the type of `div(…)` are one type: {codes:?}"
    );
}
/// **The same conversion, with the declaration in a header** — the shape the corpus has, and the one the one-file
/// fixtures above cannot reproduce.
///
/// `library.c` writes `div_t divided = div(7, 2);` with both names in `<stdlib.h>`; the checker said the value "does
/// not convert to `div_t`". The difference from the one-file fixture is where the declaration lives, so the fixture has
/// to live in two files too.
#[test]
fn a_conversion_whose_declaration_is_in_a_header_is_still_a_conversion() {
    let header = "\
#ifndef STDLIB_H
#define STDLIB_H
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t __cdecl div(int numerator, int denominator);
#endif
";
    let source = "\
#include \"stdlib.h\"
div_t divided = div(7, 2);
";
    let files = MemoryFiles::new()
        .with_file("/p/stdlib.h", header)
        .with_file("/p/library.c", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let config = CompilerConfig {
        standard: Some("gnu17".into()),
        ..CompilerConfig::default()
    };
    let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
    session.add_project_files([
        std::path::PathBuf::from("/p/stdlib.h"),
        std::path::PathBuf::from("/p/library.c"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/library.c"));
    session.index_everything();
    while session.pending_work() > 0 {
        session.advance(64);
    }
    let codes: Vec<DiagnosticCode> = session
        .diagnostics(std::path::Path::new("/p/library.c"))
        .map(|found| {
            found
                .checks
                .into_iter()
                .map(|finding| finding.code)
                .collect()
        })
        .unwrap_or_default();
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "`div_t` from a header is the same type as `div_t` in the file: {codes:?}"
    );
}
/// **A declaration in a header counts even when the same file defines the function later** — the corpus's
/// `functions_selector`/`functions_aborts` shape.
///
/// `functions.c` calls `functions_selector()` at line 61 and defines it at line 182, with the declaration in
/// `corpus.h` — which is included at the top. The use is therefore declared, and the index says so when asked from
/// another file; asked from the file itself it answered only the **definition**, which is after the use, so the check
/// read the call as undeclared. Measured: two findings on one C corpus.
#[test]
fn a_header_declaration_counts_even_when_the_definition_is_later_in_the_file() {
    let header = "\
#ifndef STDLIB_H
#define STDLIB_H
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t div(int numerator, int denominator);
#endif
";
    let source = "\
#include \"stdlib.h\"
div_t divided = div(7, 2);
div_t div(int numerator, int denominator) {
    div_t result;
    result.quot = numerator / denominator;
    result.rem = numerator % denominator;
    return result;
}
";
    let files = MemoryFiles::new()
        .with_file("/p/stdlib.h", header)
        .with_file("/p/library.c", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let config = CompilerConfig {
        standard: Some("gnu17".into()),
        ..CompilerConfig::default()
    };
    let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
    session.add_project_files([
        std::path::PathBuf::from("/p/stdlib.h"),
        std::path::PathBuf::from("/p/library.c"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/library.c"));
    session.index_everything();
    while session.pending_work() > 0 {
        session.advance(64);
    }
    let codes: Vec<DiagnosticCode> = session
        .diagnostics(std::path::Path::new("/p/library.c"))
        .map(|found| {
            found
                .checks
                .into_iter()
                .map(|finding| finding.code)
                .collect()
        })
        .unwrap_or_default();
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "the header declares `div` before the use: {codes:?}"
    );
}
/// **Only the macro whose body is an expression without parentheses is this rule's finding.**
///
/// Measured on a nine-file C corpus: five findings, and every one of them was about a macro whose body is not an
/// unparenthesised expression — a statement expression (`({ … })`), a declaration (`static const point p = {…}`), an
/// X-macro fragment (`NAME##x = v,`), and two calls (`fprintf(…)`, `STRINGIFY(v)`). Each is a body a caller cannot
/// splice anything into.
#[test]
fn only_an_unparenthesised_expression_body_is_a_macro_parentheses_finding() {
    let codes = codes_of_a_file(
        "/p/macros.c",
        "\
#define TWICE(x) x * 2
#define CALL(f, v) f(v)
#define STRINGIFY(v) #v
#define DECLARE(name, v) static int name = (v)
#define FRAGMENT(name) COLOUR_##name = 1,
// **The corpus's own shapes**, with the line continuations that make a body more than one line: a statement
// expression, a `do { } while (0)`, and a declaration list.
#define STATEMENT(x)    \
    ({                  \
        int t = (x);    \
        t * t;          \
    })
#define ASSERT(c)         \
    do {                  \
        if (!(c)) {       \
        }                 \
    } while (0)
#define DEFINE(name, v)      \
    static int name = (v)
",
    );
    assert!(
        codes.contains(&DiagnosticCode::MacroParentheses),
        "`x * 2` is the shape this rule exists for: {codes:?}"
    );
    assert_eq!(
        codes
            .iter()
            .filter(|code| **code == DiagnosticCode::MacroParentheses)
            .count(),
        1,
        "and it is the only one: {codes:?}"
    );
}

/// **A `_Generic` selection whose associations name types parses**, which is the whole point of the construct.
///
/// Found by fixing the macro body range: `CORPUS_TYPE_NAME(value)` is
/// `_Generic((value), int:"int", double:"double", long:"long", char*:"char *", const char*:"const char *", default:"other")`,
/// and once the pasted text stopped carrying the comment that followed it, the file's rendering began to report
/// `expected `;``, `unexpected token`, and `expected }, but get string literal` — four syntax errors on a file gcc
/// compiles without a warning.
#[test]
fn a_generic_selection_with_typed_associations_parses() {
    let codes = codes_of_with(
        "\
static int name_of(int value) {
    return (int)strlen(_Generic((value), int: \"int\", double: \"double\", long: \"long\", char*: \"char *\", const char*: \"const char *\", default: \"other\"));
}
",
        "/p/generic.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::SyntaxError),
        "a `_Generic` with six associations is C11: {codes:?}"
    );
}

/// **The corpus's `_Generic` macro, pasted where it is used** — the shape that produced four syntax errors.
///
/// The macro is written over three continued lines and uses six associations; the use is inside a call
/// (`strlen(TYPE_NAME(v))`), which is where the paste lands.
#[test]
fn a_generic_macro_pasted_into_a_call_parses() {
    let codes = codes_of_with(
        "\
#define CORPUS_TYPE_NAME(value) _Generic((value), \
    int: \"int\",                                 \
    double: \"double\",                          \
    long: \"long\",                              \
    char *: \"char *\",                          \
    const char *: \"const char *\",              \
    default: \"other\")
static int name_of(int integer) {
    return (int)strlen(CORPUS_TYPE_NAME(integer));
}
",
        "/p/generic_macro.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::SyntaxError),
        "the macro's body is one `_Generic` selection: {codes:?}"
    );
}
/// **An X-macro's `##` pasting still pastes** — the shape `CORPUS_COLOURS(CORPUS_ENUM_ENTRY)` has.
///
/// Found while fixing the macro body range, and the *first* version of this test was wrong in a way worth recording:
/// it used `NAME_ENTRY` before defining it, which is a C error, so the `SyntaxError` it asserted against was its own.
/// With the definitions in order the paste is correct — `COLOUR_##name` becomes `COLOUR_red` — and the test now says so.
#[test]
fn an_x_macro_pastes_its_names() {
    let codes = codes_of_with(
        "\
#define LIST(X) X(red, 0) X(green, 1)
#define ENTRY(name, value) COLOUR_##name = value,
#define NAME_ENTRY(name, value) #name,
enum colours { LIST(ENTRY) COLOUR_COUNT };
static const char *const NAMES[] = {LIST(NAME_ENTRY) \"count\"};
",
        "/p/xmacro.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::SyntaxError),
        "the pasted names are identifiers: {codes:?}"
    );
}
/// **A call whose only argument is a macro that expands to a `_Generic`** counts as one argument.
///
/// The corpus writes `strlen(CORPUS_TYPE_NAME(integer))`, where the macro body is one `_Generic` selection with six
/// `type: value` associations — and `argument-count` reported **five** of those calls as passing too few arguments to
/// `strlen`, which takes one. The commas inside the expansion are the selection's, not the call's.
///
/// The declaration is written here rather than included, because the rule needs a `strlen` it can see: a fixture whose
/// `<string.h>` does not resolve has no callee and the rule says nothing, which is how the first version of this test
/// passed while the corpus failed.
#[test]
fn a_macro_that_expands_to_a_generic_selection_is_one_argument() {
    let codes = codes_of_with(
        "\
extern unsigned long long strlen(const char *text);
#define TYPE_NAME(value) _Generic((value), int: \"int\", double: \"double\", long: \"long\", default: \"other\")
static int name_of(int integer) {
    return (int)strlen(TYPE_NAME(integer));
}
",
        "/p/one_argument.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "one argument, four associations inside it: {codes:?}"
    );
}

/// **A local declared inside a statement expression is not a redefinition** when the macro is expanded twice.
///
/// `#define CORPUS_SQUARE(v) ({ int corpus_square = (v); corpus_square * corpus_square; })` used twice in one function
/// declares `corpus_square` twice — in two *different* statement-expression scopes, which is legal C. `redefinition`
/// reported the second one.
#[test]
fn a_local_in_a_statement_expression_is_not_a_redefinition() {
    let codes = codes_of_with(
        "\
#define SQUARE(value) ({ int squared = (value); squared * squared; })
static int twice(int first, int second) {
    int a = SQUARE(first);
    int b = SQUARE(second);
    return a + b;
}
",
        "/p/statement.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::Redefinition),
        "two statement expressions, two scopes: {codes:?}"
    );
}
/// **The corpus's own `CORPUS_SQUARE`, expanded once**, is not a redefinition.
///
/// The body ends with `corpus_square *corpus_square;` — which is *statement-shaped like a declaration* (`T *name;`) and
/// is an expression here, because `corpus_square` is a variable and not a type. With that statement read as a
/// declaration, the block holds two bindings of the name and `redefinition` reports the second.
#[test]
fn the_corpus_square_body_reads_its_last_statement_as_an_expression() {
    let codes = codes_of_with(
        "\
#define SQUARE(value)    \
    ({                   \
        int corpus_square = (value); \
        corpus_square *corpus_square; \
    })
static int squared(int value) {
    int total = 0;
    total += SQUARE(value);
    return total;
}
",
        "/p/square.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::Redefinition),
        "`corpus_square *corpus_square;` is a multiplication: {codes:?}"
    );
}

/// **`restrict` on a pointer parameter, at file scope, in a file that has declarations before it.**
///
/// `static int restrict_sum(int *restrict left, int *restrict right)` is the corpus's line, and the one-parameter
/// fixture that passes did not carry the preceding declarations — so this one does.
#[test]
fn a_restrict_parameter_after_other_declarations_is_not_a_name() {
    let codes = codes_of_with(
        "\
static int a_const_int = 7;
static int *const const_pointer = (int *)&a_const_int;
static const int *const const_pointer_to_const = &a_const_int;
static volatile int a_volatile_int = 3;
static volatile const int volatile_const_int = 4;
static int restrict_sum(int *restrict left, int *restrict right) {
    return *left + *right;
}
",
        "/p/restrict.c",
        Some("c17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::Redefinition),
        "two `restrict` parameters are two qualifiers: {codes:?}"
    );
}

/// **A name defined in an unnamed namespace is visible later in the same file.**
///
/// `namespace { int helper(); }` is how a C++ file gives a function internal linkage, and [namespace.def] makes its
/// members visible in the enclosing scope — a `using namespace` the compiler writes for you. A plain scope-chain walk
/// never reaches the child scope, so every call to a file-local helper read as undeclared (22 findings across the C++
/// corpus, one per helper).
#[test]
fn an_unnamed_namespaces_member_is_visible_later_in_the_file() {
    let codes = codes_of(
        "\
namespace {
int helper(int value) { return value + 1; }
int counter = 0;
}

int use_helper(int value) { return helper(value) + counter; }
",
    );
    assert!(
        !codes.contains(&DiagnosticCode::UndefinedName),
        "an unnamed namespace's members are visible here: {codes:?}"
    );
}

/// **`[[maybe_unused]]` is the reader answering this rule's question**, and a local with a type that can have a
/// destructor is not "unused" at all: `Guard guard(counter);` exists for the side effect of its lifetime.
#[test]
fn a_marked_or_lifetime_object_is_not_reported_unused() {
    let marked = codes_of(
        "\
void f() {
    [[maybe_unused]] int local = 3;
}
",
    );
    assert!(
        !marked.contains(&DiagnosticCode::Unused),
        "the attribute is the answer: {marked:?}"
    );

    let lifetime = codes_of(
        "\
struct Guard { explicit Guard(int& counter) : counter_(counter) { ++counter_; } ~Guard() { --counter_; } int& counter_; };
void f() {
    int counter = 0;
    Guard guard(counter);
}
",
    );
    assert!(
        !lifetime.contains(&DiagnosticCode::Unused),
        "an object whose use is its lifetime is not unused: {lifetime:?}"
    );

    let plain = codes_of(
        "\
void f() {
    int local = 3;
}
",
    );
    assert!(
        plain.contains(&DiagnosticCode::Unused),
        "an unmarked builtin is still reported: {plain:?}"
    );
}

/// **`std::any any = 1;` has type `std::any`**, not `void` — the declared name must not be read as the *declarator* of
/// an out-of-line definition just because the type's last segment spells the same word.
#[test]
fn a_variable_named_like_its_type_keeps_that_type() {
    let codes = codes_of(
        "\
void f() {
    std::any any = 1;
    any = std::string{\"anything\"};
}
",
    );
    assert!(
        !codes.contains(&DiagnosticCode::AssignTypeCheck),
        "`std::any any` is an `std::any`, and both assignments convert: {codes:?}"
    );
}

/// **A variadic macro's call has no arity to check** — and the count it does have is the macro's, not a function's.
///
/// ```c
/// #define SUM(count, ...) (sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
/// int n = SUM(total, 1, 2, 3);      // one fixed parameter, then the pack
/// ```
///
/// `argument-count` reported this call: the macro's replacement list expands to a call of `sum_impl` with `count`
/// and `__VA_ARGS__`, and the check was counting the *expansion's* arguments against `sum_impl`'s declaration — while
/// the reader wrote one argument list, the macro's. Measured on a C corpus: one false finding, on the call the user
/// pointed at.
#[test]
fn a_variadic_macro_call_is_not_an_argument_count_finding() {
    let codes = codes_of_with(
        "\
#define SUM(count, ...) (sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
int sum_impl(int count, ...);
int f(void) {
    int total = 0;
    return SUM(total, 1, 2, 3);
}
",
        "/p/variadic.c",
        Some("gnu17"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "a variadic macro takes any number of arguments: {codes:?}"
    );
}
/// **The corpus's own `__VA_OPT__` shape** — the one that still reports an argument count through the real server.
///
/// ```c
/// #define C23_SUM(count, ...) (c23_sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
/// static int c23_sum_impl(int count, ...) { return count; }
/// int c23_va_opt(int count, ...) { return C23_SUM(count, 1, 2, 3) + count; }
/// ```
///
/// The fixture above (`a_variadic_macro_call_is_not_an_argument_count_finding`) declares the callee as a **prototype**
/// and passes; this one *defines* it, which is the corpus's shape and the one an editor reported: "`c23_sum_impl` takes
/// 1 argument(s) and this call passes more". The difference between the two fixtures is the whole reason this test
/// exists — a prototype's parameter list reaches the rule as the declaration's **text**, while a definition's is read
/// from the tree.
#[test]
fn a_variadic_macro_whose_callee_is_a_definition_is_not_an_argument_count_finding() {
    let codes = codes_of_with(
        "\
#define C23_SUM(count, ...) (c23_sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
static int c23_sum_impl(int count, ...) { return count; }
int c23_va_opt(int count, ...) { return C23_SUM(count, 1, 2, 3) + count; }
",
        "/p/vaopt.c",
        Some("c23"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ArgumentCount),
        "a variadic callee takes any number of arguments: {codes:?}"
    );
}

/// **The `include/` beside `src/` layout resolves without a compilation database** — CMake's own convention.
///
/// ```text
/// <root>/include/techniques.h
/// <root>/src/techniques.cpp      #include "techniques.h"
/// ```
///
/// A quoted include is searched beside the including file, then in the `include` directories above it — which is what
/// `include_roots_above` exists for. Measured on a real C++ project laid out exactly this way: the include was reported
/// `include-not-found`, the header was never read, and every member question about a type the header declares answered
/// nothing at all.
#[test]
fn the_include_directory_beside_src_resolves_a_quoted_include() {
    let root = std::env::temp_dir().join("cppls-include-layout");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("include")).expect("the layout is created");
    std::fs::create_dir_all(root.join("src")).expect("the layout is created");
    std::fs::write(
        root.join("include/techniques.h"),
        "struct Widget { int size() const; };\n",
    )
    .expect("the header is written");
    let source =
        "#include \"techniques.h\"\n\nint use() { Widget widget; return widget.size(); }\n";
    std::fs::write(root.join("src/techniques.cpp"), source).expect("the source is written");

    let mut session = cpp_code_analysis::Session::open(
        root.clone(),
        cpp_code_analysis::SessionFiles::new(
            cpp_code_analysis::OpenDocuments::new(),
            cpp_code_analysis::DiskFiles,
        ),
        cpp_code_analysis::WatchFilter::new(&root),
    );
    session.add_project_files([
        root.join("src/techniques.cpp"),
        root.join("include/techniques.h"),
    ]);
    session.index_everything();
    session.cook(root.join("src/techniques.cpp"));

    let found = session
        .diagnostics(root.join("src/techniques.cpp"))
        .expect("the file is analysed");
    let codes: Vec<&str> = found.checks.iter().map(|check| check.code.name()).collect();
    assert!(
        !codes.contains(&"include-not-found"),
        "`include/` beside `src/` is on the search path: {codes:?}"
    );
    let _ = std::fs::remove_dir_all(&root);
}

/// **A parameter whose type is the callee's own template parameter takes anything** — `value_or(0)`.
///
/// ```cpp
/// template <typename U> int value_or(U&& other) const;
/// Opt o; o.value_or(0);          // `U` is deduced from the argument; nothing can be checked against it
/// ```
///
/// Measured on a C++ project: `number.value_or(0)` produced *"this passes `0` where `_Ty2&&` is declared for `value_or`"*,
/// which is the standard library's own `std::optional<T>::value_or` and is perfectly valid.
#[test]
fn a_parameter_that_is_the_callees_template_parameter_takes_anything() {
    let codes = codes_of_with(
        "\
struct Opt {
    template <typename U>
    int value_or(U&& other) const;
};

int f() {
    Opt o;
    return o.value_or(0);
}
",
        "/p/a.cpp",
        Some("c++20"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ParamTypeCheck),
        "`U` is deduced from the argument: {codes:?}"
    );
}
/// The same call against **two** members of one name — `value_or` has a `const&` and an `&&` overload in the standard
/// library, both written `(_Ty2&&)`.
#[test]
fn a_template_parameter_member_overload_set_is_silent() {
    let codes = codes_of_with(
        "\
struct Opt {
    template <typename U> int value_or(U&& other) const &;
    template <typename U> int value_or(U&& other) &&;
};

int f() {
    Opt o;
    return o.value_or(0);
}
",
        "/p/a.cpp",
        Some("c++20"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ParamTypeCheck),
        "neither overload has a type to check `0` against: {codes:?}"
    );
}
/// **A `friend` may read what is private**, which is what every wrapper class and every `operator<<` is built on.
///
/// `Borrower` is named in `Holder`'s own declaration, so its member may read `Holder::secret` — and the access check
/// reported it until the friend declarations of the declaring class were read: measured on MSVC's `comutil.h`, seven
/// findings of exactly this family.
#[test]
fn a_friends_code_may_read_what_is_private() {
    let codes = codes_of_with(
        "\
class Holder {\
    friend class Borrower;\
    int secret = 1;\
};\
class Borrower {\
public:\
    int peek(Holder& holder) { return holder.secret; }\
};\
",
        "/p/a.cpp",
        Some("c++20"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::AccessInvisible),
        "the friend declaration permits it: {codes:?}"
    );
}

/// **A private member read inside its class's own out-of-class definition** is that class's own code.
///
/// `int Holder::peek() { return secret; }` has no `ClassDef` above it in the tree — the class is written in the
/// specifier — so the access check could not see that the reader *is* `Holder`, and reported it. Measured on
/// MSVC's `comutil.h`: seven `AccessInvisible` findings, six of them defined out of class.
#[test]
fn an_out_of_class_definition_may_read_its_own_private_member() {
    let codes = codes_of_with(
        "\
struct Outer {
    struct Inner {
        int peek() const;
    private:
        int secret = 1;
    };
};
    int peek() const;\
private:\
    int secret = 1;\
};\
int Holder::peek() const { return secret; }\
",
        "/p/a.cpp",
        Some("c++20"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::AccessInvisible),
        "the definition is the class's own code: {codes:?}"
    );
}

/// **A template parameter cannot be judged against a concept** — it is whatever the caller instantiates.
///
/// `template <class _Tp> void f(_Tp&& value) { g(std::forward<_Tp>(value)); }` is the shape every generic library is
/// written in, and `_Tp&&` was reported as not satisfying `std::floating_point`. Measured on libstdc++'s `<compare>`.
#[test]
fn a_template_parameter_is_not_judged_against_a_concept() {
    let codes = codes_of_with(
        "\
template <class _Tp>
concept floating = __is_floating_point(_Tp);

void takes_a_float(floating auto value) { (void)value; }
void takes_an_int(int value) { (void)value; }

template <class _Tp>
void forward_it(_Tp&& value) {
    takes_an_int(1);
    (void)value;
}
",
        "/p/a.cpp",
        Some("c++20"),
    );
    assert!(
        !codes.contains(&DiagnosticCode::ConceptNotSatisfied),
        "a parameter is not a type: {codes:?}"
    );
}

/// **An out-of-class constructor and destructor are not functions with a return type** — the user's own file.
///
/// `LSPHandle.cpp` writes
///
/// ```cpp
/// LSPHandle::LSPHandle(LanguageServer *server)
///     : _server(server) {
///     Initialize();
/// }
/// ```
///
/// and the rule reported "this function is declared to return `` and its body has no `return`" on it. A constructor
/// has no return type *at all*, so the empty spelling in that sentence is the second symptom of the same mistake: the
/// rule read a declaration whose specifier sequence is empty as one that *has* a written return type.
///
/// The in-class shape was already covered (`struct S { S(int x) {…} };` in `missing_return_is_a_control_flow_question`);
/// what differs out of class is the qualifier, which makes the grammar produce a specifier sequence node with nothing
/// in it. Counted rather than set-compared: the free function in the fixture must still report.
#[test]
fn missing_return_is_silent_for_an_out_of_class_constructor_and_destructor() {
    let source = "\
struct S { S(int x); ~S(); int f(); };
S::S(int x) : _x(x) { Initialize(); }
S::~S() { }
int S::f() { }
int free_function() { }
";
    let codes = codes_of(source);
    let reports = codes
        .iter()
        .filter(|code| **code == DiagnosticCode::MissingReturn)
        .count();
    assert_eq!(
        reports, 2,
        "`int S::f()` and `int free_function()` promise a return and have none: {codes:?}"
    );
}

/// **A parameter written as a template parameter takes anything, and the relation is not allowed to say otherwise.**
///
/// The reader's report, on a real project:
///
/// ```text
/// void Report::add(std::string line) { lines.push_back(std::move(line)); }
/// this passes `std::move(line)` where `const _Ty&` is declared for `push_back`
/// ```
///
/// `_Ty` is `std::vector`'s own parameter, and what it accepts is decided by the call — there is nothing to compare an
/// argument against. The relation answered `No` (the target names a type nothing declares), and that refusal is what
/// the diagnostic was made of; `convert::conversion`'s template-parameter rule sits in the `Unknown` arm and never ran
/// for a `No`.
#[test]
fn a_template_parameter_parameter_is_never_a_mismatch() {
    let source = "
namespace std {
template <class T> T&& move(T& value) noexcept;
template <class _Ty> class vector {
public:
    void push_back(const _Ty& value);
};
class string {};
}
void f() {
    std::vector<std::string> lines;
    std::string line;
    lines.push_back(std::move(line));
}
";
    assert!(
        !codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
        "`const _Ty&` takes what the call decides: {:?}",
        codes_of(source)
    );
}

/// **The errors a file produces**, as the diagnostics request reports them — the parser's channel rather than the
/// checks'.
fn errors_of_a_file(path: &str, source: &str) -> Vec<String> {
    let files = MemoryFiles::new().with_file(path, source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from(path)]);
    session.want_cooked_reading(std::path::Path::new(path));
    session.index_everything();

    session
        .diagnostics(std::path::Path::new(path))
        .map(|found| {
            found
                .errors
                .iter()
                .map(|error| error.message.clone())
                .collect()
        })
        .unwrap_or_default()
}

/// **The session reads a `.c` file with C's keyword table.** `int new = 0;` compiles as C and does not as C++ — and
/// the language comes from the compile database, or from the extension when there is none. Measured on neovim, whose
/// `src/nvim/autocmd.c:1343` is `Object new = …` and whose `src/nvim/marktree.c:392` has a parameter named `delete`;
/// read with C++'s table, the declaration fails and a whole function body is taken for an expression.
#[test]
fn a_c_file_may_name_things_cpp_reserves() {
    let c = errors_of_a_file(
        "/p/a.c",
        "struct O { int x; };\nstruct O new = { 0 };\nvoid f(int delete) { (void)delete; }\n",
    );
    assert!(c.is_empty(), "those are names in C: {c:?}");

    let cpp = errors_of_a_file("/p/a.cpp", "int new = 0;\n");
    assert!(
        !cpp.is_empty(),
        "the same text in C++ is the keyword, and the declaration is not one"
    );
}
/// **A dereference in a call argument is not a redeclaration.**
///
/// `xfree(*matches);` has two readings: a call of `xfree` with `*matches` for its argument, and a declaration of
/// `matches` as a pointer to `xfree` — the classic ambiguous shape, which only *lookup* settles (`xfree` is a
/// function, so it cannot be the type). The grammar takes the declaration reading, the scope walk binds `matches` a
/// second time from it, and this rule reported the repeat. Measured on neovim's `cmdexpand.c:3389`, in
/// `xfree(*matches);` — real code, reported as a redefinition.
#[test]
fn a_dereference_in_a_call_argument_is_not_a_redeclaration() {
    let dereference = "\
void xfree(void *p);
void f(char **matches) { xfree(*matches); }
";
    assert_eq!(
        codes_of_a_file("/p/a.c", dereference),
        Vec::new(),
        "a call's argument declares nothing"
    );

    // **A pointer-to-type declaration keeps its reading**, because its first name is a type and not a function.
    let declaration = "\
struct T { int n; };
void f(void) {
    T (*p);
    (void)p;
}
";
    assert_eq!(
        codes_of_a_file("/p/a.c", declaration),
        Vec::new(),
        "`T (*p);` declares `p` and nothing repeats"
    );

    // **And a repeat that really is one still reports** — the fix must not silence the rule.
    let repeated = "\
void f(void) {
    int count = 1;
    int count = 2;
    (void)count;
}
";
    assert_eq!(
        codes_of_a_file("/p/a.c", repeated),
        [DiagnosticCode::Redefinition],
        "two variables of one name in one scope is what the rule is for"
    );
}

/// **`return 0;` from a function declared to return a pointer is legal** — `0` is the null pointer constant, and the
/// conversion relation cannot see a value.
///
/// Measured on neovim's `indent.c:585`: a macro expanded to a `0` in the body of a function returning `int *`, and the
/// rule reported "``0`` returns a value that does not convert to `int *`". `assign-type-check` has had this exemption
/// since its census; this rule did not.
#[test]
fn the_null_pointer_constant_returns_from_a_pointer_function() {
    let null_constant = "\
int *find(int n) {
    if (n > 0) {
        return 0;
    }
    return 0;
}
";
    assert_eq!(
        codes_of_a_file("/p/a.c", null_constant),
        Vec::new(),
        "`return 0;` is a null pointer, not a type error"
    );

    // **A value that is not the constant still reports** — `n` is an `int`, and `int *` is not what it converts to.
    let mismatched = "\
int *find(int n) {
    return n;
}
";
    assert_eq!(
        codes_of_a_file("/p/a.c", mismatched),
        [DiagnosticCode::ReturnTypeMismatch],
        "`int` does not convert to `int *`"
    );
}