]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/diagnostics.rs
Rollup merge of #96568 - EliasHolzmann:fmt_doc_fixes, r=joshtriplett
[rust.git] / compiler / rustc_resolve / src / diagnostics.rs
1 use std::ptr;
2
3 use rustc_ast::ptr::P;
4 use rustc_ast::visit::{self, Visitor};
5 use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::struct_span_err;
9 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
10 use rustc_feature::BUILTIN_ATTRIBUTES;
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
13 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_hir::PrimTy;
15 use rustc_middle::bug;
16 use rustc_middle::ty::DefIdTree;
17 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
18 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
19 use rustc_session::lint::BuiltinLintDiagnostics;
20 use rustc_session::Session;
21 use rustc_span::edition::Edition;
22 use rustc_span::hygiene::MacroKind;
23 use rustc_span::lev_distance::find_best_match_for_name;
24 use rustc_span::source_map::SourceMap;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Span};
27 use tracing::debug;
28
29 use crate::imports::{Import, ImportKind, ImportResolver};
30 use crate::late::Rib;
31 use crate::path_names_to_string;
32 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
33 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
34 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
35 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
36 use crate::{Segment, UseError};
37
38 type Res = def::Res<ast::NodeId>;
39
40 /// A vector of spans and replacements, a message and applicability.
41 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
42
43 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
44 /// similarly named label and whether or not it is reachable.
45 crate type LabelSuggestion = (Ident, bool);
46
47 crate enum SuggestionTarget {
48     /// The target has a similar name as the name used by the programmer (probably a typo)
49     SimilarlyNamed,
50     /// The target is the only valid item that can be used in the corresponding context
51     SingleItem,
52 }
53
54 crate struct TypoSuggestion {
55     pub candidate: Symbol,
56     pub res: Res,
57     pub target: SuggestionTarget,
58 }
59
60 impl TypoSuggestion {
61     crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
62         Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
63     }
64     crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
65         Self { candidate, res, target: SuggestionTarget::SingleItem }
66     }
67 }
68
69 /// A free importable items suggested in case of resolution failure.
70 crate struct ImportSuggestion {
71     pub did: Option<DefId>,
72     pub descr: &'static str,
73     pub path: Path,
74     pub accessible: bool,
75     /// An extra note that should be issued if this item is suggested
76     pub note: Option<String>,
77 }
78
79 /// Adjust the impl span so that just the `impl` keyword is taken by removing
80 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
81 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
82 ///
83 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
84 /// parser. If you need to use this function or something similar, please consider updating the
85 /// `source_map` functions and this function to something more robust.
86 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
87     let impl_span = sm.span_until_char(impl_span, '<');
88     sm.span_until_whitespace(impl_span)
89 }
90
91 impl<'a> Resolver<'a> {
92     crate fn report_errors(&mut self, krate: &Crate) {
93         self.report_with_use_injections(krate);
94
95         for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
96             let msg = "macro-expanded `macro_export` macros from the current crate \
97                        cannot be referred to by absolute paths";
98             self.lint_buffer.buffer_lint_with_diagnostic(
99                 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
100                 CRATE_NODE_ID,
101                 span_use,
102                 msg,
103                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
104             );
105         }
106
107         for ambiguity_error in &self.ambiguity_errors {
108             self.report_ambiguity_error(ambiguity_error);
109         }
110
111         let mut reported_spans = FxHashSet::default();
112         for error in &self.privacy_errors {
113             if reported_spans.insert(error.dedup_span) {
114                 self.report_privacy_error(error);
115             }
116         }
117     }
118
119     fn report_with_use_injections(&mut self, krate: &Crate) {
120         for UseError { mut err, candidates, def_id, instead, suggestion } in
121             self.use_injections.drain(..)
122         {
123             let (span, found_use) = if let Some(def_id) = def_id.as_local() {
124                 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
125             } else {
126                 (None, FoundUse::No)
127             };
128             if !candidates.is_empty() {
129                 show_candidates(
130                     &self.definitions,
131                     self.session,
132                     &mut err,
133                     span,
134                     &candidates,
135                     if instead { Instead::Yes } else { Instead::No },
136                     found_use,
137                     IsPattern::No,
138                 );
139             } else if let Some((span, msg, sugg, appl)) = suggestion {
140                 err.span_suggestion(span, msg, sugg, appl);
141             }
142             err.emit();
143         }
144     }
145
146     crate fn report_conflict<'b>(
147         &mut self,
148         parent: Module<'_>,
149         ident: Ident,
150         ns: Namespace,
151         new_binding: &NameBinding<'b>,
152         old_binding: &NameBinding<'b>,
153     ) {
154         // Error on the second of two conflicting names
155         if old_binding.span.lo() > new_binding.span.lo() {
156             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
157         }
158
159         let container = match parent.kind {
160             ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
161             ModuleKind::Block(..) => "block",
162         };
163
164         let old_noun = match old_binding.is_import() {
165             true => "import",
166             false => "definition",
167         };
168
169         let new_participle = match new_binding.is_import() {
170             true => "imported",
171             false => "defined",
172         };
173
174         let (name, span) =
175             (ident.name, self.session.source_map().guess_head_span(new_binding.span));
176
177         if let Some(s) = self.name_already_seen.get(&name) {
178             if s == &span {
179                 return;
180             }
181         }
182
183         let old_kind = match (ns, old_binding.module()) {
184             (ValueNS, _) => "value",
185             (MacroNS, _) => "macro",
186             (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
187             (TypeNS, Some(module)) if module.is_normal() => "module",
188             (TypeNS, Some(module)) if module.is_trait() => "trait",
189             (TypeNS, _) => "type",
190         };
191
192         let msg = format!("the name `{}` is defined multiple times", name);
193
194         let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
195             (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
196             (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
197                 true => struct_span_err!(self.session, span, E0254, "{}", msg),
198                 false => struct_span_err!(self.session, span, E0260, "{}", msg),
199             },
200             _ => match (old_binding.is_import(), new_binding.is_import()) {
201                 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
202                 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
203                 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
204             },
205         };
206
207         err.note(&format!(
208             "`{}` must be defined only once in the {} namespace of this {}",
209             name,
210             ns.descr(),
211             container
212         ));
213
214         err.span_label(span, format!("`{}` re{} here", name, new_participle));
215         err.span_label(
216             self.session.source_map().guess_head_span(old_binding.span),
217             format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
218         );
219
220         // See https://github.com/rust-lang/rust/issues/32354
221         use NameBindingKind::Import;
222         let import = match (&new_binding.kind, &old_binding.kind) {
223             // If there are two imports where one or both have attributes then prefer removing the
224             // import without attributes.
225             (Import { import: new, .. }, Import { import: old, .. })
226                 if {
227                     !new_binding.span.is_dummy()
228                         && !old_binding.span.is_dummy()
229                         && (new.has_attributes || old.has_attributes)
230                 } =>
231             {
232                 if old.has_attributes {
233                     Some((new, new_binding.span, true))
234                 } else {
235                     Some((old, old_binding.span, true))
236                 }
237             }
238             // Otherwise prioritize the new binding.
239             (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
240                 Some((import, new_binding.span, other.is_import()))
241             }
242             (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
243                 Some((import, old_binding.span, other.is_import()))
244             }
245             _ => None,
246         };
247
248         // Check if the target of the use for both bindings is the same.
249         let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
250         let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
251         let from_item =
252             self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
253         // Only suggest removing an import if both bindings are to the same def, if both spans
254         // aren't dummy spans. Further, if both bindings are imports, then the ident must have
255         // been introduced by an item.
256         let should_remove_import = duplicate
257             && !has_dummy_span
258             && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
259
260         match import {
261             Some((import, span, true)) if should_remove_import && import.is_nested() => {
262                 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
263             }
264             Some((import, _, true)) if should_remove_import && !import.is_glob() => {
265                 // Simple case - remove the entire import. Due to the above match arm, this can
266                 // only be a single use so just remove it entirely.
267                 err.tool_only_span_suggestion(
268                     import.use_span_with_attributes,
269                     "remove unnecessary import",
270                     String::new(),
271                     Applicability::MaybeIncorrect,
272                 );
273             }
274             Some((import, span, _)) => {
275                 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
276             }
277             _ => {}
278         }
279
280         err.emit();
281         self.name_already_seen.insert(name, span);
282     }
283
284     /// This function adds a suggestion to change the binding name of a new import that conflicts
285     /// with an existing import.
286     ///
287     /// ```text,ignore (diagnostic)
288     /// help: you can use `as` to change the binding name of the import
289     ///    |
290     /// LL | use foo::bar as other_bar;
291     ///    |     ^^^^^^^^^^^^^^^^^^^^^
292     /// ```
293     fn add_suggestion_for_rename_of_use(
294         &self,
295         err: &mut Diagnostic,
296         name: Symbol,
297         import: &Import<'_>,
298         binding_span: Span,
299     ) {
300         let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
301             format!("Other{}", name)
302         } else {
303             format!("other_{}", name)
304         };
305
306         let mut suggestion = None;
307         match import.kind {
308             ImportKind::Single { type_ns_only: true, .. } => {
309                 suggestion = Some(format!("self as {}", suggested_name))
310             }
311             ImportKind::Single { source, .. } => {
312                 if let Some(pos) =
313                     source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
314                 {
315                     if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
316                         if pos <= snippet.len() {
317                             suggestion = Some(format!(
318                                 "{} as {}{}",
319                                 &snippet[..pos],
320                                 suggested_name,
321                                 if snippet.ends_with(';') { ";" } else { "" }
322                             ))
323                         }
324                     }
325                 }
326             }
327             ImportKind::ExternCrate { source, target } => {
328                 suggestion = Some(format!(
329                     "extern crate {} as {};",
330                     source.unwrap_or(target.name),
331                     suggested_name,
332                 ))
333             }
334             _ => unreachable!(),
335         }
336
337         let rename_msg = "you can use `as` to change the binding name of the import";
338         if let Some(suggestion) = suggestion {
339             err.span_suggestion(
340                 binding_span,
341                 rename_msg,
342                 suggestion,
343                 Applicability::MaybeIncorrect,
344             );
345         } else {
346             err.span_label(binding_span, rename_msg);
347         }
348     }
349
350     /// This function adds a suggestion to remove an unnecessary binding from an import that is
351     /// nested. In the following example, this function will be invoked to remove the `a` binding
352     /// in the second use statement:
353     ///
354     /// ```ignore (diagnostic)
355     /// use issue_52891::a;
356     /// use issue_52891::{d, a, e};
357     /// ```
358     ///
359     /// The following suggestion will be added:
360     ///
361     /// ```ignore (diagnostic)
362     /// use issue_52891::{d, a, e};
363     ///                      ^-- help: remove unnecessary import
364     /// ```
365     ///
366     /// If the nested use contains only one import then the suggestion will remove the entire
367     /// line.
368     ///
369     /// It is expected that the provided import is nested - this isn't checked by the
370     /// function. If this invariant is not upheld, this function's behaviour will be unexpected
371     /// as characters expected by span manipulations won't be present.
372     fn add_suggestion_for_duplicate_nested_use(
373         &self,
374         err: &mut Diagnostic,
375         import: &Import<'_>,
376         binding_span: Span,
377     ) {
378         assert!(import.is_nested());
379         let message = "remove unnecessary import";
380
381         // Two examples will be used to illustrate the span manipulations we're doing:
382         //
383         // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
384         //   `a` and `import.use_span` is `issue_52891::{d, a, e};`.
385         // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
386         //   `a` and `import.use_span` is `issue_52891::{d, e, a};`.
387
388         let (found_closing_brace, span) =
389             find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
390
391         // If there was a closing brace then identify the span to remove any trailing commas from
392         // previous imports.
393         if found_closing_brace {
394             if let Some(span) = extend_span_to_previous_binding(self.session, span) {
395                 err.tool_only_span_suggestion(
396                     span,
397                     message,
398                     String::new(),
399                     Applicability::MaybeIncorrect,
400                 );
401             } else {
402                 // Remove the entire line if we cannot extend the span back, this indicates an
403                 // `issue_52891::{self}` case.
404                 err.span_suggestion(
405                     import.use_span_with_attributes,
406                     message,
407                     String::new(),
408                     Applicability::MaybeIncorrect,
409                 );
410             }
411
412             return;
413         }
414
415         err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
416     }
417
418     crate fn lint_if_path_starts_with_module(
419         &mut self,
420         finalize: Option<Finalize>,
421         path: &[Segment],
422         second_binding: Option<&NameBinding<'_>>,
423     ) {
424         let Some(Finalize { node_id, root_span, .. }) = finalize else {
425             return;
426         };
427
428         let first_name = match path.get(0) {
429             // In the 2018 edition this lint is a hard error, so nothing to do
430             Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
431             _ => return,
432         };
433
434         // We're only interested in `use` paths which should start with
435         // `{{root}}` currently.
436         if first_name != kw::PathRoot {
437             return;
438         }
439
440         match path.get(1) {
441             // If this import looks like `crate::...` it's already good
442             Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
443             // Otherwise go below to see if it's an extern crate
444             Some(_) => {}
445             // If the path has length one (and it's `PathRoot` most likely)
446             // then we don't know whether we're gonna be importing a crate or an
447             // item in our crate. Defer this lint to elsewhere
448             None => return,
449         }
450
451         // If the first element of our path was actually resolved to an
452         // `ExternCrate` (also used for `crate::...`) then no need to issue a
453         // warning, this looks all good!
454         if let Some(binding) = second_binding {
455             if let NameBindingKind::Import { import, .. } = binding.kind {
456                 // Careful: we still want to rewrite paths from renamed extern crates.
457                 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
458                     return;
459                 }
460             }
461         }
462
463         let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
464         self.lint_buffer.buffer_lint_with_diagnostic(
465             ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
466             node_id,
467             root_span,
468             "absolute paths must start with `self`, `super`, \
469              `crate`, or an external crate name in the 2018 edition",
470             diag,
471         );
472     }
473
474     crate fn add_module_candidates(
475         &mut self,
476         module: Module<'a>,
477         names: &mut Vec<TypoSuggestion>,
478         filter_fn: &impl Fn(Res) -> bool,
479     ) {
480         for (key, resolution) in self.resolutions(module).borrow().iter() {
481             if let Some(binding) = resolution.borrow().binding {
482                 let res = binding.res();
483                 if filter_fn(res) {
484                     names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
485                 }
486             }
487         }
488     }
489
490     /// Combines an error with provided span and emits it.
491     ///
492     /// This takes the error provided, combines it with the span and any additional spans inside the
493     /// error and emits it.
494     crate fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
495         self.into_struct_error(span, resolution_error).emit();
496     }
497
498     crate fn into_struct_error(
499         &mut self,
500         span: Span,
501         resolution_error: ResolutionError<'a>,
502     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
503         match resolution_error {
504             ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
505                 let mut err = struct_span_err!(
506                     self.session,
507                     span,
508                     E0401,
509                     "can't use generic parameters from outer function",
510                 );
511                 err.span_label(span, "use of generic parameter from outer function".to_string());
512
513                 let sm = self.session.source_map();
514                 match outer_res {
515                     Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
516                         if let Some(impl_span) =
517                             maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
518                         {
519                             err.span_label(
520                                 reduce_impl_span_to_impl_keyword(sm, impl_span),
521                                 "`Self` type implicitly declared here, by this `impl`",
522                             );
523                         }
524                         match (maybe_trait_defid, maybe_impl_defid) {
525                             (Some(_), None) => {
526                                 err.span_label(span, "can't use `Self` here");
527                             }
528                             (_, Some(_)) => {
529                                 err.span_label(span, "use a type here instead");
530                             }
531                             (None, None) => bug!("`impl` without trait nor type?"),
532                         }
533                         return err;
534                     }
535                     Res::Def(DefKind::TyParam, def_id) => {
536                         if let Some(span) = self.opt_span(def_id) {
537                             err.span_label(span, "type parameter from outer function");
538                         }
539                     }
540                     Res::Def(DefKind::ConstParam, def_id) => {
541                         if let Some(span) = self.opt_span(def_id) {
542                             err.span_label(span, "const parameter from outer function");
543                         }
544                     }
545                     _ => {
546                         bug!(
547                             "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
548                             DefKind::TyParam or DefKind::ConstParam"
549                         );
550                     }
551                 }
552
553                 if has_generic_params == HasGenericParams::Yes {
554                     // Try to retrieve the span of the function signature and generate a new
555                     // message with a local type or const parameter.
556                     let sugg_msg = "try using a local generic parameter instead";
557                     if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
558                         // Suggest the modification to the user
559                         err.span_suggestion(
560                             sugg_span,
561                             sugg_msg,
562                             snippet,
563                             Applicability::MachineApplicable,
564                         );
565                     } else if let Some(sp) = sm.generate_fn_name_span(span) {
566                         err.span_label(
567                             sp,
568                             "try adding a local generic parameter in this method instead"
569                                 .to_string(),
570                         );
571                     } else {
572                         err.help("try using a local generic parameter instead");
573                     }
574                 }
575
576                 err
577             }
578             ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
579                 let mut err = struct_span_err!(
580                     self.session,
581                     span,
582                     E0403,
583                     "the name `{}` is already used for a generic \
584                      parameter in this item's generic parameters",
585                     name,
586                 );
587                 err.span_label(span, "already used");
588                 err.span_label(first_use_span, format!("first use of `{}`", name));
589                 err
590             }
591             ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
592                 let mut err = struct_span_err!(
593                     self.session,
594                     span,
595                     E0407,
596                     "method `{}` is not a member of trait `{}`",
597                     method,
598                     trait_
599                 );
600                 err.span_label(span, format!("not a member of trait `{}`", trait_));
601                 if let Some(candidate) = candidate {
602                     err.span_suggestion(
603                         method.span,
604                         "there is an associated function with a similar name",
605                         candidate.to_ident_string(),
606                         Applicability::MaybeIncorrect,
607                     );
608                 }
609                 err
610             }
611             ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
612                 let mut err = struct_span_err!(
613                     self.session,
614                     span,
615                     E0437,
616                     "type `{}` is not a member of trait `{}`",
617                     type_,
618                     trait_
619                 );
620                 err.span_label(span, format!("not a member of trait `{}`", trait_));
621                 if let Some(candidate) = candidate {
622                     err.span_suggestion(
623                         type_.span,
624                         "there is an associated type with a similar name",
625                         candidate.to_ident_string(),
626                         Applicability::MaybeIncorrect,
627                     );
628                 }
629                 err
630             }
631             ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
632                 let mut err = struct_span_err!(
633                     self.session,
634                     span,
635                     E0438,
636                     "const `{}` is not a member of trait `{}`",
637                     const_,
638                     trait_
639                 );
640                 err.span_label(span, format!("not a member of trait `{}`", trait_));
641                 if let Some(candidate) = candidate {
642                     err.span_suggestion(
643                         const_.span,
644                         "there is an associated constant with a similar name",
645                         candidate.to_ident_string(),
646                         Applicability::MaybeIncorrect,
647                     );
648                 }
649                 err
650             }
651             ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
652                 let BindingError { name, target, origin, could_be_path } = binding_error;
653
654                 let target_sp = target.iter().copied().collect::<Vec<_>>();
655                 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
656
657                 let msp = MultiSpan::from_spans(target_sp.clone());
658                 let mut err = struct_span_err!(
659                     self.session,
660                     msp,
661                     E0408,
662                     "variable `{}` is not bound in all patterns",
663                     name,
664                 );
665                 for sp in target_sp {
666                     err.span_label(sp, format!("pattern doesn't bind `{}`", name));
667                 }
668                 for sp in origin_sp {
669                     err.span_label(sp, "variable not in all patterns");
670                 }
671                 if could_be_path {
672                     let import_suggestions = self.lookup_import_candidates(
673                         Ident::with_dummy_span(name),
674                         Namespace::ValueNS,
675                         &parent_scope,
676                         &|res: Res| match res {
677                             Res::Def(
678                                 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
679                                 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
680                                 | DefKind::Const
681                                 | DefKind::AssocConst,
682                                 _,
683                             ) => true,
684                             _ => false,
685                         },
686                     );
687
688                     if import_suggestions.is_empty() {
689                         let help_msg = format!(
690                             "if you meant to match on a variant or a `const` item, consider \
691                              making the path in the pattern qualified: `path::to::ModOrType::{}`",
692                             name,
693                         );
694                         err.span_help(span, &help_msg);
695                     }
696                     show_candidates(
697                         &self.definitions,
698                         self.session,
699                         &mut err,
700                         Some(span),
701                         &import_suggestions,
702                         Instead::No,
703                         FoundUse::Yes,
704                         IsPattern::Yes,
705                     );
706                 }
707                 err
708             }
709             ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
710                 let mut err = struct_span_err!(
711                     self.session,
712                     span,
713                     E0409,
714                     "variable `{}` is bound inconsistently across alternatives separated by `|`",
715                     variable_name
716                 );
717                 err.span_label(span, "bound in different ways");
718                 err.span_label(first_binding_span, "first binding");
719                 err
720             }
721             ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
722                 let mut err = struct_span_err!(
723                     self.session,
724                     span,
725                     E0415,
726                     "identifier `{}` is bound more than once in this parameter list",
727                     identifier
728                 );
729                 err.span_label(span, "used as parameter more than once");
730                 err
731             }
732             ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
733                 let mut err = struct_span_err!(
734                     self.session,
735                     span,
736                     E0416,
737                     "identifier `{}` is bound more than once in the same pattern",
738                     identifier
739                 );
740                 err.span_label(span, "used in a pattern more than once");
741                 err
742             }
743             ResolutionError::UndeclaredLabel { name, suggestion } => {
744                 let mut err = struct_span_err!(
745                     self.session,
746                     span,
747                     E0426,
748                     "use of undeclared label `{}`",
749                     name
750                 );
751
752                 err.span_label(span, format!("undeclared label `{}`", name));
753
754                 match suggestion {
755                     // A reachable label with a similar name exists.
756                     Some((ident, true)) => {
757                         err.span_label(ident.span, "a label with a similar name is reachable");
758                         err.span_suggestion(
759                             span,
760                             "try using similarly named label",
761                             ident.name.to_string(),
762                             Applicability::MaybeIncorrect,
763                         );
764                     }
765                     // An unreachable label with a similar name exists.
766                     Some((ident, false)) => {
767                         err.span_label(
768                             ident.span,
769                             "a label with a similar name exists but is unreachable",
770                         );
771                     }
772                     // No similarly-named labels exist.
773                     None => (),
774                 }
775
776                 err
777             }
778             ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
779                 let mut err = struct_span_err!(
780                     self.session,
781                     span,
782                     E0429,
783                     "{}",
784                     "`self` imports are only allowed within a { } list"
785                 );
786
787                 // None of the suggestions below would help with a case like `use self`.
788                 if !root {
789                     // use foo::bar::self        -> foo::bar
790                     // use foo::bar::self as abc -> foo::bar as abc
791                     err.span_suggestion(
792                         span,
793                         "consider importing the module directly",
794                         "".to_string(),
795                         Applicability::MachineApplicable,
796                     );
797
798                     // use foo::bar::self        -> foo::bar::{self}
799                     // use foo::bar::self as abc -> foo::bar::{self as abc}
800                     let braces = vec![
801                         (span_with_rename.shrink_to_lo(), "{".to_string()),
802                         (span_with_rename.shrink_to_hi(), "}".to_string()),
803                     ];
804                     err.multipart_suggestion(
805                         "alternatively, use the multi-path `use` syntax to import `self`",
806                         braces,
807                         Applicability::MachineApplicable,
808                     );
809                 }
810                 err
811             }
812             ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
813                 let mut err = struct_span_err!(
814                     self.session,
815                     span,
816                     E0430,
817                     "`self` import can only appear once in an import list"
818                 );
819                 err.span_label(span, "can only appear once in an import list");
820                 err
821             }
822             ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
823                 let mut err = struct_span_err!(
824                     self.session,
825                     span,
826                     E0431,
827                     "`self` import can only appear in an import list with \
828                                                 a non-empty prefix"
829                 );
830                 err.span_label(span, "can only appear in an import list with a non-empty prefix");
831                 err
832             }
833             ResolutionError::FailedToResolve { label, suggestion } => {
834                 let mut err =
835                     struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
836                 err.span_label(span, label);
837
838                 if let Some((suggestions, msg, applicability)) = suggestion {
839                     if suggestions.is_empty() {
840                         err.help(&msg);
841                         return err;
842                     }
843                     err.multipart_suggestion(&msg, suggestions, applicability);
844                 }
845
846                 err
847             }
848             ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
849                 let mut err = struct_span_err!(
850                     self.session,
851                     span,
852                     E0434,
853                     "{}",
854                     "can't capture dynamic environment in a fn item"
855                 );
856                 err.help("use the `|| { ... }` closure form instead");
857                 err
858             }
859             ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
860                 let mut err = struct_span_err!(
861                     self.session,
862                     span,
863                     E0435,
864                     "attempt to use a non-constant value in a constant"
865                 );
866                 // let foo =...
867                 //     ^^^ given this Span
868                 // ------- get this Span to have an applicable suggestion
869
870                 // edit:
871                 // only do this if the const and usage of the non-constant value are on the same line
872                 // the further the two are apart, the higher the chance of the suggestion being wrong
873
874                 let sp = self
875                     .session
876                     .source_map()
877                     .span_extend_to_prev_str(ident.span, current, true, false);
878
879                 match sp {
880                     Some(sp) if !self.session.source_map().is_multiline(sp) => {
881                         let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
882                         err.span_suggestion(
883                             sp,
884                             &format!("consider using `{}` instead of `{}`", sugg, current),
885                             format!("{} {}", sugg, ident),
886                             Applicability::MaybeIncorrect,
887                         );
888                         err.span_label(span, "non-constant value");
889                     }
890                     _ => {
891                         err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
892                     }
893                 }
894
895                 err
896             }
897             ResolutionError::BindingShadowsSomethingUnacceptable {
898                 shadowing_binding_descr,
899                 name,
900                 participle,
901                 article,
902                 shadowed_binding_descr,
903                 shadowed_binding_span,
904             } => {
905                 let mut err = struct_span_err!(
906                     self.session,
907                     span,
908                     E0530,
909                     "{}s cannot shadow {}s",
910                     shadowing_binding_descr,
911                     shadowed_binding_descr,
912                 );
913                 err.span_label(
914                     span,
915                     format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
916                 );
917                 let msg =
918                     format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
919                 err.span_label(shadowed_binding_span, msg);
920                 err
921             }
922             ResolutionError::ForwardDeclaredGenericParam => {
923                 let mut err = struct_span_err!(
924                     self.session,
925                     span,
926                     E0128,
927                     "generic parameters with a default cannot use \
928                                                 forward declared identifiers"
929                 );
930                 err.span_label(
931                     span,
932                     "defaulted generic parameters cannot be forward declared".to_string(),
933                 );
934                 err
935             }
936             ResolutionError::ParamInTyOfConstParam(name) => {
937                 let mut err = struct_span_err!(
938                     self.session,
939                     span,
940                     E0770,
941                     "the type of const parameters must not depend on other generic parameters"
942                 );
943                 err.span_label(
944                     span,
945                     format!("the type must not depend on the parameter `{}`", name),
946                 );
947                 err
948             }
949             ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
950                 let mut err = self.session.struct_span_err(
951                     span,
952                     "generic parameters may not be used in const operations",
953                 );
954                 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
955
956                 if is_type {
957                     err.note("type parameters may not be used in const expressions");
958                 } else {
959                     err.help(&format!(
960                         "const parameters may only be used as standalone arguments, i.e. `{}`",
961                         name
962                     ));
963                 }
964
965                 if self.session.is_nightly_build() {
966                     err.help(
967                         "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
968                     );
969                 }
970
971                 err
972             }
973             ResolutionError::SelfInGenericParamDefault => {
974                 let mut err = struct_span_err!(
975                     self.session,
976                     span,
977                     E0735,
978                     "generic parameters cannot use `Self` in their defaults"
979                 );
980                 err.span_label(span, "`Self` in generic parameter default".to_string());
981                 err
982             }
983             ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
984                 let mut err = struct_span_err!(
985                     self.session,
986                     span,
987                     E0767,
988                     "use of unreachable label `{}`",
989                     name,
990                 );
991
992                 err.span_label(definition_span, "unreachable label defined here");
993                 err.span_label(span, format!("unreachable label `{}`", name));
994                 err.note(
995                     "labels are unreachable through functions, closures, async blocks and modules",
996                 );
997
998                 match suggestion {
999                     // A reachable label with a similar name exists.
1000                     Some((ident, true)) => {
1001                         err.span_label(ident.span, "a label with a similar name is reachable");
1002                         err.span_suggestion(
1003                             span,
1004                             "try using similarly named label",
1005                             ident.name.to_string(),
1006                             Applicability::MaybeIncorrect,
1007                         );
1008                     }
1009                     // An unreachable label with a similar name exists.
1010                     Some((ident, false)) => {
1011                         err.span_label(
1012                             ident.span,
1013                             "a label with a similar name exists but is also unreachable",
1014                         );
1015                     }
1016                     // No similarly-named labels exist.
1017                     None => (),
1018                 }
1019
1020                 err
1021             }
1022             ResolutionError::TraitImplMismatch {
1023                 name,
1024                 kind,
1025                 code,
1026                 trait_item_span,
1027                 trait_path,
1028             } => {
1029                 let mut err = self.session.struct_span_err_with_code(
1030                     span,
1031                     &format!(
1032                         "item `{}` is an associated {}, which doesn't match its trait `{}`",
1033                         name, kind, trait_path,
1034                     ),
1035                     code,
1036                 );
1037                 err.span_label(span, "does not match trait");
1038                 err.span_label(trait_item_span, "item in trait");
1039                 err
1040             }
1041             ResolutionError::InvalidAsmSym => {
1042                 let mut err = self.session.struct_span_err(span, "invalid `sym` operand");
1043                 err.span_label(span, "is a local variable");
1044                 err.help("`sym` operands must refer to either a function or a static");
1045                 err
1046             }
1047         }
1048     }
1049
1050     crate fn report_vis_error(
1051         &mut self,
1052         vis_resolution_error: VisResolutionError<'_>,
1053     ) -> ErrorGuaranteed {
1054         match vis_resolution_error {
1055             VisResolutionError::Relative2018(span, path) => {
1056                 let mut err = self.session.struct_span_err(
1057                     span,
1058                     "relative paths are not supported in visibilities in 2018 edition or later",
1059                 );
1060                 err.span_suggestion(
1061                     path.span,
1062                     "try",
1063                     format!("crate::{}", pprust::path_to_string(&path)),
1064                     Applicability::MaybeIncorrect,
1065                 );
1066                 err
1067             }
1068             VisResolutionError::AncestorOnly(span) => struct_span_err!(
1069                 self.session,
1070                 span,
1071                 E0742,
1072                 "visibilities can only be restricted to ancestor modules"
1073             ),
1074             VisResolutionError::FailedToResolve(span, label, suggestion) => {
1075                 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
1076             }
1077             VisResolutionError::ExpectedFound(span, path_str, res) => {
1078                 let mut err = struct_span_err!(
1079                     self.session,
1080                     span,
1081                     E0577,
1082                     "expected module, found {} `{}`",
1083                     res.descr(),
1084                     path_str
1085                 );
1086                 err.span_label(span, "not a module");
1087                 err
1088             }
1089             VisResolutionError::Indeterminate(span) => struct_span_err!(
1090                 self.session,
1091                 span,
1092                 E0578,
1093                 "cannot determine resolution for the visibility"
1094             ),
1095             VisResolutionError::ModuleOnly(span) => {
1096                 self.session.struct_span_err(span, "visibility must resolve to a module")
1097             }
1098         }
1099         .emit()
1100     }
1101
1102     /// Lookup typo candidate in scope for a macro or import.
1103     fn early_lookup_typo_candidate(
1104         &mut self,
1105         scope_set: ScopeSet<'a>,
1106         parent_scope: &ParentScope<'a>,
1107         ident: Ident,
1108         filter_fn: &impl Fn(Res) -> bool,
1109     ) -> Option<TypoSuggestion> {
1110         let mut suggestions = Vec::new();
1111         let ctxt = ident.span.ctxt();
1112         self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1113             match scope {
1114                 Scope::DeriveHelpers(expn_id) => {
1115                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1116                     if filter_fn(res) {
1117                         suggestions.extend(
1118                             this.helper_attrs
1119                                 .get(&expn_id)
1120                                 .into_iter()
1121                                 .flatten()
1122                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1123                         );
1124                     }
1125                 }
1126                 Scope::DeriveHelpersCompat => {
1127                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1128                     if filter_fn(res) {
1129                         for derive in parent_scope.derives {
1130                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1131                             if let Ok((Some(ext), _)) = this.resolve_macro_path(
1132                                 derive,
1133                                 Some(MacroKind::Derive),
1134                                 parent_scope,
1135                                 false,
1136                                 false,
1137                             ) {
1138                                 suggestions.extend(
1139                                     ext.helper_attrs
1140                                         .iter()
1141                                         .map(|name| TypoSuggestion::typo_from_res(*name, res)),
1142                                 );
1143                             }
1144                         }
1145                     }
1146                 }
1147                 Scope::MacroRules(macro_rules_scope) => {
1148                     if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1149                         let res = macro_rules_binding.binding.res();
1150                         if filter_fn(res) {
1151                             suggestions.push(TypoSuggestion::typo_from_res(
1152                                 macro_rules_binding.ident.name,
1153                                 res,
1154                             ))
1155                         }
1156                     }
1157                 }
1158                 Scope::CrateRoot => {
1159                     let root_ident = Ident::new(kw::PathRoot, ident.span);
1160                     let root_module = this.resolve_crate_root(root_ident);
1161                     this.add_module_candidates(root_module, &mut suggestions, filter_fn);
1162                 }
1163                 Scope::Module(module, _) => {
1164                     this.add_module_candidates(module, &mut suggestions, filter_fn);
1165                 }
1166                 Scope::RegisteredAttrs => {
1167                     let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
1168                     if filter_fn(res) {
1169                         suggestions.extend(
1170                             this.registered_attrs
1171                                 .iter()
1172                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1173                         );
1174                     }
1175                 }
1176                 Scope::MacroUsePrelude => {
1177                     suggestions.extend(this.macro_use_prelude.iter().filter_map(
1178                         |(name, binding)| {
1179                             let res = binding.res();
1180                             filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
1181                         },
1182                     ));
1183                 }
1184                 Scope::BuiltinAttrs => {
1185                     let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1186                     if filter_fn(res) {
1187                         suggestions.extend(
1188                             BUILTIN_ATTRIBUTES
1189                                 .iter()
1190                                 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
1191                         );
1192                     }
1193                 }
1194                 Scope::ExternPrelude => {
1195                     suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1196                         let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1197                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
1198                     }));
1199                 }
1200                 Scope::ToolPrelude => {
1201                     let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1202                     suggestions.extend(
1203                         this.registered_tools
1204                             .iter()
1205                             .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1206                     );
1207                 }
1208                 Scope::StdLibPrelude => {
1209                     if let Some(prelude) = this.prelude {
1210                         let mut tmp_suggestions = Vec::new();
1211                         this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
1212                         suggestions.extend(
1213                             tmp_suggestions
1214                                 .into_iter()
1215                                 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1216                         );
1217                     }
1218                 }
1219                 Scope::BuiltinTypes => {
1220                     suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1221                         let res = Res::PrimTy(*prim_ty);
1222                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
1223                     }))
1224                 }
1225             }
1226
1227             None::<()>
1228         });
1229
1230         // Make sure error reporting is deterministic.
1231         suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1232
1233         match find_best_match_for_name(
1234             &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1235             ident.name,
1236             None,
1237         ) {
1238             Some(found) if found != ident.name => {
1239                 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1240             }
1241             _ => None,
1242         }
1243     }
1244
1245     fn lookup_import_candidates_from_module<FilterFn>(
1246         &mut self,
1247         lookup_ident: Ident,
1248         namespace: Namespace,
1249         parent_scope: &ParentScope<'a>,
1250         start_module: Module<'a>,
1251         crate_name: Ident,
1252         filter_fn: FilterFn,
1253     ) -> Vec<ImportSuggestion>
1254     where
1255         FilterFn: Fn(Res) -> bool,
1256     {
1257         let mut candidates = Vec::new();
1258         let mut seen_modules = FxHashSet::default();
1259         let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
1260         let mut worklist_via_import = vec![];
1261
1262         while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1263             None => worklist_via_import.pop(),
1264             Some(x) => Some(x),
1265         } {
1266             let in_module_is_extern = !in_module.def_id().is_local();
1267             // We have to visit module children in deterministic order to avoid
1268             // instabilities in reported imports (#43552).
1269             in_module.for_each_child(self, |this, ident, ns, name_binding| {
1270                 // avoid non-importable candidates
1271                 if !name_binding.is_importable() {
1272                     return;
1273                 }
1274
1275                 let child_accessible =
1276                     accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1277
1278                 // do not venture inside inaccessible items of other crates
1279                 if in_module_is_extern && !child_accessible {
1280                     return;
1281                 }
1282
1283                 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1284
1285                 // There is an assumption elsewhere that paths of variants are in the enum's
1286                 // declaration and not imported. With this assumption, the variant component is
1287                 // chopped and the rest of the path is assumed to be the enum's own path. For
1288                 // errors where a variant is used as the type instead of the enum, this causes
1289                 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1290                 if via_import && name_binding.is_possibly_imported_variant() {
1291                     return;
1292                 }
1293
1294                 // #90113: Do not count an inaccessible reexported item as a candidate.
1295                 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1296                     if this.is_accessible_from(binding.vis, parent_scope.module)
1297                         && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1298                     {
1299                         return;
1300                     }
1301                 }
1302
1303                 // collect results based on the filter function
1304                 // avoid suggesting anything from the same module in which we are resolving
1305                 // avoid suggesting anything with a hygienic name
1306                 if ident.name == lookup_ident.name
1307                     && ns == namespace
1308                     && !ptr::eq(in_module, parent_scope.module)
1309                     && !ident.span.normalize_to_macros_2_0().from_expansion()
1310                 {
1311                     let res = name_binding.res();
1312                     if filter_fn(res) {
1313                         // create the path
1314                         let mut segms = path_segments.clone();
1315                         if lookup_ident.span.rust_2018() {
1316                             // crate-local absolute paths start with `crate::` in edition 2018
1317                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1318                             segms.insert(0, ast::PathSegment::from_ident(crate_name));
1319                         }
1320
1321                         segms.push(ast::PathSegment::from_ident(ident));
1322                         let path = Path { span: name_binding.span, segments: segms, tokens: None };
1323                         let did = match res {
1324                             Res::Def(DefKind::Ctor(..), did) => this.parent(did),
1325                             _ => res.opt_def_id(),
1326                         };
1327
1328                         if child_accessible {
1329                             // Remove invisible match if exists
1330                             if let Some(idx) = candidates
1331                                 .iter()
1332                                 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1333                             {
1334                                 candidates.remove(idx);
1335                             }
1336                         }
1337
1338                         if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1339                             // See if we're recommending TryFrom, TryInto, or FromIterator and add
1340                             // a note about editions
1341                             let note = if let Some(did) = did {
1342                                 let requires_note = !did.is_local()
1343                                     && this.cstore().item_attrs_untracked(did, this.session).any(
1344                                         |attr| {
1345                                             if attr.has_name(sym::rustc_diagnostic_item) {
1346                                                 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1347                                                     .map(|x| Some(x))
1348                                                     .contains(&attr.value_str())
1349                                             } else {
1350                                                 false
1351                                             }
1352                                         },
1353                                     );
1354
1355                                 requires_note.then(|| {
1356                                     format!(
1357                                         "'{}' is included in the prelude starting in Edition 2021",
1358                                         path_names_to_string(&path)
1359                                     )
1360                                 })
1361                             } else {
1362                                 None
1363                             };
1364
1365                             candidates.push(ImportSuggestion {
1366                                 did,
1367                                 descr: res.descr(),
1368                                 path,
1369                                 accessible: child_accessible,
1370                                 note,
1371                             });
1372                         }
1373                     }
1374                 }
1375
1376                 // collect submodules to explore
1377                 if let Some(module) = name_binding.module() {
1378                     // form the path
1379                     let mut path_segments = path_segments.clone();
1380                     path_segments.push(ast::PathSegment::from_ident(ident));
1381
1382                     let is_extern_crate_that_also_appears_in_prelude =
1383                         name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1384
1385                     if !is_extern_crate_that_also_appears_in_prelude {
1386                         // add the module to the lookup
1387                         if seen_modules.insert(module.def_id()) {
1388                             if via_import { &mut worklist_via_import } else { &mut worklist }
1389                                 .push((module, path_segments, child_accessible));
1390                         }
1391                     }
1392                 }
1393             })
1394         }
1395
1396         // If only some candidates are accessible, take just them
1397         if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1398             candidates = candidates.into_iter().filter(|x| x.accessible).collect();
1399         }
1400
1401         candidates
1402     }
1403
1404     /// When name resolution fails, this method can be used to look up candidate
1405     /// entities with the expected name. It allows filtering them using the
1406     /// supplied predicate (which should be used to only accept the types of
1407     /// definitions expected, e.g., traits). The lookup spans across all crates.
1408     ///
1409     /// N.B., the method does not look into imports, but this is not a problem,
1410     /// since we report the definitions (thus, the de-aliased imports).
1411     crate fn lookup_import_candidates<FilterFn>(
1412         &mut self,
1413         lookup_ident: Ident,
1414         namespace: Namespace,
1415         parent_scope: &ParentScope<'a>,
1416         filter_fn: FilterFn,
1417     ) -> Vec<ImportSuggestion>
1418     where
1419         FilterFn: Fn(Res) -> bool,
1420     {
1421         let mut suggestions = self.lookup_import_candidates_from_module(
1422             lookup_ident,
1423             namespace,
1424             parent_scope,
1425             self.graph_root,
1426             Ident::with_dummy_span(kw::Crate),
1427             &filter_fn,
1428         );
1429
1430         if lookup_ident.span.rust_2018() {
1431             let extern_prelude_names = self.extern_prelude.clone();
1432             for (ident, _) in extern_prelude_names.into_iter() {
1433                 if ident.span.from_expansion() {
1434                     // Idents are adjusted to the root context before being
1435                     // resolved in the extern prelude, so reporting this to the
1436                     // user is no help. This skips the injected
1437                     // `extern crate std` in the 2018 edition, which would
1438                     // otherwise cause duplicate suggestions.
1439                     continue;
1440                 }
1441                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1442                     let crate_root = self.expect_module(crate_id.as_def_id());
1443                     suggestions.extend(self.lookup_import_candidates_from_module(
1444                         lookup_ident,
1445                         namespace,
1446                         parent_scope,
1447                         crate_root,
1448                         ident,
1449                         &filter_fn,
1450                     ));
1451                 }
1452             }
1453         }
1454
1455         suggestions
1456     }
1457
1458     crate fn unresolved_macro_suggestions(
1459         &mut self,
1460         err: &mut Diagnostic,
1461         macro_kind: MacroKind,
1462         parent_scope: &ParentScope<'a>,
1463         ident: Ident,
1464     ) {
1465         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1466         let suggestion = self.early_lookup_typo_candidate(
1467             ScopeSet::Macro(macro_kind),
1468             parent_scope,
1469             ident,
1470             is_expected,
1471         );
1472         self.add_typo_suggestion(err, suggestion, ident.span);
1473
1474         let import_suggestions =
1475             self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1476         show_candidates(
1477             &self.definitions,
1478             self.session,
1479             err,
1480             None,
1481             &import_suggestions,
1482             Instead::No,
1483             FoundUse::Yes,
1484             IsPattern::No,
1485         );
1486
1487         if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1488             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1489             err.span_note(ident.span, &msg);
1490             return;
1491         }
1492         if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1493             err.help("have you added the `#[macro_use]` on the module/import?");
1494             return;
1495         }
1496         for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1497             if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1498                 ident,
1499                 ScopeSet::All(ns, false),
1500                 &parent_scope,
1501                 None,
1502                 false,
1503                 None,
1504             ) {
1505                 let desc = match binding.res() {
1506                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1507                         "a function-like macro".to_string()
1508                     }
1509                     Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1510                         format!("an attribute: `#[{}]`", ident)
1511                     }
1512                     Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1513                         format!("a derive macro: `#[derive({})]`", ident)
1514                     }
1515                     Res::ToolMod => {
1516                         // Don't confuse the user with tool modules.
1517                         continue;
1518                     }
1519                     Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1520                         "only a trait, without a derive macro".to_string()
1521                     }
1522                     res => format!(
1523                         "{} {}, not {} {}",
1524                         res.article(),
1525                         res.descr(),
1526                         macro_kind.article(),
1527                         macro_kind.descr_expected(),
1528                     ),
1529                 };
1530                 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1531                     if !import.span.is_dummy() {
1532                         err.span_note(
1533                             import.span,
1534                             &format!("`{}` is imported here, but it is {}", ident, desc),
1535                         );
1536                         // Silence the 'unused import' warning we might get,
1537                         // since this diagnostic already covers that import.
1538                         self.record_use(ident, binding, false);
1539                         return;
1540                     }
1541                 }
1542                 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1543                 return;
1544             }
1545         }
1546     }
1547
1548     crate fn add_typo_suggestion(
1549         &self,
1550         err: &mut Diagnostic,
1551         suggestion: Option<TypoSuggestion>,
1552         span: Span,
1553     ) -> bool {
1554         let suggestion = match suggestion {
1555             None => return false,
1556             // We shouldn't suggest underscore.
1557             Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1558             Some(suggestion) => suggestion,
1559         };
1560         let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1561             LOCAL_CRATE => self.opt_span(def_id),
1562             _ => Some(
1563                 self.session
1564                     .source_map()
1565                     .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1566             ),
1567         });
1568         if let Some(def_span) = def_span {
1569             if span.overlaps(def_span) {
1570                 // Don't suggest typo suggestion for itself like in the following:
1571                 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1572                 //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1573                 //    |
1574                 // LL | struct X {}
1575                 //    | ----------- `X` defined here
1576                 // LL |
1577                 // LL | const Y: X = X("ö");
1578                 //    | -------------^^^^^^- similarly named constant `Y` defined here
1579                 //    |
1580                 // help: use struct literal syntax instead
1581                 //    |
1582                 // LL | const Y: X = X {};
1583                 //    |              ^^^^
1584                 // help: a constant with a similar name exists
1585                 //    |
1586                 // LL | const Y: X = Y("ö");
1587                 //    |              ^
1588                 return false;
1589             }
1590             let prefix = match suggestion.target {
1591                 SuggestionTarget::SimilarlyNamed => "similarly named ",
1592                 SuggestionTarget::SingleItem => "",
1593             };
1594
1595             err.span_label(
1596                 self.session.source_map().guess_head_span(def_span),
1597                 &format!(
1598                     "{}{} `{}` defined here",
1599                     prefix,
1600                     suggestion.res.descr(),
1601                     suggestion.candidate.as_str(),
1602                 ),
1603             );
1604         }
1605         let msg = match suggestion.target {
1606             SuggestionTarget::SimilarlyNamed => format!(
1607                 "{} {} with a similar name exists",
1608                 suggestion.res.article(),
1609                 suggestion.res.descr()
1610             ),
1611             SuggestionTarget::SingleItem => {
1612                 format!("maybe you meant this {}", suggestion.res.descr())
1613             }
1614         };
1615         err.span_suggestion(
1616             span,
1617             &msg,
1618             suggestion.candidate.to_string(),
1619             Applicability::MaybeIncorrect,
1620         );
1621         true
1622     }
1623
1624     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1625         let res = b.res();
1626         if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1627             // These already contain the "built-in" prefix or look bad with it.
1628             let add_built_in =
1629                 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1630             let (built_in, from) = if from_prelude {
1631                 ("", " from prelude")
1632             } else if b.is_extern_crate()
1633                 && !b.is_import()
1634                 && self.session.opts.externs.get(ident.as_str()).is_some()
1635             {
1636                 ("", " passed with `--extern`")
1637             } else if add_built_in {
1638                 (" built-in", "")
1639             } else {
1640                 ("", "")
1641             };
1642
1643             let a = if built_in.is_empty() { res.article() } else { "a" };
1644             format!("{a}{built_in} {thing}{from}", thing = res.descr())
1645         } else {
1646             let introduced = if b.is_import() { "imported" } else { "defined" };
1647             format!("the {thing} {introduced} here", thing = res.descr())
1648         }
1649     }
1650
1651     fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1652         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1653         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1654             // We have to print the span-less alternative first, otherwise formatting looks bad.
1655             (b2, b1, misc2, misc1, true)
1656         } else {
1657             (b1, b2, misc1, misc2, false)
1658         };
1659
1660         let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1661         err.span_label(ident.span, "ambiguous name");
1662         err.note(&format!("ambiguous because of {}", kind.descr()));
1663
1664         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1665             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1666             let note_msg = format!("`{ident}` could{also} refer to {what}");
1667
1668             let thing = b.res().descr();
1669             let mut help_msgs = Vec::new();
1670             if b.is_glob_import()
1671                 && (kind == AmbiguityKind::GlobVsGlob
1672                     || kind == AmbiguityKind::GlobVsExpanded
1673                     || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1674             {
1675                 help_msgs.push(format!(
1676                     "consider adding an explicit import of `{ident}` to disambiguate"
1677                 ))
1678             }
1679             if b.is_extern_crate() && ident.span.rust_2018() {
1680                 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1681             }
1682             if misc == AmbiguityErrorMisc::SuggestCrate {
1683                 help_msgs
1684                     .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1685             } else if misc == AmbiguityErrorMisc::SuggestSelf {
1686                 help_msgs
1687                     .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1688             }
1689
1690             err.span_note(b.span, &note_msg);
1691             for (i, help_msg) in help_msgs.iter().enumerate() {
1692                 let or = if i == 0 { "" } else { "or " };
1693                 err.help(&format!("{}{}", or, help_msg));
1694             }
1695         };
1696
1697         could_refer_to(b1, misc1, "");
1698         could_refer_to(b2, misc2, " also");
1699         err.emit();
1700     }
1701
1702     /// If the binding refers to a tuple struct constructor with fields,
1703     /// returns the span of its fields.
1704     fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1705         if let NameBindingKind::Res(
1706             Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1707             _,
1708         ) = binding.kind
1709         {
1710             let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1711             let fields = self.field_names.get(&def_id)?;
1712             return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1713         }
1714         None
1715     }
1716
1717     fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1718         let PrivacyError { ident, binding, .. } = *privacy_error;
1719
1720         let res = binding.res();
1721         let ctor_fields_span = self.ctor_fields_span(binding);
1722         let plain_descr = res.descr().to_string();
1723         let nonimport_descr =
1724             if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1725         let import_descr = nonimport_descr.clone() + " import";
1726         let get_descr =
1727             |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1728
1729         // Print the primary message.
1730         let descr = get_descr(binding);
1731         let mut err =
1732             struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1733         err.span_label(ident.span, &format!("private {}", descr));
1734         if let Some(span) = ctor_fields_span {
1735             err.span_label(span, "a constructor is private if any of the fields is private");
1736         }
1737
1738         // Print the whole import chain to make it easier to see what happens.
1739         let first_binding = binding;
1740         let mut next_binding = Some(binding);
1741         let mut next_ident = ident;
1742         while let Some(binding) = next_binding {
1743             let name = next_ident;
1744             next_binding = match binding.kind {
1745                 _ if res == Res::Err => None,
1746                 NameBindingKind::Import { binding, import, .. } => match import.kind {
1747                     _ if binding.span.is_dummy() => None,
1748                     ImportKind::Single { source, .. } => {
1749                         next_ident = source;
1750                         Some(binding)
1751                     }
1752                     ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1753                     ImportKind::ExternCrate { .. } => None,
1754                 },
1755                 _ => None,
1756             };
1757
1758             let first = ptr::eq(binding, first_binding);
1759             let msg = format!(
1760                 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1761                 and_refers_to = if first { "" } else { "...and refers to " },
1762                 item = get_descr(binding),
1763                 which = if first { "" } else { " which" },
1764                 dots = if next_binding.is_some() { "..." } else { "" },
1765             );
1766             let def_span = self.session.source_map().guess_head_span(binding.span);
1767             let mut note_span = MultiSpan::from_span(def_span);
1768             if !first && binding.vis.is_public() {
1769                 note_span.push_span_label(def_span, "consider importing it directly");
1770             }
1771             err.span_note(note_span, &msg);
1772         }
1773
1774         err.emit();
1775     }
1776
1777     crate fn find_similarly_named_module_or_crate(
1778         &mut self,
1779         ident: Symbol,
1780         current_module: &Module<'a>,
1781     ) -> Option<Symbol> {
1782         let mut candidates = self
1783             .extern_prelude
1784             .iter()
1785             .map(|(ident, _)| ident.name)
1786             .chain(
1787                 self.module_map
1788                     .iter()
1789                     .filter(|(_, module)| {
1790                         current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1791                     })
1792                     .flat_map(|(_, module)| module.kind.name()),
1793             )
1794             .filter(|c| !c.to_string().is_empty())
1795             .collect::<Vec<_>>();
1796         candidates.sort();
1797         candidates.dedup();
1798         match find_best_match_for_name(&candidates, ident, None) {
1799             Some(sugg) if sugg == ident => None,
1800             sugg => sugg,
1801         }
1802     }
1803
1804     crate fn report_path_resolution_error(
1805         &mut self,
1806         path: &[Segment],
1807         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1808         parent_scope: &ParentScope<'a>,
1809         ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1810         ignore_binding: Option<&'a NameBinding<'a>>,
1811         module: Option<ModuleOrUniformRoot<'a>>,
1812         i: usize,
1813         ident: Ident,
1814     ) -> (String, Option<Suggestion>) {
1815         let is_last = i == path.len() - 1;
1816         let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1817         let module_res = match module {
1818             Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1819             _ => None,
1820         };
1821         if module_res == self.graph_root.res() {
1822             let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1823             let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1824             candidates
1825                 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1826             if let Some(candidate) = candidates.get(0) {
1827                 (
1828                     String::from("unresolved import"),
1829                     Some((
1830                         vec![(ident.span, pprust::path_to_string(&candidate.path))],
1831                         String::from("a similar path exists"),
1832                         Applicability::MaybeIncorrect,
1833                     )),
1834                 )
1835             } else if self.session.edition() == Edition::Edition2015 {
1836                 (format!("maybe a missing crate `{}`?", ident), None)
1837             } else {
1838                 (format!("could not find `{}` in the crate root", ident), None)
1839             }
1840         } else if i > 0 {
1841             let parent = path[i - 1].ident.name;
1842             let parent = match parent {
1843                 // ::foo is mounted at the crate root for 2015, and is the extern
1844                 // prelude for 2018+
1845                 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1846                     "the list of imported crates".to_owned()
1847                 }
1848                 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1849                 _ => format!("`{}`", parent),
1850             };
1851
1852             let mut msg = format!("could not find `{}` in {}", ident, parent);
1853             if ns == TypeNS || ns == ValueNS {
1854                 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1855                 let binding = if let Some(module) = module {
1856                     self.resolve_ident_in_module(
1857                         module,
1858                         ident,
1859                         ns_to_try,
1860                         parent_scope,
1861                         None,
1862                         ignore_binding,
1863                     ).ok()
1864                 } else if let Some(ribs) = ribs
1865                     && let Some(TypeNS | ValueNS) = opt_ns
1866                 {
1867                     match self.resolve_ident_in_lexical_scope(
1868                         ident,
1869                         ns_to_try,
1870                         parent_scope,
1871                         None,
1872                         &ribs[ns_to_try],
1873                         ignore_binding,
1874                     ) {
1875                         // we found a locally-imported or available item/module
1876                         Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1877                         _ => None,
1878                     }
1879                 } else {
1880                     let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1881                     self.early_resolve_ident_in_lexical_scope(
1882                         ident,
1883                         scopes,
1884                         parent_scope,
1885                         None,
1886                         false,
1887                         ignore_binding,
1888                     ).ok()
1889                 };
1890                 if let Some(binding) = binding {
1891                     let mut found = |what| {
1892                         msg = format!(
1893                             "expected {}, found {} `{}` in {}",
1894                             ns.descr(),
1895                             what,
1896                             ident,
1897                             parent
1898                         )
1899                     };
1900                     if binding.module().is_some() {
1901                         found("module")
1902                     } else {
1903                         match binding.res() {
1904                             Res::Def(kind, id) => found(kind.descr(id)),
1905                             _ => found(ns_to_try.descr()),
1906                         }
1907                     }
1908                 };
1909             }
1910             (msg, None)
1911         } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1912             // Check whether the name refers to an item in the value namespace.
1913             let binding = if let Some(ribs) = ribs {
1914                 self.resolve_ident_in_lexical_scope(
1915                     ident,
1916                     ValueNS,
1917                     parent_scope,
1918                     None,
1919                     &ribs[ValueNS],
1920                     ignore_binding,
1921                 )
1922             } else {
1923                 None
1924             };
1925             let match_span = match binding {
1926                 // Name matches a local variable. For example:
1927                 // ```
1928                 // fn f() {
1929                 //     let Foo: &str = "";
1930                 //     println!("{}", Foo::Bar); // Name refers to local
1931                 //                               // variable `Foo`.
1932                 // }
1933                 // ```
1934                 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1935                     Some(*self.pat_span_map.get(&id).unwrap())
1936                 }
1937                 // Name matches item from a local name binding
1938                 // created by `use` declaration. For example:
1939                 // ```
1940                 // pub Foo: &str = "";
1941                 //
1942                 // mod submod {
1943                 //     use super::Foo;
1944                 //     println!("{}", Foo::Bar); // Name refers to local
1945                 //                               // binding `Foo`.
1946                 // }
1947                 // ```
1948                 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1949                 _ => None,
1950             };
1951             let suggestion = if let Some(span) = match_span {
1952                 Some((
1953                     vec![(span, String::from(""))],
1954                     format!("`{}` is defined here, but is not a type", ident),
1955                     Applicability::MaybeIncorrect,
1956                 ))
1957             } else {
1958                 None
1959             };
1960
1961             (format!("use of undeclared type `{}`", ident), suggestion)
1962         } else {
1963             let suggestion = if ident.name == sym::alloc {
1964                 Some((
1965                     vec![],
1966                     String::from("add `extern crate alloc` to use the `alloc` crate"),
1967                     Applicability::MaybeIncorrect,
1968                 ))
1969             } else {
1970                 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1971                     |sugg| {
1972                         (
1973                             vec![(ident.span, sugg.to_string())],
1974                             String::from("there is a crate or module with a similar name"),
1975                             Applicability::MaybeIncorrect,
1976                         )
1977                     },
1978                 )
1979             };
1980             (format!("use of undeclared crate or module `{}`", ident), suggestion)
1981         }
1982     }
1983 }
1984
1985 impl<'a, 'b> ImportResolver<'a, 'b> {
1986     /// Adds suggestions for a path that cannot be resolved.
1987     pub(crate) fn make_path_suggestion(
1988         &mut self,
1989         span: Span,
1990         mut path: Vec<Segment>,
1991         parent_scope: &ParentScope<'b>,
1992     ) -> Option<(Vec<Segment>, Vec<String>)> {
1993         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1994
1995         match (path.get(0), path.get(1)) {
1996             // `{{root}}::ident::...` on both editions.
1997             // On 2015 `{{root}}` is usually added implicitly.
1998             (Some(fst), Some(snd))
1999                 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
2000             // `ident::...` on 2018.
2001             (Some(fst), _)
2002                 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
2003             {
2004                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
2005                 path.insert(0, Segment::from_ident(Ident::empty()));
2006             }
2007             _ => return None,
2008         }
2009
2010         self.make_missing_self_suggestion(path.clone(), parent_scope)
2011             .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2012             .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2013             .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2014     }
2015
2016     /// Suggest a missing `self::` if that resolves to an correct module.
2017     ///
2018     /// ```text
2019     ///    |
2020     /// LL | use foo::Bar;
2021     ///    |     ^^^ did you mean `self::foo`?
2022     /// ```
2023     fn make_missing_self_suggestion(
2024         &mut self,
2025         mut path: Vec<Segment>,
2026         parent_scope: &ParentScope<'b>,
2027     ) -> Option<(Vec<Segment>, Vec<String>)> {
2028         // Replace first ident with `self` and check if that is valid.
2029         path[0].ident.name = kw::SelfLower;
2030         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2031         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2032         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2033     }
2034
2035     /// Suggests a missing `crate::` if that resolves to an correct module.
2036     ///
2037     /// ```text
2038     ///    |
2039     /// LL | use foo::Bar;
2040     ///    |     ^^^ did you mean `crate::foo`?
2041     /// ```
2042     fn make_missing_crate_suggestion(
2043         &mut self,
2044         mut path: Vec<Segment>,
2045         parent_scope: &ParentScope<'b>,
2046     ) -> Option<(Vec<Segment>, Vec<String>)> {
2047         // Replace first ident with `crate` and check if that is valid.
2048         path[0].ident.name = kw::Crate;
2049         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2050         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
2051         if let PathResult::Module(..) = result {
2052             Some((
2053                 path,
2054                 vec![
2055                     "`use` statements changed in Rust 2018; read more at \
2056                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2057                      clarity.html>"
2058                         .to_string(),
2059                 ],
2060             ))
2061         } else {
2062             None
2063         }
2064     }
2065
2066     /// Suggests a missing `super::` if that resolves to an correct module.
2067     ///
2068     /// ```text
2069     ///    |
2070     /// LL | use foo::Bar;
2071     ///    |     ^^^ did you mean `super::foo`?
2072     /// ```
2073     fn make_missing_super_suggestion(
2074         &mut self,
2075         mut path: Vec<Segment>,
2076         parent_scope: &ParentScope<'b>,
2077     ) -> Option<(Vec<Segment>, Vec<String>)> {
2078         // Replace first ident with `crate` and check if that is valid.
2079         path[0].ident.name = kw::Super;
2080         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2081         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
2082         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2083     }
2084
2085     /// Suggests a missing external crate name if that resolves to an correct module.
2086     ///
2087     /// ```text
2088     ///    |
2089     /// LL | use foobar::Baz;
2090     ///    |     ^^^^^^ did you mean `baz::foobar`?
2091     /// ```
2092     ///
2093     /// Used when importing a submodule of an external crate but missing that crate's
2094     /// name as the first part of path.
2095     fn make_external_crate_suggestion(
2096         &mut self,
2097         mut path: Vec<Segment>,
2098         parent_scope: &ParentScope<'b>,
2099     ) -> Option<(Vec<Segment>, Vec<String>)> {
2100         if path[1].ident.span.rust_2015() {
2101             return None;
2102         }
2103
2104         // Sort extern crate names in *reverse* order to get
2105         // 1) some consistent ordering for emitted diagnostics, and
2106         // 2) `std` suggestions before `core` suggestions.
2107         let mut extern_crate_names =
2108             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2109         extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2110
2111         for name in extern_crate_names.into_iter() {
2112             // Replace first ident with a crate name and check if that is valid.
2113             path[0].ident.name = name;
2114             let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2115             debug!(
2116                 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2117                 name, path, result
2118             );
2119             if let PathResult::Module(..) = result {
2120                 return Some((path, Vec::new()));
2121             }
2122         }
2123
2124         None
2125     }
2126
2127     /// Suggests importing a macro from the root of the crate rather than a module within
2128     /// the crate.
2129     ///
2130     /// ```text
2131     /// help: a macro with this name exists at the root of the crate
2132     ///    |
2133     /// LL | use issue_59764::makro;
2134     ///    |     ^^^^^^^^^^^^^^^^^^
2135     ///    |
2136     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2137     ///            at the root of the crate instead of the module where it is defined
2138     /// ```
2139     pub(crate) fn check_for_module_export_macro(
2140         &mut self,
2141         import: &'b Import<'b>,
2142         module: ModuleOrUniformRoot<'b>,
2143         ident: Ident,
2144     ) -> Option<(Option<Suggestion>, Vec<String>)> {
2145         let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2146             return None;
2147         };
2148
2149         while let Some(parent) = crate_module.parent {
2150             crate_module = parent;
2151         }
2152
2153         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2154             // Don't make a suggestion if the import was already from the root of the
2155             // crate.
2156             return None;
2157         }
2158
2159         let resolutions = self.r.resolutions(crate_module).borrow();
2160         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2161         let binding = resolution.borrow().binding()?;
2162         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2163             let module_name = crate_module.kind.name().unwrap();
2164             let import_snippet = match import.kind {
2165                 ImportKind::Single { source, target, .. } if source != target => {
2166                     format!("{} as {}", source, target)
2167                 }
2168                 _ => format!("{}", ident),
2169             };
2170
2171             let mut corrections: Vec<(Span, String)> = Vec::new();
2172             if !import.is_nested() {
2173                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2174                 // intermediate segments.
2175                 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2176             } else {
2177                 // Find the binding span (and any trailing commas and spaces).
2178                 //   ie. `use a::b::{c, d, e};`
2179                 //                      ^^^
2180                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2181                     self.r.session,
2182                     import.span,
2183                     import.use_span,
2184                 );
2185                 debug!(
2186                     "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2187                     found_closing_brace, binding_span
2188                 );
2189
2190                 let mut removal_span = binding_span;
2191                 if found_closing_brace {
2192                     // If the binding span ended with a closing brace, as in the below example:
2193                     //   ie. `use a::b::{c, d};`
2194                     //                      ^
2195                     // Then expand the span of characters to remove to include the previous
2196                     // binding's trailing comma.
2197                     //   ie. `use a::b::{c, d};`
2198                     //                    ^^^
2199                     if let Some(previous_span) =
2200                         extend_span_to_previous_binding(self.r.session, binding_span)
2201                     {
2202                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2203                         removal_span = removal_span.with_lo(previous_span.lo());
2204                     }
2205                 }
2206                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2207
2208                 // Remove the `removal_span`.
2209                 corrections.push((removal_span, "".to_string()));
2210
2211                 // Find the span after the crate name and if it has nested imports immediately
2212                 // after the crate name already.
2213                 //   ie. `use a::b::{c, d};`
2214                 //               ^^^^^^^^^
2215                 //   or  `use a::{b, c, d}};`
2216                 //               ^^^^^^^^^^^
2217                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2218                     self.r.session,
2219                     module_name,
2220                     import.use_span,
2221                 );
2222                 debug!(
2223                     "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2224                     has_nested, after_crate_name
2225                 );
2226
2227                 let source_map = self.r.session.source_map();
2228
2229                 // Add the import to the start, with a `{` if required.
2230                 let start_point = source_map.start_point(after_crate_name);
2231                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2232                     corrections.push((
2233                         start_point,
2234                         if has_nested {
2235                             // In this case, `start_snippet` must equal '{'.
2236                             format!("{}{}, ", start_snippet, import_snippet)
2237                         } else {
2238                             // In this case, add a `{`, then the moved import, then whatever
2239                             // was there before.
2240                             format!("{{{}, {}", import_snippet, start_snippet)
2241                         },
2242                     ));
2243                 }
2244
2245                 // Add a `};` to the end if nested, matching the `{` added at the start.
2246                 if !has_nested {
2247                     corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2248                 }
2249             }
2250
2251             let suggestion = Some((
2252                 corrections,
2253                 String::from("a macro with this name exists at the root of the crate"),
2254                 Applicability::MaybeIncorrect,
2255             ));
2256             let note = vec![
2257                 "this could be because a macro annotated with `#[macro_export]` will be exported \
2258                  at the root of the crate instead of the module where it is defined"
2259                     .to_string(),
2260             ];
2261             Some((suggestion, note))
2262         } else {
2263             None
2264         }
2265     }
2266 }
2267
2268 /// Given a `binding_span` of a binding within a use statement:
2269 ///
2270 /// ```
2271 /// use foo::{a, b, c};
2272 ///              ^
2273 /// ```
2274 ///
2275 /// then return the span until the next binding or the end of the statement:
2276 ///
2277 /// ```
2278 /// use foo::{a, b, c};
2279 ///              ^^^
2280 /// ```
2281 fn find_span_of_binding_until_next_binding(
2282     sess: &Session,
2283     binding_span: Span,
2284     use_span: Span,
2285 ) -> (bool, Span) {
2286     let source_map = sess.source_map();
2287
2288     // Find the span of everything after the binding.
2289     //   ie. `a, e};` or `a};`
2290     let binding_until_end = binding_span.with_hi(use_span.hi());
2291
2292     // Find everything after the binding but not including the binding.
2293     //   ie. `, e};` or `};`
2294     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2295
2296     // Keep characters in the span until we encounter something that isn't a comma or
2297     // whitespace.
2298     //   ie. `, ` or ``.
2299     //
2300     // Also note whether a closing brace character was encountered. If there
2301     // was, then later go backwards to remove any trailing commas that are left.
2302     let mut found_closing_brace = false;
2303     let after_binding_until_next_binding =
2304         source_map.span_take_while(after_binding_until_end, |&ch| {
2305             if ch == '}' {
2306                 found_closing_brace = true;
2307             }
2308             ch == ' ' || ch == ','
2309         });
2310
2311     // Combine the two spans.
2312     //   ie. `a, ` or `a`.
2313     //
2314     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2315     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2316
2317     (found_closing_brace, span)
2318 }
2319
2320 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2321 /// binding.
2322 ///
2323 /// ```
2324 /// use foo::a::{a, b, c};
2325 ///               ^^--- binding span
2326 ///               |
2327 ///               returned span
2328 ///
2329 /// use foo::{a, b, c};
2330 ///           --- binding span
2331 /// ```
2332 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2333     let source_map = sess.source_map();
2334
2335     // `prev_source` will contain all of the source that came before the span.
2336     // Then split based on a command and take the first (ie. closest to our span)
2337     // snippet. In the example, this is a space.
2338     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2339
2340     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2341     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2342     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2343         return None;
2344     }
2345
2346     let prev_comma = prev_comma.first().unwrap();
2347     let prev_starting_brace = prev_starting_brace.first().unwrap();
2348
2349     // If the amount of source code before the comma is greater than
2350     // the amount of source code before the starting brace then we've only
2351     // got one item in the nested item (eg. `issue_52891::{self}`).
2352     if prev_comma.len() > prev_starting_brace.len() {
2353         return None;
2354     }
2355
2356     Some(binding_span.with_lo(BytePos(
2357         // Take away the number of bytes for the characters we've found and an
2358         // extra for the comma.
2359         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2360     )))
2361 }
2362
2363 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2364 /// it is a nested use tree.
2365 ///
2366 /// ```
2367 /// use foo::a::{b, c};
2368 ///          ^^^^^^^^^^ // false
2369 ///
2370 /// use foo::{a, b, c};
2371 ///          ^^^^^^^^^^ // true
2372 ///
2373 /// use foo::{a, b::{c, d}};
2374 ///          ^^^^^^^^^^^^^^^ // true
2375 /// ```
2376 fn find_span_immediately_after_crate_name(
2377     sess: &Session,
2378     module_name: Symbol,
2379     use_span: Span,
2380 ) -> (bool, Span) {
2381     debug!(
2382         "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2383         module_name, use_span
2384     );
2385     let source_map = sess.source_map();
2386
2387     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2388     let mut num_colons = 0;
2389     // Find second colon.. `use issue_59764:`
2390     let until_second_colon = source_map.span_take_while(use_span, |c| {
2391         if *c == ':' {
2392             num_colons += 1;
2393         }
2394         !matches!(c, ':' if num_colons == 2)
2395     });
2396     // Find everything after the second colon.. `foo::{baz, makro};`
2397     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2398
2399     let mut found_a_non_whitespace_character = false;
2400     // Find the first non-whitespace character in `from_second_colon`.. `f`
2401     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2402         if found_a_non_whitespace_character {
2403             return false;
2404         }
2405         if !c.is_whitespace() {
2406             found_a_non_whitespace_character = true;
2407         }
2408         true
2409     });
2410
2411     // Find the first `{` in from_second_colon.. `foo::{`
2412     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2413
2414     (next_left_bracket == after_second_colon, from_second_colon)
2415 }
2416
2417 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2418 /// independent options.
2419 enum Instead {
2420     Yes,
2421     No,
2422 }
2423
2424 /// Whether an existing place with an `use` item was found.
2425 enum FoundUse {
2426     Yes,
2427     No,
2428 }
2429
2430 /// Whether a binding is part of a pattern or an expression. Used for diagnostics.
2431 enum IsPattern {
2432     /// The binding is part of a pattern
2433     Yes,
2434     /// The binding is part of an expression
2435     No,
2436 }
2437
2438 /// When an entity with a given name is not available in scope, we search for
2439 /// entities with that name in all crates. This method allows outputting the
2440 /// results of this search in a programmer-friendly way
2441 fn show_candidates(
2442     definitions: &rustc_hir::definitions::Definitions,
2443     session: &Session,
2444     err: &mut Diagnostic,
2445     // This is `None` if all placement locations are inside expansions
2446     use_placement_span: Option<Span>,
2447     candidates: &[ImportSuggestion],
2448     instead: Instead,
2449     found_use: FoundUse,
2450     is_pattern: IsPattern,
2451 ) {
2452     if candidates.is_empty() {
2453         return;
2454     }
2455
2456     let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2457         Vec::new();
2458     let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2459         Vec::new();
2460
2461     candidates.iter().for_each(|c| {
2462         (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2463             .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2464     });
2465
2466     // we want consistent results across executions, but candidates are produced
2467     // by iterating through a hash map, so make sure they are ordered:
2468     for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2469         path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2470         let core_path_strings =
2471             path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2472         path_strings.extend(core_path_strings);
2473         path_strings.dedup_by(|a, b| a.0 == b.0);
2474     }
2475
2476     if !accessible_path_strings.is_empty() {
2477         let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2478             ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2479         } else {
2480             ("one of these", "items", String::new())
2481         };
2482
2483         let instead = if let Instead::Yes = instead { " instead" } else { "" };
2484         let mut msg = if let IsPattern::Yes = is_pattern {
2485             format!(
2486                 "if you meant to match on {}{}{}, use the full path in the pattern",
2487                 kind, instead, name
2488             )
2489         } else {
2490             format!("consider importing {} {}{}", determiner, kind, instead)
2491         };
2492
2493         for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2494             err.note(note);
2495         }
2496
2497         if let (IsPattern::Yes, Some(span)) = (is_pattern, use_placement_span) {
2498             err.span_suggestions(
2499                 span,
2500                 &msg,
2501                 accessible_path_strings.into_iter().map(|a| a.0),
2502                 Applicability::MaybeIncorrect,
2503             );
2504         } else if let Some(span) = use_placement_span {
2505             for candidate in &mut accessible_path_strings {
2506                 // produce an additional newline to separate the new use statement
2507                 // from the directly following item.
2508                 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2509                 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
2510             }
2511
2512             err.span_suggestions(
2513                 span,
2514                 &msg,
2515                 accessible_path_strings.into_iter().map(|a| a.0),
2516                 Applicability::MaybeIncorrect,
2517             );
2518         } else {
2519             msg.push(':');
2520
2521             for candidate in accessible_path_strings {
2522                 msg.push('\n');
2523                 msg.push_str(&candidate.0);
2524             }
2525
2526             err.note(&msg);
2527         }
2528     } else {
2529         assert!(!inaccessible_path_strings.is_empty());
2530
2531         let prefix =
2532             if let IsPattern::Yes = is_pattern { "you might have meant to match on " } else { "" };
2533         if inaccessible_path_strings.len() == 1 {
2534             let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2535             let msg = format!(
2536                 "{}{} `{}`{} exists but is inaccessible",
2537                 prefix,
2538                 descr,
2539                 name,
2540                 if let IsPattern::Yes = is_pattern { ", which" } else { "" }
2541             );
2542
2543             if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2544                 let span = definitions.def_span(local_def_id);
2545                 let span = session.source_map().guess_head_span(span);
2546                 let mut multi_span = MultiSpan::from_span(span);
2547                 multi_span.push_span_label(span, "not accessible".to_string());
2548                 err.span_note(multi_span, &msg);
2549             } else {
2550                 err.note(&msg);
2551             }
2552             if let Some(note) = (*note).as_deref() {
2553                 err.note(note);
2554             }
2555         } else {
2556             let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2557             let descr = if inaccessible_path_strings
2558                 .iter()
2559                 .skip(1)
2560                 .all(|(_, descr, _, _)| descr == descr_first)
2561             {
2562                 descr_first.to_string()
2563             } else {
2564                 "item".to_string()
2565             };
2566
2567             let mut msg = format!("{}these {}s exist but are inaccessible", prefix, descr);
2568             let mut has_colon = false;
2569
2570             let mut spans = Vec::new();
2571             for (name, _, def_id, _) in &inaccessible_path_strings {
2572                 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2573                     let span = definitions.def_span(local_def_id);
2574                     let span = session.source_map().guess_head_span(span);
2575                     spans.push((name, span));
2576                 } else {
2577                     if !has_colon {
2578                         msg.push(':');
2579                         has_colon = true;
2580                     }
2581                     msg.push('\n');
2582                     msg.push_str(name);
2583                 }
2584             }
2585
2586             let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2587             for (name, span) in spans {
2588                 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2589             }
2590
2591             for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2592                 err.note(note);
2593             }
2594
2595             err.span_note(multi_span, &msg);
2596         }
2597     }
2598 }
2599
2600 #[derive(Debug)]
2601 struct UsePlacementFinder {
2602     target_module: NodeId,
2603     first_legal_span: Option<Span>,
2604     first_use_span: Option<Span>,
2605 }
2606
2607 impl UsePlacementFinder {
2608     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2609         let mut finder =
2610             UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2611         finder.visit_crate(krate);
2612         if let Some(use_span) = finder.first_use_span {
2613             (Some(use_span), FoundUse::Yes)
2614         } else {
2615             (finder.first_legal_span, FoundUse::No)
2616         }
2617     }
2618 }
2619
2620 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2621     fn visit_crate(&mut self, c: &Crate) {
2622         if self.target_module == CRATE_NODE_ID {
2623             let inject = c.spans.inject_use_span;
2624             if is_span_suitable_for_use_injection(inject) {
2625                 self.first_legal_span = Some(inject);
2626             }
2627             self.first_use_span = search_for_any_use_in_items(&c.items);
2628             return;
2629         } else {
2630             visit::walk_crate(self, c);
2631         }
2632     }
2633
2634     fn visit_item(&mut self, item: &'tcx ast::Item) {
2635         if self.target_module == item.id {
2636             if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2637                 let inject = mod_spans.inject_use_span;
2638                 if is_span_suitable_for_use_injection(inject) {
2639                     self.first_legal_span = Some(inject);
2640                 }
2641                 self.first_use_span = search_for_any_use_in_items(items);
2642                 return;
2643             }
2644         } else {
2645             visit::walk_item(self, item);
2646         }
2647     }
2648 }
2649
2650 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2651     for item in items {
2652         if let ItemKind::Use(..) = item.kind {
2653             if is_span_suitable_for_use_injection(item.span) {
2654                 return Some(item.span.shrink_to_lo());
2655             }
2656         }
2657     }
2658     return None;
2659 }
2660
2661 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2662     // don't suggest placing a use before the prelude
2663     // import or other generated ones
2664     !s.from_expansion()
2665 }