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