frontend 0.4.1

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
//! A bunch of methods and structures more or less related to resolving imports.

// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use core::cmp::Ordering;
use core::mem;

use crate::rustc_ast::NodeId;
use crate::rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use crate::rustc_data_structures::intern::Interned;
use crate::rustc_errors::{Applicability, BufferedEarlyLint, Diagnostic};
use crate::rustc_expand::base::SyntaxExtensionKind;
use crate::rustc_hir::def::{self, DefKind, PartialRes};
use crate::rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap};
use crate::rustc_lint_defs::LintId;
use crate::rustc_lint_defs::builtin::{
    AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
    PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
};
use crate::rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
use crate::span_bug;
use crate::rustc_middle::ty::Visibility;
use crate::rustc_session::diagnostics::feature_err;
use crate::rustc_span::edit_distance::find_best_match_for_name;
use crate::rustc_span::hygiene::LocalExpnId;
use crate::rustc_span::{Ident, Span, Symbol, kw, sym};
use tracing::debug;

use crate::rustc_resolve::Namespace::{self, *};
use crate::rustc_resolve::diagnostics::impls::{OnUnknownData, Suggestion};
use crate::rustc_resolve::diagnostics::{
    self, CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS,
    CannotBeReexportedPrivate, CannotBeReexportedPrivateNS, CannotDetermineImportResolution,
    CannotGlobImportAllCrates, ConsiderAddingMacroExport, ConsiderMarkingAsPub,
    ConsiderMarkingAsPubCrate,
};
use crate::rustc_resolve::ref_mut::{CmCell, CmRefCell};
use crate::rustc_resolve::{
    AmbiguityError, BindingKey, Decl, DeclData, DeclKind, Determinacy, Finalize, IdentKey,
    ImportSuggestion, ImportSummary, LocalModule, ModuleOrUniformRoot, ParentScope, PathResult,
    PerNS, Res, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string,
    names_to_string,
};

/// A potential import declaration in the process of being planted into a module.
/// Also used for lazily planting names from `--extern` flags to extern prelude.
#[derive(Clone, Copy, Default, PartialEq, Debug)]
pub(crate) enum PendingDecl<'ra> {
    Ready(Option<Decl<'ra>>),
    #[default]
    Pending,
}

enum ImportResolutionKind<'ra> {
    // these are the decls the import imports, not the import declarations themselves
    Single(PerNS<PendingDecl<'ra>>),
    Glob(Vec<(Decl<'ra>, BindingKey, Span /* orig_ident_span */)>),
}

pub(crate) struct ImportResolution<'ra> {
    kind: ImportResolutionKind<'ra>,
    imported_module: ModuleOrUniformRoot<'ra>,
}

impl<'ra> PendingDecl<'ra> {
    pub(crate) fn decl(self) -> Option<Decl<'ra>> {
        match self {
            PendingDecl::Ready(decl) => decl,
            PendingDecl::Pending => None,
        }
    }
}

/// Contains data for specific kinds of imports.
pub(crate) enum ImportKind<'ra> {
    Single {
        /// `source` in `use prefix::source as target`.
        source: Ident,
        /// `target` in `use prefix::source as target`.
        /// It will directly use `source` when the format is `use prefix::source`.
        target: Ident,
        /// Name declarations introduced by the import.
        decls: PerNS<CmCell<PendingDecl<'ra>>>,
        /// Did this import result from a nested import? i.e. `use foo::{bar, baz};`
        nested: bool,
        /// The ID of the `UseTree` that imported this `Import`.
        ///
        /// In the case where the `Import` was expanded from a "nested" use tree,
        /// this id is the ID of the leaf tree. For example:
        ///
        /// ```ignore (pacify the merciless tidy)
        /// use foo::bar::{a, b}
        /// ```
        ///
        /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
        /// for `a` in this field.
        id: NodeId,
        def_id: LocalDefId,
    },
    Glob {
        // The visibility of the greatest re-export.
        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
        max_vis: CmCell<Option<Visibility>>,
        id: NodeId,
        def_id: LocalDefId,
    },
    ExternCrate {
        source: Option<Symbol>,
        target: Ident,
        id: NodeId,
        def_id: LocalDefId,
    },
    MacroUse {
        /// A field has been added indicating whether it should be reported as a lint,
        /// addressing issue#119301.
        warn_private: bool,
    },
    MacroExport,
}

/// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
/// contain `Cell`s which can introduce infinite loops while printing.
impl<'ra> core::fmt::Debug for ImportKind<'ra> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use ImportKind::*;
        match self {
            Single { source, target, decls, nested, id, def_id } => f
                .debug_struct("Single")
                .field("source", source)
                .field("target", target)
                // Ignore the nested bindings to avoid an infinite loop while printing.
                .field(
                    "decls",
                    &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!(".."))),
                )
                .field("nested", nested)
                .field("id", id)
                .field("def_id", def_id)
                .finish(),
            Glob { max_vis, id, def_id } => f
                .debug_struct("Glob")
                .field("max_vis", max_vis)
                .field("id", id)
                .field("def_id", def_id)
                .finish(),
            ExternCrate { source, target, id, def_id } => f
                .debug_struct("ExternCrate")
                .field("source", source)
                .field("target", target)
                .field("id", id)
                .field("def_id", def_id)
                .finish(),
            MacroUse { warn_private } => {
                f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
            }
            MacroExport => f.debug_struct("MacroExport").finish(),
        }
    }
}

/// One import.
#[derive(Debug)]
pub(crate) struct ImportData<'ra> {
    pub kind: ImportKind<'ra>,

    /// Node ID of the "root" use item -- this is always the same as `ImportKind`'s `id`
    /// (if it exists) except in the case of "nested" use trees, in which case
    /// it will be the ID of the root use tree. e.g., in the example
    /// ```ignore (incomplete code)
    /// use foo::bar::{a, b}
    /// ```
    /// this would be the ID of the `use foo::bar` `UseTree` node.
    /// In case of imports without their own node ID it's the closest node that can be used,
    /// for example, for reporting lints.
    pub root_id: NodeId,

    /// Span of the entire use statement.
    pub use_span: Span,

    /// Span of the entire use statement with attributes.
    pub use_span_with_attributes: Span,

    /// Did the use statement have any attributes?
    pub has_attributes: bool,

    /// Span of this use tree.
    pub span: Span,

    /// Span of the *root* use tree (see `root_id`).
    pub root_span: Span,

    pub parent_scope: ParentScope<'ra>,
    pub module_path: Vec<Segment>,
    /// The resolution of `module_path`:
    ///
    /// | `module_path` | `imported_module` | remark |
    /// |-|-|-|
    /// |`use prefix::foo`| `ModuleOrUniformRoot::Module(prefix)`         | - |
    /// |`use ::foo`      | `ModuleOrUniformRoot::ExternPrelude`          | 2018+ editions |
    /// |`use ::foo`      | `ModuleOrUniformRoot::ModuleAndExternPrelude` | a special case in 2015 edition |
    /// |`use foo`        | `ModuleOrUniformRoot::CurrentScope`           | - |
    pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
    pub vis: Visibility,

    /// Span of the visibility.
    pub vis_span: Span,

    /// A `#[diagnostic::on_unknown]` attribute applied
    /// to the given import. This allows crates to specify
    /// custom error messages for a specific import
    ///
    /// This is `None` if the feature flag for `diagnostic::on_unknown` is disabled.
    pub on_unknown_attr: Option<OnUnknownData>,
}

/// `Interned` is used because values of this type have "identity" and compare as unequal even if
/// they have the same contents.
pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;

impl<'ra> ImportData<'ra> {
    pub(crate) fn is_glob(&self) -> bool {
        matches!(self.kind, ImportKind::Glob { .. })
    }

    pub(crate) fn is_nested(&self) -> bool {
        match self.kind {
            ImportKind::Single { nested, .. } => nested,
            _ => false,
        }
    }

