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