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