1use std::mem;
4
5use rustc_ast::{Item, NodeId};
6use rustc_attr_parsing::AttributeParser;
7use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
8use rustc_data_structures::intern::Interned;
9use rustc_errors::codes::*;
10use rustc_errors::{Applicability, Diagnostic, MultiSpan, pluralize, struct_span_code_err};
11use rustc_hir::Attribute;
12use rustc_hir::attrs::AttributeKind;
13use rustc_hir::attrs::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
14use rustc_hir::def::{self, DefKind, PartialRes};
15use rustc_hir::def_id::{DefId, LocalDefIdMap};
16use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
17use rustc_middle::span_bug;
18use rustc_middle::ty::{TyCtxt, Visibility};
19use rustc_session::lint::builtin::{
20 AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
21 PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
22};
23use rustc_session::parse::feature_err;
24use rustc_span::edit_distance::find_best_match_for_name;
25use rustc_span::hygiene::LocalExpnId;
26use rustc_span::{Ident, Span, Symbol, kw, sym};
27use tracing::debug;
28
29use crate::Namespace::{self, *};
30use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
31use crate::errors::{
32 self, CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS,
33 CannotBeReexportedPrivate, CannotBeReexportedPrivateNS, CannotDetermineImportResolution,
34 CannotGlobImportAllCrates, ConsiderAddingMacroExport, ConsiderMarkingAsPub,
35 ConsiderMarkingAsPubCrate,
36};
37use crate::ref_mut::CmCell;
38use crate::{
39 AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
40 IdentKey, ImportSuggestion, Module, ModuleOrUniformRoot, ParentScope, PathResult, PerNS,
41 ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
42};
43
44type Res = def::Res<NodeId>;
45
46#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for PendingDecl<'ra> {
#[inline]
fn clone(&self) -> PendingDecl<'ra> {
let _: ::core::clone::AssertParamIsClone<Option<Decl<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for PendingDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::default::Default for PendingDecl<'ra> {
#[inline]
fn default() -> PendingDecl<'ra> { Self::Pending }
}Default, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for PendingDecl<'ra> {
#[inline]
fn eq(&self, other: &PendingDecl<'ra>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PendingDecl::Ready(__self_0), PendingDecl::Ready(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for PendingDecl<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PendingDecl::Ready(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ready",
&__self_0),
PendingDecl::Pending =>
::core::fmt::Formatter::write_str(f, "Pending"),
}
}
}Debug)]
49pub(crate) enum PendingDecl<'ra> {
50 Ready(Option<Decl<'ra>>),
51 #[default]
52 Pending,
53}
54
55impl<'ra> PendingDecl<'ra> {
56 pub(crate) fn decl(self) -> Option<Decl<'ra>> {
57 match self {
58 PendingDecl::Ready(decl) => decl,
59 PendingDecl::Pending => None,
60 }
61 }
62}
63
64#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportKind<'ra> {
#[inline]
fn clone(&self) -> ImportKind<'ra> {
match self {
ImportKind::Single {
source: __self_0,
target: __self_1,
decls: __self_2,
type_ns_only: __self_3,
nested: __self_4,
id: __self_5 } =>
ImportKind::Single {
source: ::core::clone::Clone::clone(__self_0),
target: ::core::clone::Clone::clone(__self_1),
decls: ::core::clone::Clone::clone(__self_2),
type_ns_only: ::core::clone::Clone::clone(__self_3),
nested: ::core::clone::Clone::clone(__self_4),
id: ::core::clone::Clone::clone(__self_5),
},
ImportKind::Glob { max_vis: __self_0, id: __self_1 } =>
ImportKind::Glob {
max_vis: ::core::clone::Clone::clone(__self_0),
id: ::core::clone::Clone::clone(__self_1),
},
ImportKind::ExternCrate {
source: __self_0, target: __self_1, id: __self_2 } =>
ImportKind::ExternCrate {
source: ::core::clone::Clone::clone(__self_0),
target: ::core::clone::Clone::clone(__self_1),
id: ::core::clone::Clone::clone(__self_2),
},
ImportKind::MacroUse { warn_private: __self_0 } =>
ImportKind::MacroUse {
warn_private: ::core::clone::Clone::clone(__self_0),
},
ImportKind::MacroExport => ImportKind::MacroExport,
}
}
}Clone)]
66pub(crate) enum ImportKind<'ra> {
67 Single {
68 source: Ident,
70 target: Ident,
73 decls: PerNS<CmCell<PendingDecl<'ra>>>,
75 type_ns_only: bool,
77 nested: bool,
79 id: NodeId,
91 },
92 Glob {
93 max_vis: CmCell<Option<Visibility>>,
96 id: NodeId,
97 },
98 ExternCrate {
99 source: Option<Symbol>,
100 target: Ident,
101 id: NodeId,
102 },
103 MacroUse {
104 warn_private: bool,
107 },
108 MacroExport,
109}
110
111impl<'ra> std::fmt::Debug for ImportKind<'ra> {
114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 use ImportKind::*;
116 match self {
117 Single { source, target, decls, type_ns_only, nested, id, .. } => f
118 .debug_struct("Single")
119 .field("source", source)
120 .field("target", target)
121 .field(
123 "decls",
124 &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!("..")format_args!(".."))),
125 )
126 .field("type_ns_only", type_ns_only)
127 .field("nested", nested)
128 .field("id", id)
129 .finish(),
130 Glob { max_vis, id } => {
131 f.debug_struct("Glob").field("max_vis", max_vis).field("id", id).finish()
132 }
133 ExternCrate { source, target, id } => f
134 .debug_struct("ExternCrate")
135 .field("source", source)
136 .field("target", target)
137 .field("id", id)
138 .finish(),
139 MacroUse { warn_private } => {
140 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
141 }
142 MacroExport => f.debug_struct("MacroExport").finish(),
143 }
144 }
145}
146
147#[derive(#[automatically_derived]
impl ::core::fmt::Debug for OnUnknownData {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "OnUnknownData",
"directive", &&self.directive)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for OnUnknownData {
#[inline]
fn clone(&self) -> OnUnknownData {
OnUnknownData {
directive: ::core::clone::Clone::clone(&self.directive),
}
}
}Clone, #[automatically_derived]
impl ::core::default::Default for OnUnknownData {
#[inline]
fn default() -> OnUnknownData {
OnUnknownData { directive: ::core::default::Default::default() }
}
}Default)]
148pub(crate) struct OnUnknownData {
149 directive: Directive,
150}
151
152impl OnUnknownData {
153 pub(crate) fn from_attrs<'tcx>(tcx: TyCtxt<'tcx>, item: &Item) -> Option<OnUnknownData> {
154 if let Some(Attribute::Parsed(AttributeKind::OnUnknown { directive, .. })) =
155 AttributeParser::parse_limited(
156 tcx.sess,
157 &item.attrs,
158 &[sym::diagnostic, sym::on_unknown],
159 item.span,
160 item.id,
161 Some(tcx.features()),
162 )
163 {
164 Some(Self { directive: *directive? })
165 } else {
166 None
167 }
168 }
169}
170
171#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ImportData<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["kind", "root_id", "use_span", "use_span_with_attributes",
"has_attributes", "span", "root_span", "parent_scope",
"module_path", "imported_module", "vis", "vis_span",
"on_unknown_attr"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.root_id, &self.use_span,
&self.use_span_with_attributes, &self.has_attributes,
&self.span, &self.root_span, &self.parent_scope,
&self.module_path, &self.imported_module, &self.vis,
&self.vis_span, &&self.on_unknown_attr];
::core::fmt::Formatter::debug_struct_fields_finish(f, "ImportData",
names, values)
}
}Debug, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportData<'ra> {
#[inline]
fn clone(&self) -> ImportData<'ra> {
ImportData {
kind: ::core::clone::Clone::clone(&self.kind),
root_id: ::core::clone::Clone::clone(&self.root_id),
use_span: ::core::clone::Clone::clone(&self.use_span),
use_span_with_attributes: ::core::clone::Clone::clone(&self.use_span_with_attributes),
has_attributes: ::core::clone::Clone::clone(&self.has_attributes),
span: ::core::clone::Clone::clone(&self.span),
root_span: ::core::clone::Clone::clone(&self.root_span),
parent_scope: ::core::clone::Clone::clone(&self.parent_scope),
module_path: ::core::clone::Clone::clone(&self.module_path),
imported_module: ::core::clone::Clone::clone(&self.imported_module),
vis: ::core::clone::Clone::clone(&self.vis),
vis_span: ::core::clone::Clone::clone(&self.vis_span),
on_unknown_attr: ::core::clone::Clone::clone(&self.on_unknown_attr),
}
}
}Clone)]
173pub(crate) struct ImportData<'ra> {
174 pub kind: ImportKind<'ra>,
175
176 pub root_id: NodeId,
186
187 pub use_span: Span,
189
190 pub use_span_with_attributes: Span,
192
193 pub has_attributes: bool,
195
196 pub span: Span,
198
199 pub root_span: Span,
201
202 pub parent_scope: ParentScope<'ra>,
203 pub module_path: Vec<Segment>,
204 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
213 pub vis: Visibility,
214
215 pub vis_span: Span,
217
218 pub on_unknown_attr: Option<OnUnknownData>,
222}
223
224pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
227
228impl std::hash::Hash for ImportData<'_> {
233 fn hash<H>(&self, _: &mut H)
234 where
235 H: std::hash::Hasher,
236 {
237 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
238 }
239}
240
241impl<'ra> ImportData<'ra> {
242 pub(crate) fn is_glob(&self) -> bool {
243 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Glob { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Glob { .. })
244 }
245
246 pub(crate) fn is_nested(&self) -> bool {
247 match self.kind {
248 ImportKind::Single { nested, .. } => nested,
249 _ => false,
250 }
251 }
252
253 pub(crate) fn id(&self) -> Option<NodeId> {
254 match self.kind {
255 ImportKind::Single { id, .. }
256 | ImportKind::Glob { id, .. }
257 | ImportKind::ExternCrate { id, .. } => Some(id),
258 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
259 }
260 }
261
262 pub(crate) fn simplify(&self, r: &Resolver<'_, '_>) -> Reexport {
263 let to_def_id = |id| r.local_def_id(id).to_def_id();
264 match self.kind {
265 ImportKind::Single { id, .. } => Reexport::Single(to_def_id(id)),
266 ImportKind::Glob { id, .. } => Reexport::Glob(to_def_id(id)),
267 ImportKind::ExternCrate { id, .. } => Reexport::ExternCrate(to_def_id(id)),
268 ImportKind::MacroUse { .. } => Reexport::MacroUse,
269 ImportKind::MacroExport => Reexport::MacroExport,
270 }
271 }
272}
273
274#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for NameResolution<'ra> {
#[inline]
fn clone(&self) -> NameResolution<'ra> {
NameResolution {
single_imports: ::core::clone::Clone::clone(&self.single_imports),
non_glob_decl: ::core::clone::Clone::clone(&self.non_glob_decl),
glob_decl: ::core::clone::Clone::clone(&self.glob_decl),
orig_ident_span: ::core::clone::Clone::clone(&self.orig_ident_span),
}
}
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for NameResolution<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"NameResolution", "single_imports", &self.single_imports,
"non_glob_decl", &self.non_glob_decl, "glob_decl",
&self.glob_decl, "orig_ident_span", &&self.orig_ident_span)
}
}Debug)]
276pub(crate) struct NameResolution<'ra> {
277 pub single_imports: FxIndexSet<Import<'ra>>,
280 pub non_glob_decl: Option<Decl<'ra>> = None,
282 pub glob_decl: Option<Decl<'ra>> = None,
284 pub orig_ident_span: Span,
285}
286
287impl<'ra> NameResolution<'ra> {
288 pub(crate) fn new(orig_ident_span: Span) -> Self {
289 NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
290 }
291
292 pub(crate) fn binding(&self) -> Option<Decl<'ra>> {
294 self.best_decl().and_then(|binding| {
295 if !binding.is_glob_import() || self.single_imports.is_empty() {
296 Some(binding)
297 } else {
298 None
299 }
300 })
301 }
302
303 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
304 self.non_glob_decl.or(self.glob_decl)
305 }
306}
307
308#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnresolvedImportError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["span", "label", "note", "suggestion", "candidates", "segment",
"module", "on_unknown_attr"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.span, &self.label, &self.note, &self.suggestion,
&self.candidates, &self.segment, &self.module,
&&self.on_unknown_attr];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"UnresolvedImportError", names, values)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for UnresolvedImportError {
#[inline]
fn clone(&self) -> UnresolvedImportError {
UnresolvedImportError {
span: ::core::clone::Clone::clone(&self.span),
label: ::core::clone::Clone::clone(&self.label),
note: ::core::clone::Clone::clone(&self.note),
suggestion: ::core::clone::Clone::clone(&self.suggestion),
candidates: ::core::clone::Clone::clone(&self.candidates),
segment: ::core::clone::Clone::clone(&self.segment),
module: ::core::clone::Clone::clone(&self.module),
on_unknown_attr: ::core::clone::Clone::clone(&self.on_unknown_attr),
}
}
}Clone)]
311struct UnresolvedImportError {
312 span: Span,
313 label: Option<String>,
314 note: Option<String>,
315 suggestion: Option<Suggestion>,
316 candidates: Option<Vec<ImportSuggestion>>,
317 segment: Option<Symbol>,
318 module: Option<DefId>,
320 on_unknown_attr: Option<OnUnknownData>,
321}
322
323fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
326 match (&import.kind, &decl.kind) {
327 (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
328 if let ImportKind::ExternCrate { id, .. } = decl_import.kind
329 && import.vis.is_public() =>
330 {
331 Some(id)
332 }
333 _ => None,
334 }
335}
336
337fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
339 if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
340 && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
341 && import1 == import2
342 {
343 match (&d1.expansion, &d2.expansion) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(d1.expansion, d2.expansion);
344 match (&d1.span, &d2.span) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(d1.span, d2.span);
345 if d1.ambiguity.get() != d2.ambiguity.get() {
346 if !d1.ambiguity.get().is_some() {
::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
347 if !d2.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: d2.ambiguity.get().is_none()")
};assert!(d2.ambiguity.get().is_none());
348 }
349 remove_same_import(d1_next, d2_next)
353 } else {
354 (d1, d2)
355 }
356}
357
358impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
359 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
362 let import_vis = import.vis.to_def_id();
363 let vis = if decl.vis().is_at_least(import_vis, self.tcx)
364 || pub_use_of_private_extern_crate_hack(import, decl).is_some()
365 {
366 import_vis
367 } else {
368 decl.vis()
369 };
370
371 if let ImportKind::Glob { ref max_vis, .. } = import.kind
372 && (vis == import_vis
373 || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
374 {
375 max_vis.set_unchecked(Some(vis.expect_local()))
376 }
377
378 self.arenas.alloc_decl(DeclData {
379 kind: DeclKind::Import { source_decl: decl, import },
380 ambiguity: CmCell::new(None),
381 warn_ambiguity: CmCell::new(false),
382 span: import.span,
383 vis: CmCell::new(vis),
384 expansion: import.parent_scope.expansion,
385 parent_module: Some(import.parent_scope.module),
386 })
387 }
388
389 fn select_glob_decl(
392 &self,
393 old_glob_decl: Decl<'ra>,
394 glob_decl: Decl<'ra>,
395 warn_ambiguity: bool,
396 ) -> Decl<'ra> {
397 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
398 if !old_glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: old_glob_decl.is_glob_import()")
};assert!(old_glob_decl.is_glob_import());
399 match (&glob_decl, &old_glob_decl) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_ne!(glob_decl, old_glob_decl);
400 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
417 if deep_decl != glob_decl {
418 match (&old_deep_decl, &old_glob_decl) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_ne!(old_deep_decl, old_glob_decl);
420 if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
426 glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
428 }
429 if glob_decl.is_ambiguity_recursive() {
430 glob_decl.warn_ambiguity.set_unchecked(true);
431 }
432 glob_decl
433 } else if glob_decl.res() != old_glob_decl.res() {
434 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
435 old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
436 if warn_ambiguity {
437 old_glob_decl
438 } else {
439 self.arenas.alloc_decl((*old_glob_decl).clone())
443 }
444 } else if !old_glob_decl.vis().is_at_least(glob_decl.vis(), self.tcx) {
445 glob_decl
449 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
450 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
452 old_glob_decl.warn_ambiguity.set_unchecked(true);
453 old_glob_decl
454 } else {
455 old_glob_decl
456 }
457 }
458
459 pub(crate) fn try_plant_decl_into_local_module(
462 &mut self,
463 ident: IdentKey,
464 orig_ident_span: Span,
465 ns: Namespace,
466 decl: Decl<'ra>,
467 warn_ambiguity: bool,
468 ) -> Result<(), Decl<'ra>> {
469 let module = decl.parent_module.unwrap();
470 let res = decl.res();
471 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
472 let key = BindingKey::new_disambiguated(ident, ns, || {
476 module.underscore_disambiguator.update_unchecked(|d| d + 1);
477 module.underscore_disambiguator.get()
478 });
479 self.update_local_resolution(
480 module,
481 key,
482 orig_ident_span,
483 warn_ambiguity,
484 |this, resolution| {
485 if let Some(old_decl) = resolution.best_decl() {
486 match (&decl, &old_decl) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_ne!(decl, old_decl);
487 if !!decl.warn_ambiguity.get() {
::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
488 if res == Res::Err && old_decl.res() != Res::Err {
489 return Ok(());
491 }
492 match (old_decl.is_glob_import(), decl.is_glob_import()) {
493 (true, true) => {
494 resolution.glob_decl =
495 Some(this.select_glob_decl(old_decl, decl, warn_ambiguity));
496 }
497 (old_glob @ true, false) | (old_glob @ false, true) => {
498 let (glob_decl, non_glob_decl) =
499 if old_glob { (old_decl, decl) } else { (decl, old_decl) };
500 resolution.non_glob_decl = Some(non_glob_decl);
501 if let Some(old_glob_decl) = resolution.glob_decl
502 && old_glob_decl != glob_decl
503 {
504 resolution.glob_decl =
505 Some(this.select_glob_decl(old_glob_decl, glob_decl, false));
506 } else {
507 resolution.glob_decl = Some(glob_decl);
508 }
509 }
510 (false, false) => {
511 return Err(old_decl);
512 }
513 }
514 } else {
515 if decl.is_glob_import() {
516 resolution.glob_decl = Some(decl);
517 } else {
518 resolution.non_glob_decl = Some(decl);
519 }
520 }
521
522 Ok(())
523 },
524 )
525 }
526
527 fn update_local_resolution<T, F>(
530 &mut self,
531 module: Module<'ra>,
532 key: BindingKey,
533 orig_ident_span: Span,
534 warn_ambiguity: bool,
535 f: F,
536 ) -> T
537 where
538 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
539 {
540 let (binding, t, warn_ambiguity) = {
543 let resolution = &mut *self
544 .resolution_or_default(module, key, orig_ident_span)
545 .borrow_mut_unchecked();
546 let old_decl = resolution.binding();
547
548 let t = f(self, resolution);
549
550 if let Some(binding) = resolution.binding()
551 && old_decl != Some(binding)
552 {
553 (binding, t, warn_ambiguity || old_decl.is_some())
554 } else {
555 return t;
556 }
557 };
558
559 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
560 return t;
561 };
562
563 for import in glob_importers.iter() {
565 let mut ident = key.ident;
566 let scope = match ident
567 .ctxt
568 .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
569 {
570 Some(Some(def)) => self.expn_def_scope(def),
571 Some(None) => import.parent_scope.module,
572 None => continue,
573 };
574 if self.is_accessible_from(binding.vis(), scope) {
575 let import_decl = self.new_import_decl(binding, *import);
576 let _ = self.try_plant_decl_into_local_module(
577 ident,
578 orig_ident_span,
579 key.ns,
580 import_decl,
581 warn_ambiguity,
582 );
583 }
584 }
585
586 t
587 }
588
589 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
592 if let ImportKind::Single { target, ref decls, .. } = import.kind {
593 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
594 return; }
596 let dummy_decl = self.dummy_decl;
597 let dummy_decl = self.new_import_decl(dummy_decl, import);
598 self.per_ns(|this, ns| {
599 let module = import.parent_scope.module;
600 let ident = IdentKey::new(target);
601 let _ = this.try_plant_decl_into_local_module(
602 ident,
603 target.span,
604 ns,
605 dummy_decl,
606 false,
607 );
608 if target.name != kw::Underscore {
610 let key = BindingKey::new(ident, ns);
611 this.update_local_resolution(
612 module,
613 key,
614 target.span,
615 false,
616 |_, resolution| {
617 resolution.single_imports.swap_remove(&import);
618 },
619 )
620 }
621 });
622 self.record_use(target, dummy_decl, Used::Other);
623 } else if import.imported_module.get().is_none() {
624 self.import_use_map.insert(import, Used::Other);
625 if let Some(id) = import.id() {
626 self.used_imports.insert(id);
627 }
628 }
629 }
630
631 pub(crate) fn resolve_imports(&mut self) {
642 let mut prev_indeterminate_count = usize::MAX;
643 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
644 while indeterminate_count < prev_indeterminate_count {
645 prev_indeterminate_count = indeterminate_count;
646 indeterminate_count = 0;
647 self.assert_speculative = true;
648 for import in mem::take(&mut self.indeterminate_imports) {
649 let import_indeterminate_count = self.cm().resolve_import(import);
650 indeterminate_count += import_indeterminate_count;
651 match import_indeterminate_count {
652 0 => self.determined_imports.push(import),
653 _ => self.indeterminate_imports.push(import),
654 }
655 }
656 self.assert_speculative = false;
657 }
658 }
659
660 pub(crate) fn finalize_imports(&mut self) {
661 let mut module_children = Default::default();
662 let mut ambig_module_children = Default::default();
663 for module in &self.local_modules {
664 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
665 }
666 self.module_children = module_children;
667 self.ambig_module_children = ambig_module_children;
668
669 let mut seen_spans = FxHashSet::default();
670 let mut errors = ::alloc::vec::Vec::new()vec![];
671 let mut prev_root_id: NodeId = NodeId::ZERO;
672 let determined_imports = mem::take(&mut self.determined_imports);
673 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
674
675 let mut glob_error = false;
676 for (is_indeterminate, import) in determined_imports
677 .iter()
678 .map(|i| (false, i))
679 .chain(indeterminate_imports.iter().map(|i| (true, i)))
680 {
681 let unresolved_import_error = self.finalize_import(*import);
682 self.import_dummy_binding(*import, is_indeterminate);
685
686 let Some(err) = unresolved_import_error else { continue };
687
688 glob_error |= import.is_glob();
689
690 if let ImportKind::Single { source, ref decls, .. } = import.kind
691 && source.name == kw::SelfLower
692 && let PendingDecl::Ready(None) = decls.value_ns.get()
694 {
695 continue;
696 }
697
698 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
699 {
700 self.throw_unresolved_import_error(errors, glob_error);
703 errors = ::alloc::vec::Vec::new()vec![];
704 }
705 if seen_spans.insert(err.span) {
706 errors.push((*import, err));
707 prev_root_id = import.root_id;
708 }
709 }
710
711 if self.cstore().had_extern_crate_load_failure() {
712 self.tcx.sess.dcx().abort_if_errors();
713 }
714
715 if !errors.is_empty() {
716 self.throw_unresolved_import_error(errors, glob_error);
717 return;
718 }
719
720 for import in &indeterminate_imports {
721 let path = import_path_to_string(
722 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
723 &import.kind,
724 import.span,
725 );
726 if path.contains("::") {
729 let err = UnresolvedImportError {
730 span: import.span,
731 label: None,
732 note: None,
733 suggestion: None,
734 candidates: None,
735 segment: None,
736 module: None,
737 on_unknown_attr: import.on_unknown_attr.clone(),
738 };
739 errors.push((*import, err))
740 }
741 }
742
743 if !errors.is_empty() {
744 self.throw_unresolved_import_error(errors, glob_error);
745 }
746 }
747
748 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
749 for module in &self.local_modules {
750 for (key, resolution) in self.resolutions(*module).borrow().iter() {
751 let resolution = resolution.borrow();
752 let Some(binding) = resolution.best_decl() else { continue };
753
754 if let DeclKind::Import { import, .. } = binding.kind
755 && let Some(amb_binding) = binding.ambiguity.get()
756 && binding.res() != Res::Err
757 && exported_ambiguities.contains(&binding)
758 {
759 self.lint_buffer.buffer_lint(
760 AMBIGUOUS_GLOB_REEXPORTS,
761 import.root_id,
762 import.root_span,
763 errors::AmbiguousGlobReexports {
764 name: key.ident.name.to_string(),
765 namespace: key.ns.descr().to_string(),
766 first_reexport: import.root_span,
767 duplicate_reexport: amb_binding.span,
768 },
769 );
770 }
771
772 if let Some(glob_decl) = resolution.glob_decl
773 && resolution.non_glob_decl.is_some()
774 {
775 if binding.res() != Res::Err
776 && glob_decl.res() != Res::Err
777 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
778 && let Some(glob_import_id) = glob_import.id()
779 && let glob_import_def_id = self.local_def_id(glob_import_id)
780 && self.effective_visibilities.is_exported(glob_import_def_id)
781 && glob_decl.vis().is_public()
782 && !binding.vis().is_public()
783 {
784 let binding_id = match binding.kind {
785 DeclKind::Def(res) => {
786 Some(self.def_id_to_node_id(res.def_id().expect_local()))
787 }
788 DeclKind::Import { import, .. } => import.id(),
789 };
790 if let Some(binding_id) = binding_id {
791 self.lint_buffer.buffer_lint(
792 HIDDEN_GLOB_REEXPORTS,
793 binding_id,
794 binding.span,
795 errors::HiddenGlobReexports {
796 name: key.ident.name.to_string(),
797 namespace: key.ns.descr().to_owned(),
798 glob_reexport: glob_decl.span,
799 private_item: binding.span,
800 },
801 );
802 }
803 }
804 }
805
806 if let DeclKind::Import { import, .. } = binding.kind
807 && let Some(binding_id) = import.id()
808 && let import_def_id = self.local_def_id(binding_id)
809 && self.effective_visibilities.is_exported(import_def_id)
810 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
811 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
812 && !reexported_def_id.is_local()
813 && self.tcx.is_private_dep(reexported_def_id.krate)
814 {
815 self.lint_buffer.buffer_lint(
816 EXPORTED_PRIVATE_DEPENDENCIES,
817 binding_id,
818 binding.span,
819 crate::errors::ReexportPrivateDependency {
820 name: key.ident.name,
821 kind: binding.res().descr(),
822 krate: self.tcx.crate_name(reexported_def_id.krate),
823 },
824 );
825 }
826 }
827 }
828 }
829
830 fn throw_unresolved_import_error(
831 &mut self,
832 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
833 glob_error: bool,
834 ) {
835 errors.retain(|(_import, err)| match err.module {
836 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
838 _ => err.segment != Some(kw::Underscore),
841 });
842 if errors.is_empty() {
843 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
844 return;
845 }
846
847 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
848
849 let paths = errors
850 .iter()
851 .map(|(import, err)| {
852 let path = import_path_to_string(
853 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
854 &import.kind,
855 err.span,
856 );
857 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
858 })
859 .collect::<Vec<_>>();
860 let default_message =
861 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unresolved import{0} {1}",
if paths.len() == 1 { "" } else { "s" }, paths.join(", ")))
})format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
862 let (message, label, notes) = if self.tcx.features().diagnostic_on_unknown()
863 && let Some(directive) = errors[0].1.on_unknown_attr.as_ref().map(|a| &a.directive)
864 {
865 let args = FormatArgs {
866 this: paths.join(", "),
867 this_sugared: String::new(),
869 item_context: "",
871 generic_args: Vec::new(),
873 };
874 let CustomDiagnostic { message, label, notes, .. } = directive.eval(None, &args);
875
876 (message, label, notes)
877 } else {
878 (None, None, Vec::new())
879 };
880 let has_custom_message = message.is_some();
881 let message = message.as_deref().unwrap_or(default_message.as_str());
882
883 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", message))
})).with_code(E0432)
}struct_span_code_err!(self.dcx(), span, E0432, "{message}");
884 if has_custom_message {
885 diag.note(default_message);
886 }
887
888 if !notes.is_empty() {
889 for note in notes {
890 diag.note(note);
891 }
892 } else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
893 errors.iter().last()
894 {
895 diag.note(note.clone());
896 }
897
898 const MAX_LABEL_COUNT: usize = 10;
900
901 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
902 if let Some(label) = &label {
903 diag.span_label(err.span, label.clone());
904 } else if let Some(label) = &err.label {
905 diag.span_label(err.span, label.clone());
906 }
907
908 if let Some((suggestions, msg, applicability)) = err.suggestion {
909 if suggestions.is_empty() {
910 diag.help(msg);
911 continue;
912 }
913 diag.multipart_suggestion(msg, suggestions, applicability);
914 }
915
916 if let Some(candidates) = &err.candidates {
917 match &import.kind {
918 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
919 self.tcx,
920 &mut diag,
921 Some(err.span),
922 candidates,
923 DiagMode::Import { append: false, unresolved_import: true },
924 (source != target)
925 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
926 .as_deref()
927 .unwrap_or(""),
928 ),
929 ImportKind::Single { nested: true, source, target, .. } => {
930 import_candidates(
931 self.tcx,
932 &mut diag,
933 None,
934 candidates,
935 DiagMode::Normal,
936 (source != target)
937 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
938 .as_deref()
939 .unwrap_or(""),
940 );
941 }
942 _ => {}
943 }
944 }
945
946 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
947 && let Some(segment) = err.segment
948 && let Some(module) = err.module
949 {
950 self.find_cfg_stripped(&mut diag, &segment, module)
951 }
952 }
953
954 let guar = diag.emit();
955 if glob_error {
956 self.glob_error = Some(guar);
957 }
958 }
959
960 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
967 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:967",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(967u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(resolving import for module) resolving import `{0}::...` in `{1}`",
Segment::names_to_string(&import.module_path),
module_to_string(import.parent_scope.module).unwrap_or_else(||
"???".to_string())) as &dyn Value))])
});
} else { ; }
};debug!(
968 "(resolving import for module) resolving import `{}::...` in `{}`",
969 Segment::names_to_string(&import.module_path),
970 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
971 );
972 let module = if let Some(module) = import.imported_module.get() {
973 module
974 } else {
975 let path_res = self.reborrow().maybe_resolve_path(
976 &import.module_path,
977 None,
978 &import.parent_scope,
979 Some(import),
980 );
981
982 match path_res {
983 PathResult::Module(module) => module,
984 PathResult::Indeterminate => return 3,
985 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
986 }
987 };
988
989 import.imported_module.set_unchecked(Some(module));
990 let (source, target, bindings, type_ns_only) = match import.kind {
991 ImportKind::Single { source, target, ref decls, type_ns_only, .. } => {
992 (source, target, decls, type_ns_only)
993 }
994 ImportKind::Glob { .. } => {
995 self.get_mut_unchecked().resolve_glob_import(import);
996 return 0;
997 }
998 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
999 };
1000
1001 let mut indeterminate_count = 0;
1002 self.per_ns_cm(|mut this, ns| {
1003 if !type_ns_only || ns == TypeNS {
1004 if bindings[ns].get() != PendingDecl::Pending {
1005 return;
1006 };
1007 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1008 module,
1009 source,
1010 ns,
1011 &import.parent_scope,
1012 Some(import),
1013 );
1014 let parent = import.parent_scope.module;
1015 let binding = match binding_result {
1016 Ok(binding) => {
1017 if binding.is_assoc_item()
1018 && !this.tcx.features().import_trait_associated_functions()
1019 {
1020 feature_err(
1021 this.tcx.sess,
1022 sym::import_trait_associated_functions,
1023 import.span,
1024 "`use` associated items of traits is unstable",
1025 )
1026 .emit();
1027 }
1028 let import_decl = this.new_import_decl(binding, import);
1030 this.get_mut_unchecked().plant_decl_into_local_module(
1031 IdentKey::new(target),
1032 target.span,
1033 ns,
1034 import_decl,
1035 );
1036 PendingDecl::Ready(Some(import_decl))
1037 }
1038 Err(Determinacy::Determined) => {
1039 if target.name != kw::Underscore {
1041 let key = BindingKey::new(IdentKey::new(target), ns);
1042 this.get_mut_unchecked().update_local_resolution(
1043 parent,
1044 key,
1045 target.span,
1046 false,
1047 |_, resolution| {
1048 resolution.single_imports.swap_remove(&import);
1049 },
1050 );
1051 }
1052 PendingDecl::Ready(None)
1053 }
1054 Err(Determinacy::Undetermined) => {
1055 indeterminate_count += 1;
1056 PendingDecl::Pending
1057 }
1058 };
1059 bindings[ns].set_unchecked(binding);
1060 }
1061 });
1062
1063 indeterminate_count
1064 }
1065
1066 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1071 let ignore_decl = match &import.kind {
1072 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1073 _ => None,
1074 };
1075 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1076 errors.iter().filter(|error| error.warning.is_none()).count()
1077 };
1078 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1079 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1080
1081 let privacy_errors_len = self.privacy_errors.len();
1083
1084 let path_res = self.cm().resolve_path(
1085 &import.module_path,
1086 None,
1087 &import.parent_scope,
1088 Some(finalize),
1089 ignore_decl,
1090 Some(import),
1091 );
1092
1093 let no_ambiguity =
1094 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1095
1096 let module = match path_res {
1097 PathResult::Module(module) => {
1098 if let Some(initial_module) = import.imported_module.get() {
1100 if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1101 ::rustc_middle::util::bug::span_bug_fmt(import.span,
format_args!("inconsistent resolution for an import"));span_bug!(import.span, "inconsistent resolution for an import");
1102 }
1103 } else if self.privacy_errors.is_empty() {
1104 self.dcx()
1105 .create_err(CannotDetermineImportResolution { span: import.span })
1106 .emit();
1107 }
1108
1109 module
1110 }
1111 PathResult::Failed {
1112 is_error_from_last_segment: false,
1113 span,
1114 segment_name,
1115 label,
1116 suggestion,
1117 module,
1118 error_implied_by_parse_error: _,
1119 message,
1120 } => {
1121 if no_ambiguity {
1122 if !self.issue_145575_hack_applied {
1123 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1124 }
1125 self.report_error(
1126 span,
1127 ResolutionError::FailedToResolve {
1128 segment: segment_name,
1129 label,
1130 suggestion,
1131 module,
1132 message,
1133 },
1134 );
1135 }
1136 return None;
1137 }
1138 PathResult::Failed {
1139 is_error_from_last_segment: true,
1140 span,
1141 label,
1142 suggestion,
1143 module,
1144 segment_name,
1145 ..
1146 } => {
1147 if no_ambiguity {
1148 if !self.issue_145575_hack_applied {
1149 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1150 }
1151 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1152 m.opt_def_id()
1153 } else {
1154 None
1155 };
1156 let err = match self
1157 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1158 {
1159 Some((suggestion, note)) => UnresolvedImportError {
1160 span,
1161 label: None,
1162 note,
1163 suggestion: Some((
1164 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, Segment::names_to_string(&suggestion))]))vec![(span, Segment::names_to_string(&suggestion))],
1165 String::from("a similar path exists"),
1166 Applicability::MaybeIncorrect,
1167 )),
1168 candidates: None,
1169 segment: Some(segment_name),
1170 module,
1171 on_unknown_attr: import.on_unknown_attr.clone(),
1172 },
1173 None => UnresolvedImportError {
1174 span,
1175 label: Some(label),
1176 note: None,
1177 suggestion,
1178 candidates: None,
1179 segment: Some(segment_name),
1180 module,
1181 on_unknown_attr: import.on_unknown_attr.clone(),
1182 },
1183 };
1184 return Some(err);
1185 }
1186 return None;
1187 }
1188 PathResult::NonModule(partial_res) => {
1189 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1190 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1192 }
1193 return None;
1195 }
1196 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1197 };
1198
1199 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1200 ImportKind::Single { source, target, ref decls, type_ns_only, id, .. } => {
1201 (source, target, decls, type_ns_only, id)
1202 }
1203 ImportKind::Glob { ref max_vis, id } => {
1204 if import.module_path.len() <= 1 {
1205 let mut full_path = import.module_path.clone();
1208 full_path.push(Segment::from_ident(Ident::dummy()));
1209 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1210 }
1211
1212 if let ModuleOrUniformRoot::Module(module) = module
1213 && module == import.parent_scope.module
1214 {
1215 return Some(UnresolvedImportError {
1217 span: import.span,
1218 label: Some(String::from("cannot glob-import a module into itself")),
1219 note: None,
1220 suggestion: None,
1221 candidates: None,
1222 segment: None,
1223 module: None,
1224 on_unknown_attr: None,
1225 });
1226 }
1227 if let Some(max_vis) = max_vis.get()
1228 && !max_vis.is_at_least(import.vis, self.tcx)
1229 {
1230 let def_id = self.local_def_id(id);
1231 self.lint_buffer.buffer_lint(
1232 UNUSED_IMPORTS,
1233 id,
1234 import.span,
1235 crate::errors::RedundantImportVisibility {
1236 span: import.span,
1237 help: (),
1238 max_vis: max_vis.to_string(def_id, self.tcx),
1239 import_vis: import.vis.to_string(def_id, self.tcx),
1240 },
1241 );
1242 }
1243 return None;
1244 }
1245 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1246 };
1247
1248 if self.privacy_errors.len() != privacy_errors_len {
1249 let mut path = import.module_path.clone();
1252 path.push(Segment::from_ident(ident));
1253 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1254 &path,
1255 None,
1256 &import.parent_scope,
1257 Some(finalize),
1258 ignore_decl,
1259 None,
1260 ) {
1261 let res = module.res().map(|r| (r, ident));
1262 for error in &mut self.privacy_errors[privacy_errors_len..] {
1263 error.outermost_res = res;
1264 }
1265 }
1266 }
1267
1268 let mut all_ns_err = true;
1269 self.per_ns(|this, ns| {
1270 if !type_ns_only || ns == TypeNS {
1271 let binding = this.cm().resolve_ident_in_module(
1272 module,
1273 ident,
1274 ns,
1275 &import.parent_scope,
1276 Some(Finalize {
1277 report_private: false,
1278 import_vis: Some(import.vis),
1279 ..finalize
1280 }),
1281 bindings[ns].get().decl(),
1282 Some(import),
1283 );
1284
1285 match binding {
1286 Ok(binding) => {
1287 let initial_res = bindings[ns].get().decl().map(|binding| {
1289 let initial_binding = binding.import_source();
1290 all_ns_err = false;
1291 if target.name == kw::Underscore
1292 && initial_binding.is_extern_crate()
1293 && !initial_binding.is_import()
1294 {
1295 let used = if import.module_path.is_empty() {
1296 Used::Scope
1297 } else {
1298 Used::Other
1299 };
1300 this.record_use(ident, binding, used);
1301 }
1302 initial_binding.res()
1303 });
1304 let res = binding.res();
1305 let has_ambiguity_error =
1306 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1307 if res == Res::Err || has_ambiguity_error {
1308 this.dcx()
1309 .span_delayed_bug(import.span, "some error happened for an import");
1310 return;
1311 }
1312 if let Some(initial_res) = initial_res {
1313 if res != initial_res && !this.issue_145575_hack_applied {
1314 ::rustc_middle::util::bug::span_bug_fmt(import.span,
format_args!("inconsistent resolution for an import"));span_bug!(import.span, "inconsistent resolution for an import");
1315 }
1316 } else if this.privacy_errors.is_empty() {
1317 this.dcx()
1318 .create_err(CannotDetermineImportResolution { span: import.span })
1319 .emit();
1320 }
1321 }
1322 Err(..) => {
1323 }
1330 }
1331 }
1332 });
1333
1334 if all_ns_err {
1335 let mut all_ns_failed = true;
1336 self.per_ns(|this, ns| {
1337 if !type_ns_only || ns == TypeNS {
1338 let binding = this.cm().resolve_ident_in_module(
1339 module,
1340 ident,
1341 ns,
1342 &import.parent_scope,
1343 Some(finalize),
1344 None,
1345 None,
1346 );
1347 if binding.is_ok() {
1348 all_ns_failed = false;
1349 }
1350 }
1351 });
1352
1353 return if all_ns_failed {
1354 let names = match module {
1355 ModuleOrUniformRoot::Module(module) => {
1356 self.resolutions(module)
1357 .borrow()
1358 .iter()
1359 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1360 if i.name == ident.name {
1361 return None;
1362 } if i.name == kw::Underscore {
1364 return None;
1365 } let resolution = resolution.borrow();
1368 if let Some(name_binding) = resolution.best_decl() {
1369 match name_binding.kind {
1370 DeclKind::Import { source_decl, .. } => {
1371 match source_decl.kind {
1372 DeclKind::Def(Res::Err) => None,
1375 _ => Some(i.name),
1376 }
1377 }
1378 _ => Some(i.name),
1379 }
1380 } else if resolution.single_imports.is_empty() {
1381 None
1382 } else {
1383 Some(i.name)
1384 }
1385 })
1386 .collect()
1387 }
1388 _ => Vec::new(),
1389 };
1390
1391 let lev_suggestion =
1392 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1393 (
1394 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, suggestion.to_string())]))vec![(ident.span, suggestion.to_string())],
1395 String::from("a similar name exists in the module"),
1396 Applicability::MaybeIncorrect,
1397 )
1398 });
1399
1400 let (suggestion, note) =
1401 match self.check_for_module_export_macro(import, module, ident) {
1402 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1403 _ => (lev_suggestion, None),
1404 };
1405
1406 let label = match module {
1407 ModuleOrUniformRoot::Module(module) => {
1408 let module_str = module_to_string(module);
1409 if let Some(module_str) = module_str {
1410 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1411 } else {
1412 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1413 }
1414 }
1415 _ => {
1416 if !ident.is_path_segment_keyword() {
1417 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1418 } else {
1419 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1422 }
1423 }
1424 };
1425
1426 let parent_suggestion =
1427 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1428
1429 Some(UnresolvedImportError {
1430 span: import.span,
1431 label: Some(label),
1432 note,
1433 suggestion,
1434 candidates: if !parent_suggestion.is_empty() {
1435 Some(parent_suggestion)
1436 } else {
1437 None
1438 },
1439 module: import.imported_module.get().and_then(|module| {
1440 if let ModuleOrUniformRoot::Module(m) = module {
1441 m.opt_def_id()
1442 } else {
1443 None
1444 }
1445 }),
1446 segment: Some(ident.name),
1447 on_unknown_attr: import.on_unknown_attr.clone(),
1448 })
1449 } else {
1450 None
1452 };
1453 }
1454
1455 let mut reexport_error = None;
1456 let mut any_successful_reexport = false;
1457 let mut crate_private_reexport = false;
1458 self.per_ns(|this, ns| {
1459 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1460 return;
1461 };
1462
1463 if !binding.vis().is_at_least(import.vis, this.tcx) {
1464 reexport_error = Some((ns, binding));
1465 if let Visibility::Restricted(binding_def_id) = binding.vis()
1466 && binding_def_id.is_top_level_module()
1467 {
1468 crate_private_reexport = true;
1469 }
1470 } else {
1471 any_successful_reexport = true;
1472 }
1473 });
1474
1475 if !any_successful_reexport {
1477 let (ns, binding) = reexport_error.unwrap();
1478 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1479 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1480 self.lint_buffer.buffer_lint(
1481 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1482 import_id,
1483 import.span,
1484 crate::errors::PrivateExternCrateReexport {
1485 ident,
1486 sugg: extern_crate_sp.shrink_to_lo(),
1487 },
1488 );
1489 } else if ns == TypeNS {
1490 let err = if crate_private_reexport {
1491 self.dcx()
1492 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1493 } else {
1494 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1495 };
1496 err.emit();
1497 } else {
1498 let mut err = if crate_private_reexport {
1499 self.dcx()
1500 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1501 } else {
1502 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1503 };
1504
1505 match binding.kind {
1506 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1507 if self.get_macro_by_def_id(def_id).macro_rules =>
1509 {
1510 err.subdiagnostic( ConsiderAddingMacroExport {
1511 span: binding.span,
1512 });
1513 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1514 vis_span: import.vis_span,
1515 });
1516 }
1517 _ => {
1518 err.subdiagnostic( ConsiderMarkingAsPub {
1519 span: import.span,
1520 ident,
1521 });
1522 }
1523 }
1524 err.emit();
1525 }
1526 }
1527
1528 if import.module_path.len() <= 1 {
1529 let mut full_path = import.module_path.clone();
1532 full_path.push(Segment::from_ident(ident));
1533 self.per_ns(|this, ns| {
1534 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1535 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1536 }
1537 });
1538 }
1539
1540 self.per_ns(|this, ns| {
1544 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1545 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1546 }
1547 });
1548
1549 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:1549",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1549u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(resolving single import) successfully resolved import")
as &dyn Value))])
});
} else { ; }
};debug!("(resolving single import) successfully resolved import");
1550 None
1551 }
1552
1553 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1554 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1556 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1557 };
1558
1559 if source != target {
1561 return false;
1562 }
1563
1564 if import.parent_scope.expansion != LocalExpnId::ROOT {
1566 return false;
1567 }
1568
1569 if self.import_use_map.get(&import) == Some(&Used::Other)
1574 || self.effective_visibilities.is_exported(self.local_def_id(id))
1575 {
1576 return false;
1577 }
1578
1579 let mut is_redundant = true;
1580 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1581 self.per_ns(|this, ns| {
1582 let binding = decls[ns].get().decl().map(|b| b.import_source());
1583 if is_redundant && let Some(binding) = binding {
1584 if binding.res() == Res::Err {
1585 return;
1586 }
1587
1588 match this.cm().resolve_ident_in_scope_set(
1589 target,
1590 ScopeSet::All(ns),
1591 &import.parent_scope,
1592 None,
1593 decls[ns].get().decl(),
1594 None,
1595 ) {
1596 Ok(other_binding) => {
1597 is_redundant = binding.res() == other_binding.res()
1598 && !other_binding.is_ambiguity_recursive();
1599 if is_redundant {
1600 redundant_span[ns] =
1601 Some((other_binding.span, other_binding.is_import()));
1602 }
1603 }
1604 Err(_) => is_redundant = false,
1605 }
1606 }
1607 });
1608
1609 if is_redundant && !redundant_span.is_empty() {
1610 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1611 redundant_spans.sort();
1612 redundant_spans.dedup();
1613 self.lint_buffer.dyn_buffer_lint(
1614 REDUNDANT_IMPORTS,
1615 id,
1616 import.span,
1617 move |dcx, level| {
1618 let ident = source;
1619 let subs = redundant_spans
1620 .into_iter()
1621 .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1622 (false, true) => {
1623 errors::RedundantImportSub::ImportedHere { span, ident }
1624 }
1625 (false, false) => {
1626 errors::RedundantImportSub::DefinedHere { span, ident }
1627 }
1628 (true, true) => {
1629 errors::RedundantImportSub::ImportedPrelude { span, ident }
1630 }
1631 (true, false) => {
1632 errors::RedundantImportSub::DefinedPrelude { span, ident }
1633 }
1634 })
1635 .collect();
1636 errors::RedundantImport { subs, ident }.into_diag(dcx, level)
1637 },
1638 );
1639 return true;
1640 }
1641
1642 false
1643 }
1644
1645 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1646 let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1648
1649 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1650 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1651 return;
1652 };
1653
1654 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1655 feature_err(
1656 self.tcx.sess,
1657 sym::import_trait_associated_functions,
1658 import.span,
1659 "`use` associated items of traits is unstable",
1660 )
1661 .emit();
1662 }
1663
1664 if module == import.parent_scope.module {
1665 return;
1666 }
1667
1668 module.glob_importers.borrow_mut_unchecked().push(import);
1670
1671 let bindings = self
1674 .resolutions(module)
1675 .borrow()
1676 .iter()
1677 .filter_map(|(key, resolution)| {
1678 let resolution = resolution.borrow();
1679 resolution.binding().map(|binding| (*key, binding, resolution.orig_ident_span))
1680 })
1681 .collect::<Vec<_>>();
1682 for (mut key, binding, orig_ident_span) in bindings {
1683 let scope =
1684 match key.ident.ctxt.update_unchecked(|ctxt| {
1685 ctxt.reverse_glob_adjust(module.expansion, import.span)
1686 }) {
1687 Some(Some(def)) => self.expn_def_scope(def),
1688 Some(None) => import.parent_scope.module,
1689 None => continue,
1690 };
1691 if self.is_accessible_from(binding.vis(), scope) {
1692 let import_decl = self.new_import_decl(binding, import);
1693 let warn_ambiguity = self
1694 .resolution(import.parent_scope.module, key)
1695 .and_then(|r| r.binding())
1696 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1697 let _ = self.try_plant_decl_into_local_module(
1698 key.ident,
1699 orig_ident_span,
1700 key.ns,
1701 import_decl,
1702 warn_ambiguity,
1703 );
1704 }
1705 }
1706
1707 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1709 }
1710
1711 fn finalize_resolutions_in(
1714 &self,
1715 module: Module<'ra>,
1716 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1717 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1718 ) {
1719 *module.globs.borrow_mut(self) = Vec::new();
1721
1722 let Some(def_id) = module.opt_def_id() else { return };
1723
1724 let mut children = Vec::new();
1725 let mut ambig_children = Vec::new();
1726
1727 module.for_each_child(self, |this, ident, orig_ident_span, _, binding| {
1728 let res = binding.res().expect_non_local();
1729 if res != def::Res::Err {
1730 let ident = ident.orig(orig_ident_span);
1731 let child =
1732 |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1733 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1734 let main = child(ambig_binding1.reexport_chain(this));
1735 let second = ModChild {
1736 ident,
1737 res: ambig_binding2.res().expect_non_local(),
1738 vis: ambig_binding2.vis(),
1739 reexport_chain: ambig_binding2.reexport_chain(this),
1740 };
1741 ambig_children.push(AmbigModChild { main, second })
1742 } else {
1743 children.push(child(binding.reexport_chain(this)));
1744 }
1745 }
1746 });
1747
1748 if !children.is_empty() {
1749 module_children.insert(def_id.expect_local(), children);
1750 }
1751 if !ambig_children.is_empty() {
1752 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1753 }
1754 }
1755}
1756
1757fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1758 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1759 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1760 if let Some(pos) = pos {
1761 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1762 names_to_string(names.iter().map(|ident| ident.name))
1763 } else {
1764 let names = if global { &names[1..] } else { names };
1765 if names.is_empty() {
1766 import_kind_to_string(import_kind)
1767 } else {
1768 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}",
names_to_string(names.iter().map(|ident| ident.name)),
import_kind_to_string(import_kind)))
})format!(
1769 "{}::{}",
1770 names_to_string(names.iter().map(|ident| ident.name)),
1771 import_kind_to_string(import_kind),
1772 )
1773 }
1774 }
1775}
1776
1777fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1778 match import_kind {
1779 ImportKind::Single { source, .. } => source.to_string(),
1780 ImportKind::Glob { .. } => "*".to_string(),
1781 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1782 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1783 ImportKind::MacroExport => "#[macro_export]".to_string(),
1784 }
1785}