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