Suggest using anonymous lifetime in impl Trait return

This commit is contained in:
Esteban Küber 2019-03-04 11:52:03 -08:00
parent 33ef0bad21
commit ee2a9d93e9
2 changed files with 45 additions and 9 deletions

View file

@ -103,13 +103,43 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> {
error_var
);
let many = if let Ok(snippet) = self.tcx().sess.source_map().span_to_snippet(span) {
if "'static" == &named.to_string() && snippet.starts_with("impl ") {
diag.span_suggestion(
span,
"add explicit unnamed lifetime `'_` to the return type to constrain it",
format!("{} + '_", snippet),
Applicability::Unspecified,
);
true
} else {
false
}
} else {
false
};
if many {
diag.span_label(
span,
"`impl Trait` types can only capture lifetimes that they reference"
);
} else {
diag.span_label(span, format!("lifetime `{}` required", named));
}
diag.span_suggestion(
new_ty_span,
&format!("add explicit lifetime `{}` to {}", named, span_label_var),
new_ty.to_string(),
Applicability::Unspecified,
)
.span_label(span, format!("lifetime `{}` required", named));
new_ty_span,
&format!("{}add explicit lifetime `{}` to {}",
if many {
"otherwise, "
} else {
""
},
named,
span_label_var,
),
new_ty.to_string(),
Applicability::Unspecified,
);
Some(diag)
}

View file

@ -2,9 +2,15 @@ error[E0621]: explicit lifetime required in the type of `x`
--> $DIR/must_outlive_least_region_or_bound.rs:3:23
|
LL | fn elided(x: &i32) -> impl Copy { x }
| ---- ^^^^^^^^^ lifetime `'static` required
| |
| help: add explicit lifetime `'static` to the type of `x`: `&'static i32`
| ^^^^^^^^^ `impl Trait` types can only capture lifetimes that they reference
help: add explicit unnamed lifetime `'_` to the return type to constrain it
|
LL | fn elided(x: &i32) -> impl Copy + '_ { x }
| ^^^^^^^^^^^^^^
help: otherwise, add explicit lifetime `'static` to the type of `x`
|
LL | fn elided(x: &'static i32) -> impl Copy { x }
| ^^^^^^^^^^^^
error: cannot infer an appropriate lifetime
--> $DIR/must_outlive_least_region_or_bound.rs:6:44