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 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));
374 let decl_vis = decl.vis();
375 if decl_vis.partial_cmp(import.vis, self.tcx) == Some(Ordering::Less)
376 && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
377 && pub_use_of_private_extern_crate_hack(import, decl).is_none()
378 {
379 decl_vis.expect_local()
382 } else {
383 import.vis
392 }
393 }
394
395 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
398 let vis = self.import_decl_vis(decl, import.summary());
399
400 if let ImportKind::Glob { ref max_vis, .. } = import.kind
401 && (vis == import.vis
402 || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
403 {
404 max_vis.set_unchecked(Some(vis))
405 }
406
407 self.arenas.alloc_decl(DeclData {
408 kind: DeclKind::Import { source_decl: decl, import },
409 ambiguity: CmCell::new(None),
410 warn_ambiguity: CmCell::new(false),
411 span: import.span,
412 vis: CmCell::new(vis.to_def_id()),
413 expansion: import.parent_scope.expansion,
414 parent_module: Some(import.parent_scope.module),
415 })
416 }
417
418 fn select_glob_decl(
421 &self,
422 old_glob_decl: Decl<'ra>,
423 glob_decl: Decl<'ra>,
424 warn_ambiguity: bool,
425 ) -> Decl<'ra> {
426 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
427 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());
428 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);
429 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
446 if deep_decl != glob_decl {
447 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);
449 if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
455 glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
457 }
458 if glob_decl.is_ambiguity_recursive() {
459 glob_decl.warn_ambiguity.set_unchecked(true);
460 }
461 glob_decl
462 } else if glob_decl.res() != old_glob_decl.res() {
463 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
464 old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
465 if warn_ambiguity {
466 old_glob_decl
467 } else {
468 self.arenas.alloc_decl((*old_glob_decl).clone())
472 }
473 } else if glob_decl.vis().greater_than(old_glob_decl.vis(), self.tcx) {
474 glob_decl
479 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
480 old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
482 old_glob_decl.warn_ambiguity.set_unchecked(true);
483 old_glob_decl
484 } else {
485 old_glob_decl
486 }
487 }
488
489 pub(crate) fn try_plant_decl_into_local_module(
492 &mut self,
493 ident: IdentKey,
494 orig_ident_span: Span,
495 ns: Namespace,
496 decl: Decl<'ra>,
497 warn_ambiguity: bool,
498 ) -> Result<(), Decl<'ra>> {
499 if !!decl.warn_ambiguity.get() {
::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
500 if !decl.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: decl.ambiguity.get().is_none()")
};assert!(decl.ambiguity.get().is_none());
501 let module = decl.parent_module.unwrap().expect_local();
502 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()));
503 let res = decl.res();
504 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
505 let key = BindingKey::new_disambiguated(ident, ns, || {
509 module.underscore_disambiguator.update_unchecked(|d| d + 1);
510 module.underscore_disambiguator.get()
511 });
512 self.update_local_resolution(
513 module,
514 key,
515 orig_ident_span,
516 warn_ambiguity,
517 |this, resolution| {
518 if decl.is_glob_import() {
519 resolution.glob_decl = Some(match resolution.glob_decl {
520 Some(old_decl) => this.select_glob_decl(
521 old_decl,
522 decl,
523 warn_ambiguity && resolution.non_glob_decl.is_none(),
524 ),
525 None => decl,
526 })
527 } else {
528 resolution.non_glob_decl = Some(match resolution.non_glob_decl {
529 Some(old_decl) => return Err(old_decl),
530 None => decl,
531 })
532 }
533
534 Ok(())
535 },
536 )
537 }
538
539 fn update_local_resolution<T, F>(
542 &mut self,
543 module: LocalModule<'ra>,
544 key: BindingKey,
545 orig_ident_span: Span,
546 warn_ambiguity: bool,
547 f: F,
548 ) -> T
549 where
550 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
551 {
552 let (binding, t, warn_ambiguity) = {
555 let resolution = &mut *self
556 .resolution_or_default(module.to_module(), key, orig_ident_span)
557 .borrow_mut_unchecked();
558 let old_decl = resolution.determined_decl();
559
560 let t = f(self, resolution);
561
562 if let Some(binding) = resolution.determined_decl()
563 && old_decl != Some(binding)
564 {
565 (binding, t, warn_ambiguity || old_decl.is_some())
566 } else {
567 return t;
568 }
569 };
570
571 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
572 return t;
573 };
574
575 for import in glob_importers.iter() {
577 let mut ident = key.ident;
578 let scope = match ident
579 .ctxt
580 .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
581 {
582 Some(Some(def)) => self.expn_def_scope(def),
583 Some(None) => import.parent_scope.module,
584 None => continue,
585 };
586 if self.is_accessible_from(binding.vis(), scope) {
587 let import_decl = self.new_import_decl(binding, *import);
588 self.try_plant_decl_into_local_module(
589 ident,
590 orig_ident_span,
591 key.ns,
592 import_decl,
593 warn_ambiguity,
594 )
595 .expect("planting a glob cannot fail");
596 }
597 }
598
599 t
600 }
601
602 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
605 if let ImportKind::Single { target, ref decls, .. } = import.kind {
606 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
607 return; }
609 let dummy_decl = self.dummy_decl;
610 let dummy_decl = self.new_import_decl(dummy_decl, import);
611 self.per_ns(|this, ns| {
612 let ident = IdentKey::new(target);
613 let _ = this.try_plant_decl_into_local_module(
615 ident,
616 target.span,
617 ns,
618 dummy_decl,
619 false,
620 );
621 if target.name != kw::Underscore {
623 let key = BindingKey::new(ident, ns);
624 this.update_local_resolution(
625 import.parent_scope.module.expect_local(),
626 key,
627 target.span,
628 false,
629 |_, resolution| {
630 resolution.single_imports.swap_remove(&import);
631 },
632 )
633 }
634 });
635 self.record_use(target, dummy_decl, Used::Other);
636 } else if import.imported_module.get().is_none() {
637 self.import_use_map.insert(import, Used::Other);
638 if let Some(id) = import.id() {
639 self.used_imports.insert(id);
640 }
641 }
642 }
643
644 pub(crate) fn resolve_imports(&mut self) {
655 let mut prev_indeterminate_count = usize::MAX;
656 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
657 while indeterminate_count < prev_indeterminate_count {
658 prev_indeterminate_count = indeterminate_count;
659 indeterminate_count = 0;
660 self.assert_speculative = true;
661 for import in mem::take(&mut self.indeterminate_imports) {
662 let import_indeterminate_count = self.cm().resolve_import(import);
663 indeterminate_count += import_indeterminate_count;
664 match import_indeterminate_count {
665 0 => self.determined_imports.push(import),
666 _ => self.indeterminate_imports.push(import),
667 }
668 }
669 self.assert_speculative = false;
670 }
671 }
672
673 pub(crate) fn finalize_imports(&mut self) {
674 let mut module_children = Default::default();
675 let mut ambig_module_children = Default::default();
676 for module in &self.local_modules {
677 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
678 }
679 self.module_children = module_children;
680 self.ambig_module_children = ambig_module_children;
681
682 let mut seen_spans = FxHashSet::default();
683 let mut errors = ::alloc::vec::Vec::new()vec![];
684 let mut prev_root_id: NodeId = NodeId::ZERO;
685 let determined_imports = mem::take(&mut self.determined_imports);
686 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
687
688 let mut glob_error = false;
689 for (is_indeterminate, import) in determined_imports
690 .iter()
691 .map(|i| (false, i))
692 .chain(indeterminate_imports.iter().map(|i| (true, i)))
693 {
694 let unresolved_import_error = self.finalize_import(*import);
695 self.import_dummy_binding(*import, is_indeterminate);
698
699 let Some(err) = unresolved_import_error else { continue };
700
701 glob_error |= import.is_glob();
702
703 if let ImportKind::Single { source, ref decls, .. } = import.kind
704 && source.name == kw::SelfLower
705 && let PendingDecl::Ready(None) = decls.value_ns.get()
707 {
708 continue;
709 }
710
711 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
712 {
713 self.throw_unresolved_import_error(errors, glob_error);
716 errors = ::alloc::vec::Vec::new()vec![];
717 }
718 if seen_spans.insert(err.span) {
719 errors.push((*import, err));
720 prev_root_id = import.root_id;
721 }
722 }
723
724 if self.cstore().had_extern_crate_load_failure() {
725 self.tcx.sess.dcx().abort_if_errors();
726 }
727
728 if !errors.is_empty() {
729 self.throw_unresolved_import_error(errors, glob_error);
730 return;
731 }
732
733 for import in &indeterminate_imports {
734 let path = import_path_to_string(
735 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
736 &import.kind,
737 import.span,
738 );
739 if path.contains("::") {
742 let err = UnresolvedImportError {
743 span: import.span,
744 label: None,
745 note: None,
746 suggestion: None,
747 candidates: None,
748 segment: None,
749 module: None,
750 on_unknown_attr: import.on_unknown_attr.clone(),
751 };
752 errors.push((*import, err))
753 }
754 }
755
756 if !errors.is_empty() {
757 self.throw_unresolved_import_error(errors, glob_error);
758 }
759 }
760
761 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
762 for module in &self.local_modules {
763 for (key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
764 let resolution = resolution.borrow();
765 let Some(binding) = resolution.best_decl() else { continue };
766
767 if let DeclKind::Import { import, .. } = binding.kind
768 && let Some(amb_binding) = binding.ambiguity.get()
769 && binding.res() != Res::Err
770 && exported_ambiguities.contains(&binding)
771 {
772 self.lint_buffer.buffer_lint(
773 AMBIGUOUS_GLOB_REEXPORTS,
774 import.root_id,
775 import.root_span,
776 errors::AmbiguousGlobReexports {
777 name: key.ident.name.to_string(),
778 namespace: key.ns.descr().to_string(),
779 first_reexport: import.root_span,
780 duplicate_reexport: amb_binding.span,
781 },
782 );
783 }
784
785 if let Some(glob_decl) = resolution.glob_decl
786 && resolution.non_glob_decl.is_some()
787 {
788 if binding.res() != Res::Err
789 && glob_decl.res() != Res::Err
790 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
791 && let Some(glob_import_id) = glob_import.id()
792 && let glob_import_def_id = self.local_def_id(glob_import_id)
793 && self.effective_visibilities.is_exported(glob_import_def_id)
794 && glob_decl.vis().is_public()
795 && !binding.vis().is_public()
796 {
797 let binding_id = match binding.kind {
798 DeclKind::Def(res) => {
799 Some(self.def_id_to_node_id(res.def_id().expect_local()))
800 }
801 DeclKind::Import { import, .. } => import.id(),
802 };
803 if let Some(binding_id) = binding_id {
804 self.lint_buffer.buffer_lint(
805 HIDDEN_GLOB_REEXPORTS,
806 binding_id,
807 binding.span,
808 errors::HiddenGlobReexports {
809 name: key.ident.name.to_string(),
810 namespace: key.ns.descr().to_owned(),
811 glob_reexport: glob_decl.span,
812 private_item: binding.span,
813 },
814 );
815 }
816 }
817 }
818
819 if let DeclKind::Import { import, .. } = binding.kind
820 && let Some(binding_id) = import.id()
821 && let import_def_id = self.local_def_id(binding_id)
822 && self.effective_visibilities.is_exported(import_def_id)
823 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
824 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
825 && !reexported_def_id.is_local()
826 && self.tcx.is_private_dep(reexported_def_id.krate)
827 {
828 self.lint_buffer.buffer_lint(
829 EXPORTED_PRIVATE_DEPENDENCIES,
830 binding_id,
831 binding.span,
832 crate::errors::ReexportPrivateDependency {
833 name: key.ident.name,
834 kind: binding.res().descr(),
835 krate: self.tcx.crate_name(reexported_def_id.krate),
836 },
837 );
838 }
839 }
840 }
841 }
842
843 fn throw_unresolved_import_error(
844 &mut self,
845 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
846 glob_error: bool,
847 ) {
848 errors.retain(|(_import, err)| match err.module {
849 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
851 _ => err.segment != Some(kw::Underscore),
854 });
855 if errors.is_empty() {
856 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
857 return;
858 }
859
860 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
861
862 let paths = errors
863 .iter()
864 .map(|(import, err)| {
865 let path = import_path_to_string(
866 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
867 &import.kind,
868 err.span,
869 );
870 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
871 })
872 .collect::<Vec<_>>();
873 let default_message =
874 ::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(", "),);
875 let (message, label, notes) =
876 if let Some(directive) = errors[0].1.on_unknown_attr.as_ref().map(|a| &a.directive) {
878 let this = errors.iter().map(|(_import, err)| {
879
880 err.segment.unwrap_or(kw::Underscore)
882 }).join(", ");
883
884 let args = FormatArgs {
885 this,
886 ..
887 };
888 let CustomDiagnostic { message, label, notes, .. } = directive.eval(None, &args);
889
890 (message, label, notes)
891 } else {
892 (None, None, Vec::new())
893 };
894 let has_custom_message = message.is_some();
895 let message = message.as_deref().unwrap_or(default_message.as_str());
896
897 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}");
898 if has_custom_message {
899 diag.note(default_message);
900 }
901
902 if !notes.is_empty() {
903 for note in notes {
904 diag.note(note);
905 }
906 } else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
907 errors.iter().last()
908 {
909 diag.note(note.clone());
910 }
911
912 const MAX_LABEL_COUNT: usize = 10;
914
915 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
916 if let Some(label) = &label {
917 diag.span_label(err.span, label.clone());
918 } else if let Some(label) = &err.label {
919 diag.span_label(err.span, label.clone());
920 }
921
922 if let Some((suggestions, msg, applicability)) = err.suggestion {
923 if suggestions.is_empty() {
924 diag.help(msg);
925 continue;
926 }
927 diag.multipart_suggestion(msg, suggestions, applicability);
928 }
929
930 if let Some(candidates) = &err.candidates {
931 match &import.kind {
932 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
933 self.tcx,
934 &mut diag,
935 Some(err.span),
936 candidates,
937 DiagMode::Import { append: false, unresolved_import: true },
938 (source != target)
939 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
940 .as_deref()
941 .unwrap_or(""),
942 ),
943 ImportKind::Single { nested: true, source, target, .. } => {
944 import_candidates(
945 self.tcx,
946 &mut diag,
947 None,
948 candidates,
949 DiagMode::Normal,
950 (source != target)
951 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
952 .as_deref()
953 .unwrap_or(""),
954 );
955 }
956 _ => {}
957 }
958 }
959
960 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
961 && let Some(segment) = err.segment
962 && let Some(module) = err.module
963 {
964 self.find_cfg_stripped(&mut diag, &segment, module)
965 }
966 }
967
968 let guar = diag.emit();
969 if glob_error {
970 self.glob_error = Some(guar);
971 }
972 }
973
974 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
981 {
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:981",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(981u32),
::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!(
982 "(resolving import for module) resolving import `{}::...` in `{}`",
983 Segment::names_to_string(&import.module_path),
984 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
985 );
986 let module = if let Some(module) = import.imported_module.get() {
987 module
988 } else {
989 let path_res = self.reborrow().maybe_resolve_path(
990 &import.module_path,
991 None,
992 &import.parent_scope,
993 Some(import),
994 );
995
996 match path_res {
997 PathResult::Module(module) => module,
998 PathResult::Indeterminate => return 3,
999 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
1000 }
1001 };
1002
1003 import.imported_module.set_unchecked(Some(module));
1004 let (source, target, bindings) = match import.kind {
1005 ImportKind::Single { source, target, ref decls, .. } => (source, target, decls),
1006 ImportKind::Glob { .. } => {
1007 self.get_mut_unchecked().resolve_glob_import(import);
1008 return 0;
1009 }
1010 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1011 };
1012
1013 let mut indeterminate_count = 0;
1014 self.per_ns_cm(|mut this, ns| {
1015 if bindings[ns].get() != PendingDecl::Pending {
1016 return;
1017 };
1018 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1019 module,
1020 source,
1021 ns,
1022 &import.parent_scope,
1023 Some(import),
1024 );
1025 let parent = import.parent_scope.module;
1026 let binding = match binding_result {
1027 Ok(binding) => {
1028 if binding.is_assoc_item()
1029 && !this.tcx.features().import_trait_associated_functions()
1030 {
1031 feature_err(
1032 this.tcx.sess,
1033 sym::import_trait_associated_functions,
1034 import.span,
1035 "`use` associated items of traits is unstable",
1036 )
1037 .emit();
1038 }
1039 let import_decl = this.new_import_decl(binding, import);
1041 this.get_mut_unchecked().plant_decl_into_local_module(
1042 IdentKey::new(target),
1043 target.span,
1044 ns,
1045 import_decl,
1046 );
1047 PendingDecl::Ready(Some(import_decl))
1048 }
1049 Err(Determinacy::Determined) => {
1050 if target.name != kw::Underscore {
1052 let key = BindingKey::new(IdentKey::new(target), ns);
1053 this.get_mut_unchecked().update_local_resolution(
1054 parent.expect_local(),
1055 key,
1056 target.span,
1057 false,
1058 |_, resolution| {
1059 resolution.single_imports.swap_remove(&import);
1060 },
1061 );
1062 }
1063 PendingDecl::Ready(None)
1064 }
1065 Err(Determinacy::Undetermined) => {
1066 indeterminate_count += 1;
1067 PendingDecl::Pending
1068 }
1069 };
1070 bindings[ns].set_unchecked(binding);
1071 });
1072
1073 indeterminate_count
1074 }
1075
1076 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1081 let ignore_decl = match &import.kind {
1082 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1083 _ => None,
1084 };
1085 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1086 errors.iter().filter(|error| error.warning.is_none()).count()
1087 };
1088 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1089 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1090
1091 let privacy_errors_len = self.privacy_errors.len();
1093
1094 let path_res = self.cm().resolve_path(
1095 &import.module_path,
1096 None,
1097 &import.parent_scope,
1098 Some(finalize),
1099 ignore_decl,
1100 Some(import),
1101 );
1102
1103 let no_ambiguity =
1104 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1105
1106 let module = match path_res {
1107 PathResult::Module(module) => {
1108 if let Some(initial_module) = import.imported_module.get() {
1110 if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1111 ::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");
1112 }
1113 } else if self.privacy_errors.is_empty() {
1114 self.dcx()
1115 .create_err(CannotDetermineImportResolution { span: import.span })
1116 .emit();
1117 }
1118
1119 module
1120 }
1121 PathResult::Failed {
1122 is_error_from_last_segment: false,
1123 span,
1124 segment_name,
1125 label,
1126 suggestion,
1127 module,
1128 error_implied_by_parse_error: _,
1129 message,
1130 note: _,
1131 } => {
1132 if no_ambiguity {
1133 if !self.issue_145575_hack_applied {
1134 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());
1135 }
1136 self.report_error(
1137 span,
1138 ResolutionError::FailedToResolve {
1139 segment: segment_name,
1140 label,
1141 suggestion,
1142 module,
1143 message,
1144 },
1145 );
1146 }
1147 return None;
1148 }
1149 PathResult::Failed {
1150 is_error_from_last_segment: true,
1151 span,
1152 label,
1153 suggestion,
1154 module,
1155 segment_name,
1156 note,
1157 ..
1158 } => {
1159 if no_ambiguity {
1160 if !self.issue_145575_hack_applied {
1161 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());
1162 }
1163 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1164 m.opt_def_id()
1165 } else {
1166 None
1167 };
1168 let err = match self
1169 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1170 {
1171 Some((suggestion, note)) => UnresolvedImportError {
1172 span,
1173 label: None,
1174 note,
1175 suggestion: Some((
1176 ::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))],
1177 String::from("a similar path exists"),
1178 Applicability::MaybeIncorrect,
1179 )),
1180 candidates: None,
1181 segment: Some(segment_name),
1182 module,
1183 on_unknown_attr: import.on_unknown_attr.clone(),
1184 },
1185 None => UnresolvedImportError {
1186 span,
1187 label: Some(label),
1188 note,
1189 suggestion,
1190 candidates: None,
1191 segment: Some(segment_name),
1192 module,
1193 on_unknown_attr: import.on_unknown_attr.clone(),
1194 },
1195 };
1196 return Some(err);
1197 }
1198 return None;
1199 }
1200 PathResult::NonModule(partial_res) => {
1201 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1202 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());
1204 }
1205 return None;
1207 }
1208 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1209 };
1210
1211 let (ident, target, bindings, import_id) = match import.kind {
1212 ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1213 ImportKind::Glob { ref max_vis, id } => {
1214 if import.module_path.len() <= 1 {
1215 let mut full_path = import.module_path.clone();
1218 full_path.push(Segment::from_ident(Ident::dummy()));
1219 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1220 }
1221
1222 if let ModuleOrUniformRoot::Module(module) = module
1223 && module == import.parent_scope.module
1224 {
1225 return Some(UnresolvedImportError {
1227 span: import.span,
1228 label: Some(String::from("cannot glob-import a module into itself")),
1229 note: None,
1230 suggestion: None,
1231 candidates: None,
1232 segment: None,
1233 module: None,
1234 on_unknown_attr: None,
1235 });
1236 }
1237 if let Some(max_vis) = max_vis.get()
1238 && import.vis.greater_than(max_vis, self.tcx)
1239 {
1240 let def_id = self.local_def_id(id);
1241 self.lint_buffer.buffer_lint(
1242 UNUSED_IMPORTS,
1243 id,
1244 import.span,
1245 crate::errors::RedundantImportVisibility {
1246 span: import.span,
1247 help: (),
1248 max_vis: max_vis.to_string(def_id, self.tcx),
1249 import_vis: import.vis.to_string(def_id, self.tcx),
1250 },
1251 );
1252 }
1253 return None;
1254 }
1255 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1256 };
1257
1258 if self.privacy_errors.len() != privacy_errors_len {
1259 let mut path = import.module_path.clone();
1262 path.push(Segment::from_ident(ident));
1263 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1264 &path,
1265 None,
1266 &import.parent_scope,
1267 Some(finalize),
1268 ignore_decl,
1269 None,
1270 ) {
1271 let res = module.res().map(|r| (r, ident));
1272 for error in &mut self.privacy_errors[privacy_errors_len..] {
1273 error.outermost_res = res;
1274 }
1275 }
1276 }
1277
1278 let mut all_ns_err = true;
1279 self.per_ns(|this, ns| {
1280 let binding = this.cm().resolve_ident_in_module(
1281 module,
1282 ident,
1283 ns,
1284 &import.parent_scope,
1285 Some(Finalize {
1286 report_private: false,
1287 import: Some(import.summary()),
1288 ..finalize
1289 }),
1290 bindings[ns].get().decl(),
1291 Some(import),
1292 );
1293
1294 match binding {
1295 Ok(binding) => {
1296 let initial_res = bindings[ns].get().decl().map(|binding| {
1298 let initial_binding = binding.import_source();
1299 all_ns_err = false;
1300 if target.name == kw::Underscore
1301 && initial_binding.is_extern_crate()
1302 && !initial_binding.is_import()
1303 {
1304 let used = if import.module_path.is_empty() {
1305 Used::Scope
1306 } else {
1307 Used::Other
1308 };
1309 this.record_use(ident, binding, used);
1310 }
1311 initial_binding.res()
1312 });
1313 let res = binding.res();
1314 let has_ambiguity_error =
1315 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1316 if res == Res::Err || has_ambiguity_error {
1317 this.dcx()
1318 .span_delayed_bug(import.span, "some error happened for an import");
1319 return;
1320 }
1321 if let Some(initial_res) = initial_res {
1322 if res != initial_res && !this.issue_145575_hack_applied {
1323 ::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");
1324 }
1325 } else if this.privacy_errors.is_empty() {
1326 this.dcx()
1327 .create_err(CannotDetermineImportResolution { span: import.span })
1328 .emit();
1329 }
1330 }
1331 Err(..) => {
1332 }
1339 }
1340 });
1341
1342 if all_ns_err {
1343 let mut all_ns_failed = true;
1344 self.per_ns(|this, ns| {
1345 let binding = this.cm().resolve_ident_in_module(
1346 module,
1347 ident,
1348 ns,
1349 &import.parent_scope,
1350 Some(finalize),
1351 None,
1352 None,
1353 );
1354 if binding.is_ok() {
1355 all_ns_failed = false;
1356 }
1357 });
1358
1359 return if all_ns_failed {
1360 let names = match module {
1361 ModuleOrUniformRoot::Module(module) => {
1362 self.resolutions(module)
1363 .borrow()
1364 .iter()
1365 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1366 if i.name == ident.name {
1367 return None;
1368 } if i.name == kw::Underscore {
1370 return None;
1371 } let resolution = resolution.borrow();
1374 if let Some(name_binding) = resolution.best_decl() {
1375 match name_binding.kind {
1376 DeclKind::Import { source_decl, .. } => {
1377 match source_decl.kind {
1378 DeclKind::Def(Res::Err) => None,
1381 _ => Some(i.name),
1382 }
1383 }
1384 _ => Some(i.name),
1385 }
1386 } else if resolution.single_imports.is_empty() {
1387 None
1388 } else {
1389 Some(i.name)
1390 }
1391 })
1392 .collect()
1393 }
1394 _ => Vec::new(),
1395 };
1396
1397 let lev_suggestion =
1398 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1399 (
1400 ::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())],
1401 String::from("a similar name exists in the module"),
1402 Applicability::MaybeIncorrect,
1403 )
1404 });
1405
1406 let (suggestion, note) =
1407 match self.check_for_module_export_macro(import, module, ident) {
1408 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1409 _ => (lev_suggestion, None),
1410 };
1411
1412 let note = if self.tcx.features().import_trait_associated_functions()
1415 && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1416 && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1417 {
1418 note.or(Some(
1419 "cannot import inherent associated items, only trait associated items"
1420 .to_string(),
1421 ))
1422 } else {
1423 note
1424 };
1425
1426 let label = match module {
1427 ModuleOrUniformRoot::Module(module) => {
1428 let module_str = module_to_string(module);
1429 if let Some(module_str) = module_str {
1430 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1431 } else {
1432 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1433 }
1434 }
1435 _ => {
1436 if !ident.is_path_segment_keyword() {
1437 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1438 } else {
1439 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1442 }
1443 }
1444 };
1445
1446 let parent_suggestion =
1447 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1448
1449 Some(UnresolvedImportError {
1450 span: import.span,
1451 label: Some(label),
1452 note,
1453 suggestion,
1454 candidates: if !parent_suggestion.is_empty() {
1455 Some(parent_suggestion)
1456 } else {
1457 None
1458 },
1459 module: import.imported_module.get().and_then(|module| {
1460 if let ModuleOrUniformRoot::Module(m) = module {
1461 m.opt_def_id()
1462 } else {
1463 None
1464 }
1465 }),
1466 segment: Some(ident.name),
1467 on_unknown_attr: import.on_unknown_attr.clone(),
1468 })
1469 } else {
1470 None
1472 };
1473 }
1474
1475 let mut reexport_error = None;
1476 let mut any_successful_reexport = false;
1477 let mut crate_private_reexport = false;
1478 self.per_ns(|this, ns| {
1479 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1480 return;
1481 };
1482
1483 if import.vis.greater_than(binding.vis(), this.tcx) {
1484 reexport_error = Some((ns, binding));
1485 if let Visibility::Restricted(binding_def_id) = binding.vis()
1486 && binding_def_id.is_top_level_module()
1487 {
1488 crate_private_reexport = true;
1489 }
1490 } else {
1491 any_successful_reexport = true;
1492 }
1493 });
1494
1495 if !any_successful_reexport {
1497 let (ns, binding) = reexport_error.unwrap();
1498 if let Some(extern_crate_id) =
1499 pub_use_of_private_extern_crate_hack(import.summary(), binding)
1500 {
1501 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1502 self.lint_buffer.buffer_lint(
1503 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1504 import_id,
1505 import.span,
1506 crate::errors::PrivateExternCrateReexport {
1507 ident,
1508 sugg: extern_crate_sp.shrink_to_lo(),
1509 },
1510 );
1511 } else if ns == TypeNS {
1512 let err = if crate_private_reexport {
1513 self.dcx()
1514 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1515 } else {
1516 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1517 };
1518 err.emit();
1519 } else {
1520 let mut err = if crate_private_reexport {
1521 self.dcx()
1522 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1523 } else {
1524 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1525 };
1526
1527 match binding.kind {
1528 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1529 if self.get_macro_by_def_id(def_id).macro_rules =>
1531 {
1532 err.subdiagnostic( ConsiderAddingMacroExport {
1533 span: binding.span,
1534 });
1535 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1536 vis_span: import.vis_span,
1537 });
1538 }
1539 _ => {
1540 err.subdiagnostic( ConsiderMarkingAsPub {
1541 span: import.span,
1542 ident,
1543 });
1544 }
1545 }
1546 err.emit();
1547 }
1548 }
1549
1550 if import.module_path.len() <= 1 {
1551 let mut full_path = import.module_path.clone();
1554 full_path.push(Segment::from_ident(ident));
1555 self.per_ns(|this, ns| {
1556 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1557 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1558 }
1559 });
1560 }
1561
1562 self.per_ns(|this, ns| {
1566 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1567 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1568 }
1569 });
1570
1571 {
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:1571",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1571u32),
::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");
1572 None
1573 }
1574
1575 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1576 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1578 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1579 };
1580
1581 if source != target {
1583 return false;
1584 }
1585
1586 if import.parent_scope.expansion != LocalExpnId::ROOT {
1588 return false;
1589 }
1590
1591 if self.import_use_map.get(&import) == Some(&Used::Other)
1596 || self.effective_visibilities.is_exported(self.local_def_id(id))
1597 {
1598 return false;
1599 }
1600
1601 let mut is_redundant = true;
1602 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1603 self.per_ns(|this, ns| {
1604 let binding = decls[ns].get().decl().map(|b| b.import_source());
1605 if is_redundant && let Some(binding) = binding {
1606 if binding.res() == Res::Err {
1607 return;
1608 }
1609
1610 match this.cm().resolve_ident_in_scope_set(
1611 target,
1612 ScopeSet::All(ns),
1613 &import.parent_scope,
1614 None,
1615 decls[ns].get().decl(),
1616 None,
1617 ) {
1618 Ok(other_binding) => {
1619 is_redundant = binding.res() == other_binding.res()
1620 && !other_binding.is_ambiguity_recursive();
1621 if is_redundant {
1622 redundant_span[ns] =
1623 Some((other_binding.span, other_binding.is_import()));
1624 }
1625 }
1626 Err(_) => is_redundant = false,
1627 }
1628 }
1629 });
1630
1631 if is_redundant && !redundant_span.is_empty() {
1632 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1633 redundant_spans.sort();
1634 redundant_spans.dedup();
1635 self.lint_buffer.dyn_buffer_lint(
1636 REDUNDANT_IMPORTS,
1637 id,
1638 import.span,
1639 move |dcx, level| {
1640 let ident = source;
1641 let subs = redundant_spans
1642 .into_iter()
1643 .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1644 (false, true) => {
1645 errors::RedundantImportSub::ImportedHere { span, ident }
1646 }
1647 (false, false) => {
1648 errors::RedundantImportSub::DefinedHere { span, ident }
1649 }
1650 (true, true) => {
1651 errors::RedundantImportSub::ImportedPrelude { span, ident }
1652 }
1653 (true, false) => {
1654 errors::RedundantImportSub::DefinedPrelude { span, ident }
1655 }
1656 })
1657 .collect();
1658 errors::RedundantImport { subs, ident }.into_diag(dcx, level)
1659 },
1660 );
1661 return true;
1662 }
1663
1664 false
1665 }
1666
1667 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1668 let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1670
1671 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1672 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1673 return;
1674 };
1675
1676 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1677 feature_err(
1678 self.tcx.sess,
1679 sym::import_trait_associated_functions,
1680 import.span,
1681 "`use` associated items of traits is unstable",
1682 )
1683 .emit();
1684 }
1685
1686 if module == import.parent_scope.module {
1687 return;
1688 }
1689
1690 module.glob_importers.borrow_mut_unchecked().push(import);
1692
1693 let bindings = self
1696 .resolutions(module)
1697 .borrow()
1698 .iter()
1699 .filter_map(|(key, resolution)| {
1700 let resolution = resolution.borrow();
1701 resolution.determined_decl().map(|decl| (*key, decl, resolution.orig_ident_span))
1702 })
1703 .collect::<Vec<_>>();
1704 for (mut key, binding, orig_ident_span) in bindings {
1705 let scope =
1706 match key.ident.ctxt.update_unchecked(|ctxt| {
1707 ctxt.reverse_glob_adjust(module.expansion, import.span)
1708 }) {
1709 Some(Some(def)) => self.expn_def_scope(def),
1710 Some(None) => import.parent_scope.module,
1711 None => continue,
1712 };
1713 if self.is_accessible_from(binding.vis(), scope) {
1714 let import_decl = self.new_import_decl(binding, import);
1715 let warn_ambiguity = self
1716 .resolution(import.parent_scope.module, key)
1717 .and_then(|r| r.determined_decl())
1718 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1719 self.try_plant_decl_into_local_module(
1720 key.ident,
1721 orig_ident_span,
1722 key.ns,
1723 import_decl,
1724 warn_ambiguity,
1725 )
1726 .expect("planting a glob cannot fail");
1727 }
1728 }
1729
1730 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1732 }
1733
1734 fn finalize_resolutions_in(
1737 &self,
1738 module: LocalModule<'ra>,
1739 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1740 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1741 ) {
1742 *module.globs.borrow_mut(self) = Vec::new();
1744
1745 let Some(def_id) = module.opt_def_id() else { return };
1746
1747 let mut children = Vec::new();
1748 let mut ambig_children = Vec::new();
1749
1750 module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, binding| {
1751 let res = binding.res().expect_non_local();
1752 if res != def::Res::Err {
1753 let ident = ident.orig(orig_ident_span);
1754 let child =
1755 |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1756 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1757 let main = child(ambig_binding1.reexport_chain(this));
1758 let second = ModChild {
1759 ident,
1760 res: ambig_binding2.res().expect_non_local(),
1761 vis: ambig_binding2.vis(),
1762 reexport_chain: ambig_binding2.reexport_chain(this),
1763 };
1764 ambig_children.push(AmbigModChild { main, second })
1765 } else {
1766 children.push(child(binding.reexport_chain(this)));
1767 }
1768 }
1769 });
1770
1771 if !children.is_empty() {
1772 module_children.insert(def_id.expect_local(), children);
1773 }
1774 if !ambig_children.is_empty() {
1775 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1776 }
1777 }
1778}
1779
1780fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1781 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1782 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1783 if let Some(pos) = pos {
1784 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1785 names_to_string(names.iter().map(|ident| ident.name))
1786 } else {
1787 let names = if global { &names[1..] } else { names };
1788 if names.is_empty() {
1789 import_kind_to_string(import_kind)
1790 } else {
1791 ::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!(
1792 "{}::{}",
1793 names_to_string(names.iter().map(|ident| ident.name)),
1794 import_kind_to_string(import_kind),
1795 )
1796 }
1797 }
1798}
1799
1800fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1801 match import_kind {
1802 ImportKind::Single { source, .. } => source.to_string(),
1803 ImportKind::Glob { .. } => "*".to_string(),
1804 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1805 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1806 ImportKind::MacroExport => "#[macro_export]".to_string(),
1807 }
1808}