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