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