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