]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/diagnostics.rs
Auto merge of #90391 - camelid:crate-size, r=jyn514
[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                 // avoid suggesting anything with a hygienic name
846                 if ident.name == lookup_ident.name
847                     && ns == namespace
848                     && !ptr::eq(in_module, parent_scope.module)
849                     && !ident.span.normalize_to_macros_2_0().from_expansion()
850                 {
851                     let res = name_binding.res();
852                     if filter_fn(res) {
853                         // create the path
854                         let mut segms = path_segments.clone();
855                         if lookup_ident.span.rust_2018() {
856                             // crate-local absolute paths start with `crate::` in edition 2018
857                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
858                             segms.insert(0, ast::PathSegment::from_ident(crate_name));
859                         }
860
861                         segms.push(ast::PathSegment::from_ident(ident));
862                         let path = Path { span: name_binding.span, segments: segms, tokens: None };
863                         let did = match res {
864                             Res::Def(DefKind::Ctor(..), did) => this.parent(did),
865                             _ => res.opt_def_id(),
866                         };
867
868                         if child_accessible {
869                             // Remove invisible match if exists
870                             if let Some(idx) = candidates
871                                 .iter()
872                                 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
873                             {
874                                 candidates.remove(idx);
875                             }
876                         }
877
878                         if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
879                             // See if we're recommending TryFrom, TryInto, or FromIterator and add
880                             // a note about editions
881                             let note = if let Some(did) = did {
882                                 let requires_note = !did.is_local()
883                                     && this.cstore().item_attrs(did, this.session).iter().any(
884                                         |attr| {
885                                             if attr.has_name(sym::rustc_diagnostic_item) {
886                                                 [sym::TryInto, sym::TryFrom, sym::FromIterator]
887                                                     .map(|x| Some(x))
888                                                     .contains(&attr.value_str())
889                                             } else {
890                                                 false
891                                             }
892                                         },
893                                     );
894
895                                 requires_note.then(|| {
896                                     format!(
897                                         "'{}' is included in the prelude starting in Edition 2021",
898                                         path_names_to_string(&path)
899                                     )
900                                 })
901                             } else {
902                                 None
903                             };
904
905                             candidates.push(ImportSuggestion {
906                                 did,
907                                 descr: res.descr(),
908                                 path,
909                                 accessible: child_accessible,
910                                 note,
911                             });
912                         }
913                     }
914                 }
915
916                 // collect submodules to explore
917                 if let Some(module) = name_binding.module() {
918                     // form the path
919                     let mut path_segments = path_segments.clone();
920                     path_segments.push(ast::PathSegment::from_ident(ident));
921
922                     let is_extern_crate_that_also_appears_in_prelude =
923                         name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
924
925                     if !is_extern_crate_that_also_appears_in_prelude {
926                         // add the module to the lookup
927                         if seen_modules.insert(module.def_id()) {
928                             if via_import { &mut worklist_via_import } else { &mut worklist }
929                                 .push((module, path_segments, child_accessible));
930                         }
931                     }
932                 }
933             })
934         }
935
936         // If only some candidates are accessible, take just them
937         if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
938             candidates = candidates.into_iter().filter(|x| x.accessible).collect();
939         }
940
941         candidates
942     }
943
944     /// When name resolution fails, this method can be used to look up candidate
945     /// entities with the expected name. It allows filtering them using the
946     /// supplied predicate (which should be used to only accept the types of
947     /// definitions expected, e.g., traits). The lookup spans across all crates.
948     ///
949     /// N.B., the method does not look into imports, but this is not a problem,
950     /// since we report the definitions (thus, the de-aliased imports).
951     crate fn lookup_import_candidates<FilterFn>(
952         &mut self,
953         lookup_ident: Ident,
954         namespace: Namespace,
955         parent_scope: &ParentScope<'a>,
956         filter_fn: FilterFn,
957     ) -> Vec<ImportSuggestion>
958     where
959         FilterFn: Fn(Res) -> bool,
960     {
961         let mut suggestions = self.lookup_import_candidates_from_module(
962             lookup_ident,
963             namespace,
964             parent_scope,
965             self.graph_root,
966             Ident::with_dummy_span(kw::Crate),
967             &filter_fn,
968         );
969
970         if lookup_ident.span.rust_2018() {
971             let extern_prelude_names = self.extern_prelude.clone();
972             for (ident, _) in extern_prelude_names.into_iter() {
973                 if ident.span.from_expansion() {
974                     // Idents are adjusted to the root context before being
975                     // resolved in the extern prelude, so reporting this to the
976                     // user is no help. This skips the injected
977                     // `extern crate std` in the 2018 edition, which would
978                     // otherwise cause duplicate suggestions.
979                     continue;
980                 }
981                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
982                     let crate_root = self.expect_module(crate_id.as_def_id());
983                     suggestions.extend(self.lookup_import_candidates_from_module(
984                         lookup_ident,
985                         namespace,
986                         parent_scope,
987                         crate_root,
988                         ident,
989                         &filter_fn,
990                     ));
991                 }
992             }
993         }
994
995         suggestions
996     }
997
998     crate fn unresolved_macro_suggestions(
999         &mut self,
1000         err: &mut DiagnosticBuilder<'a>,
1001         macro_kind: MacroKind,
1002         parent_scope: &ParentScope<'a>,
1003         ident: Ident,
1004     ) {
1005         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1006         let suggestion = self.early_lookup_typo_candidate(
1007             ScopeSet::Macro(macro_kind),
1008             parent_scope,
1009             ident,
1010             is_expected,
1011         );
1012         self.add_typo_suggestion(err, suggestion, ident.span);
1013
1014         let import_suggestions =
1015             self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1016         show_candidates(
1017             &self.definitions,
1018             self.session,
1019             err,
1020             None,
1021             &import_suggestions,
1022             false,
1023             true,
1024         );
1025
1026         if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1027             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1028             err.span_note(ident.span, &msg);
1029             return;
1030         }
1031         if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1032             err.help("have you added the `#[macro_use]` on the module/import?");
1033             return;
1034         }
1035         for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1036             if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1037                 ident,
1038                 ScopeSet::All(ns, false),
1039                 &parent_scope,
1040                 false,
1041                 false,
1042                 ident.span,
1043             ) {
1044                 let desc = match binding.res() {
1045                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1046                         "a function-like macro".to_string()
1047                     }
1048                     Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1049                         format!("an attribute: `#[{}]`", ident)
1050                     }
1051                     Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1052                         format!("a derive macro: `#[derive({})]`", ident)
1053                     }
1054                     Res::ToolMod => {
1055                         // Don't confuse the user with tool modules.
1056                         continue;
1057                     }
1058                     Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1059                         "only a trait, without a derive macro".to_string()
1060                     }
1061                     res => format!(
1062                         "{} {}, not {} {}",
1063                         res.article(),
1064                         res.descr(),
1065                         macro_kind.article(),
1066                         macro_kind.descr_expected(),
1067                     ),
1068                 };
1069                 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1070                     if !import.span.is_dummy() {
1071                         err.span_note(
1072                             import.span,
1073                             &format!("`{}` is imported here, but it is {}", ident, desc),
1074                         );
1075                         // Silence the 'unused import' warning we might get,
1076                         // since this diagnostic already covers that import.
1077                         self.record_use(ident, binding, false);
1078                         return;
1079                     }
1080                 }
1081                 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1082                 return;
1083             }
1084         }
1085     }
1086
1087     crate fn add_typo_suggestion(
1088         &self,
1089         err: &mut DiagnosticBuilder<'_>,
1090         suggestion: Option<TypoSuggestion>,
1091         span: Span,
1092     ) -> bool {
1093         let suggestion = match suggestion {
1094             None => return false,
1095             // We shouldn't suggest underscore.
1096             Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1097             Some(suggestion) => suggestion,
1098         };
1099         let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1100             LOCAL_CRATE => self.opt_span(def_id),
1101             _ => Some(
1102                 self.session
1103                     .source_map()
1104                     .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1105             ),
1106         });
1107         if let Some(def_span) = def_span {
1108             if span.overlaps(def_span) {
1109                 // Don't suggest typo suggestion for itself like in the following:
1110                 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1111                 //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1112                 //    |
1113                 // LL | struct X {}
1114                 //    | ----------- `X` defined here
1115                 // LL |
1116                 // LL | const Y: X = X("ö");
1117                 //    | -------------^^^^^^- similarly named constant `Y` defined here
1118                 //    |
1119                 // help: use struct literal syntax instead
1120                 //    |
1121                 // LL | const Y: X = X {};
1122                 //    |              ^^^^
1123                 // help: a constant with a similar name exists
1124                 //    |
1125                 // LL | const Y: X = Y("ö");
1126                 //    |              ^
1127                 return false;
1128             }
1129             let prefix = match suggestion.target {
1130                 SuggestionTarget::SimilarlyNamed => "similarly named ",
1131                 SuggestionTarget::SingleItem => "",
1132             };
1133
1134             err.span_label(
1135                 self.session.source_map().guess_head_span(def_span),
1136                 &format!(
1137                     "{}{} `{}` defined here",
1138                     prefix,
1139                     suggestion.res.descr(),
1140                     suggestion.candidate.as_str(),
1141                 ),
1142             );
1143         }
1144         let msg = match suggestion.target {
1145             SuggestionTarget::SimilarlyNamed => format!(
1146                 "{} {} with a similar name exists",
1147                 suggestion.res.article(),
1148                 suggestion.res.descr()
1149             ),
1150             SuggestionTarget::SingleItem => {
1151                 format!("maybe you meant this {}", suggestion.res.descr())
1152             }
1153         };
1154         err.span_suggestion(
1155             span,
1156             &msg,
1157             suggestion.candidate.to_string(),
1158             Applicability::MaybeIncorrect,
1159         );
1160         true
1161     }
1162
1163     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1164         let res = b.res();
1165         if b.span.is_dummy() {
1166             // These already contain the "built-in" prefix or look bad with it.
1167             let add_built_in =
1168                 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1169             let (built_in, from) = if from_prelude {
1170                 ("", " from prelude")
1171             } else if b.is_extern_crate()
1172                 && !b.is_import()
1173                 && self.session.opts.externs.get(&ident.as_str()).is_some()
1174             {
1175                 ("", " passed with `--extern`")
1176             } else if add_built_in {
1177                 (" built-in", "")
1178             } else {
1179                 ("", "")
1180             };
1181
1182             let a = if built_in.is_empty() { res.article() } else { "a" };
1183             format!("{a}{built_in} {thing}{from}", thing = res.descr())
1184         } else {
1185             let introduced = if b.is_import() { "imported" } else { "defined" };
1186             format!("the {thing} {introduced} here", thing = res.descr())
1187         }
1188     }
1189
1190     crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1191         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1192         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1193             // We have to print the span-less alternative first, otherwise formatting looks bad.
1194             (b2, b1, misc2, misc1, true)
1195         } else {
1196             (b1, b2, misc1, misc2, false)
1197         };
1198
1199         let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1200         err.span_label(ident.span, "ambiguous name");
1201         err.note(&format!("ambiguous because of {}", kind.descr()));
1202
1203         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1204             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1205             let note_msg = format!("`{ident}` could{also} refer to {what}");
1206
1207             let thing = b.res().descr();
1208             let mut help_msgs = Vec::new();
1209             if b.is_glob_import()
1210                 && (kind == AmbiguityKind::GlobVsGlob
1211                     || kind == AmbiguityKind::GlobVsExpanded
1212                     || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1213             {
1214                 help_msgs.push(format!(
1215                     "consider adding an explicit import of `{ident}` to disambiguate"
1216                 ))
1217             }
1218             if b.is_extern_crate() && ident.span.rust_2018() {
1219                 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1220             }
1221             if misc == AmbiguityErrorMisc::SuggestCrate {
1222                 help_msgs
1223                     .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1224             } else if misc == AmbiguityErrorMisc::SuggestSelf {
1225                 help_msgs
1226                     .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1227             }
1228
1229             err.span_note(b.span, &note_msg);
1230             for (i, help_msg) in help_msgs.iter().enumerate() {
1231                 let or = if i == 0 { "" } else { "or " };
1232                 err.help(&format!("{}{}", or, help_msg));
1233             }
1234         };
1235
1236         could_refer_to(b1, misc1, "");
1237         could_refer_to(b2, misc2, " also");
1238         err.emit();
1239     }
1240
1241     /// If the binding refers to a tuple struct constructor with fields,
1242     /// returns the span of its fields.
1243     fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1244         if let NameBindingKind::Res(
1245             Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1246             _,
1247         ) = binding.kind
1248         {
1249             let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1250             let fields = self.field_names.get(&def_id)?;
1251             return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1252         }
1253         None
1254     }
1255
1256     crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1257         let PrivacyError { ident, binding, .. } = *privacy_error;
1258
1259         let res = binding.res();
1260         let ctor_fields_span = self.ctor_fields_span(binding);
1261         let plain_descr = res.descr().to_string();
1262         let nonimport_descr =
1263             if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1264         let import_descr = nonimport_descr.clone() + " import";
1265         let get_descr =
1266             |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1267
1268         // Print the primary message.
1269         let descr = get_descr(binding);
1270         let mut err =
1271             struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1272         err.span_label(ident.span, &format!("private {}", descr));
1273         if let Some(span) = ctor_fields_span {
1274             err.span_label(span, "a constructor is private if any of the fields is private");
1275         }
1276
1277         // Print the whole import chain to make it easier to see what happens.
1278         let first_binding = binding;
1279         let mut next_binding = Some(binding);
1280         let mut next_ident = ident;
1281         while let Some(binding) = next_binding {
1282             let name = next_ident;
1283             next_binding = match binding.kind {
1284                 _ if res == Res::Err => None,
1285                 NameBindingKind::Import { binding, import, .. } => match import.kind {
1286                     _ if binding.span.is_dummy() => None,
1287                     ImportKind::Single { source, .. } => {
1288                         next_ident = source;
1289                         Some(binding)
1290                     }
1291                     ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1292                     ImportKind::ExternCrate { .. } => None,
1293                 },
1294                 _ => None,
1295             };
1296
1297             let first = ptr::eq(binding, first_binding);
1298             let msg = format!(
1299                 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1300                 and_refers_to = if first { "" } else { "...and refers to " },
1301                 item = get_descr(binding),
1302                 which = if first { "" } else { " which" },
1303                 dots = if next_binding.is_some() { "..." } else { "" },
1304             );
1305             let def_span = self.session.source_map().guess_head_span(binding.span);
1306             let mut note_span = MultiSpan::from_span(def_span);
1307             if !first && binding.vis == ty::Visibility::Public {
1308                 note_span.push_span_label(def_span, "consider importing it directly".into());
1309             }
1310             err.span_note(note_span, &msg);
1311         }
1312
1313         err.emit();
1314     }
1315
1316     crate fn find_similarly_named_module_or_crate(
1317         &mut self,
1318         ident: Symbol,
1319         current_module: &Module<'a>,
1320     ) -> Option<Symbol> {
1321         let mut candidates = self
1322             .extern_prelude
1323             .iter()
1324             .map(|(ident, _)| ident.name)
1325             .chain(
1326                 self.module_map
1327                     .iter()
1328                     .filter(|(_, module)| {
1329                         current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1330                     })
1331                     .map(|(_, module)| module.kind.name())
1332                     .flatten(),
1333             )
1334             .filter(|c| !c.to_string().is_empty())
1335             .collect::<Vec<_>>();
1336         candidates.sort();
1337         candidates.dedup();
1338         match find_best_match_for_name(&candidates, ident, None) {
1339             Some(sugg) if sugg == ident => None,
1340             sugg => sugg,
1341         }
1342     }
1343 }
1344
1345 impl<'a, 'b> ImportResolver<'a, 'b> {
1346     /// Adds suggestions for a path that cannot be resolved.
1347     pub(crate) fn make_path_suggestion(
1348         &mut self,
1349         span: Span,
1350         mut path: Vec<Segment>,
1351         parent_scope: &ParentScope<'b>,
1352     ) -> Option<(Vec<Segment>, Vec<String>)> {
1353         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1354
1355         match (path.get(0), path.get(1)) {
1356             // `{{root}}::ident::...` on both editions.
1357             // On 2015 `{{root}}` is usually added implicitly.
1358             (Some(fst), Some(snd))
1359                 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1360             // `ident::...` on 2018.
1361             (Some(fst), _)
1362                 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1363             {
1364                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1365                 path.insert(0, Segment::from_ident(Ident::empty()));
1366             }
1367             _ => return None,
1368         }
1369
1370         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1371             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1372             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1373             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1374     }
1375
1376     /// Suggest a missing `self::` if that resolves to an correct module.
1377     ///
1378     /// ```text
1379     ///    |
1380     /// LL | use foo::Bar;
1381     ///    |     ^^^ did you mean `self::foo`?
1382     /// ```
1383     fn make_missing_self_suggestion(
1384         &mut self,
1385         span: Span,
1386         mut path: Vec<Segment>,
1387         parent_scope: &ParentScope<'b>,
1388     ) -> Option<(Vec<Segment>, Vec<String>)> {
1389         // Replace first ident with `self` and check if that is valid.
1390         path[0].ident.name = kw::SelfLower;
1391         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1392         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1393         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1394     }
1395
1396     /// Suggests a missing `crate::` if that resolves to an correct module.
1397     ///
1398     /// ```text
1399     ///    |
1400     /// LL | use foo::Bar;
1401     ///    |     ^^^ did you mean `crate::foo`?
1402     /// ```
1403     fn make_missing_crate_suggestion(
1404         &mut self,
1405         span: Span,
1406         mut path: Vec<Segment>,
1407         parent_scope: &ParentScope<'b>,
1408     ) -> Option<(Vec<Segment>, Vec<String>)> {
1409         // Replace first ident with `crate` and check if that is valid.
1410         path[0].ident.name = kw::Crate;
1411         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1412         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
1413         if let PathResult::Module(..) = result {
1414             Some((
1415                 path,
1416                 vec![
1417                     "`use` statements changed in Rust 2018; read more at \
1418                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1419                      clarity.html>"
1420                         .to_string(),
1421                 ],
1422             ))
1423         } else {
1424             None
1425         }
1426     }
1427
1428     /// Suggests a missing `super::` if that resolves to an correct module.
1429     ///
1430     /// ```text
1431     ///    |
1432     /// LL | use foo::Bar;
1433     ///    |     ^^^ did you mean `super::foo`?
1434     /// ```
1435     fn make_missing_super_suggestion(
1436         &mut self,
1437         span: Span,
1438         mut path: Vec<Segment>,
1439         parent_scope: &ParentScope<'b>,
1440     ) -> Option<(Vec<Segment>, Vec<String>)> {
1441         // Replace first ident with `crate` and check if that is valid.
1442         path[0].ident.name = kw::Super;
1443         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1444         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
1445         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1446     }
1447
1448     /// Suggests a missing external crate name if that resolves to an correct module.
1449     ///
1450     /// ```text
1451     ///    |
1452     /// LL | use foobar::Baz;
1453     ///    |     ^^^^^^ did you mean `baz::foobar`?
1454     /// ```
1455     ///
1456     /// Used when importing a submodule of an external crate but missing that crate's
1457     /// name as the first part of path.
1458     fn make_external_crate_suggestion(
1459         &mut self,
1460         span: Span,
1461         mut path: Vec<Segment>,
1462         parent_scope: &ParentScope<'b>,
1463     ) -> Option<(Vec<Segment>, Vec<String>)> {
1464         if path[1].ident.span.rust_2015() {
1465             return None;
1466         }
1467
1468         // Sort extern crate names in reverse order to get
1469         // 1) some consistent ordering for emitted diagnostics, and
1470         // 2) `std` suggestions before `core` suggestions.
1471         let mut extern_crate_names =
1472             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1473         extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1474
1475         for name in extern_crate_names.into_iter() {
1476             // Replace first ident with a crate name and check if that is valid.
1477             path[0].ident.name = name;
1478             let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1479             debug!(
1480                 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1481                 name, path, result
1482             );
1483             if let PathResult::Module(..) = result {
1484                 return Some((path, Vec::new()));
1485             }
1486         }
1487
1488         None
1489     }
1490
1491     /// Suggests importing a macro from the root of the crate rather than a module within
1492     /// the crate.
1493     ///
1494     /// ```text
1495     /// help: a macro with this name exists at the root of the crate
1496     ///    |
1497     /// LL | use issue_59764::makro;
1498     ///    |     ^^^^^^^^^^^^^^^^^^
1499     ///    |
1500     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
1501     ///            at the root of the crate instead of the module where it is defined
1502     /// ```
1503     pub(crate) fn check_for_module_export_macro(
1504         &mut self,
1505         import: &'b Import<'b>,
1506         module: ModuleOrUniformRoot<'b>,
1507         ident: Ident,
1508     ) -> Option<(Option<Suggestion>, Vec<String>)> {
1509         let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1510             return None;
1511         };
1512
1513         while let Some(parent) = crate_module.parent {
1514             crate_module = parent;
1515         }
1516
1517         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1518             // Don't make a suggestion if the import was already from the root of the
1519             // crate.
1520             return None;
1521         }
1522
1523         let resolutions = self.r.resolutions(crate_module).borrow();
1524         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1525         let binding = resolution.borrow().binding()?;
1526         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1527             let module_name = crate_module.kind.name().unwrap();
1528             let import_snippet = match import.kind {
1529                 ImportKind::Single { source, target, .. } if source != target => {
1530                     format!("{} as {}", source, target)
1531                 }
1532                 _ => format!("{}", ident),
1533             };
1534
1535             let mut corrections: Vec<(Span, String)> = Vec::new();
1536             if !import.is_nested() {
1537                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1538                 // intermediate segments.
1539                 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1540             } else {
1541                 // Find the binding span (and any trailing commas and spaces).
1542                 //   ie. `use a::b::{c, d, e};`
1543                 //                      ^^^
1544                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1545                     self.r.session,
1546                     import.span,
1547                     import.use_span,
1548                 );
1549                 debug!(
1550                     "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1551                     found_closing_brace, binding_span
1552                 );
1553
1554                 let mut removal_span = binding_span;
1555                 if found_closing_brace {
1556                     // If the binding span ended with a closing brace, as in the below example:
1557                     //   ie. `use a::b::{c, d};`
1558                     //                      ^
1559                     // Then expand the span of characters to remove to include the previous
1560                     // binding's trailing comma.
1561                     //   ie. `use a::b::{c, d};`
1562                     //                    ^^^
1563                     if let Some(previous_span) =
1564                         extend_span_to_previous_binding(self.r.session, binding_span)
1565                     {
1566                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1567                         removal_span = removal_span.with_lo(previous_span.lo());
1568                     }
1569                 }
1570                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1571
1572                 // Remove the `removal_span`.
1573                 corrections.push((removal_span, "".to_string()));
1574
1575                 // Find the span after the crate name and if it has nested imports immediatately
1576                 // after the crate name already.
1577                 //   ie. `use a::b::{c, d};`
1578                 //               ^^^^^^^^^
1579                 //   or  `use a::{b, c, d}};`
1580                 //               ^^^^^^^^^^^
1581                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1582                     self.r.session,
1583                     module_name,
1584                     import.use_span,
1585                 );
1586                 debug!(
1587                     "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1588                     has_nested, after_crate_name
1589                 );
1590
1591                 let source_map = self.r.session.source_map();
1592
1593                 // Add the import to the start, with a `{` if required.
1594                 let start_point = source_map.start_point(after_crate_name);
1595                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1596                     corrections.push((
1597                         start_point,
1598                         if has_nested {
1599                             // In this case, `start_snippet` must equal '{'.
1600                             format!("{}{}, ", start_snippet, import_snippet)
1601                         } else {
1602                             // In this case, add a `{`, then the moved import, then whatever
1603                             // was there before.
1604                             format!("{{{}, {}", import_snippet, start_snippet)
1605                         },
1606                     ));
1607                 }
1608
1609                 // Add a `};` to the end if nested, matching the `{` added at the start.
1610                 if !has_nested {
1611                     corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1612                 }
1613             }
1614
1615             let suggestion = Some((
1616                 corrections,
1617                 String::from("a macro with this name exists at the root of the crate"),
1618                 Applicability::MaybeIncorrect,
1619             ));
1620             let note = vec![
1621                 "this could be because a macro annotated with `#[macro_export]` will be exported \
1622                  at the root of the crate instead of the module where it is defined"
1623                     .to_string(),
1624             ];
1625             Some((suggestion, note))
1626         } else {
1627             None
1628         }
1629     }
1630 }
1631
1632 /// Given a `binding_span` of a binding within a use statement:
1633 ///
1634 /// ```
1635 /// use foo::{a, b, c};
1636 ///              ^
1637 /// ```
1638 ///
1639 /// then return the span until the next binding or the end of the statement:
1640 ///
1641 /// ```
1642 /// use foo::{a, b, c};
1643 ///              ^^^
1644 /// ```
1645 pub(crate) fn find_span_of_binding_until_next_binding(
1646     sess: &Session,
1647     binding_span: Span,
1648     use_span: Span,
1649 ) -> (bool, Span) {
1650     let source_map = sess.source_map();
1651
1652     // Find the span of everything after the binding.
1653     //   ie. `a, e};` or `a};`
1654     let binding_until_end = binding_span.with_hi(use_span.hi());
1655
1656     // Find everything after the binding but not including the binding.
1657     //   ie. `, e};` or `};`
1658     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1659
1660     // Keep characters in the span until we encounter something that isn't a comma or
1661     // whitespace.
1662     //   ie. `, ` or ``.
1663     //
1664     // Also note whether a closing brace character was encountered. If there
1665     // was, then later go backwards to remove any trailing commas that are left.
1666     let mut found_closing_brace = false;
1667     let after_binding_until_next_binding =
1668         source_map.span_take_while(after_binding_until_end, |&ch| {
1669             if ch == '}' {
1670                 found_closing_brace = true;
1671             }
1672             ch == ' ' || ch == ','
1673         });
1674
1675     // Combine the two spans.
1676     //   ie. `a, ` or `a`.
1677     //
1678     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1679     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1680
1681     (found_closing_brace, span)
1682 }
1683
1684 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1685 /// binding.
1686 ///
1687 /// ```
1688 /// use foo::a::{a, b, c};
1689 ///               ^^--- binding span
1690 ///               |
1691 ///               returned span
1692 ///
1693 /// use foo::{a, b, c};
1694 ///           --- binding span
1695 /// ```
1696 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1697     let source_map = sess.source_map();
1698
1699     // `prev_source` will contain all of the source that came before the span.
1700     // Then split based on a command and take the first (ie. closest to our span)
1701     // snippet. In the example, this is a space.
1702     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1703
1704     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1705     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1706     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1707         return None;
1708     }
1709
1710     let prev_comma = prev_comma.first().unwrap();
1711     let prev_starting_brace = prev_starting_brace.first().unwrap();
1712
1713     // If the amount of source code before the comma is greater than
1714     // the amount of source code before the starting brace then we've only
1715     // got one item in the nested item (eg. `issue_52891::{self}`).
1716     if prev_comma.len() > prev_starting_brace.len() {
1717         return None;
1718     }
1719
1720     Some(binding_span.with_lo(BytePos(
1721         // Take away the number of bytes for the characters we've found and an
1722         // extra for the comma.
1723         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1724     )))
1725 }
1726
1727 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1728 /// it is a nested use tree.
1729 ///
1730 /// ```
1731 /// use foo::a::{b, c};
1732 ///          ^^^^^^^^^^ // false
1733 ///
1734 /// use foo::{a, b, c};
1735 ///          ^^^^^^^^^^ // true
1736 ///
1737 /// use foo::{a, b::{c, d}};
1738 ///          ^^^^^^^^^^^^^^^ // true
1739 /// ```
1740 fn find_span_immediately_after_crate_name(
1741     sess: &Session,
1742     module_name: Symbol,
1743     use_span: Span,
1744 ) -> (bool, Span) {
1745     debug!(
1746         "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1747         module_name, use_span
1748     );
1749     let source_map = sess.source_map();
1750
1751     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1752     let mut num_colons = 0;
1753     // Find second colon.. `use issue_59764:`
1754     let until_second_colon = source_map.span_take_while(use_span, |c| {
1755         if *c == ':' {
1756             num_colons += 1;
1757         }
1758         !matches!(c, ':' if num_colons == 2)
1759     });
1760     // Find everything after the second colon.. `foo::{baz, makro};`
1761     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1762
1763     let mut found_a_non_whitespace_character = false;
1764     // Find the first non-whitespace character in `from_second_colon`.. `f`
1765     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1766         if found_a_non_whitespace_character {
1767             return false;
1768         }
1769         if !c.is_whitespace() {
1770             found_a_non_whitespace_character = true;
1771         }
1772         true
1773     });
1774
1775     // Find the first `{` in from_second_colon.. `foo::{`
1776     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1777
1778     (next_left_bracket == after_second_colon, from_second_colon)
1779 }
1780
1781 /// When an entity with a given name is not available in scope, we search for
1782 /// entities with that name in all crates. This method allows outputting the
1783 /// results of this search in a programmer-friendly way
1784 crate fn show_candidates(
1785     definitions: &rustc_hir::definitions::Definitions,
1786     session: &Session,
1787     err: &mut DiagnosticBuilder<'_>,
1788     // This is `None` if all placement locations are inside expansions
1789     use_placement_span: Option<Span>,
1790     candidates: &[ImportSuggestion],
1791     instead: bool,
1792     found_use: bool,
1793 ) {
1794     if candidates.is_empty() {
1795         return;
1796     }
1797
1798     let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1799         Vec::new();
1800     let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1801         Vec::new();
1802
1803     candidates.iter().for_each(|c| {
1804         (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1805             .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
1806     });
1807
1808     // we want consistent results across executions, but candidates are produced
1809     // by iterating through a hash map, so make sure they are ordered:
1810     for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1811         path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1812         let core_path_strings =
1813             path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1814         path_strings.extend(core_path_strings);
1815         path_strings.dedup_by(|a, b| a.0 == b.0);
1816     }
1817
1818     if !accessible_path_strings.is_empty() {
1819         let (determiner, kind) = if accessible_path_strings.len() == 1 {
1820             ("this", accessible_path_strings[0].1)
1821         } else {
1822             ("one of these", "items")
1823         };
1824
1825         let instead = if instead { " instead" } else { "" };
1826         let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1827
1828         for note in accessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1829             err.note(note);
1830         }
1831
1832         if let Some(span) = use_placement_span {
1833             for candidate in &mut accessible_path_strings {
1834                 // produce an additional newline to separate the new use statement
1835                 // from the directly following item.
1836                 let additional_newline = if found_use { "" } else { "\n" };
1837                 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1838             }
1839
1840             err.span_suggestions(
1841                 span,
1842                 &msg,
1843                 accessible_path_strings.into_iter().map(|a| a.0),
1844                 Applicability::Unspecified,
1845             );
1846         } else {
1847             msg.push(':');
1848
1849             for candidate in accessible_path_strings {
1850                 msg.push('\n');
1851                 msg.push_str(&candidate.0);
1852             }
1853
1854             err.note(&msg);
1855         }
1856     } else {
1857         assert!(!inaccessible_path_strings.is_empty());
1858
1859         if inaccessible_path_strings.len() == 1 {
1860             let (name, descr, def_id, note) = &inaccessible_path_strings[0];
1861             let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1862
1863             if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1864                 let span = definitions.def_span(local_def_id);
1865                 let span = session.source_map().guess_head_span(span);
1866                 let mut multi_span = MultiSpan::from_span(span);
1867                 multi_span.push_span_label(span, "not accessible".to_string());
1868                 err.span_note(multi_span, &msg);
1869             } else {
1870                 err.note(&msg);
1871             }
1872             if let Some(note) = (*note).as_deref() {
1873                 err.note(note);
1874             }
1875         } else {
1876             let (_, descr_first, _, _) = &inaccessible_path_strings[0];
1877             let descr = if inaccessible_path_strings
1878                 .iter()
1879                 .skip(1)
1880                 .all(|(_, descr, _, _)| descr == descr_first)
1881             {
1882                 descr_first.to_string()
1883             } else {
1884                 "item".to_string()
1885             };
1886
1887             let mut msg = format!("these {}s exist but are inaccessible", descr);
1888             let mut has_colon = false;
1889
1890             let mut spans = Vec::new();
1891             for (name, _, def_id, _) in &inaccessible_path_strings {
1892                 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1893                     let span = definitions.def_span(local_def_id);
1894                     let span = session.source_map().guess_head_span(span);
1895                     spans.push((name, span));
1896                 } else {
1897                     if !has_colon {
1898                         msg.push(':');
1899                         has_colon = true;
1900                     }
1901                     msg.push('\n');
1902                     msg.push_str(name);
1903                 }
1904             }
1905
1906             let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1907             for (name, span) in spans {
1908                 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1909             }
1910
1911             for note in inaccessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1912                 err.note(note);
1913             }
1914
1915             err.span_note(multi_span, &msg);
1916         }
1917     }
1918 }