1
Fork 0

Fix lifetime suggestion for type aliases with objects in them

This commit is contained in:
Michael Goulet 2023-04-25 20:41:59 +00:00
parent 666fee2a5f
commit 183f1a6a70
4 changed files with 72 additions and 6 deletions

View file

@ -845,7 +845,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
return;
}
let Some((alias_tys, alias_span)) = self
let Some((alias_tys, alias_span, lt_addition_span)) = self
.infcx
.tcx
.return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) else { return; };
@ -858,10 +858,20 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
()
}
if let TyKind::TraitObject(_, lt, _) = alias_ty.kind {
spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
if lt.ident.name == kw::Empty {
spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
} else {
spans_suggs.push((lt.ident.span, "'a".to_string()));
}
}
}
spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
if let Some(lt_addition_span) = lt_addition_span {
spans_suggs.push((lt_addition_span, "'a, ".to_string()));
} else {
spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
}
diag.multipart_suggestion_verbose(
&format!(
"to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"

View file

@ -1116,11 +1116,13 @@ impl<'tcx> TyCtxt<'tcx> {
v.0
}
/// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in its return type and associated alias span when type alias is used
/// Given a `DefId` for an `fn`, return all the `dyn` and `impl` traits in
/// its return type, and the associated alias span when type alias is used,
/// along with a span for lifetime suggestion (if there are existing generics).
pub fn return_type_impl_or_dyn_traits_with_type_alias(
self,
scope_def_id: LocalDefId,
) -> Option<(Vec<&'tcx hir::Ty<'tcx>>, Span)> {
) -> Option<(Vec<&'tcx hir::Ty<'tcx>>, Span, Option<Span>)> {
let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id);
let mut v = TraitObjectVisitor(vec![], self.hir());
// when the return type is a type alias
@ -1134,7 +1136,7 @@ impl<'tcx> TyCtxt<'tcx> {
{
v.visit_ty(alias_ty);
if !v.0.is_empty() {
return Some((v.0, alias_generics.span));
return Some((v.0, alias_generics.span, alias_generics.span_for_lifetime_suggestion()));
}
}
return None;