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