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
60enum ImportResolutionKind<'ra> {
61 Single(PerNS<PendingDecl<'ra>>),
62 Glob(Vec<(Decl<'ra>, BindingKey, Span )>),
63}
64
65struct ImportResolution<'ra> {
66 kind: ImportResolutionKind<'ra>,
67 imported_module: ModuleOrUniformRoot<'ra>,
68}
69
70impl<'ra> PendingDecl<'ra> {
71 pub(crate) fn decl(self) -> Option<Decl<'ra>> {
72 match self {
73 PendingDecl::Ready(decl) => decl,
74 PendingDecl::Pending => None,
75 }
76 }
77}
78
79#[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)]
81pub(crate) enum ImportKind<'ra> {
82 Single {
83 source: Ident,
85 target: Ident,
88 decls: PerNS<CmCell<PendingDecl<'ra>>>,
90 nested: bool,
92 id: NodeId,
104 def_id: LocalDefId,
105 },
106 Glob {
107 max_vis: CmCell<Option<Visibility>>,
110 id: NodeId,
111 def_id: LocalDefId,
112 },
113 ExternCrate {
114 source: Option<Symbol>,
115 target: Ident,
116 id: NodeId,
117 def_id: LocalDefId,
118 },
119 MacroUse {
120 warn_private: bool,
123 },
124 MacroExport,
125}
126
127impl<'ra> std::fmt::Debug for ImportKind<'ra> {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 use ImportKind::*;
132 match self {
133 Single { source, target, decls, nested, id, def_id } => f
134 .debug_struct("Single")
135 .field("source", source)
136 .field("target", target)
137 .field(
139 "decls",
140 &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!("..")format_args!(".."))),
141 )
142 .field("nested", nested)
143 .field("id", id)
144 .field("def_id", def_id)
145 .finish(),
146 Glob { max_vis, id, def_id } => f
147 .debug_struct("Glob")
148 .field("max_vis", max_vis)
149 .field("id", id)
150 .field("def_id", def_id)
151 .finish(),
152 ExternCrate { source, target, id, def_id } => f
153 .debug_struct("ExternCrate")
154 .field("source", source)
155 .field("target", target)
156 .field("id", id)
157 .field("def_id", def_id)
158 .finish(),
159 MacroUse { warn_private } => {
160 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
161 }
162 MacroExport => f.debug_struct("MacroExport").finish(),
163 }
164 }
165}
166
167#[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)]
168pub(crate) struct OnUnknownData {
169 directive: Box<Directive>,
170}
171
172impl OnUnknownData {
173 pub(crate) fn from_attrs<'tcx>(tcx: TyCtxt<'tcx>, item: &Item) -> Option<OnUnknownData> {
174 if tcx.features().diagnostic_on_unknown()
175 && let Some(Attribute::Parsed(AttributeKind::OnUnknown { directive, .. })) =
176 AttributeParser::parse_limited(
177 tcx.sess,
178 &item.attrs,
179 &[sym::diagnostic, sym::on_unknown],
180 )
181 {
182 Some(Self { directive: directive? })
183 } else {
184 None
185 }
186 }
187}
188
189#[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)]
191pub(crate) struct ImportData<'ra> {
192 pub kind: ImportKind<'ra>,
193
194 pub root_id: NodeId,
204
205 pub use_span: Span,
207
208 pub use_span_with_attributes: Span,
210
211 pub has_attributes: bool,
213
214 pub span: Span,
216
217 pub root_span: Span,
219
220 pub parent_scope: ParentScope<'ra>,
221 pub module_path: Vec<Segment>,
222 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
231 pub vis: Visibility,
232
233 pub vis_span: Span,
235
236 pub on_unknown_attr: Option<OnUnknownData>,
242}
243
244pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
247
248impl std::hash::Hash for ImportData<'_> {
253 fn hash<H>(&self, _: &mut H)
254 where
255 H: std::hash::Hasher,
256 {
257 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
258 }
259}
260
261impl<'ra> ImportData<'ra> {
262 pub(crate) fn is_glob(&self) -> bool {
263 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Glob { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Glob { .. })
264 }
265
266 pub(crate) fn is_nested(&self) -> bool {
267 match self.kind {
268 ImportKind::Single { nested, .. } => nested,
269 _ => false,
270 }
271 }
272
273 pub(crate) fn id(&self) -> Option<NodeId> {
274 match self.kind {
275 ImportKind::Single { id, .. }
276 | ImportKind::Glob { id, .. }
277 | ImportKind::ExternCrate { id, .. } => Some(id),
278 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
279 }
280 }
281
282 pub(crate) fn def_id(&self) -> Option<LocalDefId> {
283 match self.kind {
284 ImportKind::Single { def_id, .. }
285 | ImportKind::Glob { def_id, .. }
286 | ImportKind::ExternCrate { def_id, .. } => Some(def_id),
287 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
288 }
289 }
290
291 pub(crate) fn simplify(&self) -> Reexport {
292 match self.kind {
293 ImportKind::Single { def_id, .. } => Reexport::Single(def_id.to_def_id()),
294 ImportKind::Glob { def_id, .. } => Reexport::Glob(def_id.to_def_id()),
295 ImportKind::ExternCrate { def_id, .. } => Reexport::ExternCrate(def_id.to_def_id()),
296 ImportKind::MacroUse { .. } => Reexport::MacroUse,
297 ImportKind::MacroExport => Reexport::MacroExport,
298 }
299 }
300
301 fn summary(&self) -> ImportSummary {
302 ImportSummary {
303 vis: self.vis,
304 nearest_parent_mod: self.parent_scope.module.nearest_parent_mod().expect_local(),
305 is_single: #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Single { .. }),
306 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 }),
307 span: self.span,
308 }
309 }
310}
311
312#[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)]
314pub(crate) struct NameResolution<'ra> {
315 pub single_imports: FxIndexSet<Import<'ra>>,
318 pub non_glob_decl: Option<Decl<'ra>> = None,
320 pub glob_decl: Option<Decl<'ra>> = None,
322 pub orig_ident_span: Span,
323}
324
325impl<'ra> NameResolution<'ra> {
326 pub(crate) fn new(orig_ident_span: Span) -> Self {
327 NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
328 }
329
330 pub(crate) fn determined_decl(&self) -> Option<Decl<'ra>> {
339 if self.non_glob_decl.is_some() {
340 self.non_glob_decl
341 } else if self.glob_decl.is_some() && self.single_imports.is_empty() {
342 self.glob_decl
343 } else {
344 None
345 }
346 }
347
348 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
349 self.non_glob_decl.or(self.glob_decl)
350 }
351}
352
353#[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)]
356struct UnresolvedImportError {
357 span: Span,
358 label: Option<String>,
359 note: Option<String>,
360 suggestion: Option<Suggestion>,
361 candidates: Option<Vec<ImportSuggestion>>,
362 segment: Option<Ident>,
363 module: Option<DefId>,
365 on_unknown_attr: Option<OnUnknownData>,
366}
367
368fn pub_use_of_private_extern_crate_hack(
371 import: ImportSummary,
372 decl: Decl<'_>,
373) -> Option<LocalDefId> {
374 match (import.is_single, decl.kind) {
375 (true, DeclKind::Import { import: decl_import, .. })
376 if let ImportKind::ExternCrate { def_id, .. } = decl_import.kind
377 && import.vis.is_public() =>
378 {
379 Some(def_id)
380 }
381 _ => None,
382 }
383}
384
385fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
387 if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
388 && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
389 && import1 == import2
390 {
391 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);
392 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);
393 if d1.ambiguity.get() != d2.ambiguity.get() {
394 if !d1.ambiguity.get().is_some() {
::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
395 }
396 remove_same_import(d1_next, d2_next)
399 } else {
400 (d1, d2)
401 }
402}
403
404impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
405 pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
406 self.import_decl_vis_ext(decl, import, false)
407 }
408
409 pub(crate) fn import_decl_vis_ext(
410 &self,
411 decl: Decl<'ra>,
412 import: ImportSummary,
413 min: bool,
414 ) -> Visibility {
415 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));
416 let decl_vis = if min { decl.min_vis() } else { decl.vis() };
417 let ord = decl_vis.partial_cmp(import.vis, self.tcx);
418 let extern_crate_hack = pub_use_of_private_extern_crate_hack(import, decl).is_some();
419 if ord == Some(Ordering::Less)
420 && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
421 && !extern_crate_hack
422 {
423 decl_vis.expect_local()
426 } else {
427 if !min
435 && #[allow(non_exhaustive_omitted_patterns)] match ord {
None | Some(Ordering::Less) => true,
_ => false,
}matches!(ord, None | Some(Ordering::Less))
436 && !extern_crate_hack
437 && !import.priv_macro_use
438 {
439 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);
440 self.dcx().span_delayed_bug(import.span, msg);
441 }
442 import.vis
443 }
444 }
445
446 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
449 let vis = self.import_decl_vis(decl, import.summary());
450
451 if let ImportKind::Glob { ref max_vis, .. } = import.kind
452 && (vis == import.vis
453 || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
454 {
455 max_vis.set(Some(vis), self)
457 }
458
459 self.arenas.alloc_decl(DeclData {
460 kind: DeclKind::Import { source_decl: decl, import },
461 ambiguity: CmCell::new(None),
462 span: import.span,
463 initial_vis: vis.to_def_id(),
464 ambiguity_vis_max: CmCell::new(None),
465 ambiguity_vis_min: CmCell::new(None),
466 expansion: import.parent_scope.expansion,
467 parent_module: Some(import.parent_scope.module),
468 })
469 }
470
471 fn is_noise_0_7_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
472 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
473 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
474 let [seg1, seg2] = &i1.module_path[..] else { return false };
475 if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin_surflet" {
476 return false;
477 }
478 let [seg1, seg2] = &i2.module_path[..] else { return false };
479 if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin" {
480 return false;
481 }
482 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
483 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
484 self.def_path_str(def_id1).ends_with("noise_fns::generators::perlin_surflet::Perlin")
485 && self.def_path_str(def_id2).ends_with("noise_fns::generators::perlin::Perlin")
486 }
487
488 fn is_rustybuzz_0_4_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
489 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
490 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
491 let [seg1, seg2] = &i1.module_path[..] else { return false };
492 if seg1.ident.name != kw::Super || seg2.ident.name.as_str() != "gsubgpos" {
493 return false;
494 }
495 let [seg1] = &i2.module_path[..] else { return false };
496 if seg1.ident.name != kw::Super {
497 return false;
498 }
499 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
500 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
501 self.def_path_str(def_id1).ends_with("tables::gsubgpos::Class")
502 && self.def_path_str(def_id2).ends_with("ggg::Class")
503 }
504
505 fn is_pdf_0_9_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
506 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
507 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
508 let [seg1, seg2] = &i1.module_path[..] else { return false };
509 if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "content" {
510 return false;
511 }
512 let [seg1, seg2] = &i2.module_path[..] else { return false };
513 if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "object" {
514 return false;
515 }
516 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
517 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
518 self.def_path_str(def_id1).ends_with("crate::content::Rect")
519 && self.def_path_str(def_id2).ends_with("crate::object::types::Rect")
520 }
521
522 fn is_net2_0_2_39(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
523 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
524 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
525 let [seg1, seg2, seg3, seg4] = &i1.module_path[..] else { return false };
526 if seg1.ident.name != kw::PathRoot
527 || seg2.ident.name.as_str() != "winapi"
528 || seg3.ident.name.as_str() != "shared"
529 || seg4.ident.name.as_str() != "ws2def"
530 {
531 return false;
532 }
533 let [seg1, seg2, seg3, seg4] = &i2.module_path[..] else { return false };
534 if seg1.ident.name != kw::PathRoot
535 || seg2.ident.name.as_str() != "winapi"
536 || seg3.ident.name.as_str() != "um"
537 || seg4.ident.name.as_str() != "winsock2"
538 {
539 return false;
540 }
541 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
542 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
543 self.def_path_str(def_id1).starts_with("winapi::shared::ws2def::")
544 && self.def_path_str(def_id2).starts_with("winapi::um::winsock2::")
545 }
546
547 fn select_glob_decl(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> Decl<'ra> {
550 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
551 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());
552 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);
553 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
565 if deep_decl != glob_decl {
566 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);
568 if !!deep_decl.is_glob_import() {
::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
569 if let Some((old_ambig, _)) = old_glob_decl.ambiguity.get()
570 && glob_decl.ambiguity.get().is_none()
571 {
572 glob_decl.ambiguity.set(Some((old_ambig, true)), self);
574 }
575 glob_decl
576 } else if glob_decl.res() != old_glob_decl.res() {
577 let warning = self.is_noise_0_7_0(old_glob_decl, glob_decl)
578 || self.is_rustybuzz_0_4_0(old_glob_decl, glob_decl)
579 || self.is_pdf_0_9_0(old_glob_decl, glob_decl)
580 || self.is_net2_0_2_39(old_glob_decl, glob_decl);
581 old_glob_decl.ambiguity.set(Some((glob_decl, warning)), self);
582 old_glob_decl
583 } else if let old_vis = old_glob_decl.vis()
584 && let vis = glob_decl.vis()
585 && old_vis != vis
586 {
587 if vis.greater_than(old_vis, self.tcx) {
590 old_glob_decl.ambiguity_vis_max.set(Some(glob_decl), self);
591 } else if let old_min_vis = old_glob_decl.min_vis()
592 && old_min_vis != vis
593 && old_min_vis.greater_than(vis, self.tcx)
594 {
595 old_glob_decl.ambiguity_vis_min.set(Some(glob_decl), self);
596 }
597 old_glob_decl
598 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
599 old_glob_decl.ambiguity.set(Some((glob_decl, true)), self);
601 old_glob_decl
602 } else {
603 old_glob_decl
604 }
605 }
606
607 pub(crate) fn try_plant_decl_into_local_module(
610 &mut self,
611 ident: IdentKey,
612 orig_ident_span: Span,
613 ns: Namespace,
614 decl: Decl<'ra>,
615 ) -> Result<(), Decl<'ra>> {
616 if !decl.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: decl.ambiguity.get().is_none()")
};assert!(decl.ambiguity.get().is_none());
617 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());
618 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());
619 let module = decl.parent_module.unwrap().expect_local();
620 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()));
621 let res = decl.res();
622 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
623 let key = BindingKey::new_disambiguated(ident, ns, || {
627 module.underscore_disambiguator.update(self, |d| d + 1);
628 module.underscore_disambiguator.get()
629 });
630 self.update_local_resolution(module, key, orig_ident_span, |this, resolution| {
631 if res == Res::Err
632 && let Some(old_decl) = resolution.best_decl()
633 && old_decl.res() != Res::Err
634 {
635 return Ok(());
639 }
640 if decl.is_glob_import() {
641 resolution.glob_decl = Some(match resolution.glob_decl {
642 Some(old_decl) => this.select_glob_decl(old_decl, decl),
643 None => decl,
644 });
645 } else {
646 resolution.non_glob_decl = Some(match resolution.non_glob_decl {
647 Some(old_decl) => return Err(old_decl),
648 None => decl,
649 })
650 }
651
652 Ok(())
653 })
654 }
655
656 fn update_local_resolution<T, F>(
659 &mut self,
660 module: LocalModule<'ra>,
661 key: BindingKey,
662 orig_ident_span: Span,
663 f: F,
664 ) -> T
665 where
666 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
667 {
668 let (binding, t) = {
671 let resolution = &mut *self
672 .resolution_or_default(module.to_module(), key, orig_ident_span)
673 .borrow_mut(self);
674 let old_decl = resolution.determined_decl();
675 let old_vis = old_decl.map(|d| d.vis());
676
677 let t = f(self, resolution);
678
679 if let Some(binding) = resolution.determined_decl()
680 && (old_decl != Some(binding) || old_vis != Some(binding.vis()))
681 {
682 (binding, t)
683 } else {
684 return t;
685 }
686 };
687
688 let Ok(glob_importers) = module.glob_importers.try_borrow_mut(self) else {
689 return t;
690 };
691
692 for import in glob_importers.iter() {
694 let mut ident = key.ident;
695 let scope = match ident
696 .ctxt
697 .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
698 {
699 Some(Some(def)) => self.expn_def_scope(def),
700 Some(None) => import.parent_scope.module,
701 None => continue,
702 };
703 if self.is_accessible_from(binding.vis(), scope) {
704 let import_decl = self.new_import_decl(binding, *import);
705 self.try_plant_decl_into_local_module(ident, orig_ident_span, key.ns, import_decl)
706 .expect("planting a glob cannot fail");
707 }
708 }
709
710 t
711 }
712
713 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
716 if let ImportKind::Single { target, ref decls, .. } = import.kind {
717 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
718 return; }
720 let dummy_decl = self.dummy_decl;
721 let dummy_decl = self.new_import_decl(dummy_decl, import);
722 self.per_ns(|this, ns| {
723 let ident = IdentKey::new(target);
724 let _ = this.try_plant_decl_into_local_module(ident, target.span, ns, dummy_decl);
726 if target.name != kw::Underscore {
728 let key = BindingKey::new(ident, ns);
729 this.update_local_resolution(
730 import.parent_scope.module.expect_local(),
731 key,
732 target.span,
733 |_, resolution| {
734 resolution.single_imports.swap_remove(&import);
735 },
736 )
737 }
738 });
739 self.record_use(target, dummy_decl, Used::Other);
740 } else if import.imported_module.get().is_none() {
741 self.import_use_map.insert(import, Used::Other);
742 if let Some(id) = import.id() {
743 self.used_imports.insert(id);
744 }
745 }
746 }
747
748 pub(crate) fn resolve_imports(&mut self) {
760 let mut prev_indeterminate_count = usize::MAX;
761 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
762 while indeterminate_count < prev_indeterminate_count {
763 prev_indeterminate_count = indeterminate_count;
764 indeterminate_count = 0;
765 let mut resolutions = Vec::new();
766 self.assert_speculative = true;
767 for import in mem::take(&mut self.indeterminate_imports) {
768 let (resolution, import_indeterminate_count) = self.cm().resolve_import(import);
769 indeterminate_count += import_indeterminate_count;
770 match import_indeterminate_count {
771 0 => self.determined_imports.push(import),
772 _ => self.indeterminate_imports.push(import),
773 }
774 if let Some(resolution) = resolution {
775 resolutions.push((import, resolution));
776 }
777 }
778 self.assert_speculative = false;
779 self.write_import_resolutions(resolutions);
780 }
781 }
782
783 fn write_import_resolutions(
784 &mut self,
785 import_resolutions: Vec<(Import<'ra>, ImportResolution<'ra>)>,
786 ) {
787 for (import, resolution) in &import_resolutions {
788 let ImportResolution { imported_module, .. } = resolution;
789 import.imported_module.set(Some(*imported_module), self);
790
791 if import.is_glob()
792 && let ModuleOrUniformRoot::Module(module) = imported_module
793 && import.parent_scope.module != *module
794 && module.is_local()
795 {
796 module.glob_importers.borrow_mut(self).push(*import);
797 }
798 }
799
800 for (import, resolution) in import_resolutions {
801 let ImportResolution { imported_module, kind: resolution_kind } = resolution;
802
803 match (&import.kind, resolution_kind) {
804 (
805 ImportKind::Single { target, decls, .. },
806 ImportResolutionKind::Single(import_decls),
807 ) => {
808 self.per_ns(|this, ns| {
809 match import_decls[ns] {
810 PendingDecl::Ready(Some(import_decl)) => {
811 if import_decl.is_assoc_item()
812 && !this.tcx.features().import_trait_associated_functions()
813 {
814 feature_err(
815 this.tcx.sess,
816 sym::import_trait_associated_functions,
817 import.span,
818 "`use` associated items of traits is unstable",
819 )
820 .emit();
821 }
822 this.plant_decl_into_local_module(
823 IdentKey::new(*target),
824 target.span,
825 ns,
826 import_decl,
827 );
828 decls[ns].set(PendingDecl::Ready(Some(import_decl)), this);
829 }
830 PendingDecl::Ready(None) => {
831 if target.name != kw::Underscore {
833 let key = BindingKey::new(IdentKey::new(*target), ns);
834 this.update_local_resolution(
835 import.parent_scope.module.expect_local(),
836 key,
837 target.span,
838 |_, resolution| {
839 resolution.single_imports.swap_remove(&import);
840 },
841 );
842 }
843 decls[ns].set(PendingDecl::Ready(None), this);
844 }
845 PendingDecl::Pending => {}
846 }
847 });
848 }
849 (ImportKind::Glob { id, .. }, ImportResolutionKind::Glob(imported_decls)) => {
850 let ModuleOrUniformRoot::Module(module) = imported_module else {
851 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
852 continue;
853 };
854
855 if module.is_trait() && !self.tcx.features().import_trait_associated_functions()
856 {
857 feature_err(
858 self.tcx.sess,
859 sym::import_trait_associated_functions,
860 import.span,
861 "`use` associated items of traits is unstable",
862 )
863 .emit();
864 }
865
866 for (binding, key, orig_ident_span) in imported_decls {
867 let import_decl = self.new_import_decl(binding, import);
868 let _ = self
869 .try_plant_decl_into_local_module(
870 key.ident,
871 orig_ident_span,
872 key.ns,
873 import_decl,
874 )
875 .expect("planting a glob cannot fail");
876 }
877
878 self.record_partial_res(*id, PartialRes::new(module.res().unwrap()));
879 }
880
881 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("mismatched import and resolution kind")));
}unreachable!("mismatched import and resolution kind"),
883 }
884 }
885 }
886
887 pub(crate) fn finalize_imports(&mut self) {
888 let mut module_children = Default::default();
889 let mut ambig_module_children = Default::default();
890 for module in &self.local_modules {
891 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
892 }
893 self.module_children = module_children;
894 self.ambig_module_children = ambig_module_children;
895
896 let mut seen_spans = FxHashSet::default();
897 let mut errors = ::alloc::vec::Vec::new()vec![];
898 let mut prev_root_id: NodeId = NodeId::ZERO;
899 let determined_imports = mem::take(&mut self.determined_imports);
900 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
901
902 let mut glob_error = false;
903 for (is_indeterminate, import) in determined_imports
904 .iter()
905 .map(|i| (false, i))
906 .chain(indeterminate_imports.iter().map(|i| (true, i)))
907 {
908 let unresolved_import_error = self.finalize_import(*import);
909 self.import_dummy_binding(*import, is_indeterminate);
912
913 let Some(err) = unresolved_import_error else { continue };
914
915 glob_error |= import.is_glob();
916
917 if let ImportKind::Single { source, ref decls, .. } = import.kind
918 && source.name == kw::SelfLower
919 && let PendingDecl::Ready(None) = decls.value_ns.get()
921 {
922 continue;
923 }
924
925 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
926 {
927 self.throw_unresolved_import_error(errors, glob_error);
930 errors = ::alloc::vec::Vec::new()vec![];
931 }
932 if seen_spans.insert(err.span) {
933 errors.push((*import, err));
934 prev_root_id = import.root_id;
935 }
936 }
937
938 if self.cstore().had_extern_crate_load_failure() {
939 self.tcx.sess.dcx().abort_if_errors();
940 }
941
942 if !errors.is_empty() {
943 self.throw_unresolved_import_error(errors, glob_error);
944 return;
945 }
946
947 for import in &indeterminate_imports {
948 let path = import_path_to_string(
949 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
950 &import.kind,
951 import.span,
952 );
953 if path.contains("::") {
956 let err = UnresolvedImportError {
957 span: import.span,
958 label: None,
959 note: None,
960 suggestion: None,
961 candidates: None,
962 segment: None,
963 module: None,
964 on_unknown_attr: import.on_unknown_attr.clone(),
965 };
966 errors.push((*import, err))
967 }
968 }
969
970 if !errors.is_empty() {
971 self.throw_unresolved_import_error(errors, glob_error);
972 }
973 }
974
975 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
976 for module in &self.local_modules {
977 for (key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
978 let resolution = resolution.borrow();
979 let Some(binding) = resolution.best_decl() else { continue };
980
981 for decl in [resolution.non_glob_decl, resolution.glob_decl] {
984 if let Some(decl) = decl
985 && let DeclKind::Import { source_decl, import } = decl.kind
986 && decl.ambiguity_vis_max.get().is_none()
990 {
991 let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
994 if #[allow(non_exhaustive_omitted_patterns)] match ord {
None | Some(Ordering::Less) => true,
_ => false,
}matches!(ord, None | Some(Ordering::Less)) {
995 let ident = match import.kind {
996 ImportKind::Single { source, .. } => source,
997 _ => key.ident.orig(resolution.orig_ident_span),
998 };
999 if let Some(lint) =
1000 self.report_cannot_reexport(import, source_decl, ident, key.ns)
1001 {
1002 self.lint_buffer.add_early_lint(lint);
1003 }
1004 }
1005 }
1006 }
1007
1008 if let DeclKind::Import { import, .. } = binding.kind
1009 && let Some((amb_binding, _)) = binding.ambiguity.get()
1010 && binding.res() != Res::Err
1011 && exported_ambiguities.contains(&binding)
1012 {
1013 self.lint_buffer.buffer_lint(
1014 AMBIGUOUS_GLOB_REEXPORTS,
1015 import.root_id,
1016 import.root_span,
1017 errors::AmbiguousGlobReexports {
1018 name: key.ident.name.to_string(),
1019 namespace: key.ns.descr().to_string(),
1020 first_reexport: import.root_span,
1021 duplicate_reexport: amb_binding.span,
1022 },
1023 );
1024 }
1025
1026 if let Some(glob_decl) = resolution.glob_decl
1027 && resolution.non_glob_decl.is_some()
1028 {
1029 if binding.res() != Res::Err
1030 && glob_decl.res() != Res::Err
1031 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
1032 && let Some(glob_import_def_id) = glob_import.def_id()
1033 && self.effective_visibilities.is_exported(glob_import_def_id)
1034 && glob_decl.vis().is_public()
1035 && !binding.vis().is_public()
1036 {
1037 let binding_id = match binding.kind {
1038 DeclKind::Def(res) => {
1039 Some(self.def_id_to_node_id(res.def_id().expect_local()))
1040 }
1041 DeclKind::Import { import, .. } => import.id(),
1042 };
1043 if let Some(binding_id) = binding_id {
1044 self.lint_buffer.buffer_lint(
1045 HIDDEN_GLOB_REEXPORTS,
1046 binding_id,
1047 binding.span,
1048 errors::HiddenGlobReexports {
1049 name: key.ident.name.to_string(),
1050 namespace: key.ns.descr().to_owned(),
1051 glob_reexport: glob_decl.span,
1052 private_item: binding.span,
1053 },
1054 );
1055 }
1056 }
1057 }
1058
1059 if let DeclKind::Import { import, .. } = binding.kind
1060 && let Some(binding_id) = import.id()
1061 && let import_def_id = import.def_id().unwrap()
1062 && self.effective_visibilities.is_exported(import_def_id)
1063 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
1064 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
1065 && !reexported_def_id.is_local()
1066 && self.tcx.is_private_dep(reexported_def_id.krate)
1067 {
1068 self.lint_buffer.buffer_lint(
1069 EXPORTED_PRIVATE_DEPENDENCIES,
1070 binding_id,
1071 binding.span,
1072 crate::errors::ReexportPrivateDependency {
1073 name: key.ident.name,
1074 kind: binding.res().descr(),
1075 krate: self.tcx.crate_name(reexported_def_id.krate),
1076 },
1077 );
1078 }
1079 }
1080 }
1081 }
1082
1083 fn throw_unresolved_import_error(
1084 &mut self,
1085 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
1086 glob_error: bool,
1087 ) {
1088 errors.retain(|(_import, err)| match err.module {
1089 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
1091 _ => err.segment.map(|s| s.name) != Some(kw::Underscore),
1094 });
1095 if errors.is_empty() {
1096 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
1097 return;
1098 }
1099
1100 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
1101
1102 let paths = errors
1103 .iter()
1104 .map(|(import, err)| {
1105 let path = import_path_to_string(
1106 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
1107 &import.kind,
1108 err.span,
1109 );
1110 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
1111 })
1112 .collect::<Vec<_>>();
1113 let default_message =
1114 ::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(", "),);
1115 let (message, label, notes) =
1116 if let Some(directive) = errors[0].1.on_unknown_attr.as_ref().map(|a| &a.directive) {
1118 let this = errors.iter().map(|(_import, err)| {
1119
1120 err.segment.map(|s|s.name).unwrap_or(kw::Underscore)
1122 }).join(", ");
1123
1124 let args = FormatArgs {
1125 this,
1126 ..
1127 };
1128 let CustomDiagnostic { message, label, notes, .. } = directive.eval(None, &args);
1129
1130 (message, label, notes)
1131 } else {
1132 (None, None, Vec::new())
1133 };
1134 let has_custom_message = message.is_some();
1135 let message = message.as_deref().unwrap_or(default_message.as_str());
1136
1137 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}");
1138 if has_custom_message {
1139 diag.note(default_message);
1140 }
1141
1142 if !notes.is_empty() {
1143 for note in notes {
1144 diag.note(note);
1145 }
1146 } else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
1147 errors.iter().last()
1148 {
1149 diag.note(note.clone());
1150 }
1151
1152 const MAX_LABEL_COUNT: usize = 10;
1154
1155 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
1156 let label_span = match err.segment {
1157 Some(segment) => segment.span,
1158 None => err.span,
1159 };
1160 if let Some(label) = &label {
1161 diag.span_label(label_span, label.clone());
1162 } else if let Some(label) = &err.label {
1163 diag.span_label(label_span, label.clone());
1164 }
1165
1166 if let Some((suggestions, msg, applicability)) = err.suggestion {
1167 if suggestions.is_empty() {
1168 diag.help(msg);
1169 continue;
1170 }
1171 diag.multipart_suggestion(msg, suggestions, applicability);
1172 }
1173
1174 if let Some(candidates) = &err.candidates {
1175 match &import.kind {
1176 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
1177 self.tcx,
1178 &mut diag,
1179 Some(err.span),
1180 candidates,
1181 DiagMode::Import { append: false, unresolved_import: true },
1182 (source != target)
1183 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
1184 .as_deref()
1185 .unwrap_or(""),
1186 ),
1187 ImportKind::Single { nested: true, source, target, .. } => {
1188 import_candidates(
1189 self.tcx,
1190 &mut diag,
1191 None,
1192 candidates,
1193 DiagMode::Normal,
1194 (source != target)
1195 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
1196 .as_deref()
1197 .unwrap_or(""),
1198 );
1199 }
1200 _ => {}
1201 }
1202 }
1203
1204 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
1205 && let Some(segment) = err.segment
1206 && let Some(module) = err.module
1207 {
1208 self.find_cfg_stripped(&mut diag, &segment.name, module)
1209 }
1210 }
1211
1212 let guar = diag.emit();
1213 if glob_error {
1214 self.glob_error = Some(guar);
1215 }
1216 }
1217
1218 fn resolve_import<'r>(
1224 mut self: CmResolver<'r, 'ra, 'tcx>,
1225 import: Import<'ra>,
1226 ) -> (Option<ImportResolution<'ra>>, usize) {
1227 {
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:1227",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1227u32),
::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}::{1}` in `{2}`",
Segment::names_to_string(&import.module_path),
import_kind_to_string(&import.kind),
module_to_string(import.parent_scope.module).unwrap_or_else(||
"???".to_string())) as &dyn Value))])
});
} else { ; }
};debug!(
1228 "(resolving import for module) resolving import `{}::{}` in `{}`",
1229 Segment::names_to_string(&import.module_path),
1230 import_kind_to_string(&import.kind),
1231 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
1232 );
1233 let module = if let Some(module) = import.imported_module.get() {
1234 module
1235 } else {
1236 let path_res = self.reborrow().maybe_resolve_path(
1237 &import.module_path,
1238 None,
1239 &import.parent_scope,
1240 Some(import),
1241 );
1242
1243 match path_res {
1244 PathResult::Module(module) => module,
1245 PathResult::Indeterminate => return (None, 3),
1246 PathResult::NonModule(..) | PathResult::Failed { .. } => return (None, 0),
1247 }
1248 };
1249
1250 let (source, bindings) = match import.kind {
1251 ImportKind::Single { source, ref decls, .. } => (source, decls),
1252 ImportKind::Glob { .. } => {
1253 let import_resolution = ImportResolution {
1254 imported_module: module,
1255 kind: self.resolve_glob_import(import, module),
1256 };
1257 return (Some(import_resolution), 0);
1258 }
1259 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1260 };
1261
1262 let mut import_decls = PerNS::default();
1263 let mut indeterminate_count = 0;
1264 self.per_ns_cm(|mut this, ns| {
1265 if bindings[ns].get() != PendingDecl::Pending {
1266 return;
1267 };
1268 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1269 module,
1270 source,
1271 ns,
1272 &import.parent_scope,
1273 Some(import),
1274 );
1275 let pending_decl = match binding_result {
1276 Ok(binding) => {
1277 let import_decl = this.new_import_decl(binding, import);
1279 PendingDecl::Ready(Some(import_decl))
1280 }
1281 Err(Determinacy::Determined) => PendingDecl::Ready(None),
1282 Err(Determinacy::Undetermined) => {
1283 indeterminate_count += 1;
1284 PendingDecl::Pending
1285 }
1286 };
1287 import_decls[ns] = pending_decl;
1288 });
1289 let import_resolution = ImportResolution {
1290 imported_module: module,
1291 kind: ImportResolutionKind::Single(import_decls),
1292 };
1293
1294 (Some(import_resolution), indeterminate_count)
1295 }
1296
1297 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1302 let ignore_decl = match &import.kind {
1303 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1304 _ => None,
1305 };
1306 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1307 errors.iter().filter(|error| error.warning.is_none()).count()
1308 };
1309 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1310 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1311
1312 let privacy_errors_len = self.privacy_errors.len();
1314
1315 let path_res = self.cm().resolve_path(
1316 &import.module_path,
1317 None,
1318 &import.parent_scope,
1319 Some(finalize),
1320 ignore_decl,
1321 Some(import),
1322 );
1323
1324 let no_ambiguity =
1325 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1326
1327 let module = match path_res {
1328 PathResult::Module(module) => {
1329 if let Some(initial_module) = import.imported_module.get() {
1331 if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1332 ::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");
1333 }
1334 } else if self.privacy_errors.is_empty() {
1335 self.dcx()
1336 .create_err(CannotDetermineImportResolution { span: import.span })
1337 .emit();
1338 }
1339
1340 module
1341 }
1342 PathResult::Failed {
1343 is_error_from_last_segment: false,
1344 span,
1345 segment,
1346 label,
1347 suggestion,
1348 module,
1349 error_implied_by_parse_error: _,
1350 message,
1351 note: _,
1352 } => {
1353 if no_ambiguity {
1354 if !self.issue_145575_hack_applied {
1355 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());
1356 }
1357 self.report_error(
1358 span,
1359 ResolutionError::FailedToResolve {
1360 segment: segment.name,
1361 label,
1362 suggestion,
1363 module,
1364 message,
1365 },
1366 );
1367 }
1368 return None;
1369 }
1370 PathResult::Failed {
1371 is_error_from_last_segment: true,
1372 span,
1373 label,
1374 suggestion,
1375 module,
1376 segment,
1377 note,
1378 ..
1379 } => {
1380 if no_ambiguity {
1381 if !self.issue_145575_hack_applied {
1382 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());
1383 }
1384 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1385 m.opt_def_id()
1386 } else {
1387 None
1388 };
1389 let err = match self
1390 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1391 {
1392 Some((suggestion, note)) => UnresolvedImportError {
1393 span,
1394 label: None,
1395 note,
1396 suggestion: Some((
1397 ::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))],
1398 String::from("a similar path exists"),
1399 Applicability::MaybeIncorrect,
1400 )),
1401 candidates: None,
1402 segment: Some(segment),
1403 module,
1404 on_unknown_attr: import.on_unknown_attr.clone(),
1405 },
1406 None => UnresolvedImportError {
1407 span,
1408 label: Some(label),
1409 note,
1410 suggestion,
1411 candidates: None,
1412 segment: Some(segment),
1413 module,
1414 on_unknown_attr: import.on_unknown_attr.clone(),
1415 },
1416 };
1417 return Some(err);
1418 }
1419 return None;
1420 }
1421 PathResult::NonModule(partial_res) => {
1422 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1423 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());
1425 }
1426 return None;
1428 }
1429 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1430 };
1431
1432 let (ident, target, bindings, import_id) = match import.kind {
1433 ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1434 ImportKind::Glob { ref max_vis, id, def_id } => {
1435 if import.module_path.len() <= 1 {
1436 let mut full_path = import.module_path.clone();
1439 full_path.push(Segment::from_ident(Ident::dummy()));
1440 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1441 }
1442
1443 if let ModuleOrUniformRoot::Module(module) = module
1444 && module == import.parent_scope.module
1445 {
1446 return Some(UnresolvedImportError {
1448 span: import.span,
1449 label: Some(String::from("cannot glob-import a module into itself")),
1450 note: None,
1451 suggestion: None,
1452 candidates: None,
1453 segment: None,
1454 module: None,
1455 on_unknown_attr: None,
1456 });
1457 }
1458 if let Some(max_vis) = max_vis.get()
1459 && import.vis.greater_than(max_vis, self.tcx)
1460 {
1461 self.lint_buffer.buffer_lint(
1462 UNUSED_IMPORTS,
1463 id,
1464 import.span,
1465 crate::errors::RedundantImportVisibility {
1466 span: import.span,
1467 help: (),
1468 max_vis: max_vis.to_string(def_id, self.tcx),
1469 import_vis: import.vis.to_string(def_id, self.tcx),
1470 },
1471 );
1472 }
1473 return None;
1474 }
1475 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1476 };
1477
1478 if self.privacy_errors.len() != privacy_errors_len {
1479 let mut path = import.module_path.clone();
1482 path.push(Segment::from_ident(ident));
1483 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1484 &path,
1485 None,
1486 &import.parent_scope,
1487 Some(finalize),
1488 ignore_decl,
1489 None,
1490 ) {
1491 let res = module.res().map(|r| (r, ident));
1492 for error in &mut self.privacy_errors[privacy_errors_len..] {
1493 error.outermost_res = res;
1494 }
1495 } else {
1496 for ns in [TypeNS, ValueNS, MacroNS] {
1500 if let Ok(binding) = self.cm().resolve_ident_in_module(
1501 module,
1502 ident,
1503 ns,
1504 &import.parent_scope,
1505 None,
1506 ignore_decl,
1507 None,
1508 ) {
1509 let res = binding.res();
1510 for error in &mut self.privacy_errors[privacy_errors_len..] {
1511 error.outermost_res = Some((res, ident));
1512 }
1513 break;
1514 }
1515 }
1516 }
1517 }
1518
1519 let mut all_ns_err = true;
1520 self.per_ns(|this, ns| {
1521 let binding = this.cm().resolve_ident_in_module(
1522 module,
1523 ident,
1524 ns,
1525 &import.parent_scope,
1526 Some(Finalize {
1527 report_private: false,
1528 import: Some(import.summary()),
1529 ..finalize
1530 }),
1531 bindings[ns].get().decl(),
1532 Some(import),
1533 );
1534
1535 match binding {
1536 Ok(binding) => {
1537 let initial_res = bindings[ns].get().decl().map(|binding| {
1539 let initial_binding = binding.import_source();
1540 all_ns_err = false;
1541 if target.name == kw::Underscore
1542 && initial_binding.is_extern_crate()
1543 && !initial_binding.is_import()
1544 {
1545 let used = if import.module_path.is_empty() {
1546 Used::Scope
1547 } else {
1548 Used::Other
1549 };
1550 this.record_use(ident, binding, used);
1551 }
1552 initial_binding.res()
1553 });
1554 let res = binding.res();
1555 let has_ambiguity_error =
1556 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1557 if res == Res::Err || has_ambiguity_error {
1558 this.dcx()
1559 .span_delayed_bug(import.span, "some error happened for an import");
1560 return;
1561 }
1562 if let Some(initial_res) = initial_res {
1563 if res != initial_res && !this.issue_145575_hack_applied {
1564 ::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");
1565 }
1566 } else if this.privacy_errors.is_empty() {
1567 this.dcx()
1568 .create_err(CannotDetermineImportResolution { span: import.span })
1569 .emit();
1570 }
1571 }
1572 Err(..) => {
1573 }
1580 }
1581 });
1582
1583 if all_ns_err {
1584 let mut all_ns_failed = true;
1585 self.per_ns(|this, ns| {
1586 let binding = this.cm().resolve_ident_in_module(
1587 module,
1588 ident,
1589 ns,
1590 &import.parent_scope,
1591 Some(finalize),
1592 None,
1593 None,
1594 );
1595 if binding.is_ok() {
1596 all_ns_failed = false;
1597 }
1598 });
1599
1600 return if all_ns_failed {
1601 let names = match module {
1602 ModuleOrUniformRoot::Module(module) => {
1603 self.resolutions(module)
1604 .borrow()
1605 .iter()
1606 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1607 if i.name == ident.name {
1608 return None;
1609 } if i.name == kw::Underscore {
1611 return None;
1612 } let resolution = resolution.borrow();
1615 if let Some(name_binding) = resolution.best_decl() {
1616 match name_binding.kind {
1617 DeclKind::Import { source_decl, .. } => {
1618 match source_decl.kind {
1619 DeclKind::Def(Res::Err) => None,
1622 _ => Some(i.name),
1623 }
1624 }
1625 _ => Some(i.name),
1626 }
1627 } else if resolution.single_imports.is_empty() {
1628 None
1629 } else {
1630 Some(i.name)
1631 }
1632 })
1633 .collect()
1634 }
1635 _ => Vec::new(),
1636 };
1637
1638 let lev_suggestion =
1639 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1640 (
1641 ::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())],
1642 String::from("a similar name exists in the module"),
1643 Applicability::MaybeIncorrect,
1644 )
1645 });
1646
1647 let (suggestion, note) =
1648 match self.check_for_module_export_macro(import, module, ident) {
1649 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1650 _ => (lev_suggestion, None),
1651 };
1652
1653 let note = if self.tcx.features().import_trait_associated_functions()
1656 && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1657 && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1658 {
1659 note.or(Some(
1660 "cannot import inherent associated items, only trait associated items"
1661 .to_string(),
1662 ))
1663 } else {
1664 note
1665 };
1666
1667 let label = match module {
1668 ModuleOrUniformRoot::Module(module) => {
1669 let module_str = module_to_string(module);
1670 if let Some(module_str) = module_str {
1671 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1672 } else {
1673 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1674 }
1675 }
1676 _ => {
1677 if !ident.is_path_segment_keyword() {
1678 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1679 } else {
1680 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1683 }
1684 }
1685 };
1686
1687 let parent_suggestion =
1688 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1689
1690 Some(UnresolvedImportError {
1691 span: import.span,
1692 label: Some(label),
1693 note,
1694 suggestion,
1695 candidates: if !parent_suggestion.is_empty() {
1696 Some(parent_suggestion)
1697 } else {
1698 None
1699 },
1700 module: import.imported_module.get().and_then(|module| {
1701 if let ModuleOrUniformRoot::Module(m) = module {
1702 m.opt_def_id()
1703 } else {
1704 None
1705 }
1706 }),
1707 segment: Some(ident),
1708 on_unknown_attr: import.on_unknown_attr.clone(),
1709 })
1710 } else {
1711 None
1713 };
1714 }
1715
1716 let mut reexport_error = None;
1717 let mut any_successful_reexport = false;
1718 self.per_ns(|this, ns| {
1719 let Some(binding) = bindings[ns].get().decl() else {
1720 return;
1721 };
1722
1723 if import.vis.greater_than(binding.vis(), this.tcx) {
1724 reexport_error = Some((ns, binding.import_source()));
1728 } else {
1729 any_successful_reexport = true;
1730 }
1731 });
1732
1733 if !any_successful_reexport {
1734 let (ns, binding) = reexport_error.unwrap();
1735 if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
1736 self.lint_buffer.add_early_lint(lint);
1737 }
1738 }
1739
1740 if import.module_path.len() <= 1 {
1741 let mut full_path = import.module_path.clone();
1744 full_path.push(Segment::from_ident(ident));
1745 self.per_ns(|this, ns| {
1746 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1747 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1748 }
1749 });
1750 }
1751
1752 self.per_ns(|this, ns| {
1756 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1757 this.owners.get_mut(&import_id).unwrap().import_res[ns] = Some(binding.res());
1758 }
1759 });
1760
1761 {
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:1761",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1761u32),
::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");
1762 None
1763 }
1764
1765 fn report_cannot_reexport(
1766 &self,
1767 import: Import<'ra>,
1768 decl: Decl<'ra>,
1769 ident: Ident,
1770 ns: Namespace,
1771 ) -> Option<BufferedEarlyLint> {
1772 let crate_private_reexport = match decl.vis() {
1773 Visibility::Restricted(def_id) if def_id.is_top_level_module() => true,
1774 _ => false,
1775 };
1776
1777 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import.summary(), decl)
1778 {
1779 let ImportKind::Single { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1780 let sugg = self.tcx.source_span(extern_crate_id).shrink_to_lo();
1781 let diagnostic = crate::errors::PrivateExternCrateReexport { ident, sugg };
1782 return Some(BufferedEarlyLint {
1783 lint_id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
1784 node_id: id,
1785 span: Some(import.span.into()),
1786 diagnostic: diagnostic.into(),
1787 });
1788 } else if ns == TypeNS {
1789 let err = if crate_private_reexport {
1790 self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1791 } else {
1792 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1793 };
1794 err.emit();
1795 } else {
1796 let mut err = if crate_private_reexport {
1797 self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1798 } else {
1799 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1800 };
1801
1802 match decl.kind {
1803 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1805 if let SyntaxExtensionKind::MacroRules(mr) =
1806 &self.get_macro_by_def_id(def_id).kind
1807 && mr.is_macro_rules() =>
1808 {
1809 err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
1810 err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
1811 }
1812 _ => {
1813 err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
1814 }
1815 }
1816 err.emit();
1817 }
1818
1819 None
1820 }
1821
1822 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1823 let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
1825 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1826 };
1827
1828 if source != target {
1830 return false;
1831 }
1832
1833 if import.parent_scope.expansion != LocalExpnId::ROOT {
1835 return false;
1836 }
1837
1838 if self.import_use_map.get(&import) == Some(&Used::Other)
1843 || self.effective_visibilities.is_exported(def_id)
1844 {
1845 return false;
1846 }
1847
1848 let mut is_redundant = true;
1849 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1850 self.per_ns(|this, ns| {
1851 let binding = decls[ns].get().decl().map(|b| b.import_source());
1852 if is_redundant && let Some(binding) = binding {
1853 if binding.res() == Res::Err {
1854 return;
1855 }
1856
1857 match this.cm().resolve_ident_in_scope_set(
1858 target,
1859 ScopeSet::All(ns),
1860 &import.parent_scope,
1861 None,
1862 decls[ns].get().decl(),
1863 None,
1864 ) {
1865 Ok(other_binding) => {
1866 is_redundant = binding.res() == other_binding.res()
1867 && !other_binding.is_ambiguity_recursive();
1868 if is_redundant {
1869 redundant_span[ns] =
1870 Some((other_binding.span, other_binding.is_import()));
1871 }
1872 }
1873 Err(_) => is_redundant = false,
1874 }
1875 }
1876 });
1877
1878 if is_redundant && !redundant_span.is_empty() {
1879 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1880 redundant_spans.sort();
1881 redundant_spans.dedup();
1882 self.lint_buffer.dyn_buffer_lint(
1883 REDUNDANT_IMPORTS,
1884 id,
1885 import.span,
1886 move |dcx, level| {
1887 let ident = source;
1888 let subs = redundant_spans
1889 .into_iter()
1890 .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1891 (false, true) => {
1892 errors::RedundantImportSub::ImportedHere { span, ident }
1893 }
1894 (false, false) => {
1895 errors::RedundantImportSub::DefinedHere { span, ident }
1896 }
1897 (true, true) => {
1898 errors::RedundantImportSub::ImportedPrelude { span, ident }
1899 }
1900 (true, false) => {
1901 errors::RedundantImportSub::DefinedPrelude { span, ident }
1902 }
1903 })
1904 .collect();
1905 errors::RedundantImport { subs, ident }.into_diag(dcx, level)
1906 },
1907 );
1908 return true;
1909 }
1910
1911 false
1912 }
1913
1914 fn resolve_glob_import(
1915 &self,
1916 import: Import<'ra>,
1917 imported_module: ModuleOrUniformRoot<'ra>,
1918 ) -> ImportResolutionKind<'ra> {
1919 let import_bindings = match imported_module {
1920 ModuleOrUniformRoot::Module(module) if module != import.parent_scope.module => self
1921 .resolutions(module)
1922 .borrow()
1923 .iter()
1924 .filter_map(|(key, resolution)| {
1925 let res = resolution.borrow();
1926 let decl = res.determined_decl()?;
1927 let mut key = *key;
1928 let scope = match key.ident.ctxt.update_unchecked(|ctxt| {
1929 ctxt.reverse_glob_adjust(module.expansion, import.span)
1930 }) {
1931 Some(Some(def)) => self.expn_def_scope(def),
1932 Some(None) => import.parent_scope.module,
1933 None => return None,
1934 };
1935 self.is_accessible_from(decl.vis(), scope).then_some((
1936 decl,
1937 key,
1938 res.orig_ident_span,
1939 ))
1940 })
1941 .collect::<Vec<_>>(),
1942
1943 _ => ::alloc::vec::Vec::new()vec![],
1945 };
1946
1947 ImportResolutionKind::Glob(import_bindings)
1948 }
1949
1950 fn rust_embed_hack(&self, module: LocalModule<'ra>, decl: Decl<'ra>) -> bool {
1952 if let DeclKind::Import { source_decl, import } = decl.kind
1961 && let ImportKind::Single { source, .. } = import.kind
1963 && source.name == sym::RustEmbed
1964 && let DeclKind::Import { import, .. } = source_decl.kind
1966 && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroUse { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::MacroUse { .. })
1967 && self.macro_use_prelude.contains_key(&source.name) && let Some(y_decl) = self
1970 .resolution(module.to_module(), BindingKey::new(IdentKey::new(source), MacroNS))
1971 .and_then(|res| res.best_decl())
1972 && y_decl.is_glob_import()
1974 && y_decl.vis().is_public()
1975 {
1976 return true;
1977 }
1978
1979 false
1980 }
1981
1982 fn finalize_resolutions_in(
1985 &self,
1986 module: LocalModule<'ra>,
1987 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1988 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1989 ) {
1990 *module.globs.borrow_mut(self) = Vec::new();
1992
1993 let Some(def_id) = module.opt_def_id() else { return };
1994
1995 let mut children = Vec::new();
1996 let mut ambig_children = Vec::new();
1997
1998 module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, decl| {
1999 let res = decl.res().expect_non_local();
2000 if res != def::Res::Err {
2001 let vis = if this.rust_embed_hack(module, decl) {
2002 Visibility::Public
2003 } else {
2004 decl.vis()
2005 };
2006 let ident = ident.orig(orig_ident_span);
2007 let child = |reexport_chain| ModChild { ident, res, vis, reexport_chain };
2008 if let Some((ambig_binding1, ambig_binding2)) = decl.descent_to_ambiguity() {
2009 let main = child(ambig_binding1.reexport_chain());
2010 let second = ModChild {
2011 ident,
2012 res: ambig_binding2.res().expect_non_local(),
2013 vis: ambig_binding2.vis(),
2014 reexport_chain: ambig_binding2.reexport_chain(),
2015 };
2016 ambig_children.push(AmbigModChild { main, second })
2017 } else {
2018 children.push(child(decl.reexport_chain()));
2019 }
2020 }
2021 });
2022
2023 if !children.is_empty() {
2024 module_children.insert(def_id.expect_local(), children);
2025 }
2026 if !ambig_children.is_empty() {
2027 ambig_module_children.insert(def_id.expect_local(), ambig_children);
2028 }
2029 }
2030}
2031
2032fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
2033 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
2034 let global = !names.is_empty() && names[0].name == kw::PathRoot;
2035 if let Some(pos) = pos {
2036 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
2037 names_to_string(names.iter().map(|ident| ident.name))
2038 } else {
2039 let names = if global { &names[1..] } else { names };
2040 if names.is_empty() {
2041 import_kind_to_string(import_kind)
2042 } else {
2043 ::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!(
2044 "{}::{}",
2045 names_to_string(names.iter().map(|ident| ident.name)),
2046 import_kind_to_string(import_kind),
2047 )
2048 }
2049 }
2050}
2051
2052fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
2053 match import_kind {
2054 ImportKind::Single { source, .. } => source.to_string(),
2055 ImportKind::Glob { .. } => "*".to_string(),
2056 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
2057 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
2058 ImportKind::MacroExport => "#[macro_export]".to_string(),
2059 }
2060}