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