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