frontend 0.4.0

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
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
// ignore-tidy-file-filelength
// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use core::num::NonZero;

use crate::rustc_data_structures::fx::FxIndexMap;
use crate::rustc_errors::codes::*;
use crate::rustc_errors::formatting::DiagMessageAddArg;
use crate::rustc_errors::{
    Applicability, Diag, DiagCtxtHandle, DiagMessage, DiagStyledString, Diagnostic,
    EmissionGuarantee, Level, Subdiagnostic, SuggestionStyle, msg,
};
use crate::rustc_hir as hir;
use crate::rustc_hir::def_id::DefId;
use crate::rustc_hir::intravisit::VisitorExt;
use rustc_macros::{Diagnostic, Subdiagnostic};
use crate::rustc_middle::ty::inhabitedness::InhabitedPredicate;
use crate::rustc_middle::ty::{Clause, PolyExistentialTraitRef, Ty, TyCtxt};
use crate::rustc_session::Session;
use crate::rustc_span::edition::Edition;
use crate::rustc_span::{Ident, Span, Symbol, sym};

use crate::rustc_lint::LateContext;
use crate::rustc_lint::builtin::{InitError, ShorthandAssocTyCollector, TypeAliasBounds};
use crate::rustc_lint::lifetime_syntax::LifetimeSyntaxCategories;

#[derive(Diagnostic)]
#[diag("{$lint_level}({$lint_source}) incompatible with previous forbid", code = E0453)]
pub(crate) struct OverruledAttribute<'a> {
    #[primary_span]
    pub span: Span,
    #[label("overruled by previous forbid")]
    pub overruled: Span,
    pub lint_level: &'a str,
    pub lint_source: Symbol,
    #[subdiagnostic]
    pub sub: OverruledAttributeSub,
}

pub(crate) enum OverruledAttributeSub {
    DefaultSource { id: String },
    NodeSource { span: Span, reason: Option<Symbol> },
    CommandLineSource { id: Symbol },
}

impl Subdiagnostic for OverruledAttributeSub {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        match self {
            OverruledAttributeSub::DefaultSource { id } => {
                diag.note(msg!("`forbid` lint level is the default for {$id}"));
                diag.arg("id", id);
            }
            OverruledAttributeSub::NodeSource { span, reason } => {
                diag.span_label(span, msg!("`forbid` level set here"));
                if let Some(rationale) = reason {
                    diag.note(rationale.to_string());
                }
            }
            OverruledAttributeSub::CommandLineSource { id } => {
                diag.note(msg!("`forbid` lint level was set on command line (`-F {$id}`)"));
                diag.arg("id", id);
            }
        }
    }
}

#[derive(Diagnostic)]
#[diag("malformed lint attribute input", code = E0452)]
pub(crate) struct MalformedAttribute {
    #[primary_span]
    pub span: Span,
    #[subdiagnostic]
    pub sub: MalformedAttributeSub,
}

#[derive(Subdiagnostic)]
pub(crate) enum MalformedAttributeSub {
    #[label("bad attribute argument")]
    BadAttributeArgument(#[primary_span] Span),
    #[label("reason must be a string literal")]
    ReasonMustBeStringLiteral(#[primary_span] Span),
    #[label("reason in lint attribute must come last")]
    ReasonMustComeLast(#[primary_span] Span),
}

#[derive(Diagnostic)]
#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$tool_name}::{$lint_name}`", code = E0710)]
pub(crate) struct UnknownToolInScopedLint {
    #[primary_span]
    pub span: Option<Span>,
    pub tool_name: Symbol,
    pub lint_name: String,
    #[help("add `#![register_tool({$tool_name})]` to the crate root")]
    pub is_nightly_build: bool,
}

#[derive(Diagnostic)]
#[diag("functions generic over types or consts must be mangled")]
pub(crate) struct BuiltinNoMangleGeneric {
    #[primary_span]
    pub span: Span,
    // Use of `#[no_mangle]` suggests FFI intent; correct
    // fix may be to monomorphize source by hand
    #[suggestion(
        "remove this attribute",
        style = "short",
        code = "",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

#[derive(Diagnostic)]
#[diag("`...` range patterns are deprecated", code = E0783)]
pub(crate) struct BuiltinEllipsisInclusiveRangePatterns {
    #[primary_span]
    pub span: Span,
    #[suggestion(
        "use `..=` for an inclusive range",
        style = "short",
        code = "{replace}",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
    pub replace: String,
}

#[derive(Subdiagnostic)]
#[note("requested on the command line with `{$level} {$lint_name}`")]
pub(crate) struct RequestedLevel<'a> {
    pub level: crate::rustc_lint_defs::Level,
    pub lint_name: &'a str,
}

#[derive(Diagnostic)]
#[diag("`{$lint_group}` lint group is not supported with ´--force-warn´", code = E0602)]
pub(crate) struct UnsupportedGroup {
    pub lint_group: String,
}

#[derive(Diagnostic)]
#[diag("unknown lint tool: `{$tool_name}`", code = E0602)]
pub(crate) struct CheckNameUnknownTool<'a> {
    pub tool_name: Symbol,
    #[subdiagnostic]
    pub sub: RequestedLevel<'a>,
}

// array_into_iter.rs
#[derive(Diagnostic)]
#[diag(
    "this method call resolves to `<&{$target} as IntoIterator>::into_iter` (due to backwards compatibility), but will resolve to `<{$target} as IntoIterator>::into_iter` in Rust {$edition}"
)]
pub(crate) struct ShadowedIntoIterDiag {
    pub target: &'static str,
    pub edition: &'static str,
    #[suggestion(
        "use `.iter()` instead of `.into_iter()` to avoid ambiguity",
        code = "iter",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
    #[subdiagnostic]
    pub sub: Option<ShadowedIntoIterDiagSub>,
}

#[derive(Subdiagnostic)]
pub(crate) enum ShadowedIntoIterDiagSub {
    #[suggestion(
        "or remove `.into_iter()` to iterate by value",
        code = "",
        applicability = "maybe-incorrect"
    )]
    RemoveIntoIter {
        #[primary_span]
        span: Span,
    },
    #[multipart_suggestion(
        "or use `IntoIterator::into_iter(..)` instead of `.into_iter()` to explicitly iterate by value",
        applicability = "maybe-incorrect"
    )]
    UseExplicitIntoIter {
        #[suggestion_part(code = "IntoIterator::into_iter(")]
        start_span: Span,
        #[suggestion_part(code = ")")]
        end_span: Span,
    },
}

// autorefs.rs
#[derive(Diagnostic)]
#[diag("implicit autoref creates a reference to the dereference of a raw pointer")]
#[note(
    "creating a reference requires the pointer target to be valid and imposes aliasing requirements"
)]
pub(crate) struct ImplicitUnsafeAutorefsDiag<'a> {
    #[label("this raw pointer has type `{$raw_ptr_ty}`")]
    pub raw_ptr_span: Span,
    pub raw_ptr_ty: Ty<'a>,
    #[subdiagnostic]
    pub origin: ImplicitUnsafeAutorefsOrigin<'a>,
    #[subdiagnostic]
    pub method: Option<ImplicitUnsafeAutorefsMethodNote>,
    #[subdiagnostic]
    pub suggestion: ImplicitUnsafeAutorefsSuggestion,
}

#[derive(Subdiagnostic)]
pub(crate) enum ImplicitUnsafeAutorefsOrigin<'a> {
    #[note("autoref is being applied to this expression, resulting in: `{$autoref_ty}`")]
    Autoref {
        #[primary_span]
        autoref_span: Span,
        autoref_ty: Ty<'a>,
    },
    #[note(
        "references are created through calls to explicit `Deref(Mut)::deref(_mut)` implementations"
    )]
    OverloadedDeref,
}

#[derive(Subdiagnostic)]
#[note("method calls to `{$method_name}` require a reference")]
pub(crate) struct ImplicitUnsafeAutorefsMethodNote {
    #[primary_span]
    pub def_span: Span,
    pub method_name: Symbol,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "try using a raw pointer method instead; or if this reference is intentional, make it explicit",
    applicability = "maybe-incorrect"
)]
pub(crate) struct ImplicitUnsafeAutorefsSuggestion {
    pub mutbl: &'static str,
    pub deref: &'static str,
    #[suggestion_part(code = "({mutbl}{deref}")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

// builtin.rs
#[derive(Diagnostic)]
#[diag("denote infinite loops with `loop {\"{\"} ... {\"}\"}`")]
pub(crate) struct BuiltinWhileTrue {
    #[suggestion(
        "use `loop`",
        style = "short",
        code = "{replace}",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
    pub replace: String,
}

#[derive(Diagnostic)]
#[diag("the `{$ident}:` in this pattern is redundant")]
pub(crate) struct BuiltinNonShorthandFieldPatterns {
    pub ident: Ident,
    #[suggestion(
        "use shorthand field pattern",
        code = "{prefix}{ident}",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
    pub prefix: &'static str,
}

#[derive(Diagnostic)]
pub(crate) enum BuiltinUnsafe {
    #[diag(
        "`allow_internal_unsafe` allows defining macros using unsafe without triggering the `unsafe_code` lint at their call site"
    )]
    AllowInternalUnsafe,
    #[diag("usage of an `unsafe` block")]
    UnsafeBlock,
    #[diag("usage of an `unsafe extern` block")]
    UnsafeExternBlock,
    #[diag("declaration of an `unsafe` trait")]
    UnsafeTrait,
    #[diag("implementation of an `unsafe` trait")]
    UnsafeImpl,
    #[diag("declaration of an `unsafe` function")]
    DeclUnsafeFn,
    #[diag("declaration of an `unsafe` method")]
    DeclUnsafeMethod,
    #[diag("implementation of an `unsafe` method")]
    ImplUnsafeMethod,
    #[diag("usage of `core::arch::global_asm`")]
    #[note("using this macro is unsafe even though it does not need an `unsafe` block")]
    GlobalAsm,
}

#[derive(Diagnostic)]
#[diag("missing documentation for {$article} {$desc}")]
pub(crate) struct BuiltinMissingDoc<'a> {
    pub article: &'a str,
    pub desc: &'a str,
}

#[derive(Diagnostic)]
#[diag("type could implement `Copy`; consider adding `impl Copy`")]
pub(crate) struct BuiltinMissingCopyImpl;

pub(crate) struct BuiltinMissingDebugImpl<'a> {
    pub tcx: TyCtxt<'a>,
    pub def_id: DefId,
}

// Needed for def_path_str
impl<'a> Diagnostic<'a, ()> for BuiltinMissingDebugImpl<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let Self { tcx, def_id } = self;
        Diag::new(
            dcx,
            level,
            msg!("type does not implement `{$debug}`; consider adding `#[derive(Debug)]` or a manual implementation"),
        ).with_arg("debug", tcx.def_path_str(def_id))
    }
}

#[derive(Diagnostic)]
#[diag("anonymous parameters are deprecated and will be removed in the next edition")]
pub(crate) struct BuiltinAnonymousParams<'a> {
    #[suggestion("try naming the parameter or explicitly ignoring it", code = "_: {ty_snip}")]
    pub suggestion: (Span, Applicability),
    pub ty_snip: &'a str,
}

#[derive(Diagnostic)]
#[diag("unused doc comment")]
pub(crate) struct BuiltinUnusedDocComment<'a> {
    pub kind: &'a str,
    #[label("rustdoc does not generate documentation for {$kind}")]
    pub label: Span,
    #[subdiagnostic]
    pub sub: BuiltinUnusedDocCommentSub,
}

#[derive(Subdiagnostic)]
pub(crate) enum BuiltinUnusedDocCommentSub {
    #[help("use `//` for a plain comment")]
    PlainHelp,
    #[help("use `/* */` for a plain comment")]
    BlockHelp,
}

#[derive(Diagnostic)]
#[diag("const items should never be `#[no_mangle]`")]
pub(crate) struct BuiltinConstNoMangle {
    #[suggestion("try a static value", code = "pub static ", applicability = "machine-applicable")]
    pub suggestion: Option<Span>,
}

#[derive(Diagnostic)]
#[diag(
    "transmuting &T to &mut T is undefined behavior, even if the reference is unused, consider instead using an UnsafeCell"
)]
pub(crate) struct BuiltinMutablesTransmutes;

#[derive(Diagnostic)]
#[diag("use of an unstable feature")]
pub(crate) struct BuiltinUnstableFeatures;

// lint_ungated_async_fn_track_caller
pub(crate) struct BuiltinUngatedAsyncFnTrackCaller<'a> {
    pub label: Span,
    pub session: &'a Session,
}

impl<'a> Diagnostic<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(dcx, level, "`#[track_caller]` on async functions is a no-op")
            .with_span_label(self.label, "this function will not propagate the caller location");
        crate::rustc_session::diagnostics::add_feature_diagnostics(
            &mut diag,
            self.session,
            sym::async_fn_track_caller,
        );
        diag
    }
}

#[derive(Diagnostic)]
#[diag("unreachable `pub` {$what}")]
pub(crate) struct BuiltinUnreachablePub<'a> {
    pub what: &'a str,
    pub new_vis: &'a str,
    #[suggestion("consider restricting its visibility", code = "{new_vis}")]
    pub suggestion: (Span, Applicability),
    #[help("or consider exporting it for use by other crates")]
    pub help: bool,
}

