1use std::mem;
4
5use rustc_ast::NodeId;
6use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
7use rustc_data_structures::intern::Interned;
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
10use rustc_hir::def::{self, DefKind, PartialRes};
11use rustc_hir::def_id::{DefId, LocalDefIdMap};
12use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
13use rustc_middle::span_bug;
14use rustc_middle::ty::Visibility;
15use rustc_session::lint::BuiltinLintDiag;
16use rustc_session::lint::builtin::{
17 AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
18 PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
19};
20use rustc_session::parse::feature_err;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::hygiene::LocalExpnId;
23use rustc_span::{Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
24use tracing::debug;
25
26use crate::Namespace::{self, *};
27use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
28use crate::errors::{
29 CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
30 CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
31 ConsiderAddingMacroExport, ConsiderMarkingAsPub, ConsiderMarkingAsPubCrate,
32};
33use crate::ref_mut::CmCell;
34use crate::{
35 AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
36 ImportSuggestion, Module, ModuleOrUniformRoot, ParentScope, PathResult, PerNS, ResolutionError,
37 Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
38};
39
40type Res = def::Res<NodeId>;
41
42#[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)]
45pub(crate) enum PendingDecl<'ra> {
46 Ready(Option<Decl<'ra>>),
47 #[default]
48 Pending,
49}
50
51impl<'ra> PendingDecl<'ra> {
52 pub(crate) fn decl(self) -> Option<Decl<'ra>> {
53 match self {
54 PendingDecl::Ready(decl) => decl,
55 PendingDecl::Pending => None,
56 }
57 }
58}
59
60#[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)]
62pub(crate) enum ImportKind<'ra> {
63 Single {
64 source: Ident,
66 target: Ident,
69 decls: PerNS<CmCell<PendingDecl<'ra>>>,
71 type_ns_only: bool,
73 nested: bool,
75 id: NodeId,
87 },
88 Glob {
89 max_vis: CmCell<Option<Visibility>>,
92 id: NodeId,
93 },
94 ExternCrate {
95 source: Option<Symbol>,
96 target: Ident,
97 id: NodeId,
98 },
99 MacroUse {
100 warn_private: bool,
103 },
104 MacroExport,
105}
106
107impl<'ra> std::fmt::Debug for ImportKind<'ra> {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 use ImportKind::*;
112 match self {
113 Single { source, target, decls, type_ns_only, nested, id, .. } => f
114 .debug_struct("Single")
115 .field("source", source)
116 .field("target", target)
117 .field(
119 "decls",
120 &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!("..")format_args!(".."))),
121 )
122 .field("type_ns_only", type_ns_only)
123 .field("nested", nested)
124 .field("id", id)
125 .finish(),
126 Glob { max_vis, id } => {
127 f.debug_struct("Glob").field("max_vis", max_vis).field("id", id).finish()
128 }
129 ExternCrate { source, target, id } => f
130 .debug_struct("ExternCrate")
131 .field("source", source)
132 .field("target", target)
133 .field("id", id)
134 .finish(),
135 MacroUse { warn_private } => {
136 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
137 }
138 MacroExport => f.debug_struct("MacroExport").finish(),
139 }
140 }
141}
142
143#[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"];
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];
::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),
}
}
}Clone)]
145pub(crate) struct ImportData<'ra> {
146 pub kind: ImportKind<'ra>,
147
148 pub root_id: NodeId,
158
159 pub use_span: Span,
161
162 pub use_span_with_attributes: Span,
164
165 pub has_attributes: bool,
167
168 pub span: Span,
170
171 pub root_span: Span,
173
174 pub parent_scope: ParentScope<'ra>,
175 pub module_path: Vec<Segment>,
176 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
185 pub vis: Visibility,
186
187 pub vis_span: Span,
189}
190
191pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
194
195impl std::hash::Hash for ImportData<'_> {
200 fn hash<H>(&self, _: &mut H)
201 where
202 H: std::hash::Hasher,
203 {
204 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
205 }
206}
207
208impl<'ra> ImportData<'ra> {
209 pub(crate) fn is_glob(&self) -> bool {
210 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Glob { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Glob { .. })
211 }
212
213 pub(crate) fn is_nested(&self) -> bool {
214 match self.kind {
215 ImportKind::Single { nested, .. } => nested,
216 _ => false,
217 }
218 }
219
220 pub(crate) fn id(&self) -> Option<NodeId> {
221 match self.kind {
222 ImportKind::Single { id, .. }
223 | ImportKind::Glob { id, .. }
224 | ImportKind::ExternCrate { id, .. } => Some(id),
225 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
226 }
227 }
228
229 pub(crate) fn simplify(&self, r: &Resolver<'_, '_>) -> Reexport {
230 let to_def_id = |id| r.local_def_id(id).to_def_id();
231 match self.kind {
232 ImportKind::Single { id, .. } => Reexport::Single(to_def_id(id)),
233 ImportKind::Glob { id, .. } => Reexport::Glob(to_def_id(id)),
234 ImportKind::ExternCrate { id, .. } => Reexport::ExternCrate(to_def_id(id)),
235 ImportKind::MacroUse { .. } => Reexport::MacroUse,
236 ImportKind::MacroExport => Reexport::MacroExport,
237 }
238 }
239}
240
241#[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),
}
}
}Clone, #[automatically_derived]
impl<'ra> ::core::default::Default for NameResolution<'ra> {
#[inline]
fn default() -> NameResolution<'ra> {
NameResolution {
single_imports: ::core::default::Default::default(),
non_glob_decl: ::core::default::Default::default(),
glob_decl: ::core::default::Default::default(),
}
}
}Default, #[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_field3_finish(f,
"NameResolution", "single_imports", &self.single_imports,
"non_glob_decl", &self.non_glob_decl, "glob_decl",
&&self.glob_decl)
}
}Debug)]
243pub(crate) struct NameResolution<'ra> {
244 pub single_imports: FxIndexSet<Import<'ra>>,
247 pub non_glob_decl: Option<Decl<'ra>>,
249 pub glob_decl: Option<Decl<'ra>>,
251}
252
253impl<'ra> NameResolution<'ra> {
254 pub(crate) fn binding(&self) -> Option<Decl<'ra>> {
256 self.best_decl().and_then(|binding| {
257 if !binding.is_glob_import() || self.single_imports.is_empty() {
258 Some(binding)
259 } else {
260 None
261 }
262 })
263 }
264
265 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
266 self.non_glob_decl.or(self.glob_decl)
267 }
268}
269
270#[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"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.span, &self.label, &self.note, &self.suggestion,
&self.candidates, &self.segment, &&self.module];
::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),
}
}
}Clone)]
273struct UnresolvedImportError {
274 span: Span,
275 label: Option<String>,
276 note: Option<String>,
277 suggestion: Option<Suggestion>,
278 candidates: Option<Vec<ImportSuggestion>>,
279 segment: Option<Symbol>,
280 module: Option<DefId>,
282}
283
284fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
287 match (&import.kind, &decl.kind) {
288 (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
289 if let ImportKind::ExternCrate { id, .. } = decl_import.kind
290 && import.vis.is_public() =>
291 {
292 Some(id)
293 }
294 _ => None,
295 }
296}
297
298fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
300 if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
301 && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
302 && import1 == import2
303 {
304 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);
305 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);
306 if d1.ambiguity.get() != d2.ambiguity.get() {
307 if !d1.ambiguity.get().is_some() {
::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
308 if !d2.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: d2.ambiguity.get().is_none()")
};assert!(d2.ambiguity.get().is_none());
309 }
310 remove_same_import(d1_next, d2_next)
314 } else {
315 (d1, d2)
316 }
317}
318
319impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
320 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
323 let import_vis = import.vis.to_def_id();
324 let vis = if decl.vis().is_at_least(import_vis, self.tcx)
325 || pub_use_of_private_extern_crate_hack(import, decl).is_some()
326 {
327 import_vis
328 } else {
329 decl.vis()
330 };
331
332 if let ImportKind::Glob { ref max_vis, .. } = import.kind
333 && (vis == import_vis
334 || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
335 {
336 max_vis.set_unchecked(Some(vis.expect_local()))
337 }
338
339 self.arenas.alloc_decl(DeclData {
340 kind: DeclKind::Import { source_decl: decl, import },
341 ambiguity: CmCell::new(None),
342 warn_ambiguity: CmCell::new(false),
343 span: import.span,
344 vis: CmCell::new(vis),
345 expansion: import.parent_scope.expansion,
346 parent_module: Some(import.parent_scope.module),
347 })
348 }
349
350 fn select_glob_decl(
353 &self,
354 old_glob_decl: Decl<'ra>,
355 glob_decl: Decl<'ra>,
356 warn_ambiguity: bool,
357 ) -> Decl<'ra> {
358 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
359 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());
360 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);
361 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
376 if deep_decl != glob_decl {
377 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);
379 if !!deep_decl.is_glob_import() {
::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
383 if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
384 glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
386 }
387 if glob_decl.is_ambiguity_recursive() {
388 glob_decl.warn_ambiguity.set_unchecked(true);
389 }
390 glob_decl
391 } else if glob_decl.res() != old_glob_decl.res() {
392 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
393 old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
394 if warn_ambiguity {
395 old_glob_decl
396 } else {
397 self.arenas.alloc_decl((*old_glob_decl).clone())
401 }
402 } else if !old_glob_decl.vis().is_at_least(glob_decl.vis(), self.tcx) {
403 glob_decl
407 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
408 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
410 old_glob_decl.warn_ambiguity.set_unchecked(true);
411 old_glob_decl
412 } else {
413 old_glob_decl
414 }
415 }
416
417 pub(crate) fn try_plant_decl_into_local_module(
420 &mut self,
421 ident: Macros20NormalizedIdent,
422 ns: Namespace,
423 decl: Decl<'ra>,
424 warn_ambiguity: bool,
425 ) -> Result<(), Decl<'ra>> {
426 let module = decl.parent_module.unwrap();
427 let res = decl.res();
428 self.check_reserved_macro_name(ident.0, res);
429 let key = BindingKey::new_disambiguated(ident, ns, || {
433 module.underscore_disambiguator.update_unchecked(|d| d + 1);
434 module.underscore_disambiguator.get()
435 });
436 self.update_local_resolution(module, key, warn_ambiguity, |this, resolution| {
437 if let Some(old_decl) = resolution.best_decl() {
438 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);
439 if !!decl.warn_ambiguity.get() {
::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
440 if res == Res::Err && old_decl.res() != Res::Err {
441 return Ok(());
443 }
444 match (old_decl.is_glob_import(), decl.is_glob_import()) {
445 (true, true) => {
446 resolution.glob_decl =
447 Some(this.select_glob_decl(old_decl, decl, warn_ambiguity));
448 }
449 (old_glob @ true, false) | (old_glob @ false, true) => {
450 let (glob_decl, non_glob_decl) =
451 if old_glob { (old_decl, decl) } else { (decl, old_decl) };
452 resolution.non_glob_decl = Some(non_glob_decl);
453 if let Some(old_glob_decl) = resolution.glob_decl
454 && old_glob_decl != glob_decl
455 {
456 resolution.glob_decl =
457 Some(this.select_glob_decl(old_glob_decl, glob_decl, false));
458 } else {
459 resolution.glob_decl = Some(glob_decl);
460 }
461 }
462 (false, false) => {
463 return Err(old_decl);
464 }
465 }
466 } else {
467 if decl.is_glob_import() {
468 resolution.glob_decl = Some(decl);
469 } else {
470 resolution.non_glob_decl = Some(decl);
471 }
472 }
473
474 Ok(())
475 })
476 }
477
478 fn update_local_resolution<T, F>(
481 &mut self,
482 module: Module<'ra>,
483 key: BindingKey,
484 warn_ambiguity: bool,
485 f: F,
486 ) -> T
487 where
488 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
489 {
490 let (binding, t, warn_ambiguity) = {
493 let resolution = &mut *self.resolution_or_default(module, key).borrow_mut_unchecked();
494 let old_decl = resolution.binding();
495
496 let t = f(self, resolution);
497
498 if let Some(binding) = resolution.binding()
499 && old_decl != Some(binding)
500 {
501 (binding, t, warn_ambiguity || old_decl.is_some())
502 } else {
503 return t;
504 }
505 };
506
507 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
508 return t;
509 };
510
511 for import in glob_importers.iter() {
513 let mut ident = key.ident;
514 let scope = match ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
515 Some(Some(def)) => self.expn_def_scope(def),
516 Some(None) => import.parent_scope.module,
517 None => continue,
518 };
519 if self.is_accessible_from(binding.vis(), scope) {
520 let import_decl = self.new_import_decl(binding, *import);
521 let _ = self.try_plant_decl_into_local_module(
522 ident,
523 key.ns,
524 import_decl,
525 warn_ambiguity,
526 );
527 }
528 }
529
530 t
531 }
532
533 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
536 if let ImportKind::Single { target, ref decls, .. } = import.kind {
537 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
538 return; }
540 let dummy_decl = self.dummy_decl;
541 let dummy_decl = self.new_import_decl(dummy_decl, import);
542 self.per_ns(|this, ns| {
543 let module = import.parent_scope.module;
544 let ident = Macros20NormalizedIdent::new(target);
545 let _ = this.try_plant_decl_into_local_module(ident, ns, dummy_decl, false);
546 if target.name != kw::Underscore {
548 let key = BindingKey::new(ident, ns);
549 this.update_local_resolution(module, key, false, |_, resolution| {
550 resolution.single_imports.swap_remove(&import);
551 })
552 }
553 });
554 self.record_use(target, dummy_decl, Used::Other);
555 } else if import.imported_module.get().is_none() {
556 self.import_use_map.insert(import, Used::Other);
557 if let Some(id) = import.id() {
558 self.used_imports.insert(id);
559 }
560 }
561 }
562
563 pub(crate) fn resolve_imports(&mut self) {
574 let mut prev_indeterminate_count = usize::MAX;
575 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
576 while indeterminate_count < prev_indeterminate_count {
577 prev_indeterminate_count = indeterminate_count;
578 indeterminate_count = 0;
579 self.assert_speculative = true;
580 for import in mem::take(&mut self.indeterminate_imports) {
581 let import_indeterminate_count = self.cm().resolve_import(import);
582 indeterminate_count += import_indeterminate_count;
583 match import_indeterminate_count {
584 0 => self.determined_imports.push(import),
585 _ => self.indeterminate_imports.push(import),
586 }
587 }
588 self.assert_speculative = false;
589 }
590 }
591
592 pub(crate) fn finalize_imports(&mut self) {
593 let mut module_children = Default::default();
594 let mut ambig_module_children = Default::default();
595 for module in &self.local_modules {
596 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
597 }
598 self.module_children = module_children;
599 self.ambig_module_children = ambig_module_children;
600
601 let mut seen_spans = FxHashSet::default();
602 let mut errors = ::alloc::vec::Vec::new()vec![];
603 let mut prev_root_id: NodeId = NodeId::ZERO;
604 let determined_imports = mem::take(&mut self.determined_imports);
605 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
606
607 let mut glob_error = false;
608 for (is_indeterminate, import) in determined_imports
609 .iter()
610 .map(|i| (false, i))
611 .chain(indeterminate_imports.iter().map(|i| (true, i)))
612 {
613 let unresolved_import_error = self.finalize_import(*import);
614 self.import_dummy_binding(*import, is_indeterminate);
617
618 let Some(err) = unresolved_import_error else { continue };
619
620 glob_error |= import.is_glob();
621
622 if let ImportKind::Single { source, ref decls, .. } = import.kind
623 && source.name == kw::SelfLower
624 && let PendingDecl::Ready(None) = decls.value_ns.get()
626 {
627 continue;
628 }
629
630 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
631 {
632 self.throw_unresolved_import_error(errors, glob_error);
635 errors = ::alloc::vec::Vec::new()vec![];
636 }
637 if seen_spans.insert(err.span) {
638 errors.push((*import, err));
639 prev_root_id = import.root_id;
640 }
641 }
642
643 if !errors.is_empty() {
644 self.throw_unresolved_import_error(errors, glob_error);
645 return;
646 }
647
648 for import in &indeterminate_imports {
649 let path = import_path_to_string(
650 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
651 &import.kind,
652 import.span,
653 );
654 if path.contains("::") {
657 let err = UnresolvedImportError {
658 span: import.span,
659 label: None,
660 note: None,
661 suggestion: None,
662 candidates: None,
663 segment: None,
664 module: None,
665 };
666 errors.push((*import, err))
667 }
668 }
669
670 if !errors.is_empty() {
671 self.throw_unresolved_import_error(errors, glob_error);
672 }
673 }
674
675 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
676 for module in &self.local_modules {
677 for (key, resolution) in self.resolutions(*module).borrow().iter() {
678 let resolution = resolution.borrow();
679 let Some(binding) = resolution.best_decl() else { continue };
680
681 if let DeclKind::Import { import, .. } = binding.kind
682 && let Some(amb_binding) = binding.ambiguity.get()
683 && binding.res() != Res::Err
684 && exported_ambiguities.contains(&binding)
685 {
686 self.lint_buffer.buffer_lint(
687 AMBIGUOUS_GLOB_REEXPORTS,
688 import.root_id,
689 import.root_span,
690 BuiltinLintDiag::AmbiguousGlobReexports {
691 name: key.ident.to_string(),
692 namespace: key.ns.descr().to_string(),
693 first_reexport_span: import.root_span,
694 duplicate_reexport_span: amb_binding.span,
695 },
696 );
697 }
698
699 if let Some(glob_decl) = resolution.glob_decl
700 && resolution.non_glob_decl.is_some()
701 {
702 if binding.res() != Res::Err
703 && glob_decl.res() != Res::Err
704 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
705 && let Some(glob_import_id) = glob_import.id()
706 && let glob_import_def_id = self.local_def_id(glob_import_id)
707 && self.effective_visibilities.is_exported(glob_import_def_id)
708 && glob_decl.vis().is_public()
709 && !binding.vis().is_public()
710 {
711 let binding_id = match binding.kind {
712 DeclKind::Def(res) => {
713 Some(self.def_id_to_node_id(res.def_id().expect_local()))
714 }
715 DeclKind::Import { import, .. } => import.id(),
716 };
717 if let Some(binding_id) = binding_id {
718 self.lint_buffer.buffer_lint(
719 HIDDEN_GLOB_REEXPORTS,
720 binding_id,
721 binding.span,
722 BuiltinLintDiag::HiddenGlobReexports {
723 name: key.ident.name.to_string(),
724 namespace: key.ns.descr().to_owned(),
725 glob_reexport_span: glob_decl.span,
726 private_item_span: binding.span,
727 },
728 );
729 }
730 }
731 }
732
733 if let DeclKind::Import { import, .. } = binding.kind
734 && let Some(binding_id) = import.id()
735 && let import_def_id = self.local_def_id(binding_id)
736 && self.effective_visibilities.is_exported(import_def_id)
737 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
738 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
739 && !reexported_def_id.is_local()
740 && self.tcx.is_private_dep(reexported_def_id.krate)
741 {
742 self.lint_buffer.buffer_lint(
743 EXPORTED_PRIVATE_DEPENDENCIES,
744 binding_id,
745 binding.span,
746 crate::errors::ReexportPrivateDependency {
747 name: key.ident.name,
748 kind: binding.res().descr(),
749 krate: self.tcx.crate_name(reexported_def_id.krate),
750 },
751 );
752 }
753 }
754 }
755 }
756
757 fn throw_unresolved_import_error(
758 &mut self,
759 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
760 glob_error: bool,
761 ) {
762 errors.retain(|(_import, err)| match err.module {
763 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
765 _ => err.segment != Some(kw::Underscore),
768 });
769 if errors.is_empty() {
770 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
771 return;
772 }
773
774 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
775
776 let paths = errors
777 .iter()
778 .map(|(import, err)| {
779 let path = import_path_to_string(
780 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
781 &import.kind,
782 err.span,
783 );
784 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
785 })
786 .collect::<Vec<_>>();
787 let msg = ::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(", "),);
788
789 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", msg))
})).with_code(E0432)
}struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
790
791 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
792 diag.note(note.clone());
793 }
794
795 const MAX_LABEL_COUNT: usize = 10;
797
798 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
799 if let Some(label) = err.label {
800 diag.span_label(err.span, label);
801 }
802
803 if let Some((suggestions, msg, applicability)) = err.suggestion {
804 if suggestions.is_empty() {
805 diag.help(msg);
806 continue;
807 }
808 diag.multipart_suggestion(msg, suggestions, applicability);
809 }
810
811 if let Some(candidates) = &err.candidates {
812 match &import.kind {
813 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
814 self.tcx,
815 &mut diag,
816 Some(err.span),
817 candidates,
818 DiagMode::Import { append: false, unresolved_import: true },
819 (source != target)
820 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
821 .as_deref()
822 .unwrap_or(""),
823 ),
824 ImportKind::Single { nested: true, source, target, .. } => {
825 import_candidates(
826 self.tcx,
827 &mut diag,
828 None,
829 candidates,
830 DiagMode::Normal,
831 (source != target)
832 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
833 .as_deref()
834 .unwrap_or(""),
835 );
836 }
837 _ => {}
838 }
839 }
840
841 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
842 && let Some(segment) = err.segment
843 && let Some(module) = err.module
844 {
845 self.find_cfg_stripped(&mut diag, &segment, module)
846 }
847 }
848
849 let guar = diag.emit();
850 if glob_error {
851 self.glob_error = Some(guar);
852 }
853 }
854
855 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
862 {
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:862",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(862u32),
::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!(
863 "(resolving import for module) resolving import `{}::...` in `{}`",
864 Segment::names_to_string(&import.module_path),
865 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
866 );
867 let module = if let Some(module) = import.imported_module.get() {
868 module
869 } else {
870 let path_res = self.reborrow().maybe_resolve_path(
871 &import.module_path,
872 None,
873 &import.parent_scope,
874 Some(import),
875 );
876
877 match path_res {
878 PathResult::Module(module) => module,
879 PathResult::Indeterminate => return 3,
880 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
881 }
882 };
883
884 import.imported_module.set_unchecked(Some(module));
885 let (source, target, bindings, type_ns_only) = match import.kind {
886 ImportKind::Single { source, target, ref decls, type_ns_only, .. } => {
887 (source, target, decls, type_ns_only)
888 }
889 ImportKind::Glob { .. } => {
890 self.get_mut_unchecked().resolve_glob_import(import);
891 return 0;
892 }
893 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
894 };
895
896 let mut indeterminate_count = 0;
897 self.per_ns_cm(|this, ns| {
898 if !type_ns_only || ns == TypeNS {
899 if bindings[ns].get() != PendingDecl::Pending {
900 return;
901 };
902 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
903 module,
904 source,
905 ns,
906 &import.parent_scope,
907 Some(import),
908 );
909 let parent = import.parent_scope.module;
910 let binding = match binding_result {
911 Ok(binding) => {
912 if binding.is_assoc_item()
913 && !this.tcx.features().import_trait_associated_functions()
914 {
915 feature_err(
916 this.tcx.sess,
917 sym::import_trait_associated_functions,
918 import.span,
919 "`use` associated items of traits is unstable",
920 )
921 .emit();
922 }
923 let import_decl = this.new_import_decl(binding, import);
925 this.get_mut_unchecked().plant_decl_into_local_module(
926 Macros20NormalizedIdent::new(target),
927 ns,
928 import_decl,
929 );
930 PendingDecl::Ready(Some(import_decl))
931 }
932 Err(Determinacy::Determined) => {
933 if target.name != kw::Underscore {
935 let key = BindingKey::new(Macros20NormalizedIdent::new(target), ns);
936 this.get_mut_unchecked().update_local_resolution(
937 parent,
938 key,
939 false,
940 |_, resolution| {
941 resolution.single_imports.swap_remove(&import);
942 },
943 );
944 }
945 PendingDecl::Ready(None)
946 }
947 Err(Determinacy::Undetermined) => {
948 indeterminate_count += 1;
949 PendingDecl::Pending
950 }
951 };
952 bindings[ns].set_unchecked(binding);
953 }
954 });
955
956 indeterminate_count
957 }
958
959 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
964 let ignore_decl = match &import.kind {
965 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
966 _ => None,
967 };
968 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
969 errors.iter().filter(|error| error.warning.is_none()).count()
970 };
971 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
972 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
973
974 let privacy_errors_len = self.privacy_errors.len();
976
977 let path_res = self.cm().resolve_path(
978 &import.module_path,
979 None,
980 &import.parent_scope,
981 Some(finalize),
982 ignore_decl,
983 Some(import),
984 );
985
986 let no_ambiguity =
987 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
988
989 let module = match path_res {
990 PathResult::Module(module) => {
991 if let Some(initial_module) = import.imported_module.get() {
993 if module != initial_module && no_ambiguity {
994 ::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");
995 }
996 } else if self.privacy_errors.is_empty() {
997 self.dcx()
998 .create_err(CannotDetermineImportResolution { span: import.span })
999 .emit();
1000 }
1001
1002 module
1003 }
1004 PathResult::Failed {
1005 is_error_from_last_segment: false,
1006 span,
1007 segment_name,
1008 label,
1009 suggestion,
1010 module,
1011 error_implied_by_parse_error: _,
1012 } => {
1013 if no_ambiguity {
1014 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());
1015 self.report_error(
1016 span,
1017 ResolutionError::FailedToResolve {
1018 segment: Some(segment_name),
1019 label,
1020 suggestion,
1021 module,
1022 },
1023 );
1024 }
1025 return None;
1026 }
1027 PathResult::Failed {
1028 is_error_from_last_segment: true,
1029 span,
1030 label,
1031 suggestion,
1032 module,
1033 segment_name,
1034 ..
1035 } => {
1036 if no_ambiguity {
1037 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());
1038 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1039 m.opt_def_id()
1040 } else {
1041 None
1042 };
1043 let err = match self
1044 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1045 {
1046 Some((suggestion, note)) => UnresolvedImportError {
1047 span,
1048 label: None,
1049 note,
1050 suggestion: Some((
1051 <[_]>::into_vec(::alloc::boxed::box_new([(span,
Segment::names_to_string(&suggestion))]))vec![(span, Segment::names_to_string(&suggestion))],
1052 String::from("a similar path exists"),
1053 Applicability::MaybeIncorrect,
1054 )),
1055 candidates: None,
1056 segment: Some(segment_name),
1057 module,
1058 },
1059 None => UnresolvedImportError {
1060 span,
1061 label: Some(label),
1062 note: None,
1063 suggestion,
1064 candidates: None,
1065 segment: Some(segment_name),
1066 module,
1067 },
1068 };
1069 return Some(err);
1070 }
1071 return None;
1072 }
1073 PathResult::NonModule(partial_res) => {
1074 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1075 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());
1077 }
1078 return None;
1080 }
1081 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1082 };
1083
1084 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1085 ImportKind::Single { source, target, ref decls, type_ns_only, id, .. } => {
1086 (source, target, decls, type_ns_only, id)
1087 }
1088 ImportKind::Glob { ref max_vis, id } => {
1089 if import.module_path.len() <= 1 {
1090 let mut full_path = import.module_path.clone();
1093 full_path.push(Segment::from_ident(Ident::dummy()));
1094 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1095 }
1096
1097 if let ModuleOrUniformRoot::Module(module) = module
1098 && module == import.parent_scope.module
1099 {
1100 return Some(UnresolvedImportError {
1102 span: import.span,
1103 label: Some(String::from("cannot glob-import a module into itself")),
1104 note: None,
1105 suggestion: None,
1106 candidates: None,
1107 segment: None,
1108 module: None,
1109 });
1110 }
1111 if let Some(max_vis) = max_vis.get()
1112 && !max_vis.is_at_least(import.vis, self.tcx)
1113 {
1114 let def_id = self.local_def_id(id);
1115 self.lint_buffer.buffer_lint(
1116 UNUSED_IMPORTS,
1117 id,
1118 import.span,
1119 crate::errors::RedundantImportVisibility {
1120 span: import.span,
1121 help: (),
1122 max_vis: max_vis.to_string(def_id, self.tcx),
1123 import_vis: import.vis.to_string(def_id, self.tcx),
1124 },
1125 );
1126 }
1127 return None;
1128 }
1129 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1130 };
1131
1132 if self.privacy_errors.len() != privacy_errors_len {
1133 let mut path = import.module_path.clone();
1136 path.push(Segment::from_ident(ident));
1137 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1138 &path,
1139 None,
1140 &import.parent_scope,
1141 Some(finalize),
1142 ignore_decl,
1143 None,
1144 ) {
1145 let res = module.res().map(|r| (r, ident));
1146 for error in &mut self.privacy_errors[privacy_errors_len..] {
1147 error.outermost_res = res;
1148 }
1149 }
1150 }
1151
1152 let mut all_ns_err = true;
1153 self.per_ns(|this, ns| {
1154 if !type_ns_only || ns == TypeNS {
1155 let binding = this.cm().resolve_ident_in_module(
1156 module,
1157 ident,
1158 ns,
1159 &import.parent_scope,
1160 Some(Finalize { report_private: false, ..finalize }),
1161 bindings[ns].get().decl(),
1162 Some(import),
1163 );
1164
1165 match binding {
1166 Ok(binding) => {
1167 let initial_res = bindings[ns].get().decl().map(|binding| {
1169 let initial_binding = binding.import_source();
1170 all_ns_err = false;
1171 if target.name == kw::Underscore
1172 && initial_binding.is_extern_crate()
1173 && !initial_binding.is_import()
1174 {
1175 let used = if import.module_path.is_empty() {
1176 Used::Scope
1177 } else {
1178 Used::Other
1179 };
1180 this.record_use(ident, binding, used);
1181 }
1182 initial_binding.res()
1183 });
1184 let res = binding.res();
1185 let has_ambiguity_error =
1186 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1187 if res == Res::Err || has_ambiguity_error {
1188 this.dcx()
1189 .span_delayed_bug(import.span, "some error happened for an import");
1190 return;
1191 }
1192 if let Some(initial_res) = initial_res {
1193 if res != initial_res && !this.issue_145575_hack_applied {
1194 ::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");
1195 }
1196 } else if this.privacy_errors.is_empty() {
1197 this.dcx()
1198 .create_err(CannotDetermineImportResolution { span: import.span })
1199 .emit();
1200 }
1201 }
1202 Err(..) => {
1203 }
1210 }
1211 }
1212 });
1213
1214 if all_ns_err {
1215 let mut all_ns_failed = true;
1216 self.per_ns(|this, ns| {
1217 if !type_ns_only || ns == TypeNS {
1218 let binding = this.cm().resolve_ident_in_module(
1219 module,
1220 ident,
1221 ns,
1222 &import.parent_scope,
1223 Some(finalize),
1224 None,
1225 None,
1226 );
1227 if binding.is_ok() {
1228 all_ns_failed = false;
1229 }
1230 }
1231 });
1232
1233 return if all_ns_failed {
1234 let names = match module {
1235 ModuleOrUniformRoot::Module(module) => {
1236 self.resolutions(module)
1237 .borrow()
1238 .iter()
1239 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1240 if i.name == ident.name {
1241 return None;
1242 } let resolution = resolution.borrow();
1245 if let Some(name_binding) = resolution.best_decl() {
1246 match name_binding.kind {
1247 DeclKind::Import { source_decl, .. } => {
1248 match source_decl.kind {
1249 DeclKind::Def(Res::Err) => None,
1252 _ => Some(i.name),
1253 }
1254 }
1255 _ => Some(i.name),
1256 }
1257 } else if resolution.single_imports.is_empty() {
1258 None
1259 } else {
1260 Some(i.name)
1261 }
1262 })
1263 .collect()
1264 }
1265 _ => Vec::new(),
1266 };
1267
1268 let lev_suggestion =
1269 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1270 (
1271 <[_]>::into_vec(::alloc::boxed::box_new([(ident.span,
suggestion.to_string())]))vec![(ident.span, suggestion.to_string())],
1272 String::from("a similar name exists in the module"),
1273 Applicability::MaybeIncorrect,
1274 )
1275 });
1276
1277 let (suggestion, note) =
1278 match self.check_for_module_export_macro(import, module, ident) {
1279 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1280 _ => (lev_suggestion, None),
1281 };
1282
1283 let label = match module {
1284 ModuleOrUniformRoot::Module(module) => {
1285 let module_str = module_to_string(module);
1286 if let Some(module_str) = module_str {
1287 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1288 } else {
1289 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1290 }
1291 }
1292 _ => {
1293 if !ident.is_path_segment_keyword() {
1294 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1295 } else {
1296 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1299 }
1300 }
1301 };
1302
1303 let parent_suggestion =
1304 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1305
1306 Some(UnresolvedImportError {
1307 span: import.span,
1308 label: Some(label),
1309 note,
1310 suggestion,
1311 candidates: if !parent_suggestion.is_empty() {
1312 Some(parent_suggestion)
1313 } else {
1314 None
1315 },
1316 module: import.imported_module.get().and_then(|module| {
1317 if let ModuleOrUniformRoot::Module(m) = module {
1318 m.opt_def_id()
1319 } else {
1320 None
1321 }
1322 }),
1323 segment: Some(ident.name),
1324 })
1325 } else {
1326 None
1328 };
1329 }
1330
1331 let mut reexport_error = None;
1332 let mut any_successful_reexport = false;
1333 let mut crate_private_reexport = false;
1334 self.per_ns(|this, ns| {
1335 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1336 return;
1337 };
1338
1339 if !binding.vis().is_at_least(import.vis, this.tcx) {
1340 reexport_error = Some((ns, binding));
1341 if let Visibility::Restricted(binding_def_id) = binding.vis()
1342 && binding_def_id.is_top_level_module()
1343 {
1344 crate_private_reexport = true;
1345 }
1346 } else {
1347 any_successful_reexport = true;
1348 }
1349 });
1350
1351 if !any_successful_reexport {
1353 let (ns, binding) = reexport_error.unwrap();
1354 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1355 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1356 self.lint_buffer.buffer_lint(
1357 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1358 import_id,
1359 import.span,
1360 crate::errors::PrivateExternCrateReexport {
1361 ident,
1362 sugg: extern_crate_sp.shrink_to_lo(),
1363 },
1364 );
1365 } else if ns == TypeNS {
1366 let err = if crate_private_reexport {
1367 self.dcx()
1368 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1369 } else {
1370 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1371 };
1372 err.emit();
1373 } else {
1374 let mut err = if crate_private_reexport {
1375 self.dcx()
1376 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1377 } else {
1378 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1379 };
1380
1381 match binding.kind {
1382 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1383 if self.get_macro_by_def_id(def_id).macro_rules =>
1385 {
1386 err.subdiagnostic( ConsiderAddingMacroExport {
1387 span: binding.span,
1388 });
1389 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1390 vis_span: import.vis_span,
1391 });
1392 }
1393 _ => {
1394 err.subdiagnostic( ConsiderMarkingAsPub {
1395 span: import.span,
1396 ident,
1397 });
1398 }
1399 }
1400 err.emit();
1401 }
1402 }
1403
1404 if import.module_path.len() <= 1 {
1405 let mut full_path = import.module_path.clone();
1408 full_path.push(Segment::from_ident(ident));
1409 self.per_ns(|this, ns| {
1410 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1411 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1412 }
1413 });
1414 }
1415
1416 self.per_ns(|this, ns| {
1420 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1421 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1422 }
1423 });
1424
1425 {
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:1425",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1425u32),
::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");
1426 None
1427 }
1428
1429 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1430 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1432 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1433 };
1434
1435 if source != target {
1437 return false;
1438 }
1439
1440 if import.parent_scope.expansion != LocalExpnId::ROOT {
1442 return false;
1443 }
1444
1445 if self.import_use_map.get(&import) == Some(&Used::Other)
1450 || self.effective_visibilities.is_exported(self.local_def_id(id))
1451 {
1452 return false;
1453 }
1454
1455 let mut is_redundant = true;
1456 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1457 self.per_ns(|this, ns| {
1458 let binding = decls[ns].get().decl().map(|b| b.import_source());
1459 if is_redundant && let Some(binding) = binding {
1460 if binding.res() == Res::Err {
1461 return;
1462 }
1463
1464 match this.cm().resolve_ident_in_scope_set(
1465 target,
1466 ScopeSet::All(ns),
1467 &import.parent_scope,
1468 None,
1469 false,
1470 decls[ns].get().decl(),
1471 None,
1472 ) {
1473 Ok(other_binding) => {
1474 is_redundant = binding.res() == other_binding.res()
1475 && !other_binding.is_ambiguity_recursive();
1476 if is_redundant {
1477 redundant_span[ns] =
1478 Some((other_binding.span, other_binding.is_import()));
1479 }
1480 }
1481 Err(_) => is_redundant = false,
1482 }
1483 }
1484 });
1485
1486 if is_redundant && !redundant_span.is_empty() {
1487 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1488 redundant_spans.sort();
1489 redundant_spans.dedup();
1490 self.lint_buffer.buffer_lint(
1491 REDUNDANT_IMPORTS,
1492 id,
1493 import.span,
1494 BuiltinLintDiag::RedundantImport(redundant_spans, source),
1495 );
1496 return true;
1497 }
1498
1499 false
1500 }
1501
1502 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1503 let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1505
1506 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1507 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1508 return;
1509 };
1510
1511 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1512 feature_err(
1513 self.tcx.sess,
1514 sym::import_trait_associated_functions,
1515 import.span,
1516 "`use` associated items of traits is unstable",
1517 )
1518 .emit();
1519 }
1520
1521 if module == import.parent_scope.module {
1522 return;
1523 }
1524
1525 module.glob_importers.borrow_mut_unchecked().push(import);
1527
1528 let bindings = self
1531 .resolutions(module)
1532 .borrow()
1533 .iter()
1534 .filter_map(|(key, resolution)| {
1535 resolution.borrow().binding().map(|binding| (*key, binding))
1536 })
1537 .collect::<Vec<_>>();
1538 for (mut key, binding) in bindings {
1539 let scope = match key.ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
1540 Some(Some(def)) => self.expn_def_scope(def),
1541 Some(None) => import.parent_scope.module,
1542 None => continue,
1543 };
1544 if self.is_accessible_from(binding.vis(), scope) {
1545 let import_decl = self.new_import_decl(binding, import);
1546 let warn_ambiguity = self
1547 .resolution(import.parent_scope.module, key)
1548 .and_then(|r| r.binding())
1549 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1550 let _ = self.try_plant_decl_into_local_module(
1551 key.ident,
1552 key.ns,
1553 import_decl,
1554 warn_ambiguity,
1555 );
1556 }
1557 }
1558
1559 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1561 }
1562
1563 fn finalize_resolutions_in(
1566 &self,
1567 module: Module<'ra>,
1568 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1569 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1570 ) {
1571 *module.globs.borrow_mut(self) = Vec::new();
1573
1574 let Some(def_id) = module.opt_def_id() else { return };
1575
1576 let mut children = Vec::new();
1577 let mut ambig_children = Vec::new();
1578
1579 module.for_each_child(self, |this, ident, _, binding| {
1580 let res = binding.res().expect_non_local();
1581 if res != def::Res::Err {
1582 let child = |reexport_chain| ModChild {
1583 ident: ident.0,
1584 res,
1585 vis: binding.vis(),
1586 reexport_chain,
1587 };
1588 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1589 let main = child(ambig_binding1.reexport_chain(this));
1590 let second = ModChild {
1591 ident: ident.0,
1592 res: ambig_binding2.res().expect_non_local(),
1593 vis: ambig_binding2.vis(),
1594 reexport_chain: ambig_binding2.reexport_chain(this),
1595 };
1596 ambig_children.push(AmbigModChild { main, second })
1597 } else {
1598 children.push(child(binding.reexport_chain(this)));
1599 }
1600 }
1601 });
1602
1603 if !children.is_empty() {
1604 module_children.insert(def_id.expect_local(), children);
1605 }
1606 if !ambig_children.is_empty() {
1607 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1608 }
1609 }
1610}
1611
1612fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1613 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1614 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1615 if let Some(pos) = pos {
1616 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1617 names_to_string(names.iter().map(|ident| ident.name))
1618 } else {
1619 let names = if global { &names[1..] } else { names };
1620 if names.is_empty() {
1621 import_kind_to_string(import_kind)
1622 } else {
1623 ::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!(
1624 "{}::{}",
1625 names_to_string(names.iter().map(|ident| ident.name)),
1626 import_kind_to_string(import_kind),
1627 )
1628 }
1629 }
1630}
1631
1632fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1633 match import_kind {
1634 ImportKind::Single { source, .. } => source.to_string(),
1635 ImportKind::Glob { .. } => "*".to_string(),
1636 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1637 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1638 ImportKind::MacroExport => "#[macro_export]".to_string(),
1639 }
1640}