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