]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/diagnostics.rs
Auto merge of #91403 - cjgillot:inherit-async, r=oli-obk
[rust.git] / compiler / rustc_resolve / src / diagnostics.rs
1 use std::ptr;
2
3 use rustc_ast::{self as ast, Path};
4 use rustc_ast_pretty::pprust;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
7 use rustc_feature::BUILTIN_ATTRIBUTES;
8 use rustc_hir::def::Namespace::{self, *};
9 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
10 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::PrimTy;
12 use rustc_middle::bug;
13 use rustc_middle::ty::DefIdTree;
14 use rustc_session::Session;
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::lev_distance::find_best_match_for_name;
17 use rustc_span::source_map::SourceMap;
18 use rustc_span::symbol::{kw, sym, Ident, Symbol};
19 use rustc_span::{BytePos, MultiSpan, Span};
20 use tracing::debug;
21
22 use crate::imports::{Import, ImportKind, ImportResolver};
23 use crate::path_names_to_string;
24 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
25 use crate::{
26     BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
27 };
28 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
29 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
30
31 type Res = def::Res<ast::NodeId>;
32
33 /// A vector of spans and replacements, a message and applicability.
34 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
35
36 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
37 /// similarly named label and whether or not it is reachable.
38 crate type LabelSuggestion = (Ident, bool);
39
40 crate enum SuggestionTarget {
41     /// The target has a similar name as the name used by the programmer (probably a typo)
42     SimilarlyNamed,
43     /// The target is the only valid item that can be used in the corresponding context
44     SingleItem,
45 }
46
47 crate struct TypoSuggestion {
48     pub candidate: Symbol,
49     pub res: Res,
50     pub target: SuggestionTarget,
51 }
52
53 impl TypoSuggestion {
54     crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
55         Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
56     }
57     crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
58         Self { candidate, res, target: SuggestionTarget::SingleItem }
59     }
60 }
61
62 /// A free importable items suggested in case of resolution failure.
63 crate struct ImportSuggestion {
64     pub did: Option<DefId>,
65     pub descr: &'static str,
66     pub path: Path,
67     pub accessible: bool,
68     /// An extra note that should be issued if this item is suggested
69     pub note: Option<String>,
70 }
71
72 /// Adjust the impl span so that just the `impl` keyword is taken by removing
73 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
74 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
75 ///
76 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
77 /// parser. If you need to use this function or something similar, please consider updating the
78 /// `source_map` functions and this function to something more robust.
79 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
80     let impl_span = sm.span_until_char(impl_span, '<');
81     sm.span_until_whitespace(impl_span)
82 }
83
84 impl<'a> Resolver<'a> {
85     crate fn add_module_candidates(
86         &mut self,
87         module: Module<'a>,
88         names: &mut Vec<TypoSuggestion>,
89         filter_fn: &impl Fn(Res) -> bool,
90     ) {
91         for (key, resolution) in self.resolutions(module).borrow().iter() {
92             if let Some(binding) = resolution.borrow().binding {
93                 let res = binding.res();
94                 if filter_fn(res) {
95                     names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
96                 }
97             }
98         }
99     }
100
101     /// Combines an error with provided span and emits it.
102     ///
103     /// This takes the error provided, combines it with the span and any additional spans inside the
104     /// error and emits it.
105     crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
106         self.into_struct_error(span, resolution_error).emit();
107     }
108
109     crate fn into_struct_error(
110         &self,
111         span: Span,
112         resolution_error: ResolutionError<'_>,
113     ) -> DiagnosticBuilder<'_> {
114         match resolution_error {
115             ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
116                 let mut err = struct_span_err!(
117                     self.session,
118                     span,
119                     E0401,
120                     "can't use generic parameters from outer function",
121                 );
122                 err.span_label(span, "use of generic parameter from outer function".to_string());
123
124                 let sm = self.session.source_map();
125                 match outer_res {
126                     Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
127                         if let Some(impl_span) =
128                             maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
129                         {
130                             err.span_label(
131                                 reduce_impl_span_to_impl_keyword(sm, impl_span),
132                                 "`Self` type implicitly declared here, by this `impl`",
133                             );
134                         }
135                         match (maybe_trait_defid, maybe_impl_defid) {
136                             (Some(_), None) => {
137                                 err.span_label(span, "can't use `Self` here");
138                             }
139                             (_, Some(_)) => {
140                                 err.span_label(span, "use a type here instead");
141                             }
142                             (None, None) => bug!("`impl` without trait nor type?"),
143                         }
144                         return err;
145                     }
146                     Res::Def(DefKind::TyParam, def_id) => {
147                         if let Some(span) = self.opt_span(def_id) {
148                             err.span_label(span, "type parameter from outer function");
149                         }
150                     }
151                     Res::Def(DefKind::ConstParam, def_id) => {
152                         if let Some(span) = self.opt_span(def_id) {
153                             err.span_label(span, "const parameter from outer function");
154                         }
155                     }
156                     _ => {
157                         bug!(
158                             "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
159                             DefKind::TyParam or DefKind::ConstParam"
160                         );
161                     }
162                 }
163
164                 if has_generic_params == HasGenericParams::Yes {
165                     // Try to retrieve the span of the function signature and generate a new
166                     // message with a local type or const parameter.
167                     let sugg_msg = "try using a local generic parameter instead";
168                     if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
169                         // Suggest the modification to the user
170                         err.span_suggestion(
171                             sugg_span,
172                             sugg_msg,
173                             snippet,
174                             Applicability::MachineApplicable,
175                         );
176                     } else if let Some(sp) = sm.generate_fn_name_span(span) {
177                         err.span_label(
178                             sp,
179                             "try adding a local generic parameter in this method instead"
180                                 .to_string(),
181                         );
182                     } else {
183                         err.help("try using a local generic parameter instead");
184                     }
185                 }
186
187                 err
188             }
189             ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
190                 let mut err = struct_span_err!(
191                     self.session,
192                     span,
193                     E0403,
194                     "the name `{}` is already used for a generic \
195                      parameter in this item's generic parameters",
196                     name,
197                 );
198                 err.span_label(span, "already used");
199                 err.span_label(first_use_span, format!("first use of `{}`", name));
200                 err
201             }
202             ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
203                 let mut err = struct_span_err!(
204                     self.session,
205                     span,
206                     E0407,
207                     "method `{}` is not a member of trait `{}`",
208                     method,
209                     trait_
210                 );
211                 err.span_label(span, format!("not a member of trait `{}`", trait_));
212                 if let Some(candidate) = candidate {
213                     err.span_suggestion(
214                         method.span,
215                         "there is an associated function with a similar name",
216                         candidate.to_ident_string(),
217                         Applicability::MaybeIncorrect,
218                     );
219                 }
220                 err
221             }
222             ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
223                 let mut err = struct_span_err!(
224                     self.session,
225                     span,
226                     E0437,
227                     "type `{}` is not a member of trait `{}`",
228                     type_,
229                     trait_
230                 );
231                 err.span_label(span, format!("not a member of trait `{}`", trait_));
232                 if let Some(candidate) = candidate {
233                     err.span_suggestion(
234                         type_.span,
235                         "there is an associated type with a similar name",
236                         candidate.to_ident_string(),
237                         Applicability::MaybeIncorrect,
238                     );
239                 }
240                 err
241             }
242             ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
243                 let mut err = struct_span_err!(
244                     self.session,
245                     span,
246                     E0438,
247                     "const `{}` is not a member of trait `{}`",
248                     const_,
249                     trait_
250                 );
251                 err.span_label(span, format!("not a member of trait `{}`", trait_));
252                 if let Some(candidate) = candidate {
253                     err.span_suggestion(
254                         const_.span,
255                         "there is an associated constant with a similar name",
256                         candidate.to_ident_string(),
257                         Applicability::MaybeIncorrect,
258                     );
259                 }
260                 err
261             }
262             ResolutionError::VariableNotBoundInPattern(binding_error) => {
263                 let BindingError { name, target, origin, could_be_path } = binding_error;
264
265                 let target_sp = target.iter().copied().collect::<Vec<_>>();
266                 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
267
268                 let msp = MultiSpan::from_spans(target_sp.clone());
269                 let mut err = struct_span_err!(
270                     self.session,
271                     msp,
272                     E0408,
273                     "variable `{}` is not bound in all patterns",
274                     name,
275                 );
276                 for sp in target_sp {
277                     err.span_label(sp, format!("pattern doesn't bind `{}`", name));
278                 }
279                 for sp in origin_sp {
280                     err.span_label(sp, "variable not in all patterns");
281                 }
282                 if *could_be_path {
283                     let help_msg = format!(
284                         "if you meant to match on a variant or a `const` item, consider \
285                          making the path in the pattern qualified: `?::{}`",
286                         name,
287                     );
288                     err.span_help(span, &help_msg);
289                 }
290                 err
291             }
292             ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
293                 let mut err = struct_span_err!(
294                     self.session,
295                     span,
296                     E0409,
297                     "variable `{}` is bound inconsistently across alternatives separated by `|`",
298                     variable_name
299                 );
300                 err.span_label(span, "bound in different ways");
301                 err.span_label(first_binding_span, "first binding");
302                 err
303             }
304             ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
305                 let mut err = struct_span_err!(
306                     self.session,
307                     span,
308                     E0415,
309                     "identifier `{}` is bound more than once in this parameter list",
310                     identifier
311                 );
312                 err.span_label(span, "used as parameter more than once");
313                 err
314             }
315             ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
316                 let mut err = struct_span_err!(
317                     self.session,
318                     span,
319                     E0416,
320                     "identifier `{}` is bound more than once in the same pattern",
321                     identifier
322                 );
323                 err.span_label(span, "used in a pattern more than once");
324                 err
325             }
326             ResolutionError::UndeclaredLabel { name, suggestion } => {
327                 let mut err = struct_span_err!(
328                     self.session,
329                     span,
330                     E0426,
331                     "use of undeclared label `{}`",
332                     name
333                 );
334
335                 err.span_label(span, format!("undeclared label `{}`", name));
336
337                 match suggestion {
338                     // A reachable label with a similar name exists.
339                     Some((ident, true)) => {
340                         err.span_label(ident.span, "a label with a similar name is reachable");
341                         err.span_suggestion(
342                             span,
343                             "try using similarly named label",
344                             ident.name.to_string(),
345                             Applicability::MaybeIncorrect,
346                         );
347                     }
348                     // An unreachable label with a similar name exists.
349                     Some((ident, false)) => {
350                         err.span_label(
351                             ident.span,
352                             "a label with a similar name exists but is unreachable",
353                         );
354                     }
355                     // No similarly-named labels exist.
356                     None => (),
357                 }
358
359                 err
360             }
361             ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
362                 let mut err = struct_span_err!(
363                     self.session,
364                     span,
365                     E0429,
366                     "{}",
367                     "`self` imports are only allowed within a { } list"
368                 );
369
370                 // None of the suggestions below would help with a case like `use self`.
371                 if !root {
372                     // use foo::bar::self        -> foo::bar
373                     // use foo::bar::self as abc -> foo::bar as abc
374                     err.span_suggestion(
375                         span,
376                         "consider importing the module directly",
377                         "".to_string(),
378                         Applicability::MachineApplicable,
379                     );
380
381                     // use foo::bar::self        -> foo::bar::{self}
382                     // use foo::bar::self as abc -> foo::bar::{self as abc}
383                     let braces = vec![
384                         (span_with_rename.shrink_to_lo(), "{".to_string()),
385                         (span_with_rename.shrink_to_hi(), "}".to_string()),
386                     ];
387                     err.multipart_suggestion(
388                         "alternatively, use the multi-path `use` syntax to import `self`",
389                         braces,
390                         Applicability::MachineApplicable,
391                     );
392                 }
393                 err
394             }
395             ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
396                 let mut err = struct_span_err!(
397                     self.session,
398                     span,
399                     E0430,
400                     "`self` import can only appear once in an import list"
401                 );
402                 err.span_label(span, "can only appear once in an import list");
403                 err
404             }
405             ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
406                 let mut err = struct_span_err!(
407                     self.session,
408                     span,
409                     E0431,
410                     "`self` import can only appear in an import list with \
411                                                 a non-empty prefix"
412                 );
413                 err.span_label(span, "can only appear in an import list with a non-empty prefix");
414                 err
415             }
416             ResolutionError::FailedToResolve { label, suggestion } => {
417                 let mut err =
418                     struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
419                 err.span_label(span, label);
420
421                 if let Some((suggestions, msg, applicability)) = suggestion {
422                     if suggestions.is_empty() {
423                         err.help(&msg);
424                         return err;
425                     }
426                     err.multipart_suggestion(&msg, suggestions, applicability);
427                 }
428
429                 err
430             }
431             ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
432                 let mut err = struct_span_err!(
433                     self.session,
434                     span,
435                     E0434,
436                     "{}",
437                     "can't capture dynamic environment in a fn item"
438                 );
439                 err.help("use the `|| { ... }` closure form instead");
440                 err
441             }
442             ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
443                 let mut err = struct_span_err!(
444                     self.session,
445                     span,
446                     E0435,
447                     "attempt to use a non-constant value in a constant"
448                 );
449                 // let foo =...
450                 //     ^^^ given this Span
451                 // ------- get this Span to have an applicable suggestion
452
453                 // edit:
454                 // only do this if the const and usage of the non-constant value are on the same line
455                 // the further the two are apart, the higher the chance of the suggestion being wrong
456
457                 let sp = self
458                     .session
459                     .source_map()
460                     .span_extend_to_prev_str(ident.span, current, true, false);
461
462                 match sp {
463                     Some(sp) if !self.session.source_map().is_multiline(sp) => {
464                         let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
465                         err.span_suggestion(
466                             sp,
467                             &format!("consider using `{}` instead of `{}`", sugg, current),
468                             format!("{} {}", sugg, ident),
469                             Applicability::MaybeIncorrect,
470                         );
471                         err.span_label(span, "non-constant value");
472                     }
473                     _ => {
474                         err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
475                     }
476                 }
477
478                 err
479             }
480             ResolutionError::BindingShadowsSomethingUnacceptable {
481                 shadowing_binding_descr,
482                 name,
483                 participle,
484                 article,
485                 shadowed_binding_descr,
486                 shadowed_binding_span,
487             } => {
488                 let mut err = struct_span_err!(
489                     self.session,
490                     span,
491                     E0530,
492                     "{}s cannot shadow {}s",
493                     shadowing_binding_descr,
494                     shadowed_binding_descr,
495                 );
496                 err.span_label(
497                     span,
498                     format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
499                 );
500                 let msg =
501                     format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
502                 err.span_label(shadowed_binding_span, msg);
503                 err
504             }
505             ResolutionError::ForwardDeclaredGenericParam => {
506                 let mut err = struct_span_err!(
507                     self.session,
508                     span,
509                     E0128,
510                     "generic parameters with a default cannot use \
511                                                 forward declared identifiers"
512                 );
513                 err.span_label(
514                     span,
515                     "defaulted generic parameters cannot be forward declared".to_string(),
516                 );
517                 err
518             }
519             ResolutionError::ParamInTyOfConstParam(name) => {
520                 let mut err = struct_span_err!(
521                     self.session,
522                     span,
523                     E0770,
524                     "the type of const parameters must not depend on other generic parameters"
525                 );
526                 err.span_label(
527                     span,
528                     format!("the type must not depend on the parameter `{}`", name),
529                 );
530                 err
531             }
532             ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
533                 let mut err = self.session.struct_span_err(
534                     span,
535                     "generic parameters may not be used in const operations",
536                 );
537                 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
538
539                 if is_type {
540                     err.note("type parameters may not be used in const expressions");
541                 } else {
542                     err.help(&format!(
543                         "const parameters may only be used as standalone arguments, i.e. `{}`",
544                         name
545                     ));
546                 }
547
548                 if self.session.is_nightly_build() {
549                     err.help(
550                         "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
551                     );
552                 }
553
554                 err
555             }
556             ResolutionError::SelfInGenericParamDefault => {
557                 let mut err = struct_span_err!(
558                     self.session,
559                     span,
560                     E0735,
561                     "generic parameters cannot use `Self` in their defaults"
562                 );
563                 err.span_label(span, "`Self` in generic parameter default".to_string());
564                 err
565             }
566             ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
567                 let mut err = struct_span_err!(
568                     self.session,
569                     span,
570                     E0767,
571                     "use of unreachable label `{}`",
572                     name,
573                 );
574
575                 err.span_label(definition_span, "unreachable label defined here");
576                 err.span_label(span, format!("unreachable label `{}`", name));
577                 err.note(
578                     "labels are unreachable through functions, closures, async blocks and modules",
579                 );
580
581                 match suggestion {
582                     // A reachable label with a similar name exists.
583                     Some((ident, true)) => {
584                         err.span_label(ident.span, "a label with a similar name is reachable");
585                         err.span_suggestion(
586                             span,
587                             "try using similarly named label",
588                             ident.name.to_string(),
589                             Applicability::MaybeIncorrect,
590                         );
591                     }
592                     // An unreachable label with a similar name exists.
593                     Some((ident, false)) => {
594                         err.span_label(
595                             ident.span,
596                             "a label with a similar name exists but is also unreachable",
597                         );
598                     }
599                     // No similarly-named labels exist.
600                     None => (),
601                 }
602
603                 err
604             }
605             ResolutionError::TraitImplMismatch {
606                 name,
607                 kind,
608                 code,
609                 trait_item_span,
610                 trait_path,
611             } => {
612                 let mut err = self.session.struct_span_err_with_code(
613                     span,
614                     &format!(
615                         "item `{}` is an associated {}, which doesn't match its trait `{}`",
616                         name, kind, trait_path,
617                     ),
618                     code,
619                 );
620                 err.span_label(span, "does not match trait");
621                 err.span_label(trait_item_span, "item in trait");
622                 err
623             }
624         }
625     }
626
627     crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
628         match vis_resolution_error {
629             VisResolutionError::Relative2018(span, path) => {
630                 let mut err = self.session.struct_span_err(
631                     span,
632                     "relative paths are not supported in visibilities on 2018 edition",
633                 );
634                 err.span_suggestion(
635                     path.span,
636                     "try",
637                     format!("crate::{}", pprust::path_to_string(&path)),
638                     Applicability::MaybeIncorrect,
639                 );
640                 err
641             }
642             VisResolutionError::AncestorOnly(span) => struct_span_err!(
643                 self.session,
644                 span,
645                 E0742,
646                 "visibilities can only be restricted to ancestor modules"
647             ),
648             VisResolutionError::FailedToResolve(span, label, suggestion) => {
649                 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
650             }
651             VisResolutionError::ExpectedFound(span, path_str, res) => {
652                 let mut err = struct_span_err!(
653                     self.session,
654                     span,
655                     E0577,
656                     "expected module, found {} `{}`",
657                     res.descr(),
658                     path_str
659                 );
660                 err.span_label(span, "not a module");
661                 err
662             }
663             VisResolutionError::Indeterminate(span) => struct_span_err!(
664                 self.session,
665                 span,
666                 E0578,
667                 "cannot determine resolution for the visibility"
668             ),
669             VisResolutionError::ModuleOnly(span) => {
670                 self.session.struct_span_err(span, "visibility must resolve to a module")
671             }
672         }
673         .emit()
674     }
675
676     /// Lookup typo candidate in scope for a macro or import.
677     fn early_lookup_typo_candidate(
678         &mut self,
679         scope_set: ScopeSet<'a>,
680         parent_scope: &ParentScope<'a>,
681         ident: Ident,
682         filter_fn: &impl Fn(Res) -> bool,
683     ) -> Option<TypoSuggestion> {
684         let mut suggestions = Vec::new();
685         let ctxt = ident.span.ctxt();
686         self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
687             match scope {
688                 Scope::DeriveHelpers(expn_id) => {
689                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
690                     if filter_fn(res) {
691                         suggestions.extend(
692                             this.helper_attrs
693                                 .get(&expn_id)
694                                 .into_iter()
695                                 .flatten()
696                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
697                         );
698                     }
699                 }
700                 Scope::DeriveHelpersCompat => {
701                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
702                     if filter_fn(res) {
703                         for derive in parent_scope.derives {
704                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
705                             if let Ok((Some(ext), _)) = this.resolve_macro_path(
706                                 derive,
707                                 Some(MacroKind::Derive),
708                                 parent_scope,
709                                 false,
710                                 false,
711                             ) {
712                                 suggestions.extend(
713                                     ext.helper_attrs
714                                         .iter()
715                                         .map(|name| TypoSuggestion::typo_from_res(*name, res)),
716                                 );
717                             }
718                         }
719                     }
720                 }
721                 Scope::MacroRules(macro_rules_scope) => {
722                     if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
723                         let res = macro_rules_binding.binding.res();
724                         if filter_fn(res) {
725                             suggestions.push(TypoSuggestion::typo_from_res(
726                                 macro_rules_binding.ident.name,
727                                 res,
728                             ))
729                         }
730                     }
731                 }
732                 Scope::CrateRoot => {
733                     let root_ident = Ident::new(kw::PathRoot, ident.span);
734                     let root_module = this.resolve_crate_root(root_ident);
735                     this.add_module_candidates(root_module, &mut suggestions, filter_fn);
736                 }
737                 Scope::Module(module, _) => {
738                     this.add_module_candidates(module, &mut suggestions, filter_fn);
739                 }
740                 Scope::RegisteredAttrs => {
741                     let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
742                     if filter_fn(res) {
743                         suggestions.extend(
744                             this.registered_attrs
745                                 .iter()
746                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
747                         );
748                     }
749                 }
750                 Scope::MacroUsePrelude => {
751                     suggestions.extend(this.macro_use_prelude.iter().filter_map(
752                         |(name, binding)| {
753                             let res = binding.res();
754                             filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
755                         },
756                     ));
757                 }
758                 Scope::BuiltinAttrs => {
759                     let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
760                     if filter_fn(res) {
761                         suggestions.extend(
762                             BUILTIN_ATTRIBUTES
763                                 .iter()
764                                 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
765                         );
766                     }
767                 }
768                 Scope::ExternPrelude => {
769                     suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
770                         let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
771                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
772                     }));
773                 }
774                 Scope::ToolPrelude => {
775                     let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
776                     suggestions.extend(
777                         this.registered_tools
778                             .iter()
779                             .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
780                     );
781                 }
782                 Scope::StdLibPrelude => {
783                     if let Some(prelude) = this.prelude {
784                         let mut tmp_suggestions = Vec::new();
785                         this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
786                         suggestions.extend(
787                             tmp_suggestions
788                                 .into_iter()
789                                 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
790                         );
791                     }
792                 }
793                 Scope::BuiltinTypes => {
794                     suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
795                         let res = Res::PrimTy(*prim_ty);
796                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
797                     }))
798                 }
799             }
800
801             None::<()>
802         });
803
804         // Make sure error reporting is deterministic.
805         suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
806
807         match find_best_match_for_name(
808             &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
809             ident.name,
810             None,
811         ) {
812             Some(found) if found != ident.name => {
813                 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
814             }
815             _ => None,
816         }
817     }
818
819     fn lookup_import_candidates_from_module<FilterFn>(
820         &mut self,
821         lookup_ident: Ident,
822         namespace: Namespace,
823         parent_scope: &ParentScope<'a>,
824         start_module: Module<'a>,
825         crate_name: Ident,
826         filter_fn: FilterFn,
827     ) -> Vec<ImportSuggestion>
828     where
829         FilterFn: Fn(Res) -> bool,
830     {
831         let mut candidates = Vec::new();
832         let mut seen_modules = FxHashSet::default();
833         let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
834         let mut worklist_via_import = vec![];
835
836         while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
837             None => worklist_via_import.pop(),
838             Some(x) => Some(x),
839         } {
840             let in_module_is_extern = !in_module.def_id().is_local();
841             // We have to visit module children in deterministic order to avoid
842             // instabilities in reported imports (#43552).
843             in_module.for_each_child(self, |this, ident, ns, name_binding| {
844                 // avoid non-importable candidates
845                 if !name_binding.is_importable() {
846                     return;
847                 }
848
849                 let child_accessible =
850                     accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
851
852                 // do not venture inside inaccessible items of other crates
853                 if in_module_is_extern && !child_accessible {
854                     return;
855                 }
856
857                 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
858
859                 // There is an assumption elsewhere that paths of variants are in the enum's
860                 // declaration and not imported. With this assumption, the variant component is
861                 // chopped and the rest of the path is assumed to be the enum's own path. For
862                 // errors where a variant is used as the type instead of the enum, this causes
863                 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
864                 if via_import && name_binding.is_possibly_imported_variant() {
865                     return;
866                 }
867
868                 // #90113: Do not count an inaccessible reexported item as a candidate.
869                 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
870                     if this.is_accessible_from(binding.vis, parent_scope.module)
871                         && !this.is_accessible_from(name_binding.vis, parent_scope.module)
872                     {
873                         return;
874                     }
875                 }
876
877                 // collect results based on the filter function
878                 // avoid suggesting anything from the same module in which we are resolving
879                 // avoid suggesting anything with a hygienic name
880                 if ident.name == lookup_ident.name
881                     && ns == namespace
882                     && !ptr::eq(in_module, parent_scope.module)
883                     && !ident.span.normalize_to_macros_2_0().from_expansion()
884                 {
885                     let res = name_binding.res();
886                     if filter_fn(res) {
887                         // create the path
888                         let mut segms = path_segments.clone();
889                         if lookup_ident.span.rust_2018() {
890                             // crate-local absolute paths start with `crate::` in edition 2018
891                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
892                             segms.insert(0, ast::PathSegment::from_ident(crate_name));
893                         }
894
895                         segms.push(ast::PathSegment::from_ident(ident));
896                         let path = Path { span: name_binding.span, segments: segms, tokens: None };
897                         let did = match res {
898                             Res::Def(DefKind::Ctor(..), did) => this.parent(did),
899                             _ => res.opt_def_id(),
900                         };
901
902                         if child_accessible {
903                             // Remove invisible match if exists
904                             if let Some(idx) = candidates
905                                 .iter()
906                                 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
907                             {
908                                 candidates.remove(idx);
909                             }
910                         }
911
912                         if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
913                             // See if we're recommending TryFrom, TryInto, or FromIterator and add
914                             // a note about editions
915                             let note = if let Some(did) = did {
916                                 let requires_note = !did.is_local()
917                                     && this.cstore().item_attrs_untracked(did, this.session).any(
918                                         |attr| {
919                                             if attr.has_name(sym::rustc_diagnostic_item) {
920                                                 [sym::TryInto, sym::TryFrom, sym::FromIterator]
921                                                     .map(|x| Some(x))
922                                                     .contains(&attr.value_str())
923                                             } else {
924                                                 false
925                                             }
926                                         },
927                                     );
928
929                                 requires_note.then(|| {
930                                     format!(
931                                         "'{}' is included in the prelude starting in Edition 2021",
932                                         path_names_to_string(&path)
933                                     )
934                                 })
935                             } else {
936                                 None
937                             };
938
939                             candidates.push(ImportSuggestion {
940                                 did,
941                                 descr: res.descr(),
942                                 path,
943                                 accessible: child_accessible,
944                                 note,
945                             });
946                         }
947                     }
948                 }
949
950                 // collect submodules to explore
951                 if let Some(module) = name_binding.module() {
952                     // form the path
953                     let mut path_segments = path_segments.clone();
954                     path_segments.push(ast::PathSegment::from_ident(ident));
955
956                     let is_extern_crate_that_also_appears_in_prelude =
957                         name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
958
959                     if !is_extern_crate_that_also_appears_in_prelude {
960                         // add the module to the lookup
961                         if seen_modules.insert(module.def_id()) {
962                             if via_import { &mut worklist_via_import } else { &mut worklist }
963                                 .push((module, path_segments, child_accessible));
964                         }
965                     }
966                 }
967             })
968         }
969
970         // If only some candidates are accessible, take just them
971         if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
972             candidates = candidates.into_iter().filter(|x| x.accessible).collect();
973         }
974
975         candidates
976     }
977
978     /// When name resolution fails, this method can be used to look up candidate
979     /// entities with the expected name. It allows filtering them using the
980     /// supplied predicate (which should be used to only accept the types of
981     /// definitions expected, e.g., traits). The lookup spans across all crates.
982     ///
983     /// N.B., the method does not look into imports, but this is not a problem,
984     /// since we report the definitions (thus, the de-aliased imports).
985     crate fn lookup_import_candidates<FilterFn>(
986         &mut self,
987         lookup_ident: Ident,
988         namespace: Namespace,
989         parent_scope: &ParentScope<'a>,
990         filter_fn: FilterFn,
991     ) -> Vec<ImportSuggestion>
992     where
993         FilterFn: Fn(Res) -> bool,
994     {
995         let mut suggestions = self.lookup_import_candidates_from_module(
996             lookup_ident,
997             namespace,
998             parent_scope,
999             self.graph_root,
1000             Ident::with_dummy_span(kw::Crate),
1001             &filter_fn,
1002         );
1003
1004         if lookup_ident.span.rust_2018() {
1005             let extern_prelude_names = self.extern_prelude.clone();
1006             for (ident, _) in extern_prelude_names.into_iter() {
1007                 if ident.span.from_expansion() {
1008                     // Idents are adjusted to the root context before being
1009                     // resolved in the extern prelude, so reporting this to the
1010                     // user is no help. This skips the injected
1011                     // `extern crate std` in the 2018 edition, which would
1012                     // otherwise cause duplicate suggestions.
1013                     continue;
1014                 }
1015                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1016                     let crate_root = self.expect_module(crate_id.as_def_id());
1017                     suggestions.extend(self.lookup_import_candidates_from_module(
1018                         lookup_ident,
1019                         namespace,
1020                         parent_scope,
1021                         crate_root,
1022                         ident,
1023                         &filter_fn,
1024                     ));
1025                 }
1026             }
1027         }
1028
1029         suggestions
1030     }
1031
1032     crate fn unresolved_macro_suggestions(
1033         &mut self,
1034         err: &mut DiagnosticBuilder<'a>,
1035         macro_kind: MacroKind,
1036         parent_scope: &ParentScope<'a>,
1037         ident: Ident,
1038     ) {
1039         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1040         let suggestion = self.early_lookup_typo_candidate(
1041             ScopeSet::Macro(macro_kind),
1042             parent_scope,
1043             ident,
1044             is_expected,
1045         );
1046         self.add_typo_suggestion(err, suggestion, ident.span);
1047
1048         let import_suggestions =
1049             self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1050         show_candidates(
1051             &self.definitions,
1052             self.session,
1053             err,
1054             None,
1055             &import_suggestions,
1056             false,
1057             true,
1058         );
1059
1060         if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1061             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1062             err.span_note(ident.span, &msg);
1063             return;
1064         }
1065         if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1066             err.help("have you added the `#[macro_use]` on the module/import?");
1067             return;
1068         }
1069         for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1070             if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1071                 ident,
1072                 ScopeSet::All(ns, false),
1073                 &parent_scope,
1074                 false,
1075                 false,
1076                 ident.span,
1077             ) {
1078                 let desc = match binding.res() {
1079                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1080                         "a function-like macro".to_string()
1081                     }
1082                     Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1083                         format!("an attribute: `#[{}]`", ident)
1084                     }
1085                     Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1086                         format!("a derive macro: `#[derive({})]`", ident)
1087                     }
1088                     Res::ToolMod => {
1089                         // Don't confuse the user with tool modules.
1090                         continue;
1091                     }
1092                     Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1093                         "only a trait, without a derive macro".to_string()
1094                     }
1095                     res => format!(
1096                         "{} {}, not {} {}",
1097                         res.article(),
1098                         res.descr(),
1099                         macro_kind.article(),
1100                         macro_kind.descr_expected(),
1101                     ),
1102                 };
1103                 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1104                     if !import.span.is_dummy() {
1105                         err.span_note(
1106                             import.span,
1107                             &format!("`{}` is imported here, but it is {}", ident, desc),
1108                         );
1109                         // Silence the 'unused import' warning we might get,
1110                         // since this diagnostic already covers that import.
1111                         self.record_use(ident, binding, false);
1112                         return;
1113                     }
1114                 }
1115                 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1116                 return;
1117             }
1118         }
1119     }
1120
1121     crate fn add_typo_suggestion(
1122         &self,
1123         err: &mut DiagnosticBuilder<'_>,
1124         suggestion: Option<TypoSuggestion>,
1125         span: Span,
1126     ) -> bool {
1127         let suggestion = match suggestion {
1128             None => return false,
1129             // We shouldn't suggest underscore.
1130             Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1131             Some(suggestion) => suggestion,
1132         };
1133         let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1134             LOCAL_CRATE => self.opt_span(def_id),
1135             _ => Some(
1136                 self.session
1137                     .source_map()
1138                     .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1139             ),
1140         });
1141         if let Some(def_span) = def_span {
1142             if span.overlaps(def_span) {
1143                 // Don't suggest typo suggestion for itself like in the following:
1144                 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1145                 //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1146                 //    |
1147                 // LL | struct X {}
1148                 //    | ----------- `X` defined here
1149                 // LL |
1150                 // LL | const Y: X = X("ö");
1151                 //    | -------------^^^^^^- similarly named constant `Y` defined here
1152                 //    |
1153                 // help: use struct literal syntax instead
1154                 //    |
1155                 // LL | const Y: X = X {};
1156                 //    |              ^^^^
1157                 // help: a constant with a similar name exists
1158                 //    |
1159                 // LL | const Y: X = Y("ö");
1160                 //    |              ^
1161                 return false;
1162             }
1163             let prefix = match suggestion.target {
1164                 SuggestionTarget::SimilarlyNamed => "similarly named ",
1165                 SuggestionTarget::SingleItem => "",
1166             };
1167
1168             err.span_label(
1169                 self.session.source_map().guess_head_span(def_span),
1170                 &format!(
1171                     "{}{} `{}` defined here",
1172                     prefix,
1173                     suggestion.res.descr(),
1174                     suggestion.candidate.as_str(),
1175                 ),
1176             );
1177         }
1178         let msg = match suggestion.target {
1179             SuggestionTarget::SimilarlyNamed => format!(
1180                 "{} {} with a similar name exists",
1181                 suggestion.res.article(),
1182                 suggestion.res.descr()
1183             ),
1184             SuggestionTarget::SingleItem => {
1185                 format!("maybe you meant this {}", suggestion.res.descr())
1186             }
1187         };
1188         err.span_suggestion(
1189             span,
1190             &msg,
1191             suggestion.candidate.to_string(),
1192             Applicability::MaybeIncorrect,
1193         );
1194         true
1195     }
1196
1197     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1198         let res = b.res();
1199         if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1200             // These already contain the "built-in" prefix or look bad with it.
1201             let add_built_in =
1202                 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1203             let (built_in, from) = if from_prelude {
1204                 ("", " from prelude")
1205             } else if b.is_extern_crate()
1206                 && !b.is_import()
1207                 && self.session.opts.externs.get(ident.as_str()).is_some()
1208             {
1209                 ("", " passed with `--extern`")
1210             } else if add_built_in {
1211                 (" built-in", "")
1212             } else {
1213                 ("", "")
1214             };
1215
1216             let a = if built_in.is_empty() { res.article() } else { "a" };
1217             format!("{a}{built_in} {thing}{from}", thing = res.descr())
1218         } else {
1219             let introduced = if b.is_import() { "imported" } else { "defined" };
1220             format!("the {thing} {introduced} here", thing = res.descr())
1221         }
1222     }
1223
1224     crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1225         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1226         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1227             // We have to print the span-less alternative first, otherwise formatting looks bad.
1228             (b2, b1, misc2, misc1, true)
1229         } else {
1230             (b1, b2, misc1, misc2, false)
1231         };
1232
1233         let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1234         err.span_label(ident.span, "ambiguous name");
1235         err.note(&format!("ambiguous because of {}", kind.descr()));
1236
1237         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1238             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1239             let note_msg = format!("`{ident}` could{also} refer to {what}");
1240
1241             let thing = b.res().descr();
1242             let mut help_msgs = Vec::new();
1243             if b.is_glob_import()
1244                 && (kind == AmbiguityKind::GlobVsGlob
1245                     || kind == AmbiguityKind::GlobVsExpanded
1246                     || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1247             {
1248                 help_msgs.push(format!(
1249                     "consider adding an explicit import of `{ident}` to disambiguate"
1250                 ))
1251             }
1252             if b.is_extern_crate() && ident.span.rust_2018() {
1253                 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1254             }
1255             if misc == AmbiguityErrorMisc::SuggestCrate {
1256                 help_msgs
1257                     .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1258             } else if misc == AmbiguityErrorMisc::SuggestSelf {
1259                 help_msgs
1260                     .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1261             }
1262
1263             err.span_note(b.span, &note_msg);
1264             for (i, help_msg) in help_msgs.iter().enumerate() {
1265                 let or = if i == 0 { "" } else { "or " };
1266                 err.help(&format!("{}{}", or, help_msg));
1267             }
1268         };
1269
1270         could_refer_to(b1, misc1, "");
1271         could_refer_to(b2, misc2, " also");
1272         err.emit();
1273     }
1274
1275     /// If the binding refers to a tuple struct constructor with fields,
1276     /// returns the span of its fields.
1277     fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1278         if let NameBindingKind::Res(
1279             Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1280             _,
1281         ) = binding.kind
1282         {
1283             let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1284             let fields = self.field_names.get(&def_id)?;
1285             return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1286         }
1287         None
1288     }
1289
1290     crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1291         let PrivacyError { ident, binding, .. } = *privacy_error;
1292
1293         let res = binding.res();
1294         let ctor_fields_span = self.ctor_fields_span(binding);
1295         let plain_descr = res.descr().to_string();
1296         let nonimport_descr =
1297             if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1298         let import_descr = nonimport_descr.clone() + " import";
1299         let get_descr =
1300             |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1301
1302         // Print the primary message.
1303         let descr = get_descr(binding);
1304         let mut err =
1305             struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1306         err.span_label(ident.span, &format!("private {}", descr));
1307         if let Some(span) = ctor_fields_span {
1308             err.span_label(span, "a constructor is private if any of the fields is private");
1309         }
1310
1311         // Print the whole import chain to make it easier to see what happens.
1312         let first_binding = binding;
1313         let mut next_binding = Some(binding);
1314         let mut next_ident = ident;
1315         while let Some(binding) = next_binding {
1316             let name = next_ident;
1317             next_binding = match binding.kind {
1318                 _ if res == Res::Err => None,
1319                 NameBindingKind::Import { binding, import, .. } => match import.kind {
1320                     _ if binding.span.is_dummy() => None,
1321                     ImportKind::Single { source, .. } => {
1322                         next_ident = source;
1323                         Some(binding)
1324                     }
1325                     ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1326                     ImportKind::ExternCrate { .. } => None,
1327                 },
1328                 _ => None,
1329             };
1330
1331             let first = ptr::eq(binding, first_binding);
1332             let msg = format!(
1333                 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1334                 and_refers_to = if first { "" } else { "...and refers to " },
1335                 item = get_descr(binding),
1336                 which = if first { "" } else { " which" },
1337                 dots = if next_binding.is_some() { "..." } else { "" },
1338             );
1339             let def_span = self.session.source_map().guess_head_span(binding.span);
1340             let mut note_span = MultiSpan::from_span(def_span);
1341             if !first && binding.vis.is_public() {
1342                 note_span.push_span_label(def_span, "consider importing it directly".into());
1343             }
1344             err.span_note(note_span, &msg);
1345         }
1346
1347         err.emit();
1348     }
1349
1350     crate fn find_similarly_named_module_or_crate(
1351         &mut self,
1352         ident: Symbol,
1353         current_module: &Module<'a>,
1354     ) -> Option<Symbol> {
1355         let mut candidates = self
1356             .extern_prelude
1357             .iter()
1358             .map(|(ident, _)| ident.name)
1359             .chain(
1360                 self.module_map
1361                     .iter()
1362                     .filter(|(_, module)| {
1363                         current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1364                     })
1365                     .map(|(_, module)| module.kind.name())
1366                     .flatten(),
1367             )
1368             .filter(|c| !c.to_string().is_empty())
1369             .collect::<Vec<_>>();
1370         candidates.sort();
1371         candidates.dedup();
1372         match find_best_match_for_name(&candidates, ident, None) {
1373             Some(sugg) if sugg == ident => None,
1374             sugg => sugg,
1375         }
1376     }
1377 }
1378
1379 impl<'a, 'b> ImportResolver<'a, 'b> {
1380     /// Adds suggestions for a path that cannot be resolved.
1381     pub(crate) fn make_path_suggestion(
1382         &mut self,
1383         span: Span,
1384         mut path: Vec<Segment>,
1385         parent_scope: &ParentScope<'b>,
1386     ) -> Option<(Vec<Segment>, Vec<String>)> {
1387         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1388
1389         match (path.get(0), path.get(1)) {
1390             // `{{root}}::ident::...` on both editions.
1391             // On 2015 `{{root}}` is usually added implicitly.
1392             (Some(fst), Some(snd))
1393                 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1394             // `ident::...` on 2018.
1395             (Some(fst), _)
1396                 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1397             {
1398                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1399                 path.insert(0, Segment::from_ident(Ident::empty()));
1400             }
1401             _ => return None,
1402         }
1403
1404         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1405             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1406             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1407             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1408     }
1409
1410     /// Suggest a missing `self::` if that resolves to an correct module.
1411     ///
1412     /// ```text
1413     ///    |
1414     /// LL | use foo::Bar;
1415     ///    |     ^^^ did you mean `self::foo`?
1416     /// ```
1417     fn make_missing_self_suggestion(
1418         &mut self,
1419         span: Span,
1420         mut path: Vec<Segment>,
1421         parent_scope: &ParentScope<'b>,
1422     ) -> Option<(Vec<Segment>, Vec<String>)> {
1423         // Replace first ident with `self` and check if that is valid.
1424         path[0].ident.name = kw::SelfLower;
1425         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1426         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1427         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1428     }
1429
1430     /// Suggests a missing `crate::` if that resolves to an correct module.
1431     ///
1432     /// ```text
1433     ///    |
1434     /// LL | use foo::Bar;
1435     ///    |     ^^^ did you mean `crate::foo`?
1436     /// ```
1437     fn make_missing_crate_suggestion(
1438         &mut self,
1439         span: Span,
1440         mut path: Vec<Segment>,
1441         parent_scope: &ParentScope<'b>,
1442     ) -> Option<(Vec<Segment>, Vec<String>)> {
1443         // Replace first ident with `crate` and check if that is valid.
1444         path[0].ident.name = kw::Crate;
1445         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1446         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
1447         if let PathResult::Module(..) = result {
1448             Some((
1449                 path,
1450                 vec![
1451                     "`use` statements changed in Rust 2018; read more at \
1452                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1453                      clarity.html>"
1454                         .to_string(),
1455                 ],
1456             ))
1457         } else {
1458             None
1459         }
1460     }
1461
1462     /// Suggests a missing `super::` if that resolves to an correct module.
1463     ///
1464     /// ```text
1465     ///    |
1466     /// LL | use foo::Bar;
1467     ///    |     ^^^ did you mean `super::foo`?
1468     /// ```
1469     fn make_missing_super_suggestion(
1470         &mut self,
1471         span: Span,
1472         mut path: Vec<Segment>,
1473         parent_scope: &ParentScope<'b>,
1474     ) -> Option<(Vec<Segment>, Vec<String>)> {
1475         // Replace first ident with `crate` and check if that is valid.
1476         path[0].ident.name = kw::Super;
1477         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1478         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
1479         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1480     }
1481
1482     /// Suggests a missing external crate name if that resolves to an correct module.
1483     ///
1484     /// ```text
1485     ///    |
1486     /// LL | use foobar::Baz;
1487     ///    |     ^^^^^^ did you mean `baz::foobar`?
1488     /// ```
1489     ///
1490     /// Used when importing a submodule of an external crate but missing that crate's
1491     /// name as the first part of path.
1492     fn make_external_crate_suggestion(
1493         &mut self,
1494         span: Span,
1495         mut path: Vec<Segment>,
1496         parent_scope: &ParentScope<'b>,
1497     ) -> Option<(Vec<Segment>, Vec<String>)> {
1498         if path[1].ident.span.rust_2015() {
1499             return None;
1500         }
1501
1502         // Sort extern crate names in *reverse* order to get
1503         // 1) some consistent ordering for emitted diagnostics, and
1504         // 2) `std` suggestions before `core` suggestions.
1505         let mut extern_crate_names =
1506             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1507         extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
1508
1509         for name in extern_crate_names.into_iter() {
1510             // Replace first ident with a crate name and check if that is valid.
1511             path[0].ident.name = name;
1512             let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1513             debug!(
1514                 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1515                 name, path, result
1516             );
1517             if let PathResult::Module(..) = result {
1518                 return Some((path, Vec::new()));
1519             }
1520         }
1521
1522         None
1523     }
1524
1525     /// Suggests importing a macro from the root of the crate rather than a module within
1526     /// the crate.
1527     ///
1528     /// ```text
1529     /// help: a macro with this name exists at the root of the crate
1530     ///    |
1531     /// LL | use issue_59764::makro;
1532     ///    |     ^^^^^^^^^^^^^^^^^^
1533     ///    |
1534     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
1535     ///            at the root of the crate instead of the module where it is defined
1536     /// ```
1537     pub(crate) fn check_for_module_export_macro(
1538         &mut self,
1539         import: &'b Import<'b>,
1540         module: ModuleOrUniformRoot<'b>,
1541         ident: Ident,
1542     ) -> Option<(Option<Suggestion>, Vec<String>)> {
1543         let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1544             return None;
1545         };
1546
1547         while let Some(parent) = crate_module.parent {
1548             crate_module = parent;
1549         }
1550
1551         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1552             // Don't make a suggestion if the import was already from the root of the
1553             // crate.
1554             return None;
1555         }
1556
1557         let resolutions = self.r.resolutions(crate_module).borrow();
1558         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1559         let binding = resolution.borrow().binding()?;
1560         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1561             let module_name = crate_module.kind.name().unwrap();
1562             let import_snippet = match import.kind {
1563                 ImportKind::Single { source, target, .. } if source != target => {
1564                     format!("{} as {}", source, target)
1565                 }
1566                 _ => format!("{}", ident),
1567             };
1568
1569             let mut corrections: Vec<(Span, String)> = Vec::new();
1570             if !import.is_nested() {
1571                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1572                 // intermediate segments.
1573                 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1574             } else {
1575                 // Find the binding span (and any trailing commas and spaces).
1576                 //   ie. `use a::b::{c, d, e};`
1577                 //                      ^^^
1578                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1579                     self.r.session,
1580                     import.span,
1581                     import.use_span,
1582                 );
1583                 debug!(
1584                     "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1585                     found_closing_brace, binding_span
1586                 );
1587
1588                 let mut removal_span = binding_span;
1589                 if found_closing_brace {
1590                     // If the binding span ended with a closing brace, as in the below example:
1591                     //   ie. `use a::b::{c, d};`
1592                     //                      ^
1593                     // Then expand the span of characters to remove to include the previous
1594                     // binding's trailing comma.
1595                     //   ie. `use a::b::{c, d};`
1596                     //                    ^^^
1597                     if let Some(previous_span) =
1598                         extend_span_to_previous_binding(self.r.session, binding_span)
1599                     {
1600                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1601                         removal_span = removal_span.with_lo(previous_span.lo());
1602                     }
1603                 }
1604                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1605
1606                 // Remove the `removal_span`.
1607                 corrections.push((removal_span, "".to_string()));
1608
1609                 // Find the span after the crate name and if it has nested imports immediatately
1610                 // after the crate name already.
1611                 //   ie. `use a::b::{c, d};`
1612                 //               ^^^^^^^^^
1613                 //   or  `use a::{b, c, d}};`
1614                 //               ^^^^^^^^^^^
1615                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1616                     self.r.session,
1617                     module_name,
1618                     import.use_span,
1619                 );
1620                 debug!(
1621                     "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1622                     has_nested, after_crate_name
1623                 );
1624
1625                 let source_map = self.r.session.source_map();
1626
1627                 // Add the import to the start, with a `{` if required.
1628                 let start_point = source_map.start_point(after_crate_name);
1629                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1630                     corrections.push((
1631                         start_point,
1632                         if has_nested {
1633                             // In this case, `start_snippet` must equal '{'.
1634                             format!("{}{}, ", start_snippet, import_snippet)
1635                         } else {
1636                             // In this case, add a `{`, then the moved import, then whatever
1637                             // was there before.
1638                             format!("{{{}, {}", import_snippet, start_snippet)
1639                         },
1640                     ));
1641                 }
1642
1643                 // Add a `};` to the end if nested, matching the `{` added at the start.
1644                 if !has_nested {
1645                     corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1646                 }
1647             }
1648
1649             let suggestion = Some((
1650                 corrections,
1651                 String::from("a macro with this name exists at the root of the crate"),
1652                 Applicability::MaybeIncorrect,
1653             ));
1654             let note = vec![
1655                 "this could be because a macro annotated with `#[macro_export]` will be exported \
1656                  at the root of the crate instead of the module where it is defined"
1657                     .to_string(),
1658             ];
1659             Some((suggestion, note))
1660         } else {
1661             None
1662         }
1663     }
1664 }
1665
1666 /// Given a `binding_span` of a binding within a use statement:
1667 ///
1668 /// ```
1669 /// use foo::{a, b, c};
1670 ///              ^
1671 /// ```
1672 ///
1673 /// then return the span until the next binding or the end of the statement:
1674 ///
1675 /// ```
1676 /// use foo::{a, b, c};
1677 ///              ^^^
1678 /// ```
1679 pub(crate) fn find_span_of_binding_until_next_binding(
1680     sess: &Session,
1681     binding_span: Span,
1682     use_span: Span,
1683 ) -> (bool, Span) {
1684     let source_map = sess.source_map();
1685
1686     // Find the span of everything after the binding.
1687     //   ie. `a, e};` or `a};`
1688     let binding_until_end = binding_span.with_hi(use_span.hi());
1689
1690     // Find everything after the binding but not including the binding.
1691     //   ie. `, e};` or `};`
1692     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1693
1694     // Keep characters in the span until we encounter something that isn't a comma or
1695     // whitespace.
1696     //   ie. `, ` or ``.
1697     //
1698     // Also note whether a closing brace character was encountered. If there
1699     // was, then later go backwards to remove any trailing commas that are left.
1700     let mut found_closing_brace = false;
1701     let after_binding_until_next_binding =
1702         source_map.span_take_while(after_binding_until_end, |&ch| {
1703             if ch == '}' {
1704                 found_closing_brace = true;
1705             }
1706             ch == ' ' || ch == ','
1707         });
1708
1709     // Combine the two spans.
1710     //   ie. `a, ` or `a`.
1711     //
1712     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1713     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1714
1715     (found_closing_brace, span)
1716 }
1717
1718 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1719 /// binding.
1720 ///
1721 /// ```
1722 /// use foo::a::{a, b, c};
1723 ///               ^^--- binding span
1724 ///               |
1725 ///               returned span
1726 ///
1727 /// use foo::{a, b, c};
1728 ///           --- binding span
1729 /// ```
1730 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1731     let source_map = sess.source_map();
1732
1733     // `prev_source` will contain all of the source that came before the span.
1734     // Then split based on a command and take the first (ie. closest to our span)
1735     // snippet. In the example, this is a space.
1736     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1737
1738     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1739     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1740     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1741         return None;
1742     }
1743
1744     let prev_comma = prev_comma.first().unwrap();
1745     let prev_starting_brace = prev_starting_brace.first().unwrap();
1746
1747     // If the amount of source code before the comma is greater than
1748     // the amount of source code before the starting brace then we've only
1749     // got one item in the nested item (eg. `issue_52891::{self}`).
1750     if prev_comma.len() > prev_starting_brace.len() {
1751         return None;
1752     }
1753
1754     Some(binding_span.with_lo(BytePos(
1755         // Take away the number of bytes for the characters we've found and an
1756         // extra for the comma.
1757         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1758     )))
1759 }
1760
1761 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1762 /// it is a nested use tree.
1763 ///
1764 /// ```
1765 /// use foo::a::{b, c};
1766 ///          ^^^^^^^^^^ // false
1767 ///
1768 /// use foo::{a, b, c};
1769 ///          ^^^^^^^^^^ // true
1770 ///
1771 /// use foo::{a, b::{c, d}};
1772 ///          ^^^^^^^^^^^^^^^ // true
1773 /// ```
1774 fn find_span_immediately_after_crate_name(
1775     sess: &Session,
1776     module_name: Symbol,
1777     use_span: Span,
1778 ) -> (bool, Span) {
1779     debug!(
1780         "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1781         module_name, use_span
1782     );
1783     let source_map = sess.source_map();
1784
1785     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1786     let mut num_colons = 0;
1787     // Find second colon.. `use issue_59764:`
1788     let until_second_colon = source_map.span_take_while(use_span, |c| {
1789         if *c == ':' {
1790             num_colons += 1;
1791         }
1792         !matches!(c, ':' if num_colons == 2)
1793     });
1794     // Find everything after the second colon.. `foo::{baz, makro};`
1795     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1796
1797     let mut found_a_non_whitespace_character = false;
1798     // Find the first non-whitespace character in `from_second_colon`.. `f`
1799     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1800         if found_a_non_whitespace_character {
1801             return false;
1802         }
1803         if !c.is_whitespace() {
1804             found_a_non_whitespace_character = true;
1805         }
1806         true
1807     });
1808
1809     // Find the first `{` in from_second_colon.. `foo::{`
1810     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1811
1812     (next_left_bracket == after_second_colon, from_second_colon)
1813 }
1814
1815 /// When an entity with a given name is not available in scope, we search for
1816 /// entities with that name in all crates. This method allows outputting the
1817 /// results of this search in a programmer-friendly way
1818 crate fn show_candidates(
1819     definitions: &rustc_hir::definitions::Definitions,
1820     session: &Session,
1821     err: &mut DiagnosticBuilder<'_>,
1822     // This is `None` if all placement locations are inside expansions
1823     use_placement_span: Option<Span>,
1824     candidates: &[ImportSuggestion],
1825     instead: bool,
1826     found_use: bool,
1827 ) {
1828     if candidates.is_empty() {
1829         return;
1830     }
1831
1832     let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1833         Vec::new();
1834     let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1835         Vec::new();
1836
1837     candidates.iter().for_each(|c| {
1838         (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1839             .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
1840     });
1841
1842     // we want consistent results across executions, but candidates are produced
1843     // by iterating through a hash map, so make sure they are ordered:
1844     for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1845         path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1846         let core_path_strings =
1847             path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1848         path_strings.extend(core_path_strings);
1849         path_strings.dedup_by(|a, b| a.0 == b.0);
1850     }
1851
1852     if !accessible_path_strings.is_empty() {
1853         let (determiner, kind) = if accessible_path_strings.len() == 1 {
1854             ("this", accessible_path_strings[0].1)
1855         } else {
1856             ("one of these", "items")
1857         };
1858
1859         let instead = if instead { " instead" } else { "" };
1860         let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1861
1862         for note in accessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1863             err.note(note);
1864         }
1865
1866         if let Some(span) = use_placement_span {
1867             for candidate in &mut accessible_path_strings {
1868                 // produce an additional newline to separate the new use statement
1869                 // from the directly following item.
1870                 let additional_newline = if found_use { "" } else { "\n" };
1871                 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1872             }
1873
1874             err.span_suggestions(
1875                 span,
1876                 &msg,
1877                 accessible_path_strings.into_iter().map(|a| a.0),
1878                 Applicability::Unspecified,
1879             );
1880         } else {
1881             msg.push(':');
1882
1883             for candidate in accessible_path_strings {
1884                 msg.push('\n');
1885                 msg.push_str(&candidate.0);
1886             }
1887
1888             err.note(&msg);
1889         }
1890     } else {
1891         assert!(!inaccessible_path_strings.is_empty());
1892
1893         if inaccessible_path_strings.len() == 1 {
1894             let (name, descr, def_id, note) = &inaccessible_path_strings[0];
1895             let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1896
1897             if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1898                 let span = definitions.def_span(local_def_id);
1899                 let span = session.source_map().guess_head_span(span);
1900                 let mut multi_span = MultiSpan::from_span(span);
1901                 multi_span.push_span_label(span, "not accessible".to_string());
1902                 err.span_note(multi_span, &msg);
1903             } else {
1904                 err.note(&msg);
1905             }
1906             if let Some(note) = (*note).as_deref() {
1907                 err.note(note);
1908             }
1909         } else {
1910             let (_, descr_first, _, _) = &inaccessible_path_strings[0];
1911             let descr = if inaccessible_path_strings
1912                 .iter()
1913                 .skip(1)
1914                 .all(|(_, descr, _, _)| descr == descr_first)
1915             {
1916                 descr_first.to_string()
1917             } else {
1918                 "item".to_string()
1919             };
1920
1921             let mut msg = format!("these {}s exist but are inaccessible", descr);
1922             let mut has_colon = false;
1923
1924             let mut spans = Vec::new();
1925             for (name, _, def_id, _) in &inaccessible_path_strings {
1926                 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1927                     let span = definitions.def_span(local_def_id);
1928                     let span = session.source_map().guess_head_span(span);
1929                     spans.push((name, span));
1930                 } else {
1931                     if !has_colon {
1932                         msg.push(':');
1933                         has_colon = true;
1934                     }
1935                     msg.push('\n');
1936                     msg.push_str(name);
1937                 }
1938             }
1939
1940             let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1941             for (name, span) in spans {
1942                 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1943             }
1944
1945             for note in inaccessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1946                 err.note(note);
1947             }
1948
1949             err.span_note(multi_span, &msg);
1950         }
1951     }
1952 }