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