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