    pub(crate) fn id(&self) -> Option<NodeId> {
        match self.kind {
            ImportKind::Single { id, .. }
            | ImportKind::Glob { id, .. }
            | ImportKind::ExternCrate { id, .. } => Some(id),
            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
        }
    }

    pub(crate) fn def_id(&self) -> Option<LocalDefId> {
        match self.kind {
            ImportKind::Single { def_id, .. }
            | ImportKind::Glob { def_id, .. }
            | ImportKind::ExternCrate { def_id, .. } => Some(def_id),
            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
        }
    }

    pub(crate) fn simplify(&self) -> Reexport {
        match self.kind {
            ImportKind::Single { def_id, .. } => Reexport::Single(def_id.to_def_id()),
            ImportKind::Glob { def_id, .. } => Reexport::Glob(def_id.to_def_id()),
            ImportKind::ExternCrate { def_id, .. } => Reexport::ExternCrate(def_id.to_def_id()),
            ImportKind::MacroUse { .. } => Reexport::MacroUse,
            ImportKind::MacroExport => Reexport::MacroExport,
        }
    }

    fn summary(&self) -> ImportSummary {
        ImportSummary {
            vis: self.vis,
            nearest_parent_mod: self.parent_scope.module.nearest_parent_mod().expect_local(),
            is_single: matches!(self.kind, ImportKind::Single { .. }),
            priv_macro_use: matches!(self.kind, ImportKind::MacroUse { warn_private: true }),
            span: self.span,
        }
    }
}

/// Records information about the resolution of a name in a namespace of a module.
#[derive(Debug)]
pub(crate) struct NameResolution<'ra> {
    /// Single imports that may define the name in the namespace.
    /// Imports are arena-allocated, so it's ok to use pointers as keys.
    pub single_imports: FxIndexSet<Import<'ra>>,
    /// The non-glob declaration for this name, if it is known to exist.
    pub non_glob_decl: Option<Decl<'ra>>,
    /// The glob declaration for this name, if it is known to exist.
    pub glob_decl: Option<Decl<'ra>>,
    pub orig_ident_span: Span,
}

/// `Interned` is used because values of this type have "identity" and compare as unequal even if
/// they have the same contents.
pub(crate) type NameResolutionRef<'ra> = Interned<'ra, CmRefCell<NameResolution<'ra>>>;

impl<'ra> NameResolution<'ra> {
    pub(crate) fn new(orig_ident_span: Span) -> Self {
        NameResolution {
            single_imports: FxIndexSet::default(),
            non_glob_decl: None,
            glob_decl: None,
            orig_ident_span,
        }
    }

    /// Returns the best declaration if it is not going to change, and `None` if the best
    /// declaration may still change to something else.
    /// FIXME: this function considers `single_imports`, but not `unexpanded_invocations`, so
    /// the returned declaration may actually change after expanding macros in the same module,
    /// because of this fact we have glob overwriting (`select_glob_decl`). Consider using
    /// `unexpanded_invocations` here and avoiding glob overwriting entirely, if it doesn't cause
    /// code breakage in practice.
    /// FIXME: relationship between this function and similar `DeclData::determined` is unclear.
    pub(crate) fn determined_decl(&self) -> Option<Decl<'ra>> {
        if self.non_glob_decl.is_some() {
            self.non_glob_decl
        } else if self.glob_decl.is_some() && self.single_imports.is_empty() {
            self.glob_decl
        } else {
            None
        }
    }

    pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
        self.non_glob_decl.or(self.glob_decl)
    }
}

// module to keep the TLS private and only accessible through the function `enter_cycle_detector`.
pub(crate) mod cycle_detection {
    use alloc::vec::Vec;
    use core::ptr;
    // A nested inline module does not inherit the file's `use` items, so this is imported here.
    use eko::thread::ThreadLocal;

    use crate::rustc_resolve::{BindingKey, LocalModule};

    /// During import resolution, recursive imports can form cycles.
    /// This set stores the active resolution stack for the current thread.
    /// By keeping track of the module and `BindingKey` pair that identifies
    /// the specific resolution.
    ///
    /// The pointer is the interned address of a `Interned<'ra, ModuleData>` allocated
    /// in the `Resolver Arenas` (lifetime `'ra`), it is thus stable and allows casting
    /// to a `*const ()` for comparison. This is done because we can't use lifetimes
    /// other than `'static` in thread local storage.
    ///
    /// Was `std::thread_local!` over a `RefCell`. `eko::thread::ThreadLocal::with`
    /// hands out `&mut T` directly, so the `RefCell` is no longer needed, and the initialiser
    /// is supplied per access rather than at the declaration.
    static ACTIVE_RESOLUTIONS: ThreadLocal<Vec<(*const (), BindingKey)>> = ThreadLocal::new();

    pub(crate) struct ActiveResolutionGuard {
        key: (*const (), BindingKey),
    }

    impl Drop for ActiveResolutionGuard {
        fn drop(&mut self) {
            // `None` here means the thread has no thread-local slot at all, so there is no stack
            // to pop from; it is discarded rather than asserted on.
            let _ = ACTIVE_RESOLUTIONS.with(Vec::new, |ar| {
                // Only this guard is allowed to remove this key.
                assert!(
                    Some(self.key) == ar.pop(),
                    "This guard should be the only one removing this key"
                );
            });
        }
    }

    /// Returns `Err(())` if a cycle is detected, otherwise this returns a
    /// guard that will remove the resolution when dropped.
    pub(crate) fn enter_cycle_detector<'ra>(
        module: LocalModule<'ra>,
        binding_key: BindingKey,
    ) -> Result<ActiveResolutionGuard, ()> {
        let module_key = ptr::from_ref(module.0.0).cast();
        let key = (module_key, binding_key);
        // `None` means no thread-local slot could be created, so the cycle stack cannot be
        // consulted. That is reported as a cycle: refusing is the conservative answer, and
        // handing out a guard whose `Drop` cannot pop would be worse.
        ACTIVE_RESOLUTIONS
            .with(Vec::new, |ar| {
                if ar.contains(&key) {
                    return Err(());
                }
                ar.push(key);
                Ok(ActiveResolutionGuard { key })
            })
            .unwrap_or(Err(()))
    }
}

/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
/// import errors within the same use tree into a single diagnostic.
#[derive(Debug)]
pub(crate) struct UnresolvedImportError {
    pub(crate) span: Span,
    pub(crate) label: Option<String>,
    pub(crate) note: Option<String>,
    pub(crate) suggestion: Option<Suggestion>,
    pub(crate) help: Option<String>,
    pub(crate) candidates: Option<Vec<ImportSuggestion>>,
    pub(crate) segment: Option<Ident>,
    /// comes from `PathRes::Failed { module }`
    pub(crate) module: Option<DefId>,
    pub(crate) on_unknown_attr: Option<OnUnknownData>,
}

// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
// are permitted for backward-compatibility under a deprecation lint.
fn pub_use_of_private_extern_crate_hack(
    import: ImportSummary,
    decl: Decl<'_>,
) -> Option<LocalDefId> {
    match (import.is_single, &decl.kind) {
        (true, DeclKind::Import { import: decl_import, .. })
            if let ImportKind::ExternCrate { def_id, .. } = decl_import.kind
                && import.vis.is_public() =>
        {
            Some(def_id)
        }
        _ => None,
    }
}

/// Removes identical import layers from two declarations.
fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
    if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
        && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
        && import1 == import2
    {
        assert_eq!(d1.expansion, d2.expansion);
        assert_eq!(d1.span, d2.span);
        if d1.ambiguity.get() != d2.ambiguity.get() {
            assert!(d1.ambiguity.get().is_some());
        }
        // Visibility of the new import declaration may be different,
        // because it already incorporates the visibility of the source binding.
        remove_same_import(d1_next, d2_next)
    } else {
        (d1, d2)
    }
}

impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
    pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
        self.import_decl_vis_ext(decl, import, false)
    }

    pub(crate) fn import_decl_vis_ext(
        &self,
        decl: Decl<'ra>,
        import: ImportSummary,
        min: bool,
    ) -> Visibility {
        assert!(import.vis.is_accessible_from(import.nearest_parent_mod, self.tcx));
        let decl_vis = if min { decl.min_vis() } else { decl.vis() };
        let ord = decl_vis.partial_cmp(import.vis, self.tcx);
        let extern_crate_hack = pub_use_of_private_extern_crate_hack(import, decl).is_some();
        if ord == Some(Ordering::Less)
            && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
            && !extern_crate_hack
        {
            // Imported declaration is less visible than the import, but is still visible
            // from the current module, use the declaration's visibility.
            decl_vis.expect_local()
        } else {
            // Good case - imported declaration is more visible than the import, or the same,
            // use the import's visibility.
            //
            // Bad case - imported declaration is too private for the current module.
            // It doesn't matter what visibility we choose here (except in the `PRIVATE_MACRO_USE`
            // and `PUB_USE_OF_PRIVATE_EXTERN_CRATE` cases), because an error will be reported.
            // Use import visibility to keep the all declaration visibilities in a module ordered.
            if !min
                && matches!(ord, None | Some(Ordering::Less))
                && !extern_crate_hack
                && !import.priv_macro_use
            {
                let msg = format!("cannot extend visibility from {decl_vis:?} to {:?}", import.vis);
                self.dcx().span_delayed_bug(import.span, msg);
            }
            import.vis
        }
    }

    /// Given an import and the declaration that it points to,
    /// create the corresponding import declaration.
    pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
        let vis = self.import_decl_vis(decl, import.summary());

        if let ImportKind::Glob { ref max_vis, .. } = import.kind
            && (vis == import.vis
                || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
        {
            // `set` can't fail because this can only happen during "write_import_resolutions"
            max_vis.set_checked(Some(vis), self)
        }

        self.arenas.alloc_decl(DeclData {
            kind: DeclKind::Import { source_decl: decl, import },
            ambiguity: CmCell::new(None),
            span: import.span,
            initial_vis: vis.to_mod_id(),
            ambiguity_vis_max: CmCell::new(None),
            ambiguity_vis_min: CmCell::new(None),
            expansion: import.parent_scope.expansion,
            parent_module: Some(import.parent_scope.module),
        })
    }

    fn is_noise_0_7_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { unreachable!() };
        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { unreachable!() };
        let [seg1, seg2] = &i1.module_path[..] else { return false };
        if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin_surflet" {
            return false;
        }
        let [seg1, seg2] = &i2.module_path[..] else { return false };
        if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin" {
            return false;
        }
        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
        self.def_path_str(def_id1).ends_with("noise_fns::generators::perlin_surflet::Perlin")
            && self.def_path_str(def_id2).ends_with("noise_fns::generators::perlin::Perlin")
    }

    fn is_rustybuzz_0_4_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { unreachable!() };
        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { unreachable!() };
        let [seg1, seg2] = &i1.module_path[..] else { return false };
        if seg1.ident.name != kw::Super || seg2.ident.name.as_str() != "gsubgpos" {
            return false;
        }
        let [seg1] = &i2.module_path[..] else { return false };
        if seg1.ident.name != kw::Super {
            return false;
        }
        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
        self.def_path_str(def_id1).ends_with("tables::gsubgpos::Class")
            && self.def_path_str(def_id2).ends_with("ggg::Class")
    }

    fn is_pdf_0_9_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { unreachable!() };
        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { unreachable!() };
        let [seg1, seg2] = &i1.module_path[..] else { return false };
        if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "content" {
            return false;
        }
        let [seg1, seg2] = &i2.module_path[..] else { return false };
        if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "object" {
            return false;
        }
        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
        self.def_path_str(def_id1).ends_with("crate::rustc_resolve::content::Rect")
            && self.def_path_str(def_id2).ends_with("crate::rustc_resolve::object::types::Rect")
    }

    fn is_net2_0_2_39(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { unreachable!() };
        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { unreachable!() };
        let [seg1, seg2, seg3, seg4] = &i1.module_path[..] else { return false };
        if seg1.ident.name != kw::PathRoot
            || seg2.ident.name.as_str() != "winapi"
            || seg3.ident.name.as_str() != "shared"
            || seg4.ident.name.as_str() != "ws2def"
        {
            return false;
        }
        let [seg1, seg2, seg3, seg4] = &i2.module_path[..] else { return false };
        if seg1.ident.name != kw::PathRoot
            || seg2.ident.name.as_str() != "winapi"
            || seg3.ident.name.as_str() != "um"
            || seg4.ident.name.as_str() != "winsock2"
        {
            return false;
        }
        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
        self.def_path_str(def_id1).starts_with("winapi::shared::ws2def::")
            && self.def_path_str(def_id2).starts_with("winapi::um::winsock2::")
    }

    /// If `glob_decl` attempts to overwrite `old_glob_decl` in a module,
    /// decide which one to keep.
    fn select_glob_decl(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> Decl<'ra> {
        assert!(glob_decl.is_glob_import());
        assert!(old_glob_decl.is_glob_import());
        assert_ne!(glob_decl, old_glob_decl);
        // `best_decl` with a given key in a module may be overwritten in a
        // number of cases (all of them can be seen below in the `match` in `try_define_local`),
        // all these overwrites will be re-fetched by glob imports importing
        // from that module without generating new ambiguities.
        // - A glob decl is overwritten by a non-glob decl arriving later.
        // - A glob decl is overwritten by a glob decl re-fetching an
        //   overwritten decl from other module (the recursive case).
        // Here we are detecting all such re-fetches and overwrite old decls
        // with the re-fetched decls.
        // This is probably incorrect in corner cases, and the outdated decls still get
        // propagated to other places and get stuck there, but that's what we have at the moment.
        let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
        if deep_decl != glob_decl {
            // Some import layers have been removed, need to overwrite.
            assert_ne!(old_deep_decl, old_glob_decl);
            assert!(!deep_decl.is_glob_import());
            if let Some((old_ambig, _)) = old_glob_decl.ambiguity.get()
                && glob_decl.ambiguity.get().is_none()
            {
                // Do not lose glob ambiguities when re-fetching the glob.
                glob_decl.ambiguity.set_checked(Some((old_ambig, true)), self);
            }
            glob_decl
        } else if glob_decl.res() != old_glob_decl.res() {
            let warning = self.is_noise_0_7_0(old_glob_decl, glob_decl)
                || self.is_rustybuzz_0_4_0(old_glob_decl, glob_decl)
                || self.is_pdf_0_9_0(old_glob_decl, glob_decl)
                || self.is_net2_0_2_39(old_glob_decl, glob_decl);
            old_glob_decl.ambiguity.set_checked(Some((glob_decl, warning)), self);
            old_glob_decl
        } else if let old_vis = old_glob_decl.vis()
            && let vis = glob_decl.vis()
            && old_vis != vis
        {
            // We are glob-importing the same item but with a different visibility.
            // All visibilities here are ordered because all of them are ancestors of `module`.
            if vis.greater_than(old_vis, self.tcx) {
                old_glob_decl.ambiguity_vis_max.set_checked(Some(glob_decl), self);
            } else if let old_min_vis = old_glob_decl.min_vis()
                && old_min_vis != vis
                && old_min_vis.greater_than(vis, self.tcx)
            {
                old_glob_decl.ambiguity_vis_min.set_checked(Some(glob_decl), self);
            }
            old_glob_decl
        } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
            // Overwriting a non-ambiguous glob import with an ambiguous glob import.
            old_glob_decl.ambiguity.set_checked(Some((glob_decl, true)), self);
            old_glob_decl
        } else {
            old_glob_decl
        }
    }

    /// Attempt to put the declaration with the given name and namespace into the module,
    /// and return existing declaration if there is a collision.
    pub(crate) fn try_plant_decl_into_local_module(
        &mut self,
        ident: IdentKey,
        orig_ident_span: Span,
        ns: Namespace,
        decl: Decl<'ra>,
    ) -> Result<(), Decl<'ra>> {
        assert!(decl.ambiguity.get().is_none());
        assert!(decl.ambiguity_vis_max.get().is_none());
        assert!(decl.ambiguity_vis_min.get().is_none());
        let module = decl.parent_module.unwrap().expect_local();
        assert!(self.is_accessible_from(decl.vis(), module.to_module()));
        let res = decl.res();
        self.check_reserved_macro_name(ident.name, orig_ident_span, res);
        // Even if underscore names cannot be looked up, we still need to add them to modules,
        // because they can be fetched by glob imports from those modules, and bring traits
        // into scope both directly and through glob imports.
        let key = BindingKey::new_disambiguated(ident, ns, || {
            module.underscore_disambiguator.update(self, |d| d + 1);
            module.underscore_disambiguator.get()
        });
        self.update_local_resolution(module, key, orig_ident_span, |this, resolution| {
            if res == Res::Err
                && let Some(old_decl) = resolution.best_decl()
                && old_decl.res() != Res::Err
            {
                // Do not override real declarations with `Res::Err`s from error recovery.
                // FIXME: this special case shouldn't be necessary, but removing it triggers an ICE
                // due to some other issues (#157406, tests/ui/imports/dummy-import-ice.rs).
                return Ok(());
            }
            if decl.is_glob_import() {
                resolution.glob_decl = Some(match resolution.glob_decl {
                    Some(old_decl) => this.select_glob_decl(old_decl, decl),
                    None => decl,
                });
            } else {
                resolution.non_glob_decl = Some(match resolution.non_glob_decl {
                    Some(old_decl) => return Err(old_decl),
                    None => decl,
                })
            }

            Ok(())
        })
    }

    // Use `f` to mutate the resolution of the name in the module.
    // If the resolution becomes a success, define it in the module's glob importers.
    fn update_local_resolution<T, F>(
        &mut self,
        module: LocalModule<'ra>,
        key: BindingKey,
        orig_ident_span: Span,
        f: F,
    ) -> T
    where
        F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
    {
        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
        // during which the resolution might end up getting re-defined via a glob cycle.
        let (binding, t) = {
            let resolution = &mut *self
                .resolution_or_default(module.to_module(), key, orig_ident_span)
                .0
                .borrow_mut(self);
            let old_decl = resolution.determined_decl();
            let old_vis = old_decl.map(|d| d.vis());

            let t = f(self, resolution);

            if let Some(binding) = resolution.determined_decl()
                && (old_decl != Some(binding) || old_vis != Some(binding.vis()))
            {
                (binding, t)
            } else {
                return t;
            }
        };

        let Ok(glob_importers) = module.glob_importers.try_borrow_mut(self) else {
            return t;
        };

        // Define or update `binding` in `module`s glob importers.
        for import in glob_importers.iter() {
            let mut ident = key.ident;
            let scope = match ident
                .ctxt
                .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
            {
                Some(Some(def)) => self.expn_def_scope(def),
                Some(None) => import.parent_scope.module,
                None => continue,
            };
            if self.is_accessible_from(binding.vis(), scope) {
                let import_decl = self.new_import_decl(binding, *import);
                self.try_plant_decl_into_local_module(ident, orig_ident_span, key.ns, import_decl)
                    .expect("planting a glob cannot fail");
            }
        }

        t
    }

    // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed
    // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics.
    fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
        if let ImportKind::Single { target, ref decls, .. } = import.kind {
            if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
                return; // Has resolution, do not create the dummy binding
            }
            let dummy_decl = self.dummy_decl;
            let dummy_decl = self.new_import_decl(dummy_decl, import);
            self.per_ns_mut(|this, ns| {
                let ident = IdentKey::new(target);
                // This can fail, dummies are inserted only in non-occupied slots.
                let _ = this.try_plant_decl_into_local_module(ident, target.span, ns, dummy_decl);
                // Don't remove underscores from `single_imports`, they were never added.
                if target.name != kw::Underscore {
                    let key = BindingKey::new(ident, ns);
                    this.update_local_resolution(
                        import.parent_scope.module.expect_local(),
                        key,
                        target.span,
                        |_, resolution| {
                            resolution.single_imports.swap_remove(&import);
                        },
                    )
                }
            });
            self.record_use(target, dummy_decl, Used::Other);
        } else if import.imported_module.get().is_none() {
            self.import_use_map.insert(import, Used::Other);
            if let Some(id) = import.id() {
                self.used_imports.insert(id);
            }
        }
    }

    // Import resolution
    //
    // This is a batched fixed-point algorithm. Each import is resolved in
    // isolation, with any resolutions collected for later.
    // After a full pass over the current set of `indeterminate_imports`,
    // the collected resolutions are committed together. The process
    // repeats until either no imports remain or no further progress can
    // be made.

    /// Resolves all imports for the crate. This method performs the fixed-
    /// point iteration.
    pub(crate) fn resolve_imports(&mut self) {
        let mut prev_indeterminate_count = usize::MAX;
        let mut indeterminate_count = self.indeterminate_imports.len() * 3;
        while indeterminate_count < prev_indeterminate_count {
            prev_indeterminate_count = indeterminate_count;
            indeterminate_count = 0;

            let mut imports_to_resolve = mem::take(&mut self.indeterminate_imports);

            // SAFETY: This is a "top-level" function used by the macro expansion code, unless some
            // weird thing is done, all `tracked` borrows done in the previous call of
            // `resolve_imports` are dropped when that call ended.
            unsafe { self.speculative_flag.set(true) };
            crate::rustc_data_structures::sync::par_for_each_slice(
                &mut imports_to_resolve,
                |(import, resolution, indeterminate_count)| {
                    (*resolution, *indeterminate_count) = self.resolve_import(*import);
                },
            );
            // SAFETY: All `untracked` borrows are dropped after the `par_for_each_slice` call,
            // as they cannot escape since they are tied to the `CmRefCell` they borrowed from.
            //
            // Note: Some `CmRefCell`s are arena allocated and thus have the `'ra` lifetime,
            // allowing these borrows to escape, but that does not and should not happen.
            unsafe { self.speculative_flag.set(false) };

            self.write_import_resolutions(&imports_to_resolve);

            self.indeterminate_imports = imports_to_resolve
                .extract_if(.., |(_, _, count)| {
                    indeterminate_count += *count;
                    *count > 0
                })
                .collect();
            self.determined_imports.extend(imports_to_resolve.into_iter().map(|(i, _, _)| i));
        }
    }

    fn write_import_resolutions(
        &mut self,
        import_resolutions: &[(Import<'ra>, Option<ImportResolution<'ra>>, usize)],
    ) {
        for &(import, ref resolution, _) in import_resolutions {
            let Some(ImportResolution { imported_module, .. }) = resolution else {
                continue;
            };
            import.imported_module.set(Some(*imported_module), self);

            if import.is_glob()
                && let ModuleOrUniformRoot::Module(module) = imported_module
                && import.parent_scope.module != *module
                && module.is_local()
            {
                module.glob_importers.borrow_mut(self).push(import);
            }
        }

        for &(import, ref resolution, _) in import_resolutions {
            let Some(ImportResolution { imported_module, kind: resolution_kind }) = resolution
            else {
                continue;
            };

            match (&import.kind, resolution_kind) {
                (
                    ImportKind::Single { target, decls, .. },
                    ImportResolutionKind::Single(import_decls),
                ) => {
                    self.per_ns_mut(|this, ns| {
                        match import_decls[ns] {
                            PendingDecl::Ready(Some(decl)) => {
                                // We need the `target`, `source` can be extracted.
                                let import_decl = this.new_import_decl(decl, import);
                                if import_decl.is_assoc_item()
                                    && !this.features.import_trait_associated_functions()
                                {
                                    feature_err(
                                        this.tcx.sess,
                                        sym::import_trait_associated_functions,
                                        import.span,
                                        "`use` associated items of traits is unstable",
                                    )
                                    .emit();
                                }
                                this.plant_decl_into_local_module(
                                    IdentKey::new(*target),
                                    target.span,
                                    ns,
                                    import_decl,
                                );
                                decls[ns].set(PendingDecl::Ready(Some(import_decl)), this);
                            }
                            PendingDecl::Ready(None) => {
                                // Don't remove underscores from `single_imports`, they were never added.
                                if target.name != kw::Underscore {
                                    let key = BindingKey::new(IdentKey::new(*target), ns);
                                    this.update_local_resolution(
                                        import.parent_scope.module.expect_local(),
                                        key,
                                        target.span,
                                        |_, resolution| {
                                            resolution.single_imports.swap_remove(&import);
                                        },
                                    );
                                }
                                decls[ns].set(PendingDecl::Ready(None), this);
                            }
                            PendingDecl::Pending => {}
                        }
                    });
                }
                (ImportKind::Glob { id, .. }, ImportResolutionKind::Glob(imported_decls)) => {
                    let ModuleOrUniformRoot::Module(module) = imported_module else {
                        self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
                        continue;
                    };

                    if module.is_trait() && !self.features.import_trait_associated_functions() {
                        feature_err(
                            self.tcx.sess,
                            sym::import_trait_associated_functions,
                            import.span,
                            "`use` associated items of traits is unstable",
                        )
                        .emit();
                    }

                    for (binding, key, orig_ident_span) in imported_decls {
                        let import_decl = self.new_import_decl(*binding, import);
                        let _ = self
                            .try_plant_decl_into_local_module(
                                key.ident,
                                *orig_ident_span,
                                key.ns,
                                import_decl,
                            )
                            .expect("planting a glob cannot fail");
                    }

                    self.record_partial_res(*id, PartialRes::new(module.res().unwrap()));
                }

                // Something weird happened, which shouldn't have happened.
                _ => unreachable!("mismatched import and resolution kind"),
            }
        }
    }

    pub(crate) fn finalize_imports(&mut self) {
        let mut module_children = Default::default();
        let mut ambig_module_children = Default::default();
        for module in &self.local_modules {
            self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
        }
        self.module_children = module_children;
        self.ambig_module_children = ambig_module_children;

        let mut seen_spans = FxHashSet::default();
        let mut errors = vec![];
        let mut prev_root_id: NodeId = NodeId::ZERO;
        let determined_imports = mem::take(&mut self.determined_imports);
        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);

        let mut glob_error = false;
        for (is_indeterminate, import) in determined_imports
            .iter()
            .map(|i| (false, i))
            .chain(indeterminate_imports.iter().map(|(i, _, _)| (true, i)))
        {
            let unresolved_import_error = self.finalize_import(*import);
            // If this import is unresolved then create a dummy import
            // resolution for it so that later resolve stages won't complain.
            self.import_dummy_binding(*import, is_indeterminate);

            let Some(err) = unresolved_import_error else { continue };

            glob_error |= import.is_glob();

            if let ImportKind::Single { source, ref decls, .. } = import.kind
                && source.name == kw::SelfLower
                // Silence `unresolved import` error if E0429 is already emitted
                && let PendingDecl::Ready(None) = decls.value_ns.get()
            {
                continue;
            }

            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
            {
                // In the case of a new import line, throw a diagnostic message
                // for the previous line.
                self.throw_unresolved_import_error(errors, glob_error);
                errors = vec![];
            }
            if seen_spans.insert(err.span) {
                errors.push((*import, err));
                prev_root_id = import.root_id;
            }
        }

        if self.cstore().had_extern_crate_load_failure() {
            self.tcx.sess.dcx().abort_if_errors();
        }

        if !errors.is_empty() {
            self.throw_unresolved_import_error(errors, glob_error);
            return;
        }

        for (import, _, _) in &indeterminate_imports {
            let path = import_path_to_string(
                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
                &import.kind,
                import.span,
            );
            // FIXME: there should be a better way of doing this than
            // formatting this as a string then checking for `::`
            if path.contains("::") {
                let err = UnresolvedImportError {
                    span: import.span,
                    label: None,
                    note: None,
                    suggestion: None,
                    help: None,
                    candidates: None,
                    segment: None,
                    module: None,
                    on_unknown_attr: import.on_unknown_attr.clone(),
                };
                errors.push((*import, err))
            }
        }

        if !errors.is_empty() {
            self.throw_unresolved_import_error(errors, glob_error);
        }
    }

    pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
        for module in &self.local_modules {
            for (key, resolution) in self.resolutions(module.to_module()).iter() {
                let resolution = resolution.borrow_checked(self);
                let Some(binding) = resolution.best_decl() else { continue };

                // Report "cannot reexport" errors for exotic cases involving macros 2.0
                // privacy bending or invariant-breaking code under deprecation lints.
                for decl in [resolution.non_glob_decl, resolution.glob_decl] {
                    if let Some(decl) = decl
                        && let DeclKind::Import { source_decl, import } = decl.kind
                        // FIXME: Do not check visibility-ambiguous imports for now. To check them
                        // properly we need to preserve all imports in ambiguous glob sets and
                        // check them all individually.
                        && decl.ambiguity_vis_max.get().is_none()
                    {
                        // The source entity is too private to be reexported
                        // with the given import declaration's visibility.
                        let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
                        if matches!(ord, None | Some(Ordering::Less)) {
                            let ident = match import.kind {
                                ImportKind::Single { source, .. } => source,
                                _ => key.ident.orig(resolution.orig_ident_span),
                            };
                            if let Some(lint) =
                                self.report_cannot_reexport(import, source_decl, ident, key.ns)
                            {
                                self.lint_buffer.add_early_lint(lint);
                            }
                        }
                    }
                }

                if let DeclKind::Import { import, .. } = binding.kind
                    && let Some((amb_binding, _)) = binding.ambiguity.get()
                    && binding.res() != Res::Err
                    && exported_ambiguities.contains(&binding)
                {
                    self.lint_buffer.buffer_lint(
                        AMBIGUOUS_GLOB_REEXPORTS,
                        import.root_id,
                        import.root_span,
                        diagnostics::AmbiguousGlobReexports {
                            name: key.ident.name.to_string(),
                            namespace: key.ns.descr().to_string(),
                            first_reexport: import.root_span,
                            duplicate_reexport: amb_binding.span,
                        },
                    );
                }

                if let Some(glob_decl) = resolution.glob_decl
                    && resolution.non_glob_decl.is_some()
                {
                    if binding.res() != Res::Err
                        && glob_decl.res() != Res::Err
                        && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
                        && let Some(glob_import_def_id) = glob_import.def_id()
                        && self.effective_visibilities.is_exported(glob_import_def_id)
                        && glob_decl.vis().is_public()
                        && !binding.vis().is_public()
                    {
                        let binding_id = match binding.kind {
                            DeclKind::Def(res) => {
                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
                            }
                            DeclKind::Import { import, .. } => import.id(),
                        };
                        if let Some(binding_id) = binding_id {
                            self.lint_buffer.buffer_lint(
                                HIDDEN_GLOB_REEXPORTS,
                                binding_id,
                                binding.span,
                                diagnostics::HiddenGlobReexports {
                                    name: key.ident.name.to_string(),
                                    namespace: key.ns.descr().to_owned(),
                                    glob_reexport: glob_decl.span,
                                    private_item: binding.span,
                                },
                            );
                        }
                    }
                }

                if let DeclKind::Import { import, .. } = binding.kind
                    && let Some(binding_id) = import.id()
                    && let import_def_id = import.def_id().unwrap()
                    && self.effective_visibilities.is_exported(import_def_id)
                    && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
                    && !matches!(reexported_kind, DefKind::Ctor(..))
                    && !reexported_def_id.is_local()
                    && self.tcx.is_private_dep(reexported_def_id.krate)
                {
                    self.lint_buffer.buffer_lint(
                        EXPORTED_PRIVATE_DEPENDENCIES,
                        binding_id,
                        binding.span,
                        crate::rustc_resolve::diagnostics::ReexportPrivateDependency {
                            name: key.ident.name,
                            kind: binding.res().descr(),
                            krate: self.tcx.crate_name(reexported_def_id.krate),
                        },
                    );
                }
            }
        }
    }

    /// Attempts to resolve the given import, returning:
    /// - `0` means its resolution is determined.
    /// - Other values mean that indeterminate exists under certain namespaces.
    ///
    /// Meanwhile, if resolution is successful, its result is returned.
    fn resolve_import(&self, import: Import<'ra>) -> (Option<ImportResolution<'ra>>, usize) {
        debug!(
            "(resolving import for module) resolving import `{}::{}` in `{}`",
            Segment::names_to_string(&import.module_path),
            import_kind_to_string(&import.kind),
            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
        );
        let module = if let Some(module) = import.imported_module.get() {
            module
        } else {
            let path_res = self.cm().maybe_resolve_path(
                &import.module_path,
                None,
                &import.parent_scope,
                Some(import),
            );

            match path_res {
                PathResult::Module(module) => module,
                PathResult::Indeterminate => return (None, 3),
                PathResult::NonModule(..) | PathResult::Failed { .. } => return (None, 0),
            }
        };

        let (source, bindings) = match import.kind {
            ImportKind::Single { source, ref decls, .. } => (source, decls),
            ImportKind::Glob { .. } => {
                let import_resolution = ImportResolution {
                    imported_module: module,
                    kind: self.resolve_glob_import(import, module),
                };
                return (Some(import_resolution), 0);
            }
            _ => unreachable!(),
        };

        let mut decls = PerNS::default();
        let mut indeterminate_count = 0;
        self.per_ns(|this, ns| {
            if bindings[ns].get() != PendingDecl::Pending {
                return;
            };
            let binding_result = this.cm().maybe_resolve_ident_in_module(
                module,
                source,
                ns,
                &import.parent_scope,
                Some(import),
            );
            let pending_decl = match binding_result {
                Ok(binding) => PendingDecl::Ready(Some(binding)),
                Err(Determinacy::Determined) => PendingDecl::Ready(None),
                Err(Determinacy::Undetermined) => {
                    indeterminate_count += 1;
                    PendingDecl::Pending
                }
            };
            decls[ns] = pending_decl;
        });
        let import_resolution =
            ImportResolution { imported_module: module, kind: ImportResolutionKind::Single(decls) };

        (Some(import_resolution), indeterminate_count)
    }

    /// Performs final import resolution, consistency checks and error reporting.
    ///
    /// Optionally returns an unresolved import error. This error is buffered and used to
    /// consolidate multiple unresolved import errors into a single diagnostic.
    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
        let ignore_decl = match &import.kind {
            ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
            _ => None,
        };
        let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
            errors.iter().filter(|error| error.warning.is_none()).count()
        };
        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);

        // We'll provide more context to the privacy errors later, up to `len`.
        let privacy_errors_len = self.privacy_errors.len();

        let path_res = self.cm_mut().resolve_path(
            &import.module_path,
            None,
            &import.parent_scope,
            Some(finalize),
            ignore_decl,
            Some(import),
        );

        let no_ambiguity =
            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;

        let module = match path_res {
            PathResult::Module(module) => {
                // Consistency checks, analogous to `finalize_macro_resolutions`.
                if let Some(initial_module) = import.imported_module.get() {
                    if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
                        span_bug!(import.span, "inconsistent resolution for an import");
                    }
                } else if self.privacy_errors.is_empty() {
                    self.dcx()
                        .create_err(CannotDetermineImportResolution { span: import.span })
                        .emit();
                }

                module
            }
            PathResult::Failed {
                is_error_from_last_segment: false,
                span,
                segment,
                label,
                suggestion,
                help,
                module,
                error_implied_by_parse_error: _,
                message,
                note: _,
            } => {
                if no_ambiguity {
                    if !self.issue_145575_hack_applied {
                        assert!(import.imported_module.get().is_none());
                    }
                    self.report_error(
                        span,
                        ResolutionError::FailedToResolve {
                            segment: segment.name,
                            label,
                            suggestion,
                            help,
                            module,
                            message,
                        },
                    );
                }
                return None;
            }
            PathResult::Failed {
                is_error_from_last_segment: true,
                span,
                label,
                suggestion,
                help,
                module,
                segment,
                note,
                ..
            } => {
                if no_ambiguity {
                    if !self.issue_145575_hack_applied {
                        assert!(import.imported_module.get().is_none());
                    }
                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
                        m.opt_def_id()
                    } else {
                        None
                    };
                    let err = match self
                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
                    {
                        Some((suggestion, note)) => UnresolvedImportError {
                            span,
                            label: None,
                            note,
                            suggestion: Some((
                                vec![(span, Segment::names_to_string(&suggestion))],
                                String::from("a similar path exists"),
                                Applicability::MaybeIncorrect,
                            )),
                            help: None,
                            candidates: None,
                            segment: Some(segment),
                            module,
                            on_unknown_attr: import.on_unknown_attr.clone(),
                        },
                        None => UnresolvedImportError {
                            span,
                            label: Some(label),
                            note,
                            suggestion,
                            help,
                            candidates: None,
                            segment: Some(segment),
                            module,
                            on_unknown_attr: import.on_unknown_attr.clone(),
                        },
                    };
                    return Some(err);
                }
                return None;
            }
            PathResult::NonModule(partial_res) => {
                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
                    // Check if there are no ambiguities and the result is not dummy.
                    assert!(import.imported_module.get().is_none());
                }
                // The error was already reported earlier.
                return None;
            }
            PathResult::Indeterminate => unreachable!(),
        };

        let (ident, target, bindings, import_id) = match import.kind {
            ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
            ImportKind::Glob { ref max_vis, id, def_id } => {
                if import.module_path.len() <= 1 {
                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
                    // 2 segments, so the `resolve_path` above won't trigger it.
                    let mut full_path = import.module_path.clone();
                    full_path.push(Segment::from_ident(Ident::dummy()));
                    self.lint_if_path_starts_with_module(finalize, &full_path, None);
                }

                if let ModuleOrUniformRoot::Module(module) = module
                    && module == import.parent_scope.module
                {
                    // Importing a module into itself is not allowed.
                    return Some(UnresolvedImportError {
                        span: import.span,
                        label: Some(String::from("cannot glob-import a module into itself")),
                        note: None,
                        suggestion: None,
                        help: None,
                        candidates: None,
                        segment: None,
                        module: None,
                        on_unknown_attr: None,
                    });
                }
                if let Some(max_vis) = max_vis.get()
                    && import.vis.greater_than(max_vis, self.tcx)
                {
                    self.lint_buffer.buffer_lint(
                        UNUSED_IMPORTS,
                        id,
                        import.span,
                        crate::rustc_resolve::diagnostics::RedundantImportVisibility {
                            span: import.span,
                            help: (),
                            max_vis: max_vis.to_string(def_id, self.tcx),
                            import_vis: import.vis.to_string(def_id, self.tcx),
                        },
                    );
                }
                return None;
            }
            _ => unreachable!(),
        };

        if self.privacy_errors.len() != privacy_errors_len {
            // Get the Res for the last element, so that we can point to alternative ways of
            // importing it if available.
            let mut path = import.module_path.clone();
            path.push(Segment::from_ident(ident));
            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self
                .cm_mut()
                .resolve_path(&path, None, &import.parent_scope, Some(finalize), ignore_decl, None)
            {
                let res = module.res().map(|r| (r, ident));
                for error in &mut self.privacy_errors[privacy_errors_len..] {
                    error.outermost_res = res;
                }
            } else {
                // The final item is not a module (e.g., a struct, function, or macro).
                // Resolve it directly in the parent module to get its Res, so
                // `report_privacy_error()` can search for public re-export paths.
                for ns in [TypeNS, ValueNS, MacroNS] {
                    if let Ok(binding) = self.cm().resolve_ident_in_module(
                        module,
                        ident,
                        ns,
                        &import.parent_scope,
                        None,
                        ignore_decl,
                        None,
                    ) {
                        let res = binding.res();
                        for error in &mut self.privacy_errors[privacy_errors_len..] {
                            error.outermost_res = Some((res, ident));
                        }
                        break;
                    }
                }
            }
        }

        let mut all_ns_err = true;
        self.per_ns_mut(|this, ns| {
            let binding = this.cm_mut().resolve_ident_in_module(
                module,
                ident,
                ns,
                &import.parent_scope,
                Some(Finalize {
                    report_private: false,
                    import: Some(import.summary()),
                    ..finalize
                }),
                bindings[ns].get().decl(),
                Some(import),
            );

            match binding {
                Ok(binding) => {
                    // Consistency checks, analogous to `finalize_macro_resolutions`.
                    let initial_res = bindings[ns].get().decl().map(|binding| {
                        let initial_binding = binding.import_source();
                        all_ns_err = false;
                        if target.name == kw::Underscore
                            && initial_binding.is_extern_crate()
                            && !initial_binding.is_import()
                        {
                            let used = if import.module_path.is_empty() {
                                Used::Scope
                            } else {
                                Used::Other
                            };
                            this.record_use(ident, binding, used);
                        }
                        initial_binding.res()
                    });
                    let res = binding.res();
                    let has_ambiguity_error =
                        this.ambiguity_errors.iter().any(|error| error.warning.is_none());
                    if res == Res::Err || has_ambiguity_error {
                        this.dcx()
                            .span_delayed_bug(import.span, "some error happened for an import");
                        return;
                    }
                    if let Some(initial_res) = initial_res {
                        if res != initial_res && !this.issue_145575_hack_applied {
                            span_bug!(import.span, "inconsistent resolution for an import");
                        }
                    } else if this.privacy_errors.is_empty() {
                        this.dcx()
                            .create_err(CannotDetermineImportResolution { span: import.span })
                            .emit();
                    }
                }
                Err(..) => {
                    // FIXME: This assert may fire if public glob is later shadowed by a private
                    // single import (see test `issue-55884-2.rs`). In theory single imports should
                    // always block globs, even if they are not yet resolved, so that this kind of
                    // self-inconsistent resolution never happens.
                    // Re-enable the assert when the issue is fixed.
                    // assert!(result[ns].get().is_err());
                }
            }
        });

        if all_ns_err {
            let mut all_ns_failed = true;
            self.per_ns_mut(|this, ns| {
                let binding = this.cm_mut().resolve_ident_in_module(
                    module,
                    ident,
                    ns,
                    &import.parent_scope,
                    Some(finalize),
                    None,
                    None,
                );
                if binding.is_ok() {
                    all_ns_failed = false;
                }
            });

            return if all_ns_failed {
                let names = match module {
                    ModuleOrUniformRoot::Module(module) => {
                        self.resolutions(module)
                            .iter()
                            .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
                                if i.name == ident.name {
                                    return None;
                                } // Never suggest the same name
                                if i.name == kw::Underscore {
                                    return None;
                                } // `use _` is never valid

                                let resolution = resolution.borrow(self);
                                if let Some(name_binding) = resolution.best_decl() {
                                    match name_binding.kind {
                                        DeclKind::Import { source_decl, .. } => {
                                            match source_decl.kind {
                                                // Never suggest names that previously could not
                                                // be resolved.
                                                DeclKind::Def(Res::Err) => None,
                                                _ => Some(i.name),
                                            }
                                        }
                                        _ => Some(i.name),
                                    }
                                } else if resolution.single_imports.is_empty() {
                                    None
                                } else {
                                    Some(i.name)
                                }
                            })
                            .collect()
                    }
                    _ => Vec::new(),
                };

                let lev_suggestion =
                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
                        (
                            vec![(ident.span, suggestion.to_string())],
                            String::from("a similar name exists in the module"),
                            Applicability::MaybeIncorrect,
                        )
                    });

                let (suggestion, note) =
                    match self.check_for_module_export_macro(import, module, ident) {
                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
                        _ => (lev_suggestion, None),
                    };

                // If importing of trait asscoiated items is enabled, an also find an
                // `Enum`, then note that inherent associated items cannot be imported.
                let note = if self.features.import_trait_associated_functions()
                    && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
                    && let Some(Res::Def(DefKind::Enum, _)) = m.res()
                {
                    note.or(Some(
                        "cannot import inherent associated items, only trait associated items"
                            .to_string(),
                    ))
                } else {
                    note
                };

                let label = match module {
                    ModuleOrUniformRoot::Module(module) => {
                        let module_str = module_to_string(module);
                        if let Some(module_str) = module_str {
                            format!("no `{ident}` in `{module_str}`")
                        } else {
                            format!("no `{ident}` in the root")
                        }
                    }
                    _ => {
                        if !ident.is_path_segment_keyword() {
                            format!("no external crate `{ident}`")
                        } else {
                            // HACK(eddyb) this shows up for `self` & `super`, which
                            // should work instead - for now keep the same error message.
                            format!("no `{ident}` in the root")
                        }
                    }
                };

                let parent_suggestion =
                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);

                Some(UnresolvedImportError {
                    span: import.span,
                    label: Some(label),
                    note,
                    suggestion,
                    help: None,
                    candidates: if !parent_suggestion.is_empty() {
                        Some(parent_suggestion)
                    } else {
                        None
                    },
                    module: import.imported_module.get().and_then(|module| {
                        if let ModuleOrUniformRoot::Module(m) = module {
                            m.opt_def_id()
                        } else {
                            None
                        }
                    }),
                    segment: Some(ident),
                    on_unknown_attr: import.on_unknown_attr.clone(),
                })
            } else {
                // `resolve_ident_in_module` reported a privacy error.
                None
            };
        }

        let mut reexport_error = None;
        let mut any_successful_reexport = false;
        self.per_ns(|this, ns| {
            let Some(binding) = bindings[ns].get().decl() else {
                return;
            };

            if import.vis.greater_than(binding.vis(), this.tcx) {
                // In isolation, a declaration like this is not an error, but if *all* 1-3
                // declarations introduced by the import are more private than the import item's
                // nominal visibility, then it's an error.
                reexport_error = Some((ns, binding.import_source()));
            } else {
                any_successful_reexport = true;
            }
        });

        if !any_successful_reexport {
            let (ns, binding) = reexport_error.unwrap();
            if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
                self.lint_buffer.add_early_lint(lint);
            }
        }

        if import.module_path.len() <= 1 {
            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
            // 2 segments, so the `resolve_path` above won't trigger it.
            let mut full_path = import.module_path.clone();
            full_path.push(Segment::from_ident(ident));
            self.per_ns_mut(|this, ns| {
                if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
                    this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
                }
            });
        }

        // Record what this import resolves to for later uses in documentation,
        // this may resolve to either a value or a type, but for documentation
        // purposes it's good enough to just favor one over the other.
        self.per_ns_mut(|this, ns| {
            if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
                this.owners.get_mut(&import_id).unwrap().import_res[ns] = Some(binding.res());
            }
        });

        debug!("(resolving single import) successfully resolved import");
        None
    }

    fn report_cannot_reexport(
        &self,
        import: Import<'ra>,
        decl: Decl<'ra>,
        ident: Ident,
        ns: Namespace,
    ) -> Option<BufferedEarlyLint> {
        let crate_private_reexport = match decl.vis() {
            Visibility::Restricted(mod_id) if mod_id.is_top_level_module() => true,
            _ => false,
        };

        if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import.summary(), decl)
        {
            let ImportKind::Single { id, .. } = import.kind else { unreachable!() };
            let sugg = self.tcx.source_span(extern_crate_id).shrink_to_lo();
            let diagnostic = crate::rustc_resolve::diagnostics::PrivateExternCrateReexport { ident, sugg };
            return Some(BufferedEarlyLint {
                lint_id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
                node_id: id,
                span: Some(import.span.into()),
                diagnostic: diagnostic.into(),
            });
        } else if ns == TypeNS {
            let err = if crate_private_reexport {
                self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
            } else {
                self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
            };
            err.emit();
        } else {
            let mut err = if crate_private_reexport {
                self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
            } else {
                self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
            };

            match decl.kind {
                // exclude decl_macro
                DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
                    if let SyntaxExtensionKind::MacroRules(mr) =
                        &self.get_macro_by_def_id(def_id).kind
                        && mr.is_macro_rules() =>
                {
                    err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
                    err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
                }
                _ => {
                    err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
                }
            }
            err.emit();
        }

        None
    }

    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
        // This function is only called for single imports.
        let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
            unreachable!()
        };

        // Skip if the import is of the form `use source as target` and source != target.
        if source != target {
            return false;
        }

        // Skip if the import was produced by a macro.
        if import.parent_scope.expansion != LocalExpnId::ROOT {
            return false;
        }

        // Skip if we are inside a named module (in contrast to an anonymous
        // module defined by a block).
        // Skip if the import is public or was used through non scope-based resolution,
        // e.g. through a module-relative path.
        if self.import_use_map.get(&import) == Some(&Used::Other)
            || self.effective_visibilities.is_exported(def_id)
        {
            return false;
        }

        let mut is_redundant = true;
        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
        self.per_ns(|this, ns| {
            let binding = decls[ns].get().decl().map(|b| b.import_source());
            if is_redundant && let Some(binding) = binding {
                if binding.res() == Res::Err {
                    return;
                }

                match this.cm().resolve_ident_in_scope_set(
                    target,
                    ScopeSet::All(ns),
                    &import.parent_scope,
                    None,
                    decls[ns].get().decl(),
                    None,
                ) {
                    Ok(other_binding) => {
                        is_redundant = binding.res() == other_binding.res()
                            && !other_binding.is_ambiguity_recursive();
                        if is_redundant {
                            redundant_span[ns] =
                                Some((other_binding.span, other_binding.is_import()));
                        }
                    }
                    Err(_) => is_redundant = false,
                }
            }
        });

        if is_redundant && !redundant_span.is_empty() {
            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
            redundant_spans.sort();
            redundant_spans.dedup();
            self.lint_buffer.dyn_buffer_lint(
                REDUNDANT_IMPORTS,
                id,
                import.span,
                move |dcx, level| {
                    let ident = source;
                    let subs = redundant_spans
                        .into_iter()
                        .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
                            (false, true) => {
                                diagnostics::RedundantImportSub::ImportedHere { span, ident }
                            }
                            (false, false) => {
                                diagnostics::RedundantImportSub::DefinedHere { span, ident }
                            }
                            (true, true) => {
                                diagnostics::RedundantImportSub::ImportedPrelude { span, ident }
                            }
                            (true, false) => {
                                diagnostics::RedundantImportSub::DefinedPrelude { span, ident }
                            }
                        })
                        .collect();
                    diagnostics::RedundantImport { subs, ident }.into_diag(dcx, level)
                },
            );
            return true;
        }

        false
    }

    fn resolve_glob_import(
        &self,
        import: Import<'ra>,
        imported_module: ModuleOrUniformRoot<'ra>,
    ) -> ImportResolutionKind<'ra> {
        let import_bindings = match imported_module {
            ModuleOrUniformRoot::Module(module) if module != import.parent_scope.module => self
                .resolutions(module)
                .iter()
                .filter_map(|(key, resolution)| {
                    let res = resolution.borrow_checked(self);
                    let decl = res.determined_decl()?;
                    let mut key = *key;
                    let scope = match key.ident.ctxt.update_unchecked(|ctxt| {
                        ctxt.reverse_glob_adjust(module.expansion, import.span)
                    }) {
                        Some(Some(def)) => self.expn_def_scope(def),
                        Some(None) => import.parent_scope.module,
                        None => return None,
                    };
                    self.is_accessible_from(decl.vis(), scope).then_some((
                        decl,
                        key,
                        res.orig_ident_span,
                    ))
                })
                .collect::<Vec<_>>(),

            // Errors are reported in `write_imports_resolutions`
            _ => vec![],
        };

        ImportResolutionKind::Glob(import_bindings)
    }

    // Hack for the `rust_embed` regression observed in the crater run of #145108.
    fn rust_embed_hack(&self, module: LocalModule<'ra>, decl: Decl<'ra>) -> bool {
        // We are looking for this pattern:
        // ```rust
        // #[macro_use]
        // extern crate rust_embed_impl;
        // pub use rust_embed_impl::*;
        //
        // pub use RustEmbed as Embed;
        // ```
        if let DeclKind::Import { source_decl, import } = decl.kind
            // Check that `decl` is the re-export: "pub use RustEmbed as Embed;"
            && let ImportKind::Single { source, .. } = import.kind
            && source.name == sym::RustEmbed
            // make sure that the import points to the #[macro_use] import
            && let DeclKind::Import { import, .. } = source_decl.kind
            && matches!(import.kind, ImportKind::MacroUse { .. })
            && self.macro_use_prelude.contains_key(&source.name) // and that the name actually exists in the macro_use_prelude
            // Then check that `RustEmbed` exists in the modules Macro namespace.
            && let Some(y_decl) = self
                .resolution(module.to_module(), BindingKey::new(IdentKey::new(source), MacroNS))
                .and_then(|res| res.best_decl())
            // which comes from "pub use rust_embed_impl::*"
            && y_decl.is_glob_import()
            && y_decl.vis().is_public()
        {
            return true;
        }

        false
    }

    // Miscellaneous post-processing, including recording re-exports,
    // reporting conflicts, and reporting unresolved imports.
    fn finalize_resolutions_in(
        &self,
        module: LocalModule<'ra>,
        module_children: &mut LocalDefIdMap<Vec<ModChild>>,
        ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
    ) {
        // Since import resolution is finished, globs will not define any more names.
        *module.globs.borrow_mut_checked(self) = Vec::new();

        let Some(def_id) = module.opt_def_id() else { return };

        let mut children = Vec::new();
        let mut ambig_children = Vec::new();

        module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, decl| {
            let res = decl.res().expect_non_local();
            if res != def::Res::Err {
                let vis = if this.rust_embed_hack(module, decl) {
                    Visibility::Public
                } else {
                    decl.vis()
                };
                let ident = ident.orig(orig_ident_span);
                let child = |reexport_chain| ModChild { ident, res, vis, reexport_chain };
                if let Some((ambig_binding1, ambig_binding2)) = decl.descent_to_ambiguity() {
                    let main = child(ambig_binding1.reexport_chain());
                    let second = ModChild {
                        ident,
                        res: ambig_binding2.res().expect_non_local(),
                        vis: ambig_binding2.vis(),
                        reexport_chain: ambig_binding2.reexport_chain(),
                    };
                    ambig_children.push(AmbigModChild { main, second })
                } else {
                    children.push(child(decl.reexport_chain()));
                }
            }
        });

        if !children.is_empty() {
            module_children.insert(def_id.expect_local(), children);
        }
        if !ambig_children.is_empty() {
            ambig_module_children.insert(def_id.expect_local(), ambig_children);
        }
    }
}

pub(crate) fn import_path_to_string(
    names: &[Ident],
    import_kind: &ImportKind<'_>,
    span: Span,
) -> String {
    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
    let global = !names.is_empty() && names[0].name == kw::PathRoot;
    if let Some(pos) = pos {
        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
        names_to_string(names.iter().map(|ident| ident.name))
    } else {
        let names = if global { &names[1..] } else { names };
        if names.is_empty() {
            import_kind_to_string(import_kind)
        } else {
            format!(
                "{}::{}",
                names_to_string(names.iter().map(|ident| ident.name)),
                import_kind_to_string(import_kind),
            )
        }
    }
}

fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
    match import_kind {
        ImportKind::Single { source, .. } => source.to_string(),
        ImportKind::Glob { .. } => "*".to_string(),
        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
        ImportKind::MacroExport => "#[macro_export]".to_string(),
    }
}