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