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