1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::ImportDirectiveSubclass::*;
13 use {AmbiguityError, CrateLint, Module, PerNS};
14 use Namespace::{self, TypeNS, MacroNS};
15 use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
17 use {names_to_string, module_to_string};
18 use {resolve_error, ResolutionError};
20 use rustc_data_structures::ptr_key::PtrKey;
22 use rustc::lint::builtin::BuiltinLintDiagnostics;
23 use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
25 use rustc::hir::def::*;
26 use rustc::session::DiagnosticMessageId;
27 use rustc::util::nodemap::{FxHashMap, FxHashSet};
28 use rustc::middle::cstore::CrateStore;
30 use syntax::ast::{Ident, Name, NodeId, CRATE_NODE_ID};
31 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
32 use syntax::ext::hygiene::Mark;
33 use syntax::symbol::keywords;
34 use syntax::util::lev_distance::find_best_match_for_name;
37 use std::cell::{Cell, RefCell};
40 /// Contains data for specific types of import directives.
41 #[derive(Clone, Debug)]
42 pub enum ImportDirectiveSubclass<'a> {
46 result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
51 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
52 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
54 ExternCrate(Option<Name>),
58 /// One import directive.
59 #[derive(Debug,Clone)]
60 pub struct ImportDirective<'a> {
61 /// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
63 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
64 /// this id is the id of the leaf tree. For example:
66 /// ```ignore (pacify the mercilous tidy)
67 /// use foo::bar::{a, b}
70 /// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
71 /// for `a` in this field.
74 /// The `id` of the "root" use-kind -- this is always the same as
75 /// `id` except in the case of "nested" use trees, in which case
76 /// it will be the `id` of the root use tree. e.g., in the example
77 /// from `id`, this would be the id of the `use foo::bar`
81 /// Span of this use tree.
84 /// Span of the *root* use tree (see `root_id`).
87 pub parent: Module<'a>,
88 pub module_path: Vec<Ident>,
89 pub imported_module: Cell<Option<Module<'a>>>, // the resolution of `module_path`
90 pub subclass: ImportDirectiveSubclass<'a>,
91 pub vis: Cell<ty::Visibility>,
96 impl<'a> ImportDirective<'a> {
97 pub fn is_glob(&self) -> bool {
98 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
101 crate fn crate_lint(&self) -> CrateLint {
102 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
106 #[derive(Clone, Default, Debug)]
107 /// Records information about the resolution of a name in a namespace of a module.
108 pub struct NameResolution<'a> {
109 /// Single imports that may define the name in the namespace.
110 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
111 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
112 /// The least shadowable known binding for this name, or None if there are no known bindings.
113 pub binding: Option<&'a NameBinding<'a>>,
114 shadowed_glob: Option<&'a NameBinding<'a>>,
117 impl<'a> NameResolution<'a> {
118 // Returns the binding for the name if it is known or None if it not known.
119 fn binding(&self) -> Option<&'a NameBinding<'a>> {
120 self.binding.and_then(|binding| {
121 if !binding.is_glob_import() ||
122 self.single_imports.is_empty() { Some(binding) } else { None }
127 impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
128 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
129 -> &'a RefCell<NameResolution<'a>> {
130 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
131 .or_insert_with(|| self.arenas.alloc_name_resolution())
134 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
135 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
136 pub fn resolve_ident_in_module_unadjusted(&mut self,
140 restricted_shadowing: bool,
143 -> Result<&'a NameBinding<'a>, Determinacy> {
144 self.populate_module_if_necessary(module);
146 let resolution = self.resolution(module, ident, ns)
148 .map_err(|_| Determined)?; // This happens when there is a cycle of imports
151 if let Some(binding) = resolution.binding {
152 if let Some(shadowed_glob) = resolution.shadowed_glob {
153 let name = ident.name;
154 // Forbid expanded shadowing to avoid time travel.
155 if restricted_shadowing &&
156 binding.expansion != Mark::root() &&
157 ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
158 binding.def() != shadowed_glob.def() {
159 self.ambiguity_errors.push(AmbiguityError {
168 if self.record_use(ident, ns, binding, path_span) {
169 return Ok(self.dummy_binding);
171 if !self.is_accessible(binding.vis) {
172 self.privacy_errors.push(PrivacyError(path_span, ident.name, binding));
176 return resolution.binding.ok_or(Determined);
179 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
180 // `extern crate` are always usable for backwards compatibility, see issue #37020.
181 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
182 if usable { Ok(binding) } else { Err(Determined) }
185 // Items and single imports are not shadowable, if we have one, then it's determined.
186 if let Some(binding) = resolution.binding {
187 if !binding.is_glob_import() {
188 return check_usable(self, binding);
192 // --- From now on we either have a glob resolution or no resolution. ---
194 // Check if one of single imports can still define the name,
195 // if it can then our result is not determined and can be invalidated.
196 for single_import in &resolution.single_imports {
197 if !self.is_accessible(single_import.vis.get()) {
200 let module = unwrap_or!(single_import.imported_module.get(), return Err(Undetermined));
201 let ident = match single_import.subclass {
202 SingleImport { source, .. } => source,
205 match self.resolve_ident_in_module(module, ident, ns, false, path_span) {
206 Err(Determined) => continue,
207 Ok(_) | Err(Undetermined) => return Err(Undetermined),
211 // So we have a resolution that's from a glob import. This resolution is determined
212 // if it cannot be shadowed by some new item/import expanded from a macro.
213 // This happens either if there are no unexpanded macros, or expanded names cannot
214 // shadow globs (that happens in macro namespace or with restricted shadowing).
215 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty() ||
216 (ns == MacroNS && ptr::eq(module, self.graph_root) &&
217 !self.unresolved_invocations_macro_export.is_empty());
218 if let Some(binding) = resolution.binding {
219 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
220 return check_usable(self, binding);
222 return Err(Undetermined);
226 // --- From now on we have no resolution. ---
228 // Now we are in situation when new item/import can appear only from a glob or a macro
229 // expansion. With restricted shadowing names from globs and macro expansions cannot
230 // shadow names from outer scopes, so we can freely fallback from module search to search
231 // in outer scopes. To continue search in outer scopes we have to lie a bit and return
232 // `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
233 // for in-module resolution could be `Undetermined`.
234 if restricted_shadowing {
235 return Err(Determined);
238 // Check if one of unexpanded macros can still define the name,
239 // if it can then our "no resolution" result is not determined and can be invalidated.
240 if unexpanded_macros {
241 return Err(Undetermined);
244 // Check if one of glob imports can still define the name,
245 // if it can then our "no resolution" result is not determined and can be invalidated.
246 for glob_import in module.globs.borrow().iter() {
247 if !self.is_accessible(glob_import.vis.get()) {
250 let module = unwrap_or!(glob_import.imported_module.get(), return Err(Undetermined));
251 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
252 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
253 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
257 let result = self.resolve_ident_in_module_unadjusted(
258 module, ident, ns, false, false, path_span,
260 self.current_module = orig_current_module;
262 Err(Determined) => continue,
263 Ok(_) | Err(Undetermined) => return Err(Undetermined),
267 // No resolution and no one else can define the name - determinate error.
271 // Add an import directive to the current module.
272 pub fn add_import_directive(&mut self,
273 module_path: Vec<Ident>,
274 subclass: ImportDirectiveSubclass<'a>,
281 let current_module = self.current_module;
282 let directive = self.arenas.alloc_import_directive(ImportDirective {
283 parent: current_module,
285 imported_module: Cell::new(None),
293 used: Cell::new(false),
296 self.indeterminate_imports.push(directive);
297 match directive.subclass {
298 SingleImport { target, type_ns_only, .. } => {
299 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
300 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
301 resolution.single_imports.insert(PtrKey(directive));
304 // We don't add prelude imports to the globs since they only affect lexical scopes,
305 // which are not relevant to import resolution.
306 GlobImport { is_prelude: true, .. } => {}
307 GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
312 // Given a binding and an import directive that resolves to it,
313 // return the corresponding binding defined by the import directive.
314 pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
315 -> &'a NameBinding<'a> {
316 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
317 // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
318 !directive.is_glob() && binding.is_extern_crate() {
324 if let GlobImport { ref max_vis, .. } = directive.subclass {
325 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
330 self.arenas.alloc_name_binding(NameBinding {
331 kind: NameBindingKind::Import {
334 used: Cell::new(false),
336 span: directive.span,
338 expansion: directive.expansion,
342 // Define the name or return the existing binding if there is a collision.
343 pub fn try_define(&mut self,
347 binding: &'a NameBinding<'a>)
348 -> Result<(), &'a NameBinding<'a>> {
349 self.update_resolution(module, ident, ns, |this, resolution| {
350 if let Some(old_binding) = resolution.binding {
351 if binding.is_glob_import() {
352 if !old_binding.is_glob_import() &&
353 !(ns == MacroNS && old_binding.expansion != Mark::root()) {
354 resolution.shadowed_glob = Some(binding);
355 } else if binding.def() != old_binding.def() {
356 resolution.binding = Some(this.ambiguity(old_binding, binding));
357 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
358 // We are glob-importing the same item but with greater visibility.
359 resolution.binding = Some(binding);
361 } else if old_binding.is_glob_import() {
362 if ns == MacroNS && binding.expansion != Mark::root() &&
363 binding.def() != old_binding.def() {
364 resolution.binding = Some(this.ambiguity(binding, old_binding));
366 resolution.binding = Some(binding);
367 resolution.shadowed_glob = Some(old_binding);
369 } else if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
370 (&old_binding.kind, &binding.kind) {
372 this.session.buffer_lint_with_diagnostic(
373 DUPLICATE_MACRO_EXPORTS,
376 &format!("a macro named `{}` has already been exported", ident),
377 BuiltinLintDiagnostics::DuplicatedMacroExports(
378 ident, old_binding.span, binding.span));
380 resolution.binding = Some(binding);
382 return Err(old_binding);
385 resolution.binding = Some(binding);
392 pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
393 -> &'a NameBinding<'a> {
394 self.arenas.alloc_name_binding(NameBinding {
395 kind: NameBindingKind::Ambiguity { b1, b2 },
396 vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
398 expansion: Mark::root(),
402 // Use `f` to mutate the resolution of the name in the module.
403 // If the resolution becomes a success, define it in the module's glob importers.
404 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
406 where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
408 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
409 // during which the resolution might end up getting re-defined via a glob cycle.
411 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
412 let old_binding = resolution.binding();
414 let t = f(self, resolution);
416 match resolution.binding() {
417 _ if old_binding.is_some() => return t,
419 Some(binding) => match old_binding {
420 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
426 // Define `binding` in `module`s glob importers.
427 for directive in module.glob_importers.borrow_mut().iter() {
428 let mut ident = ident.modern();
429 let scope = match ident.span.reverse_glob_adjust(module.expansion,
430 directive.span.ctxt().modern()) {
431 Some(Some(def)) => self.macro_def_scope(def),
432 Some(None) => directive.parent,
435 if self.is_accessible_from(binding.vis, scope) {
436 let imported_binding = self.import(binding, directive);
437 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
444 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
446 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
447 if let SingleImport { target, .. } = directive.subclass {
448 let dummy_binding = self.dummy_binding;
449 let dummy_binding = self.import(dummy_binding, directive);
450 self.per_ns(|this, ns| {
451 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
457 pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
458 pub resolver: &'a mut Resolver<'b, 'c>,
461 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
462 type Target = Resolver<'b, 'c>;
463 fn deref(&self) -> &Resolver<'b, 'c> {
468 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
469 fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
474 impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
475 fn parent(self, id: DefId) -> Option<DefId> {
476 self.resolver.parent(id)
480 impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
483 // This is a fixed-point algorithm. We resolve imports until our efforts
484 // are stymied by an unresolved import; then we bail out of the current
485 // module and continue. We terminate successfully once no more imports
486 // remain or unsuccessfully when no forward progress in resolving imports
489 /// Resolves all imports for the crate. This method performs the fixed-
491 pub fn resolve_imports(&mut self) {
492 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
493 while self.indeterminate_imports.len() < prev_num_indeterminates {
494 prev_num_indeterminates = self.indeterminate_imports.len();
495 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
496 match self.resolve_import(&import) {
497 true => self.determined_imports.push(import),
498 false => self.indeterminate_imports.push(import),
504 pub fn finalize_imports(&mut self) {
505 for module in self.arenas.local_modules().iter() {
506 self.finalize_resolutions_in(module);
509 let mut errors = false;
510 let mut seen_spans = FxHashSet();
511 for i in 0 .. self.determined_imports.len() {
512 let import = self.determined_imports[i];
513 if let Some((span, err)) = self.finalize_import(import) {
516 if let SingleImport { source, ref result, .. } = import.subclass {
517 if source.name == "self" {
518 // Silence `unresolved import` error if E0429 is already emitted
519 match result.value_ns.get() {
520 Err(Determined) => continue,
526 // If the error is a single failed import then create a "fake" import
527 // resolution for it so that later resolve stages won't complain.
528 self.import_dummy_binding(import);
529 if !seen_spans.contains(&span) {
530 let path = import_path_to_string(&import.module_path[..],
533 let error = ResolutionError::UnresolvedImport(Some((span, &path, &err)));
534 resolve_error(self.resolver, span, error);
535 seen_spans.insert(span);
540 // Report unresolved imports only if no hard error was already reported
541 // to avoid generating multiple errors on the same import.
543 if let Some(import) = self.indeterminate_imports.iter().next() {
544 let error = ResolutionError::UnresolvedImport(None);
545 resolve_error(self.resolver, import.span, error);
550 /// Attempts to resolve the given import, returning true if its resolution is determined.
551 /// If successful, the resolved bindings are written into the module.
552 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
553 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
554 names_to_string(&directive.module_path[..]),
555 module_to_string(self.current_module).unwrap_or("???".to_string()));
557 self.current_module = directive.parent;
559 let module = if let Some(module) = directive.imported_module.get() {
562 let vis = directive.vis.get();
563 // For better failure detection, pretend that the import will not define any names
564 // while resolving its module path.
565 directive.vis.set(ty::Visibility::Invisible);
566 let result = self.resolve_path(&directive.module_path[..], None, false,
567 directive.span, directive.crate_lint());
568 directive.vis.set(vis);
571 PathResult::Module(module) => module,
572 PathResult::Indeterminate => return false,
577 directive.imported_module.set(Some(module));
578 let (source, target, result, type_ns_only) = match directive.subclass {
579 SingleImport { source, target, ref result, type_ns_only } =>
580 (source, target, result, type_ns_only),
581 GlobImport { .. } => {
582 self.resolve_glob_import(directive);
588 let mut indeterminate = false;
589 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
590 if let Err(Undetermined) = result[ns].get() {
591 result[ns].set(this.resolve_ident_in_module(module,
600 let parent = directive.parent;
601 match result[ns].get() {
602 Err(Undetermined) => indeterminate = true,
604 this.update_resolution(parent, target, ns, |_, resolution| {
605 resolution.single_imports.remove(&PtrKey(directive));
608 Ok(binding) if !binding.is_importable() => {
609 let msg = format!("`{}` is not directly importable", target);
610 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
611 .span_label(directive.span, "cannot be imported directly")
613 // Do not import this illegal binding. Import a dummy binding and pretend
614 // everything is fine
615 this.import_dummy_binding(directive);
618 let imported_binding = this.import(binding, directive);
619 let conflict = this.try_define(parent, target, ns, imported_binding);
620 if let Err(old_binding) = conflict {
621 this.report_conflict(parent, target, ns, imported_binding, old_binding);
630 // If appropriate, returns an error to report.
631 fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
632 self.current_module = directive.parent;
633 let ImportDirective { ref module_path, span, .. } = *directive;
634 let mut warn_if_binding_comes_from_local_crate = false;
636 // FIXME: Last path segment is treated specially in import resolution, so extern crate
637 // mode for absolute paths needs some special support for single-segment imports.
638 if module_path.len() == 1 && (module_path[0].name == keywords::CrateRoot.name() ||
639 module_path[0].name == keywords::Extern.name()) {
640 let is_extern = module_path[0].name == keywords::Extern.name() ||
641 (self.session.features_untracked().extern_absolute_paths &&
642 self.session.rust_2018());
643 match directive.subclass {
644 GlobImport { .. } if is_extern => {
645 return Some((directive.span,
646 "cannot glob-import all possible crates".to_string()));
648 GlobImport { .. } if self.session.features_untracked().extern_absolute_paths => {
649 self.lint_path_starts_with_module(
654 SingleImport { source, target, .. } => {
655 let crate_root = if source.name == keywords::Crate.name() &&
656 module_path[0].name != keywords::Extern.name() {
657 if target.name == keywords::Crate.name() {
658 return Some((directive.span,
659 "crate root imports need to be explicitly named: \
660 `use crate as name;`".to_string()));
662 Some(self.resolve_crate_root(source))
664 } else if is_extern && !source.is_path_segment_keyword() {
666 self.resolver.crate_loader.process_use_extern(
670 &self.resolver.definitions,
673 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
674 self.populate_module_if_necessary(crate_root);
677 warn_if_binding_comes_from_local_crate = true;
681 if let Some(crate_root) = crate_root {
682 let binding = (crate_root, ty::Visibility::Public, directive.span,
683 directive.expansion).to_name_binding(self.arenas);
684 let binding = self.arenas.alloc_name_binding(NameBinding {
685 kind: NameBindingKind::Import {
688 used: Cell::new(false),
690 vis: directive.vis.get(),
691 span: directive.span,
692 expansion: directive.expansion,
694 let _ = self.try_define(directive.parent, target, TypeNS, binding);
695 let import = self.import_map.entry(directive.id).or_default();
696 import[TypeNS] = Some(PathResolution::new(binding.def()));
704 let module_result = self.resolve_path(
709 directive.crate_lint(),
711 let module = match module_result {
712 PathResult::Module(module) => module,
713 PathResult::Failed(span, msg, false) => {
714 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
717 PathResult::Failed(span, msg, true) => {
718 let (mut self_path, mut self_result) = (module_path.clone(), None);
719 let is_special = |ident: Ident| ident.is_path_segment_keyword() &&
720 ident.name != keywords::CrateRoot.name();
721 if !self_path.is_empty() && !is_special(self_path[0]) &&
722 !(self_path.len() > 1 && is_special(self_path[1])) {
723 self_path[0].name = keywords::SelfValue.name();
724 self_result = Some(self.resolve_path(&self_path, None, false,
725 span, CrateLint::No));
727 return if let Some(PathResult::Module(..)) = self_result {
728 Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
736 let (ident, result, type_ns_only) = match directive.subclass {
737 SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
738 GlobImport { .. } if module.def_id() == directive.parent.def_id() => {
739 // Importing a module into itself is not allowed.
740 return Some((directive.span,
741 "Cannot glob-import a module into itself.".to_string()));
743 GlobImport { is_prelude, ref max_vis } => {
745 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
746 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
747 let msg = "A non-empty glob must import something with the glob's visibility";
748 self.session.span_err(directive.span, msg);
755 let mut all_ns_err = true;
756 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
757 if let Ok(binding) = result[ns].get() {
759 if this.record_use(ident, ns, binding, directive.span) {
760 this.resolution(module, ident, ns).borrow_mut().binding =
761 Some(this.dummy_binding);
767 let mut all_ns_failed = true;
768 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
769 match this.resolve_ident_in_module(module, ident, ns, true, span) {
770 Ok(_) => all_ns_failed = false,
775 return if all_ns_failed {
776 let resolutions = module.resolutions.borrow();
777 let names = resolutions.iter().filter_map(|(&(ref i, _), resolution)| {
778 if *i == ident { return None; } // Never suggest the same name
779 match *resolution.borrow() {
780 NameResolution { binding: Some(name_binding), .. } => {
781 match name_binding.kind {
782 NameBindingKind::Import { binding, .. } => {
784 // Never suggest the name that has binding error
785 // i.e. the name that cannot be previously resolved
786 NameBindingKind::Def(Def::Err, _) => return None,
793 NameResolution { ref single_imports, .. }
794 if single_imports.is_empty() => None,
799 match find_best_match_for_name(names, &ident.as_str(), None) {
800 Some(name) => format!(". Did you mean to use `{}`?", name),
801 None => "".to_owned(),
803 let module_str = module_to_string(module);
804 let msg = if let Some(module_str) = module_str {
805 format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
807 format!("no `{}` in the root{}", ident, lev_suggestion)
811 // `resolve_ident_in_module` reported a privacy error.
812 self.import_dummy_binding(directive);
817 let mut reexport_error = None;
818 let mut any_successful_reexport = false;
819 self.per_ns(|this, ns| {
820 if let Ok(binding) = result[ns].get() {
821 let vis = directive.vis.get();
822 if !binding.pseudo_vis().is_at_least(vis, &*this) {
823 reexport_error = Some((ns, binding));
825 any_successful_reexport = true;
830 // All namespaces must be re-exported with extra visibility for an error to occur.
831 if !any_successful_reexport {
832 let (ns, binding) = reexport_error.unwrap();
833 if ns == TypeNS && binding.is_extern_crate() {
834 let msg = format!("extern crate `{}` is private, and cannot be \
835 re-exported (error E0365), consider declaring with \
838 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
842 } else if ns == TypeNS {
843 struct_span_err!(self.session, directive.span, E0365,
844 "`{}` is private, and cannot be re-exported", ident)
845 .span_label(directive.span, format!("re-export of private `{}`", ident))
846 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
849 let msg = format!("`{}` is private, and cannot be re-exported", ident);
851 format!("consider marking `{}` as `pub` in the imported module", ident);
852 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
853 .span_note(directive.span, ¬e_msg)
858 if warn_if_binding_comes_from_local_crate {
859 let mut warned = false;
860 self.per_ns(|this, ns| {
861 let binding = match result[ns].get().ok() {
865 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
866 if let ImportDirectiveSubclass::ExternCrate(..) = d.subclass {
874 this.lint_path_starts_with_module(
881 // Record what this import resolves to for later uses in documentation,
882 // this may resolve to either a value or a type, but for documentation
883 // purposes it's good enough to just favor one over the other.
884 self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
885 let import = this.import_map.entry(directive.id).or_default();
886 import[ns] = Some(PathResolution::new(binding.def()));
889 debug!("(resolving single import) successfully resolved import");
893 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
894 let module = directive.imported_module.get().unwrap();
895 self.populate_module_if_necessary(module);
897 if let Some(Def::Trait(_)) = module.def() {
898 self.session.span_err(directive.span, "items in traits are not importable.");
900 } else if module.def_id() == directive.parent.def_id() {
902 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
903 self.prelude = Some(module);
907 // Add to module's glob_importers
908 module.glob_importers.borrow_mut().push(directive);
910 // Ensure that `resolutions` isn't borrowed during `try_define`,
911 // since it might get updated via a glob cycle.
912 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
913 resolution.borrow().binding().map(|binding| (ident, binding))
914 }).collect::<Vec<_>>();
915 for ((mut ident, ns), binding) in bindings {
916 let scope = match ident.span.reverse_glob_adjust(module.expansion,
917 directive.span.ctxt().modern()) {
918 Some(Some(def)) => self.macro_def_scope(def),
919 Some(None) => self.current_module,
922 if self.is_accessible_from(binding.pseudo_vis(), scope) {
923 let imported_binding = self.import(binding, directive);
924 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
928 // Record the destination of this import
929 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
932 // Miscellaneous post-processing, including recording re-exports,
933 // reporting conflicts, and reporting unresolved imports.
934 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
935 // Since import resolution is finished, globs will not define any more names.
936 *module.globs.borrow_mut() = Vec::new();
938 let mut reexports = Vec::new();
939 let mut exported_macro_names = FxHashMap();
940 if ptr::eq(module, self.graph_root) {
941 let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
942 for export in macro_exports.into_iter().rev() {
943 if let Some(later_span) = exported_macro_names.insert(export.ident.modern(),
945 self.session.buffer_lint_with_diagnostic(
946 DUPLICATE_MACRO_EXPORTS,
949 &format!("a macro named `{}` has already been exported", export.ident),
950 BuiltinLintDiagnostics::DuplicatedMacroExports(
951 export.ident, export.span, later_span));
953 reexports.push(export);
958 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
959 let resolution = &mut *resolution.borrow_mut();
960 let binding = match resolution.binding {
961 Some(binding) => binding,
965 if binding.is_import() || binding.is_macro_def() {
966 let def = binding.def();
968 if !def.def_id().is_local() {
969 self.cstore.export_macros_untracked(def.def_id().krate);
971 if let Def::Macro(..) = def {
972 if let Some(&span) = exported_macro_names.get(&ident.modern()) {
974 format!("a macro named `{}` has already been exported", ident);
975 self.session.struct_span_err(span, &msg)
976 .span_label(span, format!("`{}` already exported", ident))
977 .span_note(binding.span, "previous macro export here")
981 reexports.push(Export {
982 ident: ident.modern(),
991 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
992 if ns == TypeNS && orig_binding.is_variant() &&
993 !orig_binding.vis.is_at_least(binding.vis, &*self) {
994 let msg = match directive.subclass {
995 ImportDirectiveSubclass::SingleImport { .. } => {
996 format!("variant `{}` is private and cannot be re-exported",
999 ImportDirectiveSubclass::GlobImport { .. } => {
1000 let msg = "enum is private and its variants \
1001 cannot be re-exported".to_owned();
1002 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1005 let fresh = self.session.one_time_diagnostics
1006 .borrow_mut().insert(error_id);
1012 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1014 let mut err = self.session.struct_span_err(binding.span, &msg);
1016 let imported_module = directive.imported_module.get()
1017 .expect("module should exist");
1018 let resolutions = imported_module.parent.expect("parent should exist")
1019 .resolutions.borrow();
1020 let enum_path_segment_index = directive.module_path.len() - 1;
1021 let enum_ident = directive.module_path[enum_path_segment_index];
1023 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1024 .expect("resolution should exist");
1025 let enum_span = enum_resolution.borrow()
1026 .binding.expect("binding should exist")
1028 let enum_def_span = self.session.codemap().def_span(enum_span);
1029 let enum_def_snippet = self.session.codemap()
1030 .span_to_snippet(enum_def_span).expect("snippet should exist");
1031 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1032 let after_vis_index = enum_def_snippet.find("enum")
1033 .expect("`enum` keyword should exist in snippet");
1034 let suggestion = format!("pub {}",
1035 &enum_def_snippet[after_vis_index..]);
1038 .diag_span_suggestion_once(&mut err,
1039 DiagnosticMessageId::ErrorId(0),
1041 "consider making the enum public",
1050 if reexports.len() > 0 {
1051 if let Some(def_id) = module.def_id() {
1052 self.export_map.insert(def_id, reexports);
1058 fn import_path_to_string(names: &[Ident],
1059 subclass: &ImportDirectiveSubclass,
1060 span: Span) -> String {
1061 let pos = names.iter()
1062 .position(|p| span == p.span && p.name != keywords::CrateRoot.name());
1063 let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
1064 if let Some(pos) = pos {
1065 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1066 names_to_string(names)
1068 let names = if global { &names[1..] } else { names };
1069 if names.is_empty() {
1070 import_directive_subclass_to_string(subclass)
1073 names_to_string(names),
1074 import_directive_subclass_to_string(subclass))
1079 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1081 SingleImport { source, .. } => source.to_string(),
1082 GlobImport { .. } => "*".to_string(),
1083 ExternCrate(_) => "<extern crate>".to_string(),
1084 MacroUse => "#[macro_use]".to_string(),