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,
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 }
1296 }
1297
1298 let mut all_ns_err = true;
1299 self.per_ns(|this, ns| {
1300 let binding = this.cm().resolve_ident_in_module(
1301 module,
1302 ident,
1303 ns,
1304 &import.parent_scope,
1305 Some(Finalize {
1306 report_private: false,
1307 import: Some(import.summary()),
1308 ..finalize
1309 }),
1310 bindings[ns].get().decl(),
1311 Some(import),
1312 );
1313
1314 match binding {
1315 Ok(binding) => {
1316 let initial_res = bindings[ns].get().decl().map(|binding| {
1318 let initial_binding = binding.import_source();
1319 all_ns_err = false;
1320 if target.name == kw::Underscore
1321 && initial_binding.is_extern_crate()
1322 && !initial_binding.is_import()
1323 {
1324 let used = if import.module_path.is_empty() {
1325 Used::Scope
1326 } else {
1327 Used::Other
1328 };
1329 this.record_use(ident, binding, used);
1330 }
1331 initial_binding.res()
1332 });
1333 let res = binding.res();
1334 let has_ambiguity_error =
1335 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1336 if res == Res::Err || has_ambiguity_error {
1337 this.dcx()
1338 .span_delayed_bug(import.span, "some error happened for an import");
1339 return;
1340 }
1341 if let Some(initial_res) = initial_res {
1342 if res != initial_res && !this.issue_145575_hack_applied {
1343 ::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");
1344 }
1345 } else if this.privacy_errors.is_empty() {
1346 this.dcx()
1347 .create_err(CannotDetermineImportResolution { span: import.span })
1348 .emit();
1349 }
1350 }
1351 Err(..) => {
1352 }
1359 }
1360 });
1361
1362 if all_ns_err {
1363 let mut all_ns_failed = true;
1364 self.per_ns(|this, ns| {
1365 let binding = this.cm().resolve_ident_in_module(
1366 module,
1367 ident,
1368 ns,
1369 &import.parent_scope,
1370 Some(finalize),
1371 None,
1372 None,
1373 );
1374 if binding.is_ok() {
1375 all_ns_failed = false;
1376 }
1377 });
1378
1379 return if all_ns_failed {
1380 let names = match module {
1381 ModuleOrUniformRoot::Module(module) => {
1382 self.resolutions(module)
1383 .borrow()
1384 .iter()
1385 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1386 if i.name == ident.name {
1387 return None;
1388 } if i.name == kw::Underscore {
1390 return None;
1391 } let resolution = resolution.borrow();
1394 if let Some(name_binding) = resolution.best_decl() {
1395 match name_binding.kind {
1396 DeclKind::Import { source_decl, .. } => {
1397 match source_decl.kind {
1398 DeclKind::Def(Res::Err) => None,
1401 _ => Some(i.name),
1402 }
1403 }
1404 _ => Some(i.name),
1405 }
1406 } else if resolution.single_imports.is_empty() {
1407 None
1408 } else {
1409 Some(i.name)
1410 }
1411 })
1412 .collect()
1413 }
1414 _ => Vec::new(),
1415 };
1416
1417 let lev_suggestion =
1418 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1419 (
1420 ::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())],
1421 String::from("a similar name exists in the module"),
1422 Applicability::MaybeIncorrect,
1423 )
1424 });
1425
1426 let (suggestion, note) =
1427 match self.check_for_module_export_macro(import, module, ident) {
1428 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1429 _ => (lev_suggestion, None),
1430 };
1431
1432 let note = if self.tcx.features().import_trait_associated_functions()
1435 && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1436 && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1437 {
1438 note.or(Some(
1439 "cannot import inherent associated items, only trait associated items"
1440 .to_string(),
1441 ))
1442 } else {
1443 note
1444 };
1445
1446 let label = match module {
1447 ModuleOrUniformRoot::Module(module) => {
1448 let module_str = module_to_string(module);
1449 if let Some(module_str) = module_str {
1450 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1451 } else {
1452 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1453 }
1454 }
1455 _ => {
1456 if !ident.is_path_segment_keyword() {
1457 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1458 } else {
1459 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1462 }
1463 }
1464 };
1465
1466 let parent_suggestion =
1467 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1468
1469 Some(UnresolvedImportError {
1470 span: import.span,
1471 label: Some(label),
1472 note,
1473 suggestion,
1474 candidates: if !parent_suggestion.is_empty() {
1475 Some(parent_suggestion)
1476 } else {
1477 None
1478 },
1479 module: import.imported_module.get().and_then(|module| {
1480 if let ModuleOrUniformRoot::Module(m) = module {
1481 m.opt_def_id()
1482 } else {
1483 None
1484 }
1485 }),
1486 segment: Some(ident.name),
1487 on_unknown_attr: import.on_unknown_attr.clone(),
1488 })
1489 } else {
1490 None
1492 };
1493 }
1494
1495 let mut reexport_error = None;
1496 let mut any_successful_reexport = false;
1497 let mut crate_private_reexport = false;
1498 self.per_ns(|this, ns| {
1499 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1500 return;
1501 };
1502
1503 if import.vis.greater_than(binding.vis(), this.tcx) {
1504 reexport_error = Some((ns, binding));
1505 if let Visibility::Restricted(binding_def_id) = binding.vis()
1506 && binding_def_id.is_top_level_module()
1507 {
1508 crate_private_reexport = true;
1509 }
1510 } else {
1511 any_successful_reexport = true;
1512 }
1513 });
1514
1515 if !any_successful_reexport {
1517 let (ns, binding) = reexport_error.unwrap();
1518 if let Some(extern_crate_id) =
1519 pub_use_of_private_extern_crate_hack(import.summary(), binding)
1520 {
1521 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1522 self.lint_buffer.buffer_lint(
1523 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1524 import_id,
1525 import.span,
1526 crate::errors::PrivateExternCrateReexport {
1527 ident,
1528 sugg: extern_crate_sp.shrink_to_lo(),
1529 },
1530 );
1531 } else if ns == TypeNS {
1532 let err = if crate_private_reexport {
1533 self.dcx()
1534 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1535 } else {
1536 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1537 };
1538 err.emit();
1539 } else {
1540 let mut err = if crate_private_reexport {
1541 self.dcx()
1542 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1543 } else {
1544 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1545 };
1546
1547 match binding.kind {
1548 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1549 if self.get_macro_by_def_id(def_id).macro_rules =>
1551 {
1552 err.subdiagnostic( ConsiderAddingMacroExport {
1553 span: binding.span,
1554 });
1555 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1556 vis_span: import.vis_span,
1557 });
1558 }
1559 _ => {
1560 err.subdiagnostic( ConsiderMarkingAsPub {
1561 span: import.span,
1562 ident,
1563 });
1564 }
1565 }
1566 err.emit();
1567 }
1568 }
1569
1570 if import.module_path.len() <= 1 {
1571 let mut full_path = import.module_path.clone();
1574 full_path.push(Segment::from_ident(ident));
1575 self.per_ns(|this, ns| {
1576 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1577 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1578 }
1579 });
1580 }
1581
1582 self.per_ns(|this, ns| {
1586 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1587 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1588 }
1589 });
1590
1591 {
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:1591",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1591u32),
::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");
1592 None
1593 }
1594
1595 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1596 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1598 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1599 };
1600
1601 if source != target {
1603 return false;
1604 }
1605
1606 if import.parent_scope.expansion != LocalExpnId::ROOT {
1608 return false;
1609 }
1610
1611 if self.import_use_map.get(&import) == Some(&Used::Other)
1616 || self.effective_visibilities.is_exported(self.local_def_id(id))
1617 {
1618 return false;
1619 }
1620
1621 let mut is_redundant = true;
1622 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1623 self.per_ns(|this, ns| {
1624 let binding = decls[ns].get().decl().map(|b| b.import_source());
1625 if is_redundant && let Some(binding) = binding {
1626 if binding.res() == Res::Err {
1627 return;
1628 }
1629
1630 match this.cm().resolve_ident_in_scope_set(
1631 target,
1632 ScopeSet::All(ns),
1633 &import.parent_scope,
1634 None,
1635 decls[ns].get().decl(),
1636 None,
1637 ) {
1638 Ok(other_binding) => {
1639 is_redundant = binding.res() == other_binding.res()
1640 && !other_binding.is_ambiguity_recursive();
1641 if is_redundant {
1642 redundant_span[ns] =
1643 Some((other_binding.span, other_binding.is_import()));
1644 }
1645 }
1646 Err(_) => is_redundant = false,
1647 }
1648 }
1649 });
1650
1651 if is_redundant && !redundant_span.is_empty() {
1652 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1653 redundant_spans.sort();
1654 redundant_spans.dedup();
1655 self.lint_buffer.dyn_buffer_lint(
1656 REDUNDANT_IMPORTS,
1657 id,
1658 import.span,
1659 move |dcx, level| {
1660 let ident = source;
1661 let subs = redundant_spans
1662 .into_iter()
1663 .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1664 (false, true) => {
1665 errors::RedundantImportSub::ImportedHere { span, ident }
1666 }
1667 (false, false) => {
1668 errors::RedundantImportSub::DefinedHere { span, ident }
1669 }
1670 (true, true) => {
1671 errors::RedundantImportSub::ImportedPrelude { span, ident }
1672 }
1673 (true, false) => {
1674 errors::RedundantImportSub::DefinedPrelude { span, ident }
1675 }
1676 })
1677 .collect();
1678 errors::RedundantImport { subs, ident }.into_diag(dcx, level)
1679 },
1680 );
1681 return true;
1682 }
1683
1684 false
1685 }
1686
1687 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1688 let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1690
1691 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1692 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1693 return;
1694 };
1695
1696 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1697 feature_err(
1698 self.tcx.sess,
1699 sym::import_trait_associated_functions,
1700 import.span,
1701 "`use` associated items of traits is unstable",
1702 )
1703 .emit();
1704 }
1705
1706 if module == import.parent_scope.module {
1707 return;
1708 }
1709
1710 module.glob_importers.borrow_mut_unchecked().push(import);
1712
1713 let bindings = self
1716 .resolutions(module)
1717 .borrow()
1718 .iter()
1719 .filter_map(|(key, resolution)| {
1720 let resolution = resolution.borrow();
1721 resolution.determined_decl().map(|decl| (*key, decl, resolution.orig_ident_span))
1722 })
1723 .collect::<Vec<_>>();
1724 for (mut key, binding, orig_ident_span) in bindings {
1725 let scope =
1726 match key.ident.ctxt.update_unchecked(|ctxt| {
1727 ctxt.reverse_glob_adjust(module.expansion, import.span)
1728 }) {
1729 Some(Some(def)) => self.expn_def_scope(def),
1730 Some(None) => import.parent_scope.module,
1731 None => continue,
1732 };
1733 if self.is_accessible_from(binding.vis(), scope) {
1734 let import_decl = self.new_import_decl(binding, import);
1735 let warn_ambiguity = self
1736 .resolution(import.parent_scope.module, key)
1737 .and_then(|r| r.determined_decl())
1738 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1739 self.try_plant_decl_into_local_module(
1740 key.ident,
1741 orig_ident_span,
1742 key.ns,
1743 import_decl,
1744 warn_ambiguity,
1745 )
1746 .expect("planting a glob cannot fail");
1747 }
1748 }
1749
1750 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1752 }
1753
1754 fn finalize_resolutions_in(
1757 &self,
1758 module: LocalModule<'ra>,
1759 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1760 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1761 ) {
1762 *module.globs.borrow_mut(self) = Vec::new();
1764
1765 let Some(def_id) = module.opt_def_id() else { return };
1766
1767 let mut children = Vec::new();
1768 let mut ambig_children = Vec::new();
1769
1770 module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, binding| {
1771 let res = binding.res().expect_non_local();
1772 if res != def::Res::Err {
1773 let ident = ident.orig(orig_ident_span);
1774 let child =
1775 |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1776 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1777 let main = child(ambig_binding1.reexport_chain(this));
1778 let second = ModChild {
1779 ident,
1780 res: ambig_binding2.res().expect_non_local(),
1781 vis: ambig_binding2.vis(),
1782 reexport_chain: ambig_binding2.reexport_chain(this),
1783 };
1784 ambig_children.push(AmbigModChild { main, second })
1785 } else {
1786 children.push(child(binding.reexport_chain(this)));
1787 }
1788 }
1789 });
1790
1791 if !children.is_empty() {
1792 module_children.insert(def_id.expect_local(), children);
1793 }
1794 if !ambig_children.is_empty() {
1795 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1796 }
1797 }
1798}
1799
1800fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1801 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1802 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1803 if let Some(pos) = pos {
1804 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1805 names_to_string(names.iter().map(|ident| ident.name))
1806 } else {
1807 let names = if global { &names[1..] } else { names };
1808 if names.is_empty() {
1809 import_kind_to_string(import_kind)
1810 } else {
1811 ::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!(
1812 "{}::{}",
1813 names_to_string(names.iter().map(|ident| ident.name)),
1814 import_kind_to_string(import_kind),
1815 )
1816 }
1817 }
1818}
1819
1820fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1821 match import_kind {
1822 ImportKind::Single { source, .. } => source.to_string(),
1823 ImportKind::Glob { .. } => "*".to_string(),
1824 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1825 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1826 ImportKind::MacroExport => "#[macro_export]".to_string(),
1827 }
1828}