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