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