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