@@ -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 ) ?;
0 commit comments