]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late/diagnostics.rs
resolve: `lifetimes.rs` -> `late/lifetime.rs`
[rust.git] / src / librustc_resolve / late / diagnostics.rs
1 use crate::diagnostics::{ImportSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
7
8 use rustc::session::config::nightly_options;
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
11 use rustc_hir as hir;
12 use rustc_hir::def::Namespace::{self, *};
13 use rustc_hir::def::{self, CtorKind, DefKind};
14 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
15 use rustc_hir::PrimTy;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::{kw, sym};
18 use rustc_span::Span;
19 use syntax::ast::{self, Expr, ExprKind, Ident, Item, ItemKind, NodeId, Path, Ty, TyKind};
20 use syntax::util::lev_distance::find_best_match_for_name;
21
22 use log::debug;
23
24 type Res = def::Res<ast::NodeId>;
25
26 /// A field or associated item from self type suggested in case of resolution failure.
27 enum AssocSuggestion {
28     Field,
29     MethodWithSelf,
30     AssocItem,
31 }
32
33 crate enum MissingLifetimeSpot<'tcx> {
34     Generics(&'tcx hir::Generics<'tcx>),
35     HigherRanked { span: Span, span_type: ForLifetimeSpanType },
36 }
37
38 crate enum ForLifetimeSpanType {
39     BoundEmpty,
40     BoundTail,
41     TypeEmpty,
42     TypeTail,
43 }
44
45 impl ForLifetimeSpanType {
46     crate fn descr(&self) -> &'static str {
47         match self {
48             Self::BoundEmpty | Self::BoundTail => "bound",
49             Self::TypeEmpty | Self::TypeTail => "type",
50         }
51     }
52
53     crate fn suggestion(&self, sugg: &str) -> String {
54         match self {
55             Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
56             Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
57         }
58     }
59 }
60
61 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
62     fn into(self) -> MissingLifetimeSpot<'tcx> {
63         MissingLifetimeSpot::Generics(self)
64     }
65 }
66
67 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
68     namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
69 }
70
71 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
72     namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
73 }
74
75 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
76 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
77     let variant_path = &suggestion.path;
78     let variant_path_string = path_names_to_string(variant_path);
79
80     let path_len = suggestion.path.segments.len();
81     let enum_path = ast::Path {
82         span: suggestion.path.span,
83         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
84     };
85     let enum_path_string = path_names_to_string(&enum_path);
86
87     (variant_path_string, enum_path_string)
88 }
89
90 impl<'a> LateResolutionVisitor<'a, '_, '_> {
91     /// Handles error reporting for `smart_resolve_path_fragment` function.
92     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
93     pub(crate) fn smart_resolve_report_errors(
94         &mut self,
95         path: &[Segment],
96         span: Span,
97         source: PathSource<'_>,
98         res: Option<Res>,
99     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
100         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
101         let ns = source.namespace();
102         let is_expected = &|res| source.is_expected(res);
103         let is_enum_variant = &|res| {
104             if let Res::Def(DefKind::Variant, _) = res { true } else { false }
105         };
106
107         // Make the base error.
108         let expected = source.descr_expected();
109         let path_str = Segment::names_to_string(path);
110         let item_str = path.last().unwrap().ident;
111         let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
112             (
113                 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
114                 format!("not a {}", expected),
115                 span,
116                 match res {
117                     Res::Def(DefKind::Fn, _) => {
118                         // Verify whether this is a fn call or an Fn used as a type.
119                         self.r
120                             .session
121                             .source_map()
122                             .span_to_snippet(span)
123                             .map(|snippet| snippet.ends_with(')'))
124                             .unwrap_or(false)
125                     }
126                     Res::Def(DefKind::Ctor(..), _)
127                     | Res::Def(DefKind::Method, _)
128                     | Res::Def(DefKind::Const, _)
129                     | Res::Def(DefKind::AssocConst, _)
130                     | Res::SelfCtor(_)
131                     | Res::PrimTy(_)
132                     | Res::Local(_) => true,
133                     _ => false,
134                 },
135             )
136         } else {
137             let item_span = path.last().unwrap().ident.span;
138             let (mod_prefix, mod_str) = if path.len() == 1 {
139                 (String::new(), "this scope".to_string())
140             } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
141                 (String::new(), "the crate root".to_string())
142             } else {
143                 let mod_path = &path[..path.len() - 1];
144                 let mod_prefix =
145                     match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
146                         PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
147                         _ => None,
148                     }
149                     .map_or(String::new(), |res| format!("{} ", res.descr()));
150                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
151             };
152             (
153                 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
154                 format!("not found in {}", mod_str),
155                 item_span,
156                 false,
157             )
158         };
159
160         let code = source.error_code(res.is_some());
161         let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
162
163         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
164         if ["this", "my"].contains(&&*item_str.as_str())
165             && self.self_value_is_available(path[0].ident.span, span)
166         {
167             err.span_suggestion(
168                 span,
169                 "did you mean",
170                 "self".to_string(),
171                 Applicability::MaybeIncorrect,
172             );
173         }
174
175         // Emit special messages for unresolved `Self` and `self`.
176         if is_self_type(path, ns) {
177             err.code(rustc_errors::error_code!(E0411));
178             err.span_label(
179                 span,
180                 format!("`Self` is only available in impls, traits, and type definitions"),
181             );
182             return (err, Vec::new());
183         }
184         if is_self_value(path, ns) {
185             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
186
187             err.code(rustc_errors::error_code!(E0424));
188             err.span_label(span, match source {
189                 PathSource::Pat => format!(
190                     "`self` value is a keyword and may not be bound to variables or shadowed",
191                 ),
192                 _ => format!(
193                     "`self` value is a keyword only available in methods with a `self` parameter",
194                 ),
195             });
196             if let Some(span) = &self.diagnostic_metadata.current_function {
197                 err.span_label(*span, "this function doesn't have a `self` parameter");
198             }
199             return (err, Vec::new());
200         }
201
202         // Try to lookup name in more relaxed fashion for better error reporting.
203         let ident = path.last().unwrap().ident;
204         let candidates = self
205             .r
206             .lookup_import_candidates(ident, ns, is_expected)
207             .drain(..)
208             .filter(|ImportSuggestion { did, .. }| {
209                 match (did, res.and_then(|res| res.opt_def_id())) {
210                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
211                     _ => true,
212                 }
213             })
214             .collect::<Vec<_>>();
215         let crate_def_id = DefId::local(CRATE_DEF_INDEX);
216         if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
217             let enum_candidates = self.r.lookup_import_candidates(ident, ns, is_enum_variant);
218             let mut enum_candidates = enum_candidates
219                 .iter()
220                 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
221                 .collect::<Vec<_>>();
222             enum_candidates.sort();
223
224             if !enum_candidates.is_empty() {
225                 // Contextualize for E0412 "cannot find type", but don't belabor the point
226                 // (that it's a variant) for E0573 "expected type, found variant".
227                 let preamble = if res.is_none() {
228                     let others = match enum_candidates.len() {
229                         1 => String::new(),
230                         2 => " and 1 other".to_owned(),
231                         n => format!(" and {} others", n),
232                     };
233                     format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
234                 } else {
235                     String::new()
236                 };
237                 let msg = format!("{}try using the variant's enum", preamble);
238
239                 err.span_suggestions(
240                     span,
241                     &msg,
242                     enum_candidates
243                         .into_iter()
244                         .map(|(_variant_path, enum_ty_path)| enum_ty_path)
245                         // Variants re-exported in prelude doesn't mean `prelude::v1` is the
246                         // type name!
247                         // FIXME: is there a more principled way to do this that
248                         // would work for other re-exports?
249                         .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
250                         // Also write `Option` rather than `std::prelude::v1::Option`.
251                         .map(|enum_ty_path| {
252                             // FIXME #56861: DRY-er prelude filtering.
253                             enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
254                         }),
255                     Applicability::MachineApplicable,
256                 );
257             }
258         }
259         if path.len() == 1 && self.self_type_is_available(span) {
260             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
261                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
262                 match candidate {
263                     AssocSuggestion::Field => {
264                         if self_is_available {
265                             err.span_suggestion(
266                                 span,
267                                 "you might have meant to use the available field",
268                                 format!("self.{}", path_str),
269                                 Applicability::MachineApplicable,
270                             );
271                         } else {
272                             err.span_label(span, "a field by this name exists in `Self`");
273                         }
274                     }
275                     AssocSuggestion::MethodWithSelf if self_is_available => {
276                         err.span_suggestion(
277                             span,
278                             "try",
279                             format!("self.{}", path_str),
280                             Applicability::MachineApplicable,
281                         );
282                     }
283                     AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
284                         err.span_suggestion(
285                             span,
286                             "try",
287                             format!("Self::{}", path_str),
288                             Applicability::MachineApplicable,
289                         );
290                     }
291                 }
292                 return (err, candidates);
293             }
294
295             // If the first argument in call is `self` suggest calling a method.
296             if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
297                 let mut args_snippet = String::new();
298                 if let Some(args_span) = args_span {
299                     if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
300                         args_snippet = snippet;
301                     }
302                 }
303
304                 err.span_suggestion(
305                     call_span,
306                     &format!("try calling `{}` as a method", ident),
307                     format!("self.{}({})", path_str, args_snippet),
308                     Applicability::MachineApplicable,
309                 );
310                 return (err, candidates);
311             }
312         }
313
314         // Try Levenshtein algorithm.
315         let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
316         let levenshtein_worked = self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
317
318         // Try context-dependent help if relaxed lookup didn't work.
319         if let Some(res) = res {
320             if self.smart_resolve_context_dependent_help(
321                 &mut err,
322                 span,
323                 source,
324                 res,
325                 &path_str,
326                 &fallback_label,
327             ) {
328                 return (err, candidates);
329             }
330         }
331
332         // Fallback label.
333         if !levenshtein_worked {
334             err.span_label(base_span, fallback_label);
335             self.type_ascription_suggestion(&mut err, base_span);
336             match self.diagnostic_metadata.current_let_binding {
337                 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
338                     err.span_suggestion_short(
339                         pat_sp.between(ty_sp),
340                         "use `=` if you meant to assign",
341                         " = ".to_string(),
342                         Applicability::MaybeIncorrect,
343                     );
344                 }
345                 _ => {}
346             }
347         }
348         (err, candidates)
349     }
350
351     /// Check if the source is call expression and the first argument is `self`. If true,
352     /// return the span of whole call and the span for all arguments expect the first one (`self`).
353     fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
354         let mut has_self_arg = None;
355         if let PathSource::Expr(parent) = source {
356             match &parent?.kind {
357                 ExprKind::Call(_, args) if args.len() > 0 => {
358                     let mut expr_kind = &args[0].kind;
359                     loop {
360                         match expr_kind {
361                             ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
362                                 if arg_name.segments[0].ident.name == kw::SelfLower {
363                                     let call_span = parent.unwrap().span;
364                                     let tail_args_span = if args.len() > 1 {
365                                         Some(Span::new(
366                                             args[1].span.lo(),
367                                             args.last().unwrap().span.hi(),
368                                             call_span.ctxt(),
369                                         ))
370                                     } else {
371                                         None
372                                     };
373                                     has_self_arg = Some((call_span, tail_args_span));
374                                 }
375                                 break;
376                             }
377                             ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
378                             _ => break,
379                         }
380                     }
381                 }
382                 _ => (),
383             }
384         };
385         return has_self_arg;
386     }
387
388     fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
389         // HACK(estebank): find a better way to figure out that this was a
390         // parser issue where a struct literal is being used on an expression
391         // where a brace being opened means a block is being started. Look
392         // ahead for the next text to see if `span` is followed by a `{`.
393         let sm = self.r.session.source_map();
394         let mut sp = span;
395         loop {
396             sp = sm.next_point(sp);
397             match sm.span_to_snippet(sp) {
398                 Ok(ref snippet) => {
399                     if snippet.chars().any(|c| !c.is_whitespace()) {
400                         break;
401                     }
402                 }
403                 _ => break,
404             }
405         }
406         let followed_by_brace = match sm.span_to_snippet(sp) {
407             Ok(ref snippet) if snippet == "{" => true,
408             _ => false,
409         };
410         // In case this could be a struct literal that needs to be surrounded
411         // by parenthesis, find the appropriate span.
412         let mut i = 0;
413         let mut closing_brace = None;
414         loop {
415             sp = sm.next_point(sp);
416             match sm.span_to_snippet(sp) {
417                 Ok(ref snippet) => {
418                     if snippet == "}" {
419                         let sp = span.to(sp);
420                         if let Ok(snippet) = sm.span_to_snippet(sp) {
421                             closing_brace = Some((sp, snippet));
422                         }
423                         break;
424                     }
425                 }
426                 _ => break,
427             }
428             i += 1;
429             // The bigger the span, the more likely we're incorrect --
430             // bound it to 100 chars long.
431             if i > 100 {
432                 break;
433             }
434         }
435         return (followed_by_brace, closing_brace);
436     }
437
438     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
439     /// function.
440     /// Returns `true` if able to provide context-dependent help.
441     fn smart_resolve_context_dependent_help(
442         &mut self,
443         err: &mut DiagnosticBuilder<'a>,
444         span: Span,
445         source: PathSource<'_>,
446         res: Res,
447         path_str: &str,
448         fallback_label: &str,
449     ) -> bool {
450         let ns = source.namespace();
451         let is_expected = &|res| source.is_expected(res);
452
453         let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
454             ExprKind::Field(_, ident) => {
455                 err.span_suggestion(
456                     expr.span,
457                     "use the path separator to refer to an item",
458                     format!("{}::{}", path_str, ident),
459                     Applicability::MaybeIncorrect,
460                 );
461                 true
462             }
463             ExprKind::MethodCall(ref segment, ..) => {
464                 let span = expr.span.with_hi(segment.ident.span.hi());
465                 err.span_suggestion(
466                     span,
467                     "use the path separator to refer to an item",
468                     format!("{}::{}", path_str, segment.ident),
469                     Applicability::MaybeIncorrect,
470                 );
471                 true
472             }
473             _ => false,
474         };
475
476         let mut bad_struct_syntax_suggestion = |def_id: DefId| {
477             let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
478             let mut suggested = false;
479             match source {
480                 PathSource::Expr(Some(parent)) => {
481                     suggested = path_sep(err, &parent);
482                 }
483                 PathSource::Expr(None) if followed_by_brace == true => {
484                     if let Some((sp, snippet)) = closing_brace {
485                         err.span_suggestion(
486                             sp,
487                             "surround the struct literal with parenthesis",
488                             format!("({})", snippet),
489                             Applicability::MaybeIncorrect,
490                         );
491                     } else {
492                         err.span_label(
493                             span, // Note the parenthesis surrounding the suggestion below
494                             format!("did you mean `({} {{ /* fields */ }})`?", path_str),
495                         );
496                     }
497                     suggested = true;
498                 }
499                 _ => {}
500             }
501             if !suggested {
502                 if let Some(span) = self.r.definitions.opt_span(def_id) {
503                     err.span_label(span, &format!("`{}` defined here", path_str));
504                 }
505                 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", path_str));
506             }
507         };
508
509         match (res, source) {
510             (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
511                 err.span_suggestion(
512                     span,
513                     "use `!` to invoke the macro",
514                     format!("{}!", path_str),
515                     Applicability::MaybeIncorrect,
516                 );
517                 if path_str == "try" && span.rust_2015() {
518                     err.note("if you want the `try` keyword, you need to be in the 2018 edition");
519                 }
520             }
521             (Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
522                 err.span_label(span, "type aliases cannot be used as traits");
523                 if nightly_options::is_nightly_build() {
524                     err.note("did you mean to use a trait alias?");
525                 }
526             }
527             (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
528                 if !path_sep(err, &parent) {
529                     return false;
530                 }
531             }
532             (Res::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
533             | (Res::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => {
534                 if let Some(variants) = self.collect_enum_variants(def_id) {
535                     if !variants.is_empty() {
536                         let msg = if variants.len() == 1 {
537                             "try using the enum's variant"
538                         } else {
539                             "try using one of the enum's variants"
540                         };
541
542                         err.span_suggestions(
543                             span,
544                             msg,
545                             variants.iter().map(path_names_to_string),
546                             Applicability::MaybeIncorrect,
547                         );
548                     }
549                 } else {
550                     err.note("did you mean to use one of the enum's variants?");
551                 }
552             }
553             (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
554                 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
555                 {
556                     let accessible_ctor =
557                         self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
558                     if is_expected(ctor_def) && !accessible_ctor {
559                         err.span_label(
560                             span,
561                             format!("constructor is not visible here due to private fields"),
562                         );
563                     }
564                 } else {
565                     bad_struct_syntax_suggestion(def_id);
566                 }
567             }
568             (Res::Def(DefKind::Union, def_id), _)
569             | (Res::Def(DefKind::Variant, def_id), _)
570             | (Res::Def(DefKind::Ctor(_, CtorKind::Fictive), def_id), _)
571                 if ns == ValueNS =>
572             {
573                 bad_struct_syntax_suggestion(def_id);
574             }
575             (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
576                 if let Some(span) = self.r.definitions.opt_span(def_id) {
577                     err.span_label(span, &format!("`{}` defined here", path_str));
578                 }
579                 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
580             }
581             (Res::SelfTy(..), _) if ns == ValueNS => {
582                 err.span_label(span, fallback_label);
583                 err.note("can't use `Self` as a constructor, you must use the implemented struct");
584             }
585             (Res::Def(DefKind::TyAlias, _), _) | (Res::Def(DefKind::AssocTy, _), _)
586                 if ns == ValueNS =>
587             {
588                 err.note("can't use a type alias as a constructor");
589             }
590             _ => return false,
591         }
592         true
593     }
594
595     fn lookup_assoc_candidate<FilterFn>(
596         &mut self,
597         ident: Ident,
598         ns: Namespace,
599         filter_fn: FilterFn,
600     ) -> Option<AssocSuggestion>
601     where
602         FilterFn: Fn(Res) -> bool,
603     {
604         fn extract_node_id(t: &Ty) -> Option<NodeId> {
605             match t.kind {
606                 TyKind::Path(None, _) => Some(t.id),
607                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
608                 // This doesn't handle the remaining `Ty` variants as they are not
609                 // that commonly the self_type, it might be interesting to provide
610                 // support for those in future.
611                 _ => None,
612             }
613         }
614
615         // Fields are generally expected in the same contexts as locals.
616         if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
617             if let Some(node_id) =
618                 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
619             {
620                 // Look for a field with the same name in the current self_type.
621                 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
622                     match resolution.base_res() {
623                         Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
624                             if resolution.unresolved_segments() == 0 =>
625                         {
626                             if let Some(field_names) = self.r.field_names.get(&did) {
627                                 if field_names
628                                     .iter()
629                                     .any(|&field_name| ident.name == field_name.node)
630                                 {
631                                     return Some(AssocSuggestion::Field);
632                                 }
633                             }
634                         }
635                         _ => {}
636                     }
637                 }
638             }
639         }
640
641         for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
642             if *assoc_type_ident == ident {
643                 return Some(AssocSuggestion::AssocItem);
644             }
645         }
646
647         // Look for associated items in the current trait.
648         if let Some((module, _)) = self.current_trait_ref {
649             if let Ok(binding) = self.r.resolve_ident_in_module(
650                 ModuleOrUniformRoot::Module(module),
651                 ident,
652                 ns,
653                 &self.parent_scope,
654                 false,
655                 module.span,
656             ) {
657                 let res = binding.res();
658                 if filter_fn(res) {
659                     return Some(if self.r.has_self.contains(&res.def_id()) {
660                         AssocSuggestion::MethodWithSelf
661                     } else {
662                         AssocSuggestion::AssocItem
663                     });
664                 }
665             }
666         }
667
668         None
669     }
670
671     fn lookup_typo_candidate(
672         &mut self,
673         path: &[Segment],
674         ns: Namespace,
675         filter_fn: &impl Fn(Res) -> bool,
676         span: Span,
677     ) -> Option<TypoSuggestion> {
678         let mut names = Vec::new();
679         if path.len() == 1 {
680             // Search in lexical scope.
681             // Walk backwards up the ribs in scope and collect candidates.
682             for rib in self.ribs[ns].iter().rev() {
683                 // Locals and type parameters
684                 for (ident, &res) in &rib.bindings {
685                     if filter_fn(res) {
686                         names.push(TypoSuggestion::from_res(ident.name, res));
687                     }
688                 }
689                 // Items in scope
690                 if let RibKind::ModuleRibKind(module) = rib.kind {
691                     // Items from this module
692                     self.r.add_module_candidates(module, &mut names, &filter_fn);
693
694                     if let ModuleKind::Block(..) = module.kind {
695                         // We can see through blocks
696                     } else {
697                         // Items from the prelude
698                         if !module.no_implicit_prelude {
699                             let extern_prelude = self.r.extern_prelude.clone();
700                             names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
701                                 self.r
702                                     .crate_loader
703                                     .maybe_process_path_extern(ident.name, ident.span)
704                                     .and_then(|crate_id| {
705                                         let crate_mod = Res::Def(
706                                             DefKind::Mod,
707                                             DefId { krate: crate_id, index: CRATE_DEF_INDEX },
708                                         );
709
710                                         if filter_fn(crate_mod) {
711                                             Some(TypoSuggestion::from_res(ident.name, crate_mod))
712                                         } else {
713                                             None
714                                         }
715                                     })
716                             }));
717
718                             if let Some(prelude) = self.r.prelude {
719                                 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
720                             }
721                         }
722                         break;
723                     }
724                 }
725             }
726             // Add primitive types to the mix
727             if filter_fn(Res::PrimTy(PrimTy::Bool)) {
728                 names.extend(
729                     self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
730                         TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
731                     }),
732                 )
733             }
734         } else {
735             // Search in module.
736             let mod_path = &path[..path.len() - 1];
737             if let PathResult::Module(module) =
738                 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
739             {
740                 if let ModuleOrUniformRoot::Module(module) = module {
741                     self.r.add_module_candidates(module, &mut names, &filter_fn);
742                 }
743             }
744         }
745
746         let name = path[path.len() - 1].ident.name;
747         // Make sure error reporting is deterministic.
748         names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
749
750         match find_best_match_for_name(
751             names.iter().map(|suggestion| &suggestion.candidate),
752             &name.as_str(),
753             None,
754         ) {
755             Some(found) if found != name => {
756                 names.into_iter().find(|suggestion| suggestion.candidate == found)
757             }
758             _ => None,
759         }
760     }
761
762     /// Only used in a specific case of type ascription suggestions
763     fn get_colon_suggestion_span(&self, start: Span) -> Span {
764         let sm = self.r.session.source_map();
765         start.to(sm.next_point(start))
766     }
767
768     fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) {
769         let sm = self.r.session.source_map();
770         let base_snippet = sm.span_to_snippet(base_span);
771         if let Some(sp) = self.diagnostic_metadata.current_type_ascription.last() {
772             let mut sp = *sp;
773             loop {
774                 // Try to find the `:`; bail on first non-':' / non-whitespace.
775                 sp = sm.next_point(sp);
776                 if let Ok(snippet) = sm.span_to_snippet(sp.to(sm.next_point(sp))) {
777                     let line_sp = sm.lookup_char_pos(sp.hi()).line;
778                     let line_base_sp = sm.lookup_char_pos(base_span.lo()).line;
779                     if snippet == ":" {
780                         let mut show_label = true;
781                         if line_sp != line_base_sp {
782                             err.span_suggestion_short(
783                                 sp,
784                                 "did you mean to use `;` here instead?",
785                                 ";".to_string(),
786                                 Applicability::MaybeIncorrect,
787                             );
788                         } else {
789                             let colon_sp = self.get_colon_suggestion_span(sp);
790                             let after_colon_sp =
791                                 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
792                             if !sm
793                                 .span_to_snippet(after_colon_sp)
794                                 .map(|s| s == " ")
795                                 .unwrap_or(false)
796                             {
797                                 err.span_suggestion(
798                                     colon_sp,
799                                     "maybe you meant to write a path separator here",
800                                     "::".to_string(),
801                                     Applicability::MaybeIncorrect,
802                                 );
803                                 show_label = false;
804                             }
805                             if let Ok(base_snippet) = base_snippet {
806                                 let mut sp = after_colon_sp;
807                                 for _ in 0..100 {
808                                     // Try to find an assignment
809                                     sp = sm.next_point(sp);
810                                     let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
811                                     match snippet {
812                                         Ok(ref x) if x.as_str() == "=" => {
813                                             err.span_suggestion(
814                                                 base_span,
815                                                 "maybe you meant to write an assignment here",
816                                                 format!("let {}", base_snippet),
817                                                 Applicability::MaybeIncorrect,
818                                             );
819                                             show_label = false;
820                                             break;
821                                         }
822                                         Ok(ref x) if x.as_str() == "\n" => break,
823                                         Err(_) => break,
824                                         Ok(_) => {}
825                                     }
826                                 }
827                             }
828                         }
829                         if show_label {
830                             err.span_label(
831                                 base_span,
832                                 "expecting a type here because of type ascription",
833                             );
834                         }
835                         break;
836                     } else if !snippet.trim().is_empty() {
837                         debug!("tried to find type ascription `:` token, couldn't find it");
838                         break;
839                     }
840                 } else {
841                     break;
842                 }
843             }
844         }
845     }
846
847     fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
848         let mut result = None;
849         let mut seen_modules = FxHashSet::default();
850         let mut worklist = vec![(self.r.graph_root, Vec::new())];
851
852         while let Some((in_module, path_segments)) = worklist.pop() {
853             // abort if the module is already found
854             if result.is_some() {
855                 break;
856             }
857
858             in_module.for_each_child(self.r, |_, ident, _, name_binding| {
859                 // abort if the module is already found or if name_binding is private external
860                 if result.is_some() || !name_binding.vis.is_visible_locally() {
861                     return;
862                 }
863                 if let Some(module) = name_binding.module() {
864                     // form the path
865                     let mut path_segments = path_segments.clone();
866                     path_segments.push(ast::PathSegment::from_ident(ident));
867                     let module_def_id = module.def_id().unwrap();
868                     if module_def_id == def_id {
869                         let path = Path { span: name_binding.span, segments: path_segments };
870                         result = Some((module, ImportSuggestion { did: Some(def_id), path }));
871                     } else {
872                         // add the module to the lookup
873                         if seen_modules.insert(module_def_id) {
874                             worklist.push((module, path_segments));
875                         }
876                     }
877                 }
878             });
879         }
880
881         result
882     }
883
884     fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
885         self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
886             let mut variants = Vec::new();
887             enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
888                 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
889                     let mut segms = enum_import_suggestion.path.segments.clone();
890                     segms.push(ast::PathSegment::from_ident(ident));
891                     variants.push(Path { span: name_binding.span, segments: segms });
892                 }
893             });
894             variants
895         })
896     }
897
898     crate fn report_missing_type_error(
899         &self,
900         path: &[Segment],
901     ) -> Option<(Span, &'static str, String, Applicability)> {
902         let ident = match path {
903             [segment] => segment.ident,
904             _ => return None,
905         };
906         match (
907             self.diagnostic_metadata.current_item,
908             self.diagnostic_metadata.currently_processing_generics,
909         ) {
910             (Some(Item { kind: ItemKind::Fn(..), ident, .. }), true) if ident.name == sym::main => {
911                 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
912             }
913             (Some(Item { kind, .. }), true) => {
914                 // Likely missing type parameter.
915                 if let Some(generics) = kind.generics() {
916                     let msg = "you might be missing a type parameter";
917                     let (span, sugg) = if let [.., param] = &generics.params[..] {
918                         let span = if let [.., bound] = &param.bounds[..] {
919                             bound.span()
920                         } else {
921                             param.ident.span
922                         };
923                         (span, format!(", {}", ident))
924                     } else {
925                         (generics.span, format!("<{}>", ident))
926                     };
927                     // Do not suggest if this is coming from macro expansion.
928                     if !span.from_expansion() {
929                         return Some((
930                             span.shrink_to_hi(),
931                             msg,
932                             sugg,
933                             Applicability::MaybeIncorrect,
934                         ));
935                     }
936                 }
937             }
938             _ => {}
939         }
940         None
941     }
942 }
943
944 impl<'tcx> LifetimeContext<'_, 'tcx> {
945     crate fn report_missing_lifetime_specifiers(
946         &self,
947         span: Span,
948         count: usize,
949     ) -> DiagnosticBuilder<'tcx> {
950         struct_span_err!(
951             self.tcx.sess,
952             span,
953             E0106,
954             "missing lifetime specifier{}",
955             pluralize!(count)
956         )
957     }
958
959     crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
960         let mut err = struct_span_err!(
961             self.tcx.sess,
962             lifetime_ref.span,
963             E0261,
964             "use of undeclared lifetime name `{}`",
965             lifetime_ref
966         );
967         err.span_label(lifetime_ref.span, "undeclared lifetime");
968         for missing in &self.missing_named_lifetime_spots {
969             match missing {
970                 MissingLifetimeSpot::Generics(generics) => {
971                     let (span, sugg) = if let Some(param) = generics
972                         .params
973                         .iter()
974                         .filter(|p| match p.kind {
975                             hir::GenericParamKind::Type {
976                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
977                                 ..
978                             } => false,
979                             _ => true,
980                         })
981                         .next()
982                     {
983                         (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
984                     } else {
985                         (generics.span, format!("<{}>", lifetime_ref))
986                     };
987                     err.span_suggestion(
988                         span,
989                         &format!("consider introducing lifetime `{}` here", lifetime_ref),
990                         sugg,
991                         Applicability::MaybeIncorrect,
992                     );
993                 }
994                 MissingLifetimeSpot::HigherRanked { span, span_type } => {
995                     err.span_suggestion(
996                         *span,
997                         &format!(
998                             "consider making the {} lifetime-generic with a new `{}` lifetime",
999                             span_type.descr(),
1000                             lifetime_ref
1001                         ),
1002                         span_type.suggestion(&lifetime_ref.to_string()),
1003                         Applicability::MaybeIncorrect,
1004                     );
1005                     err.note(
1006                         "for more information on higher-ranked polymorphism, visit \
1007                             https://doc.rust-lang.org/nomicon/hrtb.html",
1008                     );
1009                 }
1010             }
1011         }
1012         err.emit();
1013     }
1014
1015     crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1016         if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1017             if [
1018                 self.tcx.lang_items().fn_once_trait(),
1019                 self.tcx.lang_items().fn_trait(),
1020                 self.tcx.lang_items().fn_mut_trait(),
1021             ]
1022             .contains(&Some(did))
1023             {
1024                 let (span, span_type) = match &trait_ref.bound_generic_params {
1025                     [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1026                     [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1027                 };
1028                 self.missing_named_lifetime_spots
1029                     .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1030                 return true;
1031             }
1032         };
1033         false
1034     }
1035
1036     crate fn add_missing_lifetime_specifiers_label(
1037         &self,
1038         err: &mut DiagnosticBuilder<'_>,
1039         span: Span,
1040         count: usize,
1041         lifetime_names: &FxHashSet<ast::Ident>,
1042         params: &[ElisionFailureInfo],
1043     ) {
1044         if count > 1 {
1045             err.span_label(span, format!("expected {} lifetime parameters", count));
1046         } else {
1047             let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1048             let suggest_existing = |err: &mut DiagnosticBuilder<'_>, sugg| {
1049                 err.span_suggestion(
1050                     span,
1051                     "consider using the named lifetime",
1052                     sugg,
1053                     Applicability::MaybeIncorrect,
1054                 );
1055             };
1056             let suggest_new =
1057                 |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1058                     err.span_label(span, "expected named lifetime parameter");
1059
1060                     for missing in self.missing_named_lifetime_spots.iter().rev() {
1061                         let mut introduce_suggestion = vec![];
1062                         let msg;
1063                         let should_break;
1064                         introduce_suggestion.push(match missing {
1065                         MissingLifetimeSpot::Generics(generics) => {
1066                             msg = "consider introducing a named lifetime parameter".to_string();
1067                             should_break = true;
1068                             if let Some(param) = generics.params.iter().filter(|p| match p.kind {
1069                                 hir::GenericParamKind::Type {
1070                                     synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1071                                     ..
1072                                 } => false,
1073                                 _ => true,
1074                             }).next() {
1075                                 (param.span.shrink_to_lo(), "'a, ".to_string())
1076                             } else {
1077                                 (generics.span, "<'a>".to_string())
1078                             }
1079                         }
1080                         MissingLifetimeSpot::HigherRanked { span, span_type } => {
1081                             msg = format!(
1082                                 "consider making the {} lifetime-generic with a new `'a` lifetime",
1083                                 span_type.descr(),
1084                             );
1085                             should_break = false;
1086                             err.note(
1087                                 "for more information on higher-ranked polymorphism, visit \
1088                              https://doc.rust-lang.org/nomicon/hrtb.html",
1089                             );
1090                             (*span, span_type.suggestion("'a"))
1091                         }
1092                     });
1093                         for param in params {
1094                             if let Ok(snippet) =
1095                                 self.tcx.sess.source_map().span_to_snippet(param.span)
1096                             {
1097                                 if snippet.starts_with("&") && !snippet.starts_with("&'") {
1098                                     introduce_suggestion
1099                                         .push((param.span, format!("&'a {}", &snippet[1..])));
1100                                 } else if snippet.starts_with("&'_ ") {
1101                                     introduce_suggestion
1102                                         .push((param.span, format!("&'a {}", &snippet[4..])));
1103                                 }
1104                             }
1105                         }
1106                         introduce_suggestion.push((span, sugg.to_string()));
1107                         err.multipart_suggestion(
1108                             &msg,
1109                             introduce_suggestion,
1110                             Applicability::MaybeIncorrect,
1111                         );
1112                         if should_break {
1113                             break;
1114                         }
1115                     }
1116                 };
1117
1118             match (
1119                 lifetime_names.len(),
1120                 lifetime_names.iter().next(),
1121                 snippet.as_ref().map(|s| s.as_str()),
1122             ) {
1123                 (1, Some(name), Some("&")) => {
1124                     suggest_existing(err, format!("&{} ", name));
1125                 }
1126                 (1, Some(name), Some("'_")) => {
1127                     suggest_existing(err, name.to_string());
1128                 }
1129                 (1, Some(name), Some(snippet)) if !snippet.ends_with(">") => {
1130                     suggest_existing(err, format!("{}<{}>", snippet, name));
1131                 }
1132                 (0, _, Some("&")) => {
1133                     suggest_new(err, "&'a ");
1134                 }
1135                 (0, _, Some("'_")) => {
1136                     suggest_new(err, "'a");
1137                 }
1138                 (0, _, Some(snippet)) if !snippet.ends_with(">") => {
1139                     suggest_new(err, &format!("{}<'a>", snippet));
1140                 }
1141                 _ => {
1142                     err.span_label(span, "expected lifetime parameter");
1143                 }
1144             }
1145         }
1146     }
1147 }