1 //! A bunch of methods and structures more or less related to resolving imports.
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};
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, PartialRes};
16 use rustc_hir::def_id::DefId;
17 use rustc_middle::metadata::ModChild;
18 use rustc_middle::span_bug;
20 use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
21 use rustc_session::lint::BuiltinLintDiagnostics;
22 use rustc_span::hygiene::LocalExpnId;
23 use rustc_span::lev_distance::find_best_match_for_name;
24 use rustc_span::symbol::{kw, Ident, Symbol};
32 type Res = def::Res<NodeId>;
34 /// Contains data for specific kinds of imports.
35 #[derive(Clone, Debug)]
36 pub enum ImportKind<'a> {
38 /// `source` in `use prefix::source as target`.
40 /// `target` in `use prefix::source as target`.
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.
48 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
50 /// Additional `NodeId`s allocated to a `ast::UseTree` for automatically generated `use` statement
51 /// (eg. implicit struct constructors)
52 additional_ids: (NodeId, NodeId),
56 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
57 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
60 source: Option<Symbol>,
67 #[derive(Debug, Clone)]
68 crate struct Import<'a> {
69 pub kind: ImportKind<'a>,
71 /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
73 /// In the case where the `Import` was expanded from a "nested" use tree,
74 /// this id is the ID of the leaf tree. For example:
76 /// ```ignore (pacify the merciless tidy)
77 /// use foo::bar::{a, b}
80 /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
81 /// for `a` in this field.
84 /// The `id` of the "root" use-kind -- this is always the same as
85 /// `id` except in the case of "nested" use trees, in which case
86 /// it will be the `id` of the root use tree. e.g., in the example
87 /// from `id`, this would be the ID of the `use foo::bar`
91 /// Span of the entire use statement.
94 /// Span of the entire use statement with attributes.
95 pub use_span_with_attributes: Span,
97 /// Did the use statement have any attributes?
98 pub has_attributes: bool,
100 /// Span of this use tree.
103 /// Span of the *root* use tree (see `root_id`).
106 pub parent_scope: ParentScope<'a>,
107 pub module_path: Vec<Segment>,
108 /// The resolution of `module_path`.
109 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
110 pub vis: Cell<ty::Visibility>,
111 pub used: Cell<bool>,
114 impl<'a> Import<'a> {
115 pub fn is_glob(&self) -> bool {
116 matches!(self.kind, ImportKind::Glob { .. })
119 pub fn is_nested(&self) -> bool {
121 ImportKind::Single { nested, .. } => nested,
127 /// Records information about the resolution of a name in a namespace of a module.
128 #[derive(Clone, Default, Debug)]
129 crate struct NameResolution<'a> {
130 /// Single imports that may define the name in the namespace.
131 /// Imports are arena-allocated, so it's ok to use pointers as keys.
132 pub single_imports: FxHashSet<Interned<'a, Import<'a>>>,
133 /// The least shadowable known binding for this name, or None if there are no known bindings.
134 pub binding: Option<&'a NameBinding<'a>>,
135 pub shadowed_glob: Option<&'a NameBinding<'a>>,
138 impl<'a> NameResolution<'a> {
139 // Returns the binding for the name if it is known or None if it not known.
140 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
141 self.binding.and_then(|binding| {
142 if !binding.is_glob_import() || self.single_imports.is_empty() {
150 crate fn add_single_import(&mut self, import: &'a Import<'a>) {
151 self.single_imports.insert(Interned::new_unchecked(import));
155 // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
156 // are permitted for backward-compatibility under a deprecation lint.
157 fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
158 match (&import.kind, &binding.kind) {
160 ImportKind::Single { .. },
161 NameBindingKind::Import {
162 import: Import { kind: ImportKind::ExternCrate { .. }, .. },
165 ) => import.vis.get().is_public(),
170 impl<'a> Resolver<'a> {
171 // Given a binding and an import that resolves to it,
172 // return the corresponding binding defined by the import.
175 binding: &'a NameBinding<'a>,
176 import: &'a Import<'a>,
177 ) -> &'a NameBinding<'a> {
178 let vis = if binding.vis.is_at_least(import.vis.get(), self)
179 || pub_use_of_private_extern_crate_hack(import, binding)
186 if let ImportKind::Glob { ref max_vis, .. } = import.kind {
187 if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
192 self.arenas.alloc_name_binding(NameBinding {
193 kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
197 expansion: import.parent_scope.expansion,
201 // Define the name or return the existing binding if there is a collision.
206 binding: &'a NameBinding<'a>,
207 ) -> Result<(), &'a NameBinding<'a>> {
208 let res = binding.res();
209 self.check_reserved_macro_name(key.ident, res);
210 self.set_binding_parent_module(binding, module);
211 self.update_resolution(module, key, |this, resolution| {
212 if let Some(old_binding) = resolution.binding {
214 // Do not override real bindings with `Res::Err`s from error recovery.
217 match (old_binding.is_glob_import(), binding.is_glob_import()) {
219 if res != old_binding.res() {
220 resolution.binding = Some(this.ambiguity(
221 AmbiguityKind::GlobVsGlob,
225 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
226 // We are glob-importing the same item but with greater visibility.
227 resolution.binding = Some(binding);
230 (old_glob @ true, false) | (old_glob @ false, true) => {
231 let (glob_binding, nonglob_binding) =
232 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
233 if glob_binding.res() != nonglob_binding.res()
235 && nonglob_binding.expansion != LocalExpnId::ROOT
237 resolution.binding = Some(this.ambiguity(
238 AmbiguityKind::GlobVsExpanded,
243 resolution.binding = Some(nonglob_binding);
245 resolution.shadowed_glob = Some(glob_binding);
248 return Err(old_binding);
252 resolution.binding = Some(binding);
262 primary_binding: &'a NameBinding<'a>,
263 secondary_binding: &'a NameBinding<'a>,
264 ) -> &'a NameBinding<'a> {
265 self.arenas.alloc_name_binding(NameBinding {
266 ambiguity: Some((secondary_binding, kind)),
267 ..primary_binding.clone()
271 // Use `f` to mutate the resolution of the name in the module.
272 // If the resolution becomes a success, define it in the module's glob importers.
273 fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
275 F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
277 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
278 // during which the resolution might end up getting re-defined via a glob cycle.
280 let resolution = &mut *self.resolution(module, key).borrow_mut();
281 let old_binding = resolution.binding();
283 let t = f(self, resolution);
285 match resolution.binding() {
286 _ if old_binding.is_some() => return t,
288 Some(binding) => match old_binding {
289 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
295 // Define `binding` in `module`s glob importers.
296 for import in module.glob_importers.borrow_mut().iter() {
297 let mut ident = key.ident;
298 let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
299 Some(Some(def)) => self.expn_def_scope(def),
300 Some(None) => import.parent_scope.module,
303 if self.is_accessible_from(binding.vis, scope) {
304 let imported_binding = self.import(binding, import);
305 let key = BindingKey { ident, ..key };
306 let _ = self.try_define(import.parent_scope.module, key, imported_binding);
313 // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed resolution,
314 // also mark such failed imports as used to avoid duplicate diagnostics.
315 fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
316 if let ImportKind::Single { target, ref target_bindings, .. } = import.kind {
317 if target_bindings.iter().any(|binding| binding.get().is_some()) {
318 return; // Has resolution, do not create the dummy binding
320 let dummy_binding = self.dummy_binding;
321 let dummy_binding = self.import(dummy_binding, import);
322 self.per_ns(|this, ns| {
323 let key = this.new_key(target, ns);
324 let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
326 self.record_use(target, dummy_binding, false);
327 } else if import.imported_module.get().is_none() {
328 import.used.set(true);
329 self.used_imports.insert(import.id);
334 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
335 /// import errors within the same use tree into a single diagnostic.
336 #[derive(Debug, Clone)]
337 struct UnresolvedImportError {
339 label: Option<String>,
341 suggestion: Option<Suggestion>,
344 pub struct ImportResolver<'a, 'b> {
345 pub r: &'a mut Resolver<'b>,
348 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
349 fn parent(self, id: DefId) -> Option<DefId> {
354 impl<'a, 'b> ImportResolver<'a, 'b> {
357 // This is a fixed-point algorithm. We resolve imports until our efforts
358 // are stymied by an unresolved import; then we bail out of the current
359 // module and continue. We terminate successfully once no more imports
360 // remain or unsuccessfully when no forward progress in resolving imports
363 /// Resolves all imports for the crate. This method performs the fixed-
365 pub fn resolve_imports(&mut self) {
366 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
367 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
368 prev_num_indeterminates = self.r.indeterminate_imports.len();
369 for import in mem::take(&mut self.r.indeterminate_imports) {
370 match self.resolve_import(&import) {
371 true => self.r.determined_imports.push(import),
372 false => self.r.indeterminate_imports.push(import),
378 pub fn finalize_imports(&mut self) {
379 for module in self.r.arenas.local_modules().iter() {
380 self.finalize_resolutions_in(module);
383 let mut seen_spans = FxHashSet::default();
384 let mut errors = vec![];
385 let mut prev_root_id: NodeId = NodeId::from_u32(0);
386 let determined_imports = mem::take(&mut self.r.determined_imports);
387 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
389 for (is_indeterminate, import) in determined_imports
392 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
394 let unresolved_import_error = self.finalize_import(import);
396 // If this import is unresolved then create a dummy import
397 // resolution for it so that later resolve stages won't complain.
398 self.r.import_dummy_binding(import);
400 if let Some(err) = unresolved_import_error {
401 if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
402 if source.name == kw::SelfLower {
403 // Silence `unresolved import` error if E0429 is already emitted
404 if let Err(Determined) = source_bindings.value_ns.get() {
410 if prev_root_id.as_u32() != 0
411 && prev_root_id.as_u32() != import.root_id.as_u32()
412 && !errors.is_empty()
414 // In the case of a new import line, throw a diagnostic message
415 // for the previous line.
416 self.throw_unresolved_import_error(errors, None);
419 if seen_spans.insert(err.span) {
420 let path = import_path_to_string(
421 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
425 errors.push((path, err));
426 prev_root_id = import.root_id;
428 } else if is_indeterminate {
429 let path = import_path_to_string(
430 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
434 let err = UnresolvedImportError {
440 if path.contains("::") {
441 errors.push((path, err))
446 if !errors.is_empty() {
447 self.throw_unresolved_import_error(errors, None);
451 fn throw_unresolved_import_error(
453 errors: Vec<(String, UnresolvedImportError)>,
454 span: Option<MultiSpan>,
456 /// Upper limit on the number of `span_label` messages.
457 const MAX_LABEL_COUNT: usize = 10;
459 let (span, msg) = if errors.is_empty() {
460 (span.unwrap(), "unresolved import".to_string())
462 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
464 let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
466 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
471 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
473 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
474 for message in note {
479 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
480 if let Some(label) = err.label {
481 diag.span_label(err.span, label);
484 if let Some((suggestions, msg, applicability)) = err.suggestion {
485 diag.multipart_suggestion(&msg, suggestions, applicability);
492 /// Attempts to resolve the given import, returning true if its resolution is determined.
493 /// If successful, the resolved bindings are written into the module.
494 fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
496 "(resolving import for module) resolving import `{}::...` in `{}`",
497 Segment::names_to_string(&import.module_path),
498 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
501 let module = if let Some(module) = import.imported_module.get() {
504 // For better failure detection, pretend that the import will
505 // not define any names while resolving its module path.
506 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
508 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
509 import.vis.set(orig_vis);
512 PathResult::Module(module) => module,
513 PathResult::Indeterminate => return false,
514 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
518 import.imported_module.set(Some(module));
519 let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
527 } => (source, target, source_bindings, target_bindings, type_ns_only),
528 ImportKind::Glob { .. } => {
529 self.resolve_glob_import(import);
535 let mut indeterminate = false;
536 self.r.per_ns(|this, ns| {
537 if !type_ns_only || ns == TypeNS {
538 if let Err(Undetermined) = source_bindings[ns].get() {
539 // For better failure detection, pretend that the import will
540 // not define any names while resolving its module path.
541 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
542 let binding = this.resolve_ident_in_module(
546 &import.parent_scope,
551 import.vis.set(orig_vis);
552 source_bindings[ns].set(binding);
557 let parent = import.parent_scope.module;
558 match source_bindings[ns].get() {
559 Err(Undetermined) => indeterminate = true,
560 // Don't update the resolution, because it was never added.
561 Err(Determined) if target.name == kw::Underscore => {}
562 Ok(binding) if binding.is_importable() => {
563 let imported_binding = this.import(binding, import);
564 target_bindings[ns].set(Some(imported_binding));
565 this.define(parent, target, ns, imported_binding);
567 source_binding @ (Ok(..) | Err(Determined)) => {
568 if source_binding.is_ok() {
569 let msg = format!("`{}` is not directly importable", target);
570 struct_span_err!(this.session, import.span, E0253, "{}", &msg)
571 .span_label(import.span, "cannot be imported directly")
574 let key = this.new_key(target, ns);
575 this.update_resolution(parent, key, |_, resolution| {
576 resolution.single_imports.remove(&Interned::new_unchecked(import));
586 /// Performs final import resolution, consistency checks and error reporting.
588 /// Optionally returns an unresolved import error. This error is buffered and used to
589 /// consolidate multiple unresolved import errors into a single diagnostic.
590 fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
591 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
592 let unusable_binding = match &import.kind {
593 ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
596 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
597 let finalize = Finalize::UsePath {
598 root_id: import.root_id,
599 root_span: import.root_span,
600 path_span: import.span,
602 let path_res = self.r.resolve_path(
605 &import.parent_scope,
609 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
610 import.vis.set(orig_vis);
611 let module = match path_res {
612 PathResult::Module(module) => {
613 // Consistency checks, analogous to `finalize_macro_resolutions`.
614 if let Some(initial_module) = import.imported_module.get() {
615 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
616 span_bug!(import.span, "inconsistent resolution for an import");
618 } else if self.r.privacy_errors.is_empty() {
619 let msg = "cannot determine resolution for the import";
620 let msg_note = "import resolution is stuck, try simplifying other imports";
621 self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
626 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
628 assert!(import.imported_module.get().is_none());
630 .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
634 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
636 assert!(import.imported_module.get().is_none());
637 let err = match self.make_path_suggestion(
639 import.module_path.clone(),
640 &import.parent_scope,
642 Some((suggestion, note)) => UnresolvedImportError {
647 vec![(span, Segment::names_to_string(&suggestion))],
648 String::from("a similar path exists"),
649 Applicability::MaybeIncorrect,
652 None => UnresolvedImportError {
663 PathResult::NonModule(_) => {
665 assert!(import.imported_module.get().is_none());
667 // The error was already reported earlier.
670 PathResult::Indeterminate => unreachable!(),
673 let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
681 } => (source, target, source_bindings, target_bindings, type_ns_only),
682 ImportKind::Glob { is_prelude, ref max_vis } => {
683 if import.module_path.len() <= 1 {
684 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
685 // 2 segments, so the `resolve_path` above won't trigger it.
686 let mut full_path = import.module_path.clone();
687 full_path.push(Segment::from_ident(Ident::empty()));
688 self.r.lint_if_path_starts_with_module(finalize, &full_path, None);
691 if let ModuleOrUniformRoot::Module(module) = module {
692 if ptr::eq(module, import.parent_scope.module) {
693 // Importing a module into itself is not allowed.
694 return Some(UnresolvedImportError {
696 label: Some(String::from("cannot glob-import a module into itself")),
703 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
704 !max_vis.get().is_at_least(import.vis.get(), &*self)
706 let msg = "glob import doesn't reexport anything because no candidate is public enough";
707 self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
714 let mut all_ns_err = true;
715 self.r.per_ns(|this, ns| {
716 if !type_ns_only || ns == TypeNS {
717 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
718 let binding = this.resolve_ident_in_module(
722 &import.parent_scope,
725 target_bindings[ns].get(),
727 import.vis.set(orig_vis);
731 // Consistency checks, analogous to `finalize_macro_resolutions`.
732 let initial_res = source_bindings[ns].get().map(|initial_binding| {
734 if let Some(target_binding) = target_bindings[ns].get() {
735 if target.name == kw::Underscore
736 && initial_binding.is_extern_crate()
737 && !initial_binding.is_import()
742 import.module_path.is_empty(),
746 initial_binding.res()
748 let res = binding.res();
749 if let Ok(initial_res) = initial_res {
750 if res != initial_res && this.ambiguity_errors.is_empty() {
751 span_bug!(import.span, "inconsistent resolution for an import");
753 } else if res != Res::Err
754 && this.ambiguity_errors.is_empty()
755 && this.privacy_errors.is_empty()
757 let msg = "cannot determine resolution for the import";
759 "import resolution is stuck, try simplifying other imports";
760 this.session.struct_span_err(import.span, msg).note(msg_note).emit();
764 // FIXME: This assert may fire if public glob is later shadowed by a private
765 // single import (see test `issue-55884-2.rs`). In theory single imports should
766 // always block globs, even if they are not yet resolved, so that this kind of
767 // self-inconsistent resolution never happens.
768 // Re-enable the assert when the issue is fixed.
769 // assert!(result[ns].get().is_err());
776 let mut all_ns_failed = true;
777 self.r.per_ns(|this, ns| {
778 if !type_ns_only || ns == TypeNS {
779 let binding = this.resolve_ident_in_module(
783 &import.parent_scope,
789 all_ns_failed = false;
794 return if all_ns_failed {
795 let resolutions = match module {
796 ModuleOrUniformRoot::Module(module) => {
797 Some(self.r.resolutions(module).borrow())
801 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
802 let names = resolutions
803 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
806 } // Never suggest the same name
807 match *resolution.borrow() {
808 NameResolution { binding: Some(name_binding), .. } => {
809 match name_binding.kind {
810 NameBindingKind::Import { binding, .. } => {
812 // Never suggest the name that has binding error
813 // i.e., the name that cannot be previously resolved
814 NameBindingKind::Res(Res::Err, _) => None,
821 NameResolution { ref single_imports, .. }
822 if single_imports.is_empty() =>
829 .collect::<Vec<Symbol>>();
832 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
834 vec![(ident.span, suggestion.to_string())],
835 String::from("a similar name exists in the module"),
836 Applicability::MaybeIncorrect,
840 let (suggestion, note) =
841 match self.check_for_module_export_macro(import, module, ident) {
842 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
843 _ => (lev_suggestion, Vec::new()),
846 let label = match module {
847 ModuleOrUniformRoot::Module(module) => {
848 let module_str = module_to_string(module);
849 if let Some(module_str) = module_str {
850 format!("no `{}` in `{}`", ident, module_str)
852 format!("no `{}` in the root", ident)
856 if !ident.is_path_segment_keyword() {
857 format!("no external crate `{}`", ident)
859 // HACK(eddyb) this shows up for `self` & `super`, which
860 // should work instead - for now keep the same error message.
861 format!("no `{}` in the root", ident)
866 Some(UnresolvedImportError {
873 // `resolve_ident_in_module` reported a privacy error.
878 let mut reexport_error = None;
879 let mut any_successful_reexport = false;
880 let mut crate_private_reexport = false;
881 self.r.per_ns(|this, ns| {
882 if let Ok(binding) = source_bindings[ns].get() {
883 let vis = import.vis.get();
884 if !binding.vis.is_at_least(vis, &*this) {
885 reexport_error = Some((ns, binding));
886 if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
887 if binding_def_id.is_top_level_module() {
888 crate_private_reexport = true;
892 any_successful_reexport = true;
897 // All namespaces must be re-exported with extra visibility for an error to occur.
898 if !any_successful_reexport {
899 let (ns, binding) = reexport_error.unwrap();
900 if pub_use_of_private_extern_crate_hack(import, binding) {
902 "extern crate `{}` is private, and cannot be \
903 re-exported (error E0365), consider declaring with \
907 self.r.lint_buffer.buffer_lint(
908 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
914 let error_msg = if crate_private_reexport {
916 "`{}` is only public within the crate, and cannot be re-exported outside",
920 format!("`{}` is private, and cannot be re-exported", ident)
924 let label_msg = if crate_private_reexport {
925 format!("re-export of crate public `{}`", ident)
927 format!("re-export of private `{}`", ident)
930 struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
931 .span_label(import.span, label_msg)
932 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
936 format!("consider marking `{}` as `pub` in the imported module", ident);
937 struct_span_err!(self.r.session, import.span, E0364, "{}", error_msg)
938 .span_note(import.span, ¬e_msg)
944 if import.module_path.len() <= 1 {
945 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
946 // 2 segments, so the `resolve_path` above won't trigger it.
947 let mut full_path = import.module_path.clone();
948 full_path.push(Segment::from_ident(ident));
949 self.r.per_ns(|this, ns| {
950 if let Ok(binding) = source_bindings[ns].get() {
951 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
956 // Record what this import resolves to for later uses in documentation,
957 // this may resolve to either a value or a type, but for documentation
958 // purposes it's good enough to just favor one over the other.
959 self.r.per_ns(|this, ns| {
960 if let Ok(binding) = source_bindings[ns].get() {
961 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
965 self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
967 debug!("(resolving single import) successfully resolved import");
971 fn check_for_redundant_imports(
974 import: &'b Import<'b>,
975 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
976 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
979 // Skip if the import was produced by a macro.
980 if import.parent_scope.expansion != LocalExpnId::ROOT {
984 // Skip if we are inside a named module (in contrast to an anonymous
985 // module defined by a block).
986 if let ModuleKind::Def(..) = import.parent_scope.module.kind {
990 let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
992 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
994 self.r.per_ns(|this, ns| {
995 if let Ok(binding) = source_bindings[ns].get() {
996 if binding.res() == Res::Err {
1000 match this.early_resolve_ident_in_lexical_scope(
1002 ScopeSet::All(ns, false),
1003 &import.parent_scope,
1007 target_bindings[ns].get(),
1009 Ok(other_binding) => {
1010 is_redundant[ns] = Some(
1011 binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1013 redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1015 Err(_) => is_redundant[ns] = Some(false),
1020 if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1022 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1023 redundant_spans.sort();
1024 redundant_spans.dedup();
1025 self.r.lint_buffer.buffer_lint_with_diagnostic(
1029 &format!("the item `{}` is imported redundantly", ident),
1030 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1035 fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1036 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1037 self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1041 if module.is_trait() {
1042 self.r.session.span_err(import.span, "items in traits are not importable");
1044 } else if ptr::eq(module, import.parent_scope.module) {
1046 } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1047 self.r.prelude = Some(module);
1051 // Add to module's glob_importers
1052 module.glob_importers.borrow_mut().push(import);
1054 // Ensure that `resolutions` isn't borrowed during `try_define`,
1055 // since it might get updated via a glob cycle.
1058 .resolutions(module)
1061 .filter_map(|(key, resolution)| {
1062 resolution.borrow().binding().map(|binding| (*key, binding))
1064 .collect::<Vec<_>>();
1065 for (mut key, binding) in bindings {
1066 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1067 Some(Some(def)) => self.r.expn_def_scope(def),
1068 Some(None) => import.parent_scope.module,
1071 if self.r.is_accessible_from(binding.vis, scope) {
1072 let imported_binding = self.r.import(binding, import);
1073 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1077 // Record the destination of this import
1078 self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1081 // Miscellaneous post-processing, including recording re-exports,
1082 // reporting conflicts, and reporting unresolved imports.
1083 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1084 // Since import resolution is finished, globs will not define any more names.
1085 *module.globs.borrow_mut() = Vec::new();
1087 let mut reexports = Vec::new();
1089 module.for_each_child(self.r, |_, ident, _, binding| {
1090 // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1091 // into the crate root to actual `NameBindingKind::Import`.
1092 if binding.is_import()
1093 || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
1095 let res = binding.res().expect_non_local();
1096 // Ambiguous imports are treated as errors at this point and are
1097 // not exposed to other crates (see #36837 for more details).
1098 if res != def::Res::Err && !binding.is_ambiguity() {
1099 reexports.push(ModChild {
1110 if !reexports.is_empty() {
1111 if let Some(def_id) = module.opt_def_id() {
1112 // Call to `expect_local` should be fine because current
1113 // code is only called for local modules.
1114 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1120 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1121 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1122 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1123 if let Some(pos) = pos {
1124 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1125 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1127 let names = if global { &names[1..] } else { names };
1128 if names.is_empty() {
1129 import_kind_to_string(import_kind)
1133 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1134 import_kind_to_string(import_kind),
1140 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1142 ImportKind::Single { source, .. } => source.to_string(),
1143 ImportKind::Glob { .. } => "*".to_string(),
1144 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1145 ImportKind::MacroUse => "#[macro_use]".to_string(),