Skip to content

Commit 8887af7

Browse files
committed
Improve parse errors for lifetimes in type position
1 parent 97c966b commit 8887af7

14 files changed

+234
-42
lines changed

Diff for: compiler/rustc_parse/messages.ftl

+3-1
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,9 @@ parse_mut_on_nested_ident_pattern = `mut` must be attached to each individual bi
642642
.suggestion = add `mut` to each binding
643643
parse_mut_on_non_ident_pattern = `mut` must be followed by a named binding
644644
.suggestion = remove the `mut` prefix
645-
parse_need_plus_after_trait_object_lifetime = lifetime in trait object type must be followed by `+`
645+
646+
parse_need_plus_after_trait_object_lifetime = lifetimes must be followed by `+` to form a trait object type
647+
.suggestion = consider adding a trait bound after the potential lifetime bound
646648
647649
parse_nested_adt = `{$kw_str}` definition cannot be nested inside `{$keyword}`
648650
.suggestion = consider creating a new `{$kw_str}` definition instead of nesting

Diff for: compiler/rustc_parse/src/errors.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2806,6 +2806,8 @@ pub(crate) struct ReturnTypesUseThinArrow {
28062806
pub(crate) struct NeedPlusAfterTraitObjectLifetime {
28072807
#[primary_span]
28082808
pub span: Span,
2809+
#[suggestion(code = " + /* Trait */", applicability = "has-placeholders")]
2810+
pub suggestion: Span,
28092811
}
28102812

28112813
#[derive(Diagnostic)]

Diff for: compiler/rustc_parse/src/parser/ty.rs

+57-6
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_ast::{
77
Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty,
88
TyKind, UnsafeBinderTy,
99
};
10-
use rustc_errors::{Applicability, PResult};
10+
use rustc_errors::{Applicability, Diag, PResult};
1111
use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
1212
use thin_vec::{ThinVec, thin_vec};
1313

@@ -411,6 +411,9 @@ impl<'a> Parser<'a> {
411411
TyKind::Path(None, path) if maybe_bounds => {
412412
self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true)
413413
}
414+
// For `('a) + …`, we know that `'a` in type position already lead to an error being
415+
// emitted. To reduce output, let's indirectly suppress E0178 (bad `+` in type) and
416+
// other irrelevant consequential errors.
414417
TyKind::TraitObject(bounds, TraitObjectSyntax::None)
415418
if maybe_bounds && bounds.len() == 1 && !trailing_plus =>
416419
{
@@ -425,12 +428,60 @@ impl<'a> Parser<'a> {
425428
}
426429

427430
fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> {
428-
let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus());
429-
let bounds = self.parse_generic_bounds_common(allow_plus)?;
430-
if lt_no_plus {
431-
self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime { span: lo });
431+
// A lifetime only begins a bare trait object type if it is followed by `+`!
432+
if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) {
433+
// In Rust 2021 and beyond, we assume that the user didn't intend to write a bare trait
434+
// object type with a leading lifetime bound since that seems very unlikely given the
435+
// fact that `dyn`-less trait objects are *semantically* invalid.
436+
if self.psess.edition.at_least_rust_2021() {
437+
let lt = self.expect_lifetime();
438+
let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime");
439+
err.span_label(lo, "expected type");
440+
return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) {
441+
Ok(ref_ty) => ref_ty,
442+
Err(err) => TyKind::Err(err.emit()),
443+
});
444+
}
445+
446+
self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime {
447+
span: lo,
448+
suggestion: lo.shrink_to_hi(),
449+
});
450+
}
451+
Ok(TyKind::TraitObject(
452+
self.parse_generic_bounds_common(allow_plus)?,
453+
TraitObjectSyntax::None,
454+
))
455+
}
456+
457+
fn maybe_recover_ref_ty_no_leading_ampersand<'cx>(
458+
&mut self,
459+
lt: Lifetime,
460+
lo: Span,
461+
mut err: Diag<'cx>,
462+
) -> Result<TyKind, Diag<'cx>> {
463+
if !self.may_recover() {
464+
return Err(err);
465+
}
466+
let snapshot = self.create_snapshot_for_diagnostic();
467+
let mutbl = self.parse_mutability();
468+
match self.parse_ty_no_plus() {
469+
Ok(ty) => {
470+
err.span_suggestion_verbose(
471+
lo.shrink_to_lo(),
472+
"you might have meant to write a reference type here",
473+
"&",
474+
Applicability::MaybeIncorrect,
475+
);
476+
err.emit();
477+
Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl }))
478+
}
479+
Err(diag) => {
480+
diag.cancel();
481+
self.restore_snapshot(snapshot);
482+
Err(err)
483+
}
432484
}
433-
Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
434485
}
435486

