]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/imports.rs
Rollup merge of #72780 - GuillaumeGomez:enforce-doc-alias-check, r=ollie27
[rust.git] / src / librustc_resolve / imports.rs
1 //! A bunch of methods and structures more or less related to resolving imports.
2
3 use crate::diagnostics::Suggestion;
4 use crate::Determinacy::{self, *};
5 use crate::Namespace::{self, MacroNS, TypeNS};
6 use crate::{module_to_string, names_to_string};
7 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
8 use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
9 use crate::{CrateLint, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
10 use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
11
12 use rustc_ast::ast::NodeId;
13 use rustc_ast::unwrap_or;
14 use rustc_ast::util::lev_distance::find_best_match_for_name;
15 use rustc_data_structures::fx::FxHashSet;
16 use rustc_data_structures::ptr_key::PtrKey;
17 use rustc_errors::{pluralize, struct_span_err, Applicability};
18 use rustc_hir::def::{self, PartialRes};
19 use rustc_hir::def_id::DefId;
20 use rustc_middle::hir::exports::Export;
21 use rustc_middle::ty;
22 use rustc_middle::{bug, span_bug};
23 use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
24 use rustc_session::lint::BuiltinLintDiagnostics;
25 use rustc_session::DiagnosticMessageId;
26 use rustc_span::hygiene::ExpnId;
27 use rustc_span::symbol::{kw, Ident, Symbol};
28 use rustc_span::{MultiSpan, Span};
29
30 use log::*;
31
32 use std::cell::Cell;
33 use std::{mem, ptr};
34
35 type Res = def::Res<NodeId>;
36
37 /// Contains data for specific kinds of imports.
38 #[derive(Clone, Debug)]
39 pub enum ImportKind<'a> {
40     Single {
41         /// `source` in `use prefix::source as target`.
42         source: Ident,
43         /// `target` in `use prefix::source as target`.
44         target: Ident,
45         /// Bindings to which `source` refers to.
46         source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
47         /// Bindings introduced by `target`.
48         target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
49         /// `true` for `...::{self [as target]}` imports, `false` otherwise.
50         type_ns_only: bool,
51         /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
52         nested: bool,
53     },
54     Glob {
55         is_prelude: bool,
56         max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
57                                        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
58     },
59     ExternCrate {
60         source: Option<Symbol>,
61         target: Ident,
62     },
63     MacroUse,
64 }
65
66 /// One import.
67 #[derive(Debug, Clone)]
68 crate struct Import<'a> {
69     pub kind: ImportKind<'a>,
70
71     /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
72     ///
73     /// In the case where the `Import` 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 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 vis: Cell<ty::Visibility>,
111     pub used: Cell<bool>,
112 }
113
114 impl<'a> Import<'a> {
115     pub fn is_glob(&self) -> bool {
116         match self.kind {
117             ImportKind::Glob { .. } => true,
118             _ => false,
119         }
120     }
121
122     pub fn is_nested(&self) -> bool {
123         match self.kind {
124             ImportKind::Single { nested, .. } => nested,
125             _ => false,
126         }
127     }
128
129     crate fn crate_lint(&self) -> CrateLint {
130         CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
131     }
132 }
133
134 #[derive(Clone, Default, Debug)]
135 /// Records information about the resolution of a name in a namespace of a module.
136 pub struct NameResolution<'a> {
137     /// Single imports that may define the name in the namespace.
138     /// Imports are arena-allocated, so it's ok to use pointers as keys.
139     single_imports: FxHashSet<PtrKey<'a, Import<'a>>>,
140     /// The least shadowable known binding for this name, or None if there are no known bindings.
141     pub binding: Option<&'a NameBinding<'a>>,
142     shadowed_glob: Option<&'a NameBinding<'a>>,
143 }
144
145 impl<'a> NameResolution<'a> {
146     // Returns the binding for the name if it is known or None if it not known.
147     pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
148         self.binding.and_then(|binding| {
149             if !binding.is_glob_import() || self.single_imports.is_empty() {
150                 Some(binding)
151             } else {
152                 None
153             }
154         })
155     }
156
157     crate fn add_single_import(&mut self, import: &'a Import<'a>) {
158         self.single_imports.insert(PtrKey(import));
159     }
160 }
161
162 impl<'a> Resolver<'a> {
163     crate fn resolve_ident_in_module_unadjusted(
164         &mut self,
165         module: ModuleOrUniformRoot<'a>,
166         ident: Ident,
167         ns: Namespace,
168         parent_scope: &ParentScope<'a>,
169         record_used: bool,
170         path_span: Span,
171     ) -> Result<&'a NameBinding<'a>, Determinacy> {
172         self.resolve_ident_in_module_unadjusted_ext(
173             module,
174             ident,
175             ns,
176             parent_scope,
177             false,
178             record_used,
179             path_span,
180         )
181         .map_err(|(determinacy, _)| determinacy)
182     }
183
184     /// Attempts to resolve `ident` in namespaces `ns` of `module`.
185     /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
186     crate fn resolve_ident_in_module_unadjusted_ext(
187         &mut self,
188         module: ModuleOrUniformRoot<'a>,
189         ident: Ident,
190         ns: Namespace,
191         parent_scope: &ParentScope<'a>,
192         restricted_shadowing: bool,
193         record_used: bool,
194         path_span: Span,
195     ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
196         let module = match module {
197             ModuleOrUniformRoot::Module(module) => module,
198             ModuleOrUniformRoot::CrateRootAndExternPrelude => {
199                 assert!(!restricted_shadowing);
200                 let binding = self.early_resolve_ident_in_lexical_scope(
201                     ident,
202                     ScopeSet::AbsolutePath(ns),
203                     parent_scope,
204                     record_used,
205                     record_used,
206                     path_span,
207                 );
208                 return binding.map_err(|determinacy| (determinacy, Weak::No));
209             }
210             ModuleOrUniformRoot::ExternPrelude => {
211                 assert!(!restricted_shadowing);
212                 return if ns != TypeNS {
213                     Err((Determined, Weak::No))
214                 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
215                     Ok(binding)
216                 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
217                     // Macro-expanded `extern crate` items can add names to extern prelude.
218                     Err((Undetermined, Weak::No))
219                 } else {
220                     Err((Determined, Weak::No))
221                 };
222             }
223             ModuleOrUniformRoot::CurrentScope => {
224                 assert!(!restricted_shadowing);
225                 if ns == TypeNS {
226                     if ident.name == kw::Crate || ident.name == kw::DollarCrate {
227                         let module = self.resolve_crate_root(ident);
228                         let binding = (module, ty::Visibility::Public, module.span, ExpnId::root())
229                             .to_name_binding(self.arenas);
230                         return Ok(binding);
231                     } else if ident.name == kw::Super || ident.name == kw::SelfLower {
232                         // FIXME: Implement these with renaming requirements so that e.g.
233                         // `use super;` doesn't work, but `use super as name;` does.
234                         // Fall through here to get an error from `early_resolve_...`.
235                     }
236                 }
237
238                 let scopes = ScopeSet::All(ns, true);
239                 let binding = self.early_resolve_ident_in_lexical_scope(
240                     ident,
241                     scopes,
242                     parent_scope,
243                     record_used,
244                     record_used,
245                     path_span,
246                 );
247                 return binding.map_err(|determinacy| (determinacy, Weak::No));
248             }
249         };
250
251         let key = self.new_key(ident, ns);
252         let resolution =
253             self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
254
255         if let Some(binding) = resolution.binding {
256             if !restricted_shadowing && binding.expansion != ExpnId::root() {
257                 if let NameBindingKind::Res(_, true) = binding.kind {
258                     self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
259                 }
260             }
261         }
262
263         let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
264             if let Some(blacklisted_binding) = this.blacklisted_binding {
265                 if ptr::eq(binding, blacklisted_binding) {
266                     return Err((Determined, Weak::No));
267                 }
268             }
269             // `extern crate` are always usable for backwards compatibility, see issue #37020,
270             // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
271             let usable = this.is_accessible_from(binding.vis, parent_scope.module)
272                 || binding.is_extern_crate();
273             if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
274         };
275
276         if record_used {
277             return resolution
278                 .binding
279                 .and_then(|binding| {
280                     // If the primary binding is blacklisted, search further and return the shadowed
281                     // glob binding if it exists. What we really want here is having two separate
282                     // scopes in a module - one for non-globs and one for globs, but until that's done
283                     // use this hack to avoid inconsistent resolution ICEs during import validation.
284                     if let Some(blacklisted_binding) = self.blacklisted_binding {
285                         if ptr::eq(binding, blacklisted_binding) {
286                             return resolution.shadowed_glob;
287                         }
288                     }
289                     Some(binding)
290                 })
291                 .ok_or((Determined, Weak::No))
292                 .and_then(|binding| {
293                     if self.last_import_segment && check_usable(self, binding).is_err() {
294                         Err((Determined, Weak::No))
295                     } else {
296                         self.record_use(ident, ns, binding, restricted_shadowing);
297
298                         if let Some(shadowed_glob) = resolution.shadowed_glob {
299                             // Forbid expanded shadowing to avoid time travel.
300                             if restricted_shadowing
301                                 && binding.expansion != ExpnId::root()
302                                 && binding.res() != shadowed_glob.res()
303                             {
304                                 self.ambiguity_errors.push(AmbiguityError {
305                                     kind: AmbiguityKind::GlobVsExpanded,
306                                     ident,
307                                     b1: binding,
308                                     b2: shadowed_glob,
309                                     misc1: AmbiguityErrorMisc::None,
310                                     misc2: AmbiguityErrorMisc::None,
311                                 });
312                             }
313                         }
314
315                         if !(self.is_accessible_from(binding.vis, parent_scope.module) ||
316                        // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
317                        (self.last_import_segment && binding.is_extern_crate()))
318                         {
319                             self.privacy_errors.push(PrivacyError {
320                                 ident,
321                                 binding,
322                                 dedup_span: path_span,
323                             });
324                         }
325
326                         Ok(binding)
327                     }
328                 });
329         }
330
331         // Items and single imports are not shadowable, if we have one, then it's determined.
332         if let Some(binding) = resolution.binding {
333             if !binding.is_glob_import() {
334                 return check_usable(self, binding);
335             }
336         }
337
338         // --- From now on we either have a glob resolution or no resolution. ---
339
340         // Check if one of single imports can still define the name,
341         // if it can then our result is not determined and can be invalidated.
342         for single_import in &resolution.single_imports {
343             if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
344                 continue;
345             }
346             let module = unwrap_or!(
347                 single_import.imported_module.get(),
348                 return Err((Undetermined, Weak::No))
349             );
350             let ident = match single_import.kind {
351                 ImportKind::Single { source, .. } => source,
352                 _ => unreachable!(),
353             };
354             match self.resolve_ident_in_module(
355                 module,
356                 ident,
357                 ns,
358                 &single_import.parent_scope,
359                 false,
360                 path_span,
361             ) {
362                 Err(Determined) => continue,
363                 Ok(binding)
364                     if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
365                 {
366                     continue;
367                 }
368                 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
369             }
370         }
371
372         // So we have a resolution that's from a glob import. This resolution is determined
373         // if it cannot be shadowed by some new item/import expanded from a macro.
374         // This happens either if there are no unexpanded macros, or expanded names cannot
375         // shadow globs (that happens in macro namespace or with restricted shadowing).
376         //
377         // Additionally, any macro in any module can plant names in the root module if it creates
378         // `macro_export` macros, so the root module effectively has unresolved invocations if any
379         // module has unresolved invocations.
380         // However, it causes resolution/expansion to stuck too often (#53144), so, to make
381         // progress, we have to ignore those potential unresolved invocations from other modules
382         // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
383         // shadowing is enabled, see `macro_expanded_macro_export_errors`).
384         let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
385         if let Some(binding) = resolution.binding {
386             if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
387                 return check_usable(self, binding);
388             } else {
389                 return Err((Undetermined, Weak::No));
390             }
391         }
392
393         // --- From now on we have no resolution. ---
394
395         // Now we are in situation when new item/import can appear only from a glob or a macro
396         // expansion. With restricted shadowing names from globs and macro expansions cannot
397         // shadow names from outer scopes, so we can freely fallback from module search to search
398         // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
399         // scopes we return `Undetermined` with `Weak::Yes`.
400
401         // Check if one of unexpanded macros can still define the name,
402         // if it can then our "no resolution" result is not determined and can be invalidated.
403         if unexpanded_macros {
404             return Err((Undetermined, Weak::Yes));
405         }
406
407         // Check if one of glob imports can still define the name,
408         // if it can then our "no resolution" result is not determined and can be invalidated.
409         for glob_import in module.globs.borrow().iter() {
410             if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
411                 continue;
412             }
413             let module = match glob_import.imported_module.get() {
414                 Some(ModuleOrUniformRoot::Module(module)) => module,
415                 Some(_) => continue,
416                 None => return Err((Undetermined, Weak::Yes)),
417             };
418             let tmp_parent_scope;
419             let (mut adjusted_parent_scope, mut ident) =
420                 (parent_scope, ident.normalize_to_macros_2_0());
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 that resolves to it,
455     // return the corresponding binding defined by the import.
456     crate fn import(
457         &self,
458         binding: &'a NameBinding<'a>,
459         import: &'a Import<'a>,
460     ) -> &'a NameBinding<'a> {
461         let vis = if binding.pseudo_vis().is_at_least(import.vis.get(), self) ||
462                      // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
463                      !import.is_glob() && binding.is_extern_crate()
464         {
465             import.vis.get()
466         } else {
467             binding.pseudo_vis()
468         };
469
470         if let ImportKind::Glob { ref max_vis, .. } = import.kind {
471             if vis == import.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, import, used: Cell::new(false) },
478             ambiguity: None,
479             span: import.span,
480             vis,
481             expansion: import.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 import in module.glob_importers.borrow_mut().iter() {
581             let mut ident = key.ident;
582             let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
583                 Some(Some(def)) => self.macro_def_scope(def),
584                 Some(None) => import.parent_scope.module,
585                 None => continue,
586             };
587             if self.is_accessible_from(binding.vis, scope) {
588                 let imported_binding = self.import(binding, import);
589                 let key = BindingKey { ident, ..key };
590                 let _ = self.try_define(import.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, import: &'a Import<'a>) {
600         if let ImportKind::Single { target, .. } = import.kind {
601             let dummy_binding = self.dummy_binding;
602             let dummy_binding = self.import(dummy_binding, import);
603             self.per_ns(|this, ns| {
604                 let key = this.new_key(target, ns);
605                 let _ = this.try_define(import.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 ImportKind::Single { source, ref source_bindings, .. } = import.kind {
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.kind,
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.kind,
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, import: &'b Import<'b>) -> bool {
771         debug!(
772             "(resolving import for module) resolving import `{}::...` in `{}`",
773             Segment::names_to_string(&import.module_path),
774             module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
775         );
776
777         let module = if let Some(module) = import.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 = import.vis.replace(ty::Visibility::Invisible);
783             let path_res = self.r.resolve_path(
784                 &import.module_path,
785                 None,
786                 &import.parent_scope,
787                 false,
788                 import.span,
789                 import.crate_lint(),
790             );
791             import.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         import.imported_module.set(Some(module));
801         let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
802             ImportKind::Single {
803                 source,
804                 target,
805                 ref source_bindings,
806                 ref target_bindings,
807                 type_ns_only,
808                 ..
809             } => (source, target, source_bindings, target_bindings, type_ns_only),
810             ImportKind::Glob { .. } => {
811                 self.resolve_glob_import(import);
812                 return true;
813             }
814             _ => unreachable!(),
815         };
816
817         let mut indeterminate = false;
818         self.r.per_ns(|this, ns| {
819             if !type_ns_only || ns == TypeNS {
820                 if let Err(Undetermined) = source_bindings[ns].get() {
821                     // For better failure detection, pretend that the import will
822                     // not define any names while resolving its module path.
823                     let orig_vis = import.vis.replace(ty::Visibility::Invisible);
824                     let binding = this.resolve_ident_in_module(
825                         module,
826                         source,
827                         ns,
828                         &import.parent_scope,
829                         false,
830                         import.span,
831                     );
832                     import.vis.set(orig_vis);
833
834                     source_bindings[ns].set(binding);
835                 } else {
836                     return;
837                 };
838
839                 let parent = import.parent_scope.module;
840                 match source_bindings[ns].get() {
841                     Err(Undetermined) => indeterminate = true,
842                     // Don't update the resolution, because it was never added.
843                     Err(Determined) if target.name == kw::Underscore => {}
844                     Err(Determined) => {
845                         let key = this.new_key(target, ns);
846                         this.update_resolution(parent, key, |_, resolution| {
847                             resolution.single_imports.remove(&PtrKey(import));
848                         });
849                     }
850                     Ok(binding) if !binding.is_importable() => {
851                         let msg = format!("`{}` is not directly importable", target);
852                         struct_span_err!(this.session, import.span, E0253, "{}", &msg)
853                             .span_label(import.span, "cannot be imported directly")
854                             .emit();
855                         // Do not import this illegal binding. Import a dummy binding and pretend
856                         // everything is fine
857                         this.import_dummy_binding(import);
858                     }
859                     Ok(binding) => {
860                         let imported_binding = this.import(binding, import);
861                         target_bindings[ns].set(Some(imported_binding));
862                         this.define(parent, target, ns, imported_binding);
863                     }
864                 }
865             }
866         });
867
868         !indeterminate
869     }
870
871     /// Performs final import resolution, consistency checks and error reporting.
872     ///
873     /// Optionally returns an unresolved import error. This error is buffered and used to
874     /// consolidate multiple unresolved import errors into a single diagnostic.
875     fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
876         let orig_vis = import.vis.replace(ty::Visibility::Invisible);
877         let orig_blacklisted_binding = match &import.kind {
878             ImportKind::Single { target_bindings, .. } => {
879                 Some(mem::replace(&mut self.r.blacklisted_binding, target_bindings[TypeNS].get()))
880             }
881             _ => None,
882         };
883         let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
884         let path_res = self.r.resolve_path(
885             &import.module_path,
886             None,
887             &import.parent_scope,
888             true,
889             import.span,
890             import.crate_lint(),
891         );
892         let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
893         if let Some(orig_blacklisted_binding) = orig_blacklisted_binding {
894             self.r.blacklisted_binding = orig_blacklisted_binding;
895         }
896         import.vis.set(orig_vis);
897         if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
898             // Consider erroneous imports used to avoid duplicate diagnostics.
899             self.r.used_imports.insert((import.id, TypeNS));
900         }
901         let module = match path_res {
902             PathResult::Module(module) => {
903                 // Consistency checks, analogous to `finalize_macro_resolutions`.
904                 if let Some(initial_module) = import.imported_module.get() {
905                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
906                         span_bug!(import.span, "inconsistent resolution for an import");
907                     }
908                 } else {
909                     if self.r.privacy_errors.is_empty() {
910                         let msg = "cannot determine resolution for the import";
911                         let msg_note = "import resolution is stuck, try simplifying other imports";
912                         self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
913                     }
914                 }
915
916                 module
917             }
918             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
919                 if no_ambiguity {
920                     assert!(import.imported_module.get().is_none());
921                     self.r
922                         .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
923                 }
924                 return None;
925             }
926             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
927                 if no_ambiguity {
928                     assert!(import.imported_module.get().is_none());
929                     let err = match self.make_path_suggestion(
930                         span,
931                         import.module_path.clone(),
932                         &import.parent_scope,
933                     ) {
934                         Some((suggestion, note)) => UnresolvedImportError {
935                             span,
936                             label: None,
937                             note,
938                             suggestion: Some((
939                                 vec![(span, Segment::names_to_string(&suggestion))],
940                                 String::from("a similar path exists"),
941                                 Applicability::MaybeIncorrect,
942                             )),
943                         },
944                         None => UnresolvedImportError {
945                             span,
946                             label: Some(label),
947                             note: Vec::new(),
948                             suggestion,
949                         },
950                     };
951                     return Some(err);
952                 }
953                 return None;
954             }
955             PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
956                 if no_ambiguity {
957                     assert!(import.imported_module.get().is_none());
958                 }
959                 // The error was already reported earlier.
960                 return None;
961             }
962             PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
963         };
964
965         let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
966             ImportKind::Single {
967                 source,
968                 target,
969                 ref source_bindings,
970                 ref target_bindings,
971                 type_ns_only,
972                 ..
973             } => (source, target, source_bindings, target_bindings, type_ns_only),
974             ImportKind::Glob { is_prelude, ref max_vis } => {
975                 if import.module_path.len() <= 1 {
976                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
977                     // 2 segments, so the `resolve_path` above won't trigger it.
978                     let mut full_path = import.module_path.clone();
979                     full_path.push(Segment::from_ident(Ident::invalid()));
980                     self.r.lint_if_path_starts_with_module(
981                         import.crate_lint(),
982                         &full_path,
983                         import.span,
984                         None,
985                     );
986                 }
987
988                 if let ModuleOrUniformRoot::Module(module) = module {
989                     if module.def_id() == import.parent_scope.module.def_id() {
990                         // Importing a module into itself is not allowed.
991                         return Some(UnresolvedImportError {
992                             span: import.span,
993                             label: Some(String::from("cannot glob-import a module into itself")),
994                             note: Vec::new(),
995                             suggestion: None,
996                         });
997                     }
998                 }
999                 if !is_prelude &&
1000                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1001                    !max_vis.get().is_at_least(import.vis.get(), &*self)
1002                 {
1003                     let msg = "glob import doesn't reexport anything because no candidate is public enough";
1004                     self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
1005                 }
1006                 return None;
1007             }
1008             _ => unreachable!(),
1009         };
1010
1011         let mut all_ns_err = true;
1012         self.r.per_ns(|this, ns| {
1013             if !type_ns_only || ns == TypeNS {
1014                 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
1015                 let orig_blacklisted_binding =
1016                     mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1017                 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1018                 let binding = this.resolve_ident_in_module(
1019                     module,
1020                     ident,
1021                     ns,
1022                     &import.parent_scope,
1023                     true,
1024                     import.span,
1025                 );
1026                 this.last_import_segment = orig_last_import_segment;
1027                 this.blacklisted_binding = orig_blacklisted_binding;
1028                 import.vis.set(orig_vis);
1029
1030                 match binding {
1031                     Ok(binding) => {
1032                         // Consistency checks, analogous to `finalize_macro_resolutions`.
1033                         let initial_res = source_bindings[ns].get().map(|initial_binding| {
1034                             all_ns_err = false;
1035                             if let Some(target_binding) = target_bindings[ns].get() {
1036                                 // Note that as_str() de-gensyms the Symbol
1037                                 if target.name.as_str() == "_"
1038                                     && initial_binding.is_extern_crate()
1039                                     && !initial_binding.is_import()
1040                                 {
1041                                     this.record_use(
1042                                         ident,
1043                                         ns,
1044                                         target_binding,
1045                                         import.module_path.is_empty(),
1046                                     );
1047                                 }
1048                             }
1049                             initial_binding.res()
1050                         });
1051                         let res = binding.res();
1052                         if let Ok(initial_res) = initial_res {
1053                             if res != initial_res && this.ambiguity_errors.is_empty() {
1054                                 span_bug!(import.span, "inconsistent resolution for an import");
1055                             }
1056                         } else {
1057                             if res != Res::Err
1058                                 && this.ambiguity_errors.is_empty()
1059                                 && this.privacy_errors.is_empty()
1060                             {
1061                                 let msg = "cannot determine resolution for the import";
1062                                 let msg_note =
1063                                     "import resolution is stuck, try simplifying other imports";
1064                                 this.session
1065                                     .struct_span_err(import.span, msg)
1066                                     .note(msg_note)
1067                                     .emit();
1068                             }
1069                         }
1070                     }
1071                     Err(..) => {
1072                         // FIXME: This assert may fire if public glob is later shadowed by a private
1073                         // single import (see test `issue-55884-2.rs`). In theory single imports should
1074                         // always block globs, even if they are not yet resolved, so that this kind of
1075                         // self-inconsistent resolution never happens.
1076                         // Re-enable the assert when the issue is fixed.
1077                         // assert!(result[ns].get().is_err());
1078                     }
1079                 }
1080             }
1081         });
1082
1083         if all_ns_err {
1084             let mut all_ns_failed = true;
1085             self.r.per_ns(|this, ns| {
1086                 if !type_ns_only || ns == TypeNS {
1087                     let binding = this.resolve_ident_in_module(
1088                         module,
1089                         ident,
1090                         ns,
1091                         &import.parent_scope,
1092                         true,
1093                         import.span,
1094                     );
1095                     if binding.is_ok() {
1096                         all_ns_failed = false;
1097                     }
1098                 }
1099             });
1100
1101             return if all_ns_failed {
1102                 let resolutions = match module {
1103                     ModuleOrUniformRoot::Module(module) => {
1104                         Some(self.r.resolutions(module).borrow())
1105                     }
1106                     _ => None,
1107                 };
1108                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1109                 let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1110                     if *i == ident {
1111                         return None;
1112                     } // Never suggest the same name
1113                     match *resolution.borrow() {
1114                         NameResolution { binding: Some(name_binding), .. } => {
1115                             match name_binding.kind {
1116                                 NameBindingKind::Import { binding, .. } => {
1117                                     match binding.kind {
1118                                         // Never suggest the name that has binding error
1119                                         // i.e., the name that cannot be previously resolved
1120                                         NameBindingKind::Res(Res::Err, _) => None,
1121                                         _ => Some(&i.name),
1122                                     }
1123                                 }
1124                                 _ => Some(&i.name),
1125                             }
1126                         }
1127                         NameResolution { ref single_imports, .. } if single_imports.is_empty() => {
1128                             None
1129                         }
1130                         _ => Some(&i.name),
1131                     }
1132                 });
1133
1134                 let lev_suggestion =
1135                     find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1136                         (
1137                             vec![(ident.span, suggestion.to_string())],
1138                             String::from("a similar name exists in the module"),
1139                             Applicability::MaybeIncorrect,
1140                         )
1141                     });
1142
1143                 let (suggestion, note) =
1144                     match self.check_for_module_export_macro(import, module, ident) {
1145                         Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1146                         _ => (lev_suggestion, Vec::new()),
1147                     };
1148
1149                 let label = match module {
1150                     ModuleOrUniformRoot::Module(module) => {
1151                         let module_str = module_to_string(module);
1152                         if let Some(module_str) = module_str {
1153                             format!("no `{}` in `{}`", ident, module_str)
1154                         } else {
1155                             format!("no `{}` in the root", ident)
1156                         }
1157                     }
1158                     _ => {
1159                         if !ident.is_path_segment_keyword() {
1160                             format!("no `{}` external crate", ident)
1161                         } else {
1162                             // HACK(eddyb) this shows up for `self` & `super`, which
1163                             // should work instead - for now keep the same error message.
1164                             format!("no `{}` in the root", ident)
1165                         }
1166                     }
1167                 };
1168
1169                 Some(UnresolvedImportError {
1170                     span: import.span,
1171                     label: Some(label),
1172                     note,
1173                     suggestion,
1174                 })
1175             } else {
1176                 // `resolve_ident_in_module` reported a privacy error.
1177                 self.r.import_dummy_binding(import);
1178                 None
1179             };
1180         }
1181
1182         let mut reexport_error = None;
1183         let mut any_successful_reexport = false;
1184         self.r.per_ns(|this, ns| {
1185             if let Ok(binding) = source_bindings[ns].get() {
1186                 let vis = import.vis.get();
1187                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1188                     reexport_error = Some((ns, binding));
1189                 } else {
1190                     any_successful_reexport = true;
1191                 }
1192             }
1193         });
1194
1195         // All namespaces must be re-exported with extra visibility for an error to occur.
1196         if !any_successful_reexport {
1197             let (ns, binding) = reexport_error.unwrap();
1198             if ns == TypeNS && binding.is_extern_crate() {
1199                 let msg = format!(
1200                     "extern crate `{}` is private, and cannot be \
1201                                    re-exported (error E0365), consider declaring with \
1202                                    `pub`",
1203                     ident
1204                 );
1205                 self.r.lint_buffer.buffer_lint(
1206                     PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1207                     import.id,
1208                     import.span,
1209                     &msg,
1210                 );
1211             } else if ns == TypeNS {
1212                 struct_span_err!(
1213                     self.r.session,
1214                     import.span,
1215                     E0365,
1216                     "`{}` is private, and cannot be re-exported",
1217                     ident
1218                 )
1219                 .span_label(import.span, format!("re-export of private `{}`", ident))
1220                 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1221                 .emit();
1222             } else {
1223                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1224                 let note_msg =
1225                     format!("consider marking `{}` as `pub` in the imported module", ident,);
1226                 struct_span_err!(self.r.session, import.span, E0364, "{}", &msg)
1227                     .span_note(import.span, &note_msg)
1228                     .emit();
1229             }
1230         }
1231
1232         if import.module_path.len() <= 1 {
1233             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1234             // 2 segments, so the `resolve_path` above won't trigger it.
1235             let mut full_path = import.module_path.clone();
1236             full_path.push(Segment::from_ident(ident));
1237             self.r.per_ns(|this, ns| {
1238                 if let Ok(binding) = source_bindings[ns].get() {
1239                     this.lint_if_path_starts_with_module(
1240                         import.crate_lint(),
1241                         &full_path,
1242                         import.span,
1243                         Some(binding),
1244                     );
1245                 }
1246             });
1247         }
1248
1249         // Record what this import resolves to for later uses in documentation,
1250         // this may resolve to either a value or a type, but for documentation
1251         // purposes it's good enough to just favor one over the other.
1252         self.r.per_ns(|this, ns| {
1253             if let Ok(binding) = source_bindings[ns].get() {
1254                 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
1255             }
1256         });
1257
1258         self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
1259
1260         debug!("(resolving single import) successfully resolved import");
1261         None
1262     }
1263
1264     fn check_for_redundant_imports(
1265         &mut self,
1266         ident: Ident,
1267         import: &'b Import<'b>,
1268         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1269         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1270         target: Ident,
1271     ) {
1272         // Skip if the import was produced by a macro.
1273         if import.parent_scope.expansion != ExpnId::root() {
1274             return;
1275         }
1276
1277         // Skip if we are inside a named module (in contrast to an anonymous
1278         // module defined by a block).
1279         if let ModuleKind::Def(..) = import.parent_scope.module.kind {
1280             return;
1281         }
1282
1283         let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1284
1285         let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1286
1287         self.r.per_ns(|this, ns| {
1288             if let Ok(binding) = source_bindings[ns].get() {
1289                 if binding.res() == Res::Err {
1290                     return;
1291                 }
1292
1293                 let orig_blacklisted_binding =
1294                     mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1295
1296                 match this.early_resolve_ident_in_lexical_scope(
1297                     target,
1298                     ScopeSet::All(ns, false),
1299                     &import.parent_scope,
1300                     false,
1301                     false,
1302                     import.span,
1303                 ) {
1304                     Ok(other_binding) => {
1305                         is_redundant[ns] = Some(
1306                             binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1307                         );
1308                         redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1309                     }
1310                     Err(_) => is_redundant[ns] = Some(false),
1311                 }
1312
1313                 this.blacklisted_binding = orig_blacklisted_binding;
1314             }
1315         });
1316
1317         if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1318         {
1319             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1320             redundant_spans.sort();
1321             redundant_spans.dedup();
1322             self.r.lint_buffer.buffer_lint_with_diagnostic(
1323                 UNUSED_IMPORTS,
1324                 import.id,
1325                 import.span,
1326                 &format!("the item `{}` is imported redundantly", ident),
1327                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1328             );
1329         }
1330     }
1331
1332     fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1333         let module = match import.imported_module.get().unwrap() {
1334             ModuleOrUniformRoot::Module(module) => module,
1335             _ => {
1336                 self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1337                 return;
1338             }
1339         };
1340
1341         if module.is_trait() {
1342             self.r.session.span_err(import.span, "items in traits are not importable.");
1343             return;
1344         } else if module.def_id() == import.parent_scope.module.def_id() {
1345             return;
1346         } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1347             self.r.prelude = Some(module);
1348             return;
1349         }
1350
1351         // Add to module's glob_importers
1352         module.glob_importers.borrow_mut().push(import);
1353
1354         // Ensure that `resolutions` isn't borrowed during `try_define`,
1355         // since it might get updated via a glob cycle.
1356         let bindings = self
1357             .r
1358             .resolutions(module)
1359             .borrow()
1360             .iter()
1361             .filter_map(|(key, resolution)| {
1362                 resolution.borrow().binding().map(|binding| (*key, binding))
1363             })
1364             .collect::<Vec<_>>();
1365         for (mut key, binding) in bindings {
1366             let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1367                 Some(Some(def)) => self.r.macro_def_scope(def),
1368                 Some(None) => import.parent_scope.module,
1369                 None => continue,
1370             };
1371             if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
1372                 let imported_binding = self.r.import(binding, import);
1373                 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1374             }
1375         }
1376
1377         // Record the destination of this import
1378         self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1379     }
1380
1381     // Miscellaneous post-processing, including recording re-exports,
1382     // reporting conflicts, and reporting unresolved imports.
1383     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1384         // Since import resolution is finished, globs will not define any more names.
1385         *module.globs.borrow_mut() = Vec::new();
1386
1387         let mut reexports = Vec::new();
1388
1389         module.for_each_child(self.r, |this, ident, ns, binding| {
1390             // Filter away ambiguous imports and anything that has def-site
1391             // hygiene.
1392             // FIXME: Implement actual cross-crate hygiene.
1393             let is_good_import =
1394                 binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion();
1395             if is_good_import || binding.is_macro_def() {
1396                 let res = binding.res().map_id(|id| this.definitions.local_def_id(id));
1397                 if res != def::Res::Err {
1398                     reexports.push(Export { ident, res, span: binding.span, vis: binding.vis });
1399                 }
1400             }
1401
1402             if let NameBindingKind::Import { binding: orig_binding, import, .. } = binding.kind {
1403                 if ns == TypeNS
1404                     && orig_binding.is_variant()
1405                     && !orig_binding.vis.is_at_least(binding.vis, &*this)
1406                 {
1407                     let msg = match import.kind {
1408                         ImportKind::Single { .. } => {
1409                             format!("variant `{}` is private and cannot be re-exported", ident)
1410                         }
1411                         ImportKind::Glob { .. } => {
1412                             let msg = "enum is private and its variants \
1413                                            cannot be re-exported"
1414                                 .to_owned();
1415                             let error_id = (
1416                                 DiagnosticMessageId::ErrorId(0), // no code?!
1417                                 Some(binding.span),
1418                                 msg.clone(),
1419                             );
1420                             let fresh =
1421                                 this.session.one_time_diagnostics.borrow_mut().insert(error_id);
1422                             if !fresh {
1423                                 return;
1424                             }
1425                             msg
1426                         }
1427                         ref s => bug!("unexpected import kind {:?}", s),
1428                     };
1429                     let mut err = this.session.struct_span_err(binding.span, &msg);
1430
1431                     let imported_module = match import.imported_module.get() {
1432                         Some(ModuleOrUniformRoot::Module(module)) => module,
1433                         _ => bug!("module should exist"),
1434                     };
1435                     let parent_module = imported_module.parent.expect("parent should exist");
1436                     let resolutions = this.resolutions(parent_module).borrow();
1437                     let enum_path_segment_index = import.module_path.len() - 1;
1438                     let enum_ident = import.module_path[enum_path_segment_index].ident;
1439
1440                     let key = this.new_key(enum_ident, TypeNS);
1441                     let enum_resolution = resolutions.get(&key).expect("resolution should exist");
1442                     let enum_span =
1443                         enum_resolution.borrow().binding.expect("binding should exist").span;
1444                     let enum_def_span = this.session.source_map().guess_head_span(enum_span);
1445                     let enum_def_snippet = this
1446                         .session
1447                         .source_map()
1448                         .span_to_snippet(enum_def_span)
1449                         .expect("snippet should exist");
1450                     // potentially need to strip extant `crate`/`pub(path)` for suggestion
1451                     let after_vis_index = enum_def_snippet
1452                         .find("enum")
1453                         .expect("`enum` keyword should exist in snippet");
1454                     let suggestion = format!("pub {}", &enum_def_snippet[after_vis_index..]);
1455
1456                     this.session.diag_span_suggestion_once(
1457                         &mut err,
1458                         DiagnosticMessageId::ErrorId(0),
1459                         enum_def_span,
1460                         "consider making the enum public",
1461                         suggestion,
1462                     );
1463                     err.emit();
1464                 }
1465             }
1466         });
1467
1468         if !reexports.is_empty() {
1469             if let Some(def_id) = module.def_id() {
1470                 // Call to `expect_local` should be fine because current
1471                 // code is only called for local modules.
1472                 self.r.export_map.insert(def_id.expect_local(), reexports);
1473             }
1474         }
1475     }
1476 }
1477
1478 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1479     let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1480     let global = !names.is_empty() && names[0].name == kw::PathRoot;
1481     if let Some(pos) = pos {
1482         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1483         names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1484     } else {
1485         let names = if global { &names[1..] } else { names };
1486         if names.is_empty() {
1487             import_kind_to_string(import_kind)
1488         } else {
1489             format!(
1490                 "{}::{}",
1491                 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1492                 import_kind_to_string(import_kind),
1493             )
1494         }
1495     }
1496 }
1497
1498 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1499     match import_kind {
1500         ImportKind::Single { source, .. } => source.to_string(),
1501         ImportKind::Glob { .. } => "*".to_string(),
1502         ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1503         ImportKind::MacroUse => "#[macro_use]".to_string(),
1504     }
1505 }