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