1 use ImportDirectiveSubclass::*;
3 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
4 use crate::{CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, Weak};
5 use crate::Namespace::{self, TypeNS, MacroNS};
6 use crate::{NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
7 use crate::{Resolver, Segment};
8 use crate::{names_to_string, module_to_string};
9 use crate::{resolve_error, ResolutionError, Suggestion};
10 use crate::ModuleKind;
11 use crate::macros::ParentScope;
13 use errors::Applicability;
15 use rustc_data_structures::ptr_key::PtrKey;
17 use rustc::lint::builtin::BuiltinLintDiagnostics;
18 use rustc::lint::builtin::{
19 DUPLICATE_MACRO_EXPORTS,
20 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
23 use rustc::hir::def_id::{CrateNum, DefId};
24 use rustc::hir::def::*;
25 use rustc::session::DiagnosticMessageId;
26 use rustc::util::nodemap::FxHashSet;
27 use rustc::{bug, span_bug};
29 use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID};
30 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
31 use syntax::ext::hygiene::Mark;
32 use syntax::symbol::keywords;
33 use syntax::util::lev_distance::find_best_match_for_name;
34 use syntax::{struct_span_err, unwrap_or};
35 use syntax_pos::{MultiSpan, Span};
39 use std::cell::{Cell, RefCell};
42 /// Contains data for specific types of import directives.
43 #[derive(Clone, Debug)]
44 pub enum ImportDirectiveSubclass<'a> {
46 /// `source` in `use prefix::source as target`.
48 /// `target` in `use prefix::source as target`.
50 /// Bindings to which `source` refers to.
51 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
52 /// Bindings introduced by `target`.
53 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
54 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
56 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
61 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
62 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
71 /// One import directive.
72 #[derive(Debug,Clone)]
73 crate struct ImportDirective<'a> {
74 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
76 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
77 /// this id is the ID of the leaf tree. For example:
79 /// ```ignore (pacify the mercilous tidy)
80 /// use foo::bar::{a, b}
83 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
84 /// for `a` in this field.
87 /// The `id` of the "root" use-kind -- this is always the same as
88 /// `id` except in the case of "nested" use trees, in which case
89 /// it will be the `id` of the root use tree. e.g., in the example
90 /// from `id`, this would be the ID of the `use foo::bar`
94 /// Span of the entire use statement.
97 /// Span of the entire use statement with attributes.
98 pub use_span_with_attributes: Span,
100 /// Did the use statement have any attributes?
101 pub has_attributes: bool,
103 /// Span of this use tree.
106 /// Span of the *root* use tree (see `root_id`).
109 pub parent_scope: ParentScope<'a>,
110 pub module_path: Vec<Segment>,
111 /// The resolution of `module_path`.
112 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
113 pub subclass: ImportDirectiveSubclass<'a>,
114 pub vis: Cell<ty::Visibility>,
115 pub used: Cell<bool>,
118 impl<'a> ImportDirective<'a> {
119 pub fn is_glob(&self) -> bool {
120 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
123 pub fn is_nested(&self) -> bool {
124 match self.subclass {
125 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
130 crate fn crate_lint(&self) -> CrateLint {
131 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
135 #[derive(Clone, Default, Debug)]
136 /// Records information about the resolution of a name in a namespace of a module.
137 pub struct NameResolution<'a> {
138 /// Single imports that may define the name in the namespace.
139 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
140 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
141 /// The least shadowable known binding for this name, or None if there are no known bindings.
142 pub binding: Option<&'a NameBinding<'a>>,
143 shadowed_glob: Option<&'a NameBinding<'a>>,
146 impl<'a> NameResolution<'a> {
147 // Returns the binding for the name if it is known or None if it not known.
148 fn binding(&self) -> Option<&'a NameBinding<'a>> {
149 self.binding.and_then(|binding| {
150 if !binding.is_glob_import() ||
151 self.single_imports.is_empty() { Some(binding) } else { None }
156 impl<'a> Resolver<'a> {
157 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
158 -> &'a RefCell<NameResolution<'a>> {
159 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
160 .or_insert_with(|| self.arenas.alloc_name_resolution())
163 crate fn resolve_ident_in_module_unadjusted(
165 module: ModuleOrUniformRoot<'a>,
170 ) -> Result<&'a NameBinding<'a>, Determinacy> {
171 self.resolve_ident_in_module_unadjusted_ext(
172 module, ident, ns, None, false, record_used, path_span
173 ).map_err(|(determinacy, _)| determinacy)
176 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
177 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
178 crate fn resolve_ident_in_module_unadjusted_ext(
180 module: ModuleOrUniformRoot<'a>,
183 parent_scope: Option<&ParentScope<'a>>,
184 restricted_shadowing: bool,
187 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
188 let module = match module {
189 ModuleOrUniformRoot::Module(module) => module,
190 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
191 assert!(!restricted_shadowing);
192 let parent_scope = self.dummy_parent_scope();
193 let binding = self.early_resolve_ident_in_lexical_scope(
194 ident, ScopeSet::AbsolutePath(ns), &parent_scope,
195 record_used, record_used, path_span,
197 return binding.map_err(|determinacy| (determinacy, Weak::No));
199 ModuleOrUniformRoot::ExternPrelude => {
200 assert!(!restricted_shadowing);
201 return if ns != TypeNS {
202 Err((Determined, Weak::No))
203 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
205 } else if !self.graph_root.unresolved_invocations.borrow().is_empty() {
206 // Macro-expanded `extern crate` items can add names to extern prelude.
207 Err((Undetermined, Weak::No))
209 Err((Determined, Weak::No))
212 ModuleOrUniformRoot::CurrentScope => {
213 assert!(!restricted_shadowing);
215 parent_scope.expect("no parent scope for a single-segment import");
218 if ident.name == keywords::Crate.name() ||
219 ident.name == keywords::DollarCrate.name() {
220 let module = self.resolve_crate_root(ident);
221 let binding = (module, ty::Visibility::Public,
222 module.span, Mark::root())
223 .to_name_binding(self.arenas);
225 } else if ident.name == keywords::Super.name() ||
226 ident.name == keywords::SelfLower.name() {
227 // FIXME: Implement these with renaming requirements so that e.g.
228 // `use super;` doesn't work, but `use super as name;` does.
229 // Fall through here to get an error from `early_resolve_...`.
233 let binding = self.early_resolve_ident_in_lexical_scope(
234 ident, ScopeSet::Import(ns), parent_scope, record_used, record_used, path_span
236 return binding.map_err(|determinacy| (determinacy, Weak::No));
240 self.populate_module_if_necessary(module);
242 let resolution = self.resolution(module, ident, ns)
244 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
246 if let Some(binding) = resolution.binding {
247 if !restricted_shadowing && binding.expansion != Mark::root() {
248 if let NameBindingKind::Def(_, true) = binding.kind {
249 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
254 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
255 if let Some(blacklisted_binding) = this.blacklisted_binding {
256 if ptr::eq(binding, blacklisted_binding) {
257 return Err((Determined, Weak::No));
260 // `extern crate` are always usable for backwards compatibility, see issue #37020,
261 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
262 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
263 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
267 return resolution.binding.and_then(|binding| {
268 // If the primary binding is blacklisted, search further and return the shadowed
269 // glob binding if it exists. What we really want here is having two separate
270 // scopes in a module - one for non-globs and one for globs, but until that's done
271 // use this hack to avoid inconsistent resolution ICEs during import validation.
272 if let Some(blacklisted_binding) = self.blacklisted_binding {
273 if ptr::eq(binding, blacklisted_binding) {
274 return resolution.shadowed_glob;
278 }).ok_or((Determined, Weak::No)).and_then(|binding| {
279 if self.last_import_segment && check_usable(self, binding).is_err() {
280 Err((Determined, Weak::No))
282 self.record_use(ident, ns, binding, restricted_shadowing);
284 if let Some(shadowed_glob) = resolution.shadowed_glob {
285 // Forbid expanded shadowing to avoid time travel.
286 if restricted_shadowing &&
287 binding.expansion != Mark::root() &&
288 binding.def() != shadowed_glob.def() {
289 self.ambiguity_errors.push(AmbiguityError {
290 kind: AmbiguityKind::GlobVsExpanded,
294 misc1: AmbiguityErrorMisc::None,
295 misc2: AmbiguityErrorMisc::None,
300 if !self.is_accessible(binding.vis) &&
301 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
302 !(self.last_import_segment && binding.is_extern_crate()) {
303 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
311 // Items and single imports are not shadowable, if we have one, then it's determined.
312 if let Some(binding) = resolution.binding {
313 if !binding.is_glob_import() {
314 return check_usable(self, binding);
318 // --- From now on we either have a glob resolution or no resolution. ---
320 // Check if one of single imports can still define the name,
321 // if it can then our result is not determined and can be invalidated.
322 for single_import in &resolution.single_imports {
323 if !self.is_accessible(single_import.vis.get()) {
326 let module = unwrap_or!(single_import.imported_module.get(),
327 return Err((Undetermined, Weak::No)));
328 let ident = match single_import.subclass {
329 SingleImport { source, .. } => source,
332 match self.resolve_ident_in_module(module, ident, ns, Some(&single_import.parent_scope),
334 Err(Determined) => continue,
335 Ok(binding) if !self.is_accessible_from(
336 binding.vis, single_import.parent_scope.module
338 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
342 // So we have a resolution that's from a glob import. This resolution is determined
343 // if it cannot be shadowed by some new item/import expanded from a macro.
344 // This happens either if there are no unexpanded macros, or expanded names cannot
345 // shadow globs (that happens in macro namespace or with restricted shadowing).
347 // Additionally, any macro in any module can plant names in the root module if it creates
348 // `macro_export` macros, so the root module effectively has unresolved invocations if any
349 // module has unresolved invocations.
350 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
351 // progress, we have to ignore those potential unresolved invocations from other modules
352 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
353 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
354 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
355 if let Some(binding) = resolution.binding {
356 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
357 return check_usable(self, binding);
359 return Err((Undetermined, Weak::No));
363 // --- From now on we have no resolution. ---
365 // Now we are in situation when new item/import can appear only from a glob or a macro
366 // expansion. With restricted shadowing names from globs and macro expansions cannot
367 // shadow names from outer scopes, so we can freely fallback from module search to search
368 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
369 // scopes we return `Undetermined` with `Weak::Yes`.
371 // Check if one of unexpanded macros can still define the name,
372 // if it can then our "no resolution" result is not determined and can be invalidated.
373 if unexpanded_macros {
374 return Err((Undetermined, Weak::Yes));
377 // Check if one of glob imports can still define the name,
378 // if it can then our "no resolution" result is not determined and can be invalidated.
379 for glob_import in module.globs.borrow().iter() {
380 if !self.is_accessible(glob_import.vis.get()) {
383 let module = match glob_import.imported_module.get() {
384 Some(ModuleOrUniformRoot::Module(module)) => module,
386 None => return Err((Undetermined, Weak::Yes)),
388 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
389 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
390 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
394 let result = self.resolve_ident_in_module_unadjusted(
395 ModuleOrUniformRoot::Module(module),
401 self.current_module = orig_current_module;
404 Err(Determined) => continue,
405 Ok(binding) if !self.is_accessible_from(
406 binding.vis, glob_import.parent_scope.module
408 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
412 // No resolution and no one else can define the name - determinate error.
413 Err((Determined, Weak::No))
416 // Add an import directive to the current module.
417 pub fn add_import_directive(&mut self,
418 module_path: Vec<Segment>,
419 subclass: ImportDirectiveSubclass<'a>,
426 parent_scope: ParentScope<'a>) {
427 let current_module = parent_scope.module;
428 let directive = self.arenas.alloc_import_directive(ImportDirective {
431 imported_module: Cell::new(None),
436 use_span_with_attributes: item.span_with_attributes(),
437 has_attributes: !item.attrs.is_empty(),
441 used: Cell::new(false),
444 debug!("add_import_directive({:?})", directive);
446 self.indeterminate_imports.push(directive);
447 match directive.subclass {
448 SingleImport { target, type_ns_only, .. } => {
449 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
450 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
451 resolution.single_imports.insert(PtrKey(directive));
454 // We don't add prelude imports to the globs since they only affect lexical scopes,
455 // which are not relevant to import resolution.
456 GlobImport { is_prelude: true, .. } => {}
457 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
462 // Given a binding and an import directive that resolves to it,
463 // return the corresponding binding defined by the import directive.
464 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
465 -> &'a NameBinding<'a> {
466 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
467 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
468 !directive.is_glob() && binding.is_extern_crate() {
474 if let GlobImport { ref max_vis, .. } = directive.subclass {
475 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
480 self.arenas.alloc_name_binding(NameBinding {
481 kind: NameBindingKind::Import {
484 used: Cell::new(false),
487 span: directive.span,
489 expansion: directive.parent_scope.expansion,
493 crate fn check_reserved_macro_name(&self, ident: Ident, ns: Namespace) {
494 // Reserve some names that are not quite covered by the general check
495 // performed on `Resolver::builtin_attrs`.
497 (ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") {
498 self.session.span_err(ident.span,
499 &format!("name `{}` is reserved in macro namespace", ident));
503 // Define the name or return the existing binding if there is a collision.
504 pub fn try_define(&mut self,
508 binding: &'a NameBinding<'a>)
509 -> Result<(), &'a NameBinding<'a>> {
510 self.check_reserved_macro_name(ident, ns);
511 self.set_binding_parent_module(binding, module);
512 self.update_resolution(module, ident, ns, |this, resolution| {
513 if let Some(old_binding) = resolution.binding {
514 if binding.def() == Def::Err {
515 // Do not override real bindings with `Def::Err`s from error recovery.
518 match (old_binding.is_glob_import(), binding.is_glob_import()) {
520 if binding.def() != old_binding.def() {
521 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
522 old_binding, binding));
523 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
524 // We are glob-importing the same item but with greater visibility.
525 resolution.binding = Some(binding);
528 (old_glob @ true, false) | (old_glob @ false, true) => {
529 let (glob_binding, nonglob_binding) = if old_glob {
530 (old_binding, binding)
532 (binding, old_binding)
534 if glob_binding.def() != nonglob_binding.def() &&
535 ns == MacroNS && nonglob_binding.expansion != Mark::root() {
536 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsExpanded,
537 nonglob_binding, glob_binding));
539 resolution.binding = Some(nonglob_binding);
541 resolution.shadowed_glob = Some(glob_binding);
544 if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
545 (&old_binding.kind, &binding.kind) {
547 this.session.buffer_lint_with_diagnostic(
548 DUPLICATE_MACRO_EXPORTS,
551 &format!("a macro named `{}` has already been exported", ident),
552 BuiltinLintDiagnostics::DuplicatedMacroExports(
553 ident, old_binding.span, binding.span));
555 resolution.binding = Some(binding);
557 return Err(old_binding);
562 resolution.binding = Some(binding);
569 fn ambiguity(&self, kind: AmbiguityKind,
570 primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>)
571 -> &'a NameBinding<'a> {
572 self.arenas.alloc_name_binding(NameBinding {
573 ambiguity: Some((secondary_binding, kind)),
574 ..primary_binding.clone()
578 // Use `f` to mutate the resolution of the name in the module.
579 // If the resolution becomes a success, define it in the module's glob importers.
580 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
582 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
584 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
585 // during which the resolution might end up getting re-defined via a glob cycle.
587 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
588 let old_binding = resolution.binding();
590 let t = f(self, resolution);
592 match resolution.binding() {
593 _ if old_binding.is_some() => return t,
595 Some(binding) => match old_binding {
596 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
602 // Define `binding` in `module`s glob importers.
603 for directive in module.glob_importers.borrow_mut().iter() {
604 let mut ident = ident.modern();
605 let scope = match ident.span.reverse_glob_adjust(module.expansion,
606 directive.span.ctxt().modern()) {
607 Some(Some(def)) => self.macro_def_scope(def),
608 Some(None) => directive.parent_scope.module,
611 if self.is_accessible_from(binding.vis, scope) {
612 let imported_binding = self.import(binding, directive);
613 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
620 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
622 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
623 if let SingleImport { target, .. } = directive.subclass {
624 let dummy_binding = self.dummy_binding;
625 let dummy_binding = self.import(dummy_binding, directive);
626 self.per_ns(|this, ns| {
627 let _ = this.try_define(directive.parent_scope.module, target, ns, dummy_binding);
633 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
634 /// import errors within the same use tree into a single diagnostic.
635 #[derive(Debug, Clone)]
636 struct UnresolvedImportError {
638 label: Option<String>,
639 note: Option<String>,
640 suggestion: Option<Suggestion>,
643 pub struct ImportResolver<'a, 'b: 'a> {
644 pub resolver: &'a mut Resolver<'b>,
647 impl<'a, 'b: 'a> std::ops::Deref for ImportResolver<'a, 'b> {
648 type Target = Resolver<'b>;
649 fn deref(&self) -> &Resolver<'b> {
654 impl<'a, 'b: 'a> std::ops::DerefMut for ImportResolver<'a, 'b> {
655 fn deref_mut(&mut self) -> &mut Resolver<'b> {
660 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
661 fn parent(self, id: DefId) -> Option<DefId> {
662 self.resolver.parent(id)
666 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
669 // This is a fixed-point algorithm. We resolve imports until our efforts
670 // are stymied by an unresolved import; then we bail out of the current
671 // module and continue. We terminate successfully once no more imports
672 // remain or unsuccessfully when no forward progress in resolving imports
675 /// Resolves all imports for the crate. This method performs the fixed-
677 pub fn resolve_imports(&mut self) {
678 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
679 while self.indeterminate_imports.len() < prev_num_indeterminates {
680 prev_num_indeterminates = self.indeterminate_imports.len();
681 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
682 match self.resolve_import(&import) {
683 true => self.determined_imports.push(import),
684 false => self.indeterminate_imports.push(import),
690 pub fn finalize_imports(&mut self) {
691 for module in self.arenas.local_modules().iter() {
692 self.finalize_resolutions_in(module);
695 let mut has_errors = false;
696 let mut seen_spans = FxHashSet::default();
697 let mut errors = vec![];
698 let mut prev_root_id: NodeId = NodeId::from_u32(0);
699 for i in 0 .. self.determined_imports.len() {
700 let import = self.determined_imports[i];
701 if let Some(err) = self.finalize_import(import) {
704 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
705 if source.name == "self" {
706 // Silence `unresolved import` error if E0429 is already emitted
707 if let Err(Determined) = source_bindings.value_ns.get() {
713 // If the error is a single failed import then create a "fake" import
714 // resolution for it so that later resolve stages won't complain.
715 self.import_dummy_binding(import);
716 if prev_root_id.as_u32() != 0
717 && prev_root_id.as_u32() != import.root_id.as_u32()
718 && !errors.is_empty() {
719 // In the case of a new import line, throw a diagnostic message
720 // for the previous line.
721 self.throw_unresolved_import_error(errors, None);
724 if !seen_spans.contains(&err.span) {
725 let path = import_path_to_string(
726 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
730 seen_spans.insert(err.span);
731 errors.push((path, err));
732 prev_root_id = import.root_id;
737 if !errors.is_empty() {
738 self.throw_unresolved_import_error(errors.clone(), None);
741 // Report unresolved imports only if no hard error was already reported
742 // to avoid generating multiple errors on the same import.
744 for import in &self.indeterminate_imports {
745 self.throw_unresolved_import_error(errors, Some(MultiSpan::from(import.span)));
751 fn throw_unresolved_import_error(
753 errors: Vec<(String, UnresolvedImportError)>,
754 span: Option<MultiSpan>,
756 /// Upper limit on the number of `span_label` messages.
757 const MAX_LABEL_COUNT: usize = 10;
759 let (span, msg, note) = if errors.is_empty() {
760 (span.unwrap(), "unresolved import".to_string(), None)
762 let span = MultiSpan::from_spans(
765 .map(|(_, err)| err.span)
771 .filter_map(|(_, err)| err.note.as_ref())
776 .map(|(path, _)| format!("`{}`", path))
777 .collect::<Vec<_>>();
780 "unresolved import{} {}",
781 if paths.len() > 1 { "s" } else { "" },
788 let mut diag = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
790 if let Some(note) = ¬e {
794 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
795 if let Some(label) = err.label {
796 diag.span_label(err.span, label);
799 if let Some((span, msg, suggestion, applicability)) = err.suggestion {
800 diag.span_suggestion(span, &msg, suggestion, applicability);
807 /// Attempts to resolve the given import, returning true if its resolution is determined.
808 /// If successful, the resolved bindings are written into the module.
809 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
810 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
811 Segment::names_to_string(&directive.module_path),
812 module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
814 self.current_module = directive.parent_scope.module;
816 let module = if let Some(module) = directive.imported_module.get() {
819 // For better failure detection, pretend that the import will
820 // not define any names while resolving its module path.
821 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
822 let path_res = self.resolve_path(
823 &directive.module_path,
825 &directive.parent_scope,
828 directive.crate_lint(),
830 directive.vis.set(orig_vis);
833 PathResult::Module(module) => module,
834 PathResult::Indeterminate => return false,
835 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
839 directive.imported_module.set(Some(module));
840 let (source, target, source_bindings, target_bindings, type_ns_only) =
841 match directive.subclass {
842 SingleImport { source, target, ref source_bindings,
843 ref target_bindings, type_ns_only, .. } =>
844 (source, target, source_bindings, target_bindings, type_ns_only),
845 GlobImport { .. } => {
846 self.resolve_glob_import(directive);
852 let mut indeterminate = false;
853 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
854 if let Err(Undetermined) = source_bindings[ns].get() {
855 // For better failure detection, pretend that the import will
856 // not define any names while resolving its module path.
857 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
858 let binding = this.resolve_ident_in_module(
859 module, source, ns, Some(&directive.parent_scope), false, directive.span
861 directive.vis.set(orig_vis);
863 source_bindings[ns].set(binding);
868 let parent = directive.parent_scope.module;
869 match source_bindings[ns].get() {
870 Err(Undetermined) => indeterminate = true,
872 this.update_resolution(parent, target, ns, |_, resolution| {
873 resolution.single_imports.remove(&PtrKey(directive));
876 Ok(binding) if !binding.is_importable() => {
877 let msg = format!("`{}` is not directly importable", target);
878 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
879 .span_label(directive.span, "cannot be imported directly")
881 // Do not import this illegal binding. Import a dummy binding and pretend
882 // everything is fine
883 this.import_dummy_binding(directive);
886 let imported_binding = this.import(binding, directive);
887 target_bindings[ns].set(Some(imported_binding));
888 this.define(parent, target, ns, imported_binding);
896 /// Performs final import resolution, consistency checks and error reporting.
898 /// Optionally returns an unresolved import error. This error is buffered and used to
899 /// consolidate multiple unresolved import errors into a single diagnostic.
902 directive: &'b ImportDirective<'b>
903 ) -> Option<UnresolvedImportError> {
904 self.current_module = directive.parent_scope.module;
906 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
907 let prev_ambiguity_errors_len = self.ambiguity_errors.len();
908 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
909 true, directive.span, directive.crate_lint());
910 let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
911 directive.vis.set(orig_vis);
912 let module = match path_res {
913 PathResult::Module(module) => {
914 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
915 if let Some(initial_module) = directive.imported_module.get() {
916 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
917 span_bug!(directive.span, "inconsistent resolution for an import");
920 if self.privacy_errors.is_empty() {
921 let msg = "cannot determine resolution for the import";
922 let msg_note = "import resolution is stuck, try simplifying other imports";
923 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
929 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
931 assert!(directive.imported_module.get().is_none());
932 resolve_error(self, span, ResolutionError::FailedToResolve {
939 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
941 assert!(directive.imported_module.get().is_none());
942 let err = match self.make_path_suggestion(
944 directive.module_path.clone(),
945 &directive.parent_scope,
947 Some((suggestion, note)) => {
948 UnresolvedImportError {
954 String::from("a similar path exists"),
955 Segment::names_to_string(&suggestion),
956 Applicability::MaybeIncorrect,
961 UnresolvedImportError {
974 PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
976 assert!(directive.imported_module.get().is_none());
978 // The error was already reported earlier.
981 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
984 let (ident, target, source_bindings, target_bindings, type_ns_only) =
985 match directive.subclass {
986 SingleImport { source, target, ref source_bindings,
987 ref target_bindings, type_ns_only, .. } =>
988 (source, target, source_bindings, target_bindings, type_ns_only),
989 GlobImport { is_prelude, ref max_vis } => {
990 if directive.module_path.len() <= 1 {
991 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
992 // 2 segments, so the `resolve_path` above won't trigger it.
993 let mut full_path = directive.module_path.clone();
994 full_path.push(Segment::from_ident(keywords::Invalid.ident()));
995 self.lint_if_path_starts_with_module(
996 directive.crate_lint(),
1003 if let ModuleOrUniformRoot::Module(module) = module {
1004 if module.def_id() == directive.parent_scope.module.def_id() {
1005 // Importing a module into itself is not allowed.
1006 return Some(UnresolvedImportError {
1007 span: directive.span,
1008 label: Some(String::from("cannot glob-import a module into itself")),
1015 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1016 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
1017 let msg = "A non-empty glob must import something with the glob's visibility";
1018 self.session.span_err(directive.span, msg);
1022 _ => unreachable!(),
1025 let mut all_ns_err = true;
1026 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1027 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1028 let orig_blacklisted_binding =
1029 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1030 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1031 let binding = this.resolve_ident_in_module(
1032 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1034 this.last_import_segment = orig_last_import_segment;
1035 this.blacklisted_binding = orig_blacklisted_binding;
1036 directive.vis.set(orig_vis);
1040 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
1041 let initial_def = source_bindings[ns].get().map(|initial_binding| {
1043 if let Some(target_binding) = target_bindings[ns].get() {
1044 if target.name == "_" &&
1045 initial_binding.is_extern_crate() && !initial_binding.is_import() {
1046 this.record_use(ident, ns, target_binding,
1047 directive.module_path.is_empty());
1050 initial_binding.def()
1052 let def = binding.def();
1053 if let Ok(initial_def) = initial_def {
1054 if def != initial_def && this.ambiguity_errors.is_empty() {
1055 span_bug!(directive.span, "inconsistent resolution for an import");
1058 if def != Def::Err &&
1059 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1060 let msg = "cannot determine resolution for the import";
1062 "import resolution is stuck, try simplifying other imports";
1063 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1068 // FIXME: This assert may fire if public glob is later shadowed by a private
1069 // single import (see test `issue-55884-2.rs`). In theory single imports should
1070 // always block globs, even if they are not yet resolved, so that this kind of
1071 // self-inconsistent resolution never happens.
1072 // Reenable the assert when the issue is fixed.
1073 // assert!(result[ns].get().is_err());
1079 let mut all_ns_failed = true;
1080 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1081 let binding = this.resolve_ident_in_module(
1082 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1084 if binding.is_ok() {
1085 all_ns_failed = false;
1089 return if all_ns_failed {
1090 let resolutions = match module {
1091 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1094 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1095 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1096 if *i == ident { return None; } // Never suggest the same name
1097 match *resolution.borrow() {
1098 NameResolution { binding: Some(name_binding), .. } => {
1099 match name_binding.kind {
1100 NameBindingKind::Import { binding, .. } => {
1101 match binding.kind {
1102 // Never suggest the name that has binding error
1103 // i.e., the name that cannot be previously resolved
1104 NameBindingKind::Def(Def::Err, _) => return None,
1111 NameResolution { ref single_imports, .. }
1112 if single_imports.is_empty() => None,
1117 let lev_suggestion =
1118 find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1121 String::from("a similar name exists in the module"),
1122 suggestion.to_string(),
1123 Applicability::MaybeIncorrect,
1127 let label = match module {
1128 ModuleOrUniformRoot::Module(module) => {
1129 let module_str = module_to_string(module);
1130 if let Some(module_str) = module_str {
1131 format!("no `{}` in `{}`", ident, module_str)
1133 format!("no `{}` in the root", ident)
1137 if !ident.is_path_segment_keyword() {
1138 format!("no `{}` external crate", ident)
1140 // HACK(eddyb) this shows up for `self` & `super`, which
1141 // should work instead - for now keep the same error message.
1142 format!("no `{}` in the root", ident)
1146 Some(UnresolvedImportError {
1147 span: directive.span,
1150 suggestion: lev_suggestion,
1153 // `resolve_ident_in_module` reported a privacy error.
1154 self.import_dummy_binding(directive);
1159 let mut reexport_error = None;
1160 let mut any_successful_reexport = false;
1161 self.per_ns(|this, ns| {
1162 if let Ok(binding) = source_bindings[ns].get() {
1163 let vis = directive.vis.get();
1164 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1165 reexport_error = Some((ns, binding));
1167 any_successful_reexport = true;
1172 // All namespaces must be re-exported with extra visibility for an error to occur.
1173 if !any_successful_reexport {
1174 let (ns, binding) = reexport_error.unwrap();
1175 if ns == TypeNS && binding.is_extern_crate() {
1176 let msg = format!("extern crate `{}` is private, and cannot be \
1177 re-exported (error E0365), consider declaring with \
1180 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1184 } else if ns == TypeNS {
1185 struct_span_err!(self.session, directive.span, E0365,
1186 "`{}` is private, and cannot be re-exported", ident)
1187 .span_label(directive.span, format!("re-export of private `{}`", ident))
1188 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1191 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1193 format!("consider marking `{}` as `pub` in the imported module", ident);
1194 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1195 .span_note(directive.span, ¬e_msg)
1200 if directive.module_path.len() <= 1 {
1201 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1202 // 2 segments, so the `resolve_path` above won't trigger it.
1203 let mut full_path = directive.module_path.clone();
1204 full_path.push(Segment::from_ident(ident));
1205 self.per_ns(|this, ns| {
1206 if let Ok(binding) = source_bindings[ns].get() {
1207 this.lint_if_path_starts_with_module(
1208 directive.crate_lint(),
1217 // Record what this import resolves to for later uses in documentation,
1218 // this may resolve to either a value or a type, but for documentation
1219 // purposes it's good enough to just favor one over the other.
1220 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1221 let mut def = binding.def();
1222 if let Def::Macro(def_id, _) = def {
1223 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1224 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1225 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1226 if def_id.krate == CrateNum::BuiltinMacros {
1227 this.session.span_err(directive.span, "cannot import a built-in macro");
1231 let import = this.import_map.entry(directive.id).or_default();
1232 import[ns] = Some(PathResolution::new(def));
1235 self.check_for_redundant_imports(
1243 debug!("(resolving single import) successfully resolved import");
1247 fn check_for_redundant_imports(
1250 directive: &'b ImportDirective<'b>,
1251 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1252 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1255 // Skip if the import was produced by a macro.
1256 if directive.parent_scope.expansion != Mark::root() {
1260 // Skip if we are inside a named module (in contrast to an anonymous
1261 // module defined by a block).
1262 if let ModuleKind::Def(_, _) = directive.parent_scope.module.kind {
1266 let mut is_redundant = PerNS {
1272 let mut redundant_span = PerNS {
1278 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1279 if binding.def() == Def::Err {
1283 let orig_blacklisted_binding = mem::replace(
1284 &mut this.blacklisted_binding,
1285 target_bindings[ns].get()
1288 match this.early_resolve_ident_in_lexical_scope(
1290 ScopeSet::Import(ns),
1291 &directive.parent_scope,
1296 Ok(other_binding) => {
1297 is_redundant[ns] = Some(
1298 binding.def() == other_binding.def()
1299 && !other_binding.is_ambiguity()
1301 redundant_span[ns] =
1302 Some((other_binding.span, other_binding.is_import()));
1304 Err(_) => is_redundant[ns] = Some(false)
1307 this.blacklisted_binding = orig_blacklisted_binding;
1310 if !is_redundant.is_empty() &&
1311 is_redundant.present_items().all(|is_redundant| is_redundant)
1313 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1314 redundant_spans.sort();
1315 redundant_spans.dedup();
1316 self.session.buffer_lint_with_diagnostic(
1320 &format!("the item `{}` is imported redundantly", ident),
1321 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1326 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1327 let module = match directive.imported_module.get().unwrap() {
1328 ModuleOrUniformRoot::Module(module) => module,
1330 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1335 self.populate_module_if_necessary(module);
1337 if module.is_trait() {
1338 self.session.span_err(directive.span, "items in traits are not importable.");
1340 } else if module.def_id() == directive.parent_scope.module.def_id() {
1342 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1343 self.prelude = Some(module);
1347 // Add to module's glob_importers
1348 module.glob_importers.borrow_mut().push(directive);
1350 // Ensure that `resolutions` isn't borrowed during `try_define`,
1351 // since it might get updated via a glob cycle.
1352 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1353 resolution.borrow().binding().map(|binding| (ident, binding))
1354 }).collect::<Vec<_>>();
1355 for ((mut ident, ns), binding) in bindings {
1356 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1357 directive.span.ctxt().modern()) {
1358 Some(Some(def)) => self.macro_def_scope(def),
1359 Some(None) => self.current_module,
1362 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1363 let imported_binding = self.import(binding, directive);
1364 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1368 // Record the destination of this import
1369 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1372 // Miscellaneous post-processing, including recording re-exports,
1373 // reporting conflicts, and reporting unresolved imports.
1374 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1375 // Since import resolution is finished, globs will not define any more names.
1376 *module.globs.borrow_mut() = Vec::new();
1378 let mut reexports = Vec::new();
1380 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1381 let resolution = &mut *resolution.borrow_mut();
1382 let binding = match resolution.binding {
1383 Some(binding) => binding,
1387 // Filter away ambiguous and gensymed imports. Gensymed imports
1388 // (e.g. implicitly injected `std`) cannot be properly encoded in metadata,
1389 // so they can cause name conflict errors downstream.
1390 let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
1391 !(ident.name.is_gensymed() && ident.name != "_");
1392 if is_good_import || binding.is_macro_def() {
1393 let def = binding.def();
1394 if def != Def::Err {
1395 if let Some(def_id) = def.opt_def_id() {
1396 if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1397 self.cstore.export_macros_untracked(def_id.krate);
1400 reexports.push(Export {
1401 ident: ident.modern(),
1409 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1410 if ns == TypeNS && orig_binding.is_variant() &&
1411 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1412 let msg = match directive.subclass {
1413 ImportDirectiveSubclass::SingleImport { .. } => {
1414 format!("variant `{}` is private and cannot be re-exported",
1417 ImportDirectiveSubclass::GlobImport { .. } => {
1418 let msg = "enum is private and its variants \
1419 cannot be re-exported".to_owned();
1420 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1423 let fresh = self.session.one_time_diagnostics
1424 .borrow_mut().insert(error_id);
1430 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1432 let mut err = self.session.struct_span_err(binding.span, &msg);
1434 let imported_module = match directive.imported_module.get() {
1435 Some(ModuleOrUniformRoot::Module(module)) => module,
1436 _ => bug!("module should exist"),
1438 let resolutions = imported_module.parent.expect("parent should exist")
1439 .resolutions.borrow();
1440 let enum_path_segment_index = directive.module_path.len() - 1;
1441 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1443 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1444 .expect("resolution should exist");
1445 let enum_span = enum_resolution.borrow()
1446 .binding.expect("binding should exist")
1448 let enum_def_span = self.session.source_map().def_span(enum_span);
1449 let enum_def_snippet = self.session.source_map()
1450 .span_to_snippet(enum_def_span).expect("snippet should exist");
1451 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1452 let after_vis_index = enum_def_snippet.find("enum")
1453 .expect("`enum` keyword should exist in snippet");
1454 let suggestion = format!("pub {}",
1455 &enum_def_snippet[after_vis_index..]);
1458 .diag_span_suggestion_once(&mut err,
1459 DiagnosticMessageId::ErrorId(0),
1461 "consider making the enum public",
1468 if reexports.len() > 0 {
1469 if let Some(def_id) = module.def_id() {
1470 self.export_map.insert(def_id, reexports);
1476 fn import_path_to_string(names: &[Ident],
1477 subclass: &ImportDirectiveSubclass<'_>,
1478 span: Span) -> String {
1479 let pos = names.iter()
1480 .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1481 let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1482 if let Some(pos) = pos {
1483 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1484 names_to_string(names)
1486 let names = if global { &names[1..] } else { names };
1487 if names.is_empty() {
1488 import_directive_subclass_to_string(subclass)
1491 names_to_string(names),
1492 import_directive_subclass_to_string(subclass))
1497 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1499 SingleImport { source, .. } => source.to_string(),
1500 GlobImport { .. } => "*".to_string(),
1501 ExternCrate { .. } => "<extern crate>".to_string(),
1502 MacroUse => "#[macro_use]".to_string(),