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