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