diff --git a/src/librustc/infer/error_reporting/nice_region_error/named_anon_conflict.rs b/src/librustc/infer/error_reporting/nice_region_error/named_anon_conflict.rs index 3821484d38e..8b44aa5e706 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/named_anon_conflict.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/named_anon_conflict.rs @@ -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) } diff --git a/src/test/ui/impl-trait/must_outlive_least_region_or_bound.stderr b/src/test/ui/impl-trait/must_outlive_least_region_or_bound.stderr index 8a477e42a66..8a155d1c1b2 100644 --- a/src/test/ui/impl-trait/must_outlive_least_region_or_bound.stderr +++ b/src/test/ui/impl-trait/must_outlive_least_region_or_bound.stderr @@ -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