436487
fn parse_remaining_bounds_path(

Diff for: tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ trait X {
33
}
44

55
fn foo<'a>(arg: Box<dyn X<Y('a) = &'a ()>>) {}
6-
//~^ ERROR: lifetime in trait object type must be followed by `+`
6+
//~^ ERROR: lifetimes must be followed by `+` to form a trait object type
77
//~| ERROR: parenthesized generic arguments cannot be used
88
//~| ERROR associated type takes 0 generic arguments but 1 generic argument
99
//~| ERROR associated type takes 1 lifetime argument but 0 lifetime arguments

Diff for: tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1-
error: lifetime in trait object type must be followed by `+`
1+
error: lifetimes must be followed by `+` to form a trait object type
22
--> $DIR/gat-trait-path-parenthesised-args.rs:5:29
33
|
44
LL | fn foo<'a>(arg: Box<dyn X<Y('a) = &'a ()>>) {}
55
| ^^
6+
|
7+
help: consider adding a trait bound after the potential lifetime bound
8+
|
9+
LL | fn foo<'a>(arg: Box<dyn X<Y('a + /* Trait */) = &'a ()>>) {}
10+
| +++++++++++++
611

712
error: parenthesized generic arguments cannot be used in associated type constraints
813
--> $DIR/gat-trait-path-parenthesised-args.rs:5:27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
error: lifetimes must be followed by `+` to form a trait object type
2+
--> $DIR/trait-object-macro-matcher.rs:17:8
3+
|
4+
LL | m!('static);
5+
| ^^^^^^^
6+
|
7+
help: consider adding a trait bound after the potential lifetime bound
8+
|
9+
LL | m!('static + /* Trait */);
10+
| +++++++++++++
11+
12+
error: lifetimes must be followed by `+` to form a trait object type
13+
--> $DIR/trait-object-macro-matcher.rs:17:8
14+
|
15+
LL | m!('static);
16+
| ^^^^^^^
17+
|
18+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
19+
help: consider adding a trait bound after the potential lifetime bound
20+
|
21+
LL | m!('static + /* Trait */);
22+
| +++++++++++++
23+
24+
error[E0224]: at least one trait is required for an object type
25+
--> $DIR/trait-object-macro-matcher.rs:17:8
26+
|
27+
LL | m!('static);
28+
| ^^^^^^^
29+
30+
error: aborting due to 3 previous errors
31+
32+
For more information about this error, try `rustc --explain E0224`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: expected type, found lifetime
2+
--> $DIR/trait-object-macro-matcher.rs:17:8
3+
|
4+
LL | m!('static);
5+
| ^^^^^^^ expected type
6+
7+
error: expected type, found lifetime
8+
--> $DIR/trait-object-macro-matcher.rs:17:8
9+
|
10+
LL | m!('static);
11+
| ^^^^^^^ expected type
12+
|
13+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
14+
15+
error: aborting due to 2 previous errors
16+

Diff for: tests/ui/parser/macro/trait-object-macro-matcher.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
// A single lifetime is not parsed as a type.
22
// `ty` matcher in particular doesn't accept a single lifetime
33

4+
//@ revisions: e2015 e2021
5+
//@[e2015] edition: 2015
6+
//@[e2021] edition: 2021
7+
48
macro_rules! m {
59
($t: ty) => {
610
let _: $t;
711
};
812
}
913

1014
fn main() {
15+
//[e2021]~vv ERROR expected type, found lifetime
16+
//[e2021]~v ERROR expected type, found lifetime
1117
m!('static);
12-
//~^ ERROR lifetime in trait object type must be followed by `+`
13-
//~| ERROR lifetime in trait object type must be followed by `+`
14-
//~| ERROR at least one trait is required for an object type
18+
//[e2015]~^ ERROR lifetimes must be followed by `+` to form a trait object type
19+
//[e2015]~| ERROR lifetimes must be followed by `+` to form a trait object type
20+
//[e2015]~| ERROR at least one trait is required for an object type
1521
}

Diff for: tests/ui/parser/macro/trait-object-macro-matcher.stderr

-23
This file was deleted.
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//@ edition: 2021
2+
3+
struct Entity<'a> {
4+
name: 'a str, //~ ERROR expected type, found lifetime
5+
//~^ HELP you might have meant to write a reference type here
6+
}
7+
8+
struct Buffer<'buf> {
9+
bytes: 'buf mut [u8], //~ ERROR expected type, found lifetime
10+
//~^ HELP you might have meant to write a reference type here
11+
}
12+
13+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
error: expected type, found lifetime
2+
--> $DIR/recover-ampersand-less-ref-ty.rs:4:11
3+
|
4+
LL | name: 'a str,
5+
| ^^ expected type
6+
|
7+
help: you might have meant to write a reference type here
8+
|
9+
LL | name: &'a str,
10+
| +
11+
12+
error: expected type, found lifetime
13+
--> $DIR/recover-ampersand-less-ref-ty.rs:9:12
14+
|
15+
LL | bytes: 'buf mut [u8],
16+
| ^^^^ expected type
17+
|
18+
help: you might have meant to write a reference type here
19+
|
20+
LL | bytes: &'buf mut [u8],
21+
| +
22+
23+
error: aborting due to 2 previous errors
24+

Diff for: tests/ui/parser/trait-object-lifetime-parens.stderr renamed to tests/ui/parser/trait-object-lifetime-parens.e2015.stderr

+9-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: parenthesized lifetime bounds are not supported
2-
--> $DIR/trait-object-lifetime-parens.rs:5:21
2+
--> $DIR/trait-object-lifetime-parens.rs:9:21
33
|
44
LL | fn f<'a, T: Trait + ('a)>() {}
55
| ^^^^
@@ -11,7 +11,7 @@ LL + fn f<'a, T: Trait + 'a>() {}
1111
|
1212

1313
error: parenthesized lifetime bounds are not supported
14-
--> $DIR/trait-object-lifetime-parens.rs:8:24
14+
--> $DIR/trait-object-lifetime-parens.rs:12:24
1515
|
1616
LL | let _: Box<Trait + ('a)>;
1717
| ^^^^
@@ -22,11 +22,16 @@ LL - let _: Box<Trait + ('a)>;
2222
LL + let _: Box<Trait + 'a>;
2323
|
2424

25-
error: lifetime in trait object type must be followed by `+`
26-
--> $DIR/trait-object-lifetime-parens.rs:10:17
25+
error: lifetimes must be followed by `+` to form a trait object type
26+
--> $DIR/trait-object-lifetime-parens.rs:16:17
2727
|
2828
LL | let _: Box<('a) + Trait>;
2929
| ^^
30+
|
31+
help: consider adding a trait bound after the potential lifetime bound
32+
|
33+
LL | let _: Box<('a + /* Trait */) + Trait>;
34+
| +++++++++++++
3035

3136
error: aborting due to 3 previous errors
3237

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
error: parenthesized lifetime bounds are not supported
2+
--> $DIR/trait-object-lifetime-parens.rs:9:21
3+
|
4+
LL | fn f<'a, T: Trait + ('a)>() {}
5+
| ^^^^
6+
|
7+
help: remove the parentheses
8+
|
9+
LL - fn f<'a, T: Trait + ('a)>() {}
10+
LL + fn f<'a, T: Trait + 'a>() {}
11+
|
12+
13+
error: parenthesized lifetime bounds are not supported
14+
--> $DIR/trait-object-lifetime-parens.rs:12:24
15+
|
16+
LL | let _: Box<Trait + ('a)>;
17+
| ^^^^
18+
|
19+
help: remove the parentheses
20+
|
21+
LL - let _: Box<Trait + ('a)>;
22+
LL + let _: Box<Trait + 'a>;
23+
|
24+
25+
error: expected type, found lifetime
26+
--> $DIR/trait-object-lifetime-parens.rs:16:17
27+
|
28+
LL | let _: Box<('a) + Trait>;
29+
| ^^ expected type
30+
31+
error[E0178]: expected a path on the left-hand side of `+`, not `((/*ERROR*/))`
32+
--> $DIR/trait-object-lifetime-parens.rs:16:16
33+
|
34+
LL | let _: Box<('a) + Trait>;
35+
| ^^^^^^^^^^^^ expected a path
36+
37+
error[E0782]: expected a type, found a trait
38+
--> $DIR/trait-object-lifetime-parens.rs:12:16
39+
|
40+
LL | let _: Box<Trait + ('a)>;
41+
| ^^^^^^^^^^^^
42+
|
43+
help: you can add the `dyn` keyword if you want a trait object
44+
|
45+
LL | let _: Box<dyn Trait + ('a)>;
46+
| +++
47+
48+
error: aborting due to 5 previous errors
49+
50+
Some errors have detailed explanations: E0178, E0782.
51+
For more information about an error, try `rustc --explain E0178`.

Diff for: tests/ui/parser/trait-object-lifetime-parens.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
1-
#![allow(bare_trait_objects)]
1+
//@ revisions: e2015 e2021
2+
//@[e2015] edition: 2015
3+
//@[e2021] edition: 2021
4+
5+
#![cfg_attr(e2015, allow(bare_trait_objects))]
26

37
trait Trait {}
48

59
fn f<'a, T: Trait + ('a)>() {} //~ ERROR parenthesized lifetime bounds are not supported
610

711
fn check<'a>() {
812
let _: Box<Trait + ('a)>; //~ ERROR parenthesized lifetime bounds are not supported
9-
// FIXME: It'd be great if we could add suggestion to the following case.
10-
let _: Box<('a) + Trait>; //~ ERROR lifetime in trait object type must be followed by `+`
13+
//[e2021]~^ ERROR expected a type, found a trait
14+
// FIXME: It'd be great if we could suggest removing the parentheses here too.
15+
//[e2015]~v ERROR lifetimes must be followed by `+` to form a trait object type
16+
let _: Box<('a) + Trait>;
17+
//[e2021]~^ ERROR expected type, found lifetime
18+
//[e2021]~| ERROR expected a path on the left-hand side of `+`
1119
}
1220

1321
fn main() {}

0 commit comments

Comments
 (0)