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