diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0f58206eee9f3..ec9ae63ca366a 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1499,10 +1499,16 @@ impl<'a> Resolver<'a> { && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind && let Some(span) = self.opt_span(def_id) { - err.span_help( - self.session.source_map().guess_head_span(span), - "consider adding `#[derive(Default)]` to this enum", - ); + let source_map = self.session.source_map(); + let head_span = source_map.guess_head_span(span); + if let Ok(head) = source_map.span_to_snippet(head_span) { + err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect); + } else { + err.span_help( + head_span, + "consider adding `#[derive(Default)]` to this enum", + ); + } } for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] { if let Ok(binding) = self.early_resolve_ident_in_lexical_scope( diff --git a/src/test/ui/enum/suggest-default-attribute.rs b/src/test/ui/enum/suggest-default-attribute.rs index 33bd0d2408139..1d7567e60a57c 100644 --- a/src/test/ui/enum/suggest-default-attribute.rs +++ b/src/test/ui/enum/suggest-default-attribute.rs @@ -1,4 +1,4 @@ -pub enum Test { //~ HELP consider adding `#[derive(Default)]` to this enum +pub enum Test { //~ HELP consider adding a derive #[default] //~^ ERROR cannot find attribute `default` in this scope First, diff --git a/src/test/ui/enum/suggest-default-attribute.stderr b/src/test/ui/enum/suggest-default-attribute.stderr index 791f219e8f95f..fb830d3f78b64 100644 --- a/src/test/ui/enum/suggest-default-attribute.stderr +++ b/src/test/ui/enum/suggest-default-attribute.stderr @@ -4,11 +4,11 @@ error: cannot find attribute `default` in this scope LL | #[default] | ^^^^^^^ | -help: consider adding `#[derive(Default)]` to this enum - --> $DIR/suggest-default-attribute.rs:1:1 +help: consider adding a derive + | +LL + #[derive(Default)] +LL ~ pub enum Test { | -LL | pub enum Test { - | ^^^^^^^^^^^^^ error: aborting due to previous error