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::{self, *};
29use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
30use crate::errors::{
31 CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
32 CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
33 ConsiderAddingMacroExport, ConsiderMarkingAsPub, ConsiderMarkingAsPubCrate,
34};
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<Cell<PendingBinding<'ra>>>,
72 type_ns_only: bool,
74 nested: bool,
76 id: NodeId,
88 },
89 Glob {
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 { 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: Cell<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(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(|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();
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() 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 self.assert_speculative = true;
555 let mut prev_indeterminate_count = usize::MAX;
556 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
557 while indeterminate_count < prev_indeterminate_count {
558 prev_indeterminate_count = indeterminate_count;
559 indeterminate_count = 0;
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 }
569 self.assert_speculative = false;
570 }
571
572 pub(crate) fn finalize_imports(&mut self) {
573 for module in self.arenas.local_modules().iter() {
574 self.finalize_resolutions_in(*module);
575 }
576
577 let mut seen_spans = FxHashSet::default();
578 let mut errors = vec![];
579 let mut prev_root_id: NodeId = NodeId::ZERO;
580 let determined_imports = mem::take(&mut self.determined_imports);
581 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
582
583 let mut glob_error = false;
584 for (is_indeterminate, import) in determined_imports
585 .iter()
586 .map(|i| (false, i))
587 .chain(indeterminate_imports.iter().map(|i| (true, i)))
588 {
589 let unresolved_import_error = self.finalize_import(*import);
590 self.import_dummy_binding(*import, is_indeterminate);
593
594 let Some(err) = unresolved_import_error else { continue };
595
596 glob_error |= import.is_glob();
597
598 if let ImportKind::Single { source, ref bindings, .. } = import.kind
599 && source.name == kw::SelfLower
600 && let PendingBinding::Ready(None) = bindings.value_ns.get()
602 {
603 continue;
604 }
605
606 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
607 {
608 self.throw_unresolved_import_error(errors, glob_error);
611 errors = vec![];
612 }
613 if seen_spans.insert(err.span) {
614 errors.push((*import, err));
615 prev_root_id = import.root_id;
616 }
617 }
618
619 if !errors.is_empty() {
620 self.throw_unresolved_import_error(errors, glob_error);
621 return;
622 }
623
624 for import in &indeterminate_imports {
625 let path = import_path_to_string(
626 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
627 &import.kind,
628 import.span,
629 );
630 if path.contains("::") {
633 let err = UnresolvedImportError {
634 span: import.span,
635 label: None,
636 note: None,
637 suggestion: None,
638 candidates: None,
639 segment: None,
640 module: None,
641 };
642 errors.push((*import, err))
643 }
644 }
645
646 if !errors.is_empty() {
647 self.throw_unresolved_import_error(errors, glob_error);
648 }
649 }
650
651 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<NameBinding<'ra>>) {
652 for module in self.arenas.local_modules().iter() {
653 for (key, resolution) in self.resolutions(*module).borrow().iter() {
654 let resolution = resolution.borrow();
655 let Some(binding) = resolution.best_binding() else { continue };
656
657 if let NameBindingKind::Import { import, .. } = binding.kind
658 && let Some((amb_binding, _)) = binding.ambiguity
659 && binding.res() != Res::Err
660 && exported_ambiguities.contains(&binding)
661 {
662 self.lint_buffer.buffer_lint(
663 AMBIGUOUS_GLOB_REEXPORTS,
664 import.root_id,
665 import.root_span,
666 BuiltinLintDiag::AmbiguousGlobReexports {
667 name: key.ident.to_string(),
668 namespace: key.ns.descr().to_string(),
669 first_reexport_span: import.root_span,
670 duplicate_reexport_span: amb_binding.span,
671 },
672 );
673 }
674
675 if let Some(glob_binding) = resolution.glob_binding
676 && resolution.non_glob_binding.is_some()
677 {
678 if binding.res() != Res::Err
679 && glob_binding.res() != Res::Err
680 && let NameBindingKind::Import { import: glob_import, .. } =
681 glob_binding.kind
682 && let Some(glob_import_id) = glob_import.id()
683 && let glob_import_def_id = self.local_def_id(glob_import_id)
684 && self.effective_visibilities.is_exported(glob_import_def_id)
685 && glob_binding.vis.is_public()
686 && !binding.vis.is_public()
687 {
688 let binding_id = match binding.kind {
689 NameBindingKind::Res(res) => {
690 Some(self.def_id_to_node_id(res.def_id().expect_local()))
691 }
692 NameBindingKind::Import { import, .. } => import.id(),
693 };
694 if let Some(binding_id) = binding_id {
695 self.lint_buffer.buffer_lint(
696 HIDDEN_GLOB_REEXPORTS,
697 binding_id,
698 binding.span,
699 BuiltinLintDiag::HiddenGlobReexports {
700 name: key.ident.name.to_string(),
701 namespace: key.ns.descr().to_owned(),
702 glob_reexport_span: glob_binding.span,
703 private_item_span: binding.span,
704 },
705 );
706 }
707 }
708 }
709
710 if let NameBindingKind::Import { import, .. } = binding.kind
711 && let Some(binding_id) = import.id()
712 && let import_def_id = self.local_def_id(binding_id)
713 && self.effective_visibilities.is_exported(import_def_id)
714 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
715 && !matches!(reexported_kind, DefKind::Ctor(..))
716 && !reexported_def_id.is_local()
717 && self.tcx.is_private_dep(reexported_def_id.krate)
718 {
719 self.lint_buffer.buffer_lint(
720 EXPORTED_PRIVATE_DEPENDENCIES,
721 binding_id,
722 binding.span,
723 BuiltinLintDiag::ReexportPrivateDependency {
724 kind: binding.res().descr().to_string(),
725 name: key.ident.name.to_string(),
726 krate: self.tcx.crate_name(reexported_def_id.krate),
727 },
728 );
729 }
730 }
731 }
732 }
733
734 fn throw_unresolved_import_error(
735 &mut self,
736 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
737 glob_error: bool,
738 ) {
739 errors.retain(|(_import, err)| match err.module {
740 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
742 _ => true,
743 });
744 errors.retain(|(_import, err)| {
745 err.segment != Some(kw::Underscore)
748 });
749
750 if errors.is_empty() {
751 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
752 return;
753 }
754
755 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
756
757 let paths = errors
758 .iter()
759 .map(|(import, err)| {
760 let path = import_path_to_string(
761 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
762 &import.kind,
763 err.span,
764 );
765 format!("`{path}`")
766 })
767 .collect::<Vec<_>>();
768 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
769
770 let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
771
772 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
773 diag.note(note.clone());
774 }
775
776 const MAX_LABEL_COUNT: usize = 10;
778
779 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
780 if let Some(label) = err.label {
781 diag.span_label(err.span, label);
782 }
783
784 if let Some((suggestions, msg, applicability)) = err.suggestion {
785 if suggestions.is_empty() {
786 diag.help(msg);
787 continue;
788 }
789 diag.multipart_suggestion(msg, suggestions, applicability);
790 }
791
792 if let Some(candidates) = &err.candidates {
793 match &import.kind {
794 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
795 self.tcx,
796 &mut diag,
797 Some(err.span),
798 candidates,
799 DiagMode::Import { append: false, unresolved_import: true },
800 (source != target)
801 .then(|| format!(" as {target}"))
802 .as_deref()
803 .unwrap_or(""),
804 ),
805 ImportKind::Single { nested: true, source, target, .. } => {
806 import_candidates(
807 self.tcx,
808 &mut diag,
809 None,
810 candidates,
811 DiagMode::Normal,
812 (source != target)
813 .then(|| format!(" as {target}"))
814 .as_deref()
815 .unwrap_or(""),
816 );
817 }
818 _ => {}
819 }
820 }
821
822 if matches!(import.kind, ImportKind::Single { .. })
823 && let Some(segment) = err.segment
824 && let Some(module) = err.module
825 {
826 self.find_cfg_stripped(&mut diag, &segment, module)
827 }
828 }
829
830 let guar = diag.emit();
831 if glob_error {
832 self.glob_error = Some(guar);
833 }
834 }
835
836 fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
843 debug!(
844 "(resolving import for module) resolving import `{}::...` in `{}`",
845 Segment::names_to_string(&import.module_path),
846 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
847 );
848 let module = if let Some(module) = import.imported_module.get() {
849 module
850 } else {
851 let path_res = self.reborrow().maybe_resolve_path(
852 &import.module_path,
853 None,
854 &import.parent_scope,
855 Some(import),
856 );
857
858 match path_res {
859 PathResult::Module(module) => module,
860 PathResult::Indeterminate => return 3,
861 PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
862 }
863 };
864
865 import.imported_module.set(Some(module));
866 let (source, target, bindings, type_ns_only) = match import.kind {
867 ImportKind::Single { source, target, ref bindings, type_ns_only, .. } => {
868 (source, target, bindings, type_ns_only)
869 }
870 ImportKind::Glob { .. } => {
871 self.get_mut_unchecked().resolve_glob_import(import);
874 return 0;
875 }
876 _ => unreachable!(),
877 };
878
879 let mut indeterminate_count = 0;
880 self.per_ns_cm(|this, ns| {
881 if !type_ns_only || ns == TypeNS {
882 if bindings[ns].get() != PendingBinding::Pending {
883 return;
884 };
885 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
886 module,
887 source,
888 ns,
889 &import.parent_scope,
890 Some(import),
891 );
892 let parent = import.parent_scope.module;
893 let binding = match binding_result {
894 Ok(binding) => {
895 if binding.is_assoc_item()
896 && !this.tcx.features().import_trait_associated_functions()
897 {
898 feature_err(
899 this.tcx.sess,
900 sym::import_trait_associated_functions,
901 import.span,
902 "`use` associated items of traits is unstable",
903 )
904 .emit();
905 }
906 let imported_binding = this.import(binding, import);
908 this.get_mut_unchecked().define_binding_local(
911 parent,
912 target,
913 ns,
914 imported_binding,
915 );
916 PendingBinding::Ready(Some(imported_binding))
917 }
918 Err(Determinacy::Determined) => {
919 if target.name != kw::Underscore {
921 let key = BindingKey::new(target, ns);
922 this.get_mut_unchecked().update_local_resolution(
925 parent,
926 key,
927 false,
928 |_, resolution| {
929 resolution.single_imports.swap_remove(&import);
930 },
931 );
932 }
933 PendingBinding::Ready(None)
934 }
935 Err(Determinacy::Undetermined) => {
936 indeterminate_count += 1;
937 PendingBinding::Pending
938 }
939 };
940 bindings[ns].set(binding);
941 }
942 });
943
944 indeterminate_count
945 }
946
947 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
952 let ignore_binding = match &import.kind {
953 ImportKind::Single { bindings, .. } => bindings[TypeNS].get().binding(),
954 _ => None,
955 };
956 let ambiguity_errors_len =
957 |errors: &Vec<AmbiguityError<'_>>| errors.iter().filter(|error| !error.warning).count();
958 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
959 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
960
961 let privacy_errors_len = self.privacy_errors.len();
963
964 let path_res = self.cm().resolve_path(
965 &import.module_path,
966 None,
967 &import.parent_scope,
968 Some(finalize),
969 ignore_binding,
970 Some(import),
971 );
972
973 let no_ambiguity =
974 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
975
976 let module = match path_res {
977 PathResult::Module(module) => {
978 if let Some(initial_module) = import.imported_module.get() {
980 if module != initial_module && no_ambiguity {
981 span_bug!(import.span, "inconsistent resolution for an import");
982 }
983 } else if self.privacy_errors.is_empty() {
984 self.dcx()
985 .create_err(CannotDetermineImportResolution { span: import.span })
986 .emit();
987 }
988
989 module
990 }
991 PathResult::Failed {
992 is_error_from_last_segment: false,
993 span,
994 segment_name,
995 label,
996 suggestion,
997 module,
998 error_implied_by_parse_error: _,
999 } => {
1000 if no_ambiguity {
1001 assert!(import.imported_module.get().is_none());
1002 self.report_error(
1003 span,
1004 ResolutionError::FailedToResolve {
1005 segment: Some(segment_name),
1006 label,
1007 suggestion,
1008 module,
1009 },
1010 );
1011 }
1012 return None;
1013 }
1014 PathResult::Failed {
1015 is_error_from_last_segment: true,
1016 span,
1017 label,
1018 suggestion,
1019 module,
1020 segment_name,
1021 ..
1022 } => {
1023 if no_ambiguity {
1024 assert!(import.imported_module.get().is_none());
1025 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1026 m.opt_def_id()
1027 } else {
1028 None
1029 };
1030 let err = match self
1031 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1032 {
1033 Some((suggestion, note)) => UnresolvedImportError {
1034 span,
1035 label: None,
1036 note,
1037 suggestion: Some((
1038 vec![(span, Segment::names_to_string(&suggestion))],
1039 String::from("a similar path exists"),
1040 Applicability::MaybeIncorrect,
1041 )),
1042 candidates: None,
1043 segment: Some(segment_name),
1044 module,
1045 },
1046 None => UnresolvedImportError {
1047 span,
1048 label: Some(label),
1049 note: None,
1050 suggestion,
1051 candidates: None,
1052 segment: Some(segment_name),
1053 module,
1054 },
1055 };
1056 return Some(err);
1057 }
1058 return None;
1059 }
1060 PathResult::NonModule(partial_res) => {
1061 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1062 assert!(import.imported_module.get().is_none());
1064 }
1065 return None;
1067 }
1068 PathResult::Indeterminate => unreachable!(),
1069 };
1070
1071 let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1072 ImportKind::Single { source, target, ref bindings, type_ns_only, id, .. } => {
1073 (source, target, bindings, type_ns_only, id)
1074 }
1075 ImportKind::Glob { ref max_vis, id } => {
1076 if import.module_path.len() <= 1 {
1077 let mut full_path = import.module_path.clone();
1080 full_path.push(Segment::from_ident(Ident::dummy()));
1081 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1082 }
1083
1084 if let ModuleOrUniformRoot::Module(module) = module
1085 && module == import.parent_scope.module
1086 {
1087 return Some(UnresolvedImportError {
1089 span: import.span,
1090 label: Some(String::from("cannot glob-import a module into itself")),
1091 note: None,
1092 suggestion: None,
1093 candidates: None,
1094 segment: None,
1095 module: None,
1096 });
1097 }
1098 if let Some(max_vis) = max_vis.get()
1099 && !max_vis.is_at_least(import.vis, self.tcx)
1100 {
1101 let def_id = self.local_def_id(id);
1102 self.lint_buffer.buffer_lint(
1103 UNUSED_IMPORTS,
1104 id,
1105 import.span,
1106 BuiltinLintDiag::RedundantImportVisibility {
1107 max_vis: max_vis.to_string(def_id, self.tcx),
1108 import_vis: import.vis.to_string(def_id, self.tcx),
1109 span: import.span,
1110 },
1111 );
1112 }
1113 return None;
1114 }
1115 _ => unreachable!(),
1116 };
1117
1118 if self.privacy_errors.len() != privacy_errors_len {
1119 let mut path = import.module_path.clone();
1122 path.push(Segment::from_ident(ident));
1123 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1124 &path,
1125 None,
1126 &import.parent_scope,
1127 Some(finalize),
1128 ignore_binding,
1129 None,
1130 ) {
1131 let res = module.res().map(|r| (r, ident));
1132 for error in &mut self.privacy_errors[privacy_errors_len..] {
1133 error.outermost_res = res;
1134 }
1135 }
1136 }
1137
1138 let mut all_ns_err = true;
1139 self.per_ns(|this, ns| {
1140 if !type_ns_only || ns == TypeNS {
1141 let binding = this.cm().resolve_ident_in_module(
1142 module,
1143 ident,
1144 ns,
1145 &import.parent_scope,
1146 Some(Finalize { report_private: false, ..finalize }),
1147 bindings[ns].get().binding(),
1148 Some(import),
1149 );
1150
1151 match binding {
1152 Ok(binding) => {
1153 let initial_res = bindings[ns].get().binding().map(|binding| {
1155 let initial_binding = binding.import_source();
1156 all_ns_err = false;
1157 if target.name == kw::Underscore
1158 && initial_binding.is_extern_crate()
1159 && !initial_binding.is_import()
1160 {
1161 let used = if import.module_path.is_empty() {
1162 Used::Scope
1163 } else {
1164 Used::Other
1165 };
1166 this.record_use(ident, binding, used);
1167 }
1168 initial_binding.res()
1169 });
1170 let res = binding.res();
1171 let has_ambiguity_error =
1172 this.ambiguity_errors.iter().any(|error| !error.warning);
1173 if res == Res::Err || has_ambiguity_error {
1174 this.dcx()
1175 .span_delayed_bug(import.span, "some error happened for an import");
1176 return;
1177 }
1178 if let Some(initial_res) = initial_res {
1179 if res != initial_res {
1180 span_bug!(import.span, "inconsistent resolution for an import");
1181 }
1182 } else if this.privacy_errors.is_empty() {
1183 this.dcx()
1184 .create_err(CannotDetermineImportResolution { span: import.span })
1185 .emit();
1186 }
1187 }
1188 Err(..) => {
1189 }
1196 }
1197 }
1198 });
1199
1200 if all_ns_err {
1201 let mut all_ns_failed = true;
1202 self.per_ns(|this, ns| {
1203 if !type_ns_only || ns == TypeNS {
1204 let binding = this.cm().resolve_ident_in_module(
1205 module,
1206 ident,
1207 ns,
1208 &import.parent_scope,
1209 Some(finalize),
1210 None,
1211 None,
1212 );
1213 if binding.is_ok() {
1214 all_ns_failed = false;
1215 }
1216 }
1217 });
1218
1219 return if all_ns_failed {
1220 let names = match module {
1221 ModuleOrUniformRoot::Module(module) => {
1222 self.resolutions(module)
1223 .borrow()
1224 .iter()
1225 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1226 if i.name == ident.name {
1227 return None;
1228 } let resolution = resolution.borrow();
1231 if let Some(name_binding) = resolution.best_binding() {
1232 match name_binding.kind {
1233 NameBindingKind::Import { binding, .. } => {
1234 match binding.kind {
1235 NameBindingKind::Res(Res::Err) => None,
1238 _ => Some(i.name),
1239 }
1240 }
1241 _ => Some(i.name),
1242 }
1243 } else if resolution.single_imports.is_empty() {
1244 None
1245 } else {
1246 Some(i.name)
1247 }
1248 })
1249 .collect()
1250 }
1251 _ => Vec::new(),
1252 };
1253
1254 let lev_suggestion =
1255 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1256 (
1257 vec![(ident.span, suggestion.to_string())],
1258 String::from("a similar name exists in the module"),
1259 Applicability::MaybeIncorrect,
1260 )
1261 });
1262
1263 let (suggestion, note) =
1264 match self.check_for_module_export_macro(import, module, ident) {
1265 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1266 _ => (lev_suggestion, None),
1267 };
1268
1269 let label = match module {
1270 ModuleOrUniformRoot::Module(module) => {
1271 let module_str = module_to_string(module);
1272 if let Some(module_str) = module_str {
1273 format!("no `{ident}` in `{module_str}`")
1274 } else {
1275 format!("no `{ident}` in the root")
1276 }
1277 }
1278 _ => {
1279 if !ident.is_path_segment_keyword() {
1280 format!("no external crate `{ident}`")
1281 } else {
1282 format!("no `{ident}` in the root")
1285 }
1286 }
1287 };
1288
1289 let parent_suggestion =
1290 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1291
1292 Some(UnresolvedImportError {
1293 span: import.span,
1294 label: Some(label),
1295 note,
1296 suggestion,
1297 candidates: if !parent_suggestion.is_empty() {
1298 Some(parent_suggestion)
1299 } else {
1300 None
1301 },
1302 module: import.imported_module.get().and_then(|module| {
1303 if let ModuleOrUniformRoot::Module(m) = module {
1304 m.opt_def_id()
1305 } else {
1306 None
1307 }
1308 }),
1309 segment: Some(ident.name),
1310 })
1311 } else {
1312 None
1314 };
1315 }
1316
1317 let mut reexport_error = None;
1318 let mut any_successful_reexport = false;
1319 let mut crate_private_reexport = false;
1320 self.per_ns(|this, ns| {
1321 let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) else {
1322 return;
1323 };
1324
1325 if !binding.vis.is_at_least(import.vis, this.tcx) {
1326 reexport_error = Some((ns, binding));
1327 if let Visibility::Restricted(binding_def_id) = binding.vis
1328 && binding_def_id.is_top_level_module()
1329 {
1330 crate_private_reexport = true;
1331 }
1332 } else {
1333 any_successful_reexport = true;
1334 }
1335 });
1336
1337 if !any_successful_reexport {
1339 let (ns, binding) = reexport_error.unwrap();
1340 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1341 self.lint_buffer.buffer_lint(
1342 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1343 import_id,
1344 import.span,
1345 BuiltinLintDiag::PrivateExternCrateReexport {
1346 source: ident,
1347 extern_crate_span: self.tcx.source_span(self.local_def_id(extern_crate_id)),
1348 },
1349 );
1350 } else if ns == TypeNS {
1351 let err = if crate_private_reexport {
1352 self.dcx()
1353 .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1354 } else {
1355 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1356 };
1357 err.emit();
1358 } else {
1359 let mut err = if crate_private_reexport {
1360 self.dcx()
1361 .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1362 } else {
1363 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1364 };
1365
1366 match binding.kind {
1367 NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
1368 if self.get_macro_by_def_id(def_id).macro_rules =>
1370 {
1371 err.subdiagnostic( ConsiderAddingMacroExport {
1372 span: binding.span,
1373 });
1374 err.subdiagnostic( ConsiderMarkingAsPubCrate {
1375 vis_span: import.vis_span,
1376 });
1377 }
1378 _ => {
1379 err.subdiagnostic( ConsiderMarkingAsPub {
1380 span: import.span,
1381 ident,
1382 });
1383 }
1384 }
1385 err.emit();
1386 }
1387 }
1388
1389 if import.module_path.len() <= 1 {
1390 let mut full_path = import.module_path.clone();
1393 full_path.push(Segment::from_ident(ident));
1394 self.per_ns(|this, ns| {
1395 if let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) {
1396 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1397 }
1398 });
1399 }
1400
1401 self.per_ns(|this, ns| {
1405 if let Some(binding) = bindings[ns].get().binding().map(|b| b.import_source()) {
1406 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1407 }
1408 });
1409
1410 debug!("(resolving single import) successfully resolved import");
1411 None
1412 }
1413
1414 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1415 let ImportKind::Single { source, target, ref bindings, id, .. } = import.kind else {
1417 unreachable!()
1418 };
1419
1420 if source != target {
1422 return false;
1423 }
1424
1425 if import.parent_scope.expansion != LocalExpnId::ROOT {
1427 return false;
1428 }
1429
1430 if self.import_use_map.get(&import) == Some(&Used::Other)
1435 || self.effective_visibilities.is_exported(self.local_def_id(id))
1436 {
1437 return false;
1438 }
1439
1440 let mut is_redundant = true;
1441 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1442 self.per_ns(|this, ns| {
1443 let binding = bindings[ns].get().binding().map(|b| b.import_source());
1444 if is_redundant && let Some(binding) = binding {
1445 if binding.res() == Res::Err {
1446 return;
1447 }
1448
1449 match this.cm().resolve_ident_in_scope_set(
1450 target,
1451 ScopeSet::All(ns),
1452 &import.parent_scope,
1453 None,
1454 false,
1455 bindings[ns].get().binding(),
1456 None,
1457 ) {
1458 Ok(other_binding) => {
1459 is_redundant = binding.res() == other_binding.res()
1460 && !other_binding.is_ambiguity_recursive();
1461 if is_redundant {
1462 redundant_span[ns] =
1463 Some((other_binding.span, other_binding.is_import()));
1464 }
1465 }
1466 Err(_) => is_redundant = false,
1467 }
1468 }
1469 });
1470
1471 if is_redundant && !redundant_span.is_empty() {
1472 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1473 redundant_spans.sort();
1474 redundant_spans.dedup();
1475 self.lint_buffer.buffer_lint(
1476 REDUNDANT_IMPORTS,
1477 id,
1478 import.span,
1479 BuiltinLintDiag::RedundantImport(redundant_spans, source),
1480 );
1481 return true;
1482 }
1483
1484 false
1485 }
1486
1487 fn resolve_glob_import(&mut self, import: Import<'ra>) {
1488 let ImportKind::Glob { id, .. } = import.kind else { unreachable!() };
1490
1491 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1492 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1493 return;
1494 };
1495
1496 if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1497 feature_err(
1498 self.tcx.sess,
1499 sym::import_trait_associated_functions,
1500 import.span,
1501 "`use` associated items of traits is unstable",
1502 )
1503 .emit();
1504 }
1505
1506 if module == import.parent_scope.module {
1507 return;
1508 }
1509
1510 module.glob_importers.borrow_mut().push(import);
1512
1513 let bindings = self
1516 .resolutions(module)
1517 .borrow()
1518 .iter()
1519 .filter_map(|(key, resolution)| {
1520 resolution.borrow().binding().map(|binding| (*key, binding))
1521 })
1522 .collect::<Vec<_>>();
1523 for (mut key, binding) in bindings {
1524 let scope = match key.ident.0.span.reverse_glob_adjust(module.expansion, import.span) {
1525 Some(Some(def)) => self.expn_def_scope(def),
1526 Some(None) => import.parent_scope.module,
1527 None => continue,
1528 };
1529 if self.is_accessible_from(binding.vis, scope) {
1530 let imported_binding = self.import(binding, import);
1531 let warn_ambiguity = self
1532 .resolution(import.parent_scope.module, key)
1533 .and_then(|r| r.binding())
1534 .is_some_and(|binding| binding.warn_ambiguity_recursive());
1535 let _ = self.try_define_local(
1536 import.parent_scope.module,
1537 key.ident.0,
1538 key.ns,
1539 imported_binding,
1540 warn_ambiguity,
1541 );
1542 }
1543 }
1544
1545 self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1547 }
1548
1549 fn finalize_resolutions_in(&mut self, module: Module<'ra>) {
1552 *module.globs.borrow_mut() = Vec::new();
1554
1555 let Some(def_id) = module.opt_def_id() else { return };
1556
1557 let mut children = Vec::new();
1558
1559 module.for_each_child(self, |this, ident, _, binding| {
1560 let res = binding.res().expect_non_local();
1561 let error_ambiguity = binding.is_ambiguity_recursive() && !binding.warn_ambiguity;
1562 if res != def::Res::Err && !error_ambiguity {
1563 let mut reexport_chain = SmallVec::new();
1564 let mut next_binding = binding;
1565 while let NameBindingKind::Import { binding, import, .. } = next_binding.kind {
1566 reexport_chain.push(import.simplify(this));
1567 next_binding = binding;
1568 }
1569
1570 children.push(ModChild { ident: ident.0, res, vis: binding.vis, reexport_chain });
1571 }
1572 });
1573
1574 if !children.is_empty() {
1575 self.module_children.insert(def_id.expect_local(), children);
1577 }
1578 }
1579}
1580
1581fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1582 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1583 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1584 if let Some(pos) = pos {
1585 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1586 names_to_string(names.iter().map(|ident| ident.name))
1587 } else {
1588 let names = if global { &names[1..] } else { names };
1589 if names.is_empty() {
1590 import_kind_to_string(import_kind)
1591 } else {
1592 format!(
1593 "{}::{}",
1594 names_to_string(names.iter().map(|ident| ident.name)),
1595 import_kind_to_string(import_kind),
1596 )
1597 }
1598 }
1599}
1600
1601fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1602 match import_kind {
1603 ImportKind::Single { source, .. } => source.to_string(),
1604 ImportKind::Glob { .. } => "*".to_string(),
1605 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1606 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1607 ImportKind::MacroExport => "#[macro_export]".to_string(),
1608 }
1609}