Always constrain the return type in lifetime suggestion

```
error: lifetime may not live long enough
 --> f205.rs:8:16
  |
7 |     fn resolve_symbolic_reference(&self, reference: Option<Reference>) -> Option<Reference> {
  |                                   -      --------- has type `Option<Reference<'1>>`
  |                                   |
  |                                   let's call the lifetime of this reference `'2`
8 |         return reference;
  |                ^^^^^^^^^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
  |
help: consider introducing a named lifetime parameter
  |
7 |     fn resolve_symbolic_reference<'a>(&'a self, reference: Option<Reference<'a>>) -> Option<Reference<'a>> {
  |                                  ++++  ++                                  ++++                      ++++
```

The correct suggestion would be

```
help: consider introducing a named lifetime parameter
  |
7 |     fn resolve_symbolic_reference<'a>(&self, reference: Option<Reference<'a>>) -> Option<Reference<'a>> {
  |                                  ++++                                   ++++                      ++++
```

but we are not doing the analysis to detect that yet. If we constrain `&'a self`, then the return type with a borrow will implicitly take its lifetime from `'a`, it is better to make it explicit in the suggestion, in case that `&self` *doesn't* need to be `'a`, but the return does.
This commit is contained in:
Esteban Küber 2024-05-05 03:42:47 +00:00
parent 9f730e92f2
commit 120049fab4
11 changed files with 77 additions and 72 deletions

View file

@ -450,6 +450,11 @@ impl Subdiagnostic for AddLifetimeParamsSuggestion<'_> {
};
visitor.visit_ty(self.ty_sub);
visitor.visit_ty(self.ty_sup);
if let Some(fn_decl) = node.fn_decl()
&& let hir::FnRetTy::Return(ty) = fn_decl.output
{
visitor.visit_ty(ty);
}
if visitor.suggestions.is_empty() {
return false;
}