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