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