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