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, 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 IdentKey, ImportSuggestion, Module, ModuleOrUniformRoot, ParentScope, PathResult, PerNS,
37 ResolutionError, 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),
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)]
243pub(crate) struct NameResolution<'ra> {
244 pub single_imports: FxIndexSet<Import<'ra>>,
247 pub non_glob_decl: Option<Decl<'ra>> = None,
249 pub glob_decl: Option<Decl<'ra>> = None,
251 pub orig_ident_span: Span,
252}
253
254impl<'ra> NameResolution<'ra> {
255 pub(crate) fn new(orig_ident_span: Span) -> Self {
256 NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
257 }
258
259 pub(crate) fn binding(&self) -> Option<Decl<'ra>> {
261 self.best_decl().and_then(|binding| {
262 if !binding.is_glob_import() || self.single_imports.is_empty() {
263 Some(binding)
264 } else {
265 None
266 }
267 })
268 }
269
270 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
271 self.non_glob_decl.or(self.glob_decl)
272 }
273}
274
275#[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)]
278struct UnresolvedImportError {
279 span: Span,
280 label: Option<String>,
281 note: Option<String>,
282 suggestion: Option<Suggestion>,
283 candidates: Option<Vec<ImportSuggestion>>,
284 segment: Option<Symbol>,
285 module: Option<DefId>,
287}
288
289fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
292 match (&import.kind, &decl.kind) {
293 (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
294 if let ImportKind::ExternCrate { id, .. } = decl_import.kind
295 && import.vis.is_public() =>
296 {
297 Some(id)
298 }
299 _ => None,
300 }
301}
302
303fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
305 if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
306 && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
307 && import1 == import2
308 {
309 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);
310 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);
311 if d1.ambiguity.get() != d2.ambiguity.get() {
312 if !d1.ambiguity.get().is_some() {
::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
313 if !d2.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: d2.ambiguity.get().is_none()")
};assert!(d2.ambiguity.get().is_none());
314 }
315 remove_same_import(d1_next, d2_next)
319 } else {
320 (d1, d2)
321 }
322}
323
324impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
325 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
328 let import_vis = import.vis.to_def_id();
329 let vis = if decl.vis().is_at_least(import_vis, self.tcx)
330 || pub_use_of_private_extern_crate_hack(import, decl).is_some()
331 {
332 import_vis
333 } else {
334 decl.vis()
335 };
336
337 if let ImportKind::Glob { ref max_vis, .. } = import.kind
338 && (vis == import_vis
339 || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
340 {
341 max_vis.set_unchecked(Some(vis.expect_local()))
342 }
343
344 self.arenas.alloc_decl(DeclData {
345 kind: DeclKind::Import { source_decl: decl, import },
346 ambiguity: CmCell::new(None),
347 warn_ambiguity: CmCell::new(false),
348 span: import.span,
349 vis: CmCell::new(vis),
350 expansion: import.parent_scope.expansion,
351 parent_module: Some(import.parent_scope.module),
352 })
353 }
354
355 fn select_glob_decl(
358 &self,
359 old_glob_decl: Decl<'ra>,
360 glob_decl: Decl<'ra>,
361 warn_ambiguity: bool,
362 ) -> Decl<'ra> {
363 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
364 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());
365 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);
366 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
381 if deep_decl != glob_decl {
382 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);
384 if !!deep_decl.is_glob_import() {
::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
388 if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
389 glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
391 }
392 if glob_decl.is_ambiguity_recursive() {
393 glob_decl.warn_ambiguity.set_unchecked(true);
394 }
395 glob_decl
396 } else if glob_decl.res() != old_glob_decl.res() {
397 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
398 old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
399 if warn_ambiguity {
400 old_glob_decl
401 } else {
402 self.arenas.alloc_decl((*old_glob_decl).clone())
406 }
407 } else if !old_glob_decl.vis().is_at_least(glob_decl.vis(), self.tcx) {
408 old_glob_decl.vis.set_unchecked(glob_decl.vis());
410 old_glob_decl
411 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
412 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
414 old_glob_decl.warn_ambiguity.set_unchecked(true);
415 old_glob_decl
416 } else {
417 old_glob_decl
418 }
419 }
420
421 pub(crate) fn try_plant_decl_into_local_module(
424 &mut self,
425 ident: IdentKey,
426 orig_ident_span: Span,
427 ns: Namespace,
428 decl: Decl<'ra>,
429 warn_ambiguity: bool,
430 ) -> Result<(), Decl<'ra>> {
431 let module = decl.parent_module.unwrap();
432 let res = decl.res();
433 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
434 let key = BindingKey::new_disambiguated(ident, ns, || {
438 module.underscore_disambiguator.update_unchecked(|d| d + 1);
439 module.underscore_disambiguator.get()
440 });
441 self.update_local_resolution(
442 module,
443 key,
444 orig_ident_span,
445 warn_ambiguity,
446 |this, resolution| {
447 if let Some(old_decl) = resolution.best_decl() {
448 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);
449 if !!decl.warn_ambiguity.get() {
::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
450 if res == Res::Err && old_decl.res() != Res::Err {
451 return Ok(());
453 }
454 match (old_decl.is_glob_import(), decl.is_glob_import()) {
455 (true, true) => {
456 resolution.glob_decl =
457 Some(this.select_glob_decl(old_decl, decl, warn_ambiguity));
458 }
459 (old_glob @ true, false) | (old_glob @ false, true) => {
460 let (glob_decl, non_glob_decl) =
461 if old_glob { (old_decl, decl) } else { (decl, old_decl) };
462 resolution.non_glob_decl = Some(non_glob_decl);
463 if let Some(old_glob_decl) = resolution.glob_decl
464 && old_glob_decl != glob_decl
465 {
466 resolution.glob_decl =
467 Some(this.select_glob_decl(old_glob_decl, glob_decl, false));
468 } else {
469 resolution.glob_decl = Some(glob_decl);
470 }
471 }
472 (false, false) => {
473 return Err(old_decl);
474 }
475 }
476 } else {
477 if decl.is_glob_import() {
478 resolution.glob_decl = Some(decl);
479 } else {
480 resolution.non_glob_decl = Some(decl);
481 }
482 }
483
484 Ok(())
485 },
486 )
487 }
488
489 fn update_local_resolution<T, F>(
492 &mut self,
493 module: Module<'ra>,
494 key: BindingKey,
495 orig_ident_span: Span,
496 warn_ambiguity: bool,
497 f: F,
498 ) -> T
499 where
500 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
501 {
502 let (binding, t, warn_ambiguity) = {
505 let resolution = &mut *self
506 .resolution_or_default(module, key, orig_ident_span)
507 .borrow_mut_unchecked();
508 let old_decl = resolution.binding();
509
510 let t = f(self, resolution);
511
512 if let Some(binding) = resolution.binding()
513 && old_decl != Some(binding)
514 {
515 (binding, t, warn_ambiguity || old_decl.is_some())
516 } else {
517 return t;
518 }
519 };
520
521 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
522 return t;
523 };
524
525 for import in glob_importers.iter() {
527 let mut ident = key.ident;
528 let scope = match ident
529 .ctxt
530 .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
531 {
532 Some(Some(def)) => self.expn_def_scope(def),
533 Some(None) => import.parent_scope.module,
534 None => continue,
535 };
536 if self.is_accessible_from(binding.vis(), scope) {
537 let import_decl = self.new_import_decl(binding, *import);
538 let _ = self.try_plant_decl_into_local_module(
539 ident,
540 orig_ident_span,
541 key.ns,
542 import_decl,
543 warn_ambiguity,
544 );
545 }
546 }
547
548 t
549 }
550
551 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
554 if let ImportKind::Single { target, ref decls, .. } = import.kind {
555 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
556 return; }
558 let dummy_decl = self.dummy_decl;
559 let dummy_decl = self.new_import_decl(dummy_decl, import);
560 self.per_ns(|this, ns| {
561 let module = import.parent_scope.module;
562 let ident = IdentKey::new(target);
563 let _ = this.try_plant_decl_into_local_module(
564 ident,
565 target.span,
566 ns,
567 dummy_decl,
568 false,
569 );
570 if target.name != kw::Underscore {
572 let key = BindingKey::new(ident, ns);
573 this.update_local_resolution(
574 module,
575 key,
576 target.span,
577 false,
578 |_, resolution| {
579 resolution.single_imports.swap_remove(&import);
580 },
581 )
582 }
583 });
584 self.record_use(target, dummy_decl, Used::Other);
585 } else if import.imported_module.get().is_none() {
586 self.import_use_map.insert(import, Used::Other);
587 if let Some(id) = import.id() {
588 self.used_imports.insert(id);
589 }
590 }
591 }
592
593 pub(crate) fn resolve_imports(&mut self) {
604 let mut prev_indeterminate_count = usize::MAX;
605 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
606 while indeterminate_count < prev_indeterminate_count {
607 prev_indeterminate_count = indeterminate_count;
608 indeterminate_count = 0;
609 self.assert_speculative = true;
610 for import in mem::take(&mut self.indeterminate_imports) {
611 let import_indeterminate_count = self.cm().resolve_import(import);
612 indeterminate_count += import_indeterminate_count;
613 match import_indeterminate_count {
614 0 => self.determined_imports.push(import),
615 _ => self.indeterminate_imports.push(import),
616 }
617 }
618 self.assert_speculative = false;
619 }
620 }
621
622 pub(crate) fn finalize_imports(&mut self) {
623 let mut module_children = Default::default();
624 let mut ambig_module_children = Default::default();
625 for module in &self.local_modules {
626 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
627 }
628 self.module_children = module_children;
629 self.ambig_module_children = ambig_module_children;
630
631 let mut seen_spans = FxHashSet::default();
632 let mut errors = ::alloc::vec::Vec::new()vec![];
633 let mut prev_root_id: NodeId = NodeId::ZERO;
634 let determined_imports = mem::take(&mut self.determined_imports);
635 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
636
637 let mut glob_error = false;
638 for (is_indeterminate, import) in determined_imports
639 .iter()
640 .map(|i| (false, i))
641 .chain(indeterminate_imports.iter().map(|i| (true, i)))
642 {
643 let unresolved_import_error = self.finalize_import(*import);
644 self.import_dummy_binding(*import, is_indeterminate);
647
648 let Some(err) = unresolved_import_error else { continue };
649
650 glob_error |= import.is_glob();
651
652 if let ImportKind::Single { source, ref decls, .. } = import.kind
653 && source.name == kw::SelfLower
654 && let PendingDecl::Ready(None) = decls.value_ns.get()
656 {
657 continue;
658 }
659
660 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
661 {
662 self.throw_unresolved_import_error(errors, glob_error);
665 errors = ::alloc::vec::Vec::new()vec![];
666 }
667 if seen_spans.insert(err.span) {
668 errors.push((*import, err));
669 prev_root_id = import.root_id;
670 }
671 }
672
673 if !errors.is_empty() {
674 self.throw_unresolved_import_error(errors, glob_error);
675 return;
676 }
677
678 for import in &indeterminate_imports {
679 let path = import_path_to_string(
680 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
681 &import.kind,
682 import.span,
683 );
684 if path.contains("::") {
687 let err = UnresolvedImportError {
688 span: import.span,
689 label: None,
690 note: None,
691 suggestion: None,
692 candidates: None,
693 segment: None,
694 module: None,
695 };
696 errors.push((*import, err))
697 }
698 }
699
700 if !errors.is_empty() {
701 self.throw_unresolved_import_error(errors, glob_error);
702 }
703 }
704
705 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
706 for module in &self.local_modules {
707 for (key, resolution) in self.resolutions(*module).borrow().iter() {
708 let resolution = resolution.borrow();
709 let Some(binding) = resolution.best_decl() else { continue };
710
711 if let DeclKind::Import { import, .. } = binding.kind
712 && let Some(amb_binding) = binding.ambiguity.get()
713 && binding.res() != Res::Err
714 && exported_ambiguities.contains(&binding)
715 {
716 self.lint_buffer.buffer_lint(
717 AMBIGUOUS_GLOB_REEXPORTS,
718 import.root_id,
719 import.root_span,
720 BuiltinLintDiag::AmbiguousGlobReexports {
721 name: key.ident.name.to_string(),
722 namespace: key.ns.descr().to_string(),
723 first_reexport_span: import.root_span,
724 duplicate_reexport_span: amb_binding.span,
725 },
726 );
727 }
728
729 if let Some(glob_decl) = resolution.glob_decl
730 && resolution.non_glob_decl.is_some()
731 {
732 if binding.res() != Res::Err
733 && glob_decl.res() != Res::Err
734 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
735 && let Some(glob_import_id) = glob_import.id()
736 && let glob_import_def_id = self.local_def_id(glob_import_id)
737 && self.effective_visibilities.is_exported(glob_import_def_id)
738 && glob_decl.vis().is_public()
739 && !binding.vis().is_public()
740 {
741 let binding_id = match binding.kind {
742 DeclKind::Def(res) => {
743 Some(self.def_id_to_node_id(res.def_id().expect_local()))
744 }
745 DeclKind::Import { import, .. } => import.id(),
746 };
747 if let Some(binding_id) = binding_id {
748 self.lint_buffer.buffer_lint(
749 HIDDEN_GLOB_REEXPORTS,
750 binding_id,
751 binding.span,
752 BuiltinLintDiag::HiddenGlobReexports {
753 name: key.ident.name.to_string(),
754 namespace: key.ns.descr().to_owned(),
755 glob_reexport_span: glob_decl.span,
756 private_item_span: binding.span,
757 },
758 );
759 }
760 }
761 }
762
763 if let DeclKind::Import { import, .. } = binding.kind
764 && let Some(binding_id) = import.id()
765 && let import_def_id = self.local_def_id(binding_id)
766 && self.effective_visibilities.is_exported(import_def_id)
767 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
768 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
769 && !reexported_def_id.is_local()
770 && self.tcx.is_private_dep(reexported_def_id.krate)
771 {
772 self.lint_buffer.buffer_lint(
773 EXPORTED_PRIVATE_DEPENDENCIES,
774 binding_id,
775 binding.span,
776 crate::errors::ReexportPrivateDependency {
777 name: key.ident.name,
778 kind: binding.res().descr(),
779 krate: self.tcx.crate_name(reexported_def_id.krate),
780 },
781 );
782 }
783 }
784 }
785 }
786
787 fn throw_unresolved_import_error(
788 &mut self,
789 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
790 glob_error: bool,
791 ) {
792 errors.retain(|(_import, err)| match err.module {
793 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
795 _ => err.segment != Some(kw::Underscore),
798 });
799 if errors.is_empty() {
800 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
801 return;
802 }
803
804 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
805
806 let paths = errors
807 .iter()
808 .map(|(import, err)| {
809 let path = import_path_to_string(
810 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
811 &import.kind,
812 err.span,
813 );
814 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
815 })
816 .collect::<Vec<_>>();
817 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(", "),);
818
819 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}");
820
821 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
822 diag.note(note.clone());
823 }
824
825 const MAX_LABEL_COUNT: usize = 10;
827
828 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
829 if let Some(label) = err.label {
830 diag.span_label(err.span, label);
831 }
832
833 if let Some((suggestions, msg, applicability)) = err.suggestion {
834 if suggestions.is_empty() {
835 diag.help(msg);
836 continue;
837 }
838 diag.multipart_suggestion(msg, suggestions, applicability);
839 }
840
841 if let Some(candidates) = &err.candidates {
842 match &import.kind {
843 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
844 self.tcx,
845 &mut diag,
846 Some(err.span),
847 candidates,
848 DiagMode::Import { append: false, unresolved_import: true },
849 (source != target)
850 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
851 .as_deref()
852 .unwrap_or(""),
853 ),
854 ImportKind::Single { nested: true, source, target, .. } => {
855 import_candidates(
856 self.tcx,
857 &mut diag,
858 None,
859 candidates,
860 DiagMode::Normal,
861 (source != target)
862 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
863 .as_deref()
864 .unwrap_or(""),
865 );
866 }
867 _ => {}
868 }
869 }
870
871 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
872 && let Some(segment) = err.segment
873 && let Some(module) = err.module
874 {
875 self.find_cfg_stripped(&mut diag, &segment, module)
876 }
877 }
878
879 let guar = diag.emit();
880 if glob_error {
881 self.glob_error = Some(guar);
882 }
883 }
884
885 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
892 {
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:892",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(892u32),
::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!(
893 "(resolving import for module) resolving import `{}::...` in `{}`",
894 Segment::names_to_string(&import.module_path),
895 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
896 );
897 let module = if let Some(module) = import.imported_module.get() {
898 module
899 } else {
900 let path_res = self.reborrow().maybe_resolve_path(
901 &import.module_path,
902 None,
903 &import.parent_scope,
904 Some(import),
905 );
906
907 match path_res {
908 PathResult::Module(module) => module,
909 PathResult::Indeterminate => return 3,
910 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
911 }
912 };
913
914 import.imported_module.set_unchecked(Some(module));
915 let (source, target, bindings, type_ns_only) = match import.kind {
916 ImportKind::Single { source, target, ref decls, type_ns_only, .. } => {
917 (source, target, decls, type_ns_only)
918 }
919 ImportKind::Glob { .. } => {
920 self.get_mut_unchecked().resolve_glob_import(import);
921 return 0;
922 }
923 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
924 };
925
926 let mut indeterminate_count = 0;
927 self.per_ns_cm(|mut this, ns| {
928 if !type_ns_only || ns == TypeNS {
929 if bindings[ns].get() != PendingDecl::Pending {
930 return;
931 };
932 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
933 module,
934 source,
935 ns,
936 &import.parent_scope,
937 Some(import),
938 );
939 let parent = import.parent_scope.module;
940 let binding = match binding_result {
941 Ok(binding) => {
942 if binding.is_assoc_item()
943 && !this.tcx.features().import_trait_associated_functions()
944 {
945 feature_err(
946 this.tcx.sess,
947 sym::import_trait_associated_functions,
948 import.span,
949 "`use` associated items of traits is unstable",
950 )
951 .emit();
952 }
953 let import_decl = this.new_import_decl(binding, import);
955 this.get_mut_unchecked().plant_decl_into_local_module(
956 IdentKey::new(target),
957 target.span,
958 ns,
959 import_decl,
960 );
961 PendingDecl::Ready(Some(import_decl))
962 }
963 Err(Determinacy::Determined) => {
964 if target.name != kw::Underscore {
966 let key = BindingKey::new(IdentKey::new(target), ns);
967 this.get_mut_unchecked().update_local_resolution(
968 parent,
969 key,
970 target.span,
971 false,
972 |_, resolution| {
973 resolution.single_imports.swap_remove(&import);
974 },
975 );
976 }
977 PendingDecl::Ready(None)
978 }
979 Err(Determinacy::Undetermined) => {
980 indeterminate_count += 1;
981 PendingDecl::Pending
982 }
983 };
984 bindings[ns].set_unchecked(binding);
985 }
986 });
987
988 indeterminate_count
989 }
990
991 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
996 let ignore_decl = match &import.kind {
997 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
998 _ => None,
999 };
1000 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1001 errors.iter().filter(|error| error.warning.is_none()).count()
1002 };
1003 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1004 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1005
1006 let privacy_errors_len = self.privacy_errors.len();
1008
1009 let path_res = self.cm().resolve_path(
1010 &import.module_path,
1011 None,
1012 &import.parent_scope,
1013 Some(finalize),
1014 ignore_decl,
1015 Some(import),
1016 );
1017
1018 let no_ambiguity =
1019 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1020
1021 let module = match path_res {
1022 PathResult::Module(module) => {
1023 if let Some(initial_module) = import.imported_module.get() {
1025 if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1026 ::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");
1027 }
1028 } else if self.privacy_errors.is_empty() {
1029 self.dcx()
1030 .create_err(CannotDetermineImportResolution { span: import.span })
1031 .emit();
1032 }
1033
1034 module
1035 }
1036 PathResult::Failed {
1037 is_error_from_last_segment: false,
1038 span,
1039 segment_name,
1040 label,
1041 suggestion,
1042 module,
1043 error_implied_by_parse_error: _,
1044 } => {
1045 if no_ambiguity {
1046 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());
1047 self.report_error(
1048 span,
1049 ResolutionError::FailedToResolve {
1050 segment: Some(segment_name),
1051 label,
1052 suggestion,
1053 module,
1054 },
1055 );
1056 }
1057 return None;
1058 }
1059 PathResult::Failed {
1060 is_error_from_last_segment: true,
1061 span,
1062 label,
1063 suggestion,
1064 module,
1065 segment_name,
1066 ..
1067 } => {
1068 if no_ambiguity {
1069 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());
1070 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1071 m.opt_def_id()
1072 } else {
1073 None
1074 };
1075 let err = match self
1076 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1077 {
1078 Some((suggestion, note)) => UnresolvedImportError {
1079 span,
1080 label: None,
1081 note,
1082 suggestion: Some((
1083 <[_]>::into_vec(::alloc::boxed::box_new([(span,
Segment::names_to_string(&suggestion))]))vec![(span, Segment::names_to_string(&suggestion))],
1084 String::from("a similar path exists"),
1085 Applicability::MaybeIncorrect,
1086 )),
1087 candidates: None,
1088 segment: Some(segment_name),
1089 module,
1090 },
1091 None => UnresolvedImportError {
1092 span,
1093 label: Some(label),
1094 note: None,
1095 suggestion,
1096 candidates: None,
1097 segment: Some(segment_name),
1098 module,
1099 },
1100 };
1101 return Some(err);
1102 }
1103 return None;
1104 }
1105 PathResult::NonModule(partial_res) => {
1106 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1107 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());
1109 }
1110 return None;
1112 }
1113 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1114 };
1115
1116 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1117 ImportKind::Single { source, target, ref decls, type_ns_only, id, .. } => {
1118 (source, target, decls, type_ns_only, id)
1119 }
1120 ImportKind::Glob { ref max_vis, id } => {
1121 if import.module_path.len() <= 1 {
1122 let mut full_path = import.module_path.clone();
1125 full_path.push(Segment::from_ident(Ident::dummy()));
1126 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1127 }
1128
1129 if let ModuleOrUniformRoot::Module(module) = module
1130 && module == import.parent_scope.module
1131 {
1132 return Some(UnresolvedImportError {
1134 span: import.span,
1135 label: Some(String::from("cannot glob-import a module into itself")),
1136 note: None,
1137 suggestion: None,
1138 candidates: None,
1139 segment: None,
1140 module: None,
1141 });
1142 }
1143 if let Some(max_vis) = max_vis.get()
1144 && !max_vis.is_at_least(import.vis, self.tcx)
1145 {
1146 let def_id = self.local_def_id(id);
1147 self.lint_buffer.buffer_lint(
1148 UNUSED_IMPORTS,
1149 id,
1150 import.span,
1151 crate::errors::RedundantImportVisibility {
1152 span: import.span,
1153 help: (),
1154 max_vis: max_vis.to_string(def_id, self.tcx),
1155 import_vis: import.vis.to_string(def_id, self.tcx),
1156 },
1157 );
1158 }
1159 return None;
1160 }
1161 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1162 };
1163
1164 if self.privacy_errors.len() != privacy_errors_len {
1165 let mut path = import.module_path.clone();
1168 path.push(Segment::from_ident(ident));
1169 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1170 &path,
1171 None,
1172 &import.parent_scope,
1173 Some(finalize),
1174 ignore_decl,
1175 None,
1176 ) {
1177 let res = module.res().map(|r| (r, ident));
1178 for error in &mut self.privacy_errors[privacy_errors_len..] {
1179 error.outermost_res = res;
1180 }
1181 }
1182 }
1183
1184 let mut all_ns_err = true;
1185 self.per_ns(|this, ns| {
1186 if !type_ns_only || ns == TypeNS {
1187 let binding = this.cm().resolve_ident_in_module(
1188 module,
1189 ident,
1190 ns,
1191 &import.parent_scope,
1192 Some(Finalize {
1193 report_private: false,
1194 import_vis: Some(import.vis),
1195 ..finalize
1196 }),
1197 bindings[ns].get().decl(),
1198 Some(import),
1199 );
1200
1201 match binding {
1202 Ok(binding) => {
1203 let initial_res = bindings[ns].get().decl().map(|binding| {
1205 let initial_binding = binding.import_source();
1206 all_ns_err = false;
1207 if target.name == kw::Underscore
1208 && initial_binding.is_extern_crate()
1209 && !initial_binding.is_import()
1210 {
1211 let used = if import.module_path.is_empty() {
1212 Used::Scope
1213 } else {
1214 Used::Other
1215 };
1216 this.record_use(ident, binding, used);
1217 }
1218 initial_binding.res()
1219 });
1220 let res = binding.res();
1221 let has_ambiguity_error =
1222 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1223 if res == Res::Err || has_ambiguity_error {
1224 this.dcx()
1225 .span_delayed_bug(import.span, "some error happened for an import");
1226 return;
1227 }
1228 if let Some(initial_res) = initial_res {
1229 if res != initial_res && !this.issue_145575_hack_applied {
1230 ::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");
1231 }
1232 } else if this.privacy_errors.is_empty() {
1233 this.dcx()
1234 .create_err(CannotDetermineImportResolution { span: import.span })
1235 .emit();
1236 }
1237 }
1238 Err(..) => {
1239 }
1246 }
1247 }
1248 });
1249
1250 if all_ns_err {
1251 let mut all_ns_failed = true;
1252 self.per_ns(|this, ns| {
1253 if !type_ns_only || ns == TypeNS {
1254 let binding = this.cm().resolve_ident_in_module(
1255 module,
1256 ident,
1257 ns,
1258 &import.parent_scope,
1259 Some(finalize),
1260 None,
1261 None,
1262 );
1263 if binding.is_ok() {
1264 all_ns_failed = false;
1265 }
1266 }
1267 });
1268
1269 return if all_ns_failed {
1270 let names = match module {
1271 ModuleOrUniformRoot::Module(module) => {
1272 self.resolutions(module)
1273 .borrow()
1274 .iter()
1275 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1276 if i.name == ident.name {
1277 return None;
1278 } let resolution = resolution.borrow();
1281 if let Some(name_binding) = resolution.best_decl() {
1282 match name_binding.kind {
1283 DeclKind::Import { source_decl, .. } => {
1284 match source_decl.kind {
1285 DeclKind::Def(Res::Err) => None,
1288 _ => Some(i.name),
1289 }
1290 }
1291 _ => Some(i.name),
1292 }
1293 } else if resolution.single_imports.is_empty() {
1294 None
1295 } else {
1296 Some(i.name)
1297 }
1298 })
1299 .collect()
1300 }
1301 _ => Vec::new(),
1302 };
1303
1304 let lev_suggestion =
1305 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1306 (
1307 <[_]>::into_vec(::alloc::boxed::box_new([(ident.span,
suggestion.to_string())]))vec![(ident.span, suggestion.to_string())],
1308 String::from("a similar name exists in the module"),
1309 Applicability::MaybeIncorrect,
1310 )
1311 });
1312
1313 let (suggestion, note) =
1314 match self.check_for_module_export_macro(import, module, ident) {
1315 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1316 _ => (lev_suggestion, None),
1317 };
1318
1319 let label = match module {
1320 ModuleOrUniformRoot::Module(module) => {
1321 let module_str = module_to_string(module);
1322 if let Some(module_str) = module_str {
1323 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1324 } else {
1325 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1326 }
1327 }
1328 _ => {
1329 if !ident.is_path_segment_keyword() {
1330 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1331 } else {
1332 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1335 }
1336 }
1337 };
1338
1339 let parent_suggestion =
1340 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1341
1342 Some(UnresolvedImportError {
1343 span: import.span,
1344 label: Some(label),
1345 note,
1346 suggestion,
1347 candidates: if !parent_suggestion.is_empty() {
1348 Some(parent_suggestion)
1349 } else {
1350 None
1351 },
1352 module: import.imported_module.get().and_then(|module| {
1353 if let ModuleOrUniformRoot::Module(m) = module {
1354 m.opt_def_id()
1355 } else {
1356 None
1357 }
1358 }),
1359 segment: Some(ident.name),
1360 })
1361 } else {
1362 None
1364 };
1365 }
1366
1367 let mut reexport_error = None;
1368 let mut any_successful_reexport = false;
1369 let mut crate_private_reexport = false;
1370 self.per_ns(|this, ns| {
1371 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1372 return;
1373 };
1374
1375 if !binding.vis().is_at_least(import.vis, this.tcx) {
1376 reexport_error = Some((ns, binding));
1377 if let Visibility::Restricted(binding_def_id) = binding.vis()
1378 && binding_def_id.is_top_level_module()
1379 {
1380 crate_private_reexport = true;
1381 }
1382 } else {
1383 any_successful_reexport = true;
1384 }
1385 });
1386
1387 if !any_successful_reexport {
1389 let (ns, binding) = reexport_error.unwrap();
1390 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1391 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1392 self.lint_buffer.buffer_lint(
1393 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1394 import_id,
1395 import.span,
1396 crate::errors::PrivateExternCrateReexport {
1397 ident,
1398 sugg: extern_crate_sp.shrink_to_lo(),
1399 },
1400 );
1401 } else if ns == TypeNS {
1402 let err = if crate_private_reexport {
1403 self.dcx()
1404 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1405 } else {
1406 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1407 };
1408 err.emit();
1409 } else {
1410 let mut err = if crate_private_reexport {
1411 self.dcx()
1412 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1413 } else {
1414 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1415 };
1416
1417 match binding.kind {
1418 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1419 if self.get_macro_by_def_id(def_id).macro_rules =>
1421 {
1422 err.subdiagnostic( ConsiderAddingMacroExport {
1423 span: binding.span,
1424 });
1425 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1426 vis_span: import.vis_span,
1427 });
1428 }
1429 _ => {
1430 err.subdiagnostic( ConsiderMarkingAsPub {
1431 span: import.span,
1432 ident,
1433 });
1434 }
1435 }
1436 err.emit();
1437 }
1438 }
1439
1440 if import.module_path.len() <= 1 {
1441 let mut full_path = import.module_path.clone();
1444 full_path.push(Segment::from_ident(ident));
1445 self.per_ns(|this, ns| {
1446 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1447 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1448 }
1449 });
1450 }
1451
1452 self.per_ns(|this, ns| {
1456 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1457 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1458 }
1459 });
1460
1461 {
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:1461",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1461u32),
::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");
1462 None
1463 }
1464
1465 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1466 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1468 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1469 };
1470
1471 if source != target {
1473 return false;
1474 }
1475
1476 if import.parent_scope.expansion != LocalExpnId::ROOT {
1478 return false;
1479 }
1480
1481 if self.import_use_map.get(&import) == Some(&Used::Other)
1486 || self.effective_visibilities.is_exported(self.local_def_id(id))
1487 {
1488 return false;
1489 }
1490
1491 let mut is_redundant = true;
1492 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1493 self.per_ns(|this, ns| {
1494 let binding = decls[ns].get().decl().map(|b| b.import_source());
1495 if is_redundant && let Some(binding) = binding {
1496 if binding.res() == Res::Err {
1497 return;
1498 }
1499
1500 match this.cm().resolve_ident_in_scope_set(
1501 target,
1502 ScopeSet::All(ns),
1503 &import.parent_scope,
1504 None,
1505 decls[ns].get().decl(),
1506 None,
1507 ) {
1508 Ok(other_binding) => {
1509 is_redundant = binding.res() == other_binding.res()
1510 && !other_binding.is_ambiguity_recursive();
1511 if is_redundant {
1512 redundant_span[ns] =
1513 Some((other_binding.span, other_binding.is_import()));
1514 }
1515 }
1516 Err(_) => is_redundant = false,
1517 }
1518 }
1519 });
1520
1521 if is_redundant && !redundant_span.is_empty() {
1522 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1523 redundant_spans.sort();
1524 redundant_spans.dedup();
1525 self.lint_buffer.buffer_lint(
1526 REDUNDANT_IMPORTS,
1527 id,
1528 import.span,
1529 BuiltinLintDiag::RedundantImport(redundant_spans, source),
1530 );
1531 return true;
1532 }
1533
1534 false
1535 }
1536
1537 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1538 let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1540
1541 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1542 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1543 return;
1544 };
1545
1546 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1547 feature_err(
1548 self.tcx.sess,
1549 sym::import_trait_associated_functions,
1550 import.span,
1551 "`use` associated items of traits is unstable",
1552 )
1553 .emit();
1554 }
1555
1556 if module == import.parent_scope.module {
1557 return;
1558 }
1559
1560 module.glob_importers.borrow_mut_unchecked().push(import);
1562
1563 let bindings = self
1566 .resolutions(module)
1567 .borrow()
1568 .iter()
1569 .filter_map(|(key, resolution)| {
1570 let resolution = resolution.borrow();
1571 resolution.binding().map(|binding| (*key, binding, resolution.orig_ident_span))
1572 })
1573 .collect::<Vec<_>>();
1574 for (mut key, binding, orig_ident_span) in bindings {
1575 let scope =
1576 match key.ident.ctxt.update_unchecked(|ctxt| {
1577 ctxt.reverse_glob_adjust(module.expansion, import.span)
1578 }) {
1579 Some(Some(def)) => self.expn_def_scope(def),
1580 Some(None) => import.parent_scope.module,
1581 None => continue,
1582 };
1583 if self.is_accessible_from(binding.vis(), scope) {
1584 let import_decl = self.new_import_decl(binding, import);
1585 let warn_ambiguity = self
1586 .resolution(import.parent_scope.module, key)
1587 .and_then(|r| r.binding())
1588 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1589 let _ = self.try_plant_decl_into_local_module(
1590 key.ident,
1591 orig_ident_span,
1592 key.ns,
1593 import_decl,
1594 warn_ambiguity,
1595 );
1596 }
1597 }
1598
1599 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1601 }
1602
1603 fn finalize_resolutions_in(
1606 &self,
1607 module: Module<'ra>,
1608 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1609 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1610 ) {
1611 *module.globs.borrow_mut(self) = Vec::new();
1613
1614 let Some(def_id) = module.opt_def_id() else { return };
1615
1616 let mut children = Vec::new();
1617 let mut ambig_children = Vec::new();
1618
1619 module.for_each_child(self, |this, ident, orig_ident_span, _, binding| {
1620 let res = binding.res().expect_non_local();
1621 if res != def::Res::Err {
1622 let ident = ident.orig(orig_ident_span);
1623 let child =
1624 |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1625 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1626 let main = child(ambig_binding1.reexport_chain(this));
1627 let second = ModChild {
1628 ident,
1629 res: ambig_binding2.res().expect_non_local(),
1630 vis: ambig_binding2.vis(),
1631 reexport_chain: ambig_binding2.reexport_chain(this),
1632 };
1633 ambig_children.push(AmbigModChild { main, second })
1634 } else {
1635 children.push(child(binding.reexport_chain(this)));
1636 }
1637 }
1638 });
1639
1640 if !children.is_empty() {
1641 module_children.insert(def_id.expect_local(), children);
1642 }
1643 if !ambig_children.is_empty() {
1644 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1645 }
1646 }
1647}
1648
1649fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1650 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1651 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1652 if let Some(pos) = pos {
1653 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1654 names_to_string(names.iter().map(|ident| ident.name))
1655 } else {
1656 let names = if global { &names[1..] } else { names };
1657 if names.is_empty() {
1658 import_kind_to_string(import_kind)
1659 } else {
1660 ::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!(
1661 "{}::{}",
1662 names_to_string(names.iter().map(|ident| ident.name)),
1663 import_kind_to_string(import_kind),
1664 )
1665 }
1666 }
1667}
1668
1669fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1670 match import_kind {
1671 ImportKind::Single { source, .. } => source.to_string(),
1672 ImportKind::Glob { .. } => "*".to_string(),
1673 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1674 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1675 ImportKind::MacroExport => "#[macro_export]".to_string(),
1676 }
1677}