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