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