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