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