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