]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/imports.rs
Rollup merge of #98911 - notriddle:notriddle/rustdoc-string-impl, r=GuillaumeGomez
[rust.git] / compiler / rustc_resolve / src / imports.rs
1 //! A bunch of methods and structures more or less related to resolving imports.
2
3 use crate::diagnostics::Suggestion;
4 use crate::Determinacy::{self, *};
5 use crate::Namespace::{MacroNS, TypeNS};
6 use crate::{module_to_string, names_to_string};
7 use crate::{AmbiguityKind, BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
8 use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet};
9 use crate::{NameBinding, NameBindingKind, PathResult};
10
11 use rustc_ast::NodeId;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::intern::Interned;
14 use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan};
15 use rustc_hir::def::{self, DefKind, PartialRes};
16 use rustc_middle::metadata::ModChild;
17 use rustc_middle::span_bug;
18 use rustc_middle::ty;
19 use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
20 use rustc_session::lint::BuiltinLintDiagnostics;
21 use rustc_span::hygiene::LocalExpnId;
22 use rustc_span::lev_distance::find_best_match_for_name;
23 use rustc_span::symbol::{kw, Ident, Symbol};
24 use rustc_span::Span;
25
26 use tracing::*;
27
28 use std::cell::Cell;
29 use std::{mem, ptr};
30
31 type Res = def::Res<NodeId>;
32
33 /// Contains data for specific kinds of imports.
34 #[derive(Clone, Debug)]
35 pub enum ImportKind<'a> {
36     Single {
37         /// `source` in `use prefix::source as target`.
38         source: Ident,
39         /// `target` in `use prefix::source as target`.
40         target: Ident,
41         /// Bindings to which `source` refers to.
42         source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
43         /// Bindings introduced by `target`.
44         target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
45         /// `true` for `...::{self [as target]}` imports, `false` otherwise.
46         type_ns_only: bool,
47         /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
48         nested: bool,
49         /// Additional `NodeId`s allocated to a `ast::UseTree` for automatically generated `use` statement
50         /// (eg. implicit struct constructors)
51         additional_ids: (NodeId, NodeId),
52     },
53     Glob {
54         is_prelude: bool,
55         max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
56                                        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
57     },
58     ExternCrate {
59         source: Option<Symbol>,
60         target: Ident,
61     },
62     MacroUse,
63 }
64
65 /// One import.
66 #[derive(Debug, Clone)]
67 pub(crate) struct Import<'a> {
68     pub kind: ImportKind<'a>,
69
70     /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
71     ///
72     /// In the case where the `Import` was expanded from a "nested" use tree,
73     /// this id is the ID of the leaf tree. For example:
74     ///
75     /// ```ignore (pacify the merciless tidy)
76     /// use foo::bar::{a, b}
77     /// ```
78     ///
79     /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
80     /// for `a` in this field.
81     pub id: NodeId,
82
83     /// The `id` of the "root" use-kind -- this is always the same as
84     /// `id` except in the case of "nested" use trees, in which case
85     /// it will be the `id` of the root use tree. e.g., in the example
86     /// from `id`, this would be the ID of the `use foo::bar`
87     /// `UseTree` node.
88     pub root_id: NodeId,
89
90     /// Span of the entire use statement.
91     pub use_span: Span,
92
93     /// Span of the entire use statement with attributes.
94     pub use_span_with_attributes: Span,
95
96     /// Did the use statement have any attributes?
97     pub has_attributes: bool,
98
99     /// Span of this use tree.
100     pub span: Span,
101
102     /// Span of the *root* use tree (see `root_id`).
103     pub root_span: Span,
104
105     pub parent_scope: ParentScope<'a>,
106     pub module_path: Vec<Segment>,
107     /// The resolution of `module_path`.
108     pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
109     pub vis: Cell<ty::Visibility>,
110     pub used: Cell<bool>,
111 }
112
113 impl<'a> Import<'a> {
114     pub fn is_glob(&self) -> bool {
115         matches!(self.kind, ImportKind::Glob { .. })
116     }
117
118     pub fn is_nested(&self) -> bool {
119         match self.kind {
120             ImportKind::Single { nested, .. } => nested,
121             _ => false,
122         }
123     }
124 }
125
126 /// Records information about the resolution of a name in a namespace of a module.
127 #[derive(Clone, Default, Debug)]
128 pub(crate) struct NameResolution<'a> {
129     /// Single imports that may define the name in the namespace.
130     /// Imports are arena-allocated, so it's ok to use pointers as keys.
131     pub single_imports: FxHashSet<Interned<'a, Import<'a>>>,
132     /// The least shadowable known binding for this name, or None if there are no known bindings.
133     pub binding: Option<&'a NameBinding<'a>>,
134     pub shadowed_glob: Option<&'a NameBinding<'a>>,
135 }
136
137 impl<'a> NameResolution<'a> {
138     // Returns the binding for the name if it is known or None if it not known.
139     pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
140         self.binding.and_then(|binding| {
141             if !binding.is_glob_import() || self.single_imports.is_empty() {
142                 Some(binding)
143             } else {
144                 None
145             }
146         })
147     }
148
149     pub(crate) fn add_single_import(&mut self, import: &'a Import<'a>) {
150         self.single_imports.insert(Interned::new_unchecked(import));
151     }
152 }
153
154 // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
155 // are permitted for backward-compatibility under a deprecation lint.
156 fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
157     match (&import.kind, &binding.kind) {
158         (
159             ImportKind::Single { .. },
160             NameBindingKind::Import {
161                 import: Import { kind: ImportKind::ExternCrate { .. }, .. },
162                 ..
163             },
164         ) => import.vis.get().is_public(),
165         _ => false,
166     }
167 }
168
169 impl<'a> Resolver<'a> {
170     // Given a binding and an import that resolves to it,
171     // return the corresponding binding defined by the import.
172     pub(crate) fn import(
173         &self,
174         binding: &'a NameBinding<'a>,
175         import: &'a Import<'a>,
176     ) -> &'a NameBinding<'a> {
177         let vis = if binding.vis.is_at_least(import.vis.get(), self)
178             || pub_use_of_private_extern_crate_hack(import, binding)
179         {
180             import.vis.get()
181         } else {
182             binding.vis
183         };
184
185         if let ImportKind::Glob { ref max_vis, .. } = import.kind {
186             if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
187                 max_vis.set(vis)
188             }
189         }
190
191         self.arenas.alloc_name_binding(NameBinding {
192             kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
193             ambiguity: None,
194             span: import.span,
195             vis,
196             expansion: import.parent_scope.expansion,
197         })
198     }
199
200     // Define the name or return the existing binding if there is a collision.
201     pub(crate) fn try_define(
202         &mut self,
203         module: Module<'a>,
204         key: BindingKey,
205         binding: &'a NameBinding<'a>,
206     ) -> Result<(), &'a NameBinding<'a>> {
207         let res = binding.res();
208         self.check_reserved_macro_name(key.ident, res);
209         self.set_binding_parent_module(binding, module);
210         self.update_resolution(module, key, |this, resolution| {
211             if let Some(old_binding) = resolution.binding {
212                 if res == Res::Err {
213                     // Do not override real bindings with `Res::Err`s from error recovery.
214                     return Ok(());
215                 }
216                 match (old_binding.is_glob_import(), binding.is_glob_import()) {
217                     (true, true) => {
218                         if res != old_binding.res() {
219                             resolution.binding = Some(this.ambiguity(
220                                 AmbiguityKind::GlobVsGlob,
221                                 old_binding,
222                                 binding,
223                             ));
224                         } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
225                             // We are glob-importing the same item but with greater visibility.
226                             resolution.binding = Some(binding);
227                         }
228                     }
229                     (old_glob @ true, false) | (old_glob @ false, true) => {
230                         let (glob_binding, nonglob_binding) =
231                             if old_glob { (old_binding, binding) } else { (binding, old_binding) };
232                         if glob_binding.res() != nonglob_binding.res()
233                             && key.ns == MacroNS
234                             && nonglob_binding.expansion != LocalExpnId::ROOT
235                         {
236                             resolution.binding = Some(this.ambiguity(
237                                 AmbiguityKind::GlobVsExpanded,
238                                 nonglob_binding,
239                                 glob_binding,
240                             ));
241                         } else {
242                             resolution.binding = Some(nonglob_binding);
243                         }
244                         resolution.shadowed_glob = Some(glob_binding);
245                     }
246                     (false, false) => {
247                         return Err(old_binding);
248                     }
249                 }
250             } else {
251                 resolution.binding = Some(binding);
252             }
253
254             Ok(())
255         })
256     }
257
258     fn ambiguity(
259         &self,
260         kind: AmbiguityKind,
261         primary_binding: &'a NameBinding<'a>,
262         secondary_binding: &'a NameBinding<'a>,
263     ) -> &'a NameBinding<'a> {
264         self.arenas.alloc_name_binding(NameBinding {
265             ambiguity: Some((secondary_binding, kind)),
266             ..primary_binding.clone()
267         })
268     }
269
270     // Use `f` to mutate the resolution of the name in the module.
271     // If the resolution becomes a success, define it in the module's glob importers.
272     fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
273     where
274         F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
275     {
276         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
277         // during which the resolution might end up getting re-defined via a glob cycle.
278         let (binding, t) = {
279             let resolution = &mut *self.resolution(module, key).borrow_mut();
280             let old_binding = resolution.binding();
281
282             let t = f(self, resolution);
283
284             match resolution.binding() {
285                 _ if old_binding.is_some() => return t,
286                 None => return t,
287                 Some(binding) => match old_binding {
288                     Some(old_binding) if ptr::eq(old_binding, binding) => return t,
289                     _ => (binding, t),
290                 },
291             }
292         };
293
294         // Define `binding` in `module`s glob importers.
295         for import in module.glob_importers.borrow_mut().iter() {
296             let mut ident = key.ident;
297             let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
298                 Some(Some(def)) => self.expn_def_scope(def),
299                 Some(None) => import.parent_scope.module,
300                 None => continue,
301             };
302             if self.is_accessible_from(binding.vis, scope) {
303                 let imported_binding = self.import(binding, import);
304                 let key = BindingKey { ident, ..key };
305                 let _ = self.try_define(import.parent_scope.module, key, imported_binding);
306             }
307         }
308
309         t
310     }
311
312     // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed resolution,
313     // also mark such failed imports as used to avoid duplicate diagnostics.
314     fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
315         if let ImportKind::Single { target, ref target_bindings, .. } = import.kind {
316             if target_bindings.iter().any(|binding| binding.get().is_some()) {
317                 return; // Has resolution, do not create the dummy binding
318             }
319             let dummy_binding = self.dummy_binding;
320             let dummy_binding = self.import(dummy_binding, import);
321             self.per_ns(|this, ns| {
322                 let key = this.new_key(target, ns);
323                 let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
324             });
325             self.record_use(target, dummy_binding, false);
326         } else if import.imported_module.get().is_none() {
327             import.used.set(true);
328             self.used_imports.insert(import.id);
329         }
330     }
331 }
332
333 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
334 /// import errors within the same use tree into a single diagnostic.
335 #[derive(Debug, Clone)]
336 struct UnresolvedImportError {
337     span: Span,
338     label: Option<String>,
339     note: Vec<String>,
340     suggestion: Option<Suggestion>,
341 }
342
343 pub struct ImportResolver<'a, 'b> {
344     pub r: &'a mut Resolver<'b>,
345 }
346
347 impl<'a, 'b> ImportResolver<'a, 'b> {
348     // Import resolution
349     //
350     // This is a fixed-point algorithm. We resolve imports until our efforts
351     // are stymied by an unresolved import; then we bail out of the current
352     // module and continue. We terminate successfully once no more imports
353     // remain or unsuccessfully when no forward progress in resolving imports
354     // is made.
355
356     /// Resolves all imports for the crate. This method performs the fixed-
357     /// point iteration.
358     pub fn resolve_imports(&mut self) {
359         let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
360         while self.r.indeterminate_imports.len() < prev_num_indeterminates {
361             prev_num_indeterminates = self.r.indeterminate_imports.len();
362             for import in mem::take(&mut self.r.indeterminate_imports) {
363                 match self.resolve_import(&import) {
364                     true => self.r.determined_imports.push(import),
365                     false => self.r.indeterminate_imports.push(import),
366                 }
367             }
368         }
369     }
370
371     pub fn finalize_imports(&mut self) {
372         for module in self.r.arenas.local_modules().iter() {
373             self.finalize_resolutions_in(module);
374         }
375
376         let mut seen_spans = FxHashSet::default();
377         let mut errors = vec![];
378         let mut prev_root_id: NodeId = NodeId::from_u32(0);
379         let determined_imports = mem::take(&mut self.r.determined_imports);
380         let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
381
382         for (is_indeterminate, import) in determined_imports
383             .into_iter()
384             .map(|i| (false, i))
385             .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
386         {
387             let unresolved_import_error = self.finalize_import(import);
388
389             // If this import is unresolved then create a dummy import
390             // resolution for it so that later resolve stages won't complain.
391             self.r.import_dummy_binding(import);
392
393             if let Some(err) = unresolved_import_error {
394                 if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
395                     if source.name == kw::SelfLower {
396                         // Silence `unresolved import` error if E0429 is already emitted
397                         if let Err(Determined) = source_bindings.value_ns.get() {
398                             continue;
399                         }
400                     }
401                 }
402
403                 if prev_root_id.as_u32() != 0
404                     && prev_root_id.as_u32() != import.root_id.as_u32()
405                     && !errors.is_empty()
406                 {
407                     // In the case of a new import line, throw a diagnostic message
408                     // for the previous line.
409                     self.throw_unresolved_import_error(errors, None);
410                     errors = vec![];
411                 }
412                 if seen_spans.insert(err.span) {
413                     let path = import_path_to_string(
414                         &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
415                         &import.kind,
416                         err.span,
417                     );
418                     errors.push((path, err));
419                     prev_root_id = import.root_id;
420                 }
421             } else if is_indeterminate {
422                 let path = import_path_to_string(
423                     &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
424                     &import.kind,
425                     import.span,
426                 );
427                 let err = UnresolvedImportError {
428                     span: import.span,
429                     label: None,
430                     note: Vec::new(),
431                     suggestion: None,
432                 };
433                 if path.contains("::") {
434                     errors.push((path, err))
435                 }
436             }
437         }
438
439         if !errors.is_empty() {
440             self.throw_unresolved_import_error(errors, None);
441         }
442     }
443
444     fn throw_unresolved_import_error(
445         &self,
446         errors: Vec<(String, UnresolvedImportError)>,
447         span: Option<MultiSpan>,
448     ) {
449         /// Upper limit on the number of `span_label` messages.
450         const MAX_LABEL_COUNT: usize = 10;
451
452         let (span, msg) = if errors.is_empty() {
453             (span.unwrap(), "unresolved import".to_string())
454         } else {
455             let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
456
457             let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
458
459             let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
460
461             (span, msg)
462         };
463
464         let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
465
466         if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
467             for message in note {
468                 diag.note(message);
469             }
470         }
471
472         for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
473             if let Some(label) = err.label {
474                 diag.span_label(err.span, label);
475             }
476
477             if let Some((suggestions, msg, applicability)) = err.suggestion {
478                 if suggestions.is_empty() {
479                     diag.help(&msg);
480                     continue;
481                 }
482                 diag.multipart_suggestion(&msg, suggestions, applicability);
483             }
484         }
485
486         diag.emit();
487     }
488
489     /// Attempts to resolve the given import, returning true if its resolution is determined.
490     /// If successful, the resolved bindings are written into the module.
491     fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
492         debug!(
493             "(resolving import for module) resolving import `{}::...` in `{}`",
494             Segment::names_to_string(&import.module_path),
495             module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
496         );
497
498         let module = if let Some(module) = import.imported_module.get() {
499             module
500         } else {
501             // For better failure detection, pretend that the import will
502             // not define any names while resolving its module path.
503             let orig_vis = import.vis.replace(ty::Visibility::Invisible);
504             let path_res =
505                 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
506             import.vis.set(orig_vis);
507
508             match path_res {
509                 PathResult::Module(module) => module,
510                 PathResult::Indeterminate => return false,
511                 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
512             }
513         };
514
515         import.imported_module.set(Some(module));
516         let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
517             ImportKind::Single {
518                 source,
519                 target,
520                 ref source_bindings,
521                 ref target_bindings,
522                 type_ns_only,
523                 ..
524             } => (source, target, source_bindings, target_bindings, type_ns_only),
525             ImportKind::Glob { .. } => {
526                 self.resolve_glob_import(import);
527                 return true;
528             }
529             _ => unreachable!(),
530         };
531
532         let mut indeterminate = false;
533         self.r.per_ns(|this, ns| {
534             if !type_ns_only || ns == TypeNS {
535                 if let Err(Undetermined) = source_bindings[ns].get() {
536                     // For better failure detection, pretend that the import will
537                     // not define any names while resolving its module path.
538                     let orig_vis = import.vis.replace(ty::Visibility::Invisible);
539                     let binding = this.resolve_ident_in_module(
540                         module,
541                         source,
542                         ns,
543                         &import.parent_scope,
544                         None,
545                         None,
546                     );
547                     import.vis.set(orig_vis);
548                     source_bindings[ns].set(binding);
549                 } else {
550                     return;
551                 };
552
553                 let parent = import.parent_scope.module;
554                 match source_bindings[ns].get() {
555                     Err(Undetermined) => indeterminate = true,
556                     // Don't update the resolution, because it was never added.
557                     Err(Determined) if target.name == kw::Underscore => {}
558                     Ok(binding) if binding.is_importable() => {
559                         let imported_binding = this.import(binding, import);
560                         target_bindings[ns].set(Some(imported_binding));
561                         this.define(parent, target, ns, imported_binding);
562                     }
563                     source_binding @ (Ok(..) | Err(Determined)) => {
564                         if source_binding.is_ok() {
565                             let msg = format!("`{}` is not directly importable", target);
566                             struct_span_err!(this.session, import.span, E0253, "{}", &msg)
567                                 .span_label(import.span, "cannot be imported directly")
568                                 .emit();
569                         }
570                         let key = this.new_key(target, ns);
571                         this.update_resolution(parent, key, |_, resolution| {
572                             resolution.single_imports.remove(&Interned::new_unchecked(import));
573                         });
574                     }
575                 }
576             }
577         });
578
579         !indeterminate
580     }
581
582     /// Performs final import resolution, consistency checks and error reporting.
583     ///
584     /// Optionally returns an unresolved import error. This error is buffered and used to
585     /// consolidate multiple unresolved import errors into a single diagnostic.
586     fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
587         let orig_vis = import.vis.replace(ty::Visibility::Invisible);
588         let ignore_binding = match &import.kind {
589             ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
590             _ => None,
591         };
592         let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
593         let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
594         let path_res = self.r.resolve_path(
595             &import.module_path,
596             None,
597             &import.parent_scope,
598             Some(finalize),
599             ignore_binding,
600         );
601         let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
602         import.vis.set(orig_vis);
603         let module = match path_res {
604             PathResult::Module(module) => {
605                 // Consistency checks, analogous to `finalize_macro_resolutions`.
606                 if let Some(initial_module) = import.imported_module.get() {
607                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
608                         span_bug!(import.span, "inconsistent resolution for an import");
609                     }
610                 } else if self.r.privacy_errors.is_empty() {
611                     let msg = "cannot determine resolution for the import";
612                     let msg_note = "import resolution is stuck, try simplifying other imports";
613                     self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
614                 }
615
616                 module
617             }
618             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
619                 if no_ambiguity {
620                     assert!(import.imported_module.get().is_none());
621                     self.r
622                         .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
623                 }
624                 return None;
625             }
626             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
627                 if no_ambiguity {
628                     assert!(import.imported_module.get().is_none());
629                     let err = match self.make_path_suggestion(
630                         span,
631                         import.module_path.clone(),
632                         &import.parent_scope,
633                     ) {
634                         Some((suggestion, note)) => UnresolvedImportError {
635                             span,
636                             label: None,
637                             note,
638                             suggestion: Some((
639                                 vec![(span, Segment::names_to_string(&suggestion))],
640                                 String::from("a similar path exists"),
641                                 Applicability::MaybeIncorrect,
642                             )),
643                         },
644                         None => UnresolvedImportError {
645                             span,
646                             label: Some(label),
647                             note: Vec::new(),
648                             suggestion,
649                         },
650                     };
651                     return Some(err);
652                 }
653                 return None;
654             }
655             PathResult::NonModule(_) => {
656                 if no_ambiguity {
657                     assert!(import.imported_module.get().is_none());
658                 }
659                 // The error was already reported earlier.
660                 return None;
661             }
662             PathResult::Indeterminate => unreachable!(),
663         };
664
665         let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
666             ImportKind::Single {
667                 source,
668                 target,
669                 ref source_bindings,
670                 ref target_bindings,
671                 type_ns_only,
672                 ..
673             } => (source, target, source_bindings, target_bindings, type_ns_only),
674             ImportKind::Glob { is_prelude, ref max_vis } => {
675                 if import.module_path.len() <= 1 {
676                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
677                     // 2 segments, so the `resolve_path` above won't trigger it.
678                     let mut full_path = import.module_path.clone();
679                     full_path.push(Segment::from_ident(Ident::empty()));
680                     self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
681                 }
682
683                 if let ModuleOrUniformRoot::Module(module) = module {
684                     if ptr::eq(module, import.parent_scope.module) {
685                         // Importing a module into itself is not allowed.
686                         return Some(UnresolvedImportError {
687                             span: import.span,
688                             label: Some(String::from("cannot glob-import a module into itself")),
689                             note: Vec::new(),
690                             suggestion: None,
691                         });
692                     }
693                 }
694                 if !is_prelude &&
695                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
696                    !max_vis.get().is_at_least(import.vis.get(), &*self.r)
697                 {
698                     let msg = "glob import doesn't reexport anything because no candidate is public enough";
699                     self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
700                 }
701                 return None;
702             }
703             _ => unreachable!(),
704         };
705
706         let mut all_ns_err = true;
707         self.r.per_ns(|this, ns| {
708             if !type_ns_only || ns == TypeNS {
709                 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
710                 let binding = this.resolve_ident_in_module(
711                     module,
712                     ident,
713                     ns,
714                     &import.parent_scope,
715                     Some(Finalize { report_private: false, ..finalize }),
716                     target_bindings[ns].get(),
717                 );
718                 import.vis.set(orig_vis);
719
720                 match binding {
721                     Ok(binding) => {
722                         // Consistency checks, analogous to `finalize_macro_resolutions`.
723                         let initial_res = source_bindings[ns].get().map(|initial_binding| {
724                             all_ns_err = false;
725                             if let Some(target_binding) = target_bindings[ns].get() {
726                                 if target.name == kw::Underscore
727                                     && initial_binding.is_extern_crate()
728                                     && !initial_binding.is_import()
729                                 {
730                                     this.record_use(
731                                         ident,
732                                         target_binding,
733                                         import.module_path.is_empty(),
734                                     );
735                                 }
736                             }
737                             initial_binding.res()
738                         });
739                         let res = binding.res();
740                         if let Ok(initial_res) = initial_res {
741                             if res != initial_res && this.ambiguity_errors.is_empty() {
742                                 span_bug!(import.span, "inconsistent resolution for an import");
743                             }
744                         } else if res != Res::Err
745                             && this.ambiguity_errors.is_empty()
746                             && this.privacy_errors.is_empty()
747                         {
748                             let msg = "cannot determine resolution for the import";
749                             let msg_note =
750                                 "import resolution is stuck, try simplifying other imports";
751                             this.session.struct_span_err(import.span, msg).note(msg_note).emit();
752                         }
753                     }
754                     Err(..) => {
755                         // FIXME: This assert may fire if public glob is later shadowed by a private
756                         // single import (see test `issue-55884-2.rs`). In theory single imports should
757                         // always block globs, even if they are not yet resolved, so that this kind of
758                         // self-inconsistent resolution never happens.
759                         // Re-enable the assert when the issue is fixed.
760                         // assert!(result[ns].get().is_err());
761                     }
762                 }
763             }
764         });
765
766         if all_ns_err {
767             let mut all_ns_failed = true;
768             self.r.per_ns(|this, ns| {
769                 if !type_ns_only || ns == TypeNS {
770                     let binding = this.resolve_ident_in_module(
771                         module,
772                         ident,
773                         ns,
774                         &import.parent_scope,
775                         Some(finalize),
776                         None,
777                     );
778                     if binding.is_ok() {
779                         all_ns_failed = false;
780                     }
781                 }
782             });
783
784             return if all_ns_failed {
785                 let resolutions = match module {
786                     ModuleOrUniformRoot::Module(module) => {
787                         Some(self.r.resolutions(module).borrow())
788                     }
789                     _ => None,
790                 };
791                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
792                 let names = resolutions
793                     .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
794                         if *i == ident {
795                             return None;
796                         } // Never suggest the same name
797                         match *resolution.borrow() {
798                             NameResolution { binding: Some(name_binding), .. } => {
799                                 match name_binding.kind {
800                                     NameBindingKind::Import { binding, .. } => {
801                                         match binding.kind {
802                                             // Never suggest the name that has binding error
803                                             // i.e., the name that cannot be previously resolved
804                                             NameBindingKind::Res(Res::Err, _) => None,
805                                             _ => Some(i.name),
806                                         }
807                                     }
808                                     _ => Some(i.name),
809                                 }
810                             }
811                             NameResolution { ref single_imports, .. }
812                                 if single_imports.is_empty() =>
813                             {
814                                 None
815                             }
816                             _ => Some(i.name),
817                         }
818                     })
819                     .collect::<Vec<Symbol>>();
820
821                 let lev_suggestion =
822                     find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
823                         (
824                             vec![(ident.span, suggestion.to_string())],
825                             String::from("a similar name exists in the module"),
826                             Applicability::MaybeIncorrect,
827                         )
828                     });
829
830                 let (suggestion, note) =
831                     match self.check_for_module_export_macro(import, module, ident) {
832                         Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
833                         _ => (lev_suggestion, Vec::new()),
834                     };
835
836                 let label = match module {
837                     ModuleOrUniformRoot::Module(module) => {
838                         let module_str = module_to_string(module);
839                         if let Some(module_str) = module_str {
840                             format!("no `{}` in `{}`", ident, module_str)
841                         } else {
842                             format!("no `{}` in the root", ident)
843                         }
844                     }
845                     _ => {
846                         if !ident.is_path_segment_keyword() {
847                             format!("no external crate `{}`", ident)
848                         } else {
849                             // HACK(eddyb) this shows up for `self` & `super`, which
850                             // should work instead - for now keep the same error message.
851                             format!("no `{}` in the root", ident)
852                         }
853                     }
854                 };
855
856                 Some(UnresolvedImportError {
857                     span: import.span,
858                     label: Some(label),
859                     note,
860                     suggestion,
861                 })
862             } else {
863                 // `resolve_ident_in_module` reported a privacy error.
864                 None
865             };
866         }
867
868         let mut reexport_error = None;
869         let mut any_successful_reexport = false;
870         let mut crate_private_reexport = false;
871         self.r.per_ns(|this, ns| {
872             if let Ok(binding) = source_bindings[ns].get() {
873                 let vis = import.vis.get();
874                 if !binding.vis.is_at_least(vis, &*this) {
875                     reexport_error = Some((ns, binding));
876                     if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
877                         if binding_def_id.is_top_level_module() {
878                             crate_private_reexport = true;
879                         }
880                     }
881                 } else {
882                     any_successful_reexport = true;
883                 }
884             }
885         });
886
887         // All namespaces must be re-exported with extra visibility for an error to occur.
888         if !any_successful_reexport {
889             let (ns, binding) = reexport_error.unwrap();
890             if pub_use_of_private_extern_crate_hack(import, binding) {
891                 let msg = format!(
892                     "extern crate `{}` is private, and cannot be \
893                                    re-exported (error E0365), consider declaring with \
894                                    `pub`",
895                     ident
896                 );
897                 self.r.lint_buffer.buffer_lint(
898                     PUB_USE_OF_PRIVATE_EXTERN_CRATE,
899                     import.id,
900                     import.span,
901                     &msg,
902                 );
903             } else {
904                 let error_msg = if crate_private_reexport {
905                     format!(
906                         "`{}` is only public within the crate, and cannot be re-exported outside",
907                         ident
908                     )
909                 } else {
910                     format!("`{}` is private, and cannot be re-exported", ident)
911                 };
912
913                 if ns == TypeNS {
914                     let label_msg = if crate_private_reexport {
915                         format!("re-export of crate public `{}`", ident)
916                     } else {
917                         format!("re-export of private `{}`", ident)
918                     };
919
920                     struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
921                         .span_label(import.span, label_msg)
922                         .note(&format!("consider declaring type or module `{}` with `pub`", ident))
923                         .emit();
924                 } else {
925                     let mut err =
926                         struct_span_err!(self.r.session, import.span, E0364, "{error_msg}");
927                     match binding.kind {
928                         NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id), _)
929                             // exclude decl_macro
930                             if self.r.get_macro_by_def_id(def_id).macro_rules =>
931                         {
932                             err.span_help(
933                                 binding.span,
934                                 "consider adding a `#[macro_export]` to the macro in the imported module",
935                             );
936                         }
937                         _ => {
938                             err.span_note(
939                                 import.span,
940                                 &format!(
941                                     "consider marking `{ident}` as `pub` in the imported module"
942                                 ),
943                             );
944                         }
945                     }
946                     err.emit();
947                 }
948             }
949         }
950
951         if import.module_path.len() <= 1 {
952             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
953             // 2 segments, so the `resolve_path` above won't trigger it.
954             let mut full_path = import.module_path.clone();
955             full_path.push(Segment::from_ident(ident));
956             self.r.per_ns(|this, ns| {
957                 if let Ok(binding) = source_bindings[ns].get() {
958                     this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
959                 }
960             });
961         }
962
963         // Record what this import resolves to for later uses in documentation,
964         // this may resolve to either a value or a type, but for documentation
965         // purposes it's good enough to just favor one over the other.
966         self.r.per_ns(|this, ns| {
967             if let Ok(binding) = source_bindings[ns].get() {
968                 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
969             }
970         });
971
972         self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
973
974         debug!("(resolving single import) successfully resolved import");
975         None
976     }
977
978     fn check_for_redundant_imports(
979         &mut self,
980         ident: Ident,
981         import: &'b Import<'b>,
982         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
983         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
984         target: Ident,
985     ) {
986         // Skip if the import was produced by a macro.
987         if import.parent_scope.expansion != LocalExpnId::ROOT {
988             return;
989         }
990
991         // Skip if we are inside a named module (in contrast to an anonymous
992         // module defined by a block).
993         if let ModuleKind::Def(..) = import.parent_scope.module.kind {
994             return;
995         }
996
997         let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
998
999         let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1000
1001         self.r.per_ns(|this, ns| {
1002             if let Ok(binding) = source_bindings[ns].get() {
1003                 if binding.res() == Res::Err {
1004                     return;
1005                 }
1006
1007                 match this.early_resolve_ident_in_lexical_scope(
1008                     target,
1009                     ScopeSet::All(ns, false),
1010                     &import.parent_scope,
1011                     None,
1012                     false,
1013                     target_bindings[ns].get(),
1014                 ) {
1015                     Ok(other_binding) => {
1016                         is_redundant[ns] = Some(
1017                             binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1018                         );
1019                         redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1020                     }
1021                     Err(_) => is_redundant[ns] = Some(false),
1022                 }
1023             }
1024         });
1025
1026         if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1027         {
1028             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1029             redundant_spans.sort();
1030             redundant_spans.dedup();
1031             self.r.lint_buffer.buffer_lint_with_diagnostic(
1032                 UNUSED_IMPORTS,
1033                 import.id,
1034                 import.span,
1035                 &format!("the item `{}` is imported redundantly", ident),
1036                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1037             );
1038         }
1039     }
1040
1041     fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1042         let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1043             self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1044             return;
1045         };
1046
1047         if module.is_trait() {
1048             self.r.session.span_err(import.span, "items in traits are not importable");
1049             return;
1050         } else if ptr::eq(module, import.parent_scope.module) {
1051             return;
1052         } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1053             self.r.prelude = Some(module);
1054             return;
1055         }
1056
1057         // Add to module's glob_importers
1058         module.glob_importers.borrow_mut().push(import);
1059
1060         // Ensure that `resolutions` isn't borrowed during `try_define`,
1061         // since it might get updated via a glob cycle.
1062         let bindings = self
1063             .r
1064             .resolutions(module)
1065             .borrow()
1066             .iter()
1067             .filter_map(|(key, resolution)| {
1068                 resolution.borrow().binding().map(|binding| (*key, binding))
1069             })
1070             .collect::<Vec<_>>();
1071         for (mut key, binding) in bindings {
1072             let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1073                 Some(Some(def)) => self.r.expn_def_scope(def),
1074                 Some(None) => import.parent_scope.module,
1075                 None => continue,
1076             };
1077             if self.r.is_accessible_from(binding.vis, scope) {
1078                 let imported_binding = self.r.import(binding, import);
1079                 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1080             }
1081         }
1082
1083         // Record the destination of this import
1084         self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1085     }
1086
1087     // Miscellaneous post-processing, including recording re-exports,
1088     // reporting conflicts, and reporting unresolved imports.
1089     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1090         // Since import resolution is finished, globs will not define any more names.
1091         *module.globs.borrow_mut() = Vec::new();
1092
1093         if let Some(def_id) = module.opt_def_id() {
1094             let mut reexports = Vec::new();
1095
1096             module.for_each_child(self.r, |_, ident, _, binding| {
1097                 // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1098                 // into the crate root to actual `NameBindingKind::Import`.
1099                 if binding.is_import()
1100                     || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
1101                 {
1102                     let res = binding.res().expect_non_local();
1103                     // Ambiguous imports are treated as errors at this point and are
1104                     // not exposed to other crates (see #36837 for more details).
1105                     if res != def::Res::Err && !binding.is_ambiguity() {
1106                         reexports.push(ModChild {
1107                             ident,
1108                             res,
1109                             vis: binding.vis,
1110                             span: binding.span,
1111                             macro_rules: false,
1112                         });
1113                     }
1114                 }
1115             });
1116
1117             if !reexports.is_empty() {
1118                 // Call to `expect_local` should be fine because current
1119                 // code is only called for local modules.
1120                 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1121             }
1122         }
1123     }
1124 }
1125
1126 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1127     let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1128     let global = !names.is_empty() && names[0].name == kw::PathRoot;
1129     if let Some(pos) = pos {
1130         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1131         names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1132     } else {
1133         let names = if global { &names[1..] } else { names };
1134         if names.is_empty() {
1135             import_kind_to_string(import_kind)
1136         } else {
1137             format!(
1138                 "{}::{}",
1139                 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1140                 import_kind_to_string(import_kind),
1141             )
1142         }
1143     }
1144 }
1145
1146 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1147     match import_kind {
1148         ImportKind::Single { source, .. } => source.to_string(),
1149         ImportKind::Glob { .. } => "*".to_string(),
1150         ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1151         ImportKind::MacroUse => "#[macro_use]".to_string(),
1152     }
1153 }