#[derive(Diagnostic)]
#[diag("the `expr` fragment specifier will accept more expressions in the 2024 edition")]
pub(crate) struct MacroExprFragment2024 {
    #[suggestion(
        "to keep the existing behavior, use the `expr_2021` fragment specifier",
        code = "expr_2021",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
}

pub(crate) struct BuiltinTypeAliasBounds<'hir> {
    pub in_where_clause: bool,
    pub label: Span,
    pub enable_feat_help: bool,
    pub suggestions: Vec<(Span, String)>,
    pub preds: &'hir [hir::WherePredicate<'hir>],
    pub ty: Option<&'hir hir::Ty<'hir>>,
}

impl<'a> Diagnostic<'a, ()> for BuiltinTypeAliasBounds<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(dcx, level, if self.in_where_clause {
            msg!("where clauses on type aliases are not enforced")
        } else {
            msg!("bounds on generic parameters in type aliases are not enforced")
        })
            .with_span_label(self.label, msg!("will not be checked at usage sites of the type alias"))
            .with_note(msg!(
                "this is a known limitation of the type checker that may be lifted in a future edition.
                see issue #112792 <https://github.com/rust-lang/rust/issues/112792> for more information"
            ));
        if self.enable_feat_help {
            diag.help(msg!("add `#![feature(checked_type_aliases)]` to the crate attributes to enable the desired semantics"));
        }

        // We perform the walk in here instead of in `<TypeAliasBounds as LateLintPass>` to
        // avoid doing throwaway work in case the lint ends up getting suppressed.
        let mut collector = ShorthandAssocTyCollector { qselves: Vec::new() };
        if let Some(ty) = self.ty {
            collector.visit_ty_unambig(ty);
        }

        let affect_object_lifetime_defaults = self
            .preds
            .iter()
            .filter(|pred| pred.kind.in_where_clause() == self.in_where_clause)
            .any(|pred| TypeAliasBounds::affects_object_lifetime_defaults(pred));

        // If there are any shorthand assoc tys, then the bounds can't be removed automatically.
        // The user first needs to fully qualify the assoc tys.
        let applicability = if !collector.qselves.is_empty() || affect_object_lifetime_defaults {
            Applicability::MaybeIncorrect
        } else {
            Applicability::MachineApplicable
        };

        diag.arg("count", self.suggestions.len());
        diag.multipart_suggestion(
            if self.in_where_clause {
                msg!("remove this where clause")
            } else {
                msg!(
                    "remove {$count ->
                        [one] this bound
                        *[other] these bounds
                    }"
                )
            },
            self.suggestions,
            applicability,
        );

        // Suggest fully qualifying paths of the form `T::Assoc` with `T` type param via
        // `<T as /* Trait */>::Assoc` to remove their reliance on any type param bounds.
        //
        // Instead of attempting to figure out the necessary trait ref, just use a
        // placeholder. Since we don't record type-dependent resolutions for non-body
        // items like type aliases, we can't simply deduce the corresp. trait from
        // the HIR path alone without rerunning parts of HIR ty lowering here
        // (namely `probe_single_ty_param_bound_for_assoc_ty`) which is infeasible.
        //
        // (We could employ some simple heuristics but that's likely not worth it).
        for qself in collector.qselves {
            diag.multipart_suggestion(
                msg!("fully qualify this associated type"),
                vec![
                    (qself.shrink_to_lo(), "<".into()),
                    (qself.shrink_to_hi(), " as /* Trait */>".into()),
                ],
                Applicability::HasPlaceholders,
            );
        }
        diag
    }
}

#[derive(Diagnostic)]
#[diag("{$clause_kind_name} bound {$clause} does not depend on any type or lifetime parameters")]
pub(crate) struct BuiltinTrivialBounds<'a> {
    pub clause_kind_name: &'a str,
    pub clause: Clause<'a>,
}

#[derive(Diagnostic)]
#[diag("use of a double negation")]
#[note(
    "the prefix `--` could be misinterpreted as a decrement operator which exists in other languages"
)]
#[note("use `-= 1` if you meant to decrement the value")]
pub(crate) struct BuiltinDoubleNegations {
    #[subdiagnostic]
    pub add_parens: BuiltinDoubleNegationsAddParens,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion("add parentheses for clarity", applicability = "maybe-incorrect")]
pub(crate) struct BuiltinDoubleNegationsAddParens {
    #[suggestion_part(code = "(")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

#[derive(Diagnostic)]
pub(crate) enum BuiltinEllipsisInclusiveRangePatternsLint {
    #[diag("`...` range patterns are deprecated")]
    Parenthesise {
        #[suggestion(
            "use `..=` for an inclusive range",
            code = "{replace}",
            applicability = "machine-applicable"
        )]
        suggestion: Span,
        replace: String,
    },
    #[diag("`...` range patterns are deprecated")]
    NonParenthesise {
        #[suggestion(
            "use `..=` for an inclusive range",
            style = "short",
            code = "..=",
            applicability = "machine-applicable"
        )]
        suggestion: Span,
    },
}

#[derive(Diagnostic)]
#[diag("`{$kw}` is a keyword in the {$next} edition")]
pub(crate) struct BuiltinKeywordIdents {
    pub kw: Ident,
    pub next: Edition,
    #[suggestion(
        "you can use a raw identifier to stay compatible",
        code = "{prefix}r#{kw}",
        applicability = "machine-applicable"
    )]
    pub suggestion: Span,
    pub prefix: &'static str,
}

#[derive(Diagnostic)]
#[diag("outlives requirements can be inferred")]
pub(crate) struct BuiltinExplicitOutlives {
    #[subdiagnostic]
    pub suggestion: BuiltinExplicitOutlivesSuggestion,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "remove {$count ->
        [one] this bound
        *[other] these bounds
    }"
)]
pub(crate) struct BuiltinExplicitOutlivesSuggestion {
    #[suggestion_part(code = "")]
    pub spans: Vec<Span>,
    #[applicability]
    pub applicability: Applicability,
    pub count: usize,
}

#[derive(Diagnostic)]
#[diag(
    "the feature `{$name}` is incomplete and may not be safe to use and/or cause compiler crashes"
)]
pub(crate) struct BuiltinIncompleteFeatures {
    pub name: Symbol,
    #[subdiagnostic]
    pub note: Option<BuiltinFeatureIssueNote>,
    #[subdiagnostic]
    pub help: Option<BuiltinIncompleteFeaturesHelp>,
}

#[derive(Diagnostic)]
#[diag("the feature `{$name}` is internal to the compiler or standard library")]
#[note("using it is strongly discouraged")]
pub(crate) struct BuiltinInternalFeatures {
    pub name: Symbol,
}

#[derive(Subdiagnostic)]
#[help("consider using `min_{$name}` instead, which is more stable and complete")]
pub(crate) struct BuiltinIncompleteFeaturesHelp {
    pub name: Symbol,
}

#[derive(Subdiagnostic)]
#[note("see issue #{$n} <https://github.com/rust-lang/rust/issues/{$n}> for more information")]
pub(crate) struct BuiltinFeatureIssueNote {
    pub n: NonZero<u32>,
}

pub(crate) struct BuiltinUnpermittedTypeInit<'a> {
    pub msg: DiagMessage,
    pub ty: Ty<'a>,
    pub label: Span,
    pub sub: BuiltinUnpermittedTypeInitSub,
    pub tcx: TyCtxt<'a>,
}

impl<'a> Diagnostic<'a, ()> for BuiltinUnpermittedTypeInit<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(dcx, level, self.msg)
            .with_arg("ty", self.ty)
            .with_span_label(self.label, msg!("this code causes undefined behavior when executed"));
        if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) {
            // Only suggest late `MaybeUninit::assume_init` initialization if the type is inhabited.
            diag.span_label(
                self.label,
                msg!("help: use `MaybeUninit<T>` instead, and only call `assume_init` after initialization is done"),
            );
        }
        self.sub.add_to_diag(&mut diag);
        diag
    }
}

// FIXME(davidtwco): make translatable
pub(crate) struct BuiltinUnpermittedTypeInitSub {
    pub err: InitError,
}

impl Subdiagnostic for BuiltinUnpermittedTypeInitSub {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        let mut err = self.err;
        loop {
            if let Some(span) = err.span {
                diag.span_note(span, err.message);
            } else {
                diag.note(err.message);
            }
            if let Some(e) = err.nested {
                err = *e;
            } else {
                break;
            }
        }
    }
}

#[derive(Diagnostic)]
pub(crate) enum BuiltinClashingExtern<'a> {
    #[diag("`{$this}` redeclared with a different signature")]
    SameName {
        this: Symbol,
        orig: Symbol,
        #[label("`{$orig}` previously declared here")]
        previous_decl_label: Span,
        #[label("this signature doesn't match the previous declaration")]
        mismatch_label: Span,
        #[subdiagnostic]
        sub: BuiltinClashingExternSub<'a>,
    },
    #[diag("`{$this}` redeclares `{$orig}` with a different signature")]
    DiffName {
        this: Symbol,
        orig: Symbol,
        #[label("`{$orig}` previously declared here")]
        previous_decl_label: Span,
        #[label("this signature doesn't match the previous declaration")]
        mismatch_label: Span,
        #[subdiagnostic]
        sub: BuiltinClashingExternSub<'a>,
    },
}

// FIXME(davidtwco): translatable expected/found
pub(crate) struct BuiltinClashingExternSub<'a> {
    pub tcx: TyCtxt<'a>,
    pub expected: Ty<'a>,
    pub found: Ty<'a>,
}

impl Subdiagnostic for BuiltinClashingExternSub<'_> {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        let mut expected_str = DiagStyledString::new();
        expected_str.push(self.expected.fn_sig(self.tcx).to_string(), false);
        let mut found_str = DiagStyledString::new();
        found_str.push(self.found.fn_sig(self.tcx).to_string(), true);
        diag.note_expected_found("", expected_str, "", found_str);
    }
}

#[derive(Diagnostic)]
#[diag("dereferencing a null pointer")]
pub(crate) struct BuiltinDerefNullptr {
    #[label("this code causes undefined behavior when executed")]
    pub label: Span,
}

#[derive(Diagnostic)]
pub(crate) enum BuiltinSpecialModuleNameUsed {
    #[diag("found module declaration for lib.rs")]
    #[note("lib.rs is the root of this crate's library target")]
    #[help("to refer to it from other targets, use the library's name as the path")]
    Lib,
    #[diag("found module declaration for main.rs")]
    #[note("a binary crate cannot be used as library")]
    Main,
}

// c_void_return.rs
#[derive(Diagnostic)]
#[diag("`c_void` should not be used as a return type")]
#[help("returning `()` in Rust is equivalent to returning `void` in C")]
pub(crate) struct CVoidReturn {
    #[suggestion(
        "remove the return type to implicitly return `()`",
        code = "",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

// c_void_return.rs
#[derive(Diagnostic)]
#[diag("declarations returning `c_void` are not compatible with C functions returning `void`")]
#[help("returning `()` in Rust is equivalent to returning `void` in C")]
#[note("`c_void` is only used through raw pointers for compatibility with `void` pointers")]
pub(crate) struct ExternCVoidReturn {
    #[suggestion(
        "remove the return type to implicitly return `()`",
        code = "",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

// deref_into_dyn_supertrait.rs
#[derive(Diagnostic)]
#[diag("this `Deref` implementation is covered by an implicit supertrait coercion")]
pub(crate) struct SupertraitAsDerefTarget<'a> {
    pub self_ty: Ty<'a>,
    pub supertrait_principal: PolyExistentialTraitRef<'a>,
    pub target_principal: PolyExistentialTraitRef<'a>,
    #[label(
        "`{$self_ty}` implements `Deref<Target = dyn {$target_principal}>` which conflicts with supertrait `{$supertrait_principal}`"
    )]
    pub label: Span,
    #[subdiagnostic]
    pub label2: Option<SupertraitAsDerefTargetLabel<'a>>,
}

#[derive(Subdiagnostic)]
#[label("target type is a supertrait of `{$self_ty}`")]
pub(crate) struct SupertraitAsDerefTargetLabel<'a> {
    #[primary_span]
    pub label: Span,
    pub self_ty: Ty<'a>,
}

// enum_intrinsics_non_enums.rs
#[derive(Diagnostic)]
#[diag("the return value of `mem::discriminant` is unspecified when called with a non-enum type")]
pub(crate) struct EnumIntrinsicsMemDiscriminate<'a> {
    pub ty_param: Ty<'a>,
    #[note(
        "the argument to `discriminant` should be a reference to an enum, but it was passed a reference to a `{$ty_param}`, which is not an enum"
    )]
    pub note: Span,
}

#[derive(Diagnostic)]
#[diag("the return value of `mem::variant_count` is unspecified when called with a non-enum type")]
#[note(
    "the type parameter of `variant_count` should be an enum, but it was instantiated with the type `{$ty_param}`, which is not an enum"
)]
pub(crate) struct EnumIntrinsicsMemVariant<'a> {
    pub ty_param: Ty<'a>,
}

