1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::late::{LifetimeBinderKind, LifetimeRibKind, LifetimeUseSet};
5 use crate::path_names_to_string;
6 use crate::{Module, ModuleKind, ModuleOrUniformRoot};
7 use crate::{PathResult, PathSource, Segment};
9 use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
11 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
12 NodeId, Path, Ty, TyKind,
14 use rustc_ast_pretty::pprust::path_segment_to_string;
15 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
17 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
23 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
24 use rustc_hir::PrimTy;
25 use rustc_session::lint;
26 use rustc_session::parse::feature_err;
27 use rustc_session::Session;
28 use rustc_span::edition::Edition;
29 use rustc_span::hygiene::MacroKind;
30 use rustc_span::lev_distance::find_best_match_for_name;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, Span, DUMMY_SP};
39 type Res = def::Res<ast::NodeId>;
41 /// A field or associated item from self type suggested in case of resolution failure.
42 enum AssocSuggestion {
50 impl AssocSuggestion {
51 fn action(&self) -> &'static str {
53 AssocSuggestion::Field => "use the available field",
54 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
55 AssocSuggestion::AssocFn => "call the associated function",
56 AssocSuggestion::AssocConst => "use the associated `const`",
57 AssocSuggestion::AssocType => "use the associated type",
62 pub(crate) enum MissingLifetimeSpot<'tcx> {
63 Generics(&'tcx hir::Generics<'tcx>),
64 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
68 pub(crate) enum ForLifetimeSpanType {
77 impl ForLifetimeSpanType {
78 pub(crate) fn descr(&self) -> &'static str {
80 Self::BoundEmpty | Self::BoundTail => "bound",
81 Self::TypeEmpty | Self::TypeTail => "type",
82 Self::ClosureEmpty | Self::ClosureTail => "closure",
86 pub(crate) fn suggestion(&self, sugg: &str) -> String {
88 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
89 Self::ClosureEmpty => format!("for<{}>", sugg),
90 Self::BoundTail | Self::TypeTail | Self::ClosureTail => format!(", {}", sugg),
95 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
96 fn into(self) -> MissingLifetimeSpot<'tcx> {
97 MissingLifetimeSpot::Generics(self)
101 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
102 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
105 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
106 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
109 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
110 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
111 let variant_path = &suggestion.path;
112 let variant_path_string = path_names_to_string(variant_path);
114 let path_len = suggestion.path.segments.len();
115 let enum_path = ast::Path {
116 span: suggestion.path.span,
117 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
120 let enum_path_string = path_names_to_string(&enum_path);
122 (variant_path_string, enum_path_string)
125 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
126 fn def_span(&self, def_id: DefId) -> Option<Span> {
128 LOCAL_CRATE => self.r.opt_span(def_id),
133 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
138 /// Handles error reporting for `smart_resolve_path_fragment` function.
139 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
140 pub(crate) fn smart_resolve_report_errors(
144 source: PathSource<'_>,
146 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
147 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
148 let ns = source.namespace();
149 let is_expected = &|res| source.is_expected(res);
150 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
152 debug!(?res, ?source);
154 // Make the base error.
155 struct BaseError<'a> {
157 fallback_label: String,
160 suggestion: Option<(Span, &'a str, String)>,
162 let mut expected = source.descr_expected();
163 let path_str = Segment::names_to_string(path);
164 let item_str = path.last().unwrap().ident;
165 let base_error = if let Some(res) = res {
167 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
168 fallback_label: format!("not a {expected}"),
170 could_be_expr: match res {
171 Res::Def(DefKind::Fn, _) => {
172 // Verify whether this is a fn call or an Fn used as a type.
176 .span_to_snippet(span)
177 .map(|snippet| snippet.ends_with(')'))
181 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
186 | Res::Local(_) => true,
192 let item_span = path.last().unwrap().ident.span;
193 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
194 debug!(?self.diagnostic_metadata.current_impl_items);
195 debug!(?self.diagnostic_metadata.current_function);
196 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
197 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
198 && self.current_trait_ref.is_none()
199 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
200 && let Some(item) = items.iter().find(|i| {
201 if let AssocItemKind::Fn(fn_) = &i.kind
202 && !fn_.sig.decl.has_self()
203 && i.ident.name == item_str.name
205 debug!(?item_str.name);
206 debug!(?fn_.sig.decl.inputs);
214 "consider using the associated function",
215 format!("Self::{}", item.ident)
220 (String::new(), "this scope".to_string(), suggestion)
221 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
222 if self.r.session.edition() > Edition::Edition2015 {
223 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
224 // which overrides all other expectations of item type
226 (String::new(), "the list of imported crates".to_string(), None)
228 (String::new(), "the crate root".to_string(), None)
230 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
231 (String::new(), "the crate root".to_string(), None)
233 let mod_path = &path[..path.len() - 1];
234 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
235 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
238 .map_or_else(String::new, |res| format!("{} ", res.descr()));
239 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
242 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
243 fallback_label: if path_str == "async" && expected.starts_with("struct") {
244 "`async` blocks are only allowed in Rust 2018 or later".to_string()
246 format!("not found in {mod_str}")
249 could_be_expr: false,
254 let code = source.error_code(res.is_some());
256 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
258 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
260 if let Some(sugg) = base_error.suggestion {
261 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
264 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
265 err.multipart_suggestion(
266 "you might have meant to write a `struct` literal",
268 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
269 (span.shrink_to_hi(), "}".to_string()),
271 Applicability::HasPlaceholders,
274 match (source, self.diagnostic_metadata.in_if_condition) {
277 Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
279 // Icky heuristic so we don't suggest:
280 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
281 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
282 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
283 err.span_suggestion_verbose(
284 expr_span.shrink_to_lo(),
285 "you might have meant to use pattern matching",
287 Applicability::MaybeIncorrect,
294 let is_assoc_fn = self.self_type_is_available();
295 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
296 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
297 err.span_suggestion_short(
299 "you might have meant to use `self` here instead",
301 Applicability::MaybeIncorrect,
303 if !self.self_value_is_available(path[0].ident.span) {
304 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
305 &self.diagnostic_metadata.current_function
307 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
308 (param.span.shrink_to_lo(), "&self, ")
314 .span_through_char(*fn_span, '(')
319 err.span_suggestion_verbose(
321 "if you meant to use `self`, you are also missing a `self` receiver \
324 Applicability::MaybeIncorrect,
330 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
332 // Emit special messages for unresolved `Self` and `self`.
333 if is_self_type(path, ns) {
334 err.code(rustc_errors::error_code!(E0411));
337 "`Self` is only available in impls, traits, and type definitions".to_string(),
339 if let Some(item_kind) = self.diagnostic_metadata.current_item {
341 item_kind.ident.span,
343 "`Self` not allowed in {} {}",
344 item_kind.kind.article(),
345 item_kind.kind.descr()
349 return (err, Vec::new());
351 if is_self_value(path, ns) {
352 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
354 err.code(rustc_errors::error_code!(E0424));
355 err.span_label(span, match source {
356 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed",
357 _ => "`self` value is a keyword only available in methods with a `self` parameter",
359 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
360 // The current function has a `self' parameter, but we were unable to resolve
361 // a reference to `self`. This can only happen if the `self` identifier we
362 // are resolving came from a different hygiene context.
363 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
364 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
366 let doesnt = if is_assoc_fn {
367 let (span, sugg) = fn_kind
371 .map(|p| (p.span.shrink_to_lo(), "&self, "))
373 // Try to look for the "(" after the function name, if possible.
374 // This avoids placing the suggestion into the visibility specifier.
377 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
382 .span_through_char(span, '(')
387 err.span_suggestion_verbose(
389 "add a `self` receiver parameter to make the associated `fn` a method",
391 Applicability::MaybeIncorrect,
397 if let Some(ident) = fn_kind.ident() {
400 &format!("this function {} have a `self` parameter", doesnt),
404 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
406 item_kind.ident.span,
408 "`self` not allowed in {} {}",
409 item_kind.kind.article(),
410 item_kind.kind.descr()
414 return (err, Vec::new());
417 // Try to lookup name in more relaxed fashion for better error reporting.
418 let ident = path.last().unwrap().ident;
419 let mut candidates = self
421 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
423 .filter(|ImportSuggestion { did, .. }| {
424 match (did, res.and_then(|res| res.opt_def_id())) {
425 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
429 .collect::<Vec<_>>();
430 let crate_def_id = CRATE_DEF_ID.to_def_id();
431 // Try to filter out intrinsics candidates, as long as we have
432 // some other candidates to suggest.
433 let intrinsic_candidates: Vec<_> = candidates
434 .drain_filter(|sugg| {
435 let path = path_names_to_string(&sugg.path);
436 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
439 if candidates.is_empty() {
440 // Put them back if we have no more candidates to suggest...
441 candidates.extend(intrinsic_candidates);
443 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
444 let mut enum_candidates: Vec<_> = self
446 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
448 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
449 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
451 if !enum_candidates.is_empty() {
452 if let (PathSource::Type, Some(span)) =
453 (source, self.diagnostic_metadata.current_type_ascription.last())
459 .type_ascription_path_suggestions
463 // Already reported this issue on the lhs of the type ascription.
465 return (err, candidates);
469 enum_candidates.sort();
471 // Contextualize for E0412 "cannot find type", but don't belabor the point
472 // (that it's a variant) for E0573 "expected type, found variant".
473 let preamble = if res.is_none() {
474 let others = match enum_candidates.len() {
476 2 => " and 1 other".to_owned(),
477 n => format!(" and {} others", n),
479 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
483 let msg = format!("{}try using the variant's enum", preamble);
485 err.span_suggestions(
488 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
489 Applicability::MachineApplicable,
493 // Try Levenshtein algorithm.
494 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
495 if path.len() == 1 && self.self_type_is_available() {
496 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
497 let self_is_available = self.self_value_is_available(path[0].ident.span);
499 AssocSuggestion::Field => {
500 if self_is_available {
503 "you might have meant to use the available field",
504 format!("self.{path_str}"),
505 Applicability::MachineApplicable,
508 err.span_label(span, "a field by this name exists in `Self`");
511 AssocSuggestion::MethodWithSelf if self_is_available => {
514 "you might have meant to call the method",
515 format!("self.{path_str}"),
516 Applicability::MachineApplicable,
519 AssocSuggestion::MethodWithSelf
520 | AssocSuggestion::AssocFn
521 | AssocSuggestion::AssocConst
522 | AssocSuggestion::AssocType => {
525 &format!("you might have meant to {}", candidate.action()),
526 format!("Self::{path_str}"),
527 Applicability::MachineApplicable,
531 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
532 return (err, candidates);
535 // If the first argument in call is `self` suggest calling a method.
536 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
537 let mut args_snippet = String::new();
538 if let Some(args_span) = args_span {
539 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
540 args_snippet = snippet;
546 &format!("try calling `{ident}` as a method"),
547 format!("self.{path_str}({args_snippet})"),
548 Applicability::MachineApplicable,
550 return (err, candidates);
554 // Try context-dependent help if relaxed lookup didn't work.
555 if let Some(res) = res {
556 if self.smart_resolve_context_dependent_help(
562 &base_error.fallback_label,
564 // We do this to avoid losing a secondary span when we override the main error span.
565 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
566 return (err, candidates);
571 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
572 if !self.type_ascription_suggestion(&mut err, base_error.span) {
573 let mut fallback = false;
575 PathSource::Trait(AliasPossibility::Maybe),
576 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
578 ) = (source, res, is_macro)
580 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
582 let spans: Vec<Span> = bounds
584 .map(|bound| bound.span())
585 .filter(|&sp| sp != base_error.span)
588 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
589 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
590 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
591 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
592 let last_bound_span = spans.last().cloned().unwrap();
593 let mut multi_span: MultiSpan = spans.clone().into();
595 let msg = if sp == last_bound_span {
597 "...because of {these} bound{s}",
598 these = pluralize!("this", bounds.len() - 1),
599 s = pluralize!(bounds.len() - 1),
604 multi_span.push_span_label(sp, msg);
607 .push_span_label(base_error.span, "expected this type to be a trait...");
610 "`+` is used to constrain a \"trait object\" type with lifetimes or \
611 auto-traits; structs and enums can't be bound in that way",
613 if bounds.iter().all(|bound| match bound {
614 ast::GenericBound::Outlives(_) => true,
615 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
617 let mut sugg = vec![];
618 if base_error.span != start_span {
619 sugg.push((start_span.until(base_error.span), String::new()));
621 if base_error.span != end_span {
622 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
625 err.multipart_suggestion(
626 "if you meant to use a type and not a trait here, remove the bounds",
628 Applicability::MaybeIncorrect,
634 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
636 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
638 match self.diagnostic_metadata.current_let_binding {
639 Some((pat_sp, Some(ty_sp), None))
640 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
642 err.span_suggestion_short(
643 pat_sp.between(ty_sp),
644 "use `=` if you meant to assign",
646 Applicability::MaybeIncorrect,
652 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
653 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
654 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
658 err.span_label(base_error.span, base_error.fallback_label);
661 if let Some(err_code) = &err.code {
662 if err_code == &rustc_errors::error_code!(E0425) {
663 for label_rib in &self.label_ribs {
664 for (label_ident, node_id) in &label_rib.bindings {
665 if format!("'{}", ident) == label_ident.to_string() {
666 err.span_label(label_ident.span, "a label with a similar name exists");
667 if let PathSource::Expr(Some(Expr {
668 kind: ExprKind::Break(None, Some(_)),
674 "use the similarly named label",
676 Applicability::MaybeIncorrect,
678 // Do not lint against unused label when we suggest them.
679 self.diagnostic_metadata.unused_labels.remove(node_id);
684 } else if err_code == &rustc_errors::error_code!(E0412) {
685 if let Some(correct) = Self::likely_rust_type(path) {
688 "perhaps you intended to use this type",
690 Applicability::MaybeIncorrect,
699 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
700 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
701 let TyKind::Path(_, path) = &ty.kind else { return; };
702 for segment in &path.segments {
703 let Some(params) = &segment.args else { continue; };
704 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
705 for param in ¶ms.args {
706 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
707 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
710 for bound in bounds {
711 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
716 if base_span == trait_ref.span {
717 err.span_suggestion_verbose(
718 constraint.ident.span.between(trait_ref.span),
719 "you might have meant to write a path instead of an associated type bound",
721 Applicability::MachineApplicable,
729 fn suggest_swapping_misplaced_self_ty_and_trait(
731 err: &mut Diagnostic,
732 source: PathSource<'_>,
736 if let Some((trait_ref, self_ty)) =
737 self.diagnostic_metadata.currently_processing_impl_trait.clone()
738 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
739 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
740 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
741 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
742 && trait_ref.path.span == span
743 && let PathSource::Trait(_) = source
744 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
745 && let Ok(self_ty_str) =
746 self.r.session.source_map().span_to_snippet(self_ty.span)
747 && let Ok(trait_ref_str) =
748 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
750 err.multipart_suggestion(
751 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
752 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
753 Applicability::MaybeIncorrect,
758 fn get_single_associated_item(
761 source: &PathSource<'_>,
762 filter_fn: &impl Fn(Res) -> bool,
763 ) -> Option<TypoSuggestion> {
764 if let crate::PathSource::TraitItem(_) = source {
765 let mod_path = &path[..path.len() - 1];
766 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
767 self.resolve_path(mod_path, None, None)
769 let resolutions = self.r.resolutions(module).borrow();
770 let targets: Vec<_> =
773 .filter_map(|(key, resolution)| {
774 resolution.borrow().binding.map(|binding| binding.res()).and_then(
775 |res| if filter_fn(res) { Some((key, res)) } else { None },
779 if targets.len() == 1 {
780 let target = targets[0];
781 return Some(TypoSuggestion::single_item_from_res(
791 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
792 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
793 // Detect that we are actually in a `where` predicate.
794 let (bounded_ty, bounds, where_span) =
795 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
797 bound_generic_params,
800 })) = self.diagnostic_metadata.current_where_predicate
802 if !bound_generic_params.is_empty() {
805 (bounded_ty, bounds, span)
810 // Confirm that the target is an associated type.
811 let (ty, position, path) = if let ast::TyKind::Path(
812 Some(ast::QSelf { ty, position, .. }),
816 // use this to verify that ident is a type param.
817 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
821 partial_res.base_res(),
822 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
823 ) && partial_res.unresolved_segments() == 0)
832 let peeled_ty = ty.peel_refs();
833 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
834 // Confirm that the `SelfTy` is a type parameter.
835 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
839 partial_res.base_res(),
840 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
841 ) && partial_res.unresolved_segments() == 0)
846 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
847 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
848 ) = (&type_param_path.segments[..], &bounds[..])
850 if let [ast::PathSegment { ident, args: None, .. }] =
851 &poly_trait_ref.trait_ref.path.segments[..]
853 if ident.span == span {
854 err.span_suggestion_verbose(
856 &format!("constrain the associated type to `{}`", ident),
862 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
863 .unwrap_or_else(|_| constrain_ident.to_string()),
864 path.segments[..*position]
866 .map(|segment| path_segment_to_string(segment))
869 path.segments[*position..]
871 .map(|segment| path_segment_to_string(segment))
876 Applicability::MaybeIncorrect,
886 /// Check if the source is call expression and the first argument is `self`. If true,
887 /// return the span of whole call and the span for all arguments expect the first one (`self`).
888 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
889 let mut has_self_arg = None;
890 if let PathSource::Expr(Some(parent)) = source {
892 ExprKind::Call(_, args) if !args.is_empty() => {
893 let mut expr_kind = &args[0].kind;
896 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
897 if arg_name.segments[0].ident.name == kw::SelfLower {
898 let call_span = parent.span;
899 let tail_args_span = if args.len() > 1 {
902 args.last().unwrap().span.hi(),
909 has_self_arg = Some((call_span, tail_args_span));
913 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
924 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
925 // HACK(estebank): find a better way to figure out that this was a
926 // parser issue where a struct literal is being used on an expression
927 // where a brace being opened means a block is being started. Look
928 // ahead for the next text to see if `span` is followed by a `{`.
929 let sm = self.r.session.source_map();
932 sp = sm.next_point(sp);
933 match sm.span_to_snippet(sp) {
935 if snippet.chars().any(|c| !c.is_whitespace()) {
942 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
943 // In case this could be a struct literal that needs to be surrounded
944 // by parentheses, find the appropriate span.
946 let mut closing_brace = None;
948 sp = sm.next_point(sp);
949 match sm.span_to_snippet(sp) {
952 closing_brace = Some(span.to(sp));
959 // The bigger the span, the more likely we're incorrect --
960 // bound it to 100 chars long.
965 (followed_by_brace, closing_brace)
968 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
970 /// Returns `true` if able to provide context-dependent help.
971 fn smart_resolve_context_dependent_help(
973 err: &mut Diagnostic,
975 source: PathSource<'_>,
978 fallback_label: &str,
980 let ns = source.namespace();
981 let is_expected = &|res| source.is_expected(res);
983 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
984 ExprKind::Field(_, ident) => {
987 "use the path separator to refer to an item",
988 format!("{}::{}", path_str, ident),
989 Applicability::MaybeIncorrect,
993 ExprKind::MethodCall(ref segment, ..) => {
994 let span = expr.span.with_hi(segment.ident.span.hi());
997 "use the path separator to refer to an item",
998 format!("{}::{}", path_str, segment.ident),
999 Applicability::MaybeIncorrect,
1006 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1008 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1009 | PathSource::TupleStruct(span, _) => {
1010 // We want the main underline to cover the suggested code as well for
1012 err.set_span(*span);
1019 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1020 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1023 PathSource::Expr(Some(
1024 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1025 )) if path_sep(err, &parent) => {}
1031 | ExprKind::Binary(..)
1032 | ExprKind::Unary(..)
1034 | ExprKind::While(..)
1035 | ExprKind::ForLoop(..)
1036 | ExprKind::Match(..),
1039 ) if followed_by_brace => {
1040 if let Some(sp) = closing_brace {
1041 err.span_label(span, fallback_label);
1042 err.multipart_suggestion(
1043 "surround the struct literal with parentheses",
1045 (sp.shrink_to_lo(), "(".to_string()),
1046 (sp.shrink_to_hi(), ")".to_string()),
1048 Applicability::MaybeIncorrect,
1052 span, // Note the parentheses surrounding the suggestion below
1054 "you might want to surround a struct literal with parentheses: \
1055 `({} {{ /* fields */ }})`?",
1061 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1062 let span = find_span(&source, err);
1063 if let Some(span) = self.def_span(def_id) {
1064 err.span_label(span, &format!("`{}` defined here", path_str));
1066 let (tail, descr, applicability) = match source {
1067 PathSource::Pat | PathSource::TupleStruct(..) => {
1068 ("", "pattern", Applicability::MachineApplicable)
1070 _ => (": val", "literal", Applicability::HasPlaceholders),
1072 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1076 .map(|f| format!("{}{}", f.node, tail))
1077 .collect::<Vec<String>>()
1081 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1083 let pad = match self.r.field_names.get(&def_id) {
1084 Some(fields) if fields.is_empty() => "",
1087 err.span_suggestion(
1089 &format!("use struct {} syntax instead", descr),
1090 format!("{path_str} {{{pad}{fields}{pad}}}"),
1095 err.span_label(span, fallback_label);
1100 match (res, source) {
1102 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1103 PathSource::Expr(Some(Expr {
1104 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1106 | PathSource::Struct,
1108 err.span_label(span, fallback_label);
1109 err.span_suggestion_verbose(
1110 span.shrink_to_hi(),
1111 "use `!` to invoke the macro",
1113 Applicability::MaybeIncorrect,
1115 if path_str == "try" && span.rust_2015() {
1116 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1119 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1120 err.span_label(span, fallback_label);
1122 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1123 err.span_label(span, "type aliases cannot be used as traits");
1124 if self.r.session.is_nightly_build() {
1125 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1127 if let Some(span) = self.def_span(def_id) {
1128 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1129 // The span contains a type alias so we should be able to
1130 // replace `type` with `trait`.
1131 let snip = snip.replacen("type", "trait", 1);
1132 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1134 err.span_help(span, msg);
1141 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1142 if !path_sep(err, &parent) {
1147 Res::Def(DefKind::Enum, def_id),
1148 PathSource::TupleStruct(..) | PathSource::Expr(..),
1151 .diagnostic_metadata
1152 .current_type_ascription
1158 .type_ascription_path_suggestions
1164 err.downgrade_to_delayed_bug();
1165 // We already suggested changing `:` into `::` during parsing.
1169 self.suggest_using_enum_variant(err, source, def_id, span);
1171 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1172 let (ctor_def, ctor_vis, fields) =
1173 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1174 if let PathSource::Expr(Some(parent)) = source {
1175 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1176 bad_struct_syntax_suggestion(def_id);
1182 bad_struct_syntax_suggestion(def_id);
1186 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1187 if !is_expected(ctor_def) || is_accessible {
1191 let field_spans = match source {
1192 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1193 PathSource::TupleStruct(_, pattern_spans) => {
1194 err.set_primary_message(
1195 "cannot match against a tuple struct which contains private fields",
1198 // Use spans of the tuple struct pattern.
1199 Some(Vec::from(pattern_spans))
1201 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1202 _ if source.is_call() => {
1203 err.set_primary_message(
1204 "cannot initialize a tuple struct which contains private fields",
1207 // Use spans of the tuple struct definition.
1211 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1216 if let Some(spans) =
1217 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1219 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1220 .filter(|(vis, _)| {
1221 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1223 .map(|(_, span)| *span)
1226 if non_visible_spans.len() > 0 {
1227 let mut m: MultiSpan = non_visible_spans.clone().into();
1230 .for_each(|s| m.push_span_label(s, "private field"));
1231 err.span_note(m, "constructor is not visible here due to private fields");
1237 err.span_label(span, "constructor is not visible here due to private fields");
1241 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1245 ) if ns == ValueNS => {
1246 bad_struct_syntax_suggestion(def_id);
1248 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1250 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1251 let span = find_span(&source, err);
1252 if let Some(span) = self.def_span(def_id) {
1253 err.span_label(span, &format!("`{}` defined here", path_str));
1255 err.span_suggestion(
1257 "use this syntax instead",
1259 Applicability::MaybeIncorrect,
1265 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1266 if let Some(span) = self.def_span(def_id) {
1267 err.span_label(span, &format!("`{}` defined here", path_str));
1269 let fields = self.r.field_names.get(&def_id).map_or_else(
1270 || "/* fields */".to_string(),
1271 |fields| vec!["_"; fields.len()].join(", "),
1273 err.span_suggestion(
1275 "use the tuple variant pattern syntax instead",
1276 format!("{}({})", path_str, fields),
1277 Applicability::HasPlaceholders,
1280 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1281 err.span_label(span, fallback_label);
1282 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1284 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1285 err.note("can't use a type alias as a constructor");
1292 /// Given the target `ident` and `kind`, search for the similarly named associated item
1293 /// in `self.current_trait_ref`.
1294 pub(crate) fn find_similarly_named_assoc_item(
1297 kind: &AssocItemKind,
1298 ) -> Option<Symbol> {
1299 let (module, _) = self.current_trait_ref.as_ref()?;
1300 if ident == kw::Underscore {
1301 // We do nothing for `_`.
1305 let resolutions = self.r.resolutions(module);
1306 let targets = resolutions
1309 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1310 .filter(|(_, res)| match (kind, res) {
1311 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1312 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1313 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1316 .map(|(key, _)| key.ident.name)
1317 .collect::<Vec<_>>();
1319 find_best_match_for_name(&targets, ident, None)
1322 fn lookup_assoc_candidate<FilterFn>(
1326 filter_fn: FilterFn,
1327 ) -> Option<AssocSuggestion>
1329 FilterFn: Fn(Res) -> bool,
1331 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1333 TyKind::Path(None, _) => Some(t.id),
1334 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1335 // This doesn't handle the remaining `Ty` variants as they are not
1336 // that commonly the self_type, it might be interesting to provide
1337 // support for those in future.
1342 // Fields are generally expected in the same contexts as locals.
1343 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1344 if let Some(node_id) =
1345 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1347 // Look for a field with the same name in the current self_type.
1348 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1349 match resolution.base_res() {
1350 Res::Def(DefKind::Struct | DefKind::Union, did)
1351 if resolution.unresolved_segments() == 0 =>
1353 if let Some(field_names) = self.r.field_names.get(&did) {
1356 .any(|&field_name| ident.name == field_name.node)
1358 return Some(AssocSuggestion::Field);
1368 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1369 for assoc_item in items {
1370 if assoc_item.ident == ident {
1371 return Some(match &assoc_item.kind {
1372 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1373 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1374 AssocSuggestion::MethodWithSelf
1376 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1377 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1378 ast::AssocItemKind::MacCall(_) => continue,
1384 // Look for associated items in the current trait.
1385 if let Some((module, _)) = self.current_trait_ref {
1386 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1387 ModuleOrUniformRoot::Module(module),
1392 let res = binding.res();
1394 if self.r.has_self.contains(&res.def_id()) {
1395 return Some(AssocSuggestion::MethodWithSelf);
1398 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1399 Res::Def(DefKind::AssocConst, _) => {
1400 return Some(AssocSuggestion::AssocConst);
1402 Res::Def(DefKind::AssocTy, _) => {
1403 return Some(AssocSuggestion::AssocType);
1415 fn lookup_typo_candidate(
1419 filter_fn: &impl Fn(Res) -> bool,
1420 ) -> Option<TypoSuggestion> {
1421 let mut names = Vec::new();
1422 if path.len() == 1 {
1423 // Search in lexical scope.
1424 // Walk backwards up the ribs in scope and collect candidates.
1425 for rib in self.ribs[ns].iter().rev() {
1426 // Locals and type parameters
1427 for (ident, &res) in &rib.bindings {
1429 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1433 if let RibKind::ModuleRibKind(module) = rib.kind {
1434 // Items from this module
1435 self.r.add_module_candidates(module, &mut names, &filter_fn);
1437 if let ModuleKind::Block(..) = module.kind {
1438 // We can see through blocks
1440 // Items from the prelude
1441 if !module.no_implicit_prelude {
1442 let extern_prelude = self.r.extern_prelude.clone();
1443 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1444 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1447 Res::Def(DefKind::Mod, crate_id.as_def_id());
1449 if filter_fn(crate_mod) {
1450 Some(TypoSuggestion::typo_from_res(
1451 ident.name, crate_mod,
1460 if let Some(prelude) = self.r.prelude {
1461 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1468 // Add primitive types to the mix
1469 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1470 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1471 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1475 // Search in module.
1476 let mod_path = &path[..path.len() - 1];
1477 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1478 self.resolve_path(mod_path, Some(TypeNS), None)
1480 self.r.add_module_candidates(module, &mut names, &filter_fn);
1484 let name = path[path.len() - 1].ident.name;
1485 // Make sure error reporting is deterministic.
1486 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1488 match find_best_match_for_name(
1489 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1493 Some(found) if found != name => {
1494 names.into_iter().find(|suggestion| suggestion.candidate == found)
1500 // Returns the name of the Rust type approximately corresponding to
1501 // a type name in another programming language.
1502 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1503 let name = path[path.len() - 1].ident.as_str();
1504 // Common Java types
1506 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1507 "short" => sym::i16,
1508 "Bool" => sym::bool,
1509 "Boolean" => sym::bool,
1510 "boolean" => sym::bool,
1513 "float" => sym::f32,
1514 "double" => sym::f64,
1519 /// Only used in a specific case of type ascription suggestions
1520 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1521 let sm = self.r.session.source_map();
1522 start.to(sm.next_point(start))
1525 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1526 let sm = self.r.session.source_map();
1527 let base_snippet = sm.span_to_snippet(base_span);
1528 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1529 if let Ok(snippet) = sm.span_to_snippet(sp) {
1530 let len = snippet.trim_end().len() as u32;
1531 if snippet.trim() == ":" {
1533 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1534 let mut show_label = true;
1535 if sm.is_multiline(sp) {
1536 err.span_suggestion_short(
1538 "maybe you meant to write `;` here",
1540 Applicability::MaybeIncorrect,
1543 let after_colon_sp =
1544 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1545 if snippet.len() == 1 {
1547 err.span_suggestion(
1549 "maybe you meant to write a path separator here",
1551 Applicability::MaybeIncorrect,
1558 .type_ascription_path_suggestions
1562 err.downgrade_to_delayed_bug();
1565 if let Ok(base_snippet) = base_snippet {
1566 let mut sp = after_colon_sp;
1568 // Try to find an assignment
1569 sp = sm.next_point(sp);
1570 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1572 Ok(ref x) if x.as_str() == "=" => {
1573 err.span_suggestion(
1575 "maybe you meant to write an assignment here",
1576 format!("let {}", base_snippet),
1577 Applicability::MaybeIncorrect,
1582 Ok(ref x) if x.as_str() == "\n" => break,
1592 "expecting a type here because of type ascription",
1602 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1603 let mut result = None;
1604 let mut seen_modules = FxHashSet::default();
1605 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1607 while let Some((in_module, path_segments)) = worklist.pop() {
1608 // abort if the module is already found
1609 if result.is_some() {
1613 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1614 // abort if the module is already found or if name_binding is private external
1615 if result.is_some() || !name_binding.vis.is_visible_locally() {
1618 if let Some(module) = name_binding.module() {
1620 let mut path_segments = path_segments.clone();
1621 path_segments.push(ast::PathSegment::from_ident(ident));
1622 let module_def_id = module.def_id();
1623 if module_def_id == def_id {
1625 Path { span: name_binding.span, segments: path_segments, tokens: None };
1637 // add the module to the lookup
1638 if seen_modules.insert(module_def_id) {
1639 worklist.push((module, path_segments));
1649 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1650 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1651 let mut variants = Vec::new();
1652 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1653 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1654 let mut segms = enum_import_suggestion.path.segments.clone();
1655 segms.push(ast::PathSegment::from_ident(ident));
1656 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1657 variants.push((path, def_id, kind));
1664 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1665 fn suggest_using_enum_variant(
1667 err: &mut Diagnostic,
1668 source: PathSource<'_>,
1672 let Some(variants) = self.collect_enum_ctors(def_id) else {
1673 err.note("you might have meant to use one of the enum's variants");
1677 let suggest_only_tuple_variants =
1678 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1679 if suggest_only_tuple_variants {
1680 // Suggest only tuple variants regardless of whether they have fields and do not
1681 // suggest path with added parentheses.
1682 let suggestable_variants = variants
1684 .filter(|(.., kind)| *kind == CtorKind::Fn)
1685 .map(|(variant, ..)| path_names_to_string(variant))
1686 .collect::<Vec<_>>();
1688 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1690 let source_msg = if source.is_call() {
1692 } else if matches!(source, PathSource::TupleStruct(..)) {
1698 if !suggestable_variants.is_empty() {
1699 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1700 format!("try {} the enum's variant", source_msg)
1702 format!("try {} one of the enum's variants", source_msg)
1705 err.span_suggestions(
1708 suggestable_variants.into_iter(),
1709 Applicability::MaybeIncorrect,
1713 // If the enum has no tuple variants..
1714 if non_suggestable_variant_count == variants.len() {
1715 err.help(&format!("the enum has no tuple variants {}", source_msg));
1718 // If there are also non-tuple variants..
1719 if non_suggestable_variant_count == 1 {
1721 "you might have meant {} the enum's non-tuple variant",
1724 } else if non_suggestable_variant_count >= 1 {
1726 "you might have meant {} one of the enum's non-tuple variants",
1731 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1732 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1734 CtorKind::Const => false,
1735 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1740 let mut suggestable_variants = variants
1742 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1743 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1744 .map(|(variant, kind)| match kind {
1745 CtorKind::Const => variant,
1746 CtorKind::Fn => format!("({}())", variant),
1747 CtorKind::Fictive => format!("({} {{}})", variant),
1749 .collect::<Vec<_>>();
1751 if !suggestable_variants.is_empty() {
1752 let msg = if suggestable_variants.len() == 1 {
1753 "you might have meant to use the following enum variant"
1755 "you might have meant to use one of the following enum variants"
1758 err.span_suggestions(
1761 suggestable_variants.drain(..),
1762 Applicability::MaybeIncorrect,
1766 let suggestable_variants_with_placeholders = variants
1768 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1769 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1770 .filter_map(|(variant, kind)| match kind {
1771 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1772 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1775 .collect::<Vec<_>>();
1777 if !suggestable_variants_with_placeholders.is_empty() {
1779 suggestable_variants.is_empty(),
1780 suggestable_variants_with_placeholders.len(),
1782 (true, 1) => "the following enum variant is available",
1783 (true, _) => "the following enum variants are available",
1784 (false, 1) => "alternatively, the following enum variant is available",
1785 (false, _) => "alternatively, the following enum variants are also available",
1788 err.span_suggestions(
1791 suggestable_variants_with_placeholders.into_iter(),
1792 Applicability::HasPlaceholders,
1797 if def_id.is_local() {
1798 if let Some(span) = self.def_span(def_id) {
1799 err.span_note(span, "the enum is defined here");
1804 pub(crate) fn report_missing_type_error(
1807 ) -> Option<(Span, &'static str, String, Applicability)> {
1808 let (ident, span) = match path {
1809 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
1810 (segment.ident.to_string(), segment.ident.span)
1814 let mut iter = ident.chars().map(|c| c.is_uppercase());
1815 let single_uppercase_char =
1816 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1817 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1820 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1821 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1822 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1827 kind @ ItemKind::Fn(..)
1828 | kind @ ItemKind::Enum(..)
1829 | kind @ ItemKind::Struct(..)
1830 | kind @ ItemKind::Union(..),
1835 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1836 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1837 | (Some(Item { kind, .. }), false, _) => {
1838 // Likely missing type parameter.
1839 if let Some(generics) = kind.generics() {
1840 if span.overlaps(generics.span) {
1841 // Avoid the following:
1842 // error[E0405]: cannot find trait `A` in this scope
1843 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1845 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1846 // | ^- help: you might be missing a type parameter: `, A`
1848 // | not found in this scope
1851 let msg = "you might be missing a type parameter";
1852 let (span, sugg) = if let [.., param] = &generics.params[..] {
1853 let span = if let [.., bound] = ¶m.bounds[..] {
1855 } else if let GenericParam {
1856 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1858 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1862 (span, format!(", {}", ident))
1864 (generics.span, format!("<{}>", ident))
1866 // Do not suggest if this is coming from macro expansion.
1867 if span.can_be_used_for_suggestions() {
1869 span.shrink_to_hi(),
1872 Applicability::MaybeIncorrect,
1882 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1883 /// optionally returning the closest match and whether it is reachable.
1884 pub(crate) fn suggestion_for_label_in_rib(
1888 ) -> Option<LabelSuggestion> {
1889 // Are ribs from this `rib_index` within scope?
1890 let within_scope = self.is_label_valid_from_rib(rib_index);
1892 let rib = &self.label_ribs[rib_index];
1896 .filter(|(id, _)| id.span.eq_ctxt(label.span))
1897 .map(|(id, _)| id.name)
1898 .collect::<Vec<Symbol>>();
1900 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1901 // Upon finding a similar name, get the ident that it was from - the span
1902 // contained within helps make a useful diagnostic. In addition, determine
1903 // whether this candidate is within scope.
1904 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1905 (*ident, within_scope)
1909 pub(crate) fn maybe_report_lifetime_uses(
1911 generics_span: Span,
1912 params: &[ast::GenericParam],
1914 for (param_index, param) in params.iter().enumerate() {
1915 let GenericParamKind::Lifetime = param.kind else { continue };
1917 let def_id = self.r.local_def_id(param.id);
1919 let use_set = self.lifetime_uses.remove(&def_id);
1921 "Use set for {:?}({:?} at {:?}) is {:?}",
1922 def_id, param.ident, param.ident.span, use_set
1925 let deletion_span = || {
1926 if params.len() == 1 {
1927 // if sole lifetime, remove the entire `<>` brackets
1929 } else if param_index == 0 {
1930 // if removing within `<>` brackets, we also want to
1931 // delete a leading or trailing comma as appropriate
1932 param.span().to(params[param_index + 1].span().shrink_to_lo())
1934 // if removing within `<>` brackets, we also want to
1935 // delete a leading or trailing comma as appropriate
1936 params[param_index - 1].span().shrink_to_hi().to(param.span())
1940 Some(LifetimeUseSet::Many) => {}
1941 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1942 debug!(?param.ident, ?param.ident.span, ?use_span);
1944 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1946 let deletion_span = deletion_span();
1947 self.r.lint_buffer.buffer_lint_with_diagnostic(
1948 lint::builtin::SINGLE_USE_LIFETIMES,
1951 &format!("lifetime parameter `{}` only used once", param.ident),
1952 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1953 param_span: param.ident.span,
1954 use_span: Some((use_span, elidable)),
1960 debug!(?param.ident, ?param.ident.span);
1962 let deletion_span = deletion_span();
1963 self.r.lint_buffer.buffer_lint_with_diagnostic(
1964 lint::builtin::UNUSED_LIFETIMES,
1967 &format!("lifetime parameter `{}` never used", param.ident),
1968 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1969 param_span: param.ident.span,
1979 pub(crate) fn emit_undeclared_lifetime_error(
1981 lifetime_ref: &ast::Lifetime,
1982 outer_lifetime_ref: Option<Ident>,
1984 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1985 let mut err = if let Some(outer) = outer_lifetime_ref {
1986 let mut err = struct_span_err!(
1988 lifetime_ref.ident.span,
1990 "can't use generic parameters from outer item",
1992 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1993 err.span_label(outer.span, "lifetime parameter from outer item");
1996 let mut err = struct_span_err!(
1998 lifetime_ref.ident.span,
2000 "use of undeclared lifetime name `{}`",
2003 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2006 let mut suggest_note = true;
2008 for rib in self.lifetime_ribs.iter().rev() {
2010 LifetimeRibKind::Generics { binder: _, span, kind } => {
2011 if !span.can_be_used_for_suggestions() && suggest_note {
2012 suggest_note = false; // Avoid displaying the same help multiple times.
2016 "lifetime `{}` is missing in item created through this procedural macro",
2023 let higher_ranked = matches!(
2025 LifetimeBinderKind::BareFnType
2026 | LifetimeBinderKind::PolyTrait
2027 | LifetimeBinderKind::WhereBound
2029 let (span, sugg) = if span.is_empty() {
2032 if higher_ranked { "for" } else { "" },
2034 if higher_ranked { " " } else { "" },
2039 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2040 let sugg = format!("{}, ", lifetime_ref.ident);
2044 err.span_suggestion(
2047 "consider making the {} lifetime-generic with a new `{}` lifetime",
2052 Applicability::MaybeIncorrect,
2055 "for more information on higher-ranked polymorphism, visit \
2056 https://doc.rust-lang.org/nomicon/hrtb.html",
2059 err.span_suggestion(
2061 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
2063 Applicability::MaybeIncorrect,
2067 LifetimeRibKind::Item => break,
2075 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2078 lifetime_ref.ident.span,
2080 "use of non-static lifetime `{}` in const generic",
2084 "for more information, see issue #74052 \
2085 <https://github.com/rust-lang/rust/issues/74052>",
2090 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2091 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2092 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2093 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2095 lifetime_ref: &ast::Lifetime,
2097 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2098 if !feature_active {
2100 &self.r.session.parse_sess,
2101 sym::generic_const_exprs,
2102 lifetime_ref.ident.span,
2103 "a non-static lifetime is not allowed in a `const`",
2110 /// Report lifetime/lifetime shadowing as an error.
2111 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2112 let mut err = struct_span_err!(
2116 "lifetime name `{}` shadows a lifetime name that is already in scope",
2119 err.span_label(orig.span, "first declared here");
2120 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2124 /// Shadowing involving a label is only a warning for historical reasons.
2125 //FIXME: make this a proper lint.
2126 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2127 let name = shadower.name;
2128 let shadower = shadower.span;
2129 let mut err = sess.struct_span_warn(
2131 &format!("label name `{}` shadows a label name that is already in scope", name),
2133 err.span_label(orig, "first declared here");
2134 err.span_label(shadower, format!("label `{}` already in scope", name));
2138 impl<'tcx> LifetimeContext<'_, 'tcx> {
2139 pub(crate) fn report_missing_lifetime_specifiers(
2143 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2148 "missing lifetime specifier{}",
2153 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
2154 pub(crate) fn report_elision_failure(
2156 diag: &mut Diagnostic,
2157 params: &[ElisionFailureInfo],
2159 let mut m = String::new();
2160 let len = params.len();
2162 let elided_params: Vec<_> =
2163 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2165 let elided_len = elided_params.len();
2167 for (i, info) in elided_params.into_iter().enumerate() {
2168 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2171 diag.span_label(span, "");
2172 let help_name = if let Some(ident) =
2173 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2175 format!("`{}`", ident)
2177 format!("argument {}", index + 1)
2185 "one of {}'s {} {}lifetimes",
2188 if have_bound_regions { "free " } else { "" }
2193 if elided_len == 2 && i == 0 {
2195 } else if i + 2 == elided_len {
2196 m.push_str(", or ");
2197 } else if i != elided_len - 1 {
2204 "this function's return type contains a borrowed value, \
2205 but there is no value for it to be borrowed from",
2208 } else if elided_len == 0 {
2210 "this function's return type contains a borrowed value with \
2211 an elided lifetime, but the lifetime cannot be derived from \
2215 } else if elided_len == 1 {
2217 "this function's return type contains a borrowed value, \
2218 but the signature does not say which {} it is borrowed from",
2224 "this function's return type contains a borrowed value, \
2225 but the signature does not say whether it is borrowed from {}",
2232 pub(crate) fn is_trait_ref_fn_scope(
2234 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
2236 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2238 self.tcx.lang_items().fn_once_trait(),
2239 self.tcx.lang_items().fn_trait(),
2240 self.tcx.lang_items().fn_mut_trait(),
2242 .contains(&Some(did))
2244 let (span, span_type) = if let Some(bound) =
2245 trait_ref.bound_generic_params.iter().rfind(|param| {
2248 hir::GenericParamKind::Lifetime {
2249 kind: hir::LifetimeParamKind::Explicit
2253 (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail)
2255 (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty)
2257 self.missing_named_lifetime_spots
2258 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2265 pub(crate) fn add_missing_lifetime_specifiers_label(
2267 err: &mut Diagnostic,
2268 mut spans_with_counts: Vec<(Span, usize)>,
2269 in_scope_lifetimes: FxIndexSet<LocalDefId>,
2270 params: Option<&[ElisionFailureInfo]>,
2272 let (mut lifetime_names, lifetime_spans): (FxHashSet<_>, Vec<_>) = in_scope_lifetimes
2274 .filter_map(|def_id| {
2275 let name = self.tcx.item_name(def_id.to_def_id());
2276 let span = self.tcx.def_ident_span(def_id.to_def_id())?;
2279 .filter(|&(n, _)| n != kw::UnderscoreLifetime)
2282 if let Some(params) = params {
2283 // If there's no lifetime available, suggest `'static`.
2284 if self.report_elision_failure(err, params) && lifetime_names.is_empty() {
2285 lifetime_names.insert(kw::StaticLifetime);
2288 let params = params.unwrap_or(&[]);
2290 let snippets: Vec<Option<String>> = spans_with_counts
2292 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2295 // Empty generics are marked with a span of "<", but since from now on
2296 // that information is in the snippets it can be removed from the spans.
2297 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2298 if snippet.as_deref() == Some("<") {
2299 *span = span.shrink_to_hi();
2303 for &(span, count) in &spans_with_counts {
2307 "expected {} lifetime parameter{}",
2308 if count == 1 { "named".to_string() } else { count.to_string() },
2314 let suggest_existing =
2315 |err: &mut Diagnostic,
2317 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2318 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2319 self.missing_named_lifetime_spots.iter().rev().next()
2321 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2322 // using `'a`, but also introduce the concept of HRLTs by suggesting
2323 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2324 let mut introduce_suggestion = vec![];
2326 let a_to_z_repeat_n = |n| {
2327 (b'a'..=b'z').map(move |c| {
2328 let mut s = '\''.to_string();
2329 s.extend(std::iter::repeat(char::from(c)).take(n));
2334 // If all single char lifetime names are present, we wrap around and double the chars.
2336 .flat_map(a_to_z_repeat_n)
2337 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2340 "consider making the {} lifetime-generic with a new `{}` lifetime",
2345 "for more information on higher-ranked polymorphism, visit \
2346 https://doc.rust-lang.org/nomicon/hrtb.html",
2348 let for_sugg = span_type.suggestion(<_name);
2349 for param in params {
2350 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2352 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2353 introduce_suggestion
2354 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2355 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2356 introduce_suggestion
2357 .push((param.span, format!("&{} {}", lt_name, stripped)));
2361 introduce_suggestion.push((*for_span, for_sugg));
2362 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2363 if let Some(formatter) = formatter {
2364 introduce_suggestion.push((*span, formatter(<_name)));
2367 err.multipart_suggestion_verbose(
2369 introduce_suggestion,
2370 Applicability::MaybeIncorrect,
2374 let spans_suggs: Vec<_> = formatters
2376 .zip(spans_with_counts.iter())
2377 .filter_map(|(formatter, (span, _))| {
2378 if let Some(formatter) = formatter {
2379 Some((*span, formatter(name)))
2385 if spans_suggs.is_empty() {
2386 // If all the spans come from macros, we cannot extract snippets and then
2387 // `formatters` only contains None and `spans_suggs` is empty.
2390 err.multipart_suggestion_verbose(
2392 "consider using the `{}` lifetime",
2393 lifetime_names.iter().next().unwrap()
2396 Applicability::MaybeIncorrect,
2399 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2400 for missing in self.missing_named_lifetime_spots.iter().rev() {
2401 let mut introduce_suggestion = vec![];
2404 introduce_suggestion.push(match missing {
2405 MissingLifetimeSpot::Generics(generics) => {
2406 if generics.span == DUMMY_SP {
2407 // Account for malformed generics in the HIR. This shouldn't happen,
2408 // but if we make a mistake elsewhere, mainly by keeping something in
2409 // `missing_named_lifetime_spots` that we shouldn't, like associated
2410 // `const`s or making a mistake in the AST lowering we would provide
2411 // nonsensical suggestions. Guard against that by skipping these.
2415 msg = "consider introducing a named lifetime parameter".to_string();
2416 should_break = true;
2417 if let Some(param) = generics.params.iter().find(|p| {
2420 hir::GenericParamKind::Type { synthetic: true, .. }
2421 | hir::GenericParamKind::Lifetime {
2422 kind: hir::LifetimeParamKind::Elided
2426 (param.span.shrink_to_lo(), "'a, ".to_string())
2428 (generics.span, "<'a>".to_string())
2431 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2433 "consider making the {} lifetime-generic with a new `'a` lifetime",
2436 should_break = false;
2438 "for more information on higher-ranked polymorphism, visit \
2439 https://doc.rust-lang.org/nomicon/hrtb.html",
2441 (*span, span_type.suggestion("'a"))
2443 MissingLifetimeSpot::Static => {
2444 let mut spans_suggs = Vec::new();
2445 for ((span, count), snippet) in
2446 spans_with_counts.iter().copied().zip(snippets.iter())
2448 let (span, sugg) = match snippet.as_deref() {
2449 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2450 Some("'_") => (span, "'static".to_owned()),
2451 Some(snippet) if !snippet.ends_with('>') => {
2455 std::iter::repeat("'static")
2457 .collect::<Vec<_>>()
2460 } else if snippet == "<" || snippet == "(" {
2462 span.shrink_to_hi(),
2463 std::iter::repeat("'static")
2465 .collect::<Vec<_>>()
2470 span.shrink_to_hi(),
2473 std::iter::repeat("'static")
2475 .collect::<Vec<_>>()
2483 spans_suggs.push((span, sugg.to_string()));
2485 err.multipart_suggestion_verbose(
2486 "consider using the `'static` lifetime",
2488 Applicability::MaybeIncorrect,
2494 struct Lifetime(Span, String);
2496 fn is_unnamed(&self) -> bool {
2497 self.1.starts_with('&') && !self.1.starts_with("&'")
2499 fn is_underscore(&self) -> bool {
2500 self.1.starts_with("&'_ ")
2502 fn is_named(&self) -> bool {
2503 self.1.starts_with("&'")
2505 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2509 self.is_underscore(),
2511 sugg.starts_with('&'),
2513 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2514 (true, _, _, true) => {
2515 (self.span_unnamed_borrow(), sugg[1..].to_string())
2517 (_, true, _, false) => {
2518 (self.span_underscore_borrow(), sugg.trim().to_string())
2520 (_, true, _, true) => {
2521 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2523 (_, _, true, false) => {
2524 (self.span_named_borrow(), sugg.trim().to_string())
2526 (_, _, true, true) => {
2527 (self.span_named_borrow(), sugg[1..].trim().to_string())
2533 fn span_unnamed_borrow(&self) -> Span {
2534 let lo = self.0.lo() + BytePos(1);
2535 self.0.with_lo(lo).with_hi(lo)
2537 fn span_named_borrow(&self) -> Span {
2538 let lo = self.0.lo() + BytePos(1);
2541 fn span_underscore_borrow(&self) -> Span {
2542 let lo = self.0.lo() + BytePos(1);
2543 let hi = lo + BytePos(2);
2544 self.0.with_lo(lo).with_hi(hi)
2548 for param in params {
2549 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2550 if let Some((span, sugg)) =
2551 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2553 introduce_suggestion.push((span, sugg));
2557 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2558 |((span, _), sugg)| match &sugg {
2559 Some(sugg) => Some((span, sugg.to_string())),
2563 let (span, sugg) = self
2567 .span_to_snippet(span)
2569 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2570 .unwrap_or((span, sugg));
2571 introduce_suggestion.push((span, sugg.to_string()));
2573 err.multipart_suggestion_verbose(
2575 introduce_suggestion,
2576 Applicability::MaybeIncorrect,
2584 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2585 match &lifetime_names[..] {
2587 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2588 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2590 suggs.push(match snippet.as_deref() {
2591 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2592 Some("'_") => Some(Box::new(|n| n.to_string())),
2593 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2594 Some("<") => Some(Box::new(move |n| {
2595 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2597 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2601 std::iter::repeat(name.to_string())
2603 .collect::<Vec<_>>()
2610 suggest_existing(err, name.as_str(), suggs);
2613 let mut suggs = Vec::new();
2614 for (snippet, (_, count)) in
2615 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2617 suggs.push(match snippet.as_deref() {
2618 Some("&") => Some("&'a ".to_string()),
2619 Some("'_") => Some("'a".to_string()),
2621 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2624 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2626 Some(snippet) => Some(format!(
2629 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2634 suggest_new(err, suggs);
2636 lts if lts.len() > 1 => {
2637 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2639 let mut spans_suggs: Vec<_> = Vec::new();
2640 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2641 match snippet.as_deref() {
2642 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2643 Some("&") => spans_suggs
2644 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2649 if spans_suggs.len() > 0 {
2650 // This happens when we have `Foo<T>` where we point at the space before `T`,
2651 // but this can be confusing so we give a suggestion with placeholders.
2652 err.multipart_suggestion_verbose(
2653 "consider using one of the available lifetimes here",
2655 Applicability::HasPlaceholders,
2659 _ => unreachable!(),