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