Skip to content

Commit 11682a4

Browse files
authored
Rollup merge of #162103 - raushan728:issues/161815, r=davidtwco
fix(parser): emit targeted diagnostic for fields inside traits Fixes #161815 Detect `ident: Type` or `self: Type` inside trait bodies to emit a clearer diagnostic.
2 parents 0a4206a + 6b9210c commit 11682a4

4 files changed

Lines changed: 121 additions & 0 deletions

File tree

‎compiler/rustc_parse/src/diagnostics.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2441,6 +2441,23 @@ pub(crate) struct AssociatedStaticItemNotAllowed {
24412441
pub span: Span,
24422442
}
24432443

2444+
#[derive(Subdiagnostic)]
2445+
pub(crate) enum FieldNotAllowedInTraitSugg {
2446+
#[help("consider using a method instead: `fn {$ident}(&self) -> {$ty};`")]
2447+
Method { ident: String, ty: String },
2448+
#[note("`self` can only appear as a method receiver; consider `fn method(self: {$ty})`")]
2449+
SelfReceiver { ty: String },
2450+
}
2451+
2452+
#[derive(Diagnostic)]
2453+
#[diag("fields are not allowed in trait definitions")]
2454+
pub(crate) struct FieldNotAllowedInTrait {
2455+
#[primary_span]
2456+
pub span: Span,
2457+
#[subdiagnostic]
2458+
pub sugg: FieldNotAllowedInTraitSugg,
2459+
}
2460+
24442461
#[derive(Diagnostic)]
24452462
#[diag("crate name using dashes are not valid in `extern crate` statements")]
24462463
pub(crate) struct ExternCrateNameWithDashes {

‎compiler/rustc_parse/src/parser/item.rs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,14 @@ impl<'a> Parser<'a> {
384384
Case::Insensitive,
385385
);
386386
} else if macros_allowed && self.check_path() {
387+
// Detect `field_name: Type` or `self: Type` inside a trait body and emit
388+
// a clearer diagnostic before falling through to the macro invocation path.
389+
let is_field_in_trait = fn_parse_mode.context == FnContext::Trait
390+
&& self.token.is_path_start()
391+
&& self.look_ahead(1, |t| t.kind == token::Colon);
392+
if is_field_in_trait {
393+
return self.recover_field_in_trait();
394+
}
387395
if self.isnt_macro_invocation() {
388396
self.recover_missing_kw_before_item()?;
389397
}
@@ -413,6 +421,35 @@ impl<'a> Parser<'a> {
413421
}
414422
}
415423

424+
fn recover_field_in_trait(&mut self) -> PResult<'a, Option<ItemKind>> {
425+
let ident_span = self.token.span;
426+
let ident_str = pprust::token_to_string(&self.token).into_owned();
427+
let is_self = self.token.is_keyword(kw::SelfLower);
428+
429+
self.bump(); // identifier or `self`
430+
self.bump(); // `:`
431+
432+
let ty_str = match self.parse_ty() {
433+
Ok(ty) => pprust::ty_to_string(&ty),
434+
Err(e) => {
435+
e.cancel();
436+
String::from("Type")
437+
}
438+
};
439+
// Eat the trailing separator so the parser doesn't trip over it.
440+
let _ = self.eat(exp!(Comma));
441+
let _ = self.eat(exp!(Semi));
442+
443+
let span = ident_span.to(self.prev_token.span);
444+
let sugg = if is_self {
445+
diagnostics::FieldNotAllowedInTraitSugg::SelfReceiver { ty: ty_str }
446+
} else {
447+
diagnostics::FieldNotAllowedInTraitSugg::Method { ident: ident_str, ty: ty_str }
448+
};
449+
let err = self.dcx().create_err(diagnostics::FieldNotAllowedInTrait { span, sugg });
450+
Err(err)
451+
}
452+
416453
fn parse_use_item(&mut self) -> PResult<'a, ItemKind> {
417454
let use_token_span = self.prev_token.span;
418455
let tree = self.parse_use_tree(use_token_span, None)?;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
fn main() {}
2+
3+
trait Trait1 {
4+
field_name: String, //~ ERROR fields are not allowed in trait definitions
5+
}
6+
7+
trait Trait2 {
8+
self: String, //~ ERROR fields are not allowed in trait definitions
9+
}
10+
11+
trait Trait3 {
12+
field_name: String //~ ERROR fields are not allowed in trait definitions
13+
}
14+
15+
trait Trait4 {
16+
self: String //~ ERROR fields are not allowed in trait definitions
17+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
error: fields are not allowed in trait definitions
2+
--> $DIR/trait-item-field-colon-syntax.rs:4:5
3+
|
4+
LL | trait Trait1 {
5+
| - while parsing this item list starting here
6+
LL | field_name: String,
7+
| ^^^^^^^^^^^^^^^^^^^
8+
LL | }
9+
| - the item list ends here
10+
|
11+
= help: consider using a method instead: `fn field_name(&self) -> String;`
12+
13+
error: fields are not allowed in trait definitions
14+
--> $DIR/trait-item-field-colon-syntax.rs:8:5
15+
|
16+
LL | trait Trait2 {
17+
| - while parsing this item list starting here
18+
LL | self: String,
19+
| ^^^^^^^^^^^^^
20+
LL | }
21+
| - the item list ends here
22+
|
23+
= note: `self` can only appear as a method receiver; consider `fn method(self: String)`
24+
25+
error: fields are not allowed in trait definitions
26+
--> $DIR/trait-item-field-colon-syntax.rs:12:5
27+
|
28+
LL | trait Trait3 {
29+
| - while parsing this item list starting here
30+
LL | field_name: String
31+
| ^^^^^^^^^^^^^^^^^^
32+
LL | }
33+
| - the item list ends here
34+
|
35+
= help: consider using a method instead: `fn field_name(&self) -> String;`
36+
37+
error: fields are not allowed in trait definitions
38+
--> $DIR/trait-item-field-colon-syntax.rs:16:5
39+
|
40+
LL | trait Trait4 {
41+
| - while parsing this item list starting here
42+
LL | self: String
43+
| ^^^^^^^^^^^^
44+
LL | }
45+
| - the item list ends here
46+
|
47+
= note: `self` can only appear as a method receiver; consider `fn method(self: String)`
48+
49+
error: aborting due to 4 previous errors
50+

0 commit comments

Comments
 (0)