]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/diagnostics.rs
Auto merge of #101514 - nvzqz:nvzqz/stabilize-nonzero-bits, r=thomcc
[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.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.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                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1302                     let crate_root = self.expect_module(crate_id.as_def_id());
1303                     suggestions.extend(self.lookup_import_candidates_from_module(
1304                         lookup_ident,
1305                         namespace,
1306                         parent_scope,
1307                         crate_root,
1308                         ident,
1309                         &filter_fn,
1310                     ));
1311                 }
1312             }
1313         }
1314
1315         suggestions
1316     }
1317
1318     pub(crate) fn unresolved_macro_suggestions(
1319         &mut self,
1320         err: &mut Diagnostic,
1321         macro_kind: MacroKind,
1322         parent_scope: &ParentScope<'a>,
1323         ident: Ident,
1324     ) {
1325         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1326         let suggestion = self.early_lookup_typo_candidate(
1327             ScopeSet::Macro(macro_kind),
1328             parent_scope,
1329             ident,
1330             is_expected,
1331         );
1332         self.add_typo_suggestion(err, suggestion, ident.span);
1333
1334         let import_suggestions =
1335             self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1336         show_candidates(
1337             &self.session,
1338             &self.source_span,
1339             err,
1340             None,
1341             &import_suggestions,
1342             Instead::No,
1343             FoundUse::Yes,
1344             DiagnosticMode::Normal,
1345             vec![],
1346         );
1347
1348         if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1349             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1350             err.span_note(ident.span, &msg);
1351             return;
1352         }
1353         if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1354             err.help("have you added the `#[macro_use]` on the module/import?");
1355             return;
1356         }
1357         if ident.name == kw::Default
1358             && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1359             && let Some(span) = self.opt_span(def_id)
1360         {
1361             let source_map = self.session.source_map();
1362             let head_span = source_map.guess_head_span(span);
1363             if let Ok(head) = source_map.span_to_snippet(head_span) {
1364                 err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
1365             } else {
1366                 err.span_help(
1367                     head_span,
1368                     "consider adding `#[derive(Default)]` to this enum",
1369                 );
1370             }
1371         }
1372         for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1373             if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1374                 ident,
1375                 ScopeSet::All(ns, false),
1376                 &parent_scope,
1377                 None,
1378                 false,
1379                 None,
1380             ) {
1381                 let desc = match binding.res() {
1382                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1383                         "a function-like macro".to_string()
1384                     }
1385                     Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1386                         format!("an attribute: `#[{}]`", ident)
1387                     }
1388                     Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1389                         format!("a derive macro: `#[derive({})]`", ident)
1390                     }
1391                     Res::ToolMod => {
1392                         // Don't confuse the user with tool modules.
1393                         continue;
1394                     }
1395                     Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1396                         "only a trait, without a derive macro".to_string()
1397                     }
1398                     res => format!(
1399                         "{} {}, not {} {}",
1400                         res.article(),
1401                         res.descr(),
1402                         macro_kind.article(),
1403                         macro_kind.descr_expected(),
1404                     ),
1405                 };
1406                 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1407                     if !import.span.is_dummy() {
1408                         err.span_note(
1409                             import.span,
1410                             &format!("`{}` is imported here, but it is {}", ident, desc),
1411                         );
1412                         // Silence the 'unused import' warning we might get,
1413                         // since this diagnostic already covers that import.
1414                         self.record_use(ident, binding, false);
1415                         return;
1416                     }
1417                 }
1418                 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1419                 return;
1420             }
1421         }
1422     }
1423
1424     pub(crate) fn add_typo_suggestion(
1425         &self,
1426         err: &mut Diagnostic,
1427         suggestion: Option<TypoSuggestion>,
1428         span: Span,
1429     ) -> bool {
1430         let suggestion = match suggestion {
1431             None => return false,
1432             // We shouldn't suggest underscore.
1433             Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1434             Some(suggestion) => suggestion,
1435         };
1436         let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1437             LOCAL_CRATE => self.opt_span(def_id),
1438             _ => Some(self.cstore().get_span_untracked(def_id, self.session)),
1439         });
1440         if let Some(def_span) = def_span {
1441             if span.overlaps(def_span) {
1442                 // Don't suggest typo suggestion for itself like in the following:
1443                 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1444                 //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1445                 //    |
1446                 // LL | struct X {}
1447                 //    | ----------- `X` defined here
1448                 // LL |
1449                 // LL | const Y: X = X("ö");
1450                 //    | -------------^^^^^^- similarly named constant `Y` defined here
1451                 //    |
1452                 // help: use struct literal syntax instead
1453                 //    |
1454                 // LL | const Y: X = X {};
1455                 //    |              ^^^^
1456                 // help: a constant with a similar name exists
1457                 //    |
1458                 // LL | const Y: X = Y("ö");
1459                 //    |              ^
1460                 return false;
1461             }
1462             let prefix = match suggestion.target {
1463                 SuggestionTarget::SimilarlyNamed => "similarly named ",
1464                 SuggestionTarget::SingleItem => "",
1465             };
1466
1467             err.span_label(
1468                 self.session.source_map().guess_head_span(def_span),
1469                 &format!(
1470                     "{}{} `{}` defined here",
1471                     prefix,
1472                     suggestion.res.descr(),
1473                     suggestion.candidate,
1474                 ),
1475             );
1476         }
1477         let msg = match suggestion.target {
1478             SuggestionTarget::SimilarlyNamed => format!(
1479                 "{} {} with a similar name exists",
1480                 suggestion.res.article(),
1481                 suggestion.res.descr()
1482             ),
1483             SuggestionTarget::SingleItem => {
1484                 format!("maybe you meant this {}", suggestion.res.descr())
1485             }
1486         };
1487         err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect);
1488         true
1489     }
1490
1491     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1492         let res = b.res();
1493         if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) {
1494             // These already contain the "built-in" prefix or look bad with it.
1495             let add_built_in =
1496                 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1497             let (built_in, from) = if from_prelude {
1498                 ("", " from prelude")
1499             } else if b.is_extern_crate()
1500                 && !b.is_import()
1501                 && self.session.opts.externs.get(ident.as_str()).is_some()
1502             {
1503                 ("", " passed with `--extern`")
1504             } else if add_built_in {
1505                 (" built-in", "")
1506             } else {
1507                 ("", "")
1508             };
1509
1510             let a = if built_in.is_empty() { res.article() } else { "a" };
1511             format!("{a}{built_in} {thing}{from}", thing = res.descr())
1512         } else {
1513             let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1514             format!("the {thing} {introduced} here", thing = res.descr())
1515         }
1516     }
1517
1518     fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1519         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1520         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1521             // We have to print the span-less alternative first, otherwise formatting looks bad.
1522             (b2, b1, misc2, misc1, true)
1523         } else {
1524             (b1, b2, misc1, misc2, false)
1525         };
1526
1527         let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1528         err.span_label(ident.span, "ambiguous name");
1529         err.note(&format!("ambiguous because of {}", kind.descr()));
1530
1531         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1532             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1533             let note_msg = format!("`{ident}` could{also} refer to {what}");
1534
1535             let thing = b.res().descr();
1536             let mut help_msgs = Vec::new();
1537             if b.is_glob_import()
1538                 && (kind == AmbiguityKind::GlobVsGlob
1539                     || kind == AmbiguityKind::GlobVsExpanded
1540                     || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1541             {
1542                 help_msgs.push(format!(
1543                     "consider adding an explicit import of `{ident}` to disambiguate"
1544                 ))
1545             }
1546             if b.is_extern_crate() && ident.span.rust_2018() {
1547                 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1548             }
1549             if misc == AmbiguityErrorMisc::SuggestCrate {
1550                 help_msgs
1551                     .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1552             } else if misc == AmbiguityErrorMisc::SuggestSelf {
1553                 help_msgs
1554                     .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1555             }
1556
1557             err.span_note(b.span, &note_msg);
1558             for (i, help_msg) in help_msgs.iter().enumerate() {
1559                 let or = if i == 0 { "" } else { "or " };
1560                 err.help(&format!("{}{}", or, help_msg));
1561             }
1562         };
1563
1564         could_refer_to(b1, misc1, "");
1565         could_refer_to(b2, misc2, " also");
1566         err.emit();
1567     }
1568
1569     /// If the binding refers to a tuple struct constructor with fields,
1570     /// returns the span of its fields.
1571     fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1572         if let NameBindingKind::Res(Res::Def(
1573             DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1574             ctor_def_id,
1575         )) = binding.kind
1576         {
1577             let def_id = self.parent(ctor_def_id);
1578             let fields = self.field_names.get(&def_id)?;
1579             return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1580         }
1581         None
1582     }
1583
1584     fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1585         let PrivacyError { ident, binding, .. } = *privacy_error;
1586
1587         let res = binding.res();
1588         let ctor_fields_span = self.ctor_fields_span(binding);
1589         let plain_descr = res.descr().to_string();
1590         let nonimport_descr =
1591             if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1592         let import_descr = nonimport_descr.clone() + " import";
1593         let get_descr =
1594             |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1595
1596         // Print the primary message.
1597         let descr = get_descr(binding);
1598         let mut err =
1599             struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1600         err.span_label(ident.span, &format!("private {}", descr));
1601         if let Some(span) = ctor_fields_span {
1602             err.span_label(span, "a constructor is private if any of the fields is private");
1603         }
1604
1605         // Print the whole import chain to make it easier to see what happens.
1606         let first_binding = binding;
1607         let mut next_binding = Some(binding);
1608         let mut next_ident = ident;
1609         while let Some(binding) = next_binding {
1610             let name = next_ident;
1611             next_binding = match binding.kind {
1612                 _ if res == Res::Err => None,
1613                 NameBindingKind::Import { binding, import, .. } => match import.kind {
1614                     _ if binding.span.is_dummy() => None,
1615                     ImportKind::Single { source, .. } => {
1616                         next_ident = source;
1617                         Some(binding)
1618                     }
1619                     ImportKind::Glob { .. } | ImportKind::MacroUse | ImportKind::MacroExport => {
1620                         Some(binding)
1621                     }
1622                     ImportKind::ExternCrate { .. } => None,
1623                 },
1624                 _ => None,
1625             };
1626
1627             let first = ptr::eq(binding, first_binding);
1628             let msg = format!(
1629                 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1630                 and_refers_to = if first { "" } else { "...and refers to " },
1631                 item = get_descr(binding),
1632                 which = if first { "" } else { " which" },
1633                 dots = if next_binding.is_some() { "..." } else { "" },
1634             );
1635             let def_span = self.session.source_map().guess_head_span(binding.span);
1636             let mut note_span = MultiSpan::from_span(def_span);
1637             if !first && binding.vis.is_public() {
1638                 note_span.push_span_label(def_span, "consider importing it directly");
1639             }
1640             err.span_note(note_span, &msg);
1641         }
1642
1643         err.emit();
1644     }
1645
1646     pub(crate) fn find_similarly_named_module_or_crate(
1647         &mut self,
1648         ident: Symbol,
1649         current_module: &Module<'a>,
1650     ) -> Option<Symbol> {
1651         let mut candidates = self
1652             .extern_prelude
1653             .iter()
1654             .map(|(ident, _)| ident.name)
1655             .chain(
1656                 self.module_map
1657                     .iter()
1658                     .filter(|(_, module)| {
1659                         current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1660                     })
1661                     .flat_map(|(_, module)| module.kind.name()),
1662             )
1663             .filter(|c| !c.to_string().is_empty())
1664             .collect::<Vec<_>>();
1665         candidates.sort();
1666         candidates.dedup();
1667         match find_best_match_for_name(&candidates, ident, None) {
1668             Some(sugg) if sugg == ident => None,
1669             sugg => sugg,
1670         }
1671     }
1672
1673     pub(crate) fn report_path_resolution_error(
1674         &mut self,
1675         path: &[Segment],
1676         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1677         parent_scope: &ParentScope<'a>,
1678         ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1679         ignore_binding: Option<&'a NameBinding<'a>>,
1680         module: Option<ModuleOrUniformRoot<'a>>,
1681         i: usize,
1682         ident: Ident,
1683     ) -> (String, Option<Suggestion>) {
1684         let is_last = i == path.len() - 1;
1685         let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1686         let module_res = match module {
1687             Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1688             _ => None,
1689         };
1690         if module_res == self.graph_root.res() {
1691             let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1692             let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1693             candidates
1694                 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1695             if let Some(candidate) = candidates.get(0) {
1696                 (
1697                     String::from("unresolved import"),
1698                     Some((
1699                         vec![(ident.span, pprust::path_to_string(&candidate.path))],
1700                         String::from("a similar path exists"),
1701                         Applicability::MaybeIncorrect,
1702                     )),
1703                 )
1704             } else if self.session.edition() == Edition::Edition2015 {
1705                 (
1706                     format!("maybe a missing crate `{ident}`?"),
1707                     Some((
1708                         vec![],
1709                         format!(
1710                             "consider adding `extern crate {ident}` to use the `{ident}` crate"
1711                         ),
1712                         Applicability::MaybeIncorrect,
1713                     )),
1714                 )
1715             } else {
1716                 (format!("could not find `{ident}` in the crate root"), None)
1717             }
1718         } else if i > 0 {
1719             let parent = path[i - 1].ident.name;
1720             let parent = match parent {
1721                 // ::foo is mounted at the crate root for 2015, and is the extern
1722                 // prelude for 2018+
1723                 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1724                     "the list of imported crates".to_owned()
1725                 }
1726                 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1727                 _ => format!("`{parent}`"),
1728             };
1729
1730             let mut msg = format!("could not find `{}` in {}", ident, parent);
1731             if ns == TypeNS || ns == ValueNS {
1732                 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1733                 let binding = if let Some(module) = module {
1734                     self.resolve_ident_in_module(
1735                         module,
1736                         ident,
1737                         ns_to_try,
1738                         parent_scope,
1739                         None,
1740                         ignore_binding,
1741                     ).ok()
1742                 } else if let Some(ribs) = ribs
1743                     && let Some(TypeNS | ValueNS) = opt_ns
1744                 {
1745                     match self.resolve_ident_in_lexical_scope(
1746                         ident,
1747                         ns_to_try,
1748                         parent_scope,
1749                         None,
1750                         &ribs[ns_to_try],
1751                         ignore_binding,
1752                     ) {
1753                         // we found a locally-imported or available item/module
1754                         Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1755                         _ => None,
1756                     }
1757                 } else {
1758                     let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1759                     self.early_resolve_ident_in_lexical_scope(
1760                         ident,
1761                         scopes,
1762                         parent_scope,
1763                         None,
1764                         false,
1765                         ignore_binding,
1766                     ).ok()
1767                 };
1768                 if let Some(binding) = binding {
1769                     let mut found = |what| {
1770                         msg = format!(
1771                             "expected {}, found {} `{}` in {}",
1772                             ns.descr(),
1773                             what,
1774                             ident,
1775                             parent
1776                         )
1777                     };
1778                     if binding.module().is_some() {
1779                         found("module")
1780                     } else {
1781                         match binding.res() {
1782                             Res::Def(kind, id) => found(kind.descr(id)),
1783                             _ => found(ns_to_try.descr()),
1784                         }
1785                     }
1786                 };
1787             }
1788             (msg, None)
1789         } else if ident.name == kw::SelfUpper {
1790             ("`Self` is only available in impls, traits, and type definitions".to_string(), None)
1791         } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1792             // Check whether the name refers to an item in the value namespace.
1793             let binding = if let Some(ribs) = ribs {
1794                 self.resolve_ident_in_lexical_scope(
1795                     ident,
1796                     ValueNS,
1797                     parent_scope,
1798                     None,
1799                     &ribs[ValueNS],
1800                     ignore_binding,
1801                 )
1802             } else {
1803                 None
1804             };
1805             let match_span = match binding {
1806                 // Name matches a local variable. For example:
1807                 // ```
1808                 // fn f() {
1809                 //     let Foo: &str = "";
1810                 //     println!("{}", Foo::Bar); // Name refers to local
1811                 //                               // variable `Foo`.
1812                 // }
1813                 // ```
1814                 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1815                     Some(*self.pat_span_map.get(&id).unwrap())
1816                 }
1817                 // Name matches item from a local name binding
1818                 // created by `use` declaration. For example:
1819                 // ```
1820                 // pub Foo: &str = "";
1821                 //
1822                 // mod submod {
1823                 //     use super::Foo;
1824                 //     println!("{}", Foo::Bar); // Name refers to local
1825                 //                               // binding `Foo`.
1826                 // }
1827                 // ```
1828                 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1829                 _ => None,
1830             };
1831             let suggestion = if let Some(span) = match_span {
1832                 Some((
1833                     vec![(span, String::from(""))],
1834                     format!("`{}` is defined here, but is not a type", ident),
1835                     Applicability::MaybeIncorrect,
1836                 ))
1837             } else {
1838                 None
1839             };
1840
1841             (format!("use of undeclared type `{}`", ident), suggestion)
1842         } else {
1843             let suggestion = if ident.name == sym::alloc {
1844                 Some((
1845                     vec![],
1846                     String::from("add `extern crate alloc` to use the `alloc` crate"),
1847                     Applicability::MaybeIncorrect,
1848                 ))
1849             } else {
1850                 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1851                     |sugg| {
1852                         (
1853                             vec![(ident.span, sugg.to_string())],
1854                             String::from("there is a crate or module with a similar name"),
1855                             Applicability::MaybeIncorrect,
1856                         )
1857                     },
1858                 )
1859             };
1860             (format!("use of undeclared crate or module `{}`", ident), suggestion)
1861         }
1862     }
1863 }
1864
1865 impl<'a, 'b> ImportResolver<'a, 'b> {
1866     /// Adds suggestions for a path that cannot be resolved.
1867     pub(crate) fn make_path_suggestion(
1868         &mut self,
1869         span: Span,
1870         mut path: Vec<Segment>,
1871         parent_scope: &ParentScope<'b>,
1872     ) -> Option<(Vec<Segment>, Option<String>)> {
1873         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1874
1875         match (path.get(0), path.get(1)) {
1876             // `{{root}}::ident::...` on both editions.
1877             // On 2015 `{{root}}` is usually added implicitly.
1878             (Some(fst), Some(snd))
1879                 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1880             // `ident::...` on 2018.
1881             (Some(fst), _)
1882                 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1883             {
1884                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1885                 path.insert(0, Segment::from_ident(Ident::empty()));
1886             }
1887             _ => return None,
1888         }
1889
1890         self.make_missing_self_suggestion(path.clone(), parent_scope)
1891             .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1892             .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1893             .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1894     }
1895
1896     /// Suggest a missing `self::` if that resolves to an correct module.
1897     ///
1898     /// ```text
1899     ///    |
1900     /// LL | use foo::Bar;
1901     ///    |     ^^^ did you mean `self::foo`?
1902     /// ```
1903     fn make_missing_self_suggestion(
1904         &mut self,
1905         mut path: Vec<Segment>,
1906         parent_scope: &ParentScope<'b>,
1907     ) -> Option<(Vec<Segment>, Option<String>)> {
1908         // Replace first ident with `self` and check if that is valid.
1909         path[0].ident.name = kw::SelfLower;
1910         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1911         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1912         if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1913     }
1914
1915     /// Suggests a missing `crate::` if that resolves to an correct module.
1916     ///
1917     /// ```text
1918     ///    |
1919     /// LL | use foo::Bar;
1920     ///    |     ^^^ did you mean `crate::foo`?
1921     /// ```
1922     fn make_missing_crate_suggestion(
1923         &mut self,
1924         mut path: Vec<Segment>,
1925         parent_scope: &ParentScope<'b>,
1926     ) -> Option<(Vec<Segment>, Option<String>)> {
1927         // Replace first ident with `crate` and check if that is valid.
1928         path[0].ident.name = kw::Crate;
1929         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1930         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
1931         if let PathResult::Module(..) = result {
1932             Some((
1933                 path,
1934                 Some(
1935                     "`use` statements changed in Rust 2018; read more at \
1936                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1937                      clarity.html>"
1938                         .to_string(),
1939                 ),
1940             ))
1941         } else {
1942             None
1943         }
1944     }
1945
1946     /// Suggests a missing `super::` if that resolves to an correct module.
1947     ///
1948     /// ```text
1949     ///    |
1950     /// LL | use foo::Bar;
1951     ///    |     ^^^ did you mean `super::foo`?
1952     /// ```
1953     fn make_missing_super_suggestion(
1954         &mut self,
1955         mut path: Vec<Segment>,
1956         parent_scope: &ParentScope<'b>,
1957     ) -> Option<(Vec<Segment>, Option<String>)> {
1958         // Replace first ident with `crate` and check if that is valid.
1959         path[0].ident.name = kw::Super;
1960         let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1961         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
1962         if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1963     }
1964
1965     /// Suggests a missing external crate name if that resolves to an correct module.
1966     ///
1967     /// ```text
1968     ///    |
1969     /// LL | use foobar::Baz;
1970     ///    |     ^^^^^^ did you mean `baz::foobar`?
1971     /// ```
1972     ///
1973     /// Used when importing a submodule of an external crate but missing that crate's
1974     /// name as the first part of path.
1975     fn make_external_crate_suggestion(
1976         &mut self,
1977         mut path: Vec<Segment>,
1978         parent_scope: &ParentScope<'b>,
1979     ) -> Option<(Vec<Segment>, Option<String>)> {
1980         if path[1].ident.span.rust_2015() {
1981             return None;
1982         }
1983
1984         // Sort extern crate names in *reverse* order to get
1985         // 1) some consistent ordering for emitted diagnostics, and
1986         // 2) `std` suggestions before `core` suggestions.
1987         let mut extern_crate_names =
1988             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1989         extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
1990
1991         for name in extern_crate_names.into_iter() {
1992             // Replace first ident with a crate name and check if that is valid.
1993             path[0].ident.name = name;
1994             let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1995             debug!(
1996                 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1997                 name, path, result
1998             );
1999             if let PathResult::Module(..) = result {
2000                 return Some((path, None));
2001             }
2002         }
2003
2004         None
2005     }
2006
2007     /// Suggests importing a macro from the root of the crate rather than a module within
2008     /// the crate.
2009     ///
2010     /// ```text
2011     /// help: a macro with this name exists at the root of the crate
2012     ///    |
2013     /// LL | use issue_59764::makro;
2014     ///    |     ^^^^^^^^^^^^^^^^^^
2015     ///    |
2016     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2017     ///            at the root of the crate instead of the module where it is defined
2018     /// ```
2019     pub(crate) fn check_for_module_export_macro(
2020         &mut self,
2021         import: &'b Import<'b>,
2022         module: ModuleOrUniformRoot<'b>,
2023         ident: Ident,
2024     ) -> Option<(Option<Suggestion>, Option<String>)> {
2025         let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2026             return None;
2027         };
2028
2029         while let Some(parent) = crate_module.parent {
2030             crate_module = parent;
2031         }
2032
2033         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2034             // Don't make a suggestion if the import was already from the root of the
2035             // crate.
2036             return None;
2037         }
2038
2039         let resolutions = self.r.resolutions(crate_module).borrow();
2040         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2041         let binding = resolution.borrow().binding()?;
2042         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2043             let module_name = crate_module.kind.name().unwrap();
2044             let import_snippet = match import.kind {
2045                 ImportKind::Single { source, target, .. } if source != target => {
2046                     format!("{} as {}", source, target)
2047                 }
2048                 _ => format!("{}", ident),
2049             };
2050
2051             let mut corrections: Vec<(Span, String)> = Vec::new();
2052             if !import.is_nested() {
2053                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2054                 // intermediate segments.
2055                 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2056             } else {
2057                 // Find the binding span (and any trailing commas and spaces).
2058                 //   ie. `use a::b::{c, d, e};`
2059                 //                      ^^^
2060                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2061                     self.r.session,
2062                     import.span,
2063                     import.use_span,
2064                 );
2065                 debug!(
2066                     "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2067                     found_closing_brace, binding_span
2068                 );
2069
2070                 let mut removal_span = binding_span;
2071                 if found_closing_brace {
2072                     // If the binding span ended with a closing brace, as in the below example:
2073                     //   ie. `use a::b::{c, d};`
2074                     //                      ^
2075                     // Then expand the span of characters to remove to include the previous
2076                     // binding's trailing comma.
2077                     //   ie. `use a::b::{c, d};`
2078                     //                    ^^^
2079                     if let Some(previous_span) =
2080                         extend_span_to_previous_binding(self.r.session, binding_span)
2081                     {
2082                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2083                         removal_span = removal_span.with_lo(previous_span.lo());
2084                     }
2085                 }
2086                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2087
2088                 // Remove the `removal_span`.
2089                 corrections.push((removal_span, "".to_string()));
2090
2091                 // Find the span after the crate name and if it has nested imports immediately
2092                 // after the crate name already.
2093                 //   ie. `use a::b::{c, d};`
2094                 //               ^^^^^^^^^
2095                 //   or  `use a::{b, c, d}};`
2096                 //               ^^^^^^^^^^^
2097                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2098                     self.r.session,
2099                     module_name,
2100                     import.use_span,
2101                 );
2102                 debug!(
2103                     "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2104                     has_nested, after_crate_name
2105                 );
2106
2107                 let source_map = self.r.session.source_map();
2108
2109                 // Add the import to the start, with a `{` if required.
2110                 let start_point = source_map.start_point(after_crate_name);
2111                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2112                     corrections.push((
2113                         start_point,
2114                         if has_nested {
2115                             // In this case, `start_snippet` must equal '{'.
2116                             format!("{}{}, ", start_snippet, import_snippet)
2117                         } else {
2118                             // In this case, add a `{`, then the moved import, then whatever
2119                             // was there before.
2120                             format!("{{{}, {}", import_snippet, start_snippet)
2121                         },
2122                     ));
2123                 }
2124
2125                 // Add a `};` to the end if nested, matching the `{` added at the start.
2126                 if !has_nested {
2127                     corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2128                 }
2129             }
2130
2131             let suggestion = Some((
2132                 corrections,
2133                 String::from("a macro with this name exists at the root of the crate"),
2134                 Applicability::MaybeIncorrect,
2135             ));
2136             Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \
2137             at the root of the crate instead of the module where it is defined"
2138                .to_string())))
2139         } else {
2140             None
2141         }
2142     }
2143 }
2144
2145 /// Given a `binding_span` of a binding within a use statement:
2146 ///
2147 /// ```ignore (illustrative)
2148 /// use foo::{a, b, c};
2149 /// //           ^
2150 /// ```
2151 ///
2152 /// then return the span until the next binding or the end of the statement:
2153 ///
2154 /// ```ignore (illustrative)
2155 /// use foo::{a, b, c};
2156 /// //           ^^^
2157 /// ```
2158 fn find_span_of_binding_until_next_binding(
2159     sess: &Session,
2160     binding_span: Span,
2161     use_span: Span,
2162 ) -> (bool, Span) {
2163     let source_map = sess.source_map();
2164
2165     // Find the span of everything after the binding.
2166     //   ie. `a, e};` or `a};`
2167     let binding_until_end = binding_span.with_hi(use_span.hi());
2168
2169     // Find everything after the binding but not including the binding.
2170     //   ie. `, e};` or `};`
2171     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2172
2173     // Keep characters in the span until we encounter something that isn't a comma or
2174     // whitespace.
2175     //   ie. `, ` or ``.
2176     //
2177     // Also note whether a closing brace character was encountered. If there
2178     // was, then later go backwards to remove any trailing commas that are left.
2179     let mut found_closing_brace = false;
2180     let after_binding_until_next_binding =
2181         source_map.span_take_while(after_binding_until_end, |&ch| {
2182             if ch == '}' {
2183                 found_closing_brace = true;
2184             }
2185             ch == ' ' || ch == ','
2186         });
2187
2188     // Combine the two spans.
2189     //   ie. `a, ` or `a`.
2190     //
2191     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2192     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2193
2194     (found_closing_brace, span)
2195 }
2196
2197 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2198 /// binding.
2199 ///
2200 /// ```ignore (illustrative)
2201 /// use foo::a::{a, b, c};
2202 /// //            ^^--- binding span
2203 /// //            |
2204 /// //            returned span
2205 ///
2206 /// use foo::{a, b, c};
2207 /// //        --- binding span
2208 /// ```
2209 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2210     let source_map = sess.source_map();
2211
2212     // `prev_source` will contain all of the source that came before the span.
2213     // Then split based on a command and take the first (ie. closest to our span)
2214     // snippet. In the example, this is a space.
2215     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2216
2217     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2218     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2219     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2220         return None;
2221     }
2222
2223     let prev_comma = prev_comma.first().unwrap();
2224     let prev_starting_brace = prev_starting_brace.first().unwrap();
2225
2226     // If the amount of source code before the comma is greater than
2227     // the amount of source code before the starting brace then we've only
2228     // got one item in the nested item (eg. `issue_52891::{self}`).
2229     if prev_comma.len() > prev_starting_brace.len() {
2230         return None;
2231     }
2232
2233     Some(binding_span.with_lo(BytePos(
2234         // Take away the number of bytes for the characters we've found and an
2235         // extra for the comma.
2236         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2237     )))
2238 }
2239
2240 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2241 /// it is a nested use tree.
2242 ///
2243 /// ```ignore (illustrative)
2244 /// use foo::a::{b, c};
2245 /// //       ^^^^^^^^^^ -- false
2246 ///
2247 /// use foo::{a, b, c};
2248 /// //       ^^^^^^^^^^ -- true
2249 ///
2250 /// use foo::{a, b::{c, d}};
2251 /// //       ^^^^^^^^^^^^^^^ -- true
2252 /// ```
2253 fn find_span_immediately_after_crate_name(
2254     sess: &Session,
2255     module_name: Symbol,
2256     use_span: Span,
2257 ) -> (bool, Span) {
2258     debug!(
2259         "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2260         module_name, use_span
2261     );
2262     let source_map = sess.source_map();
2263
2264     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2265     let mut num_colons = 0;
2266     // Find second colon.. `use issue_59764:`
2267     let until_second_colon = source_map.span_take_while(use_span, |c| {
2268         if *c == ':' {
2269             num_colons += 1;
2270         }
2271         !matches!(c, ':' if num_colons == 2)
2272     });
2273     // Find everything after the second colon.. `foo::{baz, makro};`
2274     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2275
2276     let mut found_a_non_whitespace_character = false;
2277     // Find the first non-whitespace character in `from_second_colon`.. `f`
2278     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2279         if found_a_non_whitespace_character {
2280             return false;
2281         }
2282         if !c.is_whitespace() {
2283             found_a_non_whitespace_character = true;
2284         }
2285         true
2286     });
2287
2288     // Find the first `{` in from_second_colon.. `foo::{`
2289     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2290
2291     (next_left_bracket == after_second_colon, from_second_colon)
2292 }
2293
2294 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2295 /// independent options.
2296 enum Instead {
2297     Yes,
2298     No,
2299 }
2300
2301 /// Whether an existing place with an `use` item was found.
2302 enum FoundUse {
2303     Yes,
2304     No,
2305 }
2306
2307 /// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2308 enum DiagnosticMode {
2309     Normal,
2310     /// The binding is part of a pattern
2311     Pattern,
2312     /// The binding is part of a use statement
2313     Import,
2314 }
2315
2316 pub(crate) fn import_candidates(
2317     session: &Session,
2318     source_span: &IndexVec<LocalDefId, Span>,
2319     err: &mut Diagnostic,
2320     // This is `None` if all placement locations are inside expansions
2321     use_placement_span: Option<Span>,
2322     candidates: &[ImportSuggestion],
2323 ) {
2324     show_candidates(
2325         session,
2326         source_span,
2327         err,
2328         use_placement_span,
2329         candidates,
2330         Instead::Yes,
2331         FoundUse::Yes,
2332         DiagnosticMode::Import,
2333         vec![],
2334     );
2335 }
2336
2337 /// When an entity with a given name is not available in scope, we search for
2338 /// entities with that name in all crates. This method allows outputting the
2339 /// results of this search in a programmer-friendly way
2340 fn show_candidates(
2341     session: &Session,
2342     source_span: &IndexVec<LocalDefId, Span>,
2343     err: &mut Diagnostic,
2344     // This is `None` if all placement locations are inside expansions
2345     use_placement_span: Option<Span>,
2346     candidates: &[ImportSuggestion],
2347     instead: Instead,
2348     found_use: FoundUse,
2349     mode: DiagnosticMode,
2350     path: Vec<Segment>,
2351 ) {
2352     if candidates.is_empty() {
2353         return;
2354     }
2355
2356     let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2357         Vec::new();
2358     let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2359         Vec::new();
2360
2361     candidates.iter().for_each(|c| {
2362         (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2363             .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2364     });
2365
2366     // we want consistent results across executions, but candidates are produced
2367     // by iterating through a hash map, so make sure they are ordered:
2368     for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2369         path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2370         let core_path_strings =
2371             path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2372         path_strings.extend(core_path_strings);
2373         path_strings.dedup_by(|a, b| a.0 == b.0);
2374     }
2375
2376     if !accessible_path_strings.is_empty() {
2377         let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2378             ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2379         } else {
2380             ("one of these", "items", String::new())
2381         };
2382
2383         let instead = if let Instead::Yes = instead { " instead" } else { "" };
2384         let mut msg = if let DiagnosticMode::Pattern = mode {
2385             format!(
2386                 "if you meant to match on {}{}{}, use the full path in the pattern",
2387                 kind, instead, name
2388             )
2389         } else {
2390             format!("consider importing {} {}{}", determiner, kind, instead)
2391         };
2392
2393         for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2394             err.note(note);
2395         }
2396
2397         if let Some(span) = use_placement_span {
2398             let add_use = match mode {
2399                 DiagnosticMode::Pattern => {
2400                     err.span_suggestions(
2401                         span,
2402                         &msg,
2403                         accessible_path_strings.into_iter().map(|a| a.0),
2404                         Applicability::MaybeIncorrect,
2405                     );
2406                     return;
2407                 }
2408                 DiagnosticMode::Import => "",
2409                 DiagnosticMode::Normal => "use ",
2410             };
2411             for candidate in &mut accessible_path_strings {
2412                 // produce an additional newline to separate the new use statement
2413                 // from the directly following item.
2414                 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2415                 candidate.0 = format!("{}{};\n{}", add_use, &candidate.0, additional_newline);
2416             }
2417
2418             err.span_suggestions(
2419                 span,
2420                 &msg,
2421                 accessible_path_strings.into_iter().map(|a| a.0),
2422                 Applicability::MaybeIncorrect,
2423             );
2424             if let [first, .., last] = &path[..] {
2425                 let sp = first.ident.span.until(last.ident.span);
2426                 if sp.can_be_used_for_suggestions() {
2427                     err.span_suggestion_verbose(
2428                         sp,
2429                         &format!("if you import `{}`, refer to it directly", last.ident),
2430                         "",
2431                         Applicability::Unspecified,
2432                     );
2433                 }
2434             }
2435         } else {
2436             msg.push(':');
2437
2438             for candidate in accessible_path_strings {
2439                 msg.push('\n');
2440                 msg.push_str(&candidate.0);
2441             }
2442
2443             err.note(&msg);
2444         }
2445     } else if !matches!(mode, DiagnosticMode::Import) {
2446         assert!(!inaccessible_path_strings.is_empty());
2447
2448         let prefix = if let DiagnosticMode::Pattern = mode {
2449             "you might have meant to match on "
2450         } else {
2451             ""
2452         };
2453         if inaccessible_path_strings.len() == 1 {
2454             let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2455             let msg = format!(
2456                 "{}{} `{}`{} exists but is inaccessible",
2457                 prefix,
2458                 descr,
2459                 name,
2460                 if let DiagnosticMode::Pattern = mode { ", which" } else { "" }
2461             );
2462
2463             if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2464                 let span = source_span[local_def_id];
2465                 let span = session.source_map().guess_head_span(span);
2466                 let mut multi_span = MultiSpan::from_span(span);
2467                 multi_span.push_span_label(span, "not accessible");
2468                 err.span_note(multi_span, &msg);
2469             } else {
2470                 err.note(&msg);
2471             }
2472             if let Some(note) = (*note).as_deref() {
2473                 err.note(note);
2474             }
2475         } else {
2476             let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2477             let descr = if inaccessible_path_strings
2478                 .iter()
2479                 .skip(1)
2480                 .all(|(_, descr, _, _)| descr == descr_first)
2481             {
2482                 descr_first
2483             } else {
2484                 "item"
2485             };
2486             let plural_descr =
2487                 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2488
2489             let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2490             let mut has_colon = false;
2491
2492             let mut spans = Vec::new();
2493             for (name, _, def_id, _) in &inaccessible_path_strings {
2494                 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2495                     let span = source_span[local_def_id];
2496                     let span = session.source_map().guess_head_span(span);
2497                     spans.push((name, span));
2498                 } else {
2499                     if !has_colon {
2500                         msg.push(':');
2501                         has_colon = true;
2502                     }
2503                     msg.push('\n');
2504                     msg.push_str(name);
2505                 }
2506             }
2507
2508             let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2509             for (name, span) in spans {
2510                 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2511             }
2512
2513             for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2514                 err.note(note);
2515             }
2516
2517             err.span_note(multi_span, &msg);
2518         }
2519     }
2520 }
2521
2522 #[derive(Debug)]
2523 struct UsePlacementFinder {
2524     target_module: NodeId,
2525     first_legal_span: Option<Span>,
2526     first_use_span: Option<Span>,
2527 }
2528
2529 impl UsePlacementFinder {
2530     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2531         let mut finder =
2532             UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2533         finder.visit_crate(krate);
2534         if let Some(use_span) = finder.first_use_span {
2535             (Some(use_span), FoundUse::Yes)
2536         } else {
2537             (finder.first_legal_span, FoundUse::No)
2538         }
2539     }
2540 }
2541
2542 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2543     fn visit_crate(&mut self, c: &Crate) {
2544         if self.target_module == CRATE_NODE_ID {
2545             let inject = c.spans.inject_use_span;
2546             if is_span_suitable_for_use_injection(inject) {
2547                 self.first_legal_span = Some(inject);
2548             }
2549             self.first_use_span = search_for_any_use_in_items(&c.items);
2550             return;
2551         } else {
2552             visit::walk_crate(self, c);
2553         }
2554     }
2555
2556     fn visit_item(&mut self, item: &'tcx ast::Item) {
2557         if self.target_module == item.id {
2558             if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2559                 let inject = mod_spans.inject_use_span;
2560                 if is_span_suitable_for_use_injection(inject) {
2561                     self.first_legal_span = Some(inject);
2562                 }
2563                 self.first_use_span = search_for_any_use_in_items(items);
2564                 return;
2565             }
2566         } else {
2567             visit::walk_item(self, item);
2568         }
2569     }
2570 }
2571
2572 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2573     for item in items {
2574         if let ItemKind::Use(..) = item.kind {
2575             if is_span_suitable_for_use_injection(item.span) {
2576                 return Some(item.span.shrink_to_lo());
2577             }
2578         }
2579     }
2580     return None;
2581 }
2582
2583 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2584     // don't suggest placing a use before the prelude
2585     // import or other generated ones
2586     !s.from_expansion()
2587 }
2588
2589 /// Convert the given number into the corresponding ordinal
2590 pub(crate) fn ordinalize(v: usize) -> String {
2591     let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2592         (false, 1) => "st",
2593         (false, 2) => "nd",
2594         (false, 3) => "rd",
2595         _ => "th",
2596     };
2597     format!("{v}{suffix}")
2598 }