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