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