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