]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/imports.rs
Rollup merge of #106739 - WaffleLapkin:astconv, r=estebank
[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)
558                             .then(|| format!(" as {target}"))
559                             .as_deref()
560                             .unwrap_or(""),
561                     ),
562                     ImportKind::Single { nested: true, source, target, .. } => {
563                         import_candidates(
564                             self.r.session,
565                             &self.r.untracked.source_span,
566                             &mut diag,
567                             None,
568                             &candidates,
569                             DiagnosticMode::Normal,
570                             (source != target)
571                                 .then(|| format!(" as {target}"))
572                                 .as_deref()
573                                 .unwrap_or(""),
574                         );
575                     }
576                     _ => {}
577                 }
578             }
579         }
580
581         diag.emit();
582     }
583
584     /// Attempts to resolve the given import, returning true if its resolution is determined.
585     /// If successful, the resolved bindings are written into the module.
586     fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
587         debug!(
588             "(resolving import for module) resolving import `{}::...` in `{}`",
589             Segment::names_to_string(&import.module_path),
590             module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
591         );
592
593         let module = if let Some(module) = import.imported_module.get() {
594             module
595         } else {
596             // For better failure detection, pretend that the import will
597             // not define any names while resolving its module path.
598             let orig_vis = import.vis.take();
599             let path_res =
600                 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
601             import.vis.set(orig_vis);
602
603             match path_res {
604                 PathResult::Module(module) => module,
605                 PathResult::Indeterminate => return false,
606                 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
607             }
608         };
609
610         import.imported_module.set(Some(module));
611         let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
612             ImportKind::Single {
613                 source,
614                 target,
615                 ref source_bindings,
616                 ref target_bindings,
617                 type_ns_only,
618                 ..
619             } => (source, target, source_bindings, target_bindings, type_ns_only),
620             ImportKind::Glob { .. } => {
621                 self.resolve_glob_import(import);
622                 return true;
623             }
624             _ => unreachable!(),
625         };
626
627         let mut indeterminate = false;
628         self.r.per_ns(|this, ns| {
629             if !type_ns_only || ns == TypeNS {
630                 if let Err(Undetermined) = source_bindings[ns].get() {
631                     // For better failure detection, pretend that the import will
632                     // not define any names while resolving its module path.
633                     let orig_vis = import.vis.take();
634                     let binding = this.resolve_ident_in_module(
635                         module,
636                         source,
637                         ns,
638                         &import.parent_scope,
639                         None,
640                         None,
641                     );
642                     import.vis.set(orig_vis);
643                     source_bindings[ns].set(binding);
644                 } else {
645                     return;
646                 };
647
648                 let parent = import.parent_scope.module;
649                 match source_bindings[ns].get() {
650                     Err(Undetermined) => indeterminate = true,
651                     // Don't update the resolution, because it was never added.
652                     Err(Determined) if target.name == kw::Underscore => {}
653                     Ok(binding) if binding.is_importable() => {
654                         let imported_binding = this.import(binding, import);
655                         target_bindings[ns].set(Some(imported_binding));
656                         this.define(parent, target, ns, imported_binding);
657                     }
658                     source_binding @ (Ok(..) | Err(Determined)) => {
659                         if source_binding.is_ok() {
660                             let msg = format!("`{}` is not directly importable", target);
661                             struct_span_err!(this.session, import.span, E0253, "{}", &msg)
662                                 .span_label(import.span, "cannot be imported directly")
663                                 .emit();
664                         }
665                         let key = this.new_key(target, ns);
666                         this.update_resolution(parent, key, |_, resolution| {
667                             resolution.single_imports.remove(&Interned::new_unchecked(import));
668                         });
669                     }
670                 }
671             }
672         });
673
674         !indeterminate
675     }
676
677     /// Performs final import resolution, consistency checks and error reporting.
678     ///
679     /// Optionally returns an unresolved import error. This error is buffered and used to
680     /// consolidate multiple unresolved import errors into a single diagnostic.
681     fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
682         let orig_vis = import.vis.take();
683         let ignore_binding = match &import.kind {
684             ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
685             _ => None,
686         };
687         let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
688         let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
689         let path_res = self.r.resolve_path(
690             &import.module_path,
691             None,
692             &import.parent_scope,
693             Some(finalize),
694             ignore_binding,
695         );
696
697         let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
698         import.vis.set(orig_vis);
699         let module = match path_res {
700             PathResult::Module(module) => {
701                 // Consistency checks, analogous to `finalize_macro_resolutions`.
702                 if let Some(initial_module) = import.imported_module.get() {
703                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
704                         span_bug!(import.span, "inconsistent resolution for an import");
705                     }
706                 } else if self.r.privacy_errors.is_empty() {
707                     let msg = "cannot determine resolution for the import";
708                     let msg_note = "import resolution is stuck, try simplifying other imports";
709                     self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
710                 }
711
712                 module
713             }
714             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
715                 if no_ambiguity {
716                     assert!(import.imported_module.get().is_none());
717                     self.r
718                         .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
719                 }
720                 return None;
721             }
722             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
723                 if no_ambiguity {
724                     assert!(import.imported_module.get().is_none());
725                     let err = match self.make_path_suggestion(
726                         span,
727                         import.module_path.clone(),
728                         &import.parent_scope,
729                     ) {
730                         Some((suggestion, note)) => UnresolvedImportError {
731                             span,
732                             label: None,
733                             note,
734                             suggestion: Some((
735                                 vec![(span, Segment::names_to_string(&suggestion))],
736                                 String::from("a similar path exists"),
737                                 Applicability::MaybeIncorrect,
738                             )),
739                             candidates: None,
740                         },
741                         None => UnresolvedImportError {
742                             span,
743                             label: Some(label),
744                             note: None,
745                             suggestion,
746                             candidates: None,
747                         },
748                     };
749                     return Some(err);
750                 }
751                 return None;
752             }
753             PathResult::NonModule(_) => {
754                 if no_ambiguity {
755                     assert!(import.imported_module.get().is_none());
756                 }
757                 // The error was already reported earlier.
758                 return None;
759             }
760             PathResult::Indeterminate => unreachable!(),
761         };
762
763         let (ident, target, source_bindings, target_bindings, type_ns_only, import_id) =
764             match import.kind {
765                 ImportKind::Single {
766                     source,
767                     target,
768                     ref source_bindings,
769                     ref target_bindings,
770                     type_ns_only,
771                     id,
772                     ..
773                 } => (source, target, source_bindings, target_bindings, type_ns_only, id),
774                 ImportKind::Glob { is_prelude, ref max_vis, id } => {
775                     if import.module_path.len() <= 1 {
776                         // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
777                         // 2 segments, so the `resolve_path` above won't trigger it.
778                         let mut full_path = import.module_path.clone();
779                         full_path.push(Segment::from_ident(Ident::empty()));
780                         self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
781                     }
782
783                     if let ModuleOrUniformRoot::Module(module) = module {
784                         if ptr::eq(module, import.parent_scope.module) {
785                             // Importing a module into itself is not allowed.
786                             return Some(UnresolvedImportError {
787                                 span: import.span,
788                                 label: Some(String::from(
789                                     "cannot glob-import a module into itself",
790                                 )),
791                                 note: None,
792                                 suggestion: None,
793                                 candidates: None,
794                             });
795                         }
796                     }
797                     if !is_prelude
798                     && let Some(max_vis) = max_vis.get()
799                     && !max_vis.is_at_least(import.expect_vis(), &*self.r)
800                 {
801                     let msg = "glob import doesn't reexport anything because no candidate is public enough";
802                     self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, id, import.span, msg);
803                 }
804                     return None;
805                 }
806                 _ => unreachable!(),
807             };
808
809         let mut all_ns_err = true;
810         self.r.per_ns(|this, ns| {
811             if !type_ns_only || ns == TypeNS {
812                 let orig_vis = import.vis.take();
813                 let binding = this.resolve_ident_in_module(
814                     module,
815                     ident,
816                     ns,
817                     &import.parent_scope,
818                     Some(Finalize { report_private: false, ..finalize }),
819                     target_bindings[ns].get(),
820                 );
821                 import.vis.set(orig_vis);
822
823                 match binding {
824                     Ok(binding) => {
825                         // Consistency checks, analogous to `finalize_macro_resolutions`.
826                         let initial_binding = source_bindings[ns].get().map(|initial_binding| {
827                             all_ns_err = false;
828                             if let Some(target_binding) = target_bindings[ns].get() {
829                                 if target.name == kw::Underscore
830                                     && initial_binding.is_extern_crate()
831                                     && !initial_binding.is_import()
832                                 {
833                                     this.record_use(
834                                         ident,
835                                         target_binding,
836                                         import.module_path.is_empty(),
837                                     );
838                                 }
839                             }
840                             initial_binding
841                         });
842                         let res = binding.res();
843                         if let Ok(initial_binding) = initial_binding {
844                             let initial_res = initial_binding.res();
845                             if res != initial_res && this.ambiguity_errors.is_empty() {
846                                 this.ambiguity_errors.push(AmbiguityError {
847                                     kind: AmbiguityKind::Import,
848                                     ident,
849                                     b1: initial_binding,
850                                     b2: binding,
851                                     misc1: AmbiguityErrorMisc::None,
852                                     misc2: AmbiguityErrorMisc::None,
853                                 });
854                             }
855                         } else if res != Res::Err
856                             && this.ambiguity_errors.is_empty()
857                             && this.privacy_errors.is_empty()
858                         {
859                             let msg = "cannot determine resolution for the import";
860                             let msg_note =
861                                 "import resolution is stuck, try simplifying other imports";
862                             this.session.struct_span_err(import.span, msg).note(msg_note).emit();
863                         }
864                     }
865                     Err(..) => {
866                         // FIXME: This assert may fire if public glob is later shadowed by a private
867                         // single import (see test `issue-55884-2.rs`). In theory single imports should
868                         // always block globs, even if they are not yet resolved, so that this kind of
869                         // self-inconsistent resolution never happens.
870                         // Re-enable the assert when the issue is fixed.
871                         // assert!(result[ns].get().is_err());
872                     }
873                 }
874             }
875         });
876
877         if all_ns_err {
878             let mut all_ns_failed = true;
879             self.r.per_ns(|this, ns| {
880                 if !type_ns_only || ns == TypeNS {
881                     let binding = this.resolve_ident_in_module(
882                         module,
883                         ident,
884                         ns,
885                         &import.parent_scope,
886                         Some(finalize),
887                         None,
888                     );
889                     if binding.is_ok() {
890                         all_ns_failed = false;
891                     }
892                 }
893             });
894
895             return if all_ns_failed {
896                 let resolutions = match module {
897                     ModuleOrUniformRoot::Module(module) => {
898                         Some(self.r.resolutions(module).borrow())
899                     }
900                     _ => None,
901                 };
902                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
903                 let names = resolutions
904                     .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
905                         if i.name == ident.name {
906                             return None;
907                         } // Never suggest the same name
908                         match *resolution.borrow() {
909                             NameResolution { binding: Some(name_binding), .. } => {
910                                 match name_binding.kind {
911                                     NameBindingKind::Import { binding, .. } => {
912                                         match binding.kind {
913                                             // Never suggest the name that has binding error
914                                             // i.e., the name that cannot be previously resolved
915                                             NameBindingKind::Res(Res::Err) => None,
916                                             _ => Some(i.name),
917                                         }
918                                     }
919                                     _ => Some(i.name),
920                                 }
921                             }
922                             NameResolution { ref single_imports, .. }
923                                 if single_imports.is_empty() =>
924                             {
925                                 None
926                             }
927                             _ => Some(i.name),
928                         }
929                     })
930                     .collect::<Vec<Symbol>>();
931
932                 let lev_suggestion =
933                     find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
934                         (
935                             vec![(ident.span, suggestion.to_string())],
936                             String::from("a similar name exists in the module"),
937                             Applicability::MaybeIncorrect,
938                         )
939                     });
940
941                 let (suggestion, note) =
942                     match self.check_for_module_export_macro(import, module, ident) {
943                         Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
944                         _ => (lev_suggestion, None),
945                     };
946
947                 let label = match module {
948                     ModuleOrUniformRoot::Module(module) => {
949                         let module_str = module_to_string(module);
950                         if let Some(module_str) = module_str {
951                             format!("no `{}` in `{}`", ident, module_str)
952                         } else {
953                             format!("no `{}` in the root", ident)
954                         }
955                     }
956                     _ => {
957                         if !ident.is_path_segment_keyword() {
958                             format!("no external crate `{}`", ident)
959                         } else {
960                             // HACK(eddyb) this shows up for `self` & `super`, which
961                             // should work instead - for now keep the same error message.
962                             format!("no `{}` in the root", ident)
963                         }
964                     }
965                 };
966
967                 let parent_suggestion =
968                     self.r.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
969
970                 Some(UnresolvedImportError {
971                     span: import.span,
972                     label: Some(label),
973                     note,
974                     suggestion,
975                     candidates: if !parent_suggestion.is_empty() {
976                         Some(parent_suggestion)
977                     } else {
978                         None
979                     },
980                 })
981             } else {
982                 // `resolve_ident_in_module` reported a privacy error.
983                 None
984             };
985         }
986
987         let mut reexport_error = None;
988         let mut any_successful_reexport = false;
989         let mut crate_private_reexport = false;
990         self.r.per_ns(|this, ns| {
991             if let Ok(binding) = source_bindings[ns].get() {
992                 if !binding.vis.is_at_least(import.expect_vis(), &*this) {
993                     reexport_error = Some((ns, binding));
994                     if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
995                         if binding_def_id.is_top_level_module() {
996                             crate_private_reexport = true;
997                         }
998                     }
999                 } else {
1000                     any_successful_reexport = true;
1001                 }
1002             }
1003         });
1004
1005         // All namespaces must be re-exported with extra visibility for an error to occur.
1006         if !any_successful_reexport {
1007             let (ns, binding) = reexport_error.unwrap();
1008             if pub_use_of_private_extern_crate_hack(import, binding) {
1009                 let msg = format!(
1010                     "extern crate `{}` is private, and cannot be \
1011                                    re-exported (error E0365), consider declaring with \
1012                                    `pub`",
1013                     ident
1014                 );
1015                 self.r.lint_buffer.buffer_lint(
1016                     PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1017                     import_id,
1018                     import.span,
1019                     &msg,
1020                 );
1021             } else {
1022                 let error_msg = if crate_private_reexport {
1023                     format!(
1024                         "`{}` is only public within the crate, and cannot be re-exported outside",
1025                         ident
1026                     )
1027                 } else {
1028                     format!("`{}` is private, and cannot be re-exported", ident)
1029                 };
1030
1031                 if ns == TypeNS {
1032                     let label_msg = if crate_private_reexport {
1033                         format!("re-export of crate public `{}`", ident)
1034                     } else {
1035                         format!("re-export of private `{}`", ident)
1036                     };
1037
1038                     struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
1039                         .span_label(import.span, label_msg)
1040                         .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1041                         .emit();
1042                 } else {
1043                     let mut err =
1044                         struct_span_err!(self.r.session, import.span, E0364, "{error_msg}");
1045                     match binding.kind {
1046                         NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
1047                             // exclude decl_macro
1048                             if self.r.get_macro_by_def_id(def_id).macro_rules =>
1049                         {
1050                             err.span_help(
1051                                 binding.span,
1052                                 "consider adding a `#[macro_export]` to the macro in the imported module",
1053                             );
1054                         }
1055                         _ => {
1056                             err.span_note(
1057                                 import.span,
1058                                 &format!(
1059                                     "consider marking `{ident}` as `pub` in the imported module"
1060                                 ),
1061                             );
1062                         }
1063                     }
1064                     err.emit();
1065                 }
1066             }
1067         }
1068
1069         if import.module_path.len() <= 1 {
1070             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1071             // 2 segments, so the `resolve_path` above won't trigger it.
1072             let mut full_path = import.module_path.clone();
1073             full_path.push(Segment::from_ident(ident));
1074             self.r.per_ns(|this, ns| {
1075                 if let Ok(binding) = source_bindings[ns].get() {
1076                     this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
1077                 }
1078             });
1079         }
1080
1081         // Record what this import resolves to for later uses in documentation,
1082         // this may resolve to either a value or a type, but for documentation
1083         // purposes it's good enough to just favor one over the other.
1084         self.r.per_ns(|this, ns| {
1085             if let Ok(binding) = source_bindings[ns].get() {
1086                 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1087             }
1088         });
1089
1090         self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
1091
1092         debug!("(resolving single import) successfully resolved import");
1093         None
1094     }
1095
1096     fn check_for_redundant_imports(
1097         &mut self,
1098         ident: Ident,
1099         import: &'b Import<'b>,
1100         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1101         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1102         target: Ident,
1103     ) {
1104         // This function is only called for single imports.
1105         let ImportKind::Single { id, .. } = import.kind else { unreachable!() };
1106
1107         // Skip if the import was produced by a macro.
1108         if import.parent_scope.expansion != LocalExpnId::ROOT {
1109             return;
1110         }
1111
1112         // Skip if we are inside a named module (in contrast to an anonymous
1113         // module defined by a block).
1114         if let ModuleKind::Def(..) = import.parent_scope.module.kind {
1115             return;
1116         }
1117
1118         let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1119
1120         let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1121
1122         self.r.per_ns(|this, ns| {
1123             if let Ok(binding) = source_bindings[ns].get() {
1124                 if binding.res() == Res::Err {
1125                     return;
1126                 }
1127
1128                 match this.early_resolve_ident_in_lexical_scope(
1129                     target,
1130                     ScopeSet::All(ns, false),
1131                     &import.parent_scope,
1132                     None,
1133                     false,
1134                     target_bindings[ns].get(),
1135                 ) {
1136                     Ok(other_binding) => {
1137                         is_redundant[ns] = Some(
1138                             binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1139                         );
1140                         redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1141                     }
1142                     Err(_) => is_redundant[ns] = Some(false),
1143                 }
1144             }
1145         });
1146
1147         if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1148         {
1149             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1150             redundant_spans.sort();
1151             redundant_spans.dedup();
1152             self.r.lint_buffer.buffer_lint_with_diagnostic(
1153                 UNUSED_IMPORTS,
1154                 id,
1155                 import.span,
1156                 &format!("the item `{}` is imported redundantly", ident),
1157                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1158             );
1159         }
1160     }
1161
1162     fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1163         // This function is only called for glob imports.
1164         let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() };
1165
1166         let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1167             self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1168             return;
1169         };
1170
1171         if module.is_trait() {
1172             self.r.session.span_err(import.span, "items in traits are not importable");
1173             return;
1174         } else if ptr::eq(module, import.parent_scope.module) {
1175             return;
1176         } else if is_prelude {
1177             self.r.prelude = Some(module);
1178             return;
1179         }
1180
1181         // Add to module's glob_importers
1182         module.glob_importers.borrow_mut().push(import);
1183
1184         // Ensure that `resolutions` isn't borrowed during `try_define`,
1185         // since it might get updated via a glob cycle.
1186         let bindings = self
1187             .r
1188             .resolutions(module)
1189             .borrow()
1190             .iter()
1191             .filter_map(|(key, resolution)| {
1192                 resolution.borrow().binding().map(|binding| (*key, binding))
1193             })
1194             .collect::<Vec<_>>();
1195         for (mut key, binding) in bindings {
1196             let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1197                 Some(Some(def)) => self.r.expn_def_scope(def),
1198                 Some(None) => import.parent_scope.module,
1199                 None => continue,
1200             };
1201             if self.r.is_accessible_from(binding.vis, scope) {
1202                 let imported_binding = self.r.import(binding, import);
1203                 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1204             }
1205         }
1206
1207         // Record the destination of this import
1208         self.r.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1209     }
1210
1211     // Miscellaneous post-processing, including recording re-exports,
1212     // reporting conflicts, and reporting unresolved imports.
1213     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1214         // Since import resolution is finished, globs will not define any more names.
1215         *module.globs.borrow_mut() = Vec::new();
1216
1217         if let Some(def_id) = module.opt_def_id() {
1218             let mut reexports = Vec::new();
1219
1220             module.for_each_child(self.r, |this, ident, _, binding| {
1221                 if let Some(res) = this.is_reexport(binding) {
1222                     reexports.push(ModChild {
1223                         ident,
1224                         res,
1225                         vis: binding.vis,
1226                         span: binding.span,
1227                         macro_rules: false,
1228                     });
1229                 }
1230             });
1231
1232             if !reexports.is_empty() {
1233                 // Call to `expect_local` should be fine because current
1234                 // code is only called for local modules.
1235                 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1236             }
1237         }
1238     }
1239 }
1240
1241 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1242     let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1243     let global = !names.is_empty() && names[0].name == kw::PathRoot;
1244     if let Some(pos) = pos {
1245         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1246         names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1247     } else {
1248         let names = if global { &names[1..] } else { names };
1249         if names.is_empty() {
1250             import_kind_to_string(import_kind)
1251         } else {
1252             format!(
1253                 "{}::{}",
1254                 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1255                 import_kind_to_string(import_kind),
1256             )
1257         }
1258     }
1259 }
1260
1261 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1262     match import_kind {
1263         ImportKind::Single { source, .. } => source.to_string(),
1264         ImportKind::Glob { .. } => "*".to_string(),
1265         ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1266         ImportKind::MacroUse => "#[macro_use]".to_string(),
1267         ImportKind::MacroExport => "#[macro_export]".to_string(),
1268     }
1269 }