]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/imports.rs
Rollup merge of #68424 - estebank:suggest-borrow-for-non-copy-vec, r=davidtwco
[rust.git] / src / librustc_resolve / imports.rs
1 //! A bunch of methods and structures more or less related to resolving imports.
2
3 use ImportDirectiveSubclass::*;
4
5 use crate::diagnostics::Suggestion;
6 use crate::Determinacy::{self, *};
7 use crate::Namespace::{self, MacroNS, TypeNS};
8 use crate::{module_to_string, names_to_string};
9 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
10 use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
11 use crate::{CrateLint, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
12 use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
13
14 use rustc::hir::exports::Export;
15 use rustc::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
16 use rustc::ty;
17 use rustc::{bug, span_bug};
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::ptr_key::PtrKey;
20 use rustc_errors::{pluralize, struct_span_err, Applicability};
21 use rustc_hir::def::{self, PartialRes};
22 use rustc_hir::def_id::DefId;
23 use rustc_session::lint::BuiltinLintDiagnostics;
24 use rustc_session::DiagnosticMessageId;
25 use rustc_span::hygiene::ExpnId;
26 use rustc_span::symbol::kw;
27 use rustc_span::{MultiSpan, Span};
28 use syntax::ast::{Ident, Name, NodeId};
29 use syntax::unwrap_or;
30 use syntax::util::lev_distance::find_best_match_for_name;
31
32 use log::*;
33
34 use std::cell::Cell;
35 use std::{mem, ptr};
36
37 type Res = def::Res<NodeId>;
38
39 /// Contains data for specific types of import directives.
40 #[derive(Clone, Debug)]
41 pub enum ImportDirectiveSubclass<'a> {
42     SingleImport {
43         /// `source` in `use prefix::source as target`.
44         source: Ident,
45         /// `target` in `use prefix::source as target`.
46         target: Ident,
47         /// Bindings to which `source` refers to.
48         source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
49         /// Bindings introduced by `target`.
50         target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
51         /// `true` for `...::{self [as target]}` imports, `false` otherwise.
52         type_ns_only: bool,
53         /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
54         nested: bool,
55     },
56     GlobImport {
57         is_prelude: bool,
58         max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
59                                        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
60     },
61     ExternCrate {
62         source: Option<Name>,
63         target: Ident,
64     },
65     MacroUse,
66 }
67
68 /// One import directive.
69 #[derive(Debug, Clone)]
70 crate struct ImportDirective<'a> {
71     /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
72     ///
73     /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
74     /// this id is the ID of the leaf tree. For example:
75     ///
76     /// ```ignore (pacify the mercilous tidy)
77     /// use foo::bar::{a, b}
78     /// ```
79     ///
80     /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
81     /// for `a` in this field.
82     pub id: NodeId,
83
84     /// The `id` of the "root" use-kind -- this is always the same as
85     /// `id` except in the case of "nested" use trees, in which case
86     /// it will be the `id` of the root use tree. e.g., in the example
87     /// from `id`, this would be the ID of the `use foo::bar`
88     /// `UseTree` node.
89     pub root_id: NodeId,
90
91     /// Span of the entire use statement.
92     pub use_span: Span,
93
94     /// Span of the entire use statement with attributes.
95     pub use_span_with_attributes: Span,
96
97     /// Did the use statement have any attributes?
98     pub has_attributes: bool,
99
100     /// Span of this use tree.
101     pub span: Span,
102
103     /// Span of the *root* use tree (see `root_id`).
104     pub root_span: Span,
105
106     pub parent_scope: ParentScope<'a>,
107     pub module_path: Vec<Segment>,
108     /// The resolution of `module_path`.
109     pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
110     pub subclass: ImportDirectiveSubclass<'a>,
111     pub vis: Cell<ty::Visibility>,
112     pub used: Cell<bool>,
113 }
114
115 impl<'a> ImportDirective<'a> {
116     pub fn is_glob(&self) -> bool {
117         match self.subclass {
118             ImportDirectiveSubclass::GlobImport { .. } => true,
119             _ => false,
120         }
121     }
122
123     pub fn is_nested(&self) -> bool {
124         match self.subclass {
125             ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
126             _ => false,
127         }
128     }
129
130     crate fn crate_lint(&self) -> CrateLint {
131         CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
132     }
133 }
134
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>>,
144 }
145
146 impl<'a> NameResolution<'a> {
147     // Returns the binding for the name if it is known or None if it not known.
148     pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
149         self.binding.and_then(|binding| {
150             if !binding.is_glob_import() || self.single_imports.is_empty() {
151                 Some(binding)
152             } else {
153                 None
154             }
155         })
156     }
157
158     crate fn add_single_import(&mut self, directive: &'a ImportDirective<'a>) {
159         self.single_imports.insert(PtrKey(directive));
160     }
161 }
162
163 impl<'a> Resolver<'a> {
164     crate fn resolve_ident_in_module_unadjusted(
165         &mut self,
166         module: ModuleOrUniformRoot<'a>,
167         ident: Ident,
168         ns: Namespace,
169         parent_scope: &ParentScope<'a>,
170         record_used: bool,
171         path_span: Span,
172     ) -> Result<&'a NameBinding<'a>, Determinacy> {
173         self.resolve_ident_in_module_unadjusted_ext(
174             module,
175             ident,
176             ns,
177             parent_scope,
178             false,
179             record_used,
180             path_span,
181         )
182         .map_err(|(determinacy, _)| determinacy)
183     }
184
185     /// Attempts to resolve `ident` in namespaces `ns` of `module`.
186     /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
187     crate fn resolve_ident_in_module_unadjusted_ext(
188         &mut self,
189         module: ModuleOrUniformRoot<'a>,
190         ident: Ident,
191         ns: Namespace,
192         parent_scope: &ParentScope<'a>,
193         restricted_shadowing: bool,
194         record_used: bool,
195         path_span: Span,
196     ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
197         let module = match module {
198             ModuleOrUniformRoot::Module(module) => module,
199             ModuleOrUniformRoot::CrateRootAndExternPrelude => {
200                 assert!(!restricted_shadowing);
201                 let binding = self.early_resolve_ident_in_lexical_scope(
202                     ident,
203                     ScopeSet::AbsolutePath(ns),
204                     parent_scope,
205                     record_used,
206                     record_used,
207                     path_span,
208                 );
209                 return binding.map_err(|determinacy| (determinacy, Weak::No));
210             }
211             ModuleOrUniformRoot::ExternPrelude => {
212                 assert!(!restricted_shadowing);
213                 return if ns != TypeNS {
214                     Err((Determined, Weak::No))
215                 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
216                     Ok(binding)
217                 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
218                     // Macro-expanded `extern crate` items can add names to extern prelude.
219                     Err((Undetermined, Weak::No))
220                 } else {
221                     Err((Determined, Weak::No))
222                 };
223             }
224             ModuleOrUniformRoot::CurrentScope => {
225                 assert!(!restricted_shadowing);
226                 if ns == TypeNS {
227                     if ident.name == kw::Crate || ident.name == kw::DollarCrate {
228                         let module = self.resolve_crate_root(ident);
229                         let binding = (module, ty::Visibility::Public, module.span, ExpnId::root())
230                             .to_name_binding(self.arenas);
231                         return Ok(binding);
232                     } else if ident.name == kw::Super || ident.name == kw::SelfLower {
233                         // FIXME: Implement these with renaming requirements so that e.g.
234                         // `use super;` doesn't work, but `use super as name;` does.
235                         // Fall through here to get an error from `early_resolve_...`.
236                     }
237                 }
238
239                 let scopes = ScopeSet::All(ns, true);
240                 let binding = self.early_resolve_ident_in_lexical_scope(
241                     ident,
242                     scopes,
243                     parent_scope,
244                     record_used,
245                     record_used,
246                     path_span,
247                 );
248                 return binding.map_err(|determinacy| (determinacy, Weak::No));
249             }
250         };
251
252         let key = self.new_key(ident, ns);
253         let resolution =
254             self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
255
256         if let Some(binding) = resolution.binding {
257             if !restricted_shadowing && binding.expansion != ExpnId::root() {
258                 if let NameBindingKind::Res(_, true) = binding.kind {
259                     self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
260                 }
261             }
262         }
263
264         let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
265             if let Some(blacklisted_binding) = this.blacklisted_binding {
266                 if ptr::eq(binding, blacklisted_binding) {
267                     return Err((Determined, Weak::No));
268                 }
269             }
270             // `extern crate` are always usable for backwards compatibility, see issue #37020,
271             // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
272             let usable = this.is_accessible_from(binding.vis, parent_scope.module)
273                 || binding.is_extern_crate();
274             if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
275         };
276
277         if record_used {
278             return resolution
279                 .binding
280                 .and_then(|binding| {
281                     // If the primary binding is blacklisted, search further and return the shadowed
282                     // glob binding if it exists. What we really want here is having two separate
283                     // scopes in a module - one for non-globs and one for globs, but until that's done
284                     // use this hack to avoid inconsistent resolution ICEs during import validation.
285                     if let Some(blacklisted_binding) = self.blacklisted_binding {
286                         if ptr::eq(binding, blacklisted_binding) {
287                             return resolution.shadowed_glob;
288                         }
289                     }
290                     Some(binding)
291                 })
292                 .ok_or((Determined, Weak::No))
293                 .and_then(|binding| {
294                     if self.last_import_segment && check_usable(self, binding).is_err() {
295                         Err((Determined, Weak::No))
296                     } else {
297                         self.record_use(ident, ns, binding, restricted_shadowing);
298
299                         if let Some(shadowed_glob) = resolution.shadowed_glob {
300                             // Forbid expanded shadowing to avoid time travel.
301                             if restricted_shadowing
302                                 && binding.expansion != ExpnId::root()
303                                 && binding.res() != shadowed_glob.res()
304                             {
305                                 self.ambiguity_errors.push(AmbiguityError {
306                                     kind: AmbiguityKind::GlobVsExpanded,
307                                     ident,
308                                     b1: binding,
309                                     b2: shadowed_glob,
310                                     misc1: AmbiguityErrorMisc::None,
311                                     misc2: AmbiguityErrorMisc::None,
312                                 });
313                             }
314                         }
315
316                         if !self.is_accessible_from(binding.vis, parent_scope.module) &&
317                        // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
318                        !(self.last_import_segment && binding.is_extern_crate())
319                         {
320                             self.privacy_errors.push(PrivacyError {
321                                 ident,
322                                 binding,
323                                 dedup_span: path_span,
324                             });
325                         }
326
327                         Ok(binding)
328                     }
329                 });
330         }
331
332         // Items and single imports are not shadowable, if we have one, then it's determined.
333         if let Some(binding) = resolution.binding {
334             if !binding.is_glob_import() {
335                 return check_usable(self, binding);
336             }
337         }
338
339         // --- From now on we either have a glob resolution or no resolution. ---
340
341         // Check if one of single imports can still define the name,
342         // if it can then our result is not determined and can be invalidated.
343         for single_import in &resolution.single_imports {
344             if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
345                 continue;
346             }
347             let module = unwrap_or!(
348                 single_import.imported_module.get(),
349                 return Err((Undetermined, Weak::No))
350             );
351             let ident = match single_import.subclass {
352                 SingleImport { source, .. } => source,
353                 _ => unreachable!(),
354             };
355             match self.resolve_ident_in_module(
356                 module,
357                 ident,
358                 ns,
359                 &single_import.parent_scope,
360                 false,
361                 path_span,
362             ) {
363                 Err(Determined) => continue,
364                 Ok(binding)
365                     if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
366                 {
367                     continue;
368                 }
369                 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
370             }
371         }
372
373         // So we have a resolution that's from a glob import. This resolution is determined
374         // if it cannot be shadowed by some new item/import expanded from a macro.
375         // This happens either if there are no unexpanded macros, or expanded names cannot
376         // shadow globs (that happens in macro namespace or with restricted shadowing).
377         //
378         // Additionally, any macro in any module can plant names in the root module if it creates
379         // `macro_export` macros, so the root module effectively has unresolved invocations if any
380         // module has unresolved invocations.
381         // However, it causes resolution/expansion to stuck too often (#53144), so, to make
382         // progress, we have to ignore those potential unresolved invocations from other modules
383         // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
384         // shadowing is enabled, see `macro_expanded_macro_export_errors`).
385         let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
386         if let Some(binding) = resolution.binding {
387             if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
388                 return check_usable(self, binding);
389             } else {
390                 return Err((Undetermined, Weak::No));
391             }
392         }
393
394         // --- From now on we have no resolution. ---
395
396         // Now we are in situation when new item/import can appear only from a glob or a macro
397         // expansion. With restricted shadowing names from globs and macro expansions cannot
398         // shadow names from outer scopes, so we can freely fallback from module search to search
399         // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
400         // scopes we return `Undetermined` with `Weak::Yes`.
401
402         // Check if one of unexpanded macros can still define the name,
403         // if it can then our "no resolution" result is not determined and can be invalidated.
404         if unexpanded_macros {
405             return Err((Undetermined, Weak::Yes));
406         }
407
408         // Check if one of glob imports can still define the name,
409         // if it can then our "no resolution" result is not determined and can be invalidated.
410         for glob_import in module.globs.borrow().iter() {
411             if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
412                 continue;
413             }
414             let module = match glob_import.imported_module.get() {
415                 Some(ModuleOrUniformRoot::Module(module)) => module,
416                 Some(_) => continue,
417                 None => return Err((Undetermined, Weak::Yes)),
418             };
419             let tmp_parent_scope;
420             let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern());
421             match ident.span.glob_adjust(module.expansion, glob_import.span) {
422                 Some(Some(def)) => {
423                     tmp_parent_scope =
424                         ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
425                     adjusted_parent_scope = &tmp_parent_scope;
426                 }
427                 Some(None) => {}
428                 None => continue,
429             };
430             let result = self.resolve_ident_in_module_unadjusted(
431                 ModuleOrUniformRoot::Module(module),
432                 ident,
433                 ns,
434                 adjusted_parent_scope,
435                 false,
436                 path_span,
437             );
438
439             match result {
440                 Err(Determined) => continue,
441                 Ok(binding)
442                     if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
443                 {
444                     continue;
445                 }
446                 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
447             }
448         }
449
450         // No resolution and no one else can define the name - determinate error.
451         Err((Determined, Weak::No))
452     }
453
454     // Given a binding and an import directive that resolves to it,
455     // return the corresponding binding defined by the import directive.
456     crate fn import(
457         &self,
458         binding: &'a NameBinding<'a>,
459         directive: &'a ImportDirective<'a>,
460     ) -> &'a NameBinding<'a> {
461         let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
462                      // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
463                      !directive.is_glob() && binding.is_extern_crate()
464         {
465             directive.vis.get()
466         } else {
467             binding.pseudo_vis()
468         };
469
470         if let GlobImport { ref max_vis, .. } = directive.subclass {
471             if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
472                 max_vis.set(vis)
473             }
474         }
475
476         self.arenas.alloc_name_binding(NameBinding {
477             kind: NameBindingKind::Import { binding, directive, used: Cell::new(false) },
478             ambiguity: None,
479             span: directive.span,
480             vis,
481             expansion: directive.parent_scope.expansion,
482         })
483     }
484
485     // Define the name or return the existing binding if there is a collision.
486     crate fn try_define(
487         &mut self,
488         module: Module<'a>,
489         key: BindingKey,
490         binding: &'a NameBinding<'a>,
491     ) -> Result<(), &'a NameBinding<'a>> {
492         let res = binding.res();
493         self.check_reserved_macro_name(key.ident, res);
494         self.set_binding_parent_module(binding, module);
495         self.update_resolution(module, key, |this, resolution| {
496             if let Some(old_binding) = resolution.binding {
497                 if res == Res::Err {
498                     // Do not override real bindings with `Res::Err`s from error recovery.
499                     return Ok(());
500                 }
501                 match (old_binding.is_glob_import(), binding.is_glob_import()) {
502                     (true, true) => {
503                         if res != old_binding.res() {
504                             resolution.binding = Some(this.ambiguity(
505                                 AmbiguityKind::GlobVsGlob,
506                                 old_binding,
507                                 binding,
508                             ));
509                         } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
510                             // We are glob-importing the same item but with greater visibility.
511                             resolution.binding = Some(binding);
512                         }
513                     }
514                     (old_glob @ true, false) | (old_glob @ false, true) => {
515                         let (glob_binding, nonglob_binding) =
516                             if old_glob { (old_binding, binding) } else { (binding, old_binding) };
517                         if glob_binding.res() != nonglob_binding.res()
518                             && key.ns == MacroNS
519                             && nonglob_binding.expansion != ExpnId::root()
520                         {
521                             resolution.binding = Some(this.ambiguity(
522                                 AmbiguityKind::GlobVsExpanded,
523                                 nonglob_binding,
524                                 glob_binding,
525                             ));
526                         } else {
527                             resolution.binding = Some(nonglob_binding);
528                         }
529                         resolution.shadowed_glob = Some(glob_binding);
530                     }
531                     (false, false) => {
532                         return Err(old_binding);
533                     }
534                 }
535             } else {
536                 resolution.binding = Some(binding);
537             }
538
539             Ok(())
540         })
541     }
542
543     fn ambiguity(
544         &self,
545         kind: AmbiguityKind,
546         primary_binding: &'a NameBinding<'a>,
547         secondary_binding: &'a NameBinding<'a>,
548     ) -> &'a NameBinding<'a> {
549         self.arenas.alloc_name_binding(NameBinding {
550             ambiguity: Some((secondary_binding, kind)),
551             ..primary_binding.clone()
552         })
553     }
554
555     // Use `f` to mutate the resolution of the name in the module.
556     // If the resolution becomes a success, define it in the module's glob importers.
557     fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
558     where
559         F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
560     {
561         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
562         // during which the resolution might end up getting re-defined via a glob cycle.
563         let (binding, t) = {
564             let resolution = &mut *self.resolution(module, key).borrow_mut();
565             let old_binding = resolution.binding();
566
567             let t = f(self, resolution);
568
569             match resolution.binding() {
570                 _ if old_binding.is_some() => return t,
571                 None => return t,
572                 Some(binding) => match old_binding {
573                     Some(old_binding) if ptr::eq(old_binding, binding) => return t,
574                     _ => (binding, t),
575                 },
576             }
577         };
578
579         // Define `binding` in `module`s glob importers.
580         for directive in module.glob_importers.borrow_mut().iter() {
581             let mut ident = key.ident;
582             let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
583                 Some(Some(def)) => self.macro_def_scope(def),
584                 Some(None) => directive.parent_scope.module,
585                 None => continue,
586             };
587             if self.is_accessible_from(binding.vis, scope) {
588                 let imported_binding = self.import(binding, directive);
589                 let key = BindingKey { ident, ..key };
590                 let _ = self.try_define(directive.parent_scope.module, key, imported_binding);
591             }
592         }
593
594         t
595     }
596
597     // Define a "dummy" resolution containing a Res::Err as a placeholder for a
598     // failed resolution
599     fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
600         if let SingleImport { target, .. } = directive.subclass {
601             let dummy_binding = self.dummy_binding;
602             let dummy_binding = self.import(dummy_binding, directive);
603             self.per_ns(|this, ns| {
604                 let key = this.new_key(target, ns);
605                 let _ = this.try_define(directive.parent_scope.module, key, dummy_binding);
606                 // Consider erroneous imports used to avoid duplicate diagnostics.
607                 this.record_use(target, ns, dummy_binding, false);
608             });
609         }
610     }
611 }
612
613 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
614 /// import errors within the same use tree into a single diagnostic.
615 #[derive(Debug, Clone)]
616 struct UnresolvedImportError {
617     span: Span,
618     label: Option<String>,
619     note: Vec<String>,
620     suggestion: Option<Suggestion>,
621 }
622
623 pub struct ImportResolver<'a, 'b> {
624     pub r: &'a mut Resolver<'b>,
625 }
626
627 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
628     fn parent(self, id: DefId) -> Option<DefId> {
629         self.r.parent(id)
630     }
631 }
632
633 impl<'a, 'b> ImportResolver<'a, 'b> {
634     // Import resolution
635     //
636     // This is a fixed-point algorithm. We resolve imports until our efforts
637     // are stymied by an unresolved import; then we bail out of the current
638     // module and continue. We terminate successfully once no more imports
639     // remain or unsuccessfully when no forward progress in resolving imports
640     // is made.
641
642     /// Resolves all imports for the crate. This method performs the fixed-
643     /// point iteration.
644     pub fn resolve_imports(&mut self) {
645         let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
646         while self.r.indeterminate_imports.len() < prev_num_indeterminates {
647             prev_num_indeterminates = self.r.indeterminate_imports.len();
648             for import in mem::take(&mut self.r.indeterminate_imports) {
649                 match self.resolve_import(&import) {
650                     true => self.r.determined_imports.push(import),
651                     false => self.r.indeterminate_imports.push(import),
652                 }
653             }
654         }
655     }
656
657     pub fn finalize_imports(&mut self) {
658         for module in self.r.arenas.local_modules().iter() {
659             self.finalize_resolutions_in(module);
660         }
661
662         let mut seen_spans = FxHashSet::default();
663         let mut errors = vec![];
664         let mut prev_root_id: NodeId = NodeId::from_u32(0);
665         let determined_imports = mem::take(&mut self.r.determined_imports);
666         let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
667
668         for (is_indeterminate, import) in determined_imports
669             .into_iter()
670             .map(|i| (false, i))
671             .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
672         {
673             if let Some(err) = self.finalize_import(import) {
674                 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
675                     if source.name == kw::SelfLower {
676                         // Silence `unresolved import` error if E0429 is already emitted
677                         if let Err(Determined) = source_bindings.value_ns.get() {
678                             continue;
679                         }
680                     }
681                 }
682
683                 // If the error is a single failed import then create a "fake" import
684                 // resolution for it so that later resolve stages won't complain.
685                 self.r.import_dummy_binding(import);
686                 if prev_root_id.as_u32() != 0
687                     && prev_root_id.as_u32() != import.root_id.as_u32()
688                     && !errors.is_empty()
689                 {
690                     // In the case of a new import line, throw a diagnostic message
691                     // for the previous line.
692                     self.throw_unresolved_import_error(errors, None);
693                     errors = vec![];
694                 }
695                 if seen_spans.insert(err.span) {
696                     let path = import_path_to_string(
697                         &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
698                         &import.subclass,
699                         err.span,
700                     );
701                     errors.push((path, err));
702                     prev_root_id = import.root_id;
703                 }
704             } else if is_indeterminate {
705                 // Consider erroneous imports used to avoid duplicate diagnostics.
706                 self.r.used_imports.insert((import.id, TypeNS));
707                 let path = import_path_to_string(
708                     &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
709                     &import.subclass,
710                     import.span,
711                 );
712                 let err = UnresolvedImportError {
713                     span: import.span,
714                     label: None,
715                     note: Vec::new(),
716                     suggestion: None,
717                 };
718                 errors.push((path, err));
719             }
720         }
721
722         if !errors.is_empty() {
723             self.throw_unresolved_import_error(errors, None);
724         }
725     }
726
727     fn throw_unresolved_import_error(
728         &self,
729         errors: Vec<(String, UnresolvedImportError)>,
730         span: Option<MultiSpan>,
731     ) {
732         /// Upper limit on the number of `span_label` messages.
733         const MAX_LABEL_COUNT: usize = 10;
734
735         let (span, msg) = if errors.is_empty() {
736             (span.unwrap(), "unresolved import".to_string())
737         } else {
738             let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
739
740             let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
741
742             let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
743
744             (span, msg)
745         };
746
747         let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
748
749         if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
750             for message in note {
751                 diag.note(&message);
752             }
753         }
754
755         for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
756             if let Some(label) = err.label {
757                 diag.span_label(err.span, label);
758             }
759
760             if let Some((suggestions, msg, applicability)) = err.suggestion {
761                 diag.multipart_suggestion(&msg, suggestions, applicability);
762             }
763         }
764
765         diag.emit();
766     }
767
768     /// Attempts to resolve the given import, returning true if its resolution is determined.
769     /// If successful, the resolved bindings are written into the module.
770     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
771         debug!(
772             "(resolving import for module) resolving import `{}::...` in `{}`",
773             Segment::names_to_string(&directive.module_path),
774             module_to_string(directive.parent_scope.module).unwrap_or_else(|| "???".to_string()),
775         );
776
777         let module = if let Some(module) = directive.imported_module.get() {
778             module
779         } else {
780             // For better failure detection, pretend that the import will
781             // not define any names while resolving its module path.
782             let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
783             let path_res = self.r.resolve_path(
784                 &directive.module_path,
785                 None,
786                 &directive.parent_scope,
787                 false,
788                 directive.span,
789                 directive.crate_lint(),
790             );
791             directive.vis.set(orig_vis);
792
793             match path_res {
794                 PathResult::Module(module) => module,
795                 PathResult::Indeterminate => return false,
796                 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
797             }
798         };
799
800         directive.imported_module.set(Some(module));
801         let (source, target, source_bindings, target_bindings, type_ns_only) =
802             match directive.subclass {
803                 SingleImport {
804                     source,
805                     target,
806                     ref source_bindings,
807                     ref target_bindings,
808                     type_ns_only,
809                     ..
810                 } => (source, target, source_bindings, target_bindings, type_ns_only),
811                 GlobImport { .. } => {
812                     self.resolve_glob_import(directive);
813                     return true;
814                 }
815                 _ => unreachable!(),
816             };
817
818         let mut indeterminate = false;
819         self.r.per_ns(|this, ns| {
820             if !type_ns_only || ns == TypeNS {
821                 if let Err(Undetermined) = source_bindings[ns].get() {
822                     // For better failure detection, pretend that the import will
823                     // not define any names while resolving its module path.
824                     let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
825                     let binding = this.resolve_ident_in_module(
826                         module,
827                         source,
828                         ns,
829                         &directive.parent_scope,
830                         false,
831                         directive.span,
832                     );
833                     directive.vis.set(orig_vis);
834
835                     source_bindings[ns].set(binding);
836                 } else {
837                     return;
838                 };
839
840                 let parent = directive.parent_scope.module;
841                 match source_bindings[ns].get() {
842                     Err(Undetermined) => indeterminate = true,
843                     // Don't update the resolution, because it was never added.
844                     Err(Determined) if target.name == kw::Underscore => {}
845                     Err(Determined) => {
846                         let key = this.new_key(target, ns);
847                         this.update_resolution(parent, key, |_, resolution| {
848                             resolution.single_imports.remove(&PtrKey(directive));
849                         });
850                     }
851                     Ok(binding) if !binding.is_importable() => {
852                         let msg = format!("`{}` is not directly importable", target);
853                         struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
854                             .span_label(directive.span, "cannot be imported directly")
855                             .emit();
856                         // Do not import this illegal binding. Import a dummy binding and pretend
857                         // everything is fine
858                         this.import_dummy_binding(directive);
859                     }
860                     Ok(binding) => {
861                         let imported_binding = this.import(binding, directive);
862                         target_bindings[ns].set(Some(imported_binding));
863                         this.define(parent, target, ns, imported_binding);
864                     }
865                 }
866             }
867         });
868
869         !indeterminate
870     }
871
872     /// Performs final import resolution, consistency checks and error reporting.
873     ///
874     /// Optionally returns an unresolved import error. This error is buffered and used to
875     /// consolidate multiple unresolved import errors into a single diagnostic.
876     fn finalize_import(
877         &mut self,
878         directive: &'b ImportDirective<'b>,
879     ) -> Option<UnresolvedImportError> {
880         let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
881         let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
882         let path_res = self.r.resolve_path(
883             &directive.module_path,
884             None,
885             &directive.parent_scope,
886             true,
887             directive.span,
888             directive.crate_lint(),
889         );
890         let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
891         directive.vis.set(orig_vis);
892         if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
893             // Consider erroneous imports used to avoid duplicate diagnostics.
894             self.r.used_imports.insert((directive.id, TypeNS));
895         }
896         let module = match path_res {
897             PathResult::Module(module) => {
898                 // Consistency checks, analogous to `finalize_macro_resolutions`.
899                 if let Some(initial_module) = directive.imported_module.get() {
900                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
901                         span_bug!(directive.span, "inconsistent resolution for an import");
902                     }
903                 } else {
904                     if self.r.privacy_errors.is_empty() {
905                         let msg = "cannot determine resolution for the import";
906                         let msg_note = "import resolution is stuck, try simplifying other imports";
907                         self.r.session.struct_span_err(directive.span, msg).note(msg_note).emit();
908                     }
909                 }
910
911                 module
912             }
913             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
914                 if no_ambiguity {
915                     assert!(directive.imported_module.get().is_none());
916                     self.r
917                         .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
918                 }
919                 return None;
920             }
921             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
922                 if no_ambiguity {
923                     assert!(directive.imported_module.get().is_none());
924                     let err = match self.make_path_suggestion(
925                         span,
926                         directive.module_path.clone(),
927                         &directive.parent_scope,
928                     ) {
929                         Some((suggestion, note)) => UnresolvedImportError {
930                             span,
931                             label: None,
932                             note,
933                             suggestion: Some((
934                                 vec![(span, Segment::names_to_string(&suggestion))],
935                                 String::from("a similar path exists"),
936                                 Applicability::MaybeIncorrect,
937                             )),
938                         },
939                         None => UnresolvedImportError {
940                             span,
941                             label: Some(label),
942                             note: Vec::new(),
943                             suggestion,
944                         },
945                     };
946                     return Some(err);
947                 }
948                 return None;
949             }
950             PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
951                 if no_ambiguity {
952                     assert!(directive.imported_module.get().is_none());
953                 }
954                 // The error was already reported earlier.
955                 return None;
956             }
957             PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
958         };
959
960         let (ident, target, source_bindings, target_bindings, type_ns_only) = match directive
961             .subclass
962         {
963             SingleImport {
964                 source,
965                 target,
966                 ref source_bindings,
967                 ref target_bindings,
968                 type_ns_only,
969                 ..
970             } => (source, target, source_bindings, target_bindings, type_ns_only),
971             GlobImport { is_prelude, ref max_vis } => {
972                 if directive.module_path.len() <= 1 {
973                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
974                     // 2 segments, so the `resolve_path` above won't trigger it.
975                     let mut full_path = directive.module_path.clone();
976                     full_path.push(Segment::from_ident(Ident::invalid()));
977                     self.r.lint_if_path_starts_with_module(
978                         directive.crate_lint(),
979                         &full_path,
980                         directive.span,
981                         None,
982                     );
983                 }
984
985                 if let ModuleOrUniformRoot::Module(module) = module {
986                     if module.def_id() == directive.parent_scope.module.def_id() {
987                         // Importing a module into itself is not allowed.
988                         return Some(UnresolvedImportError {
989                             span: directive.span,
990                             label: Some(String::from("cannot glob-import a module into itself")),
991                             note: Vec::new(),
992                             suggestion: None,
993                         });
994                     }
995                 }
996                 if !is_prelude &&
997                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
998                    !max_vis.get().is_at_least(directive.vis.get(), &*self)
999                 {
1000                     let msg = "glob import doesn't reexport anything because no candidate is public enough";
1001                     self.r.lint_buffer.buffer_lint(
1002                         UNUSED_IMPORTS,
1003                         directive.id,
1004                         directive.span,
1005                         msg,
1006                     );
1007                 }
1008                 return None;
1009             }
1010             _ => unreachable!(),
1011         };
1012
1013         let mut all_ns_err = true;
1014         self.r.per_ns(|this, ns| {
1015             if !type_ns_only || ns == TypeNS {
1016                 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1017                 let orig_blacklisted_binding =
1018                     mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1019                 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1020                 let binding = this.resolve_ident_in_module(
1021                     module,
1022                     ident,
1023                     ns,
1024                     &directive.parent_scope,
1025                     true,
1026                     directive.span,
1027                 );
1028                 this.last_import_segment = orig_last_import_segment;
1029                 this.blacklisted_binding = orig_blacklisted_binding;
1030                 directive.vis.set(orig_vis);
1031
1032                 match binding {
1033                     Ok(binding) => {
1034                         // Consistency checks, analogous to `finalize_macro_resolutions`.
1035                         let initial_res = source_bindings[ns].get().map(|initial_binding| {
1036                             all_ns_err = false;
1037                             if let Some(target_binding) = target_bindings[ns].get() {
1038                                 // Note that as_str() de-gensyms the Symbol
1039                                 if target.name.as_str() == "_"
1040                                     && initial_binding.is_extern_crate()
1041                                     && !initial_binding.is_import()
1042                                 {
1043                                     this.record_use(
1044                                         ident,
1045                                         ns,
1046                                         target_binding,
1047                                         directive.module_path.is_empty(),
1048                                     );
1049                                 }
1050                             }
1051                             initial_binding.res()
1052                         });
1053                         let res = binding.res();
1054                         if let Ok(initial_res) = initial_res {
1055                             if res != initial_res && this.ambiguity_errors.is_empty() {
1056                                 span_bug!(directive.span, "inconsistent resolution for an import");
1057                             }
1058                         } else {
1059                             if res != Res::Err
1060                                 && this.ambiguity_errors.is_empty()
1061                                 && this.privacy_errors.is_empty()
1062                             {
1063                                 let msg = "cannot determine resolution for the import";
1064                                 let msg_note =
1065                                     "import resolution is stuck, try simplifying other imports";
1066                                 this.session
1067                                     .struct_span_err(directive.span, msg)
1068                                     .note(msg_note)
1069                                     .emit();
1070                             }
1071                         }
1072                     }
1073                     Err(..) => {
1074                         // FIXME: This assert may fire if public glob is later shadowed by a private
1075                         // single import (see test `issue-55884-2.rs`). In theory single imports should
1076                         // always block globs, even if they are not yet resolved, so that this kind of
1077                         // self-inconsistent resolution never happens.
1078                         // Reenable the assert when the issue is fixed.
1079                         // assert!(result[ns].get().is_err());
1080                     }
1081                 }
1082             }
1083         });
1084
1085         if all_ns_err {
1086             let mut all_ns_failed = true;
1087             self.r.per_ns(|this, ns| {
1088                 if !type_ns_only || ns == TypeNS {
1089                     let binding = this.resolve_ident_in_module(
1090                         module,
1091                         ident,
1092                         ns,
1093                         &directive.parent_scope,
1094                         true,
1095                         directive.span,
1096                     );
1097                     if binding.is_ok() {
1098                         all_ns_failed = false;
1099                     }
1100                 }
1101             });
1102
1103             return if all_ns_failed {
1104                 let resolutions = match module {
1105                     ModuleOrUniformRoot::Module(module) => {
1106                         Some(self.r.resolutions(module).borrow())
1107                     }
1108                     _ => None,
1109                 };
1110                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1111                 let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1112                     if *i == ident {
1113                         return None;
1114                     } // Never suggest the same name
1115                     match *resolution.borrow() {
1116                         NameResolution { binding: Some(name_binding), .. } => {
1117                             match name_binding.kind {
1118                                 NameBindingKind::Import { binding, .. } => {
1119                                     match binding.kind {
1120                                         // Never suggest the name that has binding error
1121                                         // i.e., the name that cannot be previously resolved
1122                                         NameBindingKind::Res(Res::Err, _) => return None,
1123                                         _ => Some(&i.name),
1124                                     }
1125                                 }
1126                                 _ => Some(&i.name),
1127                             }
1128                         }
1129                         NameResolution { ref single_imports, .. } if single_imports.is_empty() => {
1130                             None
1131                         }
1132                         _ => Some(&i.name),
1133                     }
1134                 });
1135
1136                 let lev_suggestion =
1137                     find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1138                         (
1139                             vec![(ident.span, suggestion.to_string())],
1140                             String::from("a similar name exists in the module"),
1141                             Applicability::MaybeIncorrect,
1142                         )
1143                     });
1144
1145                 let (suggestion, note) =
1146                     match self.check_for_module_export_macro(directive, module, ident) {
1147                         Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1148                         _ => (lev_suggestion, Vec::new()),
1149                     };
1150
1151                 let label = match module {
1152                     ModuleOrUniformRoot::Module(module) => {
1153                         let module_str = module_to_string(module);
1154                         if let Some(module_str) = module_str {
1155                             format!("no `{}` in `{}`", ident, module_str)
1156                         } else {
1157                             format!("no `{}` in the root", ident)
1158                         }
1159                     }
1160                     _ => {
1161                         if !ident.is_path_segment_keyword() {
1162                             format!("no `{}` external crate", ident)
1163                         } else {
1164                             // HACK(eddyb) this shows up for `self` & `super`, which
1165                             // should work instead - for now keep the same error message.
1166                             format!("no `{}` in the root", ident)
1167                         }
1168                     }
1169                 };
1170
1171                 Some(UnresolvedImportError {
1172                     span: directive.span,
1173                     label: Some(label),
1174                     note,
1175                     suggestion,
1176                 })
1177             } else {
1178                 // `resolve_ident_in_module` reported a privacy error.
1179                 self.r.import_dummy_binding(directive);
1180                 None
1181             };
1182         }
1183
1184         let mut reexport_error = None;
1185         let mut any_successful_reexport = false;
1186         self.r.per_ns(|this, ns| {
1187             if let Ok(binding) = source_bindings[ns].get() {
1188                 let vis = directive.vis.get();
1189                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1190                     reexport_error = Some((ns, binding));
1191                 } else {
1192                     any_successful_reexport = true;
1193                 }
1194             }
1195         });
1196
1197         // All namespaces must be re-exported with extra visibility for an error to occur.
1198         if !any_successful_reexport {
1199             let (ns, binding) = reexport_error.unwrap();
1200             if ns == TypeNS && binding.is_extern_crate() {
1201                 let msg = format!(
1202                     "extern crate `{}` is private, and cannot be \
1203                                    re-exported (error E0365), consider declaring with \
1204                                    `pub`",
1205                     ident
1206                 );
1207                 self.r.lint_buffer.buffer_lint(
1208                     PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1209                     directive.id,
1210                     directive.span,
1211                     &msg,
1212                 );
1213             } else if ns == TypeNS {
1214                 struct_span_err!(
1215                     self.r.session,
1216                     directive.span,
1217                     E0365,
1218                     "`{}` is private, and cannot be re-exported",
1219                     ident
1220                 )
1221                 .span_label(directive.span, format!("re-export of private `{}`", ident))
1222                 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1223                 .emit();
1224             } else {
1225                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1226                 let note_msg =
1227                     format!("consider marking `{}` as `pub` in the imported module", ident,);
1228                 struct_span_err!(self.r.session, directive.span, E0364, "{}", &msg)
1229                     .span_note(directive.span, &note_msg)
1230                     .emit();
1231             }
1232         }
1233
1234         if directive.module_path.len() <= 1 {
1235             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1236             // 2 segments, so the `resolve_path` above won't trigger it.
1237             let mut full_path = directive.module_path.clone();
1238             full_path.push(Segment::from_ident(ident));
1239             self.r.per_ns(|this, ns| {
1240                 if let Ok(binding) = source_bindings[ns].get() {
1241                     this.lint_if_path_starts_with_module(
1242                         directive.crate_lint(),
1243                         &full_path,
1244                         directive.span,
1245                         Some(binding),
1246                     );
1247                 }
1248             });
1249         }
1250
1251         // Record what this import resolves to for later uses in documentation,
1252         // this may resolve to either a value or a type, but for documentation
1253         // purposes it's good enough to just favor one over the other.
1254         self.r.per_ns(|this, ns| {
1255             if let Some(binding) = source_bindings[ns].get().ok() {
1256                 this.import_res_map.entry(directive.id).or_default()[ns] = Some(binding.res());
1257             }
1258         });
1259
1260         self.check_for_redundant_imports(
1261             ident,
1262             directive,
1263             source_bindings,
1264             target_bindings,
1265             target,
1266         );
1267
1268         debug!("(resolving single import) successfully resolved import");
1269         None
1270     }
1271
1272     fn check_for_redundant_imports(
1273         &mut self,
1274         ident: Ident,
1275         directive: &'b ImportDirective<'b>,
1276         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1277         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1278         target: Ident,
1279     ) {
1280         // Skip if the import was produced by a macro.
1281         if directive.parent_scope.expansion != ExpnId::root() {
1282             return;
1283         }
1284
1285         // Skip if we are inside a named module (in contrast to an anonymous
1286         // module defined by a block).
1287         if let ModuleKind::Def(..) = directive.parent_scope.module.kind {
1288             return;
1289         }
1290
1291         let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1292
1293         let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1294
1295         self.r.per_ns(|this, ns| {
1296             if let Some(binding) = source_bindings[ns].get().ok() {
1297                 if binding.res() == Res::Err {
1298                     return;
1299                 }
1300
1301                 let orig_blacklisted_binding =
1302                     mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1303
1304                 match this.early_resolve_ident_in_lexical_scope(
1305                     target,
1306                     ScopeSet::All(ns, false),
1307                     &directive.parent_scope,
1308                     false,
1309                     false,
1310                     directive.span,
1311                 ) {
1312                     Ok(other_binding) => {
1313                         is_redundant[ns] = Some(
1314                             binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1315                         );
1316                         redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1317                     }
1318                     Err(_) => is_redundant[ns] = Some(false),
1319                 }
1320
1321                 this.blacklisted_binding = orig_blacklisted_binding;
1322             }
1323         });
1324
1325         if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1326         {
1327             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1328             redundant_spans.sort();
1329             redundant_spans.dedup();
1330             self.r.lint_buffer.buffer_lint_with_diagnostic(
1331                 UNUSED_IMPORTS,
1332                 directive.id,
1333                 directive.span,
1334                 &format!("the item `{}` is imported redundantly", ident),
1335                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1336             );
1337         }
1338     }
1339
1340     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1341         let module = match directive.imported_module.get().unwrap() {
1342             ModuleOrUniformRoot::Module(module) => module,
1343             _ => {
1344                 self.r.session.span_err(directive.span, "cannot glob-import all possible crates");
1345                 return;
1346             }
1347         };
1348
1349         if module.is_trait() {
1350             self.r.session.span_err(directive.span, "items in traits are not importable.");
1351             return;
1352         } else if module.def_id() == directive.parent_scope.module.def_id() {
1353             return;
1354         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1355             self.r.prelude = Some(module);
1356             return;
1357         }
1358
1359         // Add to module's glob_importers
1360         module.glob_importers.borrow_mut().push(directive);
1361
1362         // Ensure that `resolutions` isn't borrowed during `try_define`,
1363         // since it might get updated via a glob cycle.
1364         let bindings = self
1365             .r
1366             .resolutions(module)
1367             .borrow()
1368             .iter()
1369             .filter_map(|(key, resolution)| {
1370                 resolution.borrow().binding().map(|binding| (*key, binding))
1371             })
1372             .collect::<Vec<_>>();
1373         for (mut key, binding) in bindings {
1374             let scope = match key.ident.span.reverse_glob_adjust(module.expansion, directive.span) {
1375                 Some(Some(def)) => self.r.macro_def_scope(def),
1376                 Some(None) => directive.parent_scope.module,
1377                 None => continue,
1378             };
1379             if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
1380                 let imported_binding = self.r.import(binding, directive);
1381                 let _ = self.r.try_define(directive.parent_scope.module, key, imported_binding);
1382             }
1383         }
1384
1385         // Record the destination of this import
1386         self.r.record_partial_res(directive.id, PartialRes::new(module.res().unwrap()));
1387     }
1388
1389     // Miscellaneous post-processing, including recording re-exports,
1390     // reporting conflicts, and reporting unresolved imports.
1391     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1392         // Since import resolution is finished, globs will not define any more names.
1393         *module.globs.borrow_mut() = Vec::new();
1394
1395         let mut reexports = Vec::new();
1396
1397         module.for_each_child(self.r, |this, ident, ns, binding| {
1398             // Filter away ambiguous imports and anything that has def-site
1399             // hygiene.
1400             // FIXME: Implement actual cross-crate hygiene.
1401             let is_good_import =
1402                 binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion();
1403             if is_good_import || binding.is_macro_def() {
1404                 let res = binding.res();
1405                 if res != Res::Err {
1406                     if let Some(def_id) = res.opt_def_id() {
1407                         if !def_id.is_local() {
1408                             this.cstore().export_macros_untracked(def_id.krate);
1409                         }
1410                     }
1411                     reexports.push(Export { ident, res, span: binding.span, vis: binding.vis });
1412                 }
1413             }
1414
1415             if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1416                 if ns == TypeNS
1417                     && orig_binding.is_variant()
1418                     && !orig_binding.vis.is_at_least(binding.vis, &*this)
1419                 {
1420                     let msg = match directive.subclass {
1421                         ImportDirectiveSubclass::SingleImport { .. } => {
1422                             format!("variant `{}` is private and cannot be re-exported", ident)
1423                         }
1424                         ImportDirectiveSubclass::GlobImport { .. } => {
1425                             let msg = "enum is private and its variants \
1426                                            cannot be re-exported"
1427                                 .to_owned();
1428                             let error_id = (
1429                                 DiagnosticMessageId::ErrorId(0), // no code?!
1430                                 Some(binding.span),
1431                                 msg.clone(),
1432                             );
1433                             let fresh =
1434                                 this.session.one_time_diagnostics.borrow_mut().insert(error_id);
1435                             if !fresh {
1436                                 return;
1437                             }
1438                             msg
1439                         }
1440                         ref s @ _ => bug!("unexpected import subclass {:?}", s),
1441                     };
1442                     let mut err = this.session.struct_span_err(binding.span, &msg);
1443
1444                     let imported_module = match directive.imported_module.get() {
1445                         Some(ModuleOrUniformRoot::Module(module)) => module,
1446                         _ => bug!("module should exist"),
1447                     };
1448                     let parent_module = imported_module.parent.expect("parent should exist");
1449                     let resolutions = this.resolutions(parent_module).borrow();
1450                     let enum_path_segment_index = directive.module_path.len() - 1;
1451                     let enum_ident = directive.module_path[enum_path_segment_index].ident;
1452
1453                     let key = this.new_key(enum_ident, TypeNS);
1454                     let enum_resolution = resolutions.get(&key).expect("resolution should exist");
1455                     let enum_span =
1456                         enum_resolution.borrow().binding.expect("binding should exist").span;
1457                     let enum_def_span = this.session.source_map().def_span(enum_span);
1458                     let enum_def_snippet = this
1459                         .session
1460                         .source_map()
1461                         .span_to_snippet(enum_def_span)
1462                         .expect("snippet should exist");
1463                     // potentially need to strip extant `crate`/`pub(path)` for suggestion
1464                     let after_vis_index = enum_def_snippet
1465                         .find("enum")
1466                         .expect("`enum` keyword should exist in snippet");
1467                     let suggestion = format!("pub {}", &enum_def_snippet[after_vis_index..]);
1468
1469                     this.session.diag_span_suggestion_once(
1470                         &mut err,
1471                         DiagnosticMessageId::ErrorId(0),
1472                         enum_def_span,
1473                         "consider making the enum public",
1474                         suggestion,
1475                     );
1476                     err.emit();
1477                 }
1478             }
1479         });
1480
1481         if reexports.len() > 0 {
1482             if let Some(def_id) = module.def_id() {
1483                 self.r.export_map.insert(def_id, reexports);
1484             }
1485         }
1486     }
1487 }
1488
1489 fn import_path_to_string(
1490     names: &[Ident],
1491     subclass: &ImportDirectiveSubclass<'_>,
1492     span: Span,
1493 ) -> String {
1494     let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1495     let global = !names.is_empty() && names[0].name == kw::PathRoot;
1496     if let Some(pos) = pos {
1497         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1498         names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1499     } else {
1500         let names = if global { &names[1..] } else { names };
1501         if names.is_empty() {
1502             import_directive_subclass_to_string(subclass)
1503         } else {
1504             format!(
1505                 "{}::{}",
1506                 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1507                 import_directive_subclass_to_string(subclass),
1508             )
1509         }
1510     }
1511 }
1512
1513 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1514     match *subclass {
1515         SingleImport { source, .. } => source.to_string(),
1516         GlobImport { .. } => "*".to_string(),
1517         ExternCrate { .. } => "<extern crate>".to_string(),
1518         MacroUse => "#[macro_use]".to_string(),
1519     }
1520 }