1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
8 use rustc_ast::visit::FnKind;
9 use rustc_ast::{self as ast, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind};
10 use rustc_ast_pretty::pprust::path_segment_to_string;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def::Namespace::{self, *};
15 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
16 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_hir::PrimTy;
18 use rustc_session::parse::feature_err;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::lev_distance::find_best_match_for_name;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
26 type Res = def::Res<ast::NodeId>;
28 /// A field or associated item from self type suggested in case of resolution failure.
29 enum AssocSuggestion {
37 impl AssocSuggestion {
38 fn action(&self) -> &'static str {
40 AssocSuggestion::Field => "use the available field",
41 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
42 AssocSuggestion::AssocFn => "call the associated function",
43 AssocSuggestion::AssocConst => "use the associated `const`",
44 AssocSuggestion::AssocType => "use the associated type",
49 crate enum MissingLifetimeSpot<'tcx> {
50 Generics(&'tcx hir::Generics<'tcx>),
51 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
55 crate enum ForLifetimeSpanType {
62 impl ForLifetimeSpanType {
63 crate fn descr(&self) -> &'static str {
65 Self::BoundEmpty | Self::BoundTail => "bound",
66 Self::TypeEmpty | Self::TypeTail => "type",
70 crate fn suggestion(&self, sugg: &str) -> String {
72 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
73 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
78 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
79 fn into(self) -> MissingLifetimeSpot<'tcx> {
80 MissingLifetimeSpot::Generics(self)
84 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
85 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
88 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
89 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
92 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
93 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
94 let variant_path = &suggestion.path;
95 let variant_path_string = path_names_to_string(variant_path);
97 let path_len = suggestion.path.segments.len();
98 let enum_path = ast::Path {
99 span: suggestion.path.span,
100 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
103 let enum_path_string = path_names_to_string(&enum_path);
105 (variant_path_string, enum_path_string)
108 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
109 fn def_span(&self, def_id: DefId) -> Option<Span> {
111 LOCAL_CRATE => self.r.opt_span(def_id),
116 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
121 /// Handles error reporting for `smart_resolve_path_fragment` function.
122 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
123 pub(crate) fn smart_resolve_report_errors(
127 source: PathSource<'_>,
129 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
130 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
131 let ns = source.namespace();
132 let is_expected = &|res| source.is_expected(res);
133 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
135 // Make the base error.
136 let expected = source.descr_expected();
137 let path_str = Segment::names_to_string(path);
138 let item_str = path.last().unwrap().ident;
139 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
141 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
142 format!("not a {}", expected),
145 Res::Def(DefKind::Fn, _) => {
146 // Verify whether this is a fn call or an Fn used as a type.
150 .span_to_snippet(span)
151 .map(|snippet| snippet.ends_with(')'))
155 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
160 | Res::Local(_) => true,
165 let item_span = path.last().unwrap().ident.span;
166 let (mod_prefix, mod_str) = if path.len() == 1 {
167 (String::new(), "this scope".to_string())
168 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
169 (String::new(), "the crate root".to_string())
171 let mod_path = &path[..path.len() - 1];
173 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
174 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
177 .map_or(String::new(), |res| format!("{} ", res.descr()));
178 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
181 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
182 if path_str == "async" && expected.starts_with("struct") {
183 "`async` blocks are only allowed in the 2018 edition".to_string()
185 format!("not found in {}", mod_str)
192 let code = source.error_code(res.is_some());
193 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
195 match (source, self.diagnostic_metadata.in_if_condition) {
196 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
197 err.span_suggestion_verbose(
199 "you might have meant to use pattern matching",
201 Applicability::MaybeIncorrect,
203 self.r.session.if_let_suggestions.borrow_mut().insert(*span);
208 let is_assoc_fn = self.self_type_is_available(span);
209 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
210 if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
211 err.span_suggestion_short(
213 "you might have meant to use `self` here instead",
215 Applicability::MaybeIncorrect,
217 if !self.self_value_is_available(path[0].ident.span, span) {
218 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
219 &self.diagnostic_metadata.current_function
221 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
222 (param.span.shrink_to_lo(), "&self, ")
228 .span_through_char(*fn_span, '(')
233 err.span_suggestion_verbose(
235 "if you meant to use `self`, you are also missing a `self` receiver \
238 Applicability::MaybeIncorrect,
244 // Emit special messages for unresolved `Self` and `self`.
245 if is_self_type(path, ns) {
246 err.code(rustc_errors::error_code!(E0411));
249 "`Self` is only available in impls, traits, and type definitions".to_string(),
251 return (err, Vec::new());
253 if is_self_value(path, ns) {
254 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
256 err.code(rustc_errors::error_code!(E0424));
257 err.span_label(span, match source {
258 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
260 _ => "`self` value is a keyword only available in methods with a `self` parameter"
263 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
264 // The current function has a `self' parameter, but we were unable to resolve
265 // a reference to `self`. This can only happen if the `self` identifier we
266 // are resolving came from a different hygiene context.
267 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
268 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
270 let doesnt = if is_assoc_fn {
271 let (span, sugg) = fn_kind
275 .map(|p| (p.span.shrink_to_lo(), "&self, "))
281 .span_through_char(*span, '(')
286 err.span_suggestion_verbose(
288 "add a `self` receiver parameter to make the associated `fn` a method",
290 Applicability::MaybeIncorrect,
296 if let Some(ident) = fn_kind.ident() {
299 &format!("this function {} have a `self` parameter", doesnt),
304 return (err, Vec::new());
307 // Try to lookup name in more relaxed fashion for better error reporting.
308 let ident = path.last().unwrap().ident;
309 let candidates = self
311 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
313 .filter(|ImportSuggestion { did, .. }| {
314 match (did, res.and_then(|res| res.opt_def_id())) {
315 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
319 .collect::<Vec<_>>();
320 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
321 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
322 let enum_candidates =
323 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
325 if !enum_candidates.is_empty() {
326 if let (PathSource::Type, Some(span)) =
327 (source, self.diagnostic_metadata.current_type_ascription.last())
333 .type_ascription_path_suggestions
337 // Already reported this issue on the lhs of the type ascription.
339 return (err, candidates);
343 let mut enum_candidates = enum_candidates
345 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
346 .collect::<Vec<_>>();
347 enum_candidates.sort();
349 // Contextualize for E0412 "cannot find type", but don't belabor the point
350 // (that it's a variant) for E0573 "expected type, found variant".
351 let preamble = if res.is_none() {
352 let others = match enum_candidates.len() {
354 2 => " and 1 other".to_owned(),
355 n => format!(" and {} others", n),
357 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
361 let msg = format!("{}try using the variant's enum", preamble);
363 err.span_suggestions(
368 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
369 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
371 // FIXME: is there a more principled way to do this that
372 // would work for other re-exports?
373 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
374 // Also write `Option` rather than `std::prelude::v1::Option`.
375 .map(|enum_ty_path| {
376 // FIXME #56861: DRY-er prelude filtering.
377 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
379 Applicability::MachineApplicable,
383 if path.len() == 1 && self.self_type_is_available(span) {
384 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
385 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
387 AssocSuggestion::Field => {
388 if self_is_available {
391 "you might have meant to use the available field",
392 format!("self.{}", path_str),
393 Applicability::MachineApplicable,
396 err.span_label(span, "a field by this name exists in `Self`");
399 AssocSuggestion::MethodWithSelf if self_is_available => {
402 "you might have meant to call the method",
403 format!("self.{}", path_str),
404 Applicability::MachineApplicable,
407 AssocSuggestion::MethodWithSelf
408 | AssocSuggestion::AssocFn
409 | AssocSuggestion::AssocConst
410 | AssocSuggestion::AssocType => {
413 &format!("you might have meant to {}", candidate.action()),
414 format!("Self::{}", path_str),
415 Applicability::MachineApplicable,
419 return (err, candidates);
422 // If the first argument in call is `self` suggest calling a method.
423 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
424 let mut args_snippet = String::new();
425 if let Some(args_span) = args_span {
426 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
427 args_snippet = snippet;
433 &format!("try calling `{}` as a method", ident),
434 format!("self.{}({})", path_str, args_snippet),
435 Applicability::MachineApplicable,
437 return (err, candidates);
441 // Try Levenshtein algorithm.
442 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
443 // Try context-dependent help if relaxed lookup didn't work.
444 if let Some(res) = res {
445 if self.smart_resolve_context_dependent_help(
453 // We do this to avoid losing a secondary span when we override the main error span.
454 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
455 return (err, candidates);
459 if !self.type_ascription_suggestion(&mut err, base_span) {
460 let mut fallback = false;
462 PathSource::Trait(AliasPossibility::Maybe),
463 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
466 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
468 let spans: Vec<Span> = bounds
470 .map(|bound| bound.span())
471 .filter(|&sp| sp != base_span)
474 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
475 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
476 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
477 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
478 let last_bound_span = spans.last().cloned().unwrap();
479 let mut multi_span: MultiSpan = spans.clone().into();
481 let msg = if sp == last_bound_span {
483 "...because of {} bound{}",
484 if bounds.len() <= 2 { "this" } else { "these" },
485 if bounds.len() <= 2 { "" } else { "s" },
490 multi_span.push_span_label(sp, msg);
492 multi_span.push_span_label(
494 "expected this type to be a trait...".to_string(),
498 "`+` is used to constrain a \"trait object\" type with lifetimes or \
499 auto-traits; structs and enums can't be bound in that way",
501 if bounds.iter().all(|bound| match bound {
502 ast::GenericBound::Outlives(_) => true,
503 ast::GenericBound::Trait(tr, _) => tr.span == base_span,
505 let mut sugg = vec![];
506 if base_span != start_span {
507 sugg.push((start_span.until(base_span), String::new()));
509 if base_span != end_span {
510 sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
513 err.multipart_suggestion(
514 "if you meant to use a type and not a trait here, remove the bounds",
516 Applicability::MaybeIncorrect,
522 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
524 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
526 match self.diagnostic_metadata.current_let_binding {
527 Some((pat_sp, Some(ty_sp), None))
528 if ty_sp.contains(base_span) && could_be_expr =>
530 err.span_suggestion_short(
531 pat_sp.between(ty_sp),
532 "use `=` if you meant to assign",
534 Applicability::MaybeIncorrect,
542 err.span_label(base_span, fallback_label);
548 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
549 fn restrict_assoc_type_in_where_clause(
552 err: &mut DiagnosticBuilder<'_>,
554 // Detect that we are actually in a `where` predicate.
555 let (bounded_ty, bounds, where_span) =
556 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
558 bound_generic_params,
561 })) = self.diagnostic_metadata.current_where_predicate
563 if !bound_generic_params.is_empty() {
566 (bounded_ty, bounds, span)
571 // Confirm that the target is an associated type.
572 let (ty, position, path) = if let ast::TyKind::Path(
573 Some(ast::QSelf { ty, position, .. }),
577 // use this to verify that ident is a type param.
578 let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
581 &Segment::from_path(path),
592 partial_res.base_res(),
593 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
594 ) && partial_res.unresolved_segments() == 0)
603 if let ast::TyKind::Path(None, type_param_path) = &ty.peel_refs().kind {
604 // Confirm that the `SelfTy` is a type parameter.
605 let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
608 &Segment::from_path(type_param_path),
619 partial_res.base_res(),
620 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
621 ) && partial_res.unresolved_segments() == 0)
626 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
627 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
628 ) = (&type_param_path.segments[..], &bounds[..])
630 if let [ast::PathSegment { ident, args: None, .. }] =
631 &poly_trait_ref.trait_ref.path.segments[..]
633 if ident.span == span {
634 err.span_suggestion_verbose(
636 &format!("constrain the associated type to `{}`", ident),
642 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
643 .unwrap_or_else(|_| constrain_ident.to_string()),
644 path.segments[..*position]
646 .map(|segment| path_segment_to_string(segment))
649 path.segments[*position..]
651 .map(|segment| path_segment_to_string(segment))
656 Applicability::MaybeIncorrect,
666 /// Check if the source is call expression and the first argument is `self`. If true,
667 /// return the span of whole call and the span for all arguments expect the first one (`self`).
668 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
669 let mut has_self_arg = None;
670 if let PathSource::Expr(Some(parent)) = source {
672 ExprKind::Call(_, args) if !args.is_empty() => {
673 let mut expr_kind = &args[0].kind;
676 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
677 if arg_name.segments[0].ident.name == kw::SelfLower {
678 let call_span = parent.span;
679 let tail_args_span = if args.len() > 1 {
682 args.last().unwrap().span.hi(),
688 has_self_arg = Some((call_span, tail_args_span));
692 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
703 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
704 // HACK(estebank): find a better way to figure out that this was a
705 // parser issue where a struct literal is being used on an expression
706 // where a brace being opened means a block is being started. Look
707 // ahead for the next text to see if `span` is followed by a `{`.
708 let sm = self.r.session.source_map();
711 sp = sm.next_point(sp);
712 match sm.span_to_snippet(sp) {
714 if snippet.chars().any(|c| !c.is_whitespace()) {
721 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
722 // In case this could be a struct literal that needs to be surrounded
723 // by parentheses, find the appropriate span.
725 let mut closing_brace = None;
727 sp = sm.next_point(sp);
728 match sm.span_to_snippet(sp) {
731 closing_brace = Some(span.to(sp));
738 // The bigger the span, the more likely we're incorrect --
739 // bound it to 100 chars long.
744 (followed_by_brace, closing_brace)
747 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
749 /// Returns `true` if able to provide context-dependent help.
750 fn smart_resolve_context_dependent_help(
752 err: &mut DiagnosticBuilder<'a>,
754 source: PathSource<'_>,
757 fallback_label: &str,
759 let ns = source.namespace();
760 let is_expected = &|res| source.is_expected(res);
762 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
763 ExprKind::Field(_, ident) => {
766 "use the path separator to refer to an item",
767 format!("{}::{}", path_str, ident),
768 Applicability::MaybeIncorrect,
772 ExprKind::MethodCall(ref segment, ..) => {
773 let span = expr.span.with_hi(segment.ident.span.hi());
776 "use the path separator to refer to an item",
777 format!("{}::{}", path_str, segment.ident),
778 Applicability::MaybeIncorrect,
785 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
786 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
789 PathSource::Expr(Some(
790 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
791 )) if path_sep(err, &parent) => {}
797 | ExprKind::Binary(..)
798 | ExprKind::Unary(..)
800 | ExprKind::While(..)
801 | ExprKind::ForLoop(..)
802 | ExprKind::Match(..),
805 ) if followed_by_brace => {
806 if let Some(sp) = closing_brace {
807 err.span_label(span, fallback_label);
808 err.multipart_suggestion(
809 "surround the struct literal with parentheses",
811 (sp.shrink_to_lo(), "(".to_string()),
812 (sp.shrink_to_hi(), ")".to_string()),
814 Applicability::MaybeIncorrect,
818 span, // Note the parentheses surrounding the suggestion below
820 "you might want to surround a struct literal with parentheses: \
821 `({} {{ /* fields */ }})`?",
827 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
828 let span = match &source {
829 PathSource::Expr(Some(Expr {
830 span, kind: ExprKind::Call(_, _), ..
832 | PathSource::TupleStruct(span, _) => {
833 // We want the main underline to cover the suggested code as well for
840 if let Some(span) = self.def_span(def_id) {
841 err.span_label(span, &format!("`{}` defined here", path_str));
843 let (tail, descr, applicability) = match source {
844 PathSource::Pat | PathSource::TupleStruct(..) => {
845 ("", "pattern", Applicability::MachineApplicable)
847 _ => (": val", "literal", Applicability::HasPlaceholders),
849 let (fields, applicability) = match self.r.field_names.get(&def_id) {
853 .map(|f| format!("{}{}", f.node, tail))
854 .collect::<Vec<String>>()
858 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
860 let pad = match self.r.field_names.get(&def_id) {
861 Some(fields) if fields.is_empty() => "",
866 &format!("use struct {} syntax instead", descr),
867 format!("{path_str} {{{pad}{fields}{pad}}}"),
872 err.span_label(span, fallback_label);
877 match (res, source) {
878 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
879 err.span_label(span, fallback_label);
880 err.span_suggestion_verbose(
882 "use `!` to invoke the macro",
884 Applicability::MaybeIncorrect,
886 if path_str == "try" && span.rust_2015() {
887 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
890 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
891 err.span_label(span, "type aliases cannot be used as traits");
892 if self.r.session.is_nightly_build() {
893 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
895 if let Some(span) = self.def_span(def_id) {
896 err.span_help(span, msg);
902 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
903 if !path_sep(err, &parent) {
908 Res::Def(DefKind::Enum, def_id),
909 PathSource::TupleStruct(..) | PathSource::Expr(..),
913 .current_type_ascription
919 .type_ascription_path_suggestions
926 // We already suggested changing `:` into `::` during parsing.
930 self.suggest_using_enum_variant(err, source, def_id, span);
932 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
933 let (ctor_def, ctor_vis, fields) =
934 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
937 bad_struct_syntax_suggestion(def_id);
941 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
942 if !is_expected(ctor_def) || is_accessible {
946 let field_spans = match source {
947 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
948 PathSource::TupleStruct(_, pattern_spans) => {
949 err.set_primary_message(
950 "cannot match against a tuple struct which contains private fields",
953 // Use spans of the tuple struct pattern.
954 Some(Vec::from(pattern_spans))
956 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
957 _ if source.is_call() => {
958 err.set_primary_message(
959 "cannot initialize a tuple struct which contains private fields",
962 // Use spans of the tuple struct definition.
966 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
972 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
974 let non_visible_spans: Vec<Span> = fields
978 !self.r.is_accessible_from(**vis, self.parent_scope.module)
980 .map(|(_, span)| *span)
983 if non_visible_spans.len() > 0 {
984 let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into();
987 .for_each(|s| m.push_span_label(s, "private field".to_string()));
988 err.span_note(m, "constructor is not visible here due to private fields");
996 "constructor is not visible here due to private fields".to_string(),
1001 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1005 ) if ns == ValueNS => {
1006 bad_struct_syntax_suggestion(def_id);
1008 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1009 if let Some(span) = self.def_span(def_id) {
1010 err.span_label(span, &format!("`{}` defined here", path_str));
1013 self.r.field_names.get(&def_id).map_or("/* fields */".to_string(), |fields| {
1014 vec!["_"; fields.len()].join(", ")
1016 err.span_suggestion(
1018 "use the tuple variant pattern syntax instead",
1019 format!("{}({})", path_str, fields),
1020 Applicability::HasPlaceholders,
1023 (Res::SelfTy(..), _) if ns == ValueNS => {
1024 err.span_label(span, fallback_label);
1025 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1027 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1028 err.note("can't use a type alias as a constructor");
1035 fn lookup_assoc_candidate<FilterFn>(
1039 filter_fn: FilterFn,
1040 ) -> Option<AssocSuggestion>
1042 FilterFn: Fn(Res) -> bool,
1044 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1046 TyKind::Path(None, _) => Some(t.id),
1047 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1048 // This doesn't handle the remaining `Ty` variants as they are not
1049 // that commonly the self_type, it might be interesting to provide
1050 // support for those in future.
1055 // Fields are generally expected in the same contexts as locals.
1056 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1057 if let Some(node_id) =
1058 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1060 // Look for a field with the same name in the current self_type.
1061 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1062 match resolution.base_res() {
1063 Res::Def(DefKind::Struct | DefKind::Union, did)
1064 if resolution.unresolved_segments() == 0 =>
1066 if let Some(field_names) = self.r.field_names.get(&did) {
1069 .any(|&field_name| ident.name == field_name.node)
1071 return Some(AssocSuggestion::Field);
1081 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1082 for assoc_item in &items[..] {
1083 if assoc_item.ident == ident {
1084 return Some(match &assoc_item.kind {
1085 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1086 ast::AssocItemKind::Fn(_, sig, ..) if sig.decl.has_self() => {
1087 AssocSuggestion::MethodWithSelf
1089 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1090 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1091 ast::AssocItemKind::MacCall(_) => continue,
1097 // Look for associated items in the current trait.
1098 if let Some((module, _)) = self.current_trait_ref {
1099 if let Ok(binding) = self.r.resolve_ident_in_module(
1100 ModuleOrUniformRoot::Module(module),
1107 let res = binding.res();
1109 if self.r.has_self.contains(&res.def_id()) {
1110 return Some(AssocSuggestion::MethodWithSelf);
1113 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1114 Res::Def(DefKind::AssocConst, _) => {
1115 return Some(AssocSuggestion::AssocConst);
1117 Res::Def(DefKind::AssocTy, _) => {
1118 return Some(AssocSuggestion::AssocType);
1130 fn lookup_typo_candidate(
1134 filter_fn: &impl Fn(Res) -> bool,
1136 ) -> Option<TypoSuggestion> {
1137 let mut names = Vec::new();
1138 if path.len() == 1 {
1139 // Search in lexical scope.
1140 // Walk backwards up the ribs in scope and collect candidates.
1141 for rib in self.ribs[ns].iter().rev() {
1142 // Locals and type parameters
1143 for (ident, &res) in &rib.bindings {
1145 names.push(TypoSuggestion::from_res(ident.name, res));
1149 if let RibKind::ModuleRibKind(module) = rib.kind {
1150 // Items from this module
1151 self.r.add_module_candidates(module, &mut names, &filter_fn);
1153 if let ModuleKind::Block(..) = module.kind {
1154 // We can see through blocks
1156 // Items from the prelude
1157 if !module.no_implicit_prelude {
1158 let extern_prelude = self.r.extern_prelude.clone();
1159 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1160 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1162 let crate_mod = Res::Def(
1164 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
1167 if filter_fn(crate_mod) {
1168 Some(TypoSuggestion::from_res(ident.name, crate_mod))
1176 if let Some(prelude) = self.r.prelude {
1177 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1184 // Add primitive types to the mix
1185 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1187 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
1188 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
1193 // Search in module.
1194 let mod_path = &path[..path.len() - 1];
1195 if let PathResult::Module(module) =
1196 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
1198 if let ModuleOrUniformRoot::Module(module) = module {
1199 self.r.add_module_candidates(module, &mut names, &filter_fn);
1204 let name = path[path.len() - 1].ident.name;
1205 // Make sure error reporting is deterministic.
1206 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
1208 match find_best_match_for_name(
1209 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1213 Some(found) if found != name => {
1214 names.into_iter().find(|suggestion| suggestion.candidate == found)
1220 /// Only used in a specific case of type ascription suggestions
1221 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1222 let sm = self.r.session.source_map();
1223 start.to(sm.next_point(start))
1226 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
1227 let sm = self.r.session.source_map();
1228 let base_snippet = sm.span_to_snippet(base_span);
1229 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1230 if let Ok(snippet) = sm.span_to_snippet(sp) {
1231 let len = snippet.trim_end().len() as u32;
1232 if snippet.trim() == ":" {
1234 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1235 let mut show_label = true;
1236 if sm.is_multiline(sp) {
1237 err.span_suggestion_short(
1239 "maybe you meant to write `;` here",
1241 Applicability::MaybeIncorrect,
1244 let after_colon_sp =
1245 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1246 if snippet.len() == 1 {
1248 err.span_suggestion(
1250 "maybe you meant to write a path separator here",
1252 Applicability::MaybeIncorrect,
1259 .type_ascription_path_suggestions
1266 if let Ok(base_snippet) = base_snippet {
1267 let mut sp = after_colon_sp;
1269 // Try to find an assignment
1270 sp = sm.next_point(sp);
1271 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1273 Ok(ref x) if x.as_str() == "=" => {
1274 err.span_suggestion(
1276 "maybe you meant to write an assignment here",
1277 format!("let {}", base_snippet),
1278 Applicability::MaybeIncorrect,
1283 Ok(ref x) if x.as_str() == "\n" => break,
1293 "expecting a type here because of type ascription",
1303 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1304 let mut result = None;
1305 let mut seen_modules = FxHashSet::default();
1306 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1308 while let Some((in_module, path_segments)) = worklist.pop() {
1309 // abort if the module is already found
1310 if result.is_some() {
1314 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1315 // abort if the module is already found or if name_binding is private external
1316 if result.is_some() || !name_binding.vis.is_visible_locally() {
1319 if let Some(module) = name_binding.module() {
1321 let mut path_segments = path_segments.clone();
1322 path_segments.push(ast::PathSegment::from_ident(ident));
1323 let module_def_id = module.def_id().unwrap();
1324 if module_def_id == def_id {
1326 Path { span: name_binding.span, segments: path_segments, tokens: None };
1337 // add the module to the lookup
1338 if seen_modules.insert(module_def_id) {
1339 worklist.push((module, path_segments));
1349 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1350 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1351 let mut variants = Vec::new();
1352 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1353 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1354 let mut segms = enum_import_suggestion.path.segments.clone();
1355 segms.push(ast::PathSegment::from_ident(ident));
1356 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1357 variants.push((path, def_id, kind));
1364 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1365 fn suggest_using_enum_variant(
1367 err: &mut DiagnosticBuilder<'a>,
1368 source: PathSource<'_>,
1372 let variants = match self.collect_enum_ctors(def_id) {
1373 Some(variants) => variants,
1375 err.note("you might have meant to use one of the enum's variants");
1380 let suggest_only_tuple_variants =
1381 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1382 if suggest_only_tuple_variants {
1383 // Suggest only tuple variants regardless of whether they have fields and do not
1384 // suggest path with added parenthesis.
1385 let mut suggestable_variants = variants
1387 .filter(|(.., kind)| *kind == CtorKind::Fn)
1388 .map(|(variant, ..)| path_names_to_string(variant))
1389 .collect::<Vec<_>>();
1391 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1393 let source_msg = if source.is_call() {
1395 } else if matches!(source, PathSource::TupleStruct(..)) {
1401 if !suggestable_variants.is_empty() {
1402 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1403 format!("try {} the enum's variant", source_msg)
1405 format!("try {} one of the enum's variants", source_msg)
1408 err.span_suggestions(
1411 suggestable_variants.drain(..),
1412 Applicability::MaybeIncorrect,
1416 // If the enum has no tuple variants..
1417 if non_suggestable_variant_count == variants.len() {
1418 err.help(&format!("the enum has no tuple variants {}", source_msg));
1421 // If there are also non-tuple variants..
1422 if non_suggestable_variant_count == 1 {
1424 "you might have meant {} the enum's non-tuple variant",
1427 } else if non_suggestable_variant_count >= 1 {
1429 "you might have meant {} one of the enum's non-tuple variants",
1434 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1436 self.r.field_names.get(&def_id).map(|f| f.is_empty()).unwrap_or(false);
1438 CtorKind::Const => false,
1439 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1444 let mut suggestable_variants = variants
1446 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1447 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1448 .map(|(variant, kind)| match kind {
1449 CtorKind::Const => variant,
1450 CtorKind::Fn => format!("({}())", variant),
1451 CtorKind::Fictive => format!("({} {{}})", variant),
1453 .collect::<Vec<_>>();
1455 if !suggestable_variants.is_empty() {
1456 let msg = if suggestable_variants.len() == 1 {
1457 "you might have meant to use the following enum variant"
1459 "you might have meant to use one of the following enum variants"
1462 err.span_suggestions(
1465 suggestable_variants.drain(..),
1466 Applicability::MaybeIncorrect,
1470 let mut suggestable_variants_with_placeholders = variants
1472 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1473 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1474 .filter_map(|(variant, kind)| match kind {
1475 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1476 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1479 .collect::<Vec<_>>();
1481 if !suggestable_variants_with_placeholders.is_empty() {
1483 suggestable_variants.is_empty(),
1484 suggestable_variants_with_placeholders.len(),
1486 (true, 1) => "the following enum variant is available",
1487 (true, _) => "the following enum variants are available",
1488 (false, 1) => "alternatively, the following enum variant is available",
1489 (false, _) => "alternatively, the following enum variants are also available",
1492 err.span_suggestions(
1495 suggestable_variants_with_placeholders.drain(..),
1496 Applicability::HasPlaceholders,
1501 if def_id.is_local() {
1502 if let Some(span) = self.def_span(def_id) {
1503 err.span_note(span, "the enum is defined here");
1508 crate fn report_missing_type_error(
1511 ) -> Option<(Span, &'static str, String, Applicability)> {
1512 let (ident, span) = match path {
1513 [segment] if !segment.has_generic_args => {
1514 (segment.ident.to_string(), segment.ident.span)
1518 let mut iter = ident.chars().map(|c| c.is_uppercase());
1519 let single_uppercase_char =
1520 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1521 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1524 match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1525 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1526 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1531 kind @ ItemKind::Fn(..)
1532 | kind @ ItemKind::Enum(..)
1533 | kind @ ItemKind::Struct(..)
1534 | kind @ ItemKind::Union(..),
1539 | (Some(Item { kind, .. }), false) => {
1540 // Likely missing type parameter.
1541 if let Some(generics) = kind.generics() {
1542 if span.overlaps(generics.span) {
1543 // Avoid the following:
1544 // error[E0405]: cannot find trait `A` in this scope
1545 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1547 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1548 // | ^- help: you might be missing a type parameter: `, A`
1550 // | not found in this scope
1553 let msg = "you might be missing a type parameter";
1554 let (span, sugg) = if let [.., param] = &generics.params[..] {
1555 let span = if let [.., bound] = ¶m.bounds[..] {
1560 (span, format!(", {}", ident))
1562 (generics.span, format!("<{}>", ident))
1564 // Do not suggest if this is coming from macro expansion.
1565 if !span.from_expansion() {
1567 span.shrink_to_hi(),
1570 Applicability::MaybeIncorrect,
1580 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1581 /// optionally returning the closest match and whether it is reachable.
1582 crate fn suggestion_for_label_in_rib(
1586 ) -> Option<LabelSuggestion> {
1587 // Are ribs from this `rib_index` within scope?
1588 let within_scope = self.is_label_valid_from_rib(rib_index);
1590 let rib = &self.label_ribs[rib_index];
1594 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1595 .map(|(id, _)| id.name)
1596 .collect::<Vec<Symbol>>();
1598 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1599 // Upon finding a similar name, get the ident that it was from - the span
1600 // contained within helps make a useful diagnostic. In addition, determine
1601 // whether this candidate is within scope.
1602 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1603 (*ident, within_scope)
1608 impl<'tcx> LifetimeContext<'_, 'tcx> {
1609 crate fn report_missing_lifetime_specifiers(
1613 ) -> DiagnosticBuilder<'tcx> {
1618 "missing lifetime specifier{}",
1623 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1624 let mut err = struct_span_err!(
1628 "use of undeclared lifetime name `{}`",
1631 err.span_label(lifetime_ref.span, "undeclared lifetime");
1632 let mut suggests_in_band = false;
1633 for missing in &self.missing_named_lifetime_spots {
1635 MissingLifetimeSpot::Generics(generics) => {
1636 let (span, sugg) = if let Some(param) =
1637 generics.params.iter().find(|p| match p.kind {
1638 hir::GenericParamKind::Type {
1639 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1642 hir::GenericParamKind::Lifetime {
1643 kind: hir::LifetimeParamKind::Elided,
1647 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1649 suggests_in_band = true;
1650 (generics.span, format!("<{}>", lifetime_ref))
1652 err.span_suggestion(
1654 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1656 Applicability::MaybeIncorrect,
1659 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1660 err.span_suggestion(
1663 "consider making the {} lifetime-generic with a new `{}` lifetime",
1667 span_type.suggestion(&lifetime_ref.to_string()),
1668 Applicability::MaybeIncorrect,
1671 "for more information on higher-ranked polymorphism, visit \
1672 https://doc.rust-lang.org/nomicon/hrtb.html",
1678 if self.tcx.sess.is_nightly_build()
1679 && !self.tcx.features().in_band_lifetimes
1683 "if you want to experiment with in-band lifetime bindings, \
1684 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1690 // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1691 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1692 // lifetimes in const generics. See issue #74052 for discussion.
1693 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1694 let mut err = struct_span_err!(
1698 "use of non-static lifetime `{}` in const generic",
1702 "for more information, see issue #74052 \
1703 <https://github.com/rust-lang/rust/issues/74052>",
1708 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1709 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1711 self.tcx.lang_items().fn_once_trait(),
1712 self.tcx.lang_items().fn_trait(),
1713 self.tcx.lang_items().fn_mut_trait(),
1715 .contains(&Some(did))
1717 let (span, span_type) = match &trait_ref.bound_generic_params {
1718 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1719 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1721 self.missing_named_lifetime_spots
1722 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1729 crate fn add_missing_lifetime_specifiers_label(
1731 err: &mut DiagnosticBuilder<'_>,
1734 lifetime_names: &FxHashSet<Symbol>,
1735 lifetime_spans: Vec<Span>,
1736 params: &[ElisionFailureInfo],
1738 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1743 "expected {} lifetime parameter{}",
1744 if count == 1 { "named".to_string() } else { count.to_string() },
1749 let suggest_existing = |err: &mut DiagnosticBuilder<'_>,
1751 formatter: &dyn Fn(&str) -> String| {
1752 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
1753 self.missing_named_lifetime_spots.iter().rev().next()
1755 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1756 // using `'a`, but also introduce the concept of HRLTs by suggesting
1757 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1758 let mut introduce_suggestion = vec![];
1760 let a_to_z_repeat_n = |n| {
1761 (b'a'..=b'z').map(move |c| {
1762 let mut s = '\''.to_string();
1763 s.extend(std::iter::repeat(char::from(c)).take(n));
1768 // If all single char lifetime names are present, we wrap around and double the chars.
1770 .flat_map(a_to_z_repeat_n)
1771 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
1774 "consider making the {} lifetime-generic with a new `{}` lifetime",
1779 "for more information on higher-ranked polymorphism, visit \
1780 https://doc.rust-lang.org/nomicon/hrtb.html",
1782 let for_sugg = span_type.suggestion(<_name);
1783 for param in params {
1784 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1785 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1786 introduce_suggestion
1787 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
1788 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
1789 introduce_suggestion
1790 .push((param.span, format!("&{} {}", lt_name, stripped)));
1794 introduce_suggestion.push((*for_span, for_sugg));
1795 introduce_suggestion.push((span, formatter(<_name)));
1796 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1799 err.span_suggestion_verbose(
1801 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1803 Applicability::MaybeIncorrect,
1806 let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1807 for missing in self.missing_named_lifetime_spots.iter().rev() {
1808 let mut introduce_suggestion = vec![];
1811 introduce_suggestion.push(match missing {
1812 MissingLifetimeSpot::Generics(generics) => {
1813 if generics.span == DUMMY_SP {
1814 // Account for malformed generics in the HIR. This shouldn't happen,
1815 // but if we make a mistake elsewhere, mainly by keeping something in
1816 // `missing_named_lifetime_spots` that we shouldn't, like associated
1817 // `const`s or making a mistake in the AST lowering we would provide
1818 // non-sensical suggestions. Guard against that by skipping these.
1822 msg = "consider introducing a named lifetime parameter".to_string();
1823 should_break = true;
1824 if let Some(param) = generics.params.iter().find(|p| {
1825 !matches!(p.kind, hir::GenericParamKind::Type {
1826 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1830 (param.span.shrink_to_lo(), "'a, ".to_string())
1832 (generics.span, "<'a>".to_string())
1835 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1837 "consider making the {} lifetime-generic with a new `'a` lifetime",
1840 should_break = false;
1842 "for more information on higher-ranked polymorphism, visit \
1843 https://doc.rust-lang.org/nomicon/hrtb.html",
1845 (*span, span_type.suggestion("'a"))
1847 MissingLifetimeSpot::Static => {
1848 let (span, sugg) = match snippet.as_deref() {
1849 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
1850 Some("'_") => (span, "'static".to_owned()),
1851 Some(snippet) if !snippet.ends_with('>') => {
1855 std::iter::repeat("'static")
1857 .collect::<Vec<_>>()
1862 span.shrink_to_hi(),
1865 std::iter::repeat("'static")
1867 .collect::<Vec<_>>()
1875 err.span_suggestion_verbose(
1877 "consider using the `'static` lifetime",
1879 Applicability::MaybeIncorrect,
1884 for param in params {
1885 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1886 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1887 introduce_suggestion
1888 .push((param.span, format!("&'a {}", &snippet[1..])));
1889 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
1890 introduce_suggestion.push((param.span, format!("&'a {}", &stripped)));
1894 introduce_suggestion.push((span, sugg.to_string()));
1895 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1902 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
1903 match (&lifetime_names[..], snippet.as_deref()) {
1904 ([name], Some("&")) => {
1905 suggest_existing(err, &name.as_str()[..], &|name| format!("&{} ", name));
1907 ([name], Some("'_")) => {
1908 suggest_existing(err, &name.as_str()[..], &|n| n.to_string());
1910 ([name], Some("")) => {
1911 suggest_existing(err, &name.as_str()[..], &|n| format!("{}, ", n).repeat(count));
1913 ([name], Some(snippet)) if !snippet.ends_with('>') => {
1914 let f = |name: &str| {
1918 std::iter::repeat(name.to_string())
1920 .collect::<Vec<_>>()
1924 suggest_existing(err, &name.as_str()[..], &f);
1926 ([], Some("&")) if count == 1 => {
1927 suggest_new(err, "&'a ");
1929 ([], Some("'_")) if count == 1 => {
1930 suggest_new(err, "'a");
1932 ([], Some(snippet)) if !snippet.ends_with('>') => {
1934 // This happens when we have `type Bar<'a> = Foo<T>` where we point at the space
1935 // before `T`. We will suggest `type Bar<'a> = Foo<'a, T>`.
1938 &std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""),
1946 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", ")
1951 (lts, ..) if lts.len() > 1 => {
1952 err.span_note(lifetime_spans, "these named lifetimes are available to use");
1953 if Some("") == snippet.as_deref() {
1954 // This happens when we have `Foo<T>` where we point at the space before `T`,
1955 // but this can be confusing so we give a suggestion with placeholders.
1956 err.span_suggestion_verbose(
1958 "consider using one of the available lifetimes here",
1959 "'lifetime, ".repeat(count),
1960 Applicability::HasPlaceholders,
1968 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics` so
1969 /// this function will emit an error if `min_const_generics` is enabled, the body identified by
1970 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
1971 crate fn maybe_emit_forbidden_non_static_lifetime_error(
1973 body_id: hir::BodyId,
1974 lifetime_ref: &'tcx hir::Lifetime,
1976 let is_anon_const = matches!(
1977 self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
1978 hir::def::DefKind::AnonConst
1980 let is_allowed_lifetime = matches!(
1982 hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
1985 if self.tcx.features().min_const_generics && is_anon_const && !is_allowed_lifetime {
1987 &self.tcx.sess.parse_sess,
1988 sym::const_generics,
1990 "a non-static lifetime is not allowed in a `const`",