Skip to content

Commit ee2a9d9

Browse files
committed
Suggest using anonymous lifetime in impl Trait return
1 parent 33ef0ba commit ee2a9d9

File tree

2 files changed

+45
-9
lines changed

2 files changed

+45
-9
lines changed

src/librustc/infer/error_reporting/nice_region_error/named_anon_conflict.rs

+36-6
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,43 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> {
103103
error_var
104104
);
105105

106+
let many = if let Ok(snippet) = self.tcx().sess.source_map().span_to_snippet(span) {
107+
if "'static" == &named.to_string() && snippet.starts_with("impl ") {
108+
diag.span_suggestion(
109+
span,
110+
"add explicit unnamed lifetime `'_` to the return type to constrain it",
111+
format!("{} + '_", snippet),
112+
Applicability::Unspecified,
113+
);
114+
true
115+
} else {
116+
false
117+
}
118+
} else {
119+
false
120+
};
121+
if many {
122+
diag.span_label(
123+
span,
124+
"`impl Trait` types can only capture lifetimes that they reference"
125+
);
126+
} else {
127+
diag.span_label(span, format!("lifetime `{}` required", named));
128+
}
106129
diag.span_suggestion(
107-
new_ty_span,
108-
&format!("add explicit lifetime `{}` to {}", named, span_label_var),
109-
new_ty.to_string(),
110-
Applicability::Unspecified,
111-
)
112-
.span_label(span, format!("lifetime `{}` required", named));
130+
new_ty_span,
131+
&format!("{}add explicit lifetime `{}` to {}",
132+
if many {
133+
"otherwise, "
134+
} else {
135+
""
136+
},
137+
named,
138+
span_label_var,
139+
),
140+
new_ty.to_string(),
141+
Applicability::Unspecified,
142+
);
113143

114144
Some(diag)
115145
}

src/test/ui/impl-trait/must_outlive_least_region_or_bound.stderr

+9-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@ error[E0621]: explicit lifetime required in the type of `x`
22
--> $DIR/must_outlive_least_region_or_bound.rs:3:23
33
|
44
LL | fn elided(x: &i32) -> impl Copy { x }
5-
| ---- ^^^^^^^^^ lifetime `'static` required
6-
| |
7-
| help: add explicit lifetime `'static` to the type of `x`: `&'static i32`
5+
| ^^^^^^^^^ `impl Trait` types can only capture lifetimes that they reference
6+
help: add explicit unnamed lifetime `'_` to the return type to constrain it
7+
|
8+
LL | fn elided(x: &i32) -> impl Copy + '_ { x }
9+
| ^^^^^^^^^^^^^^
10+
help: otherwise, add explicit lifetime `'static` to the type of `x`
11+
|
12+
LL | fn elided(x: &'static i32) -> impl Copy { x }
13+
| ^^^^^^^^^^^^
814

915
error: cannot infer an appropriate lifetime
1016
--> $DIR/must_outlive_least_region_or_bound.rs:6:44

0 commit comments

Comments
 (0)