1use std::mem;
4
5use rustc_ast::NodeId;
6use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
7use rustc_data_structures::intern::Interned;
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
10use rustc_hir::def::{self, DefKind, PartialRes};
11use rustc_hir::def_id::{DefId, LocalDefIdMap};
12use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
13use rustc_middle::span_bug;
14use rustc_middle::ty::Visibility;
15use rustc_session::lint::BuiltinLintDiag;
16use rustc_session::lint::builtin::{
17 AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
18 PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
19};
20use rustc_session::parse::feature_err;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::hygiene::LocalExpnId;
23use rustc_span::{Ident, Span, Symbol, kw, sym};
24use tracing::debug;
25
26use crate::Namespace::{self, *};
27use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
28use crate::errors::{
29 CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
30 CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
31 ConsiderAddingMacroExport, ConsiderMarkingAsPub, ConsiderMarkingAsPubCrate,
32};
33use crate::ref_mut::CmCell;
34use crate::{
35 AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
36 ImportSuggestion, Module, ModuleOrUniformRoot, ParentScope, PathResult, PerNS, ResolutionError,
37 Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
38};
39
40type Res = def::Res<NodeId>;
41
42#[derive(Clone, Copy, Default, PartialEq)]
45pub(crate) enum PendingDecl<'ra> {
46 Ready(Option<Decl<'ra>>),
47 #[default]
48 Pending,
49}
50
51impl<'ra> PendingDecl<'ra> {
52 pub(crate) fn decl(self) -> Option<Decl<'ra>> {
53 match self {
54 PendingDecl::Ready(decl) => decl,
55 PendingDecl::Pending => None,
56 }
57 }
58}
59
60#[derive(Clone)]
62pub(crate) enum ImportKind<'ra> {
63 Single {
64 source: Ident,
66 target: Ident,
69 decls: PerNS<CmCell<PendingDecl<'ra>>>,
71 type_ns_only: bool,
73 nested: bool,
75 id: NodeId,
87 },
88 Glob {
89 max_vis: CmCell<Option<Visibility>>,
92 id: NodeId,
93 },
94 ExternCrate {
95 source: Option<Symbol>,
96 target: Ident,
97 id: NodeId,
98 },
99 MacroUse {
100 warn_private: bool,
103 },
104 MacroExport,
105}
106
107impl<'ra> std::fmt::Debug for ImportKind<'ra> {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 use ImportKind::*;
112 match self {
113 Single { source, target, decls, type_ns_only, nested, id, .. } => f
114 .debug_struct("Single")
115 .field("source", source)
116 .field("target", target)
117 .field(
119 "decls",
120 &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!(".."))),
121 )
122 .field("type_ns_only", type_ns_only)
123 .field("nested", nested)
124 .field("id", id)
125 .finish(),
126 Glob { max_vis, id } => {
127 f.debug_struct("Glob").field("max_vis", max_vis).field("id", id).finish()
128 }
129 ExternCrate { source, target, id } => f
130 .debug_struct("ExternCrate")
131 .field("source", source)
132 .field("target", target)
133 .field("id", id)
134 .finish(),
135 MacroUse { warn_private } => {
136 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
137 }
138 MacroExport => f.debug_struct("MacroExport").finish(),
139 }
140 }
141}
142
143#[derive(Debug, Clone)]
145pub(crate) struct ImportData<'ra> {
146 pub kind: ImportKind<'ra>,
147
148 pub root_id: NodeId,
158
159 pub use_span: Span,
161
162 pub use_span_with_attributes: Span,
164
165 pub has_attributes: bool,
167
168 pub span: Span,
170
171 pub root_span: Span,
173
174 pub parent_scope: ParentScope<'ra>,
175 pub module_path: Vec<Segment>,
176 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
185 pub vis: Visibility,
186
187 pub vis_span: Span,
189}
190
191pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
194
195impl std::hash::Hash for ImportData<'_> {
200 fn hash<H>(&self, _: &mut H)
201 where
202 H: std::hash::Hasher,
203 {
204 unreachable!()
205 }
206}
207
208impl<'ra> ImportData<'ra> {
209 pub(crate) fn is_glob(&self) -> bool {
210 matches!(self.kind, ImportKind::Glob { .. })
211 }
212
213 pub(crate) fn is_nested(&self) -> bool {
214 match self.kind {
215 ImportKind::Single { nested, .. } => nested,
216 _ => false,
217 }
218 }
219
220 pub(crate) fn id(&self) -> Option<NodeId> {
221 match self.kind {
222 ImportKind::Single { id, .. }
223 | ImportKind::Glob { id, .. }
224 | ImportKind::ExternCrate { id, .. } => Some(id),
225 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
226 }
227 }
228
229 pub(crate) fn simplify(&self, r: &Resolver<'_, '_>) -> Reexport {
230 let to_def_id = |id| r.local_def_id(id).to_def_id();
231 match self.kind {
232 ImportKind::Single { id, .. } => Reexport::Single(to_def_id(id)),
233 ImportKind::Glob { id, .. } => Reexport::Glob(to_def_id(id)),
234 ImportKind::ExternCrate { id, .. } => Reexport::ExternCrate(to_def_id(id)),
235 ImportKind::MacroUse { .. } => Reexport::MacroUse,
236 ImportKind::MacroExport => Reexport::MacroExport,
237 }
238 }
239}
240
241#[derive(Clone, Default, Debug)]
243pub(crate) struct NameResolution<'ra> {
244 pub single_imports: FxIndexSet<Import<'ra>>,
247 pub non_glob_decl: Option<Decl<'ra>>,
249 pub glob_decl: Option<Decl<'ra>>,
251}
252
253impl<'ra> NameResolution<'ra> {
254 pub(crate) fn binding(&self) -> Option<Decl<'ra>> {
256 self.best_decl().and_then(|binding| {
257 if !binding.is_glob_import() || self.single_imports.is_empty() {
258 Some(binding)
259 } else {
260 None
261 }
262 })
263 }
264
265 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
266 self.non_glob_decl.or(self.glob_decl)
267 }
268}
269
270#[derive(Debug, Clone)]
273struct UnresolvedImportError {
274 span: Span,
275 label: Option<String>,
276 note: Option<String>,
277 suggestion: Option<Suggestion>,
278 candidates: Option<Vec<ImportSuggestion>>,
279 segment: Option<Symbol>,
280 module: Option<DefId>,
282}
283
284fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
287 match (&import.kind, &decl.kind) {
288 (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
289 if let ImportKind::ExternCrate { id, .. } = decl_import.kind
290 && import.vis.is_public() =>
291 {
292 Some(id)
293 }
294 _ => None,
295 }
296}
297
298impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
299 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
302 let import_vis = import.vis.to_def_id();
303 let vis = if decl.vis.is_at_least(import_vis, self.tcx)
304 || pub_use_of_private_extern_crate_hack(import, decl).is_some()
305 {
306 import_vis
307 } else {
308 decl.vis
309 };
310
311 if let ImportKind::Glob { ref max_vis, .. } = import.kind
312 && (vis == import_vis
313 || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
314 {
315 max_vis.set_unchecked(Some(vis.expect_local()))
316 }
317
318 self.arenas.alloc_decl(DeclData {
319 kind: DeclKind::Import { source_decl: decl, import },
320 ambiguity: None,
321 warn_ambiguity: false,
322 span: import.span,
323 vis,
324 expansion: import.parent_scope.expansion,
325 })
326 }
327
328 pub(crate) fn try_plant_decl_into_local_module(
331 &mut self,
332 module: Module<'ra>,
333 ident: Ident,
334 ns: Namespace,
335 decl: Decl<'ra>,
336 warn_ambiguity: bool,
337 ) -> Result<(), Decl<'ra>> {
338 let res = decl.res();
339 self.check_reserved_macro_name(ident, res);
340 self.set_decl_parent_module(decl, module);
341 let key = BindingKey::new_disambiguated(ident, ns, || {
345 module.underscore_disambiguator.update_unchecked(|d| d + 1);
346 module.underscore_disambiguator.get()
347 });
348 self.update_local_resolution(module, key, warn_ambiguity, |this, resolution| {
349 if let Some(old_decl) = resolution.best_decl() {
350 if res == Res::Err && old_decl.res() != Res::Err {
351 return Ok(());
353 }
354 match (old_decl.is_glob_import(), decl.is_glob_import()) {
355 (true, true) => {
356 let (glob_decl, old_glob_decl) = (decl, old_decl);
357 if !decl.is_ambiguity_recursive()
359 && let DeclKind::Import { import: old_import, .. } = old_glob_decl.kind
360 && let DeclKind::Import { import, .. } = glob_decl.kind
361 && old_import == import
362 {
363 resolution.glob_decl = Some(glob_decl);
367 } else if res != old_glob_decl.res() {
368 resolution.glob_decl = Some(this.new_decl_with_ambiguity(
369 old_glob_decl,
370 glob_decl,
371 warn_ambiguity,
372 ));
373 } else if !old_decl.vis.is_at_least(decl.vis, this.tcx) {
374 resolution.glob_decl = Some(glob_decl);
376 } else if decl.is_ambiguity_recursive() {
377 resolution.glob_decl =
378 Some(this.new_decl_with_warn_ambiguity(glob_decl));
379 }
380 }
381 (old_glob @ true, false) | (old_glob @ false, true) => {
382 let (glob_decl, non_glob_decl) =
383 if old_glob { (old_decl, decl) } else { (decl, old_decl) };
384 resolution.non_glob_decl = Some(non_glob_decl);
385 if let Some(old_glob_decl) = resolution.glob_decl {
386 assert!(old_glob_decl.is_glob_import());
387 if glob_decl.res() != old_glob_decl.res() {
388 resolution.glob_decl = Some(this.new_decl_with_ambiguity(
389 old_glob_decl,
390 glob_decl,
391 false,
392 ));
393 } else if !old_glob_decl.vis.is_at_least(decl.vis, this.tcx) {
394 resolution.glob_decl = Some(glob_decl);
395 }
396 } else {
397 resolution.glob_decl = Some(glob_decl);
398 }
399 }
400 (false, false) => {
401 return Err(old_decl);
402 }
403 }
404 } else {
405 if decl.is_glob_import() {
406 resolution.glob_decl = Some(decl);
407 } else {
408 resolution.non_glob_decl = Some(decl);
409 }
410 }
411
412 Ok(())
413 })
414 }
415
416 fn new_decl_with_ambiguity(
417 &self,
418 primary_decl: Decl<'ra>,
419 secondary_decl: Decl<'ra>,
420 warn_ambiguity: bool,
421 ) -> Decl<'ra> {
422 let ambiguity = Some(secondary_decl);
423 let data = DeclData { ambiguity, warn_ambiguity, ..*primary_decl };
424 self.arenas.alloc_decl(data)
425 }
426
427 fn new_decl_with_warn_ambiguity(&self, decl: Decl<'ra>) -> Decl<'ra> {
428 assert!(decl.is_ambiguity_recursive());
429 self.arenas.alloc_decl(DeclData { warn_ambiguity: true, ..*decl })
430 }
431
432 fn update_local_resolution<T, F>(
435 &mut self,
436 module: Module<'ra>,
437 key: BindingKey,
438 warn_ambiguity: bool,
439 f: F,
440 ) -> T
441 where
442 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
443 {
444 let (binding, t, warn_ambiguity) = {
447 let resolution = &mut *self.resolution_or_default(module, key).borrow_mut_unchecked();
448 let old_decl = resolution.binding();
449
450 let t = f(self, resolution);
451
452 if let Some(binding) = resolution.binding()
453 && old_decl != Some(binding)
454 {
455 (binding, t, warn_ambiguity || old_decl.is_some())
456 } else {
457 return t;
458 }
459 };
460
461 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
462 return t;
463 };
464
465 for import in glob_importers.iter() {
467 let mut ident = key.ident;
468 let scope = match ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
469 Some(Some(def)) => self.expn_def_scope(def),
470 Some(None) => import.parent_scope.module,
471 None => continue,
472 };
473 if self.is_accessible_from(binding.vis, scope) {
474 let import_decl = self.new_import_decl(binding, *import);
475 let _ = self.try_plant_decl_into_local_module(
476 import.parent_scope.module,
477 ident.0,
478 key.ns,
479 import_decl,
480 warn_ambiguity,
481 );
482 }
483 }
484
485 t
486 }
487
488 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
491 if let ImportKind::Single { target, ref decls, .. } = import.kind {
492 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
493 return; }
495 let dummy_decl = self.dummy_decl;
496 let dummy_decl = self.new_import_decl(dummy_decl, import);
497 self.per_ns(|this, ns| {
498 let module = import.parent_scope.module;
499 let _ =
500 this.try_plant_decl_into_local_module(module, target, ns, dummy_decl, false);
501 if target.name != kw::Underscore {
503 let key = BindingKey::new(target, ns);
504 this.update_local_resolution(module, key, false, |_, resolution| {
505 resolution.single_imports.swap_remove(&import);
506 })
507 }
508 });
509 self.record_use(target, dummy_decl, Used::Other);
510 } else if import.imported_module.get().is_none() {
511 self.import_use_map.insert(import, Used::Other);
512 if let Some(id) = import.id() {
513 self.used_imports.insert(id);
514 }
515 }
516 }
517
518 pub(crate) fn resolve_imports(&mut self) {
529 let mut prev_indeterminate_count = usize::MAX;
530 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
531 while indeterminate_count < prev_indeterminate_count {
532 prev_indeterminate_count = indeterminate_count;
533 indeterminate_count = 0;
534 self.assert_speculative = true;
535 for import in mem::take(&mut self.indeterminate_imports) {
536 let import_indeterminate_count = self.cm().resolve_import(import);
537 indeterminate_count += import_indeterminate_count;
538 match import_indeterminate_count {
539 0 => self.determined_imports.push(import),
540 _ => self.indeterminate_imports.push(import),
541 }
542 }
543 self.assert_speculative = false;
544 }
545 }
546
547 pub(crate) fn finalize_imports(&mut self) {
548 let mut module_children = Default::default();
549 let mut ambig_module_children = Default::default();
550 for module in &self.local_modules {
551 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
552 }
553 self.module_children = module_children;
554 self.ambig_module_children = ambig_module_children;
555
556 let mut seen_spans = FxHashSet::default();
557 let mut errors = vec![];
558 let mut prev_root_id: NodeId = NodeId::ZERO;
559 let determined_imports = mem::take(&mut self.determined_imports);
560 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
561
562 let mut glob_error = false;
563 for (is_indeterminate, import) in determined_imports
564 .iter()
565 .map(|i| (false, i))
566 .chain(indeterminate_imports.iter().map(|i| (true, i)))
567 {
568 let unresolved_import_error = self.finalize_import(*import);
569 self.import_dummy_binding(*import, is_indeterminate);
572
573 let Some(err) = unresolved_import_error else { continue };
574
575 glob_error |= import.is_glob();
576
577 if let ImportKind::Single { source, ref decls, .. } = import.kind
578 && source.name == kw::SelfLower
579 && let PendingDecl::Ready(None) = decls.value_ns.get()
581 {
582 continue;
583 }
584
585 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
586 {
587 self.throw_unresolved_import_error(errors, glob_error);
590 errors = vec![];
591 }
592 if seen_spans.insert(err.span) {
593 errors.push((*import, err));
594 prev_root_id = import.root_id;
595 }
596 }
597
598 if !errors.is_empty() {
599 self.throw_unresolved_import_error(errors, glob_error);
600 return;
601 }
602
603 for import in &indeterminate_imports {
604 let path = import_path_to_string(
605 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
606 &import.kind,
607 import.span,
608 );
609 if path.contains("::") {
612 let err = UnresolvedImportError {
613 span: import.span,
614 label: None,
615 note: None,
616 suggestion: None,
617 candidates: None,
618 segment: None,
619 module: None,
620 };
621 errors.push((*import, err))
622 }
623 }
624
625 if !errors.is_empty() {
626 self.throw_unresolved_import_error(errors, glob_error);
627 }
628 }
629
630 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
631 for module in &self.local_modules {
632 for (key, resolution) in self.resolutions(*module).borrow().iter() {
633 let resolution = resolution.borrow();
634 let Some(binding) = resolution.best_decl() else { continue };
635
636 if let DeclKind::Import { import, .. } = binding.kind
637 && let Some(amb_binding) = binding.ambiguity
638 && binding.res() != Res::Err
639 && exported_ambiguities.contains(&binding)
640 {
641 self.lint_buffer.buffer_lint(
642 AMBIGUOUS_GLOB_REEXPORTS,
643 import.root_id,
644 import.root_span,
645 BuiltinLintDiag::AmbiguousGlobReexports {
646 name: key.ident.to_string(),
647 namespace: key.ns.descr().to_string(),
648 first_reexport_span: import.root_span,
649 duplicate_reexport_span: amb_binding.span,
650 },
651 );
652 }
653
654 if let Some(glob_decl) = resolution.glob_decl
655 && resolution.non_glob_decl.is_some()
656 {
657 if binding.res() != Res::Err
658 && glob_decl.res() != Res::Err
659 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
660 && let Some(glob_import_id) = glob_import.id()
661 && let glob_import_def_id = self.local_def_id(glob_import_id)
662 && self.effective_visibilities.is_exported(glob_import_def_id)
663 && glob_decl.vis.is_public()
664 && !binding.vis.is_public()
665 {
666 let binding_id = match binding.kind {
667 DeclKind::Def(res) => {
668 Some(self.def_id_to_node_id(res.def_id().expect_local()))
669 }
670 DeclKind::Import { import, .. } => import.id(),
671 };
672 if let Some(binding_id) = binding_id {
673 self.lint_buffer.buffer_lint(
674 HIDDEN_GLOB_REEXPORTS,
675 binding_id,
676 binding.span,
677 BuiltinLintDiag::HiddenGlobReexports {
678 name: key.ident.name.to_string(),
679 namespace: key.ns.descr().to_owned(),
680 glob_reexport_span: glob_decl.span,
681 private_item_span: binding.span,
682 },
683 );
684 }
685 }
686 }
687
688 if let DeclKind::Import { import, .. } = binding.kind
689 && let Some(binding_id) = import.id()
690 && let import_def_id = self.local_def_id(binding_id)
691 && self.effective_visibilities.is_exported(import_def_id)
692 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
693 && !matches!(reexported_kind, DefKind::Ctor(..))
694 && !reexported_def_id.is_local()
695 && self.tcx.is_private_dep(reexported_def_id.krate)
696 {
697 self.lint_buffer.buffer_lint(
698 EXPORTED_PRIVATE_DEPENDENCIES,
699 binding_id,
700 binding.span,
701 crate::errors::ReexportPrivateDependency {
702 name: key.ident.name,
703 kind: binding.res().descr(),
704 krate: self.tcx.crate_name(reexported_def_id.krate),
705 },
706 );
707 }
708 }
709 }
710 }
711
712 fn throw_unresolved_import_error(
713 &mut self,
714 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
715 glob_error: bool,
716 ) {
717 errors.retain(|(_import, err)| match err.module {
718 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
720 _ => err.segment != Some(kw::Underscore),
723 });
724 if errors.is_empty() {
725 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
726 return;
727 }
728
729 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
730
731 let paths = errors
732 .iter()
733 .map(|(import, err)| {
734 let path = import_path_to_string(
735 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
736 &import.kind,
737 err.span,
738 );
739 format!("`{path}`")
740 })
741 .collect::<Vec<_>>();
742 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
743
744 let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
745
746 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
747 diag.note(note.clone());
748 }
749
750 const MAX_LABEL_COUNT: usize = 10;
752
753 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
754 if let Some(label) = err.label {
755 diag.span_label(err.span, label);
756 }
757
758 if let Some((suggestions, msg, applicability)) = err.suggestion {
759 if suggestions.is_empty() {
760 diag.help(msg);
761 continue;
762 }
763 diag.multipart_suggestion(msg, suggestions, applicability);
764 }
765
766 if let Some(candidates) = &err.candidates {
767 match &import.kind {
768 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
769 self.tcx,
770 &mut diag,
771 Some(err.span),
772 candidates,
773 DiagMode::Import { append: false, unresolved_import: true },
774 (source != target)
775 .then(|| format!(" as {target}"))
776 .as_deref()
777 .unwrap_or(""),
778 ),
779 ImportKind::Single { nested: true, source, target, .. } => {
780 import_candidates(
781 self.tcx,
782 &mut diag,
783 None,
784 candidates,
785 DiagMode::Normal,
786 (source != target)
787 .then(|| format!(" as {target}"))
788 .as_deref()
789 .unwrap_or(""),
790 );
791 }
792 _ => {}
793 }
794 }
795
796 if matches!(import.kind, ImportKind::Single { .. })
797 && let Some(segment) = err.segment
798 && let Some(module) = err.module
799 {
800 self.find_cfg_stripped(&mut diag, &segment, module)
801 }
802 }
803
804 let guar = diag.emit();
805 if glob_error {
806 self.glob_error = Some(guar);
807 }
808 }
809
810 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
817 debug!(
818 "(resolving import for module) resolving import `{}::...` in `{}`",
819 Segment::names_to_string(&import.module_path),
820 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
821 );
822 let module = if let Some(module) = import.imported_module.get() {
823 module
824 } else {
825 let path_res = self.reborrow().maybe_resolve_path(
826 &import.module_path,
827 None,
828 &import.parent_scope,
829 Some(import),
830 );
831
832 match path_res {
833 PathResult::Module(module) => module,
834 PathResult::Indeterminate => return 3,
835 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
836 }
837 };
838
839 import.imported_module.set_unchecked(Some(module));
840 let (source, target, bindings, type_ns_only) = match import.kind {
841 ImportKind::Single { source, target, ref decls, type_ns_only, .. } => {
842 (source, target, decls, type_ns_only)
843 }
844 ImportKind::Glob { .. } => {
845 self.get_mut_unchecked().resolve_glob_import(import);
846 return 0;
847 }
848 _ => unreachable!(),
849 };
850
851 let mut indeterminate_count = 0;
852 self.per_ns_cm(|this, ns| {
853 if !type_ns_only || ns == TypeNS {
854 if bindings[ns].get() != PendingDecl::Pending {
855 return;
856 };
857 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
858 module,
859 source,
860 ns,
861 &import.parent_scope,
862 Some(import),
863 );
864 let parent = import.parent_scope.module;
865 let binding = match binding_result {
866 Ok(binding) => {
867 if binding.is_assoc_item()
868 && !this.tcx.features().import_trait_associated_functions()
869 {
870 feature_err(
871 this.tcx.sess,
872 sym::import_trait_associated_functions,
873 import.span,
874 "`use` associated items of traits is unstable",
875 )
876 .emit();
877 }
878 let import_decl = this.new_import_decl(binding, import);
880 this.get_mut_unchecked().plant_decl_into_local_module(
881 parent,
882 target,
883 ns,
884 import_decl,
885 );
886 PendingDecl::Ready(Some(import_decl))
887 }
888 Err(Determinacy::Determined) => {
889 if target.name != kw::Underscore {
891 let key = BindingKey::new(target, ns);
892 this.get_mut_unchecked().update_local_resolution(
893 parent,
894 key,
895 false,
896 |_, resolution| {
897 resolution.single_imports.swap_remove(&import);
898 },
899 );
900 }
901 PendingDecl::Ready(None)
902 }
903 Err(Determinacy::Undetermined) => {
904 indeterminate_count += 1;
905 PendingDecl::Pending
906 }
907 };
908 bindings[ns].set_unchecked(binding);
909 }
910 });
911
912 indeterminate_count
913 }
914
915 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
920 let ignore_decl = match &import.kind {
921 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
922 _ => None,
923 };
924 let ambiguity_errors_len =
925 |errors: &Vec<AmbiguityError<'_>>| errors.iter().filter(|error| !error.warning).count();
926 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
927 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
928
929 let privacy_errors_len = self.privacy_errors.len();
931
932 let path_res = self.cm().resolve_path(
933 &import.module_path,
934 None,
935 &import.parent_scope,
936 Some(finalize),
937 ignore_decl,
938 Some(import),
939 );
940
941 let no_ambiguity =
942 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
943
944 let module = match path_res {
945 PathResult::Module(module) => {
946 if let Some(initial_module) = import.imported_module.get() {
948 if module != initial_module && no_ambiguity {
949 span_bug!(import.span, "inconsistent resolution for an import");
950 }
951 } else if self.privacy_errors.is_empty() {
952 self.dcx()
953 .create_err(CannotDetermineImportResolution { span: import.span })
954 .emit();
955 }
956
957 module
958 }
959 PathResult::Failed {
960 is_error_from_last_segment: false,
961 span,
962 segment_name,
963 label,
964 suggestion,
965 module,
966 error_implied_by_parse_error: _,
967 } => {
968 if no_ambiguity {
969 assert!(import.imported_module.get().is_none());
970 self.report_error(
971 span,
972 ResolutionError::FailedToResolve {
973 segment: Some(segment_name),
974 label,
975 suggestion,
976 module,
977 },
978 );
979 }
980 return None;
981 }
982 PathResult::Failed {
983 is_error_from_last_segment: true,
984 span,
985 label,
986 suggestion,
987 module,
988 segment_name,
989 ..
990 } => {
991 if no_ambiguity {
992 assert!(import.imported_module.get().is_none());
993 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
994 m.opt_def_id()
995 } else {
996 None
997 };
998 let err = match self
999 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1000 {
1001 Some((suggestion, note)) => UnresolvedImportError {
1002 span,
1003 label: None,
1004 note,
1005 suggestion: Some((
1006 vec![(span, Segment::names_to_string(&suggestion))],
1007 String::from("a similar path exists"),
1008 Applicability::MaybeIncorrect,
1009 )),
1010 candidates: None,
1011 segment: Some(segment_name),
1012 module,
1013 },
1014 None => UnresolvedImportError {
1015 span,
1016 label: Some(label),
1017 note: None,
1018 suggestion,
1019 candidates: None,
1020 segment: Some(segment_name),
1021 module,
1022 },
1023 };
1024 return Some(err);
1025 }
1026 return None;
1027 }
1028 PathResult::NonModule(partial_res) => {
1029 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1030 assert!(import.imported_module.get().is_none());
1032 }
1033 return None;
1035 }
1036 PathResult::Indeterminate => unreachable!(),
1037 };
1038
1039 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1040 ImportKind::Single { source, target, ref decls, type_ns_only, id, .. } => {
1041 (source, target, decls, type_ns_only, id)
1042 }
1043 ImportKind::Glob { ref max_vis, id } => {
1044 if import.module_path.len() <= 1 {
1045 let mut full_path = import.module_path.clone();
1048 full_path.push(Segment::from_ident(Ident::dummy()));
1049 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1050 }
1051
1052 if let ModuleOrUniformRoot::Module(module) = module
1053 && module == import.parent_scope.module
1054 {
1055 return Some(UnresolvedImportError {
1057 span: import.span,
1058 label: Some(String::from("cannot glob-import a module into itself")),
1059 note: None,
1060 suggestion: None,
1061 candidates: None,
1062 segment: None,
1063 module: None,
1064 });
1065 }
1066 if let Some(max_vis) = max_vis.get()
1067 && !max_vis.is_at_least(import.vis, self.tcx)
1068 {
1069 let def_id = self.local_def_id(id);
1070 self.lint_buffer.buffer_lint(
1071 UNUSED_IMPORTS,
1072 id,
1073 import.span,
1074 crate::errors::RedundantImportVisibility {
1075 span: import.span,
1076 help: (),
1077 max_vis: max_vis.to_string(def_id, self.tcx),
1078 import_vis: import.vis.to_string(def_id, self.tcx),
1079 },
1080 );
1081 }
1082 return None;
1083 }
1084 _ => unreachable!(),
1085 };
1086
1087 if self.privacy_errors.len() != privacy_errors_len {
1088 let mut path = import.module_path.clone();
1091 path.push(Segment::from_ident(ident));
1092 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1093 &path,
1094 None,
1095 &import.parent_scope,
1096 Some(finalize),
1097 ignore_decl,
1098 None,
1099 ) {
1100 let res = module.res().map(|r| (r, ident));
1101 for error in &mut self.privacy_errors[privacy_errors_len..] {
1102 error.outermost_res = res;
1103 }
1104 }
1105 }
1106
1107 let mut all_ns_err = true;
1108 self.per_ns(|this, ns| {
1109 if !type_ns_only || ns == TypeNS {
1110 let binding = this.cm().resolve_ident_in_module(
1111 module,
1112 ident,
1113 ns,
1114 &import.parent_scope,
1115 Some(Finalize { report_private: false, ..finalize }),
1116 bindings[ns].get().decl(),
1117 Some(import),
1118 );
1119
1120 match binding {
1121 Ok(binding) => {
1122 let initial_res = bindings[ns].get().decl().map(|binding| {
1124 let initial_binding = binding.import_source();
1125 all_ns_err = false;
1126 if target.name == kw::Underscore
1127 && initial_binding.is_extern_crate()
1128 && !initial_binding.is_import()
1129 {
1130 let used = if import.module_path.is_empty() {
1131 Used::Scope
1132 } else {
1133 Used::Other
1134 };
1135 this.record_use(ident, binding, used);
1136 }
1137 initial_binding.res()
1138 });
1139 let res = binding.res();
1140 let has_ambiguity_error =
1141 this.ambiguity_errors.iter().any(|error| !error.warning);
1142 if res == Res::Err || has_ambiguity_error {
1143 this.dcx()
1144 .span_delayed_bug(import.span, "some error happened for an import");
1145 return;
1146 }
1147 if let Some(initial_res) = initial_res {
1148 if res != initial_res && !this.issue_145575_hack_applied {
1149 span_bug!(import.span, "inconsistent resolution for an import");
1150 }
1151 } else if this.privacy_errors.is_empty() {
1152 this.dcx()
1153 .create_err(CannotDetermineImportResolution { span: import.span })
1154 .emit();
1155 }
1156 }
1157 Err(..) => {
1158 }
1165 }
1166 }
1167 });
1168
1169 if all_ns_err {
1170 let mut all_ns_failed = true;
1171 self.per_ns(|this, ns| {
1172 if !type_ns_only || ns == TypeNS {
1173 let binding = this.cm().resolve_ident_in_module(
1174 module,
1175 ident,
1176 ns,
1177 &import.parent_scope,
1178 Some(finalize),
1179 None,
1180 None,
1181 );
1182 if binding.is_ok() {
1183 all_ns_failed = false;
1184 }
1185 }
1186 });
1187
1188 return if all_ns_failed {
1189 let names = match module {
1190 ModuleOrUniformRoot::Module(module) => {
1191 self.resolutions(module)
1192 .borrow()
1193 .iter()
1194 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1195 if i.name == ident.name {
1196 return None;
1197 } let resolution = resolution.borrow();
1200 if let Some(name_binding) = resolution.best_decl() {
1201 match name_binding.kind {
1202 DeclKind::Import { source_decl, .. } => {
1203 match source_decl.kind {
1204 DeclKind::Def(Res::Err) => None,
1207 _ => Some(i.name),
1208 }
1209 }
1210 _ => Some(i.name),
1211 }
1212 } else if resolution.single_imports.is_empty() {
1213 None
1214 } else {
1215 Some(i.name)
1216 }
1217 })
1218 .collect()
1219 }
1220 _ => Vec::new(),
1221 };
1222
1223 let lev_suggestion =
1224 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1225 (
1226 vec![(ident.span, suggestion.to_string())],
1227 String::from("a similar name exists in the module"),
1228 Applicability::MaybeIncorrect,
1229 )
1230 });
1231
1232 let (suggestion, note) =
1233 match self.check_for_module_export_macro(import, module, ident) {
1234 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1235 _ => (lev_suggestion, None),
1236 };
1237
1238 let label = match module {
1239 ModuleOrUniformRoot::Module(module) => {
1240 let module_str = module_to_string(module);
1241 if let Some(module_str) = module_str {
1242 format!("no `{ident}` in `{module_str}`")
1243 } else {
1244 format!("no `{ident}` in the root")
1245 }
1246 }
1247 _ => {
1248 if !ident.is_path_segment_keyword() {
1249 format!("no external crate `{ident}`")
1250 } else {
1251 format!("no `{ident}` in the root")
1254 }
1255 }
1256 };
1257
1258 let parent_suggestion =
1259 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1260
1261 Some(UnresolvedImportError {
1262 span: import.span,
1263 label: Some(label),
1264 note,
1265 suggestion,
1266 candidates: if !parent_suggestion.is_empty() {
1267 Some(parent_suggestion)
1268 } else {
1269 None
1270 },
1271 module: import.imported_module.get().and_then(|module| {
1272 if let ModuleOrUniformRoot::Module(m) = module {
1273 m.opt_def_id()
1274 } else {
1275 None
1276 }
1277 }),
1278 segment: Some(ident.name),
1279 })
1280 } else {
1281 None
1283 };
1284 }
1285
1286 let mut reexport_error = None;
1287 let mut any_successful_reexport = false;
1288 let mut crate_private_reexport = false;
1289 self.per_ns(|this, ns| {
1290 let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1291 return;
1292 };
1293
1294 if !binding.vis.is_at_least(import.vis, this.tcx) {
1295 reexport_error = Some((ns, binding));
1296 if let Visibility::Restricted(binding_def_id) = binding.vis
1297 && binding_def_id.is_top_level_module()
1298 {
1299 crate_private_reexport = true;
1300 }
1301 } else {
1302 any_successful_reexport = true;
1303 }
1304 });
1305
1306 if !any_successful_reexport {
1308 let (ns, binding) = reexport_error.unwrap();
1309 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1310 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1311 self.lint_buffer.buffer_lint(
1312 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1313 import_id,
1314 import.span,
1315 crate::errors::PrivateExternCrateReexport {
1316 ident,
1317 sugg: extern_crate_sp.shrink_to_lo(),
1318 },
1319 );
1320 } else if ns == TypeNS {
1321 let err = if crate_private_reexport {
1322 self.dcx()
1323 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1324 } else {
1325 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1326 };
1327 err.emit();
1328 } else {
1329 let mut err = if crate_private_reexport {
1330 self.dcx()
1331 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1332 } else {
1333 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1334 };
1335
1336 match binding.kind {
1337 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1338 if self.get_macro_by_def_id(def_id).macro_rules =>
1340 {
1341 err.subdiagnostic( ConsiderAddingMacroExport {
1342 span: binding.span,
1343 });
1344 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1345 vis_span: import.vis_span,
1346 });
1347 }
1348 _ => {
1349 err.subdiagnostic( ConsiderMarkingAsPub {
1350 span: import.span,
1351 ident,
1352 });
1353 }
1354 }
1355 err.emit();
1356 }
1357 }
1358
1359 if import.module_path.len() <= 1 {
1360 let mut full_path = import.module_path.clone();
1363 full_path.push(Segment::from_ident(ident));
1364 self.per_ns(|this, ns| {
1365 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1366 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1367 }
1368 });
1369 }
1370
1371 self.per_ns(|this, ns| {
1375 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1376 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1377 }
1378 });
1379
1380 debug!("(resolving single import) successfully resolved import");
1381 None
1382 }
1383
1384 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1385 let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1387 unreachable!()
1388 };
1389
1390 if source != target {
1392 return false;
1393 }
1394
1395 if import.parent_scope.expansion != LocalExpnId::ROOT {
1397 return false;
1398 }
1399
1400 if self.import_use_map.get(&import) == Some(&Used::Other)
1405 || self.effective_visibilities.is_exported(self.local_def_id(id))
1406 {
1407 return false;
1408 }
1409
1410 let mut is_redundant = true;
1411 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1412 self.per_ns(|this, ns| {
1413 let binding = decls[ns].get().decl().map(|b| b.import_source());
1414 if is_redundant && let Some(binding) = binding {
1415 if binding.res() == Res::Err {
1416 return;
1417 }
1418
1419 match this.cm().resolve_ident_in_scope_set(
1420 target,
1421 ScopeSet::All(ns),
1422 &import.parent_scope,
1423 None,
1424 false,
1425 decls[ns].get().decl(),
1426 None,
1427 ) {
1428 Ok(other_binding) => {
1429 is_redundant = binding.res() == other_binding.res()
1430 && !other_binding.is_ambiguity_recursive();
1431 if is_redundant {
1432 redundant_span[ns] =
1433 Some((other_binding.span, other_binding.is_import()));
1434 }
1435 }
1436 Err(_) => is_redundant = false,
1437 }
1438 }
1439 });
1440
1441 if is_redundant && !redundant_span.is_empty() {
1442 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1443 redundant_spans.sort();
1444 redundant_spans.dedup();
1445 self.lint_buffer.buffer_lint(
1446 REDUNDANT_IMPORTS,
1447 id,
1448 import.span,
1449 BuiltinLintDiag::RedundantImport(redundant_spans, source),
1450 );
1451 return true;
1452 }
1453
1454 false
1455 }
1456
1457 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1458 let ImportKind::Glob { id, .. } = import.kind else { unreachable!() };
1460
1461 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1462 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1463 return;
1464 };
1465
1466 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1467 feature_err(
1468 self.tcx.sess,
1469 sym::import_trait_associated_functions,
1470 import.span,
1471 "`use` associated items of traits is unstable",
1472 )
1473 .emit();
1474 }
1475
1476 if module == import.parent_scope.module {
1477 return;
1478 }
1479
1480 module.glob_importers.borrow_mut_unchecked().push(import);
1482
1483 let bindings = self
1486 .resolutions(module)
1487 .borrow()
1488 .iter()
1489 .filter_map(|(key, resolution)| {
1490 resolution.borrow().binding().map(|binding| (*key, binding))
1491 })
1492 .collect::<Vec<_>>();
1493 for (mut key, binding) in bindings {
1494 let scope = match key.ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
1495 Some(Some(def)) => self.expn_def_scope(def),
1496 Some(None) => import.parent_scope.module,
1497 None => continue,
1498 };
1499 if self.is_accessible_from(binding.vis, scope) {
1500 let import_decl = self.new_import_decl(binding, import);
1501 let warn_ambiguity = self
1502 .resolution(import.parent_scope.module, key)
1503 .and_then(|r| r.binding())
1504 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1505 let _ = self.try_plant_decl_into_local_module(
1506 import.parent_scope.module,
1507 key.ident.0,
1508 key.ns,
1509 import_decl,
1510 warn_ambiguity,
1511 );
1512 }
1513 }
1514
1515 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1517 }
1518
1519 fn finalize_resolutions_in(
1522 &self,
1523 module: Module<'ra>,
1524 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1525 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1526 ) {
1527 *module.globs.borrow_mut(self) = Vec::new();
1529
1530 let Some(def_id) = module.opt_def_id() else { return };
1531
1532 let mut children = Vec::new();
1533 let mut ambig_children = Vec::new();
1534
1535 module.for_each_child(self, |this, ident, _, binding| {
1536 let res = binding.res().expect_non_local();
1537 if res != def::Res::Err {
1538 let child = |reexport_chain| ModChild {
1539 ident: ident.0,
1540 res,
1541 vis: binding.vis,
1542 reexport_chain,
1543 };
1544 if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1545 let main = child(ambig_binding1.reexport_chain(this));
1546 let second = ModChild {
1547 ident: ident.0,
1548 res: ambig_binding2.res().expect_non_local(),
1549 vis: ambig_binding2.vis,
1550 reexport_chain: ambig_binding2.reexport_chain(this),
1551 };
1552 ambig_children.push(AmbigModChild { main, second })
1553 } else {
1554 children.push(child(binding.reexport_chain(this)));
1555 }
1556 }
1557 });
1558
1559 if !children.is_empty() {
1560 module_children.insert(def_id.expect_local(), children);
1561 }
1562 if !ambig_children.is_empty() {
1563 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1564 }
1565 }
1566}
1567
1568fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1569 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1570 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1571 if let Some(pos) = pos {
1572 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1573 names_to_string(names.iter().map(|ident| ident.name))
1574 } else {
1575 let names = if global { &names[1..] } else { names };
1576 if names.is_empty() {
1577 import_kind_to_string(import_kind)
1578 } else {
1579 format!(
1580 "{}::{}",
1581 names_to_string(names.iter().map(|ident| ident.name)),
1582 import_kind_to_string(import_kind),
1583 )
1584 }
1585 }
1586}
1587
1588fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1589 match import_kind {
1590 ImportKind::Single { source, .. } => source.to_string(),
1591 ImportKind::Glob { .. } => "*".to_string(),
1592 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1593 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1594 ImportKind::MacroExport => "#[macro_export]".to_string(),
1595 }
1596}