// expect.rs
#[derive(Diagnostic)]
#[diag("this lint expectation is unfulfilled")]
pub(crate) struct Expectation {
    #[subdiagnostic]
    pub rationale: Option<ExpectationNote>,
    #[note(
        "the `unfulfilled_lint_expectations` lint can't be expected and will always produce this message"
    )]
    pub note: bool,
}

#[derive(Subdiagnostic)]
#[note("{$rationale}")]
pub(crate) struct ExpectationNote {
    pub rationale: Symbol,
}

// ptr_nulls.rs
#[derive(Diagnostic)]
pub(crate) enum UselessPtrNullChecksDiag<'a> {
    #[diag(
        "function pointers are not nullable, so checking them for null will always return false"
    )]
    #[help(
        "wrap the function pointer inside an `Option` and use `Option::is_none` to check for null pointer value"
    )]
    FnPtr {
        orig_ty: Ty<'a>,
        #[label("expression has type `{$orig_ty}`")]
        label: Span,
    },
    #[diag("references are not nullable, so checking them for null will always return false")]
    Ref {
        orig_ty: Ty<'a>,
        #[label("expression has type `{$orig_ty}`")]
        label: Span,
    },
    #[diag(
        "returned pointer of `{$fn_name}` call is never null, so checking it for null will always return false"
    )]
    FnRet { fn_name: Ident },
}

#[derive(Diagnostic)]
pub(crate) enum InvalidNullArgumentsDiag {
    #[diag(
        "calling this function with a null pointer is undefined behavior, even if the result of the function is unused"
    )]
    #[help(
        "for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>"
    )]
    NullPtrInline {
        #[label("null pointer originates from here")]
        null_span: Span,
    },
    #[diag(
        "calling this function with a null pointer is undefined behavior, even if the result of the function is unused"
    )]
    #[help(
        "for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>"
    )]
    NullPtrThroughBinding {
        #[note("null pointer originates from here")]
        null_span: Span,
    },
}

// for_loops_over_fallibles.rs
#[derive(Diagnostic)]
#[diag(
    "for loop over {$article} `{$ref_prefix}{$ty}`. This is more readably written as an `if let` statement"
)]
pub(crate) struct ForLoopsOverFalliblesDiag<'a> {
    pub article: &'static str,
    pub ref_prefix: &'static str,
    pub ty: &'static str,
    #[subdiagnostic]
    pub sub: ForLoopsOverFalliblesLoopSub<'a>,
    #[subdiagnostic]
    pub question_mark: Option<ForLoopsOverFalliblesQuestionMark>,
    #[subdiagnostic]
    pub suggestion: ForLoopsOverFalliblesSuggestion<'a>,
}

#[derive(Subdiagnostic)]
pub(crate) enum ForLoopsOverFalliblesLoopSub<'a> {
    #[suggestion(
        "to iterate over `{$recv_snip}` remove the call to `next`",
        code = ".by_ref()",
        applicability = "maybe-incorrect"
    )]
    RemoveNext {
        #[primary_span]
        suggestion: Span,
        recv_snip: String,
    },
    #[multipart_suggestion(
        "to check pattern in a loop use `while let`",
        applicability = "maybe-incorrect"
    )]
    UseWhileLet {
        #[suggestion_part(code = "while let {var}(")]
        start_span: Span,
        #[suggestion_part(code = ") = ")]
        end_span: Span,
        var: &'a str,
    },
}

#[derive(Subdiagnostic)]
#[suggestion(
    "consider unwrapping the `Result` with `?` to iterate over its contents",
    code = "?",
    applicability = "maybe-incorrect"
)]
pub(crate) struct ForLoopsOverFalliblesQuestionMark {
    #[primary_span]
    pub suggestion: Span,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "consider using `if let` to clear intent",
    applicability = "maybe-incorrect"
)]
pub(crate) struct ForLoopsOverFalliblesSuggestion<'a> {
    pub var: &'a str,
    #[suggestion_part(code = "if let {var}(")]
    pub start_span: Span,
    #[suggestion_part(code = ") = ")]
    pub end_span: Span,
}

#[derive(Subdiagnostic)]
pub(crate) enum UseLetUnderscoreIgnoreSuggestion {
    #[note("use `let _ = ...` to ignore the expression or result")]
    Note,
    #[multipart_suggestion(
        "use `let _ = ...` to ignore the expression or result",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    Suggestion {
        #[suggestion_part(code = "let _ = ")]
        start_span: Span,
        #[suggestion_part(code = "")]
        end_span: Span,
    },
}

// runtime_symbols.rs
#[derive(Diagnostic)]
pub(crate) enum RedefiningRuntimeSymbolsDiag<'tcx> {
    #[diag(
        "invalid definition of the runtime `{$symbol_name}` symbol used by the standard library"
    )]
    #[note(
        "expected `{$expected_fn_sig}` (for the current target)
    found    `{$found_fn_sig}`"
    )]
    #[help(
        "either fix the signature or remove any attributes like `#[unsafe(no_mangle)]`, `#[unsafe(export_name = \"{$symbol_name}\")]`, or `#[link_name = \"{$symbol_name}\"]`"
    )]
    Invalid { symbol_name: String, expected_fn_sig: Ty<'tcx>, found_fn_sig: Ty<'tcx> },
    #[diag(
        "suspicious definition of the runtime `{$symbol_name}` symbol used by the standard library"
    )]
    #[note(
        "expected `{$expected_fn_sig}` (for the current target)
    found    `{$found_fn_sig}`"
    )]
    #[help(
        "either fix the signature or remove any attributes like `#[unsafe(no_mangle)]`, `#[unsafe(export_name = \"{$symbol_name}\")]`, or `#[link_name = \"{$symbol_name}\"]`"
    )]
    #[help("allow this lint if the signature is compatible")]
    Suspicious { symbol_name: String, expected_fn_sig: Ty<'tcx>, found_fn_sig: Ty<'tcx> },
}

// drop_forget_useless.rs
#[derive(Diagnostic)]
#[diag("calls to `core::mem::drop` with a reference instead of an owned value does nothing")]
pub(crate) struct DropRefDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag("calls to `core::mem::drop` with a value that implements `Copy` does nothing")]
pub(crate) struct DropCopyDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag(
    "calls to {$from_fn ->
        [true] `core::ptr::drop_in_place`
        *[false] `drop_in_place`
    } with a pointer to a reference instead of a pointer to an owned value does nothing"
)]
pub(crate) struct DropInPlaceRefDiag<'a> {
    pub from_fn: bool,
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag(
    "calls to {$from_fn ->
        [true] `core::ptr::drop_in_place`
        *[false] `drop_in_place`
    } with a pointer to a value that implements `Copy` does nothing"
)]
pub(crate) struct DropInPlaceCopyDiag<'a> {
    pub from_fn: bool,
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag("calls to `core::mem::forget` with a reference instead of an owned value does nothing")]
pub(crate) struct ForgetRefDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag("calls to `core::mem::forget` with a value that implements `Copy` does nothing")]
pub(crate) struct ForgetCopyDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub sugg: UseLetUnderscoreIgnoreSuggestion,
}

#[derive(Diagnostic)]
#[diag(
    "calls to `core::mem::drop` with `core::mem::ManuallyDrop` instead of the inner value does nothing"
)]
pub(crate) struct UndroppedManuallyDropsDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub suggestion: UndroppedManuallyDropsSuggestion,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use `core::mem::ManuallyDrop::into_inner` to get the inner value",
    applicability = "machine-applicable"
)]
pub(crate) struct UndroppedManuallyDropsSuggestion {
    #[suggestion_part(code = "core::mem::ManuallyDrop::into_inner(")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

#[derive(Diagnostic)]
#[diag(
    "calls to `drop_in_place` with a pointer to a `core::mem::ManuallyDrop` instead of the inner value does nothing"
)]
pub(crate) struct UndroppedManuallyDropsInPlaceDiag<'a> {
    pub arg_ty: Ty<'a>,
    #[label("argument has type `{$arg_ty}`")]
    pub label: Span,
    #[subdiagnostic]
    pub suggestion: UndroppedManuallyDropsInPlaceSuggestion,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use `core::mem::ManuallyDrop::drop` to drop the inner value",
    applicability = "maybe-incorrect"
)]
pub(crate) struct UndroppedManuallyDropsInPlaceSuggestion {
    #[suggestion_part(code = "core::mem::ManuallyDrop::drop(&mut *")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

// invalid_from_utf8.rs
#[derive(Diagnostic)]
pub(crate) enum InvalidFromUtf8Diag {
    #[diag("calls to `{$method}` with an invalid literal are undefined behavior")]
    Unchecked {
        method: String,
        valid_up_to: usize,
        #[label("the literal was valid UTF-8 up to the {$valid_up_to} bytes")]
        label: Span,
    },
    #[diag("calls to `{$method}` with an invalid literal always return an error")]
    Checked {
        method: String,
        valid_up_to: usize,
        #[label("the literal was valid UTF-8 up to the {$valid_up_to} bytes")]
        label: Span,
    },
}

// interior_mutable_consts.rs
#[derive(Diagnostic)]
#[diag("mutation of an interior mutable `const` item with call to `{$method_name}`")]
#[note("each usage of a `const` item creates a new temporary")]
#[note("only the temporaries and never the original `const {$const_name}` will be modified")]
#[help(
    "for more details on interior mutability see <https://doc.rust-lang.org/reference/interior-mutability.html>"
)]
pub(crate) struct ConstItemInteriorMutationsDiag<'tcx> {
    pub method_name: Ident,
    pub const_name: Ident,
    pub const_ty: Ty<'tcx>,
    #[label("`{$const_name}` is a interior mutable `const` item of type `{$const_ty}`")]
    pub receiver_span: Span,
    #[subdiagnostic]
    pub sugg_static: Option<ConstItemInteriorMutationsSuggestionStatic>,
}

#[derive(Subdiagnostic)]
pub(crate) enum ConstItemInteriorMutationsSuggestionStatic {
    #[suggestion(
        "for a shared instance of `{$const_name}`, consider making it a `static` item instead",
        code = "{before}static ",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    Spanful {
        #[primary_span]
        const_: Span,
        before: &'static str,
        const_name: Ident,
    },
    #[help("for a shared instance of `{$const_name}`, consider making it a `static` item instead")]
    Spanless { const_name: Ident },
}

// reference_casting.rs
#[derive(Diagnostic)]
pub(crate) enum InvalidReferenceCastingDiag<'tcx> {
    #[diag(
        "casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell`"
    )]
    #[note(
        "for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>"
    )]
    BorrowAsMut {
        #[label("casting happened here")]
        orig_cast: Option<Span>,
    },
    #[diag("assigning to `&T` is undefined behavior, consider using an `UnsafeCell`")]
    #[note(
        "for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>"
    )]
    AssignToRef {
        #[label("casting happened here")]
        orig_cast: Option<Span>,
    },
    #[diag(
        "casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused"
    )]
    #[note("casting from `{$from_ty}` ({$from_size} bytes) to `{$to_ty}` ({$to_size} bytes)")]
    BiggerLayout {
        #[label("casting happened here")]
        orig_cast: Option<Span>,
        #[label("backing allocation comes from here")]
        alloc: Span,
        from_ty: Ty<'tcx>,
        from_size: u64,
        to_ty: Ty<'tcx>,
        to_size: u64,
    },
}

// map_unit_fn.rs
#[derive(Diagnostic)]
#[diag("`Iterator::map` call that discard the iterator's values")]
#[note(
    "`Iterator::map`, like many of the methods on `Iterator`, gets executed lazily, meaning that its effects won't be visible until it is iterated"
)]
pub(crate) struct MappingToUnit {
    #[label("this function returns `()`, which is likely not what you wanted")]
    pub function_label: Span,
    #[label("called `Iterator::map` with callable that returns `()`")]
    pub argument_label: Span,
    #[label(
        "after this call to map, the resulting iterator is `impl Iterator<Item = ()>`, which means the only information carried by the iterator is the number of items"
    )]
    pub map_label: Span,
    #[suggestion(
        "you might have meant to use `Iterator::for_each`",
        style = "verbose",
        code = "for_each",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

// internal.rs
#[derive(Diagnostic)]
#[diag("prefer `{$preferred}` over `{$used}`, it has better performance")]
#[note("a `use crate::rustc_data_structures::fx::{$preferred}` may be necessary")]
pub(crate) struct DefaultHashTypesDiag<'a> {
    pub preferred: &'a str,
    pub used: Symbol,
}

#[derive(Diagnostic)]
#[diag("using `{$query}` can result in unstable query results")]
#[note(
    "if you believe this case to be fine, allow this lint and add a comment explaining your rationale"
)]
pub(crate) struct QueryInstability {
    pub query: Symbol,
}

#[derive(Diagnostic)]
#[diag("`{$method}` accesses information that is not tracked by the query system")]
#[note(
    "if you believe this case to be fine, allow this lint and add a comment explaining your rationale"
)]
pub(crate) struct QueryUntracked {
    pub method: Symbol,
}

#[derive(Diagnostic)]
#[diag("use `.eq_ctxt()` instead of `.ctxt() == .ctxt()`")]
pub(crate) struct SpanUseEqCtxtDiag;

#[derive(Diagnostic)]
#[diag("using `Symbol::intern` on a string literal")]
#[help("consider adding the symbol to `compiler/rustc_span/src/symbol.rs`")]
pub(crate) struct SymbolInternStringLiteralDiag;

#[derive(Diagnostic)]
#[diag("usage of `ty::TyKind::<kind>`")]
pub(crate) struct TykindKind {
    #[suggestion(
        "try using `ty::<kind>` directly",
        code = "ty",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

#[derive(Diagnostic)]
#[diag("usage of `ty::TyKind`")]
#[help("try using `Ty` instead")]
pub(crate) struct TykindDiag;

#[derive(Diagnostic)]
#[diag("usage of qualified `ty::{$ty}`")]
pub(crate) struct TyQualified {
    pub ty: String,
    #[suggestion(
        "try importing it and using it unqualified",
        code = "{ty}",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Span,
}

#[derive(Diagnostic)]
#[diag("do not use `crate::rustc_type_ir::inherent` unless you're inside of the trait solver")]
#[note(
    "the method or struct you're looking for is likely defined somewhere else downstream in the compiler"
)]
pub(crate) struct TypeIrInherentUsage;

#[derive(Diagnostic)]
#[diag(
    "do not use `crate::rustc_type_ir::Interner` or `crate::rustc_type_ir::InferCtxtLike` unless you're inside of the trait solver"
)]
#[note(
    "the method or struct you're looking for is likely defined somewhere else downstream in the compiler"
)]
pub(crate) struct TypeIrTraitUsage;

#[derive(Diagnostic)]
#[diag("do not use `rustc_type_ir` unless you are implementing type system internals")]
#[note("use `crate::rustc_middle::ty` instead")]
pub(crate) struct TypeIrDirectUse;

#[derive(Diagnostic)]
#[diag("non-glob import of `crate::rustc_type_ir::inherent`")]
pub(crate) struct NonGlobImportTypeIrInherent {
    #[suggestion(
        "try using a glob import instead",
        code = "{snippet}",
        applicability = "maybe-incorrect"
    )]
    pub suggestion: Option<Span>,
    pub snippet: &'static str,
}

#[derive(Diagnostic)]
#[diag("implementing `LintPass` by hand")]
#[help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")]
pub(crate) struct LintPassByHand;

#[derive(Diagnostic)]
#[diag("{$msg}")]
pub(crate) struct BadOptAccessDiag<'a> {
    pub msg: &'a str,
}

#[derive(Diagnostic)]
#[diag(
    "dangerous use of `extern crate {$name}` which is not guaranteed to exist exactly once in the sysroot"
)]
#[help(
    "try using a cargo dependency or using a re-export of the dependency provided by a rustc_* crate"
)]
pub(crate) struct ImplicitSysrootCrateImportDiag<'a> {
    pub name: &'a str,
}

#[derive(Diagnostic)]
#[diag("use of `AttributeKind` in `find_attr!(...)` invocation")]
#[note("`find_attr!(...)` already imports `AttributeKind::*`")]
#[help("remove `AttributeKind`")]
pub(crate) struct AttributeKindInFindAttr;

#[derive(Diagnostic)]
#[diag("match is not exhaustive")]
#[help("explicitly list all variants of the enum in a `match`")]
pub(crate) struct RustcMustMatchExhaustivelyNotExhaustive {
    #[label("required because of this attribute")]
    pub attr_span: Span,

    #[note("{$message}")]
    pub pat_span: Span,
    pub message: &'static str,
}

// let_underscore.rs
#[derive(Diagnostic)]
pub(crate) enum NonBindingLet {
    #[diag("non-binding let on a synchronization lock")]
    SyncLock {
        #[label("this lock is not assigned to a binding and is immediately dropped")]
        pat: Span,
        #[subdiagnostic]
        sub: NonBindingLetSub,
    },
    #[diag("non-binding let on a type that has a destructor")]
    DropType {
        #[subdiagnostic]
        sub: NonBindingLetSub,
    },
}

pub(crate) struct NonBindingLetSub {
    pub suggestion: Span,
    pub drop_fn_start_end: Option<(Span, Span)>,
    pub is_assign_desugar: bool,
}

impl Subdiagnostic for NonBindingLetSub {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        let can_suggest_binding = self.drop_fn_start_end.is_some() || !self.is_assign_desugar;

        if can_suggest_binding {
            let prefix = if self.is_assign_desugar { "let " } else { "" };
            diag.span_suggestion_verbose(
                self.suggestion,
                msg!(
                    "consider binding to an unused variable to avoid immediately dropping the value"
                ),
                format!("{prefix}_unused"),
                Applicability::MachineApplicable,
            );
        } else {
            diag.span_help(
                self.suggestion,
                msg!(
                    "consider binding to an unused variable to avoid immediately dropping the value"
                ),
            );
        }
        if let Some(drop_fn_start_end) = self.drop_fn_start_end {
            diag.multipart_suggestion(
                msg!("consider immediately dropping the value"),
                vec![
                    (drop_fn_start_end.0, "drop(".to_string()),
                    (drop_fn_start_end.1, ")".to_string()),
                ],
                Applicability::MachineApplicable,
            );
        } else {
            diag.help(msg!(
                "consider immediately dropping the value using `drop(..)` after the `let` statement"
            ));
        }
    }
}

// levels.rs
#[derive(Diagnostic)]
#[diag("{$lint_level}({$lint_source}) incompatible with previous forbid")]
pub(crate) struct OverruledAttributeLint<'a> {
    #[label("overruled by previous forbid")]
    pub overruled: Span,
    pub lint_level: &'a str,
    pub lint_source: Symbol,
    #[subdiagnostic]
    pub sub: OverruledAttributeSub,
}

#[derive(Diagnostic)]
#[diag("lint name `{$name}` is deprecated and may not have an effect in the future")]
pub(crate) struct DeprecatedLintName<'a> {
    pub name: String,
    #[suggestion("change it to", code = "{replace}", applicability = "machine-applicable")]
    pub suggestion: Span,
    pub replace: &'a str,
}

#[derive(Diagnostic)]
#[diag("lint name `{$name}` is deprecated and may not have an effect in the future")]
#[help("change it to {$replace}")]
pub(crate) struct DeprecatedLintNameFromCommandLine<'a> {
    pub name: String,
    pub replace: &'a str,
    #[subdiagnostic]
    pub requested_level: RequestedLevel<'a>,
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been renamed to `{$replace}`")]
pub(crate) struct RenamedLint<'a> {
    pub name: &'a str,
    pub replace: &'a str,
    #[subdiagnostic]
    pub suggestion: RenamedLintSuggestion<'a>,
}

#[derive(Subdiagnostic)]
pub(crate) enum RenamedLintSuggestion<'a> {
    #[suggestion("use the new name", code = "{replace}", applicability = "machine-applicable")]
    WithSpan {
        #[primary_span]
        suggestion: Span,
        replace: &'a str,
    },
    #[help("use the new name `{$replace}`")]
    WithoutSpan { replace: &'a str },
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been renamed to `{$replace}`")]
pub(crate) struct RenamedLintFromCommandLine<'a> {
    pub name: &'a str,
    pub replace: &'a str,
    #[subdiagnostic]
    pub suggestion: RenamedLintSuggestion<'a>,
    #[subdiagnostic]
    pub requested_level: RequestedLevel<'a>,
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been removed: {$reason}")]
pub(crate) struct RemovedLint<'a> {
    pub name: &'a str,
    pub reason: &'a str,
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been removed: {$reason}")]
pub(crate) struct RemovedLintFromCommandLine<'a> {
    pub name: &'a str,
    pub reason: &'a str,
    #[subdiagnostic]
    pub requested_level: RequestedLevel<'a>,
}

#[derive(Diagnostic)]
#[diag("unknown lint: `{$name}`")]
pub(crate) struct UnknownLint {
    pub name: String,
    #[subdiagnostic]
    pub suggestion: Option<UnknownLintSuggestion>,
}

#[derive(Subdiagnostic)]
pub(crate) enum UnknownLintSuggestion {
    #[suggestion(
        "{$from_rustc ->
            [true] a lint with a similar name exists in `rustc` lints
            *[false] did you mean
        }",
        code = "{replace}",
        applicability = "maybe-incorrect"
    )]
    WithSpan {
        #[primary_span]
        suggestion: Span,
        replace: Symbol,
        from_rustc: bool,
    },
    #[help(
        "{$from_rustc ->
            [true] a lint with a similar name exists in `rustc` lints: `{$replace}`
            *[false] did you mean: `{$replace}`
        }"
    )]
    WithoutSpan { replace: Symbol, from_rustc: bool },
}

#[derive(Diagnostic)]
#[diag("unknown lint: `{$name}`", code = E0602)]
pub(crate) struct UnknownLintFromCommandLine<'a> {
    pub name: String,
    #[subdiagnostic]
    pub suggestion: Option<UnknownLintSuggestion>,
    #[subdiagnostic]
    pub requested_level: RequestedLevel<'a>,
}

#[derive(Diagnostic)]
#[diag("{$level}({$name}) is ignored unless specified at crate level")]
pub(crate) struct IgnoredUnlessCrateSpecified<'a> {
    pub level: &'a str,
    pub name: Symbol,
}

// dangling.rs
#[derive(Diagnostic)]
#[diag("this creates a dangling pointer because temporary `{$ty}` is dropped at end of statement")]
#[help("bind the `{$ty}` to a variable such that it outlives the pointer returned by `{$callee}`")]
#[note("a dangling pointer is safe, but dereferencing one is undefined behavior")]
#[note("returning a pointer to a local variable will always result in a dangling pointer")]
#[note("for more information, see <https://doc.rust-lang.org/reference/destructors.html>")]
// FIXME: put #[primary_span] on `ptr_span` once it does not cause conflicts
pub(crate) struct DanglingPointersFromTemporaries<'tcx> {
    pub callee: Ident,
    pub ty: Ty<'tcx>,
    #[label("pointer created here")]
    pub ptr_span: Span,
    #[label("this `{$ty}` is dropped at end of statement")]
    pub temporary_span: Span,
}

#[derive(Diagnostic)]
#[diag("{$fn_kind} returns a dangling pointer to dropped local variable `{$local_var_name}`")]
#[note("a dangling pointer is safe, but dereferencing one is undefined behavior")]
#[note("for more information, see <https://doc.rust-lang.org/reference/destructors.html>")]
pub(crate) struct DanglingPointersFromLocals<'tcx> {
    pub ret_ty: Ty<'tcx>,
    #[label("return type is `{$ret_ty}`")]
    pub ret_ty_span: Span,
    pub fn_kind: &'static str,
    #[label("local variable `{$local_var_name}` is dropped at the end of the {$fn_kind}")]
    pub local_var: Span,
    pub local_var_name: Ident,
    pub local_var_ty: Ty<'tcx>,
    #[label("dangling pointer created here")]
    pub created_at: Option<Span>,
}

// multiple_supertrait_upcastable.rs
#[derive(Diagnostic)]
#[diag("`{$ident}` is dyn-compatible and has multiple supertraits")]
pub(crate) struct MultipleSupertraitUpcastable {
    pub ident: Ident,
}

// non_ascii_idents.rs
#[derive(Diagnostic)]
#[diag("identifier contains non-ASCII characters")]
pub(crate) struct IdentifierNonAsciiChar;

#[derive(Diagnostic)]
#[diag(
    "identifier contains {$codepoints_len ->
        [one] { $identifier_type ->
            [Exclusion] a character from an archaic script
            [Technical] a character that is for non-linguistic, specialized usage
            [Limited_Use] a character from a script in limited use
            [Not_NFKC] a non normalized (NFKC) character
            *[other] an uncommon character
        }
        *[other] { $identifier_type ->
            [Exclusion] {$codepoints_len} characters from archaic scripts
            [Technical] {$codepoints_len} characters that are for non-linguistic, specialized usage
            [Limited_Use] {$codepoints_len} characters from scripts in limited use
            [Not_NFKC] {$codepoints_len} non normalized (NFKC) characters
            *[other] uncommon characters
        }
    }: {$codepoints}"
)]
#[note(
    r#"{$codepoints_len ->
        [one] this character is
        *[other] these characters are
    } included in the{$identifier_type ->
        [Restricted] {""}
        *[other] {" "}{$identifier_type}
    } Unicode general security profile"#
)]
pub(crate) struct IdentifierUncommonCodepoints {
    pub codepoints: Vec<char>,
    pub codepoints_len: usize,
    pub identifier_type: &'static str,
}

#[derive(Diagnostic)]
#[diag("found both `{$existing_sym}` and `{$sym}` as identifiers, which look alike")]
pub(crate) struct ConfusableIdentifierPair {
    pub existing_sym: Symbol,
    pub sym: Symbol,
    #[label("other identifier used here")]
    pub label: Span,
    #[label("this identifier can be confused with `{$existing_sym}`")]
    pub main_label: Span,
}

#[derive(Diagnostic)]
#[diag(
    "the usage of Script Group `{$set}` in this crate consists solely of mixed script confusables"
)]
#[note("the usage includes {$includes}")]
#[note("please recheck to make sure their usages are indeed what you want")]
pub(crate) struct MixedScriptConfusables {
    pub set: String,
    pub includes: String,
}

// non_fmt_panic.rs
pub(crate) struct NonFmtPanicUnused {
    pub count: usize,
    pub suggestion: Option<Span>,
}

// Used because of two suggestions based on one Option<Span>
impl<'a> Diagnostic<'a, ()> for NonFmtPanicUnused {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(dcx, level, msg!(
            "panic message contains {$count ->
                [one] an unused
                *[other] unused
            } formatting {$count ->
                [one] placeholder
                *[other] placeholders
            }"
        ))
            .with_arg("count", self.count)
            .with_note(msg!("this message is not used as a format string when given without arguments, but will be in Rust 2021"));
        if let Some(span) = self.suggestion {
            diag.span_suggestion(
                span.shrink_to_hi(),
                msg!(
                    "add the missing {$count ->
                        [one] argument
                        *[other] arguments
                    }"
                ),
                ", ...",
                Applicability::HasPlaceholders,
            );
            diag.span_suggestion(
                span.shrink_to_lo(),
                msg!(r#"or add a "{"{"}{"}"}" format string to use the message literally"#),
                "\"{}\", ",
                Applicability::MachineApplicable,
            );
        }
        diag
    }
}

#[derive(Diagnostic)]
#[diag(
    "panic message contains {$count ->
        [one] a brace
        *[other] braces
    }"
)]
#[note("this message is not used as a format string, but will be in Rust 2021")]
pub(crate) struct NonFmtPanicBraces {
    pub count: usize,
    #[suggestion(
        "add a \"{\"{\"}{\"}\"}\" format string to use the message literally",
        code = "\"{{}}\", ",
        applicability = "machine-applicable"
    )]
    pub suggestion: Option<Span>,
}

// nonstandard_style.rs
#[derive(Diagnostic)]
#[diag("{$sort} `{$name}` should have an upper camel case name")]
pub(crate) struct NonCamelCaseType<'a> {
    pub sort: &'a str,
    pub name: &'a str,
    #[subdiagnostic]
    pub sub: NonCamelCaseTypeSub,
}

#[derive(Subdiagnostic)]
pub(crate) enum NonCamelCaseTypeSub {
    #[label("should have an UpperCamelCase name")]
    Label {
        #[primary_span]
        span: Span,
    },
    #[suggestion(
        "convert the identifier to upper camel case",
        code = "{replace}",
        applicability = "maybe-incorrect"
    )]
    Suggestion {
        #[primary_span]
        span: Span,
        replace: String,
    },
}

#[derive(Diagnostic)]
#[diag("{$sort} `{$name}` should have a snake case name")]
pub(crate) struct NonSnakeCaseDiag<'a> {
    pub sort: &'a str,
    pub name: &'a str,
    #[subdiagnostic]
    pub sub: NonSnakeCaseDiagSub,
}

pub(crate) enum NonSnakeCaseDiagSub {
    Label { span: Span },
    Help { sc: String },
    RenameOrConvertSuggestion { span: Span, suggestion: Ident },
    ConvertSuggestion { span: Span, suggestion: String },
    SuggestionAndNote { sc: String, span: Span },
}

impl Subdiagnostic for NonSnakeCaseDiagSub {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        match self {
            NonSnakeCaseDiagSub::Label { span } => {
                diag.span_label(span, msg!("should have a snake_case name"));
            }
            NonSnakeCaseDiagSub::Help { sc } => {
                diag.arg("sc", sc);
                diag.help(msg!("convert the identifier to snake case: `{$sc}`"));
            }
            NonSnakeCaseDiagSub::ConvertSuggestion { span, suggestion } => {
                diag.span_suggestion(
                    span,
                    msg!("convert the identifier to snake case"),
                    suggestion,
                    Applicability::MaybeIncorrect,
                );
            }
            NonSnakeCaseDiagSub::RenameOrConvertSuggestion { span, suggestion } => {
                diag.span_suggestion(
                    span,
                    msg!("rename the identifier or convert it to a snake case raw identifier"),
                    suggestion,
                    Applicability::MaybeIncorrect,
                );
            }
            NonSnakeCaseDiagSub::SuggestionAndNote { sc, span } => {
                diag.arg("sc", sc);
                diag.note(msg!("`{$sc}` cannot be used as a raw identifier"));
                diag.span_suggestion(
                    span,
                    msg!("rename the identifier"),
                    "",
                    Applicability::MaybeIncorrect,
                );
            }
        }
    }
}

#[derive(Diagnostic)]
#[diag("{$sort} `{$name}` should have an upper case name")]
pub(crate) struct NonUpperCaseGlobal<'a> {
    pub sort: &'a str,
    pub name: &'a str,
    #[subdiagnostic]
    pub sub: NonUpperCaseGlobalSub,
    #[subdiagnostic]
    pub usages: Vec<NonUpperCaseGlobalSubTool>,
}

#[derive(Subdiagnostic)]
pub(crate) enum NonUpperCaseGlobalSub {
    #[label("should have an UPPER_CASE name")]
    Label {
        #[primary_span]
        span: Span,
    },
    #[suggestion("convert the identifier to upper case", code = "{replace}")]
    Suggestion {
        #[primary_span]
        span: Span,
        #[applicability]
        applicability: Applicability,
        replace: String,
    },
}

#[derive(Subdiagnostic)]
#[suggestion(
    "convert the identifier to upper case",
    code = "{replace}",
    applicability = "machine-applicable",
    style = "tool-only"
)]
pub(crate) struct NonUpperCaseGlobalSubTool {
    #[primary_span]
    pub(crate) span: Span,
    pub(crate) replace: String,
}

// noop_method_call.rs
#[derive(Diagnostic)]
#[diag("call to `.{$method}()` on a reference in this situation does nothing")]
#[note(
    "the type `{$orig_ty}` does not implement `{$trait_}`, so calling `{$method}` on `&{$orig_ty}` copies the reference, which does not do anything and can be removed"
)]
pub(crate) struct NoopMethodCallDiag<'a> {
    pub method: Ident,
    pub orig_ty: Ty<'a>,
    pub trait_: Symbol,
    #[suggestion("remove this redundant call", code = "", applicability = "machine-applicable")]
    pub label: Span,
    #[suggestion(
        "if you meant to clone `{$orig_ty}`, implement `Clone` for it",
        code = "#[derive(Clone)]\n",
        applicability = "maybe-incorrect"
    )]
    pub suggest_derive: Option<Span>,
}

#[derive(Diagnostic)]
#[diag(
    "using `.deref()` on a double reference, which returns `{$ty}` instead of dereferencing the inner type"
)]
pub(crate) struct SuspiciousDoubleRefDerefDiag<'a> {
    pub ty: Ty<'a>,
}

#[derive(Diagnostic)]
#[diag(
    "using `.clone()` on a double reference, which returns `{$ty}` instead of cloning the inner type"
)]
pub(crate) struct SuspiciousDoubleRefCloneDiag<'a> {
    pub ty: Ty<'a>,
}

// non_local_defs.rs
pub(crate) enum NonLocalDefinitionsDiag {
    Impl {
        depth: u32,
        body_kind_descr: &'static str,
        body_name: String,
        cargo_update: Option<NonLocalDefinitionsCargoUpdateNote>,
        const_anon: Option<Option<Span>>,
        doctest: bool,
        macro_to_change: Option<(String, &'static str)>,
    },
    MacroRules {
        depth: u32,
        body_kind_descr: &'static str,
        body_name: String,
        doctest: bool,
        cargo_update: Option<NonLocalDefinitionsCargoUpdateNote>,
    },
}

impl<'a> Diagnostic<'a, ()> for NonLocalDefinitionsDiag {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(dcx, level, "");
        match self {
            NonLocalDefinitionsDiag::Impl {
                depth,
                body_kind_descr,
                body_name,
                cargo_update,
                const_anon,
                doctest,
                macro_to_change,
            } => {
                diag.primary_message(msg!("non-local `impl` definition, `impl` blocks should be written at the same level as their item"));
                diag.arg("depth", depth);
                diag.arg("body_kind_descr", body_kind_descr);
                diag.arg("body_name", body_name);

                if let Some((macro_to_change, macro_kind)) = macro_to_change {
                    diag.arg("macro_to_change", macro_to_change);
                    diag.arg("macro_kind", macro_kind);
                    diag.note(msg!("the {$macro_kind} `{$macro_to_change}` defines the non-local `impl`, and may need to be changed"));
                }
                if let Some(cargo_update) = cargo_update {
                    diag.subdiagnostic(cargo_update);
                }

                diag.note(msg!("an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl`"));

                if doctest {
                    diag.help(msg!("make this doc-test a standalone test with its own `fn main() {\"{\"} ... {\"}\"}`"));
                }

                if let Some(const_anon) = const_anon {
                    diag.note(msg!("items in an anonymous const item (`const _: () = {\"{\"} ... {\"}\"}`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint"));
                    if let Some(const_anon) = const_anon {
                        diag.span_suggestion(
                            const_anon,
                            msg!("use a const-anon item to suppress this lint"),
                            "_",
                            Applicability::MachineApplicable,
                        );
                    }
                }
            }
            NonLocalDefinitionsDiag::MacroRules {
                depth,
                body_kind_descr,
                body_name,
                doctest,
                cargo_update,
            } => {
                diag.primary_message(msg!("non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module"));
                diag.arg("depth", depth);
                diag.arg("body_kind_descr", body_kind_descr);
                diag.arg("body_name", body_name);

                if doctest {
                    diag.help(msg!(r#"remove the `#[macro_export]` or make this doc-test a standalone test with its own `fn main() {"{"} ... {"}"}`"#));
                } else {
                    diag.help(msg!(
                        "remove the `#[macro_export]` or move this `macro_rules!` outside the of the current {$body_kind_descr} {$depth ->
                            [one] `{$body_name}`
                            *[other] `{$body_name}` and up {$depth} bodies
                        }"
                    ));
                }

                diag.note(msg!("a `macro_rules!` definition is non-local if it is nested inside an item and has a `#[macro_export]` attribute"));

                if let Some(cargo_update) = cargo_update {
                    diag.subdiagnostic(cargo_update);
                }
            }
        }
        diag
    }
}

#[derive(Subdiagnostic)]
#[note(
    "the {$macro_kind} `{$macro_name}` may come from an old version of the `{$crate_name}` crate, try updating your dependency with `cargo update -p {$crate_name}`"
)]
pub(crate) struct NonLocalDefinitionsCargoUpdateNote {
    pub macro_kind: &'static str,
    pub macro_name: Symbol,
    pub crate_name: Symbol,
}

// precedence.rs
#[derive(Diagnostic)]
#[diag("`-` has lower precedence than method calls, which might be unexpected")]
#[note("e.g. `-4.abs()` equals `-4`; while `(-4).abs()` equals `4`")]
pub(crate) struct AmbiguousNegativeLiteralsDiag {
    #[subdiagnostic]
    pub negative_literal: AmbiguousNegativeLiteralsNegativeLiteralSuggestion,
    #[subdiagnostic]
    pub current_behavior: AmbiguousNegativeLiteralsCurrentBehaviorSuggestion,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "add parentheses around the `-` and the literal to call the method on a negative literal",
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousNegativeLiteralsNegativeLiteralSuggestion {
    #[suggestion_part(code = "(")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "add parentheses around the literal and the method call to keep the current behavior",
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousNegativeLiteralsCurrentBehaviorSuggestion {
    #[suggestion_part(code = "(")]
    pub start_span: Span,
    #[suggestion_part(code = ")")]
    pub end_span: Span,
}

// disallowed_pass_by_ref.rs
#[derive(Diagnostic)]
#[diag("passing `{$ty}` by reference")]
pub(crate) struct DisallowedPassByRefDiag {
    pub ty: String,
    #[suggestion("try passing by value", code = "{ty}", applicability = "maybe-incorrect")]
    pub suggestion: Span,
}

// redundant_semicolon.rs
#[derive(Diagnostic)]
#[diag(
    "unnecessary trailing {$multiple ->
        [true] semicolons
        *[false] semicolon
    }"
)]
pub(crate) struct RedundantSemicolonsDiag {
    pub multiple: bool,
    #[subdiagnostic]
    pub suggestion: Option<RedundantSemicolonsSuggestion>,
}

#[derive(Subdiagnostic)]
#[suggestion(
    "remove {$multiple_semicolons ->
        [true] these semicolons
        *[false] this semicolon
    }",
    code = "",
    applicability = "maybe-incorrect"
)]
pub(crate) struct RedundantSemicolonsSuggestion {
    pub multiple_semicolons: bool,
    #[primary_span]
    pub span: Span,
}

// traits.rs
pub(crate) struct DropTraitConstraintsDiag<'a> {
    pub clause: Clause<'a>,
    pub tcx: TyCtxt<'a>,
    pub def_id: DefId,
}

// Needed for def_path_str
impl<'a> Diagnostic<'a, ()> for DropTraitConstraintsDiag<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        Diag::new(dcx, level, msg!("bounds on `{$clause}` are most likely incorrect, consider instead using `{$needs_drop}` to detect whether a type can be trivially dropped"))
            .with_arg("clause", self.clause)
            .with_arg("needs_drop", self.tcx.def_path_str(self.def_id))
    }
}

pub(crate) struct DropGlue<'a> {
    pub tcx: TyCtxt<'a>,
    pub def_id: DefId,
}

// Needed for def_path_str
impl<'a> Diagnostic<'a, ()> for DropGlue<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        Diag::new(dcx, level, msg!("types that do not implement `Drop` can still have drop glue, consider instead using `{$needs_drop}` to detect whether a type is trivially dropped"))
            .with_arg("needs_drop", self.tcx.def_path_str(self.def_id))
    }
}

// transmute.rs
#[derive(Diagnostic)]
#[diag("transmuting an integer to a pointer creates a pointer without provenance")]
#[note("this is dangerous because dereferencing the resulting pointer is undefined behavior")]
#[note(
    "exposed provenance semantics can be used to create a pointer based on some previously exposed provenance"
)]
#[help(
    "if you truly mean to create a pointer without provenance, use `core::ptr::without_provenance_mut`"
)]
#[help(
    "for more information about transmute, see <https://doc.rust-lang.org/std/mem/fn.transmute.html#transmutation-between-pointers-and-integers>"
)]
#[help(
    "for more information about exposed provenance, see <https://doc.rust-lang.org/std/ptr/index.html#exposed-provenance>"
)]
pub(crate) struct IntegerToPtrTransmutes<'tcx> {
    #[subdiagnostic]
    pub suggestion: Option<IntegerToPtrTransmutesSuggestion<'tcx>>,
}

#[derive(Subdiagnostic)]
pub(crate) enum IntegerToPtrTransmutesSuggestion<'tcx> {
    #[multipart_suggestion(
        "use `core::ptr::with_exposed_provenance{$suffix}` instead to use a previously exposed provenance",
        applicability = "machine-applicable",
        style = "verbose"
    )]
    ToPtr {
        dst: Ty<'tcx>,
        suffix: &'static str,
        #[suggestion_part(code = "core::ptr::with_exposed_provenance{suffix}::<{dst}>(")]
        start_call: Span,
    },
    #[multipart_suggestion(
        "use `core::ptr::with_exposed_provenance{$suffix}` instead to use a previously exposed provenance",
        applicability = "machine-applicable",
        style = "verbose"
    )]
    ToRef {
        dst: Ty<'tcx>,
        suffix: &'static str,
        ref_mutbl: &'static str,
        #[suggestion_part(
            code = "&{ref_mutbl}*core::ptr::with_exposed_provenance{suffix}::<{dst}>("
        )]
        start_call: Span,
    },
}

// types.rs
#[derive(Diagnostic)]
#[diag("range endpoint is out of range for `{$ty}`")]
pub(crate) struct RangeEndpointOutOfRange<'a> {
    pub ty: &'a str,
    #[subdiagnostic]
    pub sub: UseInclusiveRange<'a>,
}

#[derive(Subdiagnostic)]
pub(crate) enum UseInclusiveRange<'a> {
    #[suggestion(
        "use an inclusive range instead",
        code = "{start}..={literal}{suffix}",
        applicability = "machine-applicable"
    )]
    WithoutParen {
        #[primary_span]
        sugg: Span,
        start: String,
        literal: u128,
        suffix: &'a str,
    },
    #[multipart_suggestion("use an inclusive range instead", applicability = "machine-applicable")]
    WithParen {
        #[suggestion_part(code = "=")]
        eq_sugg: Span,
        #[suggestion_part(code = "{literal}{suffix}")]
        lit_sugg: Span,
        literal: u128,
        suffix: &'a str,
    },
}

#[derive(Diagnostic)]
#[diag("literal out of range for `{$ty}`")]
pub(crate) struct OverflowingBinHex<'a> {
    pub ty: &'a str,
    #[subdiagnostic]
    pub sign: OverflowingBinHexSign<'a>,
    #[subdiagnostic]
    pub sub: Option<OverflowingBinHexSub<'a>>,
    #[subdiagnostic]
    pub sign_bit_sub: Option<OverflowingBinHexSignBitSub<'a>>,
}

#[derive(Subdiagnostic)]
pub(crate) enum OverflowingBinHexSign<'a> {
    #[note(
        "the literal `{$lit}` (decimal `{$dec}`) does not fit into the type `{$ty}` and will become `{$actually}{$ty}`"
    )]
    Positive { lit: String, ty: &'a str, actually: String, dec: u128 },
    #[note("the literal `{$lit}` (decimal `{$dec}`) does not fit into the type `{$ty}`")]
    #[note("and the value `-{$lit}` will become `{$actually}{$ty}`")]
    Negative { lit: String, ty: &'a str, actually: String, dec: u128 },
}

#[derive(Subdiagnostic)]
pub(crate) enum OverflowingBinHexSub<'a> {
    #[suggestion(
        "consider using the type `{$suggestion_ty}` instead",
        code = "{sans_suffix}{suggestion_ty}",
        applicability = "machine-applicable"
    )]
    Suggestion {
        #[primary_span]
        span: Span,
        suggestion_ty: &'a str,
        sans_suffix: &'a str,
    },
    #[help("consider using the type `{$suggestion_ty}` instead")]
    Help { suggestion_ty: &'a str },
}

#[derive(Subdiagnostic)]
pub(crate) enum OverflowingBinHexSignBitSub<'a> {
    #[suggestion(
        "to use as a negative number (decimal `{$negative_val}`), consider using the type `{$uint_ty}` for the literal and cast it to `{$int_ty}`",
        code = "{lit_no_suffix}{uint_ty}.cast_signed()",
        applicability = "maybe-incorrect"
    )]
    CastSigned {
        #[primary_span]
        span: Span,
        lit_no_suffix: &'a str,
        negative_val: String,
        uint_ty: &'a str,
        int_ty: &'a str,
    },
    #[suggestion(
        "to use as a negative number (decimal `{$negative_val}`), consider using the type `{$uint_ty}` for the literal and cast it to `{$int_ty}`",
        code = "{lit_no_suffix}{uint_ty} as {int_ty}",
        applicability = "maybe-incorrect"
    )]
    AsCast {
        #[primary_span]
        span: Span,
        lit_no_suffix: &'a str,
        negative_val: String,
        uint_ty: &'a str,
        int_ty: &'a str,
    },
}

#[derive(Diagnostic)]
#[diag("literal out of range for `{$ty}`")]
#[note("the literal `{$lit}` does not fit into the type `{$ty}` whose range is `{$min}..={$max}`")]
pub(crate) struct OverflowingInt<'a> {
    pub ty: &'a str,
    pub lit: String,
    pub min: i128,
    pub max: u128,
    #[subdiagnostic]
    pub help: Option<OverflowingIntHelp<'a>>,
}

#[derive(Subdiagnostic)]
#[help("consider using the type `{$suggestion_ty}` instead")]
pub(crate) struct OverflowingIntHelp<'a> {
    pub suggestion_ty: &'a str,
}

#[derive(Diagnostic)]
#[diag("only `u8` can be cast into `char`")]
pub(crate) struct OnlyCastu8ToChar {
    #[suggestion(
        "use a `char` literal instead",
        code = "'\\u{{{literal:X}}}'",
        applicability = "machine-applicable"
    )]
    pub span: Span,
    pub literal: u128,
}

#[derive(Diagnostic)]
#[diag("literal out of range for `{$ty}`")]
#[note("the literal `{$lit}` does not fit into the type `{$ty}` whose range is `{$min}..={$max}`")]
pub(crate) struct OverflowingUInt<'a> {
    pub ty: &'a str,
    pub lit: String,
    pub min: u128,
    pub max: u128,
}

#[derive(Diagnostic)]
#[diag("literal out of range for `{$ty}`")]
#[note(
    "the literal `{$lit}` does not fit into the type `{$ty}` and will be converted to `{$ty}::INFINITY`"
)]
pub(crate) struct OverflowingLiteral<'a> {
    pub ty: &'a str,
    pub lit: String,
}

#[derive(Diagnostic)]
#[diag("surrogate values are not valid for `char`")]
#[note("`0xD800..=0xDFFF` are reserved for Unicode surrogates and are not valid `char` values")]
pub(crate) struct SurrogateCharCast {
    pub literal: u128,
}

#[derive(Diagnostic)]
#[diag("value exceeds maximum `char` value")]
#[note("maximum valid `char` value is `0x10FFFF`")]
pub(crate) struct TooLargeCharCast {
    pub literal: u128,
}

#[derive(Diagnostic)]
#[diag(
    "repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type"
)]
pub(crate) struct UsesPowerAlignment;

#[derive(Diagnostic)]
#[diag("comparison is useless due to type limits")]
pub(crate) struct UnusedComparisons;

#[derive(Diagnostic)]
pub(crate) enum InvalidNanComparisons {
    #[diag("incorrect NaN comparison, NaN cannot be directly compared to itself")]
    EqNe {
        #[subdiagnostic]
        suggestion: InvalidNanComparisonsSuggestion,
    },
    #[diag("incorrect NaN comparison, NaN is not orderable")]
    LtLeGtGe,
}

#[derive(Subdiagnostic)]
pub(crate) enum InvalidNanComparisonsSuggestion {
    #[multipart_suggestion(
        "use `f32::is_nan()` or `f64::is_nan()` instead",
        style = "verbose",
        applicability = "machine-applicable"
    )]
    Spanful {
        #[suggestion_part(code = "!")]
        neg: Option<Span>,
        #[suggestion_part(code = ".is_nan()")]
        float: Span,
        #[suggestion_part(code = "")]
        nan_plus_binop: Span,
    },
    #[help("use `f32::is_nan()` or `f64::is_nan()` instead")]
    Spanless,
}

#[derive(Diagnostic)]
pub(crate) enum AmbiguousWidePointerComparisons<'a> {
    #[diag(
        "ambiguous wide pointer comparison, the comparison includes metadata which may not be expected"
    )]
    SpanfulEq {
        #[subdiagnostic]
        addr_suggestion: AmbiguousWidePointerComparisonsAddrSuggestion<'a>,
        #[subdiagnostic]
        addr_metadata_suggestion: Option<AmbiguousWidePointerComparisonsAddrMetadataSuggestion<'a>>,
    },
    #[diag(
        "ambiguous wide pointer comparison, the comparison includes metadata which may not be expected"
    )]
    SpanfulCmp {
        #[subdiagnostic]
        cast_suggestion: AmbiguousWidePointerComparisonsCastSuggestion<'a>,
        #[subdiagnostic]
        expect_suggestion: AmbiguousWidePointerComparisonsExpectSuggestion<'a>,
    },
    #[diag(
        "ambiguous wide pointer comparison, the comparison includes metadata which may not be expected"
    )]
    #[help("use explicit `core::ptr::eq` method to compare metadata and addresses")]
    #[help("use `core::ptr::addr_eq` or untyped pointers to only compare their addresses")]
    Spanless,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use explicit `core::ptr::eq` method to compare metadata and addresses",
    style = "verbose",
    // FIXME(#53934): make machine-applicable again
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousWidePointerComparisonsAddrMetadataSuggestion<'a> {
    pub ne: &'a str,
    pub deref_left: &'a str,
    pub deref_right: &'a str,
    pub l_modifiers: &'a str,
    pub r_modifiers: &'a str,
    #[suggestion_part(code = "{ne}core::ptr::eq({deref_left}")]
    pub left: Span,
    #[suggestion_part(code = "{l_modifiers}, {deref_right}")]
    pub middle: Span,
    #[suggestion_part(code = "{r_modifiers})")]
    pub right: Span,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use `core::ptr::addr_eq` or untyped pointers to only compare their addresses",
    style = "verbose",
    // FIXME(#53934): make machine-applicable again
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousWidePointerComparisonsAddrSuggestion<'a> {
    pub(crate) ne: &'a str,
    pub(crate) deref_left: &'a str,
    pub(crate) deref_right: &'a str,
    pub(crate) l_modifiers: &'a str,
    pub(crate) r_modifiers: &'a str,
    #[suggestion_part(code = "{ne}core::ptr::addr_eq({deref_left}")]
    pub(crate) left: Span,
    #[suggestion_part(code = "{l_modifiers}, {deref_right}")]
    pub(crate) middle: Span,
    #[suggestion_part(code = "{r_modifiers})")]
    pub(crate) right: Span,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use untyped pointers to only compare their addresses",
    style = "verbose",
    // FIXME(#53934): make machine-applicable again
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousWidePointerComparisonsCastSuggestion<'a> {
    pub(crate) deref_left: &'a str,
    pub(crate) deref_right: &'a str,
    pub(crate) paren_left: &'a str,
    pub(crate) paren_right: &'a str,
    pub(crate) l_modifiers: &'a str,
    pub(crate) r_modifiers: &'a str,
    #[suggestion_part(code = "({deref_left}")]
    pub(crate) left_before: Option<Span>,
    #[suggestion_part(code = "{l_modifiers}{paren_left}.cast::<()>()")]
    pub(crate) left_after: Span,
    #[suggestion_part(code = "({deref_right}")]
    pub(crate) right_before: Option<Span>,
    #[suggestion_part(code = "{r_modifiers}{paren_right}.cast::<()>()")]
    pub(crate) right_after: Span,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "or expect the lint to compare the pointers metadata and addresses",
    style = "verbose",
    // FIXME(#53934): make machine-applicable again
    applicability = "maybe-incorrect"
)]
pub(crate) struct AmbiguousWidePointerComparisonsExpectSuggestion<'a> {
    pub(crate) paren_left: &'a str,
    pub(crate) paren_right: &'a str,
    // FIXME(#127436): Adjust once resolved
    #[suggestion_part(
        code = r#"{{ #[expect(ambiguous_wide_pointer_comparisons, reason = "...")] {paren_left}"#
    )]
    pub(crate) before: Span,
    #[suggestion_part(code = "{paren_right} }}")]
    pub(crate) after: Span,
}

#[derive(Diagnostic)]
pub(crate) enum UnpredictableFunctionPointerComparisons<'a, 'tcx> {
    #[diag(
        "function pointer comparisons do not produce meaningful results since their addresses are not guaranteed to be unique"
    )]
    #[note("the address of the same function can vary between different codegen units")]
    #[note(
        "furthermore, different functions could have the same address after being merged together"
    )]
    #[note(
        "for more information visit <https://doc.rust-lang.org/nightly/core/ptr/fn.fn_addr_eq.html>"
    )]
    Suggestion {
        #[subdiagnostic]
        sugg: UnpredictableFunctionPointerComparisonsSuggestion<'a, 'tcx>,
    },
    #[diag(
        "function pointer comparisons do not produce meaningful results since their addresses are not guaranteed to be unique"
    )]
    #[note("the address of the same function can vary between different codegen units")]
    #[note(
        "furthermore, different functions could have the same address after being merged together"
    )]
    #[note(
        "for more information visit <https://doc.rust-lang.org/nightly/core/ptr/fn.fn_addr_eq.html>"
    )]
    Warn,
}

#[derive(Subdiagnostic)]
pub(crate) enum UnpredictableFunctionPointerComparisonsSuggestion<'a, 'tcx> {
    #[multipart_suggestion(
        "refactor your code, or use `core::ptr::fn_addr_eq` to suppress the lint",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    FnAddrEq {
        ne: &'a str,
        deref_left: &'a str,
        deref_right: &'a str,
        #[suggestion_part(code = "{ne}core::ptr::fn_addr_eq({deref_left}")]
        left: Span,
        #[suggestion_part(code = ", {deref_right}")]
        middle: Span,
        #[suggestion_part(code = ")")]
        right: Span,
    },
    #[multipart_suggestion(
        "refactor your code, or use `core::ptr::fn_addr_eq` to suppress the lint",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    FnAddrEqWithCast {
        ne: &'a str,
        deref_left: &'a str,
        deref_right: &'a str,
        fn_sig: crate::rustc_middle::ty::PolyFnSig<'tcx>,
        #[suggestion_part(code = "{ne}core::ptr::fn_addr_eq({deref_left}")]
        left: Span,
        #[suggestion_part(code = ", {deref_right}")]
        middle: Span,
        #[suggestion_part(code = " as {fn_sig})")]
        right: Span,
    },
}

pub(crate) struct ImproperCTypes<'a> {
    pub ty: Ty<'a>,
    pub desc: &'a str,
    pub label: Span,
    pub help: Option<DiagMessage>,
    pub note: DiagMessage,
    pub span_note: Option<Span>,
}

// Used because of the complexity of Option<DiagMessage>, DiagMessage, and Option<Span>
impl<'a> Diagnostic<'a, ()> for ImproperCTypes<'_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(
            dcx,
            level,
            msg!("`extern` {$desc} uses type `{$ty}`, which is not FFI-safe"),
        )
        .with_arg("ty", self.ty)
        .with_arg("desc", self.desc)
        .with_span_label(self.label, msg!("not FFI-safe"));
        if let Some(help) = self.help {
            diag.help(help);
        }
        diag.note(self.note);
        if let Some(note) = self.span_note {
            diag.span_note(note, msg!("the type is defined here"));
        }
        diag
    }
}

#[derive(Diagnostic)]
#[diag("passing type `{$ty}` to a function with \"gpu-kernel\" ABI may have unexpected behavior")]
#[help("use primitive types and raw pointers to get reliable behavior")]
pub(crate) struct ImproperGpuKernelArg<'a> {
    pub ty: Ty<'a>,
}

#[derive(Diagnostic)]
#[diag("function with the \"gpu-kernel\" ABI has a mangled name")]
#[help("use `unsafe(no_mangle)` or `unsafe(export_name = \"<name>\")`")]
#[note("mangled names make it hard to find the kernel, this is usually not intended")]
pub(crate) struct MissingGpuKernelExportName;

#[derive(Diagnostic)]
#[diag("enum variant is more than three times larger ({$largest} bytes) than the next largest")]
pub(crate) struct VariantSizeDifferencesDiag {
    pub largest: u64,
}

#[derive(Diagnostic)]
#[diag("atomic loads cannot have `Release` or `AcqRel` ordering")]
#[help("consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`")]
pub(crate) struct AtomicOrderingLoad;

#[derive(Diagnostic)]
#[diag("atomic stores cannot have `Acquire` or `AcqRel` ordering")]
#[help("consider using ordering modes `Release`, `SeqCst` or `Relaxed`")]
pub(crate) struct AtomicOrderingStore;

#[derive(Diagnostic)]
#[diag("memory fences cannot have `Relaxed` ordering")]
#[help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`")]
pub(crate) struct AtomicOrderingFence;

#[derive(Diagnostic)]
#[diag(
    "`{$method}`'s failure ordering may not be `Release` or `AcqRel`, since a failed `{$method}` does not result in a write"
)]
#[help("consider using `Acquire` or `Relaxed` failure ordering instead")]
pub(crate) struct InvalidAtomicOrderingDiag {
    pub method: Symbol,
    #[label("invalid failure ordering")]
    pub fail_order_arg_span: Span,
}

// unused.rs
#[derive(Diagnostic)]
#[diag("unused {$op} that must be used")]
pub(crate) struct UnusedOp<'a> {
    pub op: &'a str,
    #[label("the {$op} produces a value")]
    pub label: Span,
    #[subdiagnostic]
    pub suggestion: UnusedOpSuggestion,
}

#[derive(Subdiagnostic)]
pub(crate) enum UnusedOpSuggestion {
    #[suggestion(
        "use `let _ = ...` to ignore the resulting value",
        style = "verbose",
        code = "let _ = ",
        applicability = "maybe-incorrect"
    )]
    NormalExpr {
        #[primary_span]
        span: Span,
    },
    #[multipart_suggestion(
        "use `let _ = ...` to ignore the resulting value",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    BlockTailExpr {
        #[suggestion_part(code = "let _ = ")]
        before_span: Span,
        #[suggestion_part(code = ";")]
        after_span: Span,
    },
}

#[derive(Diagnostic)]
#[diag("unused result of type `{$ty}`")]
pub(crate) struct UnusedResult<'a> {
    pub ty: Ty<'a>,
}

// FIXME(davidtwco): this isn't properly translatable because of the
// pre/post strings
#[derive(Diagnostic)]
#[diag(
    "unused {$pre}{$count ->
        [one] closure
        *[other] closures
    }{$post} that must be used"
)]
#[note("closures are lazy and do nothing unless called")]
pub(crate) struct UnusedClosure<'a> {
    pub count: usize,
    pub pre: &'a str,
    pub post: &'a str,
}

// FIXME(davidtwco): this isn't properly translatable because of the
// pre/post strings
#[derive(Diagnostic)]
#[diag(
    "unused {$pre}{$count ->
        [one] coroutine
        *[other] coroutine
    }{$post} that must be used"
)]
#[note("coroutines are lazy and do nothing unless resumed")]
pub(crate) struct UnusedCoroutine<'a> {
    pub count: usize,
    pub pre: &'a str,
    pub post: &'a str,
}

// FIXME(davidtwco): this isn't properly translatable because of the pre/post
// strings
pub(crate) struct UnusedDef<'a, 'b> {
    pub pre: &'a str,
    pub post: &'a str,
    pub cx: &'a LateContext<'b>,
    pub def_id: DefId,
    pub note: Option<Symbol>,
    pub suggestion: Option<UnusedDefSuggestion>,
}

#[derive(Subdiagnostic)]
pub(crate) enum UnusedDefSuggestion {
    #[suggestion(
        "use `let _ = ...` to ignore the resulting value",
        style = "verbose",
        code = "let _ = ",
        applicability = "maybe-incorrect"
    )]
    NormalExpr {
        #[primary_span]
        span: Span,
    },
    #[multipart_suggestion(
        "use `let _ = ...` to ignore the resulting value",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    BlockTailExpr {
        #[suggestion_part(code = "let _ = ")]
        before_span: Span,
        #[suggestion_part(code = ";")]
        after_span: Span,
    },
}

// Needed because of def_path_str
impl<'a> Diagnostic<'a, ()> for UnusedDef<'_, '_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag =
            Diag::new(dcx, level, msg!("unused {$pre}`{$def}`{$post} that must be used"))
                .with_arg("pre", self.pre)
                .with_arg("post", self.post)
                .with_arg("def", self.cx.tcx.def_path_str(self.def_id));
        // check for #[must_use = "..."]
        if let Some(note) = self.note {
            diag.note(note.to_string());
        }
        if let Some(sugg) = self.suggestion {
            diag.subdiagnostic(sugg);
        }
        diag
    }
}

#[derive(Diagnostic)]
#[diag("path statement drops value")]
pub(crate) struct PathStatementDrop {
    #[subdiagnostic]
    pub sub: PathStatementDropSub,
}

#[derive(Subdiagnostic)]
pub(crate) enum PathStatementDropSub {
    #[suggestion(
        "use `drop` to clarify the intent",
        code = "drop({snippet});",
        applicability = "machine-applicable"
    )]
    Suggestion {
        #[primary_span]
        span: Span,
        snippet: String,
    },
    #[help("use `drop` to clarify the intent")]
    Help {
        #[primary_span]
        span: Span,
    },
}

#[derive(Diagnostic)]
#[diag("path statement with no effect")]
pub(crate) struct PathStatementNoEffect;

#[derive(Diagnostic)]
#[diag("unnecessary {$delim} around {$item}")]
pub(crate) struct UnusedDelim<'a> {
    pub delim: &'static str,
    pub item: &'a str,
    #[subdiagnostic]
    pub suggestion: Option<UnusedDelimSuggestion>,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion("remove these {$delim}", applicability = "machine-applicable")]
pub(crate) struct UnusedDelimSuggestion {
    #[suggestion_part(code = "{start_replace}")]
    pub start_span: Span,
    pub start_replace: &'static str,
    #[suggestion_part(code = "{end_replace}")]
    pub end_span: Span,
    pub end_replace: &'static str,
    pub delim: &'static str,
}

#[derive(Diagnostic)]
#[diag("braces around {$node} is unnecessary")]
pub(crate) struct UnusedImportBracesDiag {
    pub node: Symbol,
}

#[derive(Diagnostic)]
#[diag("unnecessary allocation, use `&` instead")]
pub(crate) struct UnusedAllocationDiag;

#[derive(Diagnostic)]
#[diag("unnecessary allocation, use `&mut` instead")]
pub(crate) struct UnusedAllocationMutDiag;

pub(crate) struct AsyncFnInTraitDiag {
    pub sugg: Option<Vec<(Span, String)>>,
}

impl<'a> Diagnostic<'a, ()> for AsyncFnInTraitDiag {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(
            dcx,
            level,
            "use of `async fn` in public traits is discouraged as auto trait bounds cannot be specified",
        );
        diag.note("you can suppress this lint if you plan to use the trait only in your own code, or do not care about auto traits like `Send` on the `Future`");
        if let Some(sugg) = self.sugg {
            diag.multipart_suggestion("you can alternatively desugar to a normal `fn` that returns `impl Future` and add any desired bounds such as `Send`, but these cannot be relaxed without a breaking API change", sugg, Applicability::MaybeIncorrect);
        }
        diag
    }
}

#[derive(Diagnostic)]
#[diag("binding has unit type `()`")]
pub(crate) struct UnitBindingsDiag {
    #[label("this pattern is inferred to be the unit type `()`")]
    pub label: Span,
}

#[derive(Diagnostic)]
pub(crate) enum InvalidAsmLabel {
    #[diag("avoid using named labels in inline assembly")]
    #[help("only local labels of the form `<number>:` should be used in inline asm")]
    #[note(
        "see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information"
    )]
    Named {
        #[note("the label may be declared in the expansion of a macro")]
        missing_precise_span: bool,
    },
    #[diag("avoid using named labels in inline assembly")]
    #[help("only local labels of the form `<number>:` should be used in inline asm")]
    #[note("format arguments may expand to a non-numeric value")]
    #[note(
        "see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information"
    )]
    FormatArg {
        #[note("the label may be declared in the expansion of a macro")]
        missing_precise_span: bool,
    },
    #[diag("avoid using labels containing only the digits `0` and `1` in inline assembly")]
    #[help("start numbering with `2` instead")]
    #[note("an LLVM bug makes these labels ambiguous with a binary literal number on x86")]
    #[note("see <https://github.com/llvm/llvm-project/issues/99547> for more information")]
    Binary {
        #[note("the label may be declared in the expansion of a macro")]
        missing_precise_span: bool,
        // hack to get a label on the whole span, must match the emitted span
        #[label("use a different label that doesn't start with `0` or `1`")]
        span: Span,
    },
}

#[derive(Diagnostic)]
#[diag("creating a {$shared_label}reference to mutable static")]
pub(crate) struct RefOfMutStatic<'a> {
    #[label("{$shared_label}reference to mutable static")]
    pub span: Span,
    #[subdiagnostic]
    pub sugg: Option<MutRefSugg>,
    pub shared_label: &'a str,
    #[note(
        "shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives"
    )]
    pub shared_note: bool,
    #[note(
        "mutable references to mutable statics are dangerous; it's undefined behavior if any other pointer to the static is used or if any other reference is created for the static while the mutable reference lives"
    )]
    pub mut_note: bool,
    #[help(
        "use a type that relies on \"interior mutability\" instead; to read more on this, visit <https://doc.rust-lang.org/reference/interior-mutability.html>"
    )]
    pub interior_mutability_help: bool,
    #[subdiagnostic]
    pub interior_mutability_sugg: Option<StaticMutRefsInteriorMutabilitySugg>,
}

#[derive(Subdiagnostic)]
pub(crate) enum MutRefSugg {
    #[multipart_suggestion(
        "use `&raw const` instead to create a raw pointer",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    Shared {
        #[suggestion_part(code = "&raw const ")]
        span: Span,
    },
    #[multipart_suggestion(
        "use `&raw mut` instead to create a raw pointer",
        style = "verbose",
        applicability = "maybe-incorrect"
    )]
    Mut {
        #[suggestion_part(code = "&raw mut ")]
        span: Span,
    },
}

#[derive(Subdiagnostic)]
#[suggestion(
    "this type already provides \"interior mutability\", so its binding doesn't need to be declared as mutable when borrowed with a shared reference",
    style = "verbose",
    applicability = "maybe-incorrect",
    code = ""
)]
pub(crate) struct StaticMutRefsInteriorMutabilitySugg {
    #[primary_span]
    pub span: Span,
}

#[derive(Diagnostic)]
#[diag("`use` of a local item without leading `self::`, `super::`, or `crate::rustc_lint::`")]
pub(crate) struct UnqualifiedLocalImportsDiag;

#[derive(Diagnostic)]
#[diag("direct cast of function item into an integer")]
pub(crate) struct FunctionCastsAsIntegerDiag<'tcx> {
    #[subdiagnostic]
    pub(crate) sugg: FunctionCastsAsIntegerSugg<'tcx>,
}

#[derive(Subdiagnostic)]
#[suggestion(
    "first cast to a pointer `as *const ()`",
    code = " as *const ()",
    applicability = "machine-applicable",
    style = "verbose"
)]
pub(crate) struct FunctionCastsAsIntegerSugg<'tcx> {
    #[primary_span]
    pub suggestion: Span,
    pub cast_to_ty: Ty<'tcx>,
}

#[derive(Debug)]
pub(crate) struct MismatchedLifetimeSyntaxes {
    pub inputs: LifetimeSyntaxCategories<Vec<Span>>,
    pub outputs: LifetimeSyntaxCategories<Vec<Span>>,

    pub suggestions: Vec<MismatchedLifetimeSyntaxesSuggestion>,
}

impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for MismatchedLifetimeSyntaxes {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
        let counts = self.inputs.len() + self.outputs.len();
        let message = match counts {
            LifetimeSyntaxCategories { hidden: 0, elided: 0, named: 0 } => {
                panic!("No lifetime mismatch detected")
            }

            LifetimeSyntaxCategories { hidden: _, elided: _, named: 0 } => {
                msg!("hiding a lifetime that's elided elsewhere is confusing")
            }

            LifetimeSyntaxCategories { hidden: _, elided: 0, named: _ } => {
                msg!("hiding a lifetime that's named elsewhere is confusing")
            }

            LifetimeSyntaxCategories { hidden: 0, elided: _, named: _ } => {
                msg!("eliding a lifetime that's named elsewhere is confusing")
            }

            LifetimeSyntaxCategories { hidden: _, elided: _, named: _ } => {
                msg!("hiding or eliding a lifetime that's named elsewhere is confusing")
            }
        };
        let mut diag = Diag::new(dcx, level, message);

        for s in self.inputs.hidden {
            diag.span_label(s, msg!("the lifetime is hidden here"));
        }
        for s in self.inputs.elided {
            diag.span_label(s, msg!("the lifetime is elided here"));
        }
        for s in self.inputs.named {
            diag.span_label(s, msg!("the lifetime is named here"));
        }

        let mut hidden_output_counts: FxIndexMap<Span, usize> = FxIndexMap::default();
        for s in self.outputs.hidden {
            *hidden_output_counts.entry(s).or_insert(0) += 1;
        }
        for (span, count) in hidden_output_counts {
            let label = msg!(
                "the same {$count ->
                    [one] lifetime
                    *[other] lifetimes
                } {$count ->
                    [one] is
                    *[other] are
                } hidden here"
            )
            .arg("count", count)
            .format();
            diag.span_label(span, label);
        }
        for s in self.outputs.elided {
            diag.span_label(s, msg!("the same lifetime is elided here"));
        }
        for s in self.outputs.named {
            diag.span_label(s, msg!("the same lifetime is named here"));
        }

        diag.help(msg!(
            "the same lifetime is referred to in inconsistent ways, making the signature confusing"
        ));

        let mut suggestions = self.suggestions.into_iter();
        if let Some(s) = suggestions.next() {
            diag.subdiagnostic(s);

            for mut s in suggestions {
                s.make_optional_alternative();
                diag.subdiagnostic(s);
            }
        }
        diag
    }
}

#[derive(Debug)]
pub(crate) enum MismatchedLifetimeSyntaxesSuggestion {
    Implicit {
        suggestions: Vec<Span>,
        optional_alternative: bool,
    },

    Mixed {
        implicit_suggestions: Vec<Span>,
        explicit_anonymous_suggestions: Vec<(Span, String)>,
        optional_alternative: bool,
    },

    Explicit {
        lifetime_name: String,
        suggestions: Vec<(Span, String)>,
        optional_alternative: bool,
    },
}

impl MismatchedLifetimeSyntaxesSuggestion {
    fn make_optional_alternative(&mut self) {
        use MismatchedLifetimeSyntaxesSuggestion::*;

        let optional_alternative = match self {
            Implicit { optional_alternative, .. }
            | Mixed { optional_alternative, .. }
            | Explicit { optional_alternative, .. } => optional_alternative,
        };

        *optional_alternative = true;
    }
}

impl Subdiagnostic for MismatchedLifetimeSyntaxesSuggestion {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        use MismatchedLifetimeSyntaxesSuggestion::*;

        let style = |optional_alternative| {
            if optional_alternative {
                SuggestionStyle::CompletelyHidden
            } else {
                SuggestionStyle::ShowAlways
            }
        };

        let applicability = |optional_alternative| {
            // `cargo fix` can't handle more than one fix for the same issue,
            // so hide alternative suggestions from it by marking them as maybe-incorrect
            if optional_alternative {
                Applicability::MaybeIncorrect
            } else {
                Applicability::MachineApplicable
            }
        };

        match self {
            Implicit { suggestions, optional_alternative } => {
                let suggestions = suggestions.into_iter().map(|s| (s, String::new())).collect();
                diag.multipart_suggestion_with_style(
                    msg!("remove the lifetime name from references"),
                    suggestions,
                    applicability(optional_alternative),
                    style(optional_alternative),
                );
            }

            Mixed {
                implicit_suggestions,
                explicit_anonymous_suggestions,
                optional_alternative,
            } => {
                let message = if implicit_suggestions.is_empty() {
                    msg!("use `'_` for type paths")
                } else {
                    msg!("remove the lifetime name from references and use `'_` for type paths")
                };

                let implicit_suggestions =
                    implicit_suggestions.into_iter().map(|s| (s, String::new()));

                let suggestions =
                    implicit_suggestions.chain(explicit_anonymous_suggestions).collect();

                diag.multipart_suggestion_with_style(
                    message,
                    suggestions,
                    applicability(optional_alternative),
                    style(optional_alternative),
                );
            }

            Explicit { lifetime_name, suggestions, optional_alternative } => {
                let msg = msg!("consistently use `{$lifetime_name}`")
                    .arg("lifetime_name", lifetime_name)
                    .format();
                diag.multipart_suggestion_with_style(
                    msg,
                    suggestions,
                    applicability(optional_alternative),
                    style(optional_alternative),
                );
            }
        }
    }
}

#[derive(Diagnostic)]
#[diag("`Eq::assert_receiver_is_total_eq` should never be implemented by hand")]
#[note("this method was used to add checks to the `Eq` derive macro")]
pub(crate) struct EqInternalMethodImplemented;

#[derive(Diagnostic)]
#[diag("cast from `{$expr_ty}` to `{$cast_ty}` implicitly relies on exposed provenance")]
#[help(
    "if conforming to strict provenance is not possible, use `core::ptr::with_exposed_provenance()`"
)]
#[note("for more information, visit <https://doc.rust-lang.org/std/ptr/index.html#provenance>")]
pub(crate) struct ImplicitProvenanceCastsInt2Ptr<'tcx> {
    pub expr_ty: Ty<'tcx>,
    pub cast_ty: Ty<'tcx>,
    #[subdiagnostic]
    pub sugg: Option<Int2PtrSuggestion>,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "use `.with_addr()` to adjust the address of a valid pointer in the same allocation",
    applicability = "has-placeholders"
)]
pub(crate) struct Int2PtrSuggestion {
    #[suggestion_part(code = "(...).with_addr(")]
    pub lo: Span,
    #[suggestion_part(code = ")")]
    pub hi: Span,
}

#[derive(Diagnostic)]
#[diag("cast from `{$cast_from_ty}` to `{$cast_to_ty}` implicitly exposes pointer provenance")]
#[help("if conforming to strict provenance is not possible, use `.expose_provenance()`")]
#[note("for more information, visit <https://doc.rust-lang.org/std/ptr/index.html#provenance>")]
pub(crate) struct ImplicitProvenanceCastsPtr2Int<'tcx> {
    pub cast_from_ty: Ty<'tcx>,
    pub cast_to_ty: Ty<'tcx>,
    #[subdiagnostic]
    pub sugg: Option<Ptr2IntSuggestion<'tcx>>,
}

#[derive(Subdiagnostic)]
pub(crate) enum Ptr2IntSuggestion<'tcx> {
    #[multipart_suggestion(
        "use `.addr()` to obtain the address of a pointer",
        applicability = "maybe-incorrect"
    )]
    NeedsParensCast {
        #[suggestion_part(code = "(")]
        expr_span: Span,
        #[suggestion_part(code = ").addr() as {cast_to_ty}")]
        cast_span: Span,
        cast_to_ty: Ty<'tcx>,
    },
    #[multipart_suggestion(
        "use `.addr()` to obtain the address of a pointer",
        applicability = "maybe-incorrect"
    )]
    NeedsParens {
        #[suggestion_part(code = "(")]
        expr_span: Span,
        #[suggestion_part(code = ").addr()")]
        cast_span: Span,
    },
    #[suggestion(
        "use `.addr()` to obtain the address of a pointer",
        code = ".addr() as {cast_to_ty}",
        applicability = "maybe-incorrect"
    )]
    NeedsCast {
        #[primary_span]
        cast_span: Span,
        cast_to_ty: Ty<'tcx>,
    },
    #[suggestion(
        "use `.addr()` to obtain the address of a pointer",
        code = ".addr()",
        applicability = "maybe-incorrect"
    )]
    Other {
        #[primary_span]
        cast_span: Span,
    },
}

#[derive(Diagnostic)]
#[diag(
    "creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers"
)]
pub(crate) struct RawBorrowViaReference<'a> {
    #[subdiagnostic]
    pub suggestion: RawBorrowViaReferenceSuggestion<'a>,
}

#[derive(Subdiagnostic)]
pub(crate) enum RawBorrowViaReferenceSuggestion<'a> {
    #[multipart_suggestion(
        "consider using `&raw {$mutbl}` for a safer and more explicit raw pointer",
        applicability = "machine-applicable"
    )]
    Spanful {
        #[suggestion_part(code = "&raw {mutbl} ")]
        left: Span,
        #[suggestion_part(code = "")]
        right: Span,
        mutbl: &'a str,
    },
    #[help("consider using `&raw {$mutbl}` for a safer and more explicit raw pointer")]
    Spanless { mutbl: &'a str },
}