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
//! This crate is responsible for the part of name resolution that doesn't require type checker.
//!
//! Module structure of the crate is built here.
//! Paths in macros, imports, expressions, types, patterns are resolved here.
//! Label and lifetime names are resolved here as well.
//!
//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.

// tidy-alphabetical-start
// tidy-alphabetical-end

#![allow(internal_features)]
// `#![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.
// No real `std::` path remains anywhere in this crate. The `std` that is still spelled in
// `diagnostics/impls.rs` and `late/diagnostics.rs` is inside string literals describing the
// *user's* code, not a path this crate resolves.

// ---------------------------------------------------------------------------------------------
// STD IS BANNED IN THIS CRATE.
//
// `#![no_std]` above is the ban and the compiler is the enforcer: without `extern crate std;`
// there is no `std` in the extern prelude, so any `std::` path fails to resolve and the build
// stops. Do not add that line back to make an error go away - the error is the point. Whatever
// needed `std` either has a `core`/`alloc` equivalent, belongs in `ekostd`, or is a
// dependency that has to be replaced.
//
// The prelude is the part a grep cannot see: `Vec`, `String`, `Box`, `format!`, `vec!`,
// `thread_local!` and `println!` name no path. Under `#![no_std]` they resolve through `alloc`
// and `eko` instead, which is why those imports appear at the top of every file here.
// ---------------------------------------------------------------------------------------------
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::cell::RefMut;
use alloc::collections::BTreeSet;
use core::ops::ControlFlow;
use alloc::sync::Arc;
use eko::thread::OnceLock;
use core::{fmt, mem};

use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
use effective_visibilities::EffectiveVisibilitiesVisitor;
use hygiene::Macros20NormalizedSyntaxContext;
use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
use late::{
    ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
    UnnecessaryQualification,
};
pub use macros::registered_lint_tools_ast;
use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
use crate::rustc_arena::{DroplessArena, TypedArena};
use crate::rustc_ast::node_id::NodeMap;
use crate::rustc_ast::{
    self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
    GenericArg, GenericArgs, Generics, NodeId, Path, attr,
};
use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
use crate::rustc_data_structures::intern::Interned;
use crate::rustc_data_structures::steal::Steal;
use crate::rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, WorkerLocal};
use crate::rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
use crate::rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
use crate::rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
use crate::rustc_feature::{BUILTIN_ATTRIBUTES, Features};
use crate::rustc_hir::attrs::StrippedCfgItem;
use crate::rustc_hir::def::Namespace::{self, *};
use crate::rustc_hir::def::{
    self, CtorOf, DefKind, DocLinkResMap, MacroKinds, NonMacroAttrKind, PartialRes, PerNS,
};
use crate::rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
use crate::rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};
use crate::rustc_hir::{PrimTy, TraitCandidate, find_attr};
use crate::rustc_index::bit_set::DenseBitSet;
use crate::rustc_lint_defs::builtin::PRIVATE_MACRO_USE;
use crate::rustc_metadata::creader::CStore;
use crate::rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
use crate::rustc_middle::middle::privacy::EffectiveVisibilities;
use crate::rustc_middle::query::Providers;
use crate::rustc_middle::ty::{
    self, DelegationInfo, MainDefinition, PerOwnerResolverData, RegisteredTools,
    ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
};
use crate::rustc_middle::{bug, span_bug};
use crate::rustc_span::def_id::{LocalModId, ModId};
use crate::rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
use crate::rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
use crate::rustc_structures::CrateType;
use smallvec::{SmallVec, smallvec};
use tracing::{debug, instrument};

use crate::rustc_resolve::diagnostics::impls::{
    ImportSuggestion, LabelSuggestion, OnUnknownData, StructCtor, Suggestion,
};
use crate::rustc_resolve::imports::{ImportResolution, NameResolutionRef};
use crate::rustc_resolve::ref_mut::speculative::SpeculativeFlag;
use crate::rustc_resolve::ref_mut::{CmCell, CmRef, CmRefCell};

mod build_reduced_graph;
mod check_unused;
mod def_collector;
mod diagnostics;
mod effective_visibilities;
mod ident;
mod imports;
mod late;
mod macros;
pub mod rustdoc;

type Res = def::Res<NodeId>;

#[derive(Copy, Clone, PartialEq, Debug)]
enum Determinacy {
    Determined,
    Undetermined,
}

impl Determinacy {
    fn determined(determined: bool) -> Determinacy {
        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
    }
}

/// A specific scope in which a name can be looked up.
#[derive(Clone, Copy, Debug)]
enum Scope<'ra> {
    /// Inert attributes registered by derive macros.
    DeriveHelpers(LocalExpnId),
    /// Inert attributes registered by derive macros, but used before they are actually declared.
    /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`
    /// is turned into a hard error.
    DeriveHelpersCompat,
    /// Textual `let`-like scopes introduced by `macro_rules!` items.
    MacroRules(MacroRulesScopeRef<'ra>),
    /// Non-glob names declared in the given module.
    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
    /// lint if it should be reported.
    ModuleNonGlobs(Module<'ra>, Option<NodeId>),
    /// Glob names declared in the given module.
    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
    /// lint if it should be reported.
    ModuleGlobs(Module<'ra>, Option<NodeId>),
    /// Names introduced by `#[macro_use]` attributes on `extern crate` items.
    MacroUsePrelude,
    /// Built-in attributes.
    BuiltinAttrs,
    /// Extern prelude names introduced by `extern crate` items.
    ExternPreludeItems,
    /// Extern prelude names introduced by `--extern` flags.
    ExternPreludeFlags,
    /// Tool modules introduced with `#![register_tool]` or `#![register_attribute_tool]`.
    ToolAttributePrelude,
    /// Standard library prelude introduced with an internal `#[prelude_import]` import.
    StdLibPrelude,
    /// Built-in types.
    BuiltinTypes,
}

/// Names from different contexts may want to visit different subsets of all specific scopes
/// with different restrictions when looking up the resolution.
#[derive(Clone, Copy, Debug)]
enum ScopeSet<'ra> {
    /// All scopes with the given namespace.
    All(Namespace),
    /// Two scopes inside a module, for non-glob and glob bindings.
    Module(Namespace, Module<'ra>),
    /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).
    ModuleAndExternPrelude(Namespace, Module<'ra>),
    /// Just two extern prelude scopes.
    ExternPrelude,
    /// Same as `All(MacroNS)`, but with the given macro kind restriction.
    Macro(MacroKind),
}

/// Everything you need to know about a name's location to resolve it.
/// Serves as a starting point for the scope visitor.
/// This struct is currently used only for early resolution (imports and macros),
/// but not for late resolution yet.
#[derive(Clone, Copy, Debug)]
struct ParentScope<'ra> {
    module: Module<'ra>,
    expansion: LocalExpnId,
    macro_rules: MacroRulesScopeRef<'ra>,
    derives: &'ra [ast::Path],
}

impl<'ra> ParentScope<'ra> {
    /// Creates a parent scope with the passed argument used as the module scope component,
    /// and other scope components set to default empty values.
    fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
        ParentScope {
            module: module.to_module(),
            expansion: LocalExpnId::ROOT,
            macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
            derives: &[],
        }
    }
}

#[derive(Copy, Debug, Clone)]
struct InvocationParent {
    parent_def: LocalDefId,
    impl_trait_context: ImplTraitContext,
    in_attr: bool,
    owner: NodeId,
}

impl InvocationParent {
    const ROOT: Self = Self {
        parent_def: CRATE_DEF_ID,
        impl_trait_context: ImplTraitContext::Existential,
        in_attr: false,
        owner: CRATE_NODE_ID,
    };
}

#[derive(Copy, Debug, Clone)]
enum ImplTraitContext {
    Existential,
    Universal,
    InBinding,
}

/// Used for tracking import use types which will be used for redundant import checking.
///
/// ### Used::Scope Example
///
/// ```rust,compile_fail
/// #![deny(redundant_imports)]
/// use core::mem::drop;
/// fn main() {
///     let s = Box::new(32);
///     drop(s);
/// }
/// ```
///
/// Used::Other is for other situations like module-relative uses.
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
enum Used {
    Scope,
    Other,
}

#[derive(Debug)]
struct BindingError {
    name: Ident,
    origin: Vec<(Span, ast::Pat)>,
    target: Vec<ast::Pat>,
    could_be_path: bool,
}

#[derive(Debug)]
enum ResolutionError<'ra> {
    /// Error E0401: can't use type or const parameters from outer item.
    GenericParamsFromOuterItem {
        outer_res: Res,
        has_generic_params: HasGenericParams,
        def_kind: DefKind,
        /// 1. label span, 2. item span, 3. item kind
        inner_item: Option<(Span, Span, ast::ItemKind)>,
        current_self_ty: Option<String>,
    },
    /// Error E0403: the name is already used for a type or const parameter in this generic
    /// parameter list.
    NameAlreadyUsedInParameterList(Ident, Span),
    /// Error E0407: method is not a member of trait.
    MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
    /// Error E0437: type is not a member of trait.
    TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
    /// Error E0438: const is not a member of trait.
    ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
    /// Error E0408: variable `{}` is not bound in all patterns.
    VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
    /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
    VariableBoundWithDifferentMode(Ident, Span),
    /// Error E0415: identifier is bound more than once in this parameter list.
    IdentifierBoundMoreThanOnceInParameterList(Ident),
    /// Error E0416: identifier is bound more than once in the same pattern.
    IdentifierBoundMoreThanOnceInSamePattern(Ident),
    /// Error E0426: use of undeclared label.
    UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
    /// Error E0433: failed to resolve.
    FailedToResolve {
        segment: Symbol,
        label: String,
        suggestion: Option<Suggestion>,
        help: Option<String>,
        module: Option<ModuleOrUniformRoot<'ra>>,
        message: String,
    },
    /// Error E0434: can't capture dynamic environment in a fn item.
    CannotCaptureDynamicEnvironmentInFnItem,
    /// Error E0435: attempt to use a non-constant value in a constant.
    AttemptToUseNonConstantValueInConstant {
        ident: Ident,
        suggestion: &'static str,
        current: &'static str,
        type_span: Option<Span>,
    },
    /// Error E0530: `X` bindings cannot shadow `Y`s.
    BindingShadowsSomethingUnacceptable {
        shadowing_binding: PatternSource,
        name: Symbol,
        participle: &'static str,
        article: &'static str,
        shadowed_binding: Res,
        shadowed_binding_span: Span,
    },
    /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
    ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
    // FIXME(generic_const_parameter_types): This should give custom output specifying it's only
    // problematic to use *forward declared* parameters when the feature is enabled.
    /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
    ParamInTyOfConstParam { name: Symbol },
    /// cannot use self in const param
    SelfInConstParam,
    /// generic parameters must not be used inside const evaluations.
    ///
    /// This error is only emitted when using `min_const_generics`.
    ParamInNonTrivialAnonConst {
        is_gca: bool,
        name: Symbol,
        param_kind: ParamKindInNonTrivialAnonConst,
    },
    /// generic parameters must not be used inside enum discriminants.
    ///
    /// This error is emitted even with `generic_const_exprs`.
    ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
    /// Error E0735: generic parameters with a default cannot use `Self`
    ForwardDeclaredSelf(ForwardGenericParamBanReason),
    /// Error E0767: use of unreachable label
    UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
    /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
    TraitImplMismatch {
        name: Ident,
        kind: &'static str,
        trait_path: String,
        trait_item_span: Span,
        code: ErrCode,
    },
    /// Error E0201: multiple impl items for the same trait item.
    TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
    /// Inline asm `sym` operand must refer to a `fn` or `static`.
    InvalidAsmSym,
    /// `self` used instead of `Self` in a generic parameter
    LowercaseSelf,
    /// A never pattern has a binding.
    BindingInNeverPattern,
}

#[derive(Debug)]
enum VisResolutionError {
    Relative2018(Span, ast::Path),
    AncestorOnly(Span),
    FailedToResolve {
        span: Span,
        segment: Symbol,
        label: String,
        suggestion: Option<Suggestion>,
        help: Option<String>,
        message: String,
    },
    ExpectedFound(Span, String, Res),
    Indeterminate(Span),
    ModuleOnly(Span),
}

/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
/// segments' which don't have the rest of an AST or HIR `PathSegment`.
#[derive(Clone, Copy, Debug)]
struct Segment {
    ident: Ident,
    id: Option<NodeId>,
    /// Signals whether this `PathSegment` has generic arguments.
    has_generic_args: bool,
    /// Signals whether this `PathSegment` has lifetime arguments.
    has_lifetime_args: bool,
    args_span: Span,
}

impl Segment {
    fn from_path(path: &Path) -> Vec<Segment> {
        path.segments.iter().map(|s| s.into()).collect()
    }

    fn from_ident(ident: Ident) -> Segment {
        Segment {
            ident,
            id: None,
            has_generic_args: false,
            has_lifetime_args: false,
            args_span: DUMMY_SP,
        }
    }

    fn names_to_string(segments: &[Segment]) -> String {
        names_to_string(segments.iter().map(|seg| seg.ident.name))
    }
}

impl<'a> From<&'a ast::PathSegment> for Segment {
    fn from(seg: &'a ast::PathSegment) -> Segment {
        let has_generic_args = seg.args.is_some();
        let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
            match args {
                GenericArgs::AngleBracketed(args) => {
                    let found_lifetimes = args
                        .args
                        .iter()
                        .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
                    (args.span, found_lifetimes)
                }
                GenericArgs::Parenthesized(args) => (args.span, true),
                GenericArgs::ParenthesizedElided(span) => (*span, true),
            }
        } else {
            (DUMMY_SP, false)
        };
        Segment {
            ident: seg.ident,
            id: Some(seg.id),
            has_generic_args,
            has_lifetime_args,
            args_span,
        }
    }
}

/// Name declaration used during late resolution.
#[derive(Debug, Copy, Clone)]
enum LateDecl<'ra> {
    /// A regular name declaration.
    Decl(Decl<'ra>),
    /// A name definition from a rib, e.g. a local variable.
    /// Omits most of the data from regular `Decl` for performance reasons.
    RibDef(Res),
}

impl<'ra> LateDecl<'ra> {
    fn res(self) -> Res {
        match self {
            LateDecl::Decl(binding) => binding.res(),
            LateDecl::RibDef(res) => res,
        }
    }
}

#[derive(Copy, Clone, PartialEq, Debug)]
enum ModuleOrUniformRoot<'ra> {
    /// Regular module.
    Module(Module<'ra>),

    /// Virtual module that denotes resolution in a module with fallback to extern prelude.
    /// Used for paths starting with `::` coming from 2015 edition macros
    /// used in 2018+ edition crates.
    ModuleAndExternPrelude(Module<'ra>),

    /// Virtual module that denotes resolution in extern prelude.
    /// Used for paths starting with `::` on 2018 edition.
    ExternPrelude,

    /// Virtual module that denotes resolution in current scope.
    /// Used only for resolving single-segment imports. The reason it exists is that import paths
    /// are always split into two parts, the first of which should be some kind of module.
    CurrentScope,

    /// Virtual module for the resolution of base names of namespaced crates,
    /// where the base name doesn't correspond to a module in the extern prelude.
    /// E.g. `my_api::utils` is in the prelude, but `my_api` is not.
    OpenModule(Symbol),
}

#[derive(Debug)]
enum PathResult<'ra> {
    Module(ModuleOrUniformRoot<'ra>),
    NonModule(PartialRes),
    Indeterminate,
    Failed {
        span: Span,
        label: String,
        suggestion: Option<Suggestion>,
        help: Option<String>,
        is_error_from_last_segment: bool,
        /// The final module being resolved, for instance:
        ///
        /// ```compile_fail
        /// mod a {
        ///     mod b {
        ///         mod c {}
        ///     }
        /// }
        ///
        /// use a::not_exist::c;
        /// ```
        ///
        /// In this case, `module` will point to `a`.
        module: Option<ModuleOrUniformRoot<'ra>>,
        /// The segment of target
        segment: Ident,
        error_implied_by_parse_error: bool,
        message: String,
        note: Option<String>,
    },
}

impl<'ra> PathResult<'ra> {
    fn failed(
        ident: Ident,
        is_error_from_last_segment: bool,
        finalize: bool,
        error_implied_by_parse_error: bool,
        module: Option<ModuleOrUniformRoot<'ra>>,
        label_and_suggestion_and_note: impl FnOnce() -> (
            String,
            String,
            Option<Suggestion>,
            Option<String>,
            Option<String>,
        ),
    ) -> PathResult<'ra> {
        let (message, label, suggestion, note, help) = if finalize {
            label_and_suggestion_and_note()
        } else {
            // FIXME: this output isn't actually present in the test suite.
            (format!("cannot find `{ident}` in this scope"), String::new(), None, None, None)
        };
        PathResult::Failed {
            span: ident.span,
            segment: ident,
            label,
            suggestion,
            help,
            is_error_from_last_segment,
            module,
            error_implied_by_parse_error,
            message,
            note,
        }
    }
}

#[derive(Debug)]
enum ModuleKind {
    /// An anonymous module; e.g., just a block.
    ///
    /// ```
    /// fn main() {
    ///     fn f() {} // (1)
    ///     { // This is an anonymous module
    ///         f(); // This resolves to (2) as we are inside the block.
    ///         fn f() {} // (2)
    ///     }
    ///     f(); // Resolves to (1)
    /// }
    /// ```
    Block,
    /// Any module with a name.
    ///
    /// This could be:
    ///
    /// * A normal module – either `mod from_file;` or `mod from_block { }` –
    ///   or the crate root (which is conceptually a top-level module).
    ///   The crate root will have `None` for the symbol.
    /// * A trait or an enum (it implicitly contains associated types, methods and variant
    ///   constructors).
    Def(DefKind, DefId, NodeId, Option<Symbol>),
}

impl ModuleKind {
    fn opt_def_id(&self) -> Option<DefId> {
        match self {
            ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
            _ => None,
        }
    }

    fn def_id(&self) -> DefId {
        self.opt_def_id().expect("`Module::def_id` is called on a block module")
    }

    fn is_local(&self) -> bool {
        match self {
            ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
            ModuleKind::Block => true,
        }
    }
}

/// Combination of a symbol and its macros 2.0 normalized hygiene context.
/// Used as a key in various kinds of name containers, including modules (as a part of slightly
/// larger `BindingKey`) and preludes.
///
/// Often passed around together with `orig_ident_span: Span`, which is an unnormalized span
/// of the original `Ident` from which `IdentKey` was obtained. This span is not used in map keys,
/// but used in a number of other scenarios - diagnostics, edition checks, `allow_unstable` checks
/// and similar. This is required because macros 2.0 normalization is lossy and the normalized
/// spans / syntax contexts no longer contain parts of macro backtraces, while the original span
/// contains everything.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct IdentKey {
    name: Symbol,
    ctxt: Macros20NormalizedSyntaxContext,
}

impl IdentKey {
    #[inline]
    fn new(ident: Ident) -> IdentKey {
        IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
    }

    #[inline]
    fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
        let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
        (IdentKey { name: ident.name, ctxt }, def)
    }

    #[inline]
    fn with_root_ctxt(name: Symbol) -> Self {
        let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
        IdentKey { name, ctxt }
    }

    #[inline]
    fn orig(self, orig_ident_span: Span) -> Ident {
        Ident::new(self.name, orig_ident_span)
    }
}

/// A key that identifies a binding in a given `Module`.
///
/// Multiple bindings in the same module can have the same key (in a valid
/// program) if all but one of them come from glob imports.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
struct BindingKey {
    /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
    /// identifier.
    ident: IdentKey,
    ns: Namespace,
    /// When we add an underscore binding (with ident `_`) to some module, this field has
    /// a non-zero value that uniquely identifies this binding in that module.
    /// For non-underscore bindings this field is zero.
    /// When a key is constructed for name lookup (as opposed to name definition), this field is
    /// also zero, even for underscore names, so for underscores the lookup will never succeed.
    disambiguator: u32,
}

impl BindingKey {
    fn new(ident: IdentKey, ns: Namespace) -> Self {
        BindingKey { ident, ns, disambiguator: 0 }
    }

    fn new_disambiguated(
        ident: IdentKey,
        ns: Namespace,
        disambiguator: impl FnOnce() -> u32,
    ) -> BindingKey {
        let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
        BindingKey { ident, ns, disambiguator }
    }
}

type ResolutionTable<'ra> = FxIndexMap<BindingKey, NameResolutionRef<'ra>>;

enum Resolutions<'ra> {
    Local(CmRefCell<ResolutionTable<'ra>>),
    Extern(OnceLock<ResolutionTable<'ra>>),
}

impl<'ra> Resolutions<'ra> {
    fn new(local: bool) -> Self {
        if local {
            Resolutions::Local(Default::default())
        } else {
            Resolutions::Extern(Default::default())
        }
    }
}

/// One node in the tree of modules.
///
/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
///
/// * `mod`
/// * crate root (aka, top-level anonymous module)
/// * `enum`
/// * `trait`
/// * curly-braced block with statements
///
/// You can use [`ModuleData::kind`] to determine the kind of module this is.
struct ModuleData<'ra> {
    /// The direct parent module (it may not be a `mod`, however).
    parent: Option<Module<'ra>>,
    /// What kind of module this is, because this may not be a `mod`.
    kind: ModuleKind,

    /// Mapping between names and their (possibly in-progress) resolutions in this module.
    /// Resolutions in modules from other crates are not populated until accessed.
    lazy_resolutions: Resolutions<'ra>,
    /// Used to disambiguate underscore items (`const _: T = ...`) in the module.
    underscore_disambiguator: CmCell<u32>,

    /// Macro invocations that can expand into items in this module.
    unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,

    /// Whether `#[no_implicit_prelude]` is active.
    no_implicit_prelude: bool,

    glob_importers: CmRefCell<Vec<Import<'ra>>>,
    globs: CmRefCell<Vec<Import<'ra>>>,

    /// Used to memoize the traits in this module for faster searches through all traits in scope.
    traits: CmRefCell<
        Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool /* lint ambiguous */)]>>,
    >,

    /// Span of the module itself. Used for error reporting.
    span: Span,

    expansion: ExpnId,

    /// Declaration for implicitly declared names that come with a module,
    /// like `self` (not yet used), or `crate`/`$crate` (for root modules).
    self_decl: Option<Decl<'ra>>,
}

/// `Interned` is used because values of this type have "identity" and compare as unequal even if
/// they have the same contents.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);

/// Same as `Module`, but is guaranteed to be from the current crate.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);

/// Same as `Module`, but is guaranteed to be from an external crate.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);

impl<'ra> ModuleData<'ra> {
    fn new(
        parent: Option<Module<'ra>>,
        kind: ModuleKind,
        expansion: ExpnId,
        span: Span,
        no_implicit_prelude: bool,
        vis: Visibility<ModId>,
        arenas: &'ra ResolverArenas<'ra>,
    ) -> Self {
        let lazy_resolutions = Resolutions::new(kind.is_local());
        let self_decl = match kind {
            ModuleKind::Def(def_kind, def_id, ..) => {
                let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
                Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
            }
            ModuleKind::Block => None,
        };
        ModuleData {
            parent,
            kind,
            lazy_resolutions,
            underscore_disambiguator: CmCell::new(0),
            unexpanded_invocations: Default::default(),
            no_implicit_prelude,
            glob_importers: CmRefCell::new(Vec::new()),
            globs: CmRefCell::new(Vec::new()),
            traits: CmRefCell::new(None),
            span,
            expansion,
            self_decl,
        }
    }

    /// Get name of the module.
    fn name(&self) -> Option<Symbol> {
        match self.kind {
            ModuleKind::Block => None,
            ModuleKind::Def(.., name) => name,
        }
    }

    fn opt_def_id(&self) -> Option<DefId> {
        self.kind.opt_def_id()
    }

    fn def_id(&self) -> DefId {
        self.kind.def_id()
    }

    fn is_local(&self) -> bool {
        self.kind.is_local()
    }

    fn has_unexpanded_invocations<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
        !self.unexpanded_invocations.borrow_checked(r).is_empty()
    }

    fn res(&self) -> Option<Res> {
        match self.kind {
            ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
            _ => None,
        }
    }

    fn def_kind(&self) -> Option<DefKind> {
        match self.kind {
            ModuleKind::Def(def_kind, ..) => Some(def_kind),
            ModuleKind::Block => None,
        }
    }
}

impl<'ra> Module<'ra> {
    fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
        self,
        resolver: &R,
        mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
    ) {
        for (key, name_resolution) in resolver.as_ref().resolutions(self).iter() {
            let name_resolution = name_resolution.borrow_checked(resolver.as_ref());
            if let Some(decl) = name_resolution.best_decl() {
                f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
            }
        }
    }

    fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
        self,
        resolver: &mut R,
        mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
    ) {
        for (key, name_resolution) in resolver.as_mut().resolutions(self).iter() {
            let name_resolution = name_resolution.borrow(resolver.as_mut());
            if let Some(decl) = name_resolution.best_decl() {
                f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
            }
        }
    }

    /// This modifies `self` in place. The traits will be stored in `self.traits`.
    fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {
        let mut traits = self.traits.borrow_mut_checked(resolver);
        if traits.is_none() {
            let mut collected_traits = Vec::new();
            self.for_each_child(resolver, |r, ident, _, ns, mut decl| {
                if ns != TypeNS {
                    return;
                }

                let ambiguous = decl.is_ambiguity_recursive();
                let mut try_record_trait = |decl: Decl<'ra>| {
                    if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = decl.res() {
                        collected_traits.push((
                            ident.name,
                            decl,
                            r.as_ref().get_module(def_id),
                            ambiguous,
                        ));
                        true
                    } else {
                        false
                    }
                };
                // Try to record at least one trait if the decl is ambiguous, such that we can
                // report the `ambiguous_glob_imported_traits` lint. Otherwise we would report an
                // error that the trait is not found.
                while !try_record_trait(decl)
                    && let Some((_, ambig_decl)) = decl.descent_to_ambiguity()
                {
                    decl = ambig_decl;
                }
            });
            *traits = Some(collected_traits.into_boxed_slice());
        }
    }

    // `self` resolves to the first module ancestor that `is_normal`.
    fn is_normal(self) -> bool {
        self.def_kind() == Some(DefKind::Mod)
    }

    fn is_trait(self) -> bool {
        matches!(self.def_kind(), Some(DefKind::Trait))
    }

    fn nearest_item_scope(self) -> Module<'ra> {
        match self.def_kind() {
            Some(DefKind::Enum | DefKind::Trait) => {
                self.parent.expect("enum or trait module without a parent")
            }
            _ => self,
        }
    }

    /// The [`ModId`] of the nearest `mod` item ancestor (which may be this module).
    /// This may be the crate root.
    fn nearest_parent_mod(self) -> ModId {
        match self.kind {
            ModuleKind::Def(DefKind::Mod, def_id, _, _) => ModId::new_unchecked(def_id),
            _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
        }
    }

    /// The [`NodeId`] of the nearest `mod` item ancestor (which may be this module).
    /// This may be the crate root.
    fn nearest_parent_mod_node_id(self) -> NodeId {
        match self.kind {
            ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
            _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
        }
    }

    fn is_ancestor_of(self, mut other: Self) -> bool {
        while self != other {
            if let Some(parent) = other.parent {
                other = parent;
            } else {
                return false;
            }
        }
        true
    }

    #[track_caller]
    fn expect_local(self) -> LocalModule<'ra> {
        match self.kind {
            ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
                span_bug!(self.span, "unexpected extern module: {self:?}")
            }
            ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
        }
    }

    #[track_caller]
    fn expect_extern(self) -> ExternModule<'ra> {
        match self.kind {
            ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
            ModuleKind::Def(..) | ModuleKind::Block => {
                span_bug!(self.span, "unexpected local module: {self:?}")
            }
        }
    }
}

impl<'ra> LocalModule<'ra> {
    fn new(
        parent: Option<LocalModule<'ra>>,
        kind: ModuleKind,
        vis: Visibility<ModId>,
        expn_id: ExpnId,
        span: Span,
        no_implicit_prelude: bool,
        arenas: &'ra ResolverArenas<'ra>,
    ) -> LocalModule<'ra> {
        assert!(kind.is_local());
        let parent = parent.map(|m| m.to_module());
        let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
        // SAFETY: `Interned` is valid because values of this type have "identity".
        LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
    }

    fn to_module(self) -> Module<'ra> {
        Module(self.0)
    }
}

impl<'ra> ExternModule<'ra> {
    fn new(
        parent: Option<ExternModule<'ra>>,
        kind: ModuleKind,
        vis: Visibility<ModId>,
        expn_id: ExpnId,
        span: Span,
        no_implicit_prelude: bool,
        arenas: &'ra ResolverArenas<'ra>,
    ) -> ExternModule<'ra> {
        assert!(!kind.is_local());
        let parent = parent.map(|m| m.to_module());
        let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
        // SAFETY: `Interned` is valid because values of this type have "identity".
        ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
    }

    fn to_module(self) -> Module<'ra> {
        Module(self.0)
    }
}

impl<'ra> core::ops::Deref for Module<'ra> {
    type Target = ModuleData<'ra>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'ra> core::ops::Deref for LocalModule<'ra> {
    type Target = ModuleData<'ra>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'ra> core::ops::Deref for ExternModule<'ra> {
    type Target = ModuleData<'ra>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'ra> fmt::Debug for Module<'ra> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.res() {
            None => write!(f, "block"),
            Some(res) => write!(f, "{:?}", res),
        }
    }
}

impl<'ra> fmt::Debug for LocalModule<'ra> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.to_module().fmt(f)
    }
}

/// Data associated with any name declaration.
#[derive(Debug)]
struct DeclData<'ra> {
    kind: DeclKind<'ra>,
    ambiguity: CmCell<Option<(Decl<'ra>, bool /*warning*/)>>,
    expansion: LocalExpnId,
    span: Span,
    initial_vis: Visibility<ModId>,
    /// If the declaration refers to an ambiguous glob set, then this is the most visible
    /// declaration from the set, if its visibility is different from `initial_vis`.
    ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
    /// If the declaration refers to an ambiguous glob set, then this is the least visible
    /// declaration from the set, if its visibility is different from `initial_vis`.
    ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
    parent_module: Option<Module<'ra>>,
}

/// `Interned` is used because values of this type have "identity" and compare as unequal even if
/// they have the same contents.
type Decl<'ra> = Interned<'ra, DeclData<'ra>>;

/// Name declaration kind.
#[derive(Debug)]
enum DeclKind<'ra> {
    /// The name declaration is a definition (possibly without a `DefId`),
    /// can be provided by source code or built into the language.
    Def(Res),
    /// The name declaration is a link to another name declaration.
    Import { source_decl: Decl<'ra>, import: Import<'ra> },
}

impl<'ra> DeclKind<'ra> {
    /// Is this an import declaration?
    fn is_import(&self) -> bool {
        matches!(*self, DeclKind::Import { .. })
    }
}

#[derive(Debug)]
struct PrivacyError<'ra> {
    ident: Ident,
    decl: Decl<'ra>,
    dedup_span: Span,
    outermost_res: Option<(Res, Ident)>,
    parent_scope: ParentScope<'ra>,
    /// Is the format `use a::{b,c}`?
    single_nested: bool,
    source: Option<ast::Expr>,
}

#[derive(Debug)]
struct UseError<'a> {
    err: Diag<'a>,
    /// Candidates which user could `use` to access the missing type.
    candidates: Vec<ImportSuggestion>,
    /// The `NodeId` of the module to place the use-statements in.
    node_id: NodeId,
    /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
    instead: bool,
    /// Extra free-form suggestion.
    suggestion: Option<(Span, &'static str, String, Applicability)>,
    /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
    /// the user to import the item directly.
    path: Vec<Segment>,
    /// Whether the expected source is a call
    is_call: bool,
}

#[derive(Debug)]
struct DelayedVisResolutionError<'ra> {
    vis: ast::Visibility,
    parent_scope: ParentScope<'ra>,
    error: VisResolutionError,
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum AmbiguityKind {
    BuiltinAttr,
    DeriveHelper,
    MacroRulesVsModularized,
    GlobVsOuter,
    GlobVsGlob,
    GlobVsExpanded,
    MoreExpandedVsOuter,
}

impl AmbiguityKind {
    fn descr(self) -> &'static str {
        match self {
            AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
            AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
            AmbiguityKind::MacroRulesVsModularized => {
                "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
            }
            AmbiguityKind::GlobVsOuter => {
                "a conflict between a name from a glob import and an outer scope during import or macro resolution"
            }
            AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
            AmbiguityKind::GlobVsExpanded => {
                "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
            }
            AmbiguityKind::MoreExpandedVsOuter => {
                "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
            }
        }
    }
}

#[derive(Clone, Copy, PartialEq)]
enum AmbiguityWarning {
    GlobImport,
    PanicImport,
}

struct AmbiguityError<'ra> {
    kind: AmbiguityKind,
    ambig_vis: Option<(Visibility, Visibility)>,
    ident: Ident,
    b1: Decl<'ra>,
    b2: Decl<'ra>,
    scope1: Scope<'ra>,
    scope2: Scope<'ra>,
    warning: Option<AmbiguityWarning>,
}

// These two take the interned handle by value. Upstream declares them on `DeclData` with
// `self: Decl<'ra>`, a receiver only `arbitrary_self_types` (unstable) accepts; an inherent
// impl on the interned type gives callers the same `decl.method()` syntax.
impl<'ra> Interned<'ra, DeclData<'ra>> {
    fn descent_to_ambiguity(self) -> Option<(Decl<'ra>, Decl<'ra>)> {
        match self.ambiguity.get() {
            Some((ambig_binding, _)) => Some((self, ambig_binding)),
            None => match self.kind {
                DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
                _ => None,
            },
        }
    }

    fn reexport_chain(self) -> SmallVec<[Reexport; 2]> {
        let mut reexport_chain = SmallVec::new();
        let mut next_binding = self;
        while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
            reexport_chain.push(import.simplify());
            next_binding = source_decl;
        }
        reexport_chain
    }
}

impl<'ra> DeclData<'ra> {
    fn vis(&self) -> Visibility<ModId> {
        // Select the maximum visibility if there are multiple ambiguous glob imports.
        self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
    }

    fn min_vis(&self) -> Visibility<ModId> {
        // Select the minimum visibility if there are multiple ambiguous glob imports.
        self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
    }

    fn res(&self) -> Res {
        match self.kind {
            DeclKind::Def(res) => res,
            DeclKind::Import { source_decl, .. } => source_decl.res(),
        }
    }

    fn import_source(&self) -> Decl<'ra> {
        match self.kind {
            DeclKind::Import { source_decl, .. } => source_decl,
            _ => unreachable!(),
        }
    }

    fn is_ambiguity_recursive(&self) -> bool {
        self.ambiguity.get().is_some()
            || match self.kind {
                DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
                _ => false,
            }
    }

    fn is_possibly_imported_variant(&self) -> bool {
        match self.kind {
            DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
            DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
                true
            }
            DeclKind::Def(..) => false,
        }
    }

    fn is_extern_crate(&self) -> bool {
        match self.kind {
            DeclKind::Import { import, .. } => {
                matches!(import.kind, ImportKind::ExternCrate { .. })
            }
            DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
            _ => false,
        }
    }

    fn is_import(&self) -> bool {
        matches!(self.kind, DeclKind::Import { .. })
    }

    /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
    /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
    fn is_import_user_facing(&self) -> bool {
        matches!(self.kind, DeclKind::Import { import, .. }
            if !matches!(import.kind, ImportKind::MacroExport))
    }

    fn is_glob_import(&self) -> bool {
        match self.kind {
            DeclKind::Import { import, .. } => import.is_glob(),
            _ => false,
        }
    }

    fn is_assoc_item(&self) -> bool {
        matches!(
            self.res(),
            Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
        )
    }

    fn macro_kinds(&self) -> Option<MacroKinds> {
        self.res().macro_kinds()
    }

    // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
    // at some expansion round `max(invoc, binding)` when they both emerged from macros.
    // Then this function returns `true` if `self` may emerge from a macro *after* that
    // in some later round and screw up our previously found resolution.
    // See more detailed explanation in
    // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
    fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
        // self > max(invoc, decl) => !(self <= invoc || self <= decl)
        // Expansions are partially ordered, so "may appear after" is an inversion of
        // "certainly appears before or simultaneously" and includes unordered cases.
        let self_parent_expansion = self.expansion;
        let other_parent_expansion = decl.expansion;
        let certainly_before_other_or_simultaneously =
            other_parent_expansion.is_descendant_of(self_parent_expansion);
        let certainly_before_invoc_or_simultaneously =
            invoc_parent_expansion.is_descendant_of(self_parent_expansion);
        !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
    }

    /// Returns whether this declaration may be shadowed or overwritten by something else later.
    /// FIXME: this function considers `unexpanded_invocations`, but not `single_imports`, so
    /// the declaration may not be as "determined" as we think.
    /// FIXME: relationship between this function and similar `NameResolution::determined_decl`
    /// is unclear.
    fn determined<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
        match &self.kind {
            DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
                !import.parent_scope.module.has_unexpanded_invocations(r)
                    && source_decl.determined(r)
            }
            _ => true,
        }
    }
}

#[derive(Debug)]
struct ExternPreludeEntry<'ra> {
    /// Name declaration from an `extern crate` item.
    /// The boolean flag is true is `item_decl` is non-redundant, happens either when
    /// `flag_decl` is `None`, or when `extern crate` introducing `item_decl` used renaming.
    item_decl: Option<(Decl<'ra>, Span, /* introduced by item */ bool)>,
    /// Name declaration from an `--extern` flag, lazily populated on first use.
    flag_decl: Option<
        CacheCell<(
            PendingDecl<'ra>,
            /* finalized */ bool,
            /* open flag (namespaced crate) */ bool,
        )>,
    >,
}

impl ExternPreludeEntry<'_> {
    fn introduced_by_item(&self) -> bool {
        matches!(self.item_decl, Some((.., true)))
    }

    fn flag() -> Self {
        ExternPreludeEntry {
            item_decl: None,
            flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
        }
    }

    fn open_flag() -> Self {
        ExternPreludeEntry {
            item_decl: None,
            flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
        }
    }

    fn span(&self) -> Span {
        match self.item_decl {
            Some((_, span, _)) => span,
            None => DUMMY_SP,
        }
    }
}

struct DeriveData {
    resolutions: Vec<DeriveResolution>,
    helper_attrs: Vec<(usize, IdentKey, Span)>,
    // if this list keeps getting extended, we could use `bitflags`,
    // something like what [`crate::rustc_type_ir::flags::TypeFlags`] is doing.
    has_derive_copy: bool,
    has_derive_ord: bool,
}

pub struct ResolverOutputs<'tcx> {
    pub global_ctxt: ResolverGlobalCtxt,
    pub ast_lowering: ResolverAstLowering<'tcx>,
}

#[derive(Debug)]
struct DelegationFnSig {
    pub has_self: bool,
}

/// The main resolver class.
///
/// This is the visitor that walks the whole crate.
pub struct Resolver<'ra, 'tcx> {
    tcx: TyCtxt<'tcx>,

    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
    expn_that_defined: UnordMap<LocalDefId, ExpnId>,

    graph_root: LocalModule<'ra>,

    /// Assert that we are in speculative resolution mode (unsafe field).
    speculative_flag: SpeculativeFlag,

    prelude: Option<Module<'ra>>,
    extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,

    /// N.B., this is used only for better diagnostics, not name resolution itself.
    field_names: LocalDefIdMap<Vec<Ident>>,
    field_defaults: LocalDefIdMap<Vec<Symbol>>,

    /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
    /// Used for hints during error reporting.
    field_visibility_spans: FxHashMap<DefId, Vec<Span>>,

    /// All imports known to succeed or fail.
    determined_imports: Vec<Import<'ra>>,

    /// All non-determined imports.
    indeterminate_imports: Vec<(Import<'ra>, Option<ImportResolution<'ra>>, usize)>,

    // Spans for local variables found during pattern resolution.
    // Used for suggestions during error reporting.
    pat_span_map: NodeMap<Span>,

    /// Resolutions for nodes that have a single resolution.
    partial_res_map: NodeMap<PartialRes>,
    /// An import will be inserted into this map if it has been used.
    import_use_map: FxHashMap<Import<'ra>, Used>,

    /// `CrateNum` resolutions of `extern crate` items.
    extern_crate_map: UnordMap<LocalDefId, CrateNum>,
    module_children: LocalDefIdMap<Vec<ModChild>>,
    ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,

    /// A map from nodes to anonymous modules.
    /// Anonymous modules are pseudo-modules that are implicitly created around items
    /// contained within blocks.
    ///
    /// For example, if we have this:
    ///
    ///  fn f() {
    ///      fn g() {
    ///          ...
    ///      }
    ///  }
    ///
    /// There will be an anonymous module created around `g` with the ID of the
    /// entry block for `f`.
    block_map: NodeMap<LocalModule<'ra>>,
    /// A fake module that contains no definition and no prelude. Used so that
    /// some AST passes can generate identifiers that only resolve to local or
    /// lang items.
    empty_module: LocalModule<'ra>,
    /// All local modules, including blocks.
    local_modules: Vec<LocalModule<'ra>>,
    /// Eagerly populated map of all local non-block modules.
    local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
    /// Lazily populated cache of modules loaded from external crates.
    extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,

    /// Maps glob imports to the names of items actually imported.
    glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
    glob_error: Option<ErrorGuaranteed>,
    visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
    used_imports: FxHashSet<NodeId>,
    maybe_unused_trait_imports: FxIndexSet<LocalDefId>,

    /// Privacy errors are delayed until the end in order to deduplicate them.
    privacy_errors: Vec<PrivacyError<'ra>>,
    /// Ambiguity errors are delayed for deduplication.
    ambiguity_errors: Vec<AmbiguityError<'ra>>,
    issue_145575_hack_applied: bool,
    /// Visibility path resolution failures are delayed until all modules are collected.
    delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>>,
    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,

    arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
    dummy_decl: Decl<'ra>,
    builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
    builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
    registered_attr_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
    macro_names: FxHashSet<IdentKey>,
    builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
    registered_attr_tools: &'tcx RegisteredTools,
    registered_lint_tools: &'tcx RegisteredTools,
    macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
    /// Eagerly populated map of all local macro definitions.
    local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>>,
    /// Lazily populated cache of macro definitions loaded from external crates.
    extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
    dummy_ext_bang: &'ra Arc<SyntaxExtension>,
    dummy_ext_derive: &'ra Arc<SyntaxExtension>,
    non_macro_attr: &'ra Arc<SyntaxExtension>,
    local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>>,
    ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>>,
    unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
    /// A map from the macro to all its potentially unused arms and the `LocalDefId` of the macro itself.
    unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,
    proc_macro_stubs: FxHashSet<LocalDefId>,
    /// Traces collected during macro resolution and validated when it's complete.
    single_segment_macro_resolutions:
        CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
    multi_segment_macro_resolutions:
        CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
    builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
    /// Derive macros cannot modify the item themselves and have to store the markers in the global
    /// context, so they attach the markers to derive container IDs using this resolver table.
    containers_deriving_copy: FxHashSet<LocalExpnId>,
    containers_deriving_ord: FxHashSet<LocalExpnId>,
    /// Parent scopes in which the macros were invoked.
    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
    invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
    /// `macro_rules` scopes *produced* by expanding the macro invocations,
    /// include all the `macro_rules` items and other invocations generated by them.
    output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
    /// `macro_rules` scopes produced by `macro_rules` item definitions.
    macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
    /// Helper attributes that are in scope for the given expansion.
    helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>>,
    /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
    /// with the given `ExpnId`.
    derive_data: FxHashMap<LocalExpnId, DeriveData>,

    /// Avoid duplicated errors for "name already defined".
    name_already_seen: FxHashMap<Symbol, Span>,

    potentially_unused_imports: Vec<Import<'ra>>,

    potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>>,

    /// Table for mapping struct IDs into struct constructor IDs,
    /// it's not used during normal resolution, only for better error reporting.
    /// Also includes of list of each fields visibility
    struct_ctors: LocalDefIdMap<StructCtor>,

    /// for all the struct
    /// it's not used during normal resolution, only for better error reporting.
    struct_generics: LocalDefIdMap<Generics>,

    lint_buffer: LintBuffer,

    next_node_id: NodeId,

    /// Preserves per owner data once the owner is finished resolving.
    owners: NodeMap<PerOwnerResolverData<'tcx>>,

    /// An entry of `owners` that gets taken out and reinserted whenever an owner is handled.
    current_owner: PerOwnerResolverData<'tcx>,

    disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,

    /// Indices of unnamed struct or variant fields with unresolved attributes.
    placeholder_field_indices: FxHashMap<NodeId, usize>,
    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
    /// we know what parent node that fragment should be attached to thanks to this table,
    /// and how the `impl Trait` fragments were introduced.
    invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,

    /// Amount of lifetime parameters for each item in the crate.
    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
    /// Generic args to suggest for required params (e.g. `<'_>`, `<_, _>`), if any.
    item_required_generic_args_suggestions: FxHashMap<LocalDefId, String>,
    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
    delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,

    main_def: Option<MainDefinition>,
    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
    /// A list of proc macro LocalDefIds, written out in the order in which
    /// they are declared in the static array generated by proc_macro_harness.
    proc_macros: Vec<LocalDefId>,
    confused_type_with_std_module: FxIndexMap<Span, Span>,

    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>>,

    effective_visibilities: EffectiveVisibilities,
    macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,

    doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap>,
    doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>>,
    all_macro_rules: UnordSet<Symbol>,

    /// Invocation ids of all glob delegations.
    glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
    /// Needed because glob delegations wait for all other neighboring macros to expand.
    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
    /// Needed because glob delegations exclude explicitly defined names.
    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,

    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
    /// could be a crate that wasn't imported. For diagnostics use only.
    current_crate_outer_attr_insert_span: Span,

    mods_with_parse_errors: FxHashSet<DefId>,

    /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we
    /// don't need to run it more than once.
    all_crate_macros_already_registered: bool,

    // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types
    // that were encountered during resolution. These names are used to generate item names
    // for APITs, so we don't want to leak details of resolution into these names.
    impl_trait_names: FxHashMap<NodeId, Symbol>,

    /// Stores `#[diagnostic::on_unknown]` attributes placed on module declarations.
    on_unknown_data: FxHashMap<LocalDefId, OnUnknownData>,
    features: &'tcx Features,
}

/// This provides memory for the rest of the crate. The `'ra` lifetime that is
/// used by many types in this crate is an abbreviation of `ResolverArenas`.
#[derive(Default)]
pub struct ResolverArenas<'ra> {
    modules: TypedArena<ModuleData<'ra>>,
    imports: TypedArena<ImportData<'ra>>,
    name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
    ast_paths: TypedArena<ast::Path>,
    macros: TypedArena<Arc<SyntaxExtension>>,
    dropless: DroplessArena,
}

impl<'ra> ResolverArenas<'ra> {
    fn new_def_decl(
        &'ra self,
        res: Res,
        vis: Visibility<ModId>,
        span: Span,
        expansion: LocalExpnId,
        parent_module: Option<Module<'ra>>,
    ) -> Decl<'ra> {
        self.alloc_decl(DeclData {
            kind: DeclKind::Def(res),
            ambiguity: CmCell::new(None),
            initial_vis: vis,
            ambiguity_vis_max: CmCell::new(None),
            ambiguity_vis_min: CmCell::new(None),
            span,
            expansion,
            parent_module,
        })
    }

    fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
        self.new_def_decl(res, Visibility::Public, span, expn_id, None)
    }

    fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
        // SAFETY: `Interned` is valid because values of this type have "identity".
        Interned::new_unchecked(self.dropless.alloc(data))
    }
    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
        // SAFETY: `Interned` is valid because values of this type have "identity".
        Interned::new_unchecked(self.imports.alloc(import))
    }
    fn alloc_name_resolution(&'ra self, resolution: NameResolution<'ra>) -> NameResolutionRef<'ra> {
        // SAFETY: `Interned` is valid because values of this type have "identity".
        Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution)))
    }
    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
        self.dropless.alloc(CacheCell::new(scope))
    }
    fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
        self.dropless.alloc(decl)
    }
    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
        self.ast_paths.alloc_from_iter(paths.iter().cloned())
    }
    fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
        self.macros.alloc(Arc::new(ext))
    }
    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
        self.dropless.alloc_from_iter(spans)
    }
}

impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
        self
    }
}

impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
        self
    }
}

impl<'tcx> Resolver<'_, 'tcx> {
    /// Only call this in analyses after the resolver has finished.
    /// Panics if the node id is currently not in the owner storage,
    /// e.g. because it's further up in the current visitor stack.
    fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
        self.owners[&owner].def_id
    }

    /// Only call this in analyses after the resolver has finished.
    /// Panics if the node id is currently not in the owner storage,
    /// e.g. because it's further up in the current visitor stack.
    fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
        self.owners[&owner].node_id_to_def_id[&id]
    }

    /// Get the `DefId` of a child of the current owner
    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
        self.current_owner.node_id_to_def_id.get(&node).copied()
    }

    /// Get the `DefId` of a child of the current owner
    fn local_def_id(&self, node: NodeId) -> LocalDefId {
        self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
    }

    /// Adds a definition with a parent definition.
    fn create_def(
        &mut self,
        parent: LocalDefId,
        node_id: ast::NodeId,
        name: Option<Symbol>,
        def_kind: DefKind,
        expn_id: ExpnId,
        span: Span,
        is_owner: bool,
    ) -> TyCtxtFeed<'tcx, LocalDefId> {
        assert!(
            !self.current_owner.node_id_to_def_id.contains_key(&node_id),
            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
            node_id,
            name,
            def_kind,
            self.tcx
                .definitions_untracked()
                .def_key(self.current_owner.node_id_to_def_id[&node_id]),
        );

        let disambiguator = self.disambiguators.get_or_create(parent);

        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
        let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
        let def_id = feed.def_id();

        // Create the definition.
        if expn_id != ExpnId::root() {
            self.expn_that_defined.insert(def_id, expn_id);
        }

        // A relative span's parent must be an absolute span.
        debug_assert_eq!(span.data_untracked().parent, None);
        let _id = self.tcx.untracked().source_span.push(span);
        debug_assert_eq!(_id, def_id);

        // Some things for which we allocate `LocalDefId`s don't correspond to
        // anything in the AST, so they don't have a `NodeId`. For these cases
        // we don't need a mapping from `NodeId` to `LocalDefId`.
        if node_id != ast::DUMMY_NODE_ID && !is_owner {
            debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
            self.current_owner.node_id_to_def_id.insert(node_id, def_id);
        }

        feed
    }

    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
        if let Some(def_id) = def_id.as_local() {
            self.item_generics_num_lifetimes[&def_id]
        } else {
            self.tcx.generics_of(def_id).own_counts().lifetimes
        }
    }

    fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
        if let Some(def_id) = def_id.as_local() {
            self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
        } else {
            let required = self
                .tcx
                .generics_of(def_id)
                .own_params
                .iter()
                .filter_map(|param| match param.kind {
                    ty::GenericParamDefKind::Lifetime => Some("'_"),
                    ty::GenericParamDefKind::Type { has_default, .. }
                    | ty::GenericParamDefKind::Const { has_default } => {
                        if has_default {
                            None
                        } else {
                            Some("_")
                        }
                    }
                })
                .collect::<Vec<_>>();

            if required.is_empty() { String::new() } else { format!("<{}>", required.join(", ")) }
        }
    }

    pub fn tcx(&self) -> TyCtxt<'tcx> {
        self.tcx
    }

    /// This function is very slow, as it iterates over the entire
    /// [PerOwnerResolverData::node_id_to_def_id] map for all [Resolver::owners]
    /// just to find the [NodeId]
    /// that corresponds to the given [LocalDefId]. Only use this in
    /// diagnostics code paths. Do not use this during macro expansion,
    /// as it will not find any node ids within your current expansion's stack.
    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
        self.owners
            .items()
            .flat_map(|(_, data)| {
                data.node_id_to_def_id
                    .items()
                    .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
            })
            .filter(|(_, v)| **v == def_id)
            .map(|(k, _)| *k)
            .get_only()
            .unwrap()
    }
}

impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
    pub fn new(
        tcx: TyCtxt<'tcx>,
        attrs: &[ast::Attribute],
        crate_span: Span,
        current_crate_outer_attr_insert_span: Span,
        arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
    ) -> Resolver<'ra, 'tcx> {
        let root_def_id = CRATE_DEF_ID.to_def_id();
        let graph_root = LocalModule::new(
            None,
            ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
            Visibility::Public,
            ExpnId::root(),
            crate_span,
            attr::contains_name(attrs, sym::no_implicit_prelude),
            arenas,
        );
        let local_modules = vec![graph_root];
        let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
        let empty_module = LocalModule::new(
            None,
            ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
            Visibility::Public,
            ExpnId::root(),
            DUMMY_SP,
            true,
            arenas,
        );

        let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
        let crate_feed = tcx.create_local_crate_def_id(crate_span);

        crate_feed.def_kind(DefKind::Mod);
        let mut owners = NodeMap::default();
        owners.insert(CRATE_NODE_ID, owner_data);

        let mut invocation_parents = FxHashMap::default();
        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);

        let extern_prelude = build_extern_prelude(tcx, attrs);
        let registered_attr_tools = tcx.registered_attr_tools(());
        let registered_lint_tools = tcx.registered_lint_tools(());
        let edition = tcx.sess.edition();

        let mut resolver = Resolver {
            tcx,

            // The outermost module has def ID 0; this is not reflected in the
            // AST.
            graph_root,
            // Only set/cleared in Resolver::resolve_imports for now
            speculative_flag: SpeculativeFlag::default(),
            extern_prelude,

            empty_module,
            local_modules,
            local_module_map,
            extern_module_map: Default::default(),

            glob_map: Default::default(),
            maybe_unused_trait_imports: Default::default(),

            arenas,
            dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
            builtin_type_decls: PrimTy::ALL
                .iter()
                .map(|prim_ty| {
                    let res = Res::PrimTy(*prim_ty);
                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
                    (prim_ty.name(), decl)
                })
                .collect(),
            builtin_attr_decls: BUILTIN_ATTRIBUTES
                .iter()
                .map(|builtin_attr| {
                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));
                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
                    (*builtin_attr, decl)
                })
                .collect(),
            registered_attr_tool_decls: registered_attr_tools
                .iter()
                .map(|&ident| {
                    let res = Res::ToolMod;
                    let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
                    (IdentKey::new(ident), decl)
                })
                .collect(),
            registered_attr_tools,
            registered_lint_tools,
            macro_use_prelude: Default::default(),
            extern_macro_map: Default::default(),
            dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
            dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
            non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
            unused_macros: Default::default(),
            unused_macro_rules: Default::default(),
            single_segment_macro_resolutions: Default::default(),
            multi_segment_macro_resolutions: Default::default(),
            lint_buffer: LintBuffer::default(),
            owners,
            current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
            invocation_parents,
            trait_impls: Default::default(),
            confused_type_with_std_module: Default::default(),
            stripped_cfg_items: Default::default(),
            effective_visibilities: Default::default(),
            macro_reachable_adts: Default::default(),
            doc_link_resolutions: Default::default(),
            doc_link_traits_in_scope: Default::default(),
            current_crate_outer_attr_insert_span,
            disambiguators: Default::default(),
            delegation_infos: Default::default(),
            features: tcx.features(),
            // Stable Rust has no field default values, so the initial values the struct
            // definition used to carry are spelled out here, at its only construction site.
            expn_that_defined: Default::default(),
            prelude: None,
            field_names: Default::default(),
            field_defaults: Default::default(),
            field_visibility_spans: default::fx_hash_map(),
            determined_imports: Vec::new(),
            indeterminate_imports: Vec::new(),
            pat_span_map: Default::default(),
            partial_res_map: Default::default(),
            import_use_map: default::fx_hash_map(),
            extern_crate_map: Default::default(),
            module_children: Default::default(),
            ambig_module_children: Default::default(),
            block_map: Default::default(),
            glob_error: None,
            visibilities_for_hashing: Vec::new(),
            used_imports: default::fx_hash_set(),
            privacy_errors: Vec::new(),
            ambiguity_errors: Vec::new(),
            issue_145575_hack_applied: false,
            delayed_vis_resolution_errors: Vec::new(),
            macro_expanded_macro_export_errors: BTreeSet::new(),
            macro_names: default::fx_hash_set(),
            builtin_macros: default::fx_hash_map(),
            local_macro_map: default::fx_hash_map(),
            local_macro_def_scopes: default::fx_hash_map(),
            ast_transform_scopes: default::fx_hash_map(),
            proc_macro_stubs: default::fx_hash_set(),
            builtin_attrs: Vec::new(),
            containers_deriving_copy: default::fx_hash_set(),
            containers_deriving_ord: default::fx_hash_set(),
            invocation_parent_scopes: default::fx_hash_map(),
            output_macro_rules_scopes: default::fx_hash_map(),
            macro_rules_scopes: default::fx_hash_map(),
            helper_attrs: default::fx_hash_map(),
            derive_data: default::fx_hash_map(),
            name_already_seen: default::fx_hash_map(),
            potentially_unused_imports: Vec::new(),
            potentially_unnecessary_qualifications: Vec::new(),
            struct_ctors: Default::default(),
            struct_generics: Default::default(),
            next_node_id: CRATE_NODE_ID,
            placeholder_field_indices: default::fx_hash_map(),
            item_generics_num_lifetimes: default::fx_hash_map(),
            item_required_generic_args_suggestions: default::fx_hash_map(),
            delegation_fn_sigs: Default::default(),
            main_def: None,
            proc_macros: Vec::new(),
            all_macro_rules: Default::default(),
            glob_delegation_invoc_ids: default::fx_hash_set(),
            impl_unexpanded_invocations: default::fx_hash_map(),
            impl_binding_keys: default::fx_hash_map(),
            mods_with_parse_errors: default::fx_hash_set(),
            all_crate_macros_already_registered: false,
            impl_trait_names: default::fx_hash_map(),
            on_unknown_data: default::fx_hash_map(),
        };

        if let Some(directive) = OnUnknownData::from_attrs(&resolver, attrs) {
            resolver.on_unknown_data.insert(CRATE_DEF_ID, directive);
        }

        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
        resolver.feed_visibility(crate_feed, Visibility::Public);

        resolver
    }

    fn new_local_module(
        &mut self,
        parent: Option<LocalModule<'ra>>,
        kind: ModuleKind,
        expn_id: ExpnId,
        span: Span,
        no_implicit_prelude: bool,
    ) -> LocalModule<'ra> {
        let vis =
            kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
        let module =
            LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
        self.local_modules.push(module);
        if let Some(def_id) = module.opt_def_id() {
            self.local_module_map.insert(def_id.expect_local(), module);
        }
        module
    }

    fn next_node_id(&mut self) -> NodeId {
        let start = self.next_node_id;
        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
        self.next_node_id = ast::NodeId::from_u32(next);
        start
    }

    fn next_node_ids(&mut self, count: usize) -> core::ops::Range<NodeId> {
        let start = self.next_node_id;
        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
        self.next_node_id = ast::NodeId::from_usize(end);
        start..self.next_node_id
    }

    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
        &mut self.lint_buffer
    }

    pub fn arenas() -> ResolverArenas<'ra> {
        Default::default()
    }

    fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
        feed.visibility(vis.to_mod_id());
        self.visibilities_for_hashing.push((feed.def_id(), vis));
    }

    pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
        let proc_macros = self.proc_macros;
        let expn_that_defined = self.expn_that_defined;
        let extern_crate_map = self.extern_crate_map;
        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
        let glob_map = self.glob_map;
        let main_def = self.main_def;
        let confused_type_with_std_module = self.confused_type_with_std_module;
        let effective_visibilities = self.effective_visibilities;

        let stripped_cfg_items = self
            .stripped_cfg_items
            .into_iter()
            .filter_map(|item| {
                let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
                Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
            })
            .collect();
        let disambiguators = self
            .disambiguators
            .into_items()
            .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
            .collect();

        let global_ctxt = ResolverGlobalCtxt {
            expn_that_defined,
            visibilities_for_hashing: self.visibilities_for_hashing,
            effective_visibilities,
            macro_reachable_adts: self.macro_reachable_adts,
            extern_crate_map,
            module_children: self.module_children,
            ambig_module_children: self.ambig_module_children,
            glob_map,
            maybe_unused_trait_imports,
            main_def,
            trait_impls: self.trait_impls,
            proc_macros,
            confused_type_with_std_module,
            doc_link_resolutions: self.doc_link_resolutions,
            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
            all_macro_rules: self.all_macro_rules,
            stripped_cfg_items,
            delegation_infos: self.delegation_infos,
        };
        let ast_lowering = ty::ResolverAstLowering {
            partial_res_map: self.partial_res_map,
            next_node_id: self.next_node_id,
            owners: self.owners,
            lint_buffer: Steal::new(self.lint_buffer),
            disambiguators,
        };
        ResolverOutputs { global_ctxt, ast_lowering }
    }

    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
        CStore::from_tcx(self.tcx)
    }

    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
        CStore::from_tcx_mut(self.tcx)
    }

    fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
        match macro_kind {
            MacroKind::Bang => self.dummy_ext_bang,
            MacroKind::Derive => self.dummy_ext_derive,
            MacroKind::Attr => self.non_macro_attr,
        }
    }

    /// Returns a conditionally mutable resolver that cannot be mutated.
    fn cm(&self) -> CmResolver<'_, 'ra, 'tcx> {
        CmResolver::Ref(self)
    }

    /// Returns a conditionally mutable resolver that can be mutated.
    /// Will panic if the `assert_speculative` field is true.
    fn cm_mut(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
        assert!(
            !self.speculative_flag.is_speculative(),
            "can't mutably borrow speculative resolver"
        );
        CmResolver::Mut(self)
    }

    /// Runs the function on each namespace.
    fn per_ns<F: FnMut(&Self, Namespace)>(&self, mut f: F) {
        f(self, TypeNS);
        f(self, ValueNS);
        f(self, MacroNS);
    }

    fn per_ns_mut<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
        f(self, TypeNS);
        f(self, ValueNS);
        f(self, MacroNS);
    }

    fn is_builtin_macro(&self, res: Res) -> bool {
        self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
    }

    fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
        self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
    }

    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
        loop {
            match ctxt.outer_expn_data().macro_def_id {
                Some(def_id) => return def_id,
                None => ctxt.remove_mark(),
            };
        }
    }

    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
        self.tcx.sess.time("resolve_crate", || {
            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
            });
            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
            self.tcx
                .sess
                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
            let (use_items, use_injections) =
                self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
            self.tcx.sess.time("resolve_main", || self.resolve_main());
            self.tcx.sess.time("resolve_check_unused", || self.check_unused(use_items));
            self.tcx
                .sess
                .time("resolve_report_errors", || self.report_errors(krate, use_injections));
            self.tcx
                .sess
                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
        });

        // Don't mutate the cstore or stable crate id map from here on.
        self.tcx.untracked().freeze_cstore();
    }

    fn traits_in_scope(
        &mut self,
        current_trait: Option<Module<'ra>>,
        parent_scope: &ParentScope<'ra>,
        sp: Span,
        assoc_item: Option<(Symbol, Namespace)>,
    ) -> &'tcx [TraitCandidate<'tcx>] {
        let mut found_traits = Vec::new();

        if let Some(module) = current_trait {
            if self.trait_may_have_item(Some(module), assoc_item) {
                let def_id = module.def_id();
                found_traits.push(TraitCandidate {
                    def_id,
                    import_ids: &[],
                    lint_ambiguous: false,
                });
            }
        }

        let scope_set = ScopeSet::All(TypeNS);
        let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
        let cmr = self.cm_mut();
        cmr.visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
            match scope {
                Scope::ModuleNonGlobs(module, _) => {
                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
                }
                Scope::ModuleGlobs(..) => {
                    // Already handled in `ModuleNonGlobs` (but see #144993).
                }
                Scope::StdLibPrelude => {
                    if let Some(module) = this.prelude {
                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
                    }
                }
                Scope::ExternPreludeItems
                | Scope::ExternPreludeFlags
                | Scope::ToolAttributePrelude
                | Scope::BuiltinTypes => {}
                _ => unreachable!(),
            }
            ControlFlow::<()>::Continue(())
        });

        self.tcx.hir_arena.alloc_slice(&found_traits)
    }

    fn traits_in_module(
        &mut self,
        module: Module<'ra>,
        assoc_item: Option<(Symbol, Namespace)>,
        found_traits: &mut Vec<TraitCandidate<'tcx>>,
    ) {
        module.ensure_traits(self);
        let traits = module.traits.borrow(self);
        for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
            traits.as_ref().unwrap().iter()
        {
            if self.trait_may_have_item(trait_module, assoc_item) {
                let def_id = trait_binding.res().def_id();
                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
                found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
            }
        }
    }

    // List of traits in scope is pruned on best effort basis. We reject traits not having an
    // associated item with the given name and namespace (if specified). This is a conservative
    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
    // associated items.
    fn trait_may_have_item(
        &self,
        trait_module: Option<Module<'ra>>,
        assoc_item: Option<(Symbol, Namespace)>,
    ) -> bool {
        match (trait_module, assoc_item) {
            (Some(trait_module), Some((name, ns))) => self
                .resolutions(trait_module)
                .iter()
                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
            _ => true,
        }
    }

    fn find_transitive_imports(
        &mut self,
        mut kind: &DeclKind<'_>,
        trait_name: Symbol,
    ) -> &'tcx [LocalDefId] {
        let mut import_ids: SmallVec<[LocalDefId; 1]> = smallvec![];
        while let DeclKind::Import { import, source_decl, .. } = kind {
            if let Some(def_id) = import.def_id() {
                self.maybe_unused_trait_imports.insert(def_id);
                import_ids.push(def_id);
            }
            self.add_to_glob_map(*import, trait_name);
            kind = &source_decl.kind;
        }

        self.tcx.hir_arena.alloc_slice(&import_ids)
    }

    fn resolutions(&self, module: Module<'ra>) -> CmRef<'ra, ResolutionTable<'ra>> {
        match &module.0.0.lazy_resolutions {
            Resolutions::Local(local_res) => local_res.borrow_checked(self),
            Resolutions::Extern(extern_res) => {
                // It is fine to return a `CmRef::Untracked`, we never give out a `&mut`
                // to an external table.
                CmRef::Untracked(
                    // As long as 1 thread is building this external table, all other threads will wait.
                    extern_res
                        .get_or_init(|| self.build_reduced_graph_external(module.expect_extern())),
                )
            }
        }
    }

    fn resolutions_mut(&mut self, module: Module<'ra>) -> RefMut<'ra, ResolutionTable<'ra>> {
        match &module.0.0.lazy_resolutions {
            Resolutions::Local(local_res) => local_res.borrow_mut(self),
            Resolutions::Extern(_) => {
                // We do not allow in place mutations of the external resolution table. In fact,
                // we never attempt it.
                unreachable!("Attempted to mutably borrow an extenral resolution table")
            }
        }
    }

    fn resolution(
        &self,
        module: Module<'ra>,
        key: BindingKey,
    ) -> Option<CmRef<'ra, NameResolution<'ra>>> {
        self.resolutions(module).get(&key).map(|resolution| resolution.0.borrow_checked(self))
    }

    #[track_caller]
    fn resolution_or_default(
        &mut self,
        module: Module<'ra>,
        key: BindingKey,
        orig_ident_span: Span,
    ) -> NameResolutionRef<'ra> {
        *self.resolutions_mut(module).entry(key).or_insert_with(|| {
            self.arenas.alloc_name_resolution(NameResolution::new(orig_ident_span))
        })
    }

    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
        for ambiguity_error in &self.ambiguity_errors {
            // if the span location and ident as well as its span are the same
            if ambiguity_error.kind == ambi.kind
                && ambiguity_error.ident == ambi.ident
                && ambiguity_error.ident.span == ambi.ident.span
                && ambiguity_error.b1.span == ambi.b1.span
                && ambiguity_error.b2.span == ambi.b2.span
            {
                return true;
            }
        }
        false
    }

    fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
        if let Some((b2, warning)) = used_decl.ambiguity.get() {
            let ambiguity_error = AmbiguityError {
                kind: AmbiguityKind::GlobVsGlob,
                ambig_vis: None,
                ident,
                b1: used_decl,
                b2,
                scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
                scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
                warning: if warning { Some(AmbiguityWarning::GlobImport) } else { None },
            };
            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
                // avoid duplicated span information to be emit out
                self.ambiguity_errors.push(ambiguity_error);
            }
        }
        if let DeclKind::Import { import, source_decl } = used_decl.kind {
            if let ImportKind::MacroUse { warn_private: true } = import.kind {
                // Do not report the lint if the macro name resolves in stdlib prelude
                // even without the problematic `macro_use` import.
                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
                    let empty_module = self.empty_module;
                    let arenas = self.arenas;
                    self.cm()
                        .maybe_resolve_ident_in_module(
                            ModuleOrUniformRoot::Module(prelude),
                            ident,
                            MacroNS,
                            &ParentScope::module(empty_module, arenas),
                            None,
                        )
                        .is_ok()
                });
                if !found_in_stdlib_prelude {
                    self.lint_buffer().buffer_lint(
                        PRIVATE_MACRO_USE,
                        import.root_id,
                        ident.span,
                        diagnostics::MacroIsPrivate { ident },
                    );
                }
            }
            // Avoid marking `extern crate` items that refer to a name from extern prelude,
            // but not introduce it, as used if they are accessed from lexical scope.
            if used == Used::Scope
                && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
                && let Some((item_decl, _, false)) = entry.item_decl
                && item_decl == used_decl
            {
                return;
            }
            let old_used = self.import_use_map.entry(import).or_insert(used);
            if *old_used < used {
                *old_used = used;
            }
            if let Some(id) = import.id() {
                self.used_imports.insert(id);
            }
            self.add_to_glob_map(import, ident.name);
            self.record_use(ident, source_decl, Used::Other);
        }
    }

    #[inline]
    fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
        if let ImportKind::Glob { def_id, .. } = import.kind {
            self.glob_map.entry(def_id).or_default().insert(name);
        }
    }

    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
        debug!("resolve_crate_root({:?})", ident);
        let mut ctxt = ident.span.ctxt();
        let mark = if ident.name == kw::DollarCrate {
            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
            // definitions actually produced by `macro` and `macro` definitions produced by
            // `macro_rules!`, but at least such configurations are not stable yet.
            ctxt = ctxt.normalize_to_macro_rules();
            debug!(
                "resolve_crate_root: marks={:?}",
                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
            );
            let mut iter = ctxt.marks().into_iter().rev().peekable();
            let mut result = None;
            // Find the last opaque mark from the end if it exists.
            while let Some(&(mark, transparency)) = iter.peek() {
                if transparency == Transparency::Opaque {
                    result = Some(mark);
                    iter.next();
                } else {
                    break;
                }
            }
            debug!(
                "resolve_crate_root: found opaque mark {:?} {:?}",
                result,
                result.map(|r| r.expn_data())
            );
            // Then find the last semi-opaque mark from the end if it exists.
            for (mark, transparency) in iter {
                if transparency == Transparency::SemiOpaque {
                    result = Some(mark);
                } else {
                    break;
                }
            }
            debug!(
                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
                result,
                result.map(|r| r.expn_data())
            );
            result
        } else {
            debug!("resolve_crate_root: not DollarCrate");
            ctxt = ctxt.normalize_to_macros_2_0();
            ctxt.adjust(ExpnId::root())
        };
        let module = match mark {
            Some(def) => self.expn_def_scope(def),
            None => {
                debug!(
                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
                    ident, ident.span
                );
                return self.graph_root.to_module();
            }
        };
        let module = self.expect_module(
            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
        );
        debug!(
            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
            ident,
            module,
            module.name(),
            ident.span
        );
        module
    }

    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
        let mut module = self.expect_module(module.nearest_parent_mod().to_def_id());
        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
            module = self.expect_module(parent.nearest_parent_mod().to_def_id());
        }
        module
    }

    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
        debug!("(recording res) recording {:?} for {}", resolution, node_id);
        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
            panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
        }
    }

    fn record_pat_span(&mut self, node: NodeId, span: Span) {
        debug!("(recording pat) recording {:?} for {:?}", node, span);
        self.pat_span_map.insert(node, span);
    }

    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
    }

    fn disambiguate_macro_rules_vs_modularized(
        &self,
        macro_rules: Decl<'ra>,
        modularized: Decl<'ra>,
    ) -> bool {
        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
        // is disambiguated to mitigate regressions from macro modularization.
        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
        //
        // Panic on unwrap should be impossible, the only name_bindings passed in should be from
        // `resolve_ident_in_scope_set` which will always refer to a local binding from an
        // import or macro definition.
        let macro_rules = macro_rules.parent_module.unwrap();
        let modularized = modularized.parent_module.unwrap();
        macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
            && modularized.is_ancestor_of(macro_rules)
    }
}

// A `self: CmResolver` receiver on `Resolver` needs the unstable `arbitrary_self_types`, so this
// lives in an inherent impl on `CmResolver` itself.
impl<'r, 'ra, 'tcx> CmResolver<'r, 'ra, 'tcx> {
    fn extern_prelude_get_item(
        mut self,
        ident: IdentKey,
        orig_ident_span: Span,
        finalize: bool,
    ) -> Option<Decl<'ra>> {
        let entry = self.extern_prelude.get(&ident);
        entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
            if finalize {
                self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
            }
            decl
        })
    }
}

impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
    fn extern_prelude_get_flag(
        &self,
        ident: IdentKey,
        orig_ident_span: Span,
        finalize: bool,
    ) -> Option<Decl<'ra>> {
        let entry = self.extern_prelude.get(&ident);
        entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
            let (pending_decl, finalized, is_open) = flag_decl.get();
            let decl = match pending_decl {
                PendingDecl::Ready(decl) => {
                    if finalize && !finalized && !is_open {
                        self.cstore_mut().process_path_extern(
                            self.tcx,
                            ident.name,
                            orig_ident_span,
                        );
                    }
                    decl
                }
                PendingDecl::Pending => {
                    debug_assert!(!finalized);
                    if is_open {
                        let res = Res::OpenMod(ident.name);
                        Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
                    } else {
                        let crate_id = if finalize {
                            self.cstore_mut().process_path_extern(
                                self.tcx,
                                ident.name,
                                orig_ident_span,
                            )
                        } else {
                            self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
                        };
                        crate_id.map(|crate_id| {
                            let def_id = crate_id.as_def_id();
                            let res = Res::Def(DefKind::Mod, def_id);
                            self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
                        })
                    }
                }
            };
            flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
            decl.or_else(|| finalize.then_some(self.dummy_decl))
        })
    }

    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
    /// isn't something that can be returned because it can't be made to live that long,
    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
    /// just that an error occurred.
    fn resolve_rustdoc_path(
        &self,
        path_str: &str,
        ns: Namespace,
        parent_scope: ParentScope<'ra>,
    ) -> Option<Res> {
        let segments: Result<Vec<_>, ()> = path_str
            .split("::")
            .enumerate()
            .map(|(i, s)| {
                let sym = if s.is_empty() {
                    if i == 0 {
                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
                        kw::PathRoot
                    } else {
                        return Err(()); // occurs in cases like `String::`
                    }
                } else {
                    Symbol::intern(s)
                };
                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
            })
            .collect();
        let Ok(segments) = segments else { return None };

        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
            PathResult::NonModule(path_res) => {
                path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
            }
            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
                None
            }
            path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
                bug!("got invalid path_result: {path_result:?}")
            }
        }
    }

    /// Retrieves definition span of the given `DefId`.
    fn def_span(&self, def_id: DefId) -> Span {
        match def_id.as_local() {
            Some(def_id) => self.tcx.source_span(def_id),
            // Query `def_span` is not used because hashing its result span is expensive.
            None => self.cstore().def_span_untracked(self.tcx(), def_id),
        }
    }

    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
        match def_id.as_local() {
            Some(def_id) => self.field_names.get(&def_id).cloned(),
            None if matches!(
                self.tcx.def_kind(def_id),
                DefKind::Struct | DefKind::Union | DefKind::Variant
            ) =>
            {
                Some(
                    self.tcx
                        .associated_item_def_ids(def_id)
                        .iter()
                        .map(|&def_id| {
                            Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
                        })
                        .collect(),
                )
            }
            _ => None,
        }
    }

    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
        match def_id.as_local() {
            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
            None if matches!(
                self.tcx.def_kind(def_id),
                DefKind::Struct | DefKind::Union | DefKind::Variant
            ) =>
            {
                Some(
                    self.tcx
                        .associated_item_def_ids(def_id)
                        .iter()
                        .filter_map(|&def_id| {
                            self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
                        })
                        .collect(),
                )
            }
            _ => None,
        }
    }

    /// Checks if an expression refers to a function marked with
    /// `#[rustc_legacy_const_generics]` and returns the argument index list
    /// from the attribute.
    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
        let ExprKind::Path(None, path) = &expr.kind else {
            return None;
        };
        // Don't perform legacy const generics rewriting if the path already
        // has generic arguments.
        if path.segments.last().unwrap().args.is_some() {
            return None;
        }

        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;

        // We only support cross-crate argument rewriting. Uses
        // within the same crate should be updated to use the new
        // const generics style.
        if def_id.is_local() {
            return None;
        }

        find_attr!(
            // we can use parsed attrs here since for other crates they're already available
            self.tcx, def_id,
            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
        )
        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
    }

    fn resolve_main(&mut self) {
        let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
        // Don't try to resolve main unless it's an executable
        if !any_exe {
            return;
        }

        let module = self.graph_root;
        let ident = Ident::with_dummy_span(sym::main);
        let parent_scope = &ParentScope::module(module, self.arenas);

        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
            ModuleOrUniformRoot::Module(module.to_module()),
            ident,
            ValueNS,
            parent_scope,
            None,
        ) else {
            return;
        };

        let res = name_binding.res();
        let is_import = name_binding.is_import();
        let span = name_binding.span;
        if let Res::Def(DefKind::Fn, _) = res {
            self.record_use(ident, name_binding, Used::Other);
        }
        self.main_def = Some(MainDefinition { res, is_import, span });
    }
}

fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
    this: &mut R,
    owner: NodeId,
    work: impl FnOnce(&mut R) -> T,
) -> T {
    let tables = this.as_mut().owners.remove(&owner).unwrap();
    with_owner_tables(this, owner, tables, work)
}

#[instrument(level = "debug", skip(this, work))]
fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
    this: &mut R,
    owner: NodeId,
    tables: PerOwnerResolverData<'tcx>,
    work: impl FnOnce(&mut R) -> T,
) -> T {
    debug_assert!(!this.as_mut().owners.contains_key(&owner));
    let resolver = this.as_mut();
    let old_owner = mem::replace(&mut resolver.current_owner, tables);
    let ret = work(this);
    let resolver = this.as_mut();
    let overwritten =
        resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
    assert!(overwritten.is_none());
    ret
}

fn build_extern_prelude<'tcx, 'ra>(
    tcx: TyCtxt<'tcx>,
    attrs: &[ast::Attribute],
) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
    let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
        .sess
        .opts
        .externs
        .iter()
        .filter_map(|(name, entry)| {
            // Make sure `self`, `super`, `_` etc do not get into extern prelude.
            // FIXME: reject `--extern self` and similar in option parsing instead.
            if entry.add_prelude
                && let sym = Symbol::intern(name)
                && sym.can_be_raw()
            {
                Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
            } else {
                None
            }
        })
        .collect();

    // Add open base entries for namespaced crates whose base segment
    // is missing from the prelude (e.g. `foo::bar` without `foo`).
    // These are necessary in order to resolve the open modules, whereas
    // the namespaced names are necessary in `extern_prelude` for actually
    // resolving the namespaced crates.
    let missing_open_bases: Vec<IdentKey> = extern_prelude
        .keys()
        .filter_map(|ident| {
            let (base, _) = ident.name.as_str().split_once("::")?;
            let base_sym = Symbol::intern(base);
            base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
        })
        .filter(|base_ident| !extern_prelude.contains_key(base_ident))
        .collect();

    extern_prelude.extend(
        missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
    );

    // Inject `core` / `std` unless suppressed by attributes.
    if !attr::contains_name(attrs, sym::no_core) {
        extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());

        if !attr::contains_name(attrs, sym::no_std) {
            extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
        }
    }

    extern_prelude
}

fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
    let mut result = String::new();
    for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
        if i > 0 {
            result.push_str("::");
        }
        if Ident::with_dummy_span(name).is_raw_guess() {
            result.push_str("r#");
        }
        result.push_str(name.as_str());
    }
    result
}

fn path_names_to_string(path: &Path) -> String {
    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
}

/// A somewhat inefficient routine to obtain the name of a module.
fn module_to_string(mut module: Module<'_>) -> Option<String> {
    let mut names = Vec::new();
    while let Some(parent) = module.parent {
        names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
        module = parent;
    }
    if names.is_empty() {
        return None;
    }
    Some(names_to_string(names.iter().rev().copied()))
}

#[derive(Copy, Clone, PartialEq, Debug)]
enum Stage {
    /// Resolving an import or a macro.
    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
    /// Used by default as a more restrictive variant that can produce additional errors.
    Early,
    /// Resolving something in late resolution when all imports are resolved
    /// and all macros are expanded.
    Late,
}

/// Parts of import data required for finalizing import resolution.
/// Does not carry a lifetime, so it can be stored in `Finalize`.
#[derive(Copy, Clone, Debug)]
struct ImportSummary {
    vis: Visibility,
    nearest_parent_mod: LocalModId,
    is_single: bool,
    priv_macro_use: bool,
    span: Span,
}

/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
#[derive(Copy, Clone, Debug)]
struct Finalize {
    /// Node ID for linting.
    node_id: NodeId,
    /// Span of the whole path or some its characteristic fragment.
    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
    path_span: Span,
    /// Span of the path start, suitable for prepending something to it.
    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
    root_span: Span,
    /// Whether to report privacy errors or silently return "no resolution" for them,
    /// similarly to speculative resolution.
    report_private: bool,
    /// Tracks whether an item is used in scope or used relatively to a module.
    used: Used,
    /// Finalizing early or late resolution.
    stage: Stage,
    /// Some import data, in case we are resolving an import's final segment.
    import: Option<ImportSummary>,
}

impl Finalize {
    fn new(node_id: NodeId, path_span: Span) -> Finalize {
        Finalize::with_root_span(node_id, path_span, path_span)
    }

    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
        Finalize {
            node_id,
            path_span,
            root_span,
            report_private: true,
            used: Used::Other,
            stage: Stage::Early,
            import: None,
        }
    }
}

pub fn provide(providers: &mut Providers) {
    providers.registered_attr_tools = macros::registered_attr_tools;
    providers.registered_lint_tools = macros::registered_lint_tools;
}

/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
///
/// `Cm` stands for "conditionally mutable".
///
/// Prefer constructing it through `Resolver::cm(_mut)` to ensure correctness.
type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;

// FIXME: These are cells for caches that can be populated even during speculative resolution,
// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
// parallel name resolution.
use core::cell::{Cell as CacheCell, RefCell as CacheRefCell};

mod ref_mut {
    use core::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
    use core::fmt;
    use core::ops::Deref;

    use crate::rustc_resolve::Resolver;

    /// A reference type that conditionally allows mutable access.
    pub(crate) enum RefOrMut<'a, T> {
        Ref(&'a T),
        Mut(&'a mut T),
    }

    impl<'a, T> Deref for RefOrMut<'a, T> {
        type Target = T;

        fn deref(&self) -> &Self::Target {
            match self {
                RefOrMut::Ref(r) => r,
                RefOrMut::Mut(r) => r,
            }
        }
    }

    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
        fn as_ref(&self) -> &T {
            &*self
        }
    }

    impl<'a, T> RefOrMut<'a, T> {
        /// This is needed because the type may allow mutable access and is therefore not `Copy`.
        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
            match self {
                RefOrMut::Ref(r) => RefOrMut::Ref(r),
                RefOrMut::Mut(r) => RefOrMut::Mut(r),
            }
        }

        /// Returns a mutable reference to the inner value if allowed.
        ///
        /// # Panics
        ///
        /// Panics if the wrapped reference is immutable.
        #[track_caller]
        pub(crate) fn get_mut(&mut self) -> &mut T {
            match self {
                RefOrMut::Ref(_) => panic!("can't mutably borrow an immutable reference"),
                RefOrMut::Mut(r) => r,
            }
        }
    }

    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
    #[derive(Default)]
    pub(crate) struct CmCell<T>(Cell<T>);

    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_tuple("CmCell").field(&self.get()).finish()
        }
    }

    impl<T: Copy> Clone for CmCell<T> {
        fn clone(&self) -> CmCell<T> {
            CmCell::new(self.get())
        }
    }

    impl<T: Copy> CmCell<T> {
        pub(crate) const fn get(&self) -> T {
            self.0.get()
        }

        pub(crate) fn update<'ra, 'tcx>(
            &self,
            r: &mut Resolver<'ra, 'tcx>,
            f: impl FnOnce(T) -> T,
        ) {
            let old = self.get();
            self.set(f(old), r);
        }
    }

    impl<T> CmCell<T> {
        pub(crate) const fn new(value: T) -> CmCell<T> {
            CmCell(Cell::new(value))
        }

        pub(crate) fn set<'ra, 'tcx>(&self, val: T, _: &mut Resolver<'ra, 'tcx>) {
            self.0.set(val);
        }

        pub(crate) fn set_checked<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
            assert!(
                !r.speculative_flag.is_speculative(),
                "Cannot mutate `CmCell` during speculative resolution"
            );
            self.0.set(val);
        }

        pub(crate) fn into_inner(self) -> T {
            self.0.into_inner()
        }
    }

    pub(crate) enum CmRef<'b, T> {
        /// A tracked borrow of a [`CmRefCell`]
        Tracked(Ref<'b, T>),
        /// An untracked or normal reference (not dynamically borrow-checked by `RefCell`)
        Untracked(&'b T),
    }

    impl<'b, T> Deref for CmRef<'b, T> {
        type Target = T;

        fn deref(&self) -> &Self::Target {
            match self {
                CmRef::Tracked(r) => r,
                CmRef::Untracked(r) => r,
            }
        }
    }

    pub(crate) mod speculative {
        #[derive(Debug, Clone, Copy, Default)]
        pub(crate) struct SpeculativeFlag(bool);

        impl SpeculativeFlag {
            /// # SAFETY
            ///
            /// All borrows created by `CmRefCell::borrow` must be dropped before changing
            /// the speculative flag:
            /// - `tracked` borrows before setting it to `true`.
            /// - `untracked` borrows before setting it to `false`.
            pub(crate) unsafe fn set(&mut self, value: bool) {
                self.0 = value;
            }

            pub(crate) fn is_speculative(&self) -> bool {
                self.0
            }
        }
    }

    /// A wrapper around a [`RefCell`] that only allows writes (mutable borrows) based on a condition in the resolver.
    #[derive(Default)]
    pub(crate) struct CmRefCell<T>(RefCell<T>);

    impl<T> CmRefCell<T> {
        pub(crate) fn new(value: T) -> CmRefCell<T> {
            CmRefCell(RefCell::new(value))
        }

        #[track_caller]
        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &mut Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
            self.try_borrow_mut(r).unwrap()
        }

        #[track_caller]
        pub(crate) fn borrow_mut_checked<'ra, 'tcx>(
            &self,
            r: &Resolver<'ra, 'tcx>,
        ) -> RefMut<'_, T> {
            self.try_borrow_mut_checked(r).unwrap()
        }

        #[track_caller]
        pub(crate) fn try_borrow_mut_checked<'ra, 'tcx>(
            &self,
            r: &Resolver<'ra, 'tcx>,
        ) -> Result<RefMut<'_, T>, BorrowMutError> {
            assert!(
                !r.speculative_flag.is_speculative(),
                "Cannot mutate `CmRefCell` state/value during speculative resolution"
            );
            self.0.try_borrow_mut()
        }

        #[track_caller]
        pub(crate) fn try_borrow_mut<'ra, 'tcx>(
            &self,
            _: &mut Resolver<'ra, 'tcx>,
        ) -> Result<RefMut<'_, T>, BorrowMutError> {
            self.0.try_borrow_mut()
        }

        pub(crate) fn borrow<'ra, 'tcx>(&self, _: &mut Resolver<'ra, 'tcx>) -> Ref<'_, T> {
            self.0.borrow()
        }

        pub(crate) fn borrow_checked<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> CmRef<'_, T> {
            if r.speculative_flag.is_speculative() {
                // `try_borrow_unguarded` is unsafe because it returns a `&T` instead
                // of `Ref<'_, T>`. It does provides an extra check to make sure no live
                // `RefMut`s are still alive, but the other way can not be checked, so:
                //
                // SAFETY: This is only safe because we know that every `Untracked` borrow
                // is only created during the import resolutions phase:
                //
                // ```rust
                // // tracked borrows
                // unsafe { resolver.speculative_flag.set_true() };
                // import_resolution(); // untracked borrows
                // unsafe { resolver.speculative_flag.set_true() };
                // // tracked borrows
                // ```
                //
                // `speculative::Flag` requires all of the borrows that happened during a
                // particular phase are dropped before being set to true/false.
                CmRef::Untracked(unsafe { self.0.try_borrow_unguarded().unwrap() })
            } else {
                CmRef::Tracked(self.0.borrow())
            }
        }
    }

    impl<T: Default> CmRefCell<T> {
        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
            if r.speculative_flag.is_speculative() {
                panic!("not allowed to mutate a CmRefCell during speculative resolution");
            }
            self.0.take()
        }
    }
}

mod hygiene {
    use crate::rustc_span::{ExpnId, SyntaxContext};

    /// A newtype around `SyntaxContext` that can only keep contexts produced by
    /// [SyntaxContext::normalize_to_macros_2_0].
    #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
    pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);

    impl Macros20NormalizedSyntaxContext {
        #[inline]
        pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
            Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
        }

        #[inline]
        pub(crate) fn new_adjusted(
            mut ctxt: SyntaxContext,
            expn_id: ExpnId,
        ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
            let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
            (Macros20NormalizedSyntaxContext(ctxt), def)
        }

        #[inline]
        pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
            debug_assert_eq!(ctxt, ctxt.normalize_to_macros_2_0());
            Macros20NormalizedSyntaxContext(ctxt)
        }

        /// The passed closure must preserve the context's normalized-ness.
        #[inline]
        pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
            let ret = f(&mut self.0);
            debug_assert_eq!(self.0, self.0.normalize_to_macros_2_0());
            ret
        }
    }

    impl core::ops::Deref for Macros20NormalizedSyntaxContext {
        type Target = SyntaxContext;
        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }
}