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