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