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, DefKind, PartialRes};
16 use rustc_middle::metadata::ModChild;
17 use rustc_middle::span_bug;
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};
31 type Res = def::Res<NodeId>;
33 /// Contains data for specific kinds of imports.
34 #[derive(Clone, Debug)]
35 pub enum ImportKind<'a> {
37 /// `source` in `use prefix::source as target`.
39 /// `target` in `use prefix::source as target`.
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.
47 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
49 /// Additional `NodeId`s allocated to a `ast::UseTree` for automatically generated `use` statement
50 /// (eg. implicit struct constructors)
51 additional_ids: (NodeId, NodeId),
55 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
56 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
59 source: Option<Symbol>,
66 #[derive(Debug, Clone)]
67 pub(crate) struct Import<'a> {
68 pub kind: ImportKind<'a>,
70 /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
72 /// In the case where the `Import` was expanded from a "nested" use tree,
73 /// this id is the ID of the leaf tree. For example:
75 /// ```ignore (pacify the merciless tidy)
76 /// use foo::bar::{a, b}
79 /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
80 /// for `a` in this field.
83 /// The `id` of the "root" use-kind -- this is always the same as
84 /// `id` except in the case of "nested" use trees, in which case
85 /// it will be the `id` of the root use tree. e.g., in the example
86 /// from `id`, this would be the ID of the `use foo::bar`
90 /// Span of the entire use statement.
93 /// Span of the entire use statement with attributes.
94 pub use_span_with_attributes: Span,
96 /// Did the use statement have any attributes?
97 pub has_attributes: bool,
99 /// Span of this use tree.
102 /// Span of the *root* use tree (see `root_id`).
105 pub parent_scope: ParentScope<'a>,
106 pub module_path: Vec<Segment>,
107 /// The resolution of `module_path`.
108 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
109 pub vis: Cell<ty::Visibility>,
110 pub used: Cell<bool>,
113 impl<'a> Import<'a> {
114 pub fn is_glob(&self) -> bool {
115 matches!(self.kind, ImportKind::Glob { .. })
118 pub fn is_nested(&self) -> bool {
120 ImportKind::Single { nested, .. } => nested,
126 /// Records information about the resolution of a name in a namespace of a module.
127 #[derive(Clone, Default, Debug)]
128 pub(crate) struct NameResolution<'a> {
129 /// Single imports that may define the name in the namespace.
130 /// Imports are arena-allocated, so it's ok to use pointers as keys.
131 pub single_imports: FxHashSet<Interned<'a, Import<'a>>>,
132 /// The least shadowable known binding for this name, or None if there are no known bindings.
133 pub binding: Option<&'a NameBinding<'a>>,
134 pub shadowed_glob: Option<&'a NameBinding<'a>>,
137 impl<'a> NameResolution<'a> {
138 // Returns the binding for the name if it is known or None if it not known.
139 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
140 self.binding.and_then(|binding| {
141 if !binding.is_glob_import() || self.single_imports.is_empty() {
149 pub(crate) fn add_single_import(&mut self, import: &'a Import<'a>) {
150 self.single_imports.insert(Interned::new_unchecked(import));
154 // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
155 // are permitted for backward-compatibility under a deprecation lint.
156 fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
157 match (&import.kind, &binding.kind) {
159 ImportKind::Single { .. },
160 NameBindingKind::Import {
161 import: Import { kind: ImportKind::ExternCrate { .. }, .. },
164 ) => import.vis.get().is_public(),
169 impl<'a> Resolver<'a> {
170 // Given a binding and an import that resolves to it,
171 // return the corresponding binding defined by the import.
172 pub(crate) fn import(
174 binding: &'a NameBinding<'a>,
175 import: &'a Import<'a>,
176 ) -> &'a NameBinding<'a> {
177 let vis = if binding.vis.is_at_least(import.vis.get(), self)
178 || pub_use_of_private_extern_crate_hack(import, binding)
185 if let ImportKind::Glob { ref max_vis, .. } = import.kind {
186 if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
191 self.arenas.alloc_name_binding(NameBinding {
192 kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
196 expansion: import.parent_scope.expansion,
200 // Define the name or return the existing binding if there is a collision.
201 pub(crate) fn try_define(
205 binding: &'a NameBinding<'a>,
206 ) -> Result<(), &'a NameBinding<'a>> {
207 let res = binding.res();
208 self.check_reserved_macro_name(key.ident, res);
209 self.set_binding_parent_module(binding, module);
210 self.update_resolution(module, key, |this, resolution| {
211 if let Some(old_binding) = resolution.binding {
213 // Do not override real bindings with `Res::Err`s from error recovery.
216 match (old_binding.is_glob_import(), binding.is_glob_import()) {
218 if res != old_binding.res() {
219 resolution.binding = Some(this.ambiguity(
220 AmbiguityKind::GlobVsGlob,
224 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
225 // We are glob-importing the same item but with greater visibility.
226 resolution.binding = Some(binding);
229 (old_glob @ true, false) | (old_glob @ false, true) => {
230 let (glob_binding, nonglob_binding) =
231 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
232 if glob_binding.res() != nonglob_binding.res()
234 && nonglob_binding.expansion != LocalExpnId::ROOT
236 resolution.binding = Some(this.ambiguity(
237 AmbiguityKind::GlobVsExpanded,
242 resolution.binding = Some(nonglob_binding);
244 resolution.shadowed_glob = Some(glob_binding);
247 return Err(old_binding);
251 resolution.binding = Some(binding);
261 primary_binding: &'a NameBinding<'a>,
262 secondary_binding: &'a NameBinding<'a>,
263 ) -> &'a NameBinding<'a> {
264 self.arenas.alloc_name_binding(NameBinding {
265 ambiguity: Some((secondary_binding, kind)),
266 ..primary_binding.clone()
270 // Use `f` to mutate the resolution of the name in the module.
271 // If the resolution becomes a success, define it in the module's glob importers.
272 fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
274 F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
276 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
277 // during which the resolution might end up getting re-defined via a glob cycle.
279 let resolution = &mut *self.resolution(module, key).borrow_mut();
280 let old_binding = resolution.binding();
282 let t = f(self, resolution);
284 match resolution.binding() {
285 _ if old_binding.is_some() => return t,
287 Some(binding) => match old_binding {
288 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
294 // Define `binding` in `module`s glob importers.
295 for import in module.glob_importers.borrow_mut().iter() {
296 let mut ident = key.ident;
297 let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
298 Some(Some(def)) => self.expn_def_scope(def),
299 Some(None) => import.parent_scope.module,
302 if self.is_accessible_from(binding.vis, scope) {
303 let imported_binding = self.import(binding, import);
304 let key = BindingKey { ident, ..key };
305 let _ = self.try_define(import.parent_scope.module, key, imported_binding);
312 // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed resolution,
313 // also mark such failed imports as used to avoid duplicate diagnostics.
314 fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
315 if let ImportKind::Single { target, ref target_bindings, .. } = import.kind {
316 if target_bindings.iter().any(|binding| binding.get().is_some()) {
317 return; // Has resolution, do not create the dummy binding
319 let dummy_binding = self.dummy_binding;
320 let dummy_binding = self.import(dummy_binding, import);
321 self.per_ns(|this, ns| {
322 let key = this.new_key(target, ns);
323 let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
325 self.record_use(target, dummy_binding, false);
326 } else if import.imported_module.get().is_none() {
327 import.used.set(true);
328 self.used_imports.insert(import.id);
333 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
334 /// import errors within the same use tree into a single diagnostic.
335 #[derive(Debug, Clone)]
336 struct UnresolvedImportError {
338 label: Option<String>,
339 note: Option<String>,
340 suggestion: Option<Suggestion>,
343 pub struct ImportResolver<'a, 'b> {
344 pub r: &'a mut Resolver<'b>,
347 impl<'a, 'b> ImportResolver<'a, 'b> {
350 // This is a fixed-point algorithm. We resolve imports until our efforts
351 // are stymied by an unresolved import; then we bail out of the current
352 // module and continue. We terminate successfully once no more imports
353 // remain or unsuccessfully when no forward progress in resolving imports
356 /// Resolves all imports for the crate. This method performs the fixed-
358 pub fn resolve_imports(&mut self) {
359 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
360 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
361 prev_num_indeterminates = self.r.indeterminate_imports.len();
362 for import in mem::take(&mut self.r.indeterminate_imports) {
363 match self.resolve_import(&import) {
364 true => self.r.determined_imports.push(import),
365 false => self.r.indeterminate_imports.push(import),
371 pub fn finalize_imports(&mut self) {
372 for module in self.r.arenas.local_modules().iter() {
373 self.finalize_resolutions_in(module);
376 let mut seen_spans = FxHashSet::default();
377 let mut errors = vec![];
378 let mut prev_root_id: NodeId = NodeId::from_u32(0);
379 let determined_imports = mem::take(&mut self.r.determined_imports);
380 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
382 for (is_indeterminate, import) in determined_imports
385 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
387 let unresolved_import_error = self.finalize_import(import);
389 // If this import is unresolved then create a dummy import
390 // resolution for it so that later resolve stages won't complain.
391 self.r.import_dummy_binding(import);
393 if let Some(err) = unresolved_import_error {
394 if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
395 if source.name == kw::SelfLower {
396 // Silence `unresolved import` error if E0429 is already emitted
397 if let Err(Determined) = source_bindings.value_ns.get() {
403 if prev_root_id.as_u32() != 0
404 && prev_root_id.as_u32() != import.root_id.as_u32()
405 && !errors.is_empty()
407 // In the case of a new import line, throw a diagnostic message
408 // for the previous line.
409 self.throw_unresolved_import_error(errors, None);
412 if seen_spans.insert(err.span) {
413 let path = import_path_to_string(
414 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
418 errors.push((path, err));
419 prev_root_id = import.root_id;
421 } else if is_indeterminate {
422 let path = import_path_to_string(
423 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
427 let err = UnresolvedImportError {
433 if path.contains("::") {
434 errors.push((path, err))
439 if !errors.is_empty() {
440 self.throw_unresolved_import_error(errors, None);
444 fn throw_unresolved_import_error(
446 errors: Vec<(String, UnresolvedImportError)>,
447 span: Option<MultiSpan>,
449 /// Upper limit on the number of `span_label` messages.
450 const MAX_LABEL_COUNT: usize = 10;
452 let (span, msg) = if errors.is_empty() {
453 (span.unwrap(), "unresolved import".to_string())
455 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
457 let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
459 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
464 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
466 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
470 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
471 if let Some(label) = err.label {
472 diag.span_label(err.span, label);
475 if let Some((suggestions, msg, applicability)) = err.suggestion {
476 if suggestions.is_empty() {
480 diag.multipart_suggestion(&msg, suggestions, applicability);
487 /// Attempts to resolve the given import, returning true if its resolution is determined.
488 /// If successful, the resolved bindings are written into the module.
489 fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
491 "(resolving import for module) resolving import `{}::...` in `{}`",
492 Segment::names_to_string(&import.module_path),
493 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
496 let module = if let Some(module) = import.imported_module.get() {
499 // For better failure detection, pretend that the import will
500 // not define any names while resolving its module path.
501 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
503 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
504 import.vis.set(orig_vis);
507 PathResult::Module(module) => module,
508 PathResult::Indeterminate => return false,
509 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
513 import.imported_module.set(Some(module));
514 let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
522 } => (source, target, source_bindings, target_bindings, type_ns_only),
523 ImportKind::Glob { .. } => {
524 self.resolve_glob_import(import);
530 let mut indeterminate = false;
531 self.r.per_ns(|this, ns| {
532 if !type_ns_only || ns == TypeNS {
533 if let Err(Undetermined) = source_bindings[ns].get() {
534 // For better failure detection, pretend that the import will
535 // not define any names while resolving its module path.
536 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
537 let binding = this.resolve_ident_in_module(
541 &import.parent_scope,
545 import.vis.set(orig_vis);
546 source_bindings[ns].set(binding);
551 let parent = import.parent_scope.module;
552 match source_bindings[ns].get() {
553 Err(Undetermined) => indeterminate = true,
554 // Don't update the resolution, because it was never added.
555 Err(Determined) if target.name == kw::Underscore => {}
556 Ok(binding) if binding.is_importable() => {
557 let imported_binding = this.import(binding, import);
558 target_bindings[ns].set(Some(imported_binding));
559 this.define(parent, target, ns, imported_binding);
561 source_binding @ (Ok(..) | Err(Determined)) => {
562 if source_binding.is_ok() {
563 let msg = format!("`{}` is not directly importable", target);
564 struct_span_err!(this.session, import.span, E0253, "{}", &msg)
565 .span_label(import.span, "cannot be imported directly")
568 let key = this.new_key(target, ns);
569 this.update_resolution(parent, key, |_, resolution| {
570 resolution.single_imports.remove(&Interned::new_unchecked(import));
580 /// Performs final import resolution, consistency checks and error reporting.
582 /// Optionally returns an unresolved import error. This error is buffered and used to
583 /// consolidate multiple unresolved import errors into a single diagnostic.
584 fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
585 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
586 let ignore_binding = match &import.kind {
587 ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
590 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
591 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
592 let path_res = self.r.resolve_path(
595 &import.parent_scope,
599 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
600 import.vis.set(orig_vis);
601 let module = match path_res {
602 PathResult::Module(module) => {
603 // Consistency checks, analogous to `finalize_macro_resolutions`.
604 if let Some(initial_module) = import.imported_module.get() {
605 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
606 span_bug!(import.span, "inconsistent resolution for an import");
608 } else if self.r.privacy_errors.is_empty() {
609 let msg = "cannot determine resolution for the import";
610 let msg_note = "import resolution is stuck, try simplifying other imports";
611 self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
616 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
618 assert!(import.imported_module.get().is_none());
620 .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
624 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
626 assert!(import.imported_module.get().is_none());
627 let err = match self.make_path_suggestion(
629 import.module_path.clone(),
630 &import.parent_scope,
632 Some((suggestion, note)) => UnresolvedImportError {
637 vec![(span, Segment::names_to_string(&suggestion))],
638 String::from("a similar path exists"),
639 Applicability::MaybeIncorrect,
642 None => UnresolvedImportError {
653 PathResult::NonModule(_) => {
655 assert!(import.imported_module.get().is_none());
657 // The error was already reported earlier.
660 PathResult::Indeterminate => unreachable!(),
663 let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
671 } => (source, target, source_bindings, target_bindings, type_ns_only),
672 ImportKind::Glob { is_prelude, ref max_vis } => {
673 if import.module_path.len() <= 1 {
674 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
675 // 2 segments, so the `resolve_path` above won't trigger it.
676 let mut full_path = import.module_path.clone();
677 full_path.push(Segment::from_ident(Ident::empty()));
678 self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
681 if let ModuleOrUniformRoot::Module(module) = module {
682 if ptr::eq(module, import.parent_scope.module) {
683 // Importing a module into itself is not allowed.
684 return Some(UnresolvedImportError {
686 label: Some(String::from("cannot glob-import a module into itself")),
693 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
694 !max_vis.get().is_at_least(import.vis.get(), &*self.r)
696 let msg = "glob import doesn't reexport anything because no candidate is public enough";
697 self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
704 let mut all_ns_err = true;
705 self.r.per_ns(|this, ns| {
706 if !type_ns_only || ns == TypeNS {
707 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
708 let binding = this.resolve_ident_in_module(
712 &import.parent_scope,
713 Some(Finalize { report_private: false, ..finalize }),
714 target_bindings[ns].get(),
716 import.vis.set(orig_vis);
720 // Consistency checks, analogous to `finalize_macro_resolutions`.
721 let initial_res = source_bindings[ns].get().map(|initial_binding| {
723 if let Some(target_binding) = target_bindings[ns].get() {
724 if target.name == kw::Underscore
725 && initial_binding.is_extern_crate()
726 && !initial_binding.is_import()
731 import.module_path.is_empty(),
735 initial_binding.res()
737 let res = binding.res();
738 if let Ok(initial_res) = initial_res {
739 if res != initial_res && this.ambiguity_errors.is_empty() {
740 span_bug!(import.span, "inconsistent resolution for an import");
742 } else if res != Res::Err
743 && this.ambiguity_errors.is_empty()
744 && this.privacy_errors.is_empty()
746 let msg = "cannot determine resolution for the import";
748 "import resolution is stuck, try simplifying other imports";
749 this.session.struct_span_err(import.span, msg).note(msg_note).emit();
753 // FIXME: This assert may fire if public glob is later shadowed by a private
754 // single import (see test `issue-55884-2.rs`). In theory single imports should
755 // always block globs, even if they are not yet resolved, so that this kind of
756 // self-inconsistent resolution never happens.
757 // Re-enable the assert when the issue is fixed.
758 // assert!(result[ns].get().is_err());
765 let mut all_ns_failed = true;
766 self.r.per_ns(|this, ns| {
767 if !type_ns_only || ns == TypeNS {
768 let binding = this.resolve_ident_in_module(
772 &import.parent_scope,
777 all_ns_failed = false;
782 return if all_ns_failed {
783 let resolutions = match module {
784 ModuleOrUniformRoot::Module(module) => {
785 Some(self.r.resolutions(module).borrow())
789 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
790 let names = resolutions
791 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
794 } // Never suggest the same name
795 match *resolution.borrow() {
796 NameResolution { binding: Some(name_binding), .. } => {
797 match name_binding.kind {
798 NameBindingKind::Import { binding, .. } => {
800 // Never suggest the name that has binding error
801 // i.e., the name that cannot be previously resolved
802 NameBindingKind::Res(Res::Err, _) => None,
809 NameResolution { ref single_imports, .. }
810 if single_imports.is_empty() =>
817 .collect::<Vec<Symbol>>();
820 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
822 vec![(ident.span, suggestion.to_string())],
823 String::from("a similar name exists in the module"),
824 Applicability::MaybeIncorrect,
828 let (suggestion, note) =
829 match self.check_for_module_export_macro(import, module, ident) {
830 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
831 _ => (lev_suggestion, None),
834 let label = match module {
835 ModuleOrUniformRoot::Module(module) => {
836 let module_str = module_to_string(module);
837 if let Some(module_str) = module_str {
838 format!("no `{}` in `{}`", ident, module_str)
840 format!("no `{}` in the root", ident)
844 if !ident.is_path_segment_keyword() {
845 format!("no external crate `{}`", ident)
847 // HACK(eddyb) this shows up for `self` & `super`, which
848 // should work instead - for now keep the same error message.
849 format!("no `{}` in the root", ident)
854 Some(UnresolvedImportError {
861 // `resolve_ident_in_module` reported a privacy error.
866 let mut reexport_error = None;
867 let mut any_successful_reexport = false;
868 let mut crate_private_reexport = false;
869 self.r.per_ns(|this, ns| {
870 if let Ok(binding) = source_bindings[ns].get() {
871 let vis = import.vis.get();
872 if !binding.vis.is_at_least(vis, &*this) {
873 reexport_error = Some((ns, binding));
874 if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
875 if binding_def_id.is_top_level_module() {
876 crate_private_reexport = true;
880 any_successful_reexport = true;
885 // All namespaces must be re-exported with extra visibility for an error to occur.
886 if !any_successful_reexport {
887 let (ns, binding) = reexport_error.unwrap();
888 if pub_use_of_private_extern_crate_hack(import, binding) {
890 "extern crate `{}` is private, and cannot be \
891 re-exported (error E0365), consider declaring with \
895 self.r.lint_buffer.buffer_lint(
896 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
902 let error_msg = if crate_private_reexport {
904 "`{}` is only public within the crate, and cannot be re-exported outside",
908 format!("`{}` is private, and cannot be re-exported", ident)
912 let label_msg = if crate_private_reexport {
913 format!("re-export of crate public `{}`", ident)
915 format!("re-export of private `{}`", ident)
918 struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
919 .span_label(import.span, label_msg)
920 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
924 struct_span_err!(self.r.session, import.span, E0364, "{error_msg}");
926 NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id), _)
927 // exclude decl_macro
928 if self.r.get_macro_by_def_id(def_id).macro_rules =>
932 "consider adding a `#[macro_export]` to the macro in the imported module",
939 "consider marking `{ident}` as `pub` in the imported module"
949 if import.module_path.len() <= 1 {
950 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
951 // 2 segments, so the `resolve_path` above won't trigger it.
952 let mut full_path = import.module_path.clone();
953 full_path.push(Segment::from_ident(ident));
954 self.r.per_ns(|this, ns| {
955 if let Ok(binding) = source_bindings[ns].get() {
956 this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
961 // Record what this import resolves to for later uses in documentation,
962 // this may resolve to either a value or a type, but for documentation
963 // purposes it's good enough to just favor one over the other.
964 self.r.per_ns(|this, ns| {
965 if let Ok(binding) = source_bindings[ns].get() {
966 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
970 self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
972 debug!("(resolving single import) successfully resolved import");
976 fn check_for_redundant_imports(
979 import: &'b Import<'b>,
980 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
981 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
984 // Skip if the import was produced by a macro.
985 if import.parent_scope.expansion != LocalExpnId::ROOT {
989 // Skip if we are inside a named module (in contrast to an anonymous
990 // module defined by a block).
991 if let ModuleKind::Def(..) = import.parent_scope.module.kind {
995 let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
997 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
999 self.r.per_ns(|this, ns| {
1000 if let Ok(binding) = source_bindings[ns].get() {
1001 if binding.res() == Res::Err {
1005 match this.early_resolve_ident_in_lexical_scope(
1007 ScopeSet::All(ns, false),
1008 &import.parent_scope,
1011 target_bindings[ns].get(),
1013 Ok(other_binding) => {
1014 is_redundant[ns] = Some(
1015 binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1017 redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1019 Err(_) => is_redundant[ns] = Some(false),
1024 if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1026 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1027 redundant_spans.sort();
1028 redundant_spans.dedup();
1029 self.r.lint_buffer.buffer_lint_with_diagnostic(
1033 &format!("the item `{}` is imported redundantly", ident),
1034 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1039 fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1040 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1041 self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1045 if module.is_trait() {
1046 self.r.session.span_err(import.span, "items in traits are not importable");
1048 } else if ptr::eq(module, import.parent_scope.module) {
1050 } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1051 self.r.prelude = Some(module);
1055 // Add to module's glob_importers
1056 module.glob_importers.borrow_mut().push(import);
1058 // Ensure that `resolutions` isn't borrowed during `try_define`,
1059 // since it might get updated via a glob cycle.
1062 .resolutions(module)
1065 .filter_map(|(key, resolution)| {
1066 resolution.borrow().binding().map(|binding| (*key, binding))
1068 .collect::<Vec<_>>();
1069 for (mut key, binding) in bindings {
1070 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1071 Some(Some(def)) => self.r.expn_def_scope(def),
1072 Some(None) => import.parent_scope.module,
1075 if self.r.is_accessible_from(binding.vis, scope) {
1076 let imported_binding = self.r.import(binding, import);
1077 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1081 // Record the destination of this import
1082 self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1085 // Miscellaneous post-processing, including recording re-exports,
1086 // reporting conflicts, and reporting unresolved imports.
1087 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1088 // Since import resolution is finished, globs will not define any more names.
1089 *module.globs.borrow_mut() = Vec::new();
1091 if let Some(def_id) = module.opt_def_id() {
1092 let mut reexports = Vec::new();
1094 module.for_each_child(self.r, |_, ident, _, binding| {
1095 // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1096 // into the crate root to actual `NameBindingKind::Import`.
1097 if binding.is_import()
1098 || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
1100 let res = binding.res().expect_non_local();
1101 // Ambiguous imports are treated as errors at this point and are
1102 // not exposed to other crates (see #36837 for more details).
1103 if res != def::Res::Err && !binding.is_ambiguity() {
1104 reexports.push(ModChild {
1115 if !reexports.is_empty() {
1116 // Call to `expect_local` should be fine because current
1117 // code is only called for local modules.
1118 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1124 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1125 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1126 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1127 if let Some(pos) = pos {
1128 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1129 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1131 let names = if global { &names[1..] } else { names };
1132 if names.is_empty() {
1133 import_kind_to_string(import_kind)
1137 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1138 import_kind_to_string(import_kind),
1144 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1146 ImportKind::Single { source, .. } => source.to_string(),
1147 ImportKind::Glob { .. } => "*".to_string(),
1148 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1149 ImportKind::MacroUse => "#[macro_use]".to_string(),