]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/imports.rs
3d0e2b9921d00e17a1602608ba1229fb9c23f39f
[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, 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 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 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     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     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     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                 diag.multipart_suggestion(&msg, suggestions, applicability);
479             }
480         }
481
482         diag.emit();
483     }
484
485     /// Attempts to resolve the given import, returning true if its resolution is determined.
486     /// If successful, the resolved bindings are written into the module.
487     fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
488         debug!(
489             "(resolving import for module) resolving import `{}::...` in `{}`",
490             Segment::names_to_string(&import.module_path),
491             module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
492         );
493
494         let module = if let Some(module) = import.imported_module.get() {
495             module
496         } else {
497             // For better failure detection, pretend that the import will
498             // not define any names while resolving its module path.
499             let orig_vis = import.vis.replace(ty::Visibility::Invisible);
500             let path_res =
501                 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
502             import.vis.set(orig_vis);
503
504             match path_res {
505                 PathResult::Module(module) => module,
506                 PathResult::Indeterminate => return false,
507                 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
508             }
509         };
510
511         import.imported_module.set(Some(module));
512         let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
513             ImportKind::Single {
514                 source,
515                 target,
516                 ref source_bindings,
517                 ref target_bindings,
518                 type_ns_only,
519                 ..
520             } => (source, target, source_bindings, target_bindings, type_ns_only),
521             ImportKind::Glob { .. } => {
522                 self.resolve_glob_import(import);
523                 return true;
524             }
525             _ => unreachable!(),
526         };
527
528         let mut indeterminate = false;
529         self.r.per_ns(|this, ns| {
530             if !type_ns_only || ns == TypeNS {
531                 if let Err(Undetermined) = source_bindings[ns].get() {
532                     // For better failure detection, pretend that the import will
533                     // not define any names while resolving its module path.
534                     let orig_vis = import.vis.replace(ty::Visibility::Invisible);
535                     let binding = this.resolve_ident_in_module(
536                         module,
537                         source,
538                         ns,
539                         &import.parent_scope,
540                         None,
541                         None,
542                     );
543                     import.vis.set(orig_vis);
544                     source_bindings[ns].set(binding);
545                 } else {
546                     return;
547                 };
548
549                 let parent = import.parent_scope.module;
550                 match source_bindings[ns].get() {
551                     Err(Undetermined) => indeterminate = true,
552                     // Don't update the resolution, because it was never added.
553                     Err(Determined) if target.name == kw::Underscore => {}
554                     Ok(binding) if binding.is_importable() => {
555                         let imported_binding = this.import(binding, import);
556                         target_bindings[ns].set(Some(imported_binding));
557                         this.define(parent, target, ns, imported_binding);
558                     }
559                     source_binding @ (Ok(..) | Err(Determined)) => {
560                         if source_binding.is_ok() {
561                             let msg = format!("`{}` is not directly importable", target);
562                             struct_span_err!(this.session, import.span, E0253, "{}", &msg)
563                                 .span_label(import.span, "cannot be imported directly")
564                                 .emit();
565                         }
566                         let key = this.new_key(target, ns);
567                         this.update_resolution(parent, key, |_, resolution| {
568                             resolution.single_imports.remove(&Interned::new_unchecked(import));
569                         });
570                     }
571                 }
572             }
573         });
574
575         !indeterminate
576     }
577
578     /// Performs final import resolution, consistency checks and error reporting.
579     ///
580     /// Optionally returns an unresolved import error. This error is buffered and used to
581     /// consolidate multiple unresolved import errors into a single diagnostic.
582     fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
583         let orig_vis = import.vis.replace(ty::Visibility::Invisible);
584         let ignore_binding = match &import.kind {
585             ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
586             _ => None,
587         };
588         let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
589         let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
590         let path_res = self.r.resolve_path(
591             &import.module_path,
592             None,
593             &import.parent_scope,
594             Some(finalize),
595             ignore_binding,
596         );
597         let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
598         import.vis.set(orig_vis);
599         let module = match path_res {
600             PathResult::Module(module) => {
601                 // Consistency checks, analogous to `finalize_macro_resolutions`.
602                 if let Some(initial_module) = import.imported_module.get() {
603                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
604                         span_bug!(import.span, "inconsistent resolution for an import");
605                     }
606                 } else if self.r.privacy_errors.is_empty() {
607                     let msg = "cannot determine resolution for the import";
608                     let msg_note = "import resolution is stuck, try simplifying other imports";
609                     self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
610                 }
611
612                 module
613             }
614             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
615                 if no_ambiguity {
616                     assert!(import.imported_module.get().is_none());
617                     self.r
618                         .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
619                 }
620                 return None;
621             }
622             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
623                 if no_ambiguity {
624                     assert!(import.imported_module.get().is_none());
625                     let err = match self.make_path_suggestion(
626                         span,
627                         import.module_path.clone(),
628                         &import.parent_scope,
629                     ) {
630                         Some((suggestion, note)) => UnresolvedImportError {
631                             span,
632                             label: None,
633                             note,
634                             suggestion: Some((
635                                 vec![(span, Segment::names_to_string(&suggestion))],
636                                 String::from("a similar path exists"),
637                                 Applicability::MaybeIncorrect,
638                             )),
639                         },
640                         None => UnresolvedImportError {
641                             span,
642                             label: Some(label),
643                             note: Vec::new(),
644                             suggestion,
645                         },
646                     };
647                     return Some(err);
648                 }
649                 return None;
650             }
651             PathResult::NonModule(_) => {
652                 if no_ambiguity {
653                     assert!(import.imported_module.get().is_none());
654                 }
655                 // The error was already reported earlier.
656                 return None;
657             }
658             PathResult::Indeterminate => unreachable!(),
659         };
660
661         let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
662             ImportKind::Single {
663                 source,
664                 target,
665                 ref source_bindings,
666                 ref target_bindings,
667                 type_ns_only,
668                 ..
669             } => (source, target, source_bindings, target_bindings, type_ns_only),
670             ImportKind::Glob { is_prelude, ref max_vis } => {
671                 if import.module_path.len() <= 1 {
672                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
673                     // 2 segments, so the `resolve_path` above won't trigger it.
674                     let mut full_path = import.module_path.clone();
675                     full_path.push(Segment::from_ident(Ident::empty()));
676                     self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
677                 }
678
679                 if let ModuleOrUniformRoot::Module(module) = module {
680                     if ptr::eq(module, import.parent_scope.module) {
681                         // Importing a module into itself is not allowed.
682                         return Some(UnresolvedImportError {
683                             span: import.span,
684                             label: Some(String::from("cannot glob-import a module into itself")),
685                             note: Vec::new(),
686                             suggestion: None,
687                         });
688                     }
689                 }
690                 if !is_prelude &&
691                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
692                    !max_vis.get().is_at_least(import.vis.get(), &*self.r)
693                 {
694                     let msg = "glob import doesn't reexport anything because no candidate is public enough";
695                     self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
696                 }
697                 return None;
698             }
699             _ => unreachable!(),
700         };
701
702         let mut all_ns_err = true;
703         self.r.per_ns(|this, ns| {
704             if !type_ns_only || ns == TypeNS {
705                 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
706                 let binding = this.resolve_ident_in_module(
707                     module,
708                     ident,
709                     ns,
710                     &import.parent_scope,
711                     Some(Finalize { report_private: false, ..finalize }),
712                     target_bindings[ns].get(),
713                 );
714                 import.vis.set(orig_vis);
715
716                 match binding {
717                     Ok(binding) => {
718                         // Consistency checks, analogous to `finalize_macro_resolutions`.
719                         let initial_res = source_bindings[ns].get().map(|initial_binding| {
720                             all_ns_err = false;
721                             if let Some(target_binding) = target_bindings[ns].get() {
722                                 if target.name == kw::Underscore
723                                     && initial_binding.is_extern_crate()
724                                     && !initial_binding.is_import()
725                                 {
726                                     this.record_use(
727                                         ident,
728                                         target_binding,
729                                         import.module_path.is_empty(),
730                                     );
731                                 }
732                             }
733                             initial_binding.res()
734                         });
735                         let res = binding.res();
736                         if let Ok(initial_res) = initial_res {
737                             if res != initial_res && this.ambiguity_errors.is_empty() {
738                                 span_bug!(import.span, "inconsistent resolution for an import");
739                             }
740                         } else if res != Res::Err
741                             && this.ambiguity_errors.is_empty()
742                             && this.privacy_errors.is_empty()
743                         {
744                             let msg = "cannot determine resolution for the import";
745                             let msg_note =
746                                 "import resolution is stuck, try simplifying other imports";
747                             this.session.struct_span_err(import.span, msg).note(msg_note).emit();
748                         }
749                     }
750                     Err(..) => {
751                         // FIXME: This assert may fire if public glob is later shadowed by a private
752                         // single import (see test `issue-55884-2.rs`). In theory single imports should
753                         // always block globs, even if they are not yet resolved, so that this kind of
754                         // self-inconsistent resolution never happens.
755                         // Re-enable the assert when the issue is fixed.
756                         // assert!(result[ns].get().is_err());
757                     }
758                 }
759             }
760         });
761
762         if all_ns_err {
763             let mut all_ns_failed = true;
764             self.r.per_ns(|this, ns| {
765                 if !type_ns_only || ns == TypeNS {
766                     let binding = this.resolve_ident_in_module(
767                         module,
768                         ident,
769                         ns,
770                         &import.parent_scope,
771                         Some(finalize),
772                         None,
773                     );
774                     if binding.is_ok() {
775                         all_ns_failed = false;
776                     }
777                 }
778             });
779
780             return if all_ns_failed {
781                 let resolutions = match module {
782                     ModuleOrUniformRoot::Module(module) => {
783                         Some(self.r.resolutions(module).borrow())
784                     }
785                     _ => None,
786                 };
787                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
788                 let names = resolutions
789                     .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
790                         if *i == ident {
791                             return None;
792                         } // Never suggest the same name
793                         match *resolution.borrow() {
794                             NameResolution { binding: Some(name_binding), .. } => {
795                                 match name_binding.kind {
796                                     NameBindingKind::Import { binding, .. } => {
797                                         match binding.kind {
798                                             // Never suggest the name that has binding error
799                                             // i.e., the name that cannot be previously resolved
800                                             NameBindingKind::Res(Res::Err, _) => None,
801                                             _ => Some(i.name),
802                                         }
803                                     }
804                                     _ => Some(i.name),
805                                 }
806                             }
807                             NameResolution { ref single_imports, .. }
808                                 if single_imports.is_empty() =>
809                             {
810                                 None
811                             }
812                             _ => Some(i.name),
813                         }
814                     })
815                     .collect::<Vec<Symbol>>();
816
817                 let lev_suggestion =
818                     find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
819                         (
820                             vec![(ident.span, suggestion.to_string())],
821                             String::from("a similar name exists in the module"),
822                             Applicability::MaybeIncorrect,
823                         )
824                     });
825
826                 let (suggestion, note) =
827                     match self.check_for_module_export_macro(import, module, ident) {
828                         Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
829                         _ => (lev_suggestion, Vec::new()),
830                     };
831
832                 let label = match module {
833                     ModuleOrUniformRoot::Module(module) => {
834                         let module_str = module_to_string(module);
835                         if let Some(module_str) = module_str {
836                             format!("no `{}` in `{}`", ident, module_str)
837                         } else {
838                             format!("no `{}` in the root", ident)
839                         }
840                     }
841                     _ => {
842                         if !ident.is_path_segment_keyword() {
843                             format!("no external crate `{}`", ident)
844                         } else {
845                             // HACK(eddyb) this shows up for `self` & `super`, which
846                             // should work instead - for now keep the same error message.
847                             format!("no `{}` in the root", ident)
848                         }
849                     }
850                 };
851
852                 Some(UnresolvedImportError {
853                     span: import.span,
854                     label: Some(label),
855                     note,
856                     suggestion,
857                 })
858             } else {
859                 // `resolve_ident_in_module` reported a privacy error.
860                 None
861             };
862         }
863
864         let mut reexport_error = None;
865         let mut any_successful_reexport = false;
866         let mut crate_private_reexport = false;
867         self.r.per_ns(|this, ns| {
868             if let Ok(binding) = source_bindings[ns].get() {
869                 let vis = import.vis.get();
870                 if !binding.vis.is_at_least(vis, &*this) {
871                     reexport_error = Some((ns, binding));
872                     if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
873                         if binding_def_id.is_top_level_module() {
874                             crate_private_reexport = true;
875                         }
876                     }
877                 } else {
878                     any_successful_reexport = true;
879                 }
880             }
881         });
882
883         // All namespaces must be re-exported with extra visibility for an error to occur.
884         if !any_successful_reexport {
885             let (ns, binding) = reexport_error.unwrap();
886             if pub_use_of_private_extern_crate_hack(import, binding) {
887                 let msg = format!(
888                     "extern crate `{}` is private, and cannot be \
889                                    re-exported (error E0365), consider declaring with \
890                                    `pub`",
891                     ident
892                 );
893                 self.r.lint_buffer.buffer_lint(
894                     PUB_USE_OF_PRIVATE_EXTERN_CRATE,
895                     import.id,
896                     import.span,
897                     &msg,
898                 );
899             } else {
900                 let error_msg = if crate_private_reexport {
901                     format!(
902                         "`{}` is only public within the crate, and cannot be re-exported outside",
903                         ident
904                     )
905                 } else {
906                     format!("`{}` is private, and cannot be re-exported", ident)
907                 };
908
909                 if ns == TypeNS {
910                     let label_msg = if crate_private_reexport {
911                         format!("re-export of crate public `{}`", ident)
912                     } else {
913                         format!("re-export of private `{}`", ident)
914                     };
915
916                     struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
917                         .span_label(import.span, label_msg)
918                         .note(&format!("consider declaring type or module `{}` with `pub`", ident))
919                         .emit();
920                 } else {
921                     let note_msg =
922                         format!("consider marking `{}` as `pub` in the imported module", ident);
923                     struct_span_err!(self.r.session, import.span, E0364, "{}", error_msg)
924                         .span_note(import.span, &note_msg)
925                         .emit();
926                 }
927             }
928         }
929
930         if import.module_path.len() <= 1 {
931             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
932             // 2 segments, so the `resolve_path` above won't trigger it.
933             let mut full_path = import.module_path.clone();
934             full_path.push(Segment::from_ident(ident));
935             self.r.per_ns(|this, ns| {
936                 if let Ok(binding) = source_bindings[ns].get() {
937                     this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
938                 }
939             });
940         }
941
942         // Record what this import resolves to for later uses in documentation,
943         // this may resolve to either a value or a type, but for documentation
944         // purposes it's good enough to just favor one over the other.
945         self.r.per_ns(|this, ns| {
946             if let Ok(binding) = source_bindings[ns].get() {
947                 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
948             }
949         });
950
951         self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
952
953         debug!("(resolving single import) successfully resolved import");
954         None
955     }
956
957     fn check_for_redundant_imports(
958         &mut self,
959         ident: Ident,
960         import: &'b Import<'b>,
961         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
962         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
963         target: Ident,
964     ) {
965         // Skip if the import was produced by a macro.
966         if import.parent_scope.expansion != LocalExpnId::ROOT {
967             return;
968         }
969
970         // Skip if we are inside a named module (in contrast to an anonymous
971         // module defined by a block).
972         if let ModuleKind::Def(..) = import.parent_scope.module.kind {
973             return;
974         }
975
976         let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
977
978         let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
979
980         self.r.per_ns(|this, ns| {
981             if let Ok(binding) = source_bindings[ns].get() {
982                 if binding.res() == Res::Err {
983                     return;
984                 }
985
986                 match this.early_resolve_ident_in_lexical_scope(
987                     target,
988                     ScopeSet::All(ns, false),
989                     &import.parent_scope,
990                     None,
991                     false,
992                     target_bindings[ns].get(),
993                 ) {
994                     Ok(other_binding) => {
995                         is_redundant[ns] = Some(
996                             binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
997                         );
998                         redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
999                     }
1000                     Err(_) => is_redundant[ns] = Some(false),
1001                 }
1002             }
1003         });
1004
1005         if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1006         {
1007             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1008             redundant_spans.sort();
1009             redundant_spans.dedup();
1010             self.r.lint_buffer.buffer_lint_with_diagnostic(
1011                 UNUSED_IMPORTS,
1012                 import.id,
1013                 import.span,
1014                 &format!("the item `{}` is imported redundantly", ident),
1015                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1016             );
1017         }
1018     }
1019
1020     fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1021         let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1022             self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1023             return;
1024         };
1025
1026         if module.is_trait() {
1027             self.r.session.span_err(import.span, "items in traits are not importable");
1028             return;
1029         } else if ptr::eq(module, import.parent_scope.module) {
1030             return;
1031         } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1032             self.r.prelude = Some(module);
1033             return;
1034         }
1035
1036         // Add to module's glob_importers
1037         module.glob_importers.borrow_mut().push(import);
1038
1039         // Ensure that `resolutions` isn't borrowed during `try_define`,
1040         // since it might get updated via a glob cycle.
1041         let bindings = self
1042             .r
1043             .resolutions(module)
1044             .borrow()
1045             .iter()
1046             .filter_map(|(key, resolution)| {
1047                 resolution.borrow().binding().map(|binding| (*key, binding))
1048             })
1049             .collect::<Vec<_>>();
1050         for (mut key, binding) in bindings {
1051             let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1052                 Some(Some(def)) => self.r.expn_def_scope(def),
1053                 Some(None) => import.parent_scope.module,
1054                 None => continue,
1055             };
1056             if self.r.is_accessible_from(binding.vis, scope) {
1057                 let imported_binding = self.r.import(binding, import);
1058                 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1059             }
1060         }
1061
1062         // Record the destination of this import
1063         self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1064     }
1065
1066     // Miscellaneous post-processing, including recording re-exports,
1067     // reporting conflicts, and reporting unresolved imports.
1068     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1069         // Since import resolution is finished, globs will not define any more names.
1070         *module.globs.borrow_mut() = Vec::new();
1071
1072         let mut reexports = Vec::new();
1073
1074         module.for_each_child(self.r, |_, ident, _, binding| {
1075             // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1076             // into the crate root to actual `NameBindingKind::Import`.
1077             if binding.is_import()
1078                 || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
1079             {
1080                 let res = binding.res().expect_non_local();
1081                 // Ambiguous imports are treated as errors at this point and are
1082                 // not exposed to other crates (see #36837 for more details).
1083                 if res != def::Res::Err && !binding.is_ambiguity() {
1084                     reexports.push(ModChild {
1085                         ident,
1086                         res,
1087                         vis: binding.vis,
1088                         span: binding.span,
1089                         macro_rules: false,
1090                     });
1091                 }
1092             }
1093         });
1094
1095         if !reexports.is_empty() {
1096             if let Some(def_id) = module.opt_def_id() {
1097                 // Call to `expect_local` should be fine because current
1098                 // code is only called for local modules.
1099                 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1100             }
1101         }
1102     }
1103 }
1104
1105 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1106     let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1107     let global = !names.is_empty() && names[0].name == kw::PathRoot;
1108     if let Some(pos) = pos {
1109         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1110         names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1111     } else {
1112         let names = if global { &names[1..] } else { names };
1113         if names.is_empty() {
1114             import_kind_to_string(import_kind)
1115         } else {
1116             format!(
1117                 "{}::{}",
1118                 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1119                 import_kind_to_string(import_kind),
1120             )
1121         }
1122     }
1123 }
1124
1125 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1126     match import_kind {
1127         ImportKind::Single { source, .. } => source.to_string(),
1128         ImportKind::Glob { .. } => "*".to_string(),
1129         ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1130         ImportKind::MacroUse => "#[macro_use]".to_string(),
1131     }
1132 }