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