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