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