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