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