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