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