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