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::{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 smallvec::SmallVec;
25use tracing::debug;
26
27use crate::Namespace::{self, *};
28use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
29use crate::errors::{
30 CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
31 CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
32 ConsiderAddingMacroExport, ConsiderMarkingAsPub, ConsiderMarkingAsPubCrate,
33};
34use crate::ref_mut::CmCell;
35use crate::{
36 AmbiguityError, AmbiguityKind, BindingKey, CmResolver, Determinacy, Finalize, ImportSuggestion,
37 Module, ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, ParentScope,
38 PathResult, PerNS, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string,
39 names_to_string,
40};
41
42type Res = def::Res<NodeId>;
43
44#[derive(Clone, Copy, Default, PartialEq)]
46pub(crate) enum PendingBinding<'ra> {
47 Ready(Option<NameBinding<'ra>>),
48 #[default]
49 Pending,
50}
51
52impl<'ra> PendingBinding<'ra> {
53 pub(crate) fn binding(self) -> Option<NameBinding<'ra>> {
54 match self {
55 PendingBinding::Ready(binding) => binding,
56 PendingBinding::Pending => None,
57 }
58 }
59}
60
61#[derive(Clone)]
63pub(crate) enum ImportKind<'ra> {
64 Single {
65 source: Ident,
67 target: Ident,
70 bindings: PerNS<CmCell<PendingBinding<'ra>>>,
72 type_ns_only: bool,
74 nested: bool,
76 id: NodeId,
88 },
89 Glob {
90 max_vis: CmCell<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 { max_vis, id } => {
128 f.debug_struct("Glob").field("max_vis", max_vis).field("id", id).finish()
129 }
130 ExternCrate { source, target, id } => f
131 .debug_struct("ExternCrate")
132 .field("source", source)
133 .field("target", target)
134 .field("id", id)
135 .finish(),
136 MacroUse { warn_private } => {
137 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
138 }
139 MacroExport => f.debug_struct("MacroExport").finish(),
140 }
141 }
142}
143
144#[derive(Debug, Clone)]
146pub(crate) struct ImportData<'ra> {
147 pub kind: ImportKind<'ra>,
148
149 pub root_id: NodeId,
159
160 pub use_span: Span,
162
163 pub use_span_with_attributes: Span,
165
166 pub has_attributes: bool,
168
169 pub span: Span,
171
172 pub root_span: Span,
174
175 pub parent_scope: ParentScope<'ra>,
176 pub module_path: Vec<Segment>,
177 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
186 pub vis: Visibility,
187
188 pub vis_span: Span,
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_unchecked(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_local(
338 &mut self,
339 module: Module<'ra>,
340 ident: Ident,
341 ns: Namespace,
342 binding: NameBinding<'ra>,
343 warn_ambiguity: bool,
344 ) -> Result<(), NameBinding<'ra>> {
345 let res = binding.res();
346 self.check_reserved_macro_name(ident, res);
347 self.set_binding_parent_module(binding, module);
348 let key = BindingKey::new_disambiguated(ident, ns, || {
352 module.underscore_disambiguator.update_unchecked(|d| d + 1);
353 module.underscore_disambiguator.get()
354 });
355 self.update_local_resolution(module, key, warn_ambiguity, |this, resolution| {
356 if let Some(old_binding) = resolution.best_binding() {
357 if res == Res::Err && old_binding.res() != Res::Err {
358 return Ok(());
360 }
361 match (old_binding.is_glob_import(), binding.is_glob_import()) {
362 (true, true) => {
363 let (glob_binding, old_glob_binding) = (binding, old_binding);
364 if !binding.is_ambiguity_recursive()
366 && let NameBindingKind::Import { import: old_import, .. } =
367 old_glob_binding.kind
368 && let NameBindingKind::Import { import, .. } = glob_binding.kind
369 && old_import == import
370 {
371 resolution.glob_binding = Some(glob_binding);
375 } else if res != old_glob_binding.res() {
376 resolution.glob_binding = Some(this.new_ambiguity_binding(
377 AmbiguityKind::GlobVsGlob,
378 old_glob_binding,
379 glob_binding,
380 warn_ambiguity,
381 ));
382 } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) {
383 resolution.glob_binding = Some(glob_binding);
385 } else if binding.is_ambiguity_recursive() {
386 resolution.glob_binding =
387 Some(this.new_warn_ambiguity_binding(glob_binding));
388 }
389 }
390 (old_glob @ true, false) | (old_glob @ false, true) => {
391 let (glob_binding, non_glob_binding) =
392 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
393 if ns == MacroNS
394 && non_glob_binding.expansion != LocalExpnId::ROOT
395 && glob_binding.res() != non_glob_binding.res()
396 {
397 resolution.non_glob_binding = Some(this.new_ambiguity_binding(
398 AmbiguityKind::GlobVsExpanded,
399 non_glob_binding,
400 glob_binding,
401 false,
402 ));
403 } else {
404 resolution.non_glob_binding = Some(non_glob_binding);
405 }
406
407 if let Some(old_glob_binding) = resolution.glob_binding {
408 assert!(old_glob_binding.is_glob_import());
409 if glob_binding.res() != old_glob_binding.res() {
410 resolution.glob_binding = Some(this.new_ambiguity_binding(
411 AmbiguityKind::GlobVsGlob,
412 old_glob_binding,
413 glob_binding,
414 false,
415 ));
416 } else if !old_glob_binding.vis.is_at_least(binding.vis, this.tcx) {
417 resolution.glob_binding = Some(glob_binding);
418 }
419 } else {
420 resolution.glob_binding = Some(glob_binding);
421 }
422 }
423 (false, false) => {
424 return Err(old_binding);
425 }
426 }
427 } else {
428 if binding.is_glob_import() {
429 resolution.glob_binding = Some(binding);
430 } else {
431 resolution.non_glob_binding = Some(binding);
432 }
433 }
434
435 Ok(())
436 })
437 }
438
439 fn new_ambiguity_binding(
440 &self,
441 ambiguity_kind: AmbiguityKind,
442 primary_binding: NameBinding<'ra>,
443 secondary_binding: NameBinding<'ra>,
444 warn_ambiguity: bool,
445 ) -> NameBinding<'ra> {
446 let ambiguity = Some((secondary_binding, ambiguity_kind));
447 let data = NameBindingData { ambiguity, warn_ambiguity, ..*primary_binding };
448 self.arenas.alloc_name_binding(data)
449 }
450
451 fn new_warn_ambiguity_binding(&self, binding: NameBinding<'ra>) -> NameBinding<'ra> {
452 assert!(binding.is_ambiguity_recursive());
453 self.arenas.alloc_name_binding(NameBindingData { warn_ambiguity: true, ..*binding })
454 }
455
456 fn update_local_resolution<T, F>(
459 &mut self,
460 module: Module<'ra>,
461 key: BindingKey,
462 warn_ambiguity: bool,
463 f: F,
464 ) -> T
465 where
466 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
467 {
468 let (binding, t, warn_ambiguity) = {
471 let resolution = &mut *self.resolution_or_default(module, key).borrow_mut_unchecked();
472 let old_binding = resolution.binding();
473
474 let t = f(self, resolution);
475
476 if let Some(binding) = resolution.binding()
477 && old_binding != Some(binding)
478 {
479 (binding, t, warn_ambiguity || old_binding.is_some())
480 } else {
481 return t;
482 }
483 };
484
485 let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
486 return t;
487 };
488
489 for import in glob_importers.iter() {
491 let mut ident = key.ident;
492 let scope = match ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
493 Some(Some(def)) => self.expn_def_scope(def),
494 Some(None) => import.parent_scope.module,
495 None => continue,
496 };
497 if self.is_accessible_from(binding.vis, scope) {
498 let imported_binding = self.import(binding, *import);
499 let _ = self.try_define_local(
500 import.parent_scope.module,
501 ident.0,
502 key.ns,
503 imported_binding,
504 warn_ambiguity,
505 );
506 }
507 }
508
509 t
510 }
511
512 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
515 if let ImportKind::Single { target, ref bindings, .. } = import.kind {
516 if !(is_indeterminate
517 || bindings.iter().all(|binding| binding.get().binding().is_none()))
518 {
519 return; }
521 let dummy_binding = self.dummy_binding;
522 let dummy_binding = self.import(dummy_binding, import);
523 self.per_ns(|this, ns| {
524 let module = import.parent_scope.module;
525 let _ = this.try_define_local(module, target, ns, dummy_binding, false);
526 if target.name != kw::Underscore {
528 let key = BindingKey::new(target, ns);
529 this.update_local_resolution(module, key, false, |_, resolution| {
530 resolution.single_imports.swap_remove(&import);
531 })
532 }
533 });
534 self.record_use(target, dummy_binding, Used::Other);
535 } else if import.imported_module.get().is_none() {
536 self.import_use_map.insert(import, Used::Other);
537 if let Some(id) = import.id() {
538 self.used_imports.insert(id);
539 }
540 }
541 }
542
543 pub(crate) fn resolve_imports(&mut self) {
554 let mut prev_indeterminate_count = usize::MAX;
555 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
556 while indeterminate_count < prev_indeterminate_count {
557 prev_indeterminate_count = indeterminate_count;
558 indeterminate_count = 0;
559 self.assert_speculative = true;
560 for import in mem::take(&mut self.indeterminate_imports) {
561 let import_indeterminate_count = self.cm().resolve_import(import);
562 indeterminate_count += import_indeterminate_count;
563 match import_indeterminate_count {
564 0 => self.determined_imports.push(import),
565 _ => self.indeterminate_imports.push(import),
566 }
567 }
568 self.assert_speculative = false;
569 }
570 }
571
572 pub(crate) fn finalize_imports(&mut self) {
573 let mut module_children = Default::default();
574 for module in &self.local_modules {
575 self.finalize_resolutions_in(*module, &mut module_children);
576 }
577 self.module_children = module_children;
578
579 let mut seen_spans = FxHashSet::default();
580 let mut errors = vec![];
581 let mut prev_root_id: NodeId = NodeId::ZERO;
582 let determined_imports = mem::take(&mut self.determined_imports);
583 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
584
585 let mut glob_error = false;
586 for (is_indeterminate, import) in determined_imports
587 .iter()
588 .map(|i| (false, i))
589 .chain(indeterminate_imports.iter().map(|i| (true, i)))
590 {
591 let unresolved_import_error = self.finalize_import(*import);
592 self.import_dummy_binding(*import, is_indeterminate);
595
596 let Some(err) = unresolved_import_error else { continue };
597
598 glob_error |= import.is_glob();
599
600 if let ImportKind::Single { source, ref bindings, .. } = import.kind
601 && source.name == kw::SelfLower
602 && let PendingBinding::Ready(None) = bindings.value_ns.get()
604 {
605 continue;
606 }
607
608 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
609 {
610 self.throw_unresolved_import_error(errors, glob_error);
613 errors = vec![];
614 }
615 if seen_spans.insert(err.span) {
616 errors.push((*import, err));
617 prev_root_id = import.root_id;
618 }
619 }
620
621 if !errors.is_empty() {
622 self.throw_unresolved_import_error(errors, glob_error);
623 return;
624 }
625
626 for import in &indeterminate_imports {
627 let path = import_path_to_string(
628 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
629 &import.kind,
630 import.span,
631 );
632 if path.contains("::") {
635 let err = UnresolvedImportError {
636 span: import.span,
637 label: None,
638 note: None,
639 suggestion: None,
640 candidates: None,
641 segment: None,
642 module: None,
643 };
644 errors.push((*import, err))
645 }
646 }
647
648 if !errors.is_empty() {
649 self.throw_unresolved_import_error(errors, glob_error);
650 }
651 }
652
653 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<NameBinding<'ra>>) {
654 for module in &self.local_modules {
655 for (key, resolution) in self.resolutions(*module).borrow().iter() {
656 let resolution = resolution.borrow();
657 let Some(binding) = resolution.best_binding() else { continue };
658
659 if let NameBindingKind::Import { import, .. } = binding.kind
660 && let Some((amb_binding, _)) = binding.ambiguity
661 && binding.res() != Res::Err
662 && exported_ambiguities.contains(&binding)
663 {
664 self.lint_buffer.buffer_lint(
665 AMBIGUOUS_GLOB_REEXPORTS,
666 import.root_id,
667 import.root_span,
668 BuiltinLintDiag::AmbiguousGlobReexports {
669 name: key.ident.to_string(),
670 namespace: key.ns.descr().to_string(),
671 first_reexport_span: import.root_span,
672 duplicate_reexport_span: amb_binding.span,
673 },
674 );
675 }
676
677 if let Some(glob_binding) = resolution.glob_binding
678 && resolution.non_glob_binding.is_some()
679 {
680 if binding.res() != Res::Err
681 && glob_binding.res() != Res::Err
682 && let NameBindingKind::Import { import: glob_import, .. } =
683 glob_binding.kind
684 && let Some(glob_import_id) = glob_import.id()
685 && let glob_import_def_id = self.local_def_id(glob_import_id)
686 && self.effective_visibilities.is_exported(glob_import_def_id)
687 && glob_binding.vis.is_public()
688 && !binding.vis.is_public()
689 {
690 let binding_id = match binding.kind {
691 NameBindingKind::Res(res) => {
692 Some(self.def_id_to_node_id(res.def_id().expect_local()))
693 }
694 NameBindingKind::Import { import, .. } => import.id(),
695 };
696 if let Some(binding_id) = binding_id {
697 self.lint_buffer.buffer_lint(
698 HIDDEN_GLOB_REEXPORTS,
699 binding_id,
700 binding.span,
701 BuiltinLintDiag::HiddenGlobReexports {
702 name: key.ident.name.to_string(),
703 namespace: key.ns.descr().to_owned(),
704 glob_reexport_span: glob_binding.span,
705 private_item_span: binding.span,
706 },
707 );
708 }
709 }
710 }
711
712 if let NameBindingKind::Import { import, .. } = binding.kind
713 && let Some(binding_id) = import.id()
714 && let import_def_id = self.local_def_id(binding_id)
715 && self.effective_visibilities.is_exported(import_def_id)
716 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
717 && !matches!(reexported_kind, DefKind::Ctor(..))
718 && !reexported_def_id.is_local()
719 && self.tcx.is_private_dep(reexported_def_id.krate)
720 {
721 self.lint_buffer.buffer_lint(
722 EXPORTED_PRIVATE_DEPENDENCIES,
723 binding_id,
724 binding.span,
725 crate::errors::ReexportPrivateDependency {
726 name: key.ident.name,
727 kind: binding.res().descr(),
728 krate: self.tcx.crate_name(reexported_def_id.krate),
729 },
730 );
731 }
732 }
733 }
734 }
735
736 fn throw_unresolved_import_error(
737 &mut self,
738 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
739 glob_error: bool,
740 ) {
741 errors.retain(|(_import, err)| match err.module {
742 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
744 _ => err.segment != Some(kw::Underscore),
747 });
748 if errors.is_empty() {
749 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
750 return;
751 }
752
753 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
754
755 let paths = errors
756 .iter()
757 .map(|(import, err)| {
758 let path = import_path_to_string(
759 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
760 &import.kind,
761 err.span,
762 );
763 format!("`{path}`")
764 })
765 .collect::<Vec<_>>();
766 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
767
768 let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
769
770 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
771 diag.note(note.clone());
772 }
773
774 const MAX_LABEL_COUNT: usize = 10;
776
777 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
778 if let Some(label) = err.label {
779 diag.span_label(err.span, label);
780 }
781
782 if let Some((suggestions, msg, applicability)) = err.suggestion {
783 if suggestions.is_empty() {
784 diag.help(msg);
785 continue;
786 }
787 diag.multipart_suggestion(msg, suggestions, applicability);
788 }
789
790 if let Some(candidates) = &err.candidates {
791 match &import.kind {
792 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
793 self.tcx,
794 &mut diag,
795 Some(err.span),
796 candidates,
797 DiagMode::Import { append: false, unresolved_import: true },
798 (source != target)
799 .then(|| format!(" as {target}"))
800 .as_deref()
801 .unwrap_or(""),
802 ),
803 ImportKind::Single { nested: true, source, target, .. } => {
804 import_candidates(
805 self.tcx,
806 &mut diag,
807 None,
808 candidates,
809 DiagMode::Normal,
810 (source != target)
811 .then(|| format!(" as {target}"))
812 .as_deref()
813 .unwrap_or(""),
814 );
815 }
816 _ => {}
817 }
818 }
819
820 if matches!(import.kind, ImportKind::Single { .. })
821 && let Some(segment) = err.segment
822 && let Some(module) = err.module
823 {
824 self.find_cfg_stripped(&mut diag, &segment, module)
825 }
826 }
827
828 let guar = diag.emit();
829 if glob_error {
830 self.glob_error = Some(guar);
831 }
832 }
833
834 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
841 debug!(
842 "(resolving import for module) resolving import `{}::...` in `{}`",
843 Segment::names_to_string(&import.module_path),
844 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
845 );
846 let module = if let Some(module) = import.imported_module.get() {
847 module
848 } else {
849 let path_res = self.reborrow().maybe_resolve_path(
850 &import.module_path,
851 None,
852 &import.parent_scope,
853 Some(import),
854 );
855
856 match path_res {
857 PathResult::Module(module) => module,
858 PathResult::Indeterminate => return 3,
859 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
860 }
861 };
862
863 import.imported_module.set_unchecked(Some(module));
864 let (source, target, bindings, type_ns_only) = match import.kind {
865 ImportKind::Single { source, target, ref bindings, type_ns_only, .. } => {
866 (source, target, bindings, type_ns_only)
867 }
868 ImportKind::Glob { .. } => {
869 self.get_mut_unchecked().resolve_glob_import(import);
870 return 0;
871 }
872 _ => unreachable!(),
873 };
874
875 let mut indeterminate_count = 0;
876 self.per_ns_cm(|this, ns| {
877 if !type_ns_only || ns == TypeNS {
878 if bindings[ns].get() != PendingBinding::Pending {
879 return;
880 };
881 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
882 module,
883 source,
884 ns,
885 &import.parent_scope,
886 Some(import),
887 );
888 let parent = import.parent_scope.module;
889 let binding = match binding_result {
890 Ok(binding) => {
891 if binding.is_assoc_item()
892 && !this.tcx.features().import_trait_associated_functions()
893 {
894 feature_err(
895 this.tcx.sess,
896 sym::import_trait_associated_functions,
897 import.span,
898 "`use` associated items of traits is unstable",
899 )
900 .emit();
901 }
902 let imported_binding = this.import(binding, import);
904 this.get_mut_unchecked().define_binding_local(
905 parent,
906 target,
907 ns,
908 imported_binding,
909 );
910 PendingBinding::Ready(Some(imported_binding))
911 }
912 Err(Determinacy::Determined) => {
913 if target.name != kw::Underscore {
915 let key = BindingKey::new(target, ns);
916 this.get_mut_unchecked().update_local_resolution(
917 parent,
918 key,
919 false,
920 |_, resolution| {
921 resolution.single_imports.swap_remove(&import);
922 },
923 );
924 }
925 PendingBinding::Ready(None)
926 }
927 Err(Determinacy::Undetermined) => {
928 indeterminate_count += 1;
929 PendingBinding::Pending
930 }
931 };
932 bindings[ns].set_unchecked(binding);
933 }
934 });
935
936 indeterminate_count
937 }
938
939 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
944 let ignore_binding = match &import.kind {
945 ImportKind::Single { bindings, .. } => bindings[TypeNS].get().binding(),
946 _ => None,
947 };
948 let ambiguity_errors_len =
949 |errors: &Vec<AmbiguityError<'_>>| errors.iter().filter(|error| !error.warning).count();
950 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
951 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
952
953 let privacy_errors_len = self.privacy_errors.len();
955
956 let path_res = self.cm().resolve_path(
957 &import.module_path,
958 None,
959 &import.parent_scope,
960 Some(finalize),
961 ignore_binding,
962 Some(import),
963 );
964
965 let no_ambiguity =
966 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
967
968 let module = match path_res {
969 PathResult::Module(module) => {
970 if let Some(initial_module) = import.imported_module.get() {
972 if module != initial_module && no_ambiguity {
973 span_bug!(import.span, "inconsistent resolution for an import");
974 }
975 } else if self.privacy_errors.is_empty() {
976 self.dcx()
977 .create_err(CannotDetermineImportResolution { span: import.span })
978 .emit();
979 }
980
981 module
982 }
983 PathResult::Failed {
984 is_error_from_last_segment: false,
985 span,
986 segment_name,
987 label,
988 suggestion,
989 module,
990 error_implied_by_parse_error: _,
991 } => {
992 if no_ambiguity {
993 assert!(import.imported_module.get().is_none());
994 self.report_error(
995 span,
996 ResolutionError::FailedToResolve {
997 segment: Some(segment_name),
998 label,
999 suggestion,
1000 module,
1001 },
1002 );
1003 }
1004 return None;
1005 }
1006 PathResult::Failed {
1007 is_error_from_last_segment: true,
1008 span,
1009 label,
1010 suggestion,
1011 module,
1012 segment_name,
1013 ..
1014 } => {
1015 if no_ambiguity {
1016 assert!(import.imported_module.get().is_none());
1017 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1018 m.opt_def_id()
1019 } else {
1020 None
1021 };
1022 let err = match self
1023 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1024 {
1025 Some((suggestion, note)) => UnresolvedImportError {
1026 span,
1027 label: None,
1028 note,
1029 suggestion: Some((
1030 vec![(span, Segment::names_to_string(&suggestion))],
1031 String::from("a similar path exists"),
1032 Applicability::MaybeIncorrect,
1033 )),
1034 candidates: None,
1035 segment: Some(segment_name),
1036 module,
1037 },
1038 None => UnresolvedImportError {
1039 span,
1040 label: Some(label),
1041 note: None,
1042 suggestion,
1043 candidates: None,
1044 segment: Some(segment_name),
1045 module,
1046 },
1047 };
1048 return Some(err);
1049 }
1050 return None;
1051 }
1052 PathResult::NonModule(partial_res) => {
1053 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1054 assert!(import.imported_module.get().is_none());
1056 }
1057 return None;
1059 }
1060 PathResult::Indeterminate => unreachable!(),
1061 };
1062
1063 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1064 ImportKind::Single { source, target, ref bindings, type_ns_only, id, .. } => {
1065 (source, target, bindings, type_ns_only, id)
1066 }
1067 ImportKind::Glob { ref max_vis, id } => {
1068 if import.module_path.len() <= 1 {
1069 let mut full_path = import.module_path.clone();
1072 full_path.push(Segment::from_ident(Ident::dummy()));
1073 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1074 }
1075
1076 if let ModuleOrUniformRoot::Module(module) = module
1077 && module == import.parent_scope.module
1078 {
1079 return Some(UnresolvedImportError {
1081 span: import.span,
1082 label: Some(String::from("cannot glob-import a module into itself")),
1083 note: None,
1084 suggestion: None,
1085 candidates: None,
1086 segment: None,
1087 module: None,
1088 });
1089 }
1090 if let Some(max_vis) = max_vis.get()
1091 && !max_vis.is_at_least(import.vis, self.tcx)
1092 {
1093 let def_id = self.local_def_id(id);
1094 self.lint_buffer.buffer_lint(
1095 UNUSED_IMPORTS,
1096 id,
1097 import.span,
1098 BuiltinLintDiag::RedundantImportVisibility {
1099 max_vis: max_vis.to_string(def_id, self.tcx),
1100 import_vis: import.vis.to_string(def_id, self.tcx),
1101 span: import.span,
1102 },
1103 );
1104 }
1105 return None;
1106 }
1107 _ => unreachable!(),
1108 };
1109
1110 if self.privacy_errors.len() != privacy_errors_len {
1111 let mut path = import.module_path.clone();
1114 path.push(Segment::from_ident(ident));
1115 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1116 &path,
1117 None,
1118 &import.parent_scope,
1119 Some(finalize),
1120 ignore_binding,
1121 None,
1122 ) {
1123 let res = module.res().map(|r| (r, ident));
1124 for error in &mut self.privacy_errors[privacy_errors_len..] {
1125 error.outermost_res = res;
1126 }
1127 }
1128 }
1129
1130 let mut all_ns_err = true;
1131 self.per_ns(|this, ns| {
1132 if !type_ns_only || ns == TypeNS {
1133 let binding = this.cm().resolve_ident_in_module(
1134 module,
1135 ident,
1136 ns,
1137 &import.parent_scope,
1138 Some(Finalize { report_private: false, ..finalize }),
1139 bindings[ns].get().binding(),
1140 Some(import),
1141 );
1142
1143 match binding {
1144 Ok(binding) => {
1145 let initial_res = bindings[ns].get().binding().map(|binding| {
1147 let initial_binding = binding.import_source();
1148 all_ns_err = false;
1149 if target.name == kw::Underscore
1150 && initial_binding.is_extern_crate()
1151 && !initial_binding.is_import()
1152 {
1153 let used = if import.module_path.is_empty() {
1154 Used::Scope
1155 } else {
1156 Used::Other
1157 };
1158 this.record_use(ident, binding, used);
1159 }
1160 initial_binding.res()
1161 });
1162 let res = binding.res();
1163 let has_ambiguity_error =
1164 this.ambiguity_errors.iter().any(|error| !error.warning);
1165 if res == Res::Err || has_ambiguity_error {
1166 this.dcx()
1167 .span_delayed_bug(import.span, "some error happened for an import");
1168 return;
1169 }
1170 if let Some(initial_res) = initial_res {
1171 if res != initial_res {
1172 span_bug!(import.span, "inconsistent resolution for an import");
1173 }
1174 } else if this.privacy_errors.is_empty() {
1175 this.dcx()
1176 .create_err(CannotDetermineImportResolution { span: import.span })
1177 .emit();
1178 }
1179 }
1180 Err(..) => {
1181 }
1188 }
1189 }
1190 });
1191
1192 if all_ns_err {
1193 let mut all_ns_failed = true;
1194 self.per_ns(|this, ns| {
1195 if !type_ns_only || ns == TypeNS {
1196 let binding = this.cm().resolve_ident_in_module(
1197 module,
1198 ident,
1199 ns,
1200 &import.parent_scope,
1201 Some(finalize),
1202 None,
1203 None,
1204 );
1205 if binding.is_ok() {
1206 all_ns_failed = false;
1207 }
1208 }
1209 });
1210
1211 return if all_ns_failed {
1212 let names = match module {
1213 ModuleOrUniformRoot::Module(module) => {
1214 self.resolutions(module)
1215 .borrow()
1216 .iter()
1217 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1218 if i.name == ident.name {
1219 return None;
1220 } let resolution = resolution.borrow();
1223 if let Some(name_binding) = resolution.best_binding() {
1224 match name_binding.kind {
1225 NameBindingKind::Import { binding, .. } => {
1226 match binding.kind {
1227 NameBindingKind::Res(Res::Err) => None,
1230 _ => Some(i.name),
1231 }
1232 }
1233 _ => Some(i.name),
1234 }
1235 } else if resolution.single_imports.is_empty() {
1236 None
1237 } else {
1238 Some(i.name)
1239 }
1240 })
1241 .collect()
1242 }
1243 _ => Vec::new(),
1244 };
1245
1246 let lev_suggestion =
1247 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1248 (
1249 vec![(ident.span, suggestion.to_string())],
1250 String::from("a similar name exists in the module"),
1251 Applicability::MaybeIncorrect,
1252 )
1253 });
1254
1255 let (suggestion, note) =
1256 match self.check_for_module_export_macro(import, module, ident) {
1257 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1258 _ => (lev_suggestion, None),
1259 };
1260
1261 let label = match module {
1262 ModuleOrUniformRoot::Module(module) => {
1263 let module_str = module_to_string(module);
1264 if let Some(module_str) = module_str {
1265 format!("no `{ident}` in `{module_str}`")
1266 } else {
1267 format!("no `{ident}` in the root")
1268 }
1269 }
1270 _ => {
1271 if !ident.is_path_segment_keyword() {
1272 format!("no external crate `{ident}`")
1273 } else {
1274 format!("no `{ident}` in the root")
1277 }
1278 }
1279 };
1280
1281 let parent_suggestion =
1282 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1283
1284 Some(UnresolvedImportError {
1285 span: import.span,
1286 label: Some(label),
1287 note,
1288 suggestion,
1289 candidates: if !parent_suggestion.is_empty() {
1290 Some(parent_suggestion)
1291 } else {
1292 None
1293 },
1294 module: import.imported_module.get().and_then(|module| {
1295 if let ModuleOrUniformRoot::Module(m) = module {
1296 m.opt_def_id()
1297 } else {
1298 None
1299 }
1300 }),
1301 segment: Some(ident.name),
1302 })
1303 } else {
1304 None
1306 };
1307 }
1308
1309 let mut reexport_error = None;
1310 let mut any_successful_reexport = false;
1311 let mut crate_private_reexport = false;
1312 self.per_ns(|this, ns| {
1313 let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) else {
1314 return;
1315 };
1316
1317 if !binding.vis.is_at_least(import.vis, this.tcx) {
1318 reexport_error = Some((ns, binding));
1319 if let Visibility::Restricted(binding_def_id) = binding.vis
1320 && binding_def_id.is_top_level_module()
1321 {
1322 crate_private_reexport = true;
1323 }
1324 } else {
1325 any_successful_reexport = true;
1326 }
1327 });
1328
1329 if !any_successful_reexport {
1331 let (ns, binding) = reexport_error.unwrap();
1332 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1333 self.lint_buffer.buffer_lint(
1334 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1335 import_id,
1336 import.span,
1337 BuiltinLintDiag::PrivateExternCrateReexport {
1338 source: ident,
1339 extern_crate_span: self.tcx.source_span(self.local_def_id(extern_crate_id)),
1340 },
1341 );
1342 } else if ns == TypeNS {
1343 let err = if crate_private_reexport {
1344 self.dcx()
1345 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1346 } else {
1347 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1348 };
1349 err.emit();
1350 } else {
1351 let mut err = if crate_private_reexport {
1352 self.dcx()
1353 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1354 } else {
1355 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1356 };
1357
1358 match binding.kind {
1359 NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
1360 if self.get_macro_by_def_id(def_id).macro_rules =>
1362 {
1363 err.subdiagnostic( ConsiderAddingMacroExport {
1364 span: binding.span,
1365 });
1366 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1367 vis_span: import.vis_span,
1368 });
1369 }
1370 _ => {
1371 err.subdiagnostic( ConsiderMarkingAsPub {
1372 span: import.span,
1373 ident,
1374 });
1375 }
1376 }
1377 err.emit();
1378 }
1379 }
1380
1381 if import.module_path.len() <= 1 {
1382 let mut full_path = import.module_path.clone();
1385 full_path.push(Segment::from_ident(ident));
1386 self.per_ns(|this, ns| {
1387 if let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) {
1388 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1389 }
1390 });
1391 }
1392
1393 self.per_ns(|this, ns| {
1397 if let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) {
1398 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1399 }
1400 });
1401
1402 debug!("(resolving single import) successfully resolved import");
1403 None
1404 }
1405
1406 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1407 let ImportKind::Single { source, target, ref bindings, id, .. } = import.kind else {
1409 unreachable!()
1410 };
1411
1412 if source != target {
1414 return false;
1415 }
1416
1417 if import.parent_scope.expansion != LocalExpnId::ROOT {
1419 return false;
1420 }
1421
1422 if self.import_use_map.get(&import) == Some(&Used::Other)
1427 || self.effective_visibilities.is_exported(self.local_def_id(id))
1428 {
1429 return false;
1430 }
1431
1432 let mut is_redundant = true;
1433 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1434 self.per_ns(|this, ns| {
1435 let binding = bindings[ns].get().binding().map(|b| b.import_source());
1436 if is_redundant && let Some(binding) = binding {
1437 if binding.res() == Res::Err {
1438 return;
1439 }
1440
1441 match this.cm().resolve_ident_in_scope_set(
1442 target,
1443 ScopeSet::All(ns),
1444 &import.parent_scope,
1445 None,
1446 false,
1447 bindings[ns].get().binding(),
1448 None,
1449 ) {
1450 Ok(other_binding) => {
1451 is_redundant = binding.res() == other_binding.res()
1452 && !other_binding.is_ambiguity_recursive();
1453 if is_redundant {
1454 redundant_span[ns] =
1455 Some((other_binding.span, other_binding.is_import()));
1456 }
1457 }
1458 Err(_) => is_redundant = false,
1459 }
1460 }
1461 });
1462
1463 if is_redundant && !redundant_span.is_empty() {
1464 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1465 redundant_spans.sort();
1466 redundant_spans.dedup();
1467 self.lint_buffer.buffer_lint(
1468 REDUNDANT_IMPORTS,
1469 id,
1470 import.span,
1471 BuiltinLintDiag::RedundantImport(redundant_spans, source),
1472 );
1473 return true;
1474 }
1475
1476 false
1477 }
1478
1479 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1480 let ImportKind::Glob { id, .. } = import.kind else { unreachable!() };
1482
1483 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1484 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1485 return;
1486 };
1487
1488 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1489 feature_err(
1490 self.tcx.sess,
1491 sym::import_trait_associated_functions,
1492 import.span,
1493 "`use` associated items of traits is unstable",
1494 )
1495 .emit();
1496 }
1497
1498 if module == import.parent_scope.module {
1499 return;
1500 }
1501
1502 module.glob_importers.borrow_mut_unchecked().push(import);
1504
1505 let bindings = self
1508 .resolutions(module)
1509 .borrow()
1510 .iter()
1511 .filter_map(|(key, resolution)| {
1512 resolution.borrow().binding().map(|binding| (*key, binding))
1513 })
1514 .collect::<Vec<_>>();
1515 for (mut key, binding) in bindings {
1516 let scope = match key.ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
1517 Some(Some(def)) => self.expn_def_scope(def),
1518 Some(None) => import.parent_scope.module,
1519 None => continue,
1520 };
1521 if self.is_accessible_from(binding.vis, scope) {
1522 let imported_binding = self.import(binding, import);
1523 let warn_ambiguity = self
1524 .resolution(import.parent_scope.module, key)
1525 .and_then(|r| r.binding())
1526 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1527 let _ = self.try_define_local(
1528 import.parent_scope.module,
1529 key.ident.0,
1530 key.ns,
1531 imported_binding,
1532 warn_ambiguity,
1533 );
1534 }
1535 }
1536
1537 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1539 }
1540
1541 fn finalize_resolutions_in(
1544 &self,
1545 module: Module<'ra>,
1546 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1547 ) {
1548 *module.globs.borrow_mut(self) = Vec::new();
1550
1551 let Some(def_id) = module.opt_def_id() else { return };
1552
1553 let mut children = Vec::new();
1554
1555 module.for_each_child(self, |this, ident, _, binding| {
1556 let res = binding.res().expect_non_local();
1557 let error_ambiguity = binding.is_ambiguity_recursive() && !binding.warn_ambiguity;
1558 if res != def::Res::Err && !error_ambiguity {
1559 let mut reexport_chain = SmallVec::new();
1560 let mut next_binding = binding;
1561 while let NameBindingKind::Import { binding, import, .. } = next_binding.kind {
1562 reexport_chain.push(import.simplify(this));
1563 next_binding = binding;
1564 }
1565
1566 children.push(ModChild { ident: ident.0, res, vis: binding.vis, reexport_chain });
1567 }
1568 });
1569
1570 if !children.is_empty() {
1571 module_children.insert(def_id.expect_local(), children);
1573 }
1574 }
1575}
1576
1577fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1578 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1579 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1580 if let Some(pos) = pos {
1581 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1582 names_to_string(names.iter().map(|ident| ident.name))
1583 } else {
1584 let names = if global { &names[1..] } else { names };
1585 if names.is_empty() {
1586 import_kind_to_string(import_kind)
1587 } else {
1588 format!(
1589 "{}::{}",
1590 names_to_string(names.iter().map(|ident| ident.name)),
1591 import_kind_to_string(import_kind),
1592 )
1593 }
1594 }
1595}
1596
1597fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1598 match import_kind {
1599 ImportKind::Single { source, .. } => source.to_string(),
1600 ImportKind::Glob { .. } => "*".to_string(),
1601 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1602 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1603 ImportKind::MacroExport => "#[macro_export]".to_string(),
1604 }
1605}