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