Skip to content

Port #[automatically_derived] to the new attribute parsing infrastructure #143779

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ impl AttributeExt for Attribute {
_ => None,
}
}

fn is_automatically_derived_attr(&self) -> bool {
self.has_name(sym::automatically_derived)
}
}

impl Attribute {
Expand Down Expand Up @@ -810,6 +814,7 @@ pub trait AttributeExt: Debug {
.iter()
.any(|kind| self.has_name(*kind))
}
fn is_automatically_derived_attr(&self) -> bool;

/// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
/// * `///doc` returns `Some(("doc", CommentKind::Line))`.
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_attr_data_structures/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ pub enum AttributeKind {
/// Represents `#[rustc_as_ptr]` (used by the `dangling_pointers_from_temporaries` lint).
AsPtr(Span),

/// Represents `#[automatically_derived]`
AutomaticallyDerived(Span),

/// Represents `#[rustc_default_body_unstable]`.
BodyStability {
stability: DefaultBodyStability,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ impl AttributeKind {
AllowIncoherentImpl(..) => No,
AllowInternalUnstable(..) => Yes,
AsPtr(..) => Yes,
AutomaticallyDerived(..) => Yes,
BodyStability { .. } => No,
CoherenceIsCore => No,
Coinductive(..) => No,
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ impl<S: Stage> NoArgsAttributeParser<S> for PassByValueParser {
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const CREATE: fn(Span) -> AttributeKind = AttributeKind::PassByValue;
}

pub(crate) struct AutomaticallyDerivedParser;
impl<S: Stage> NoArgsAttributeParser<S> for AutomaticallyDerivedParser {
const PATH: &[Symbol] = &[sym::automatically_derived];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const CREATE: fn(Span) -> AttributeKind = AttributeKind::AutomaticallyDerived;
}
5 changes: 4 additions & 1 deletion compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ use crate::attributes::link_attrs::{
ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkSectionParser,
StdInternalSymbolParser,
};
use crate::attributes::lint_helpers::{AsPtrParser, PassByValueParser, PubTransparentParser};
use crate::attributes::lint_helpers::{
AsPtrParser, AutomaticallyDerivedParser, PassByValueParser, PubTransparentParser,
};
use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser};
use crate::attributes::must_use::MustUseParser;
use crate::attributes::no_implicit_prelude::NoImplicitPreludeParser;
Expand Down Expand Up @@ -153,6 +155,7 @@ attribute_parsers!(
Single<TransparencyParser>,
Single<WithoutArgs<AllowIncoherentImplParser>>,
Single<WithoutArgs<AsPtrParser>>,
Single<WithoutArgs<AutomaticallyDerivedParser>>,
Single<WithoutArgs<CoherenceIsCoreParser>>,
Single<WithoutArgs<CoinductiveParser>>,
Single<WithoutArgs<ColdParser>>,
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1304,6 +1304,7 @@ impl AttributeExt for Attribute {
Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
Attribute::Parsed(AttributeKind::MayDangle(span)) => *span,
Attribute::Parsed(AttributeKind::Ignore { span, .. }) => *span,
Attribute::Parsed(AttributeKind::AutomaticallyDerived(span)) => *span,
Copy link
Contributor Author

@JonathanBrouwer JonathanBrouwer Jul 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is needed to fix #143780 for automatically_derived. automatically_derived is part of a test case so this is necessary to add now. @jdonszelmann and I are discussing a general solution to this problem.

a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
}
}
Expand Down Expand Up @@ -1334,6 +1335,11 @@ impl AttributeExt for Attribute {
_ => None,
}
}

fn is_automatically_derived_attr(&self) -> bool {
matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
}

#[inline]
fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
match &self {
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_lint/src/default_could_be_derived.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use rustc_attr_data_structures::{AttributeKind, find_attr};
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{Applicability, Diag};
use rustc_hir as hir;
Expand Down Expand Up @@ -62,7 +63,7 @@ impl<'tcx> LateLintPass<'tcx> for DefaultCouldBeDerived {
let hir::ImplItemKind::Fn(_sig, body_id) = impl_item.kind else { return };
let assoc = cx.tcx.associated_item(impl_item.owner_id);
let parent = assoc.container_id(cx.tcx);
if cx.tcx.has_attr(parent, sym::automatically_derived) {
if find_attr!(cx.tcx.get_all_attrs(parent), AttributeKind::AutomaticallyDerived(..)) {
// We don't care about what `#[derive(Default)]` produces in this lint.
return;
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/levels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
) {
let sess = self.sess;
for (attr_index, attr) in attrs.iter().enumerate() {
if attr.has_name(sym::automatically_derived) {
if attr.is_automatically_derived_attr() {
self.insert(
LintId::of(SINGLE_USE_LIFETIMES),
LevelAndSource {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, V
use rustc_ast::expand::StrippedCfgItem;
use rustc_ast::node_id::NodeMap;
pub use rustc_ast_ir::{Movability, Mutability, try_visit};
use rustc_attr_data_structures::AttributeKind;
use rustc_attr_data_structures::{AttributeKind, find_attr};
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
use rustc_data_structures::intern::Interned;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
Expand Down Expand Up @@ -2031,7 +2031,7 @@ impl<'tcx> TyCtxt<'tcx> {

/// Check if the given `DefId` is `#\[automatically_derived\]`.
pub fn is_automatically_derived(self, def_id: DefId) -> bool {
self.has_attr(def_id, sym::automatically_derived)
find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
}

/// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
Expand Down
6 changes: 4 additions & 2 deletions compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use core::ops::ControlFlow;

use rustc_abi::{FieldIdx, VariantIdx};
use rustc_apfloat::Float;
use rustc_attr_data_structures::{AttributeKind, find_attr};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Diag;
use rustc_hir as hir;
Expand All @@ -15,7 +16,7 @@ use rustc_middle::ty::{
};
use rustc_middle::{mir, span_bug};
use rustc_span::def_id::DefId;
use rustc_span::{DUMMY_SP, Span, sym};
use rustc_span::{DUMMY_SP, Span};
use rustc_trait_selection::traits::ObligationCause;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use tracing::{debug, instrument, trace};
Expand Down Expand Up @@ -495,7 +496,8 @@ fn type_has_partial_eq_impl<'tcx>(
let mut structural_peq = false;
let mut impl_def_id = None;
for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
automatically_derived = tcx.has_attr(def_id, sym::automatically_derived);
automatically_derived =
find_attr!(tcx.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..));
impl_def_id = Some(def_id);
}
for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_parse/src/validate_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ pub fn check_builtin_meta_item(
| sym::rustc_layout_scalar_valid_range_start
| sym::rustc_layout_scalar_valid_range_end
| sym::no_implicit_prelude
| sym::automatically_derived
) {
return;
}
Expand Down
14 changes: 10 additions & 4 deletions compiler/rustc_passes/src/check_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
Attribute::Parsed(AttributeKind::Confusables { first_span, .. }) => {
self.check_confusables(*first_span, target);
}
Attribute::Parsed(AttributeKind::AutomaticallyDerived(attr_span)) => self
.check_generic_attr(
hir_id,
sym::automatically_derived,
*attr_span,
target,
Target::Impl,
),
Attribute::Parsed(
AttributeKind::Stability { span, .. }
| AttributeKind::ConstStability { span, .. },
Expand Down Expand Up @@ -335,9 +343,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
[sym::should_panic, ..] => {
self.check_generic_attr_unparsed(hir_id, attr, target, Target::Fn)
}
[sym::automatically_derived, ..] => {
self.check_generic_attr_unparsed(hir_id, attr, target, Target::Impl)
}
[sym::proc_macro, ..] => {
self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
}
Expand Down Expand Up @@ -2814,7 +2819,6 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
// resolution for the attribute macro error.
const ATTRS_TO_CHECK: &[Symbol] = &[
sym::macro_export,
sym::automatically_derived,
sym::rustc_main,
sym::derive,
sym::test,
Expand All @@ -2837,6 +2841,8 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
(*first_attr_span, sym::repr)
} else if let Attribute::Parsed(AttributeKind::Path(.., span)) = attr {
(*span, sym::path)
} else if let Attribute::Parsed(AttributeKind::AutomaticallyDerived(span)) = attr {
(*span, sym::automatically_derived)
} else {
continue;
};
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_passes/src/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ use rustc_middle::query::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{self, RootVariableMinCaptureList, Ty, TyCtxt};
use rustc_session::lint;
use rustc_span::{BytePos, Span, Symbol, sym};
use rustc_span::{BytePos, Span, Symbol};
use tracing::{debug, instrument};

use self::LiveNodeKind::*;
Expand Down Expand Up @@ -140,7 +140,7 @@ fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) {
// Don't run unused pass for #[derive()]
let parent = tcx.local_parent(def_id);
if let DefKind::Impl { .. } = tcx.def_kind(parent)
&& tcx.has_attr(parent, sym::automatically_derived)
&& find_attr!(tcx.get_all_attrs(parent), AttributeKind::AutomaticallyDerived(..))
{
return;
}
Expand Down
3 changes: 3 additions & 0 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,9 @@ impl Item {
}
Some(format!("#[target_feature({output})]"))
}
hir::Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)) => {
Some("#[automatically_derived]".to_string())
}
_ => Some({
let mut s = rustc_hir_pretty::attribute_to_string(&tcx, attr);
assert_eq!(s.pop(), Some('\n'));
Expand Down
3 changes: 2 additions & 1 deletion src/tools/clippy/clippy_lints/src/format_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use rustc_span::edition::Edition::Edition2021;
use rustc_span::{Span, Symbol, sym};
use rustc_trait_selection::infer::TyCtxtInferExt;
use rustc_trait_selection::traits::{Obligation, ObligationCause, Selection, SelectionContext};
use rustc_attr_data_structures::{AttributeKind, find_attr};

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -656,7 +657,7 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> {
};
let selection = SelectionContext::new(&infcx).select(&obligation);
let derived = if let Ok(Some(Selection::UserDefined(data))) = selection {
tcx.has_attr(data.impl_def_id, sym::automatically_derived)
find_attr!(tcx.get_all_attrs(data.impl_def_id), AttributeKind::AutomaticallyDerived(..))
} else {
false
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl<'tcx> LateLintPass<'tcx> for DeriveDeserializeAllowingUnknown {
}

// Is it derived?
if !cx.tcx.has_attr(item.owner_id, sym::automatically_derived) {
if !find_attr!(cx.tcx.get_all_attrs(item.owner_id), AttributeKind::AutomaticallyDerived(..)) {
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/tools/clippy/clippy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1784,9 +1784,9 @@ pub fn in_automatically_derived(tcx: TyCtxt<'_>, id: HirId) -> bool {
tcx.hir_parent_owner_iter(id)
.filter(|(_, node)| matches!(node, OwnerNode::Item(item) if matches!(item.kind, ItemKind::Impl(_))))
.any(|(id, _)| {
has_attr(
find_attr!(
tcx.hir_attrs(tcx.local_def_id_to_hir_id(id.def_id)),
sym::automatically_derived,
AttributeKind::AutomaticallyDerived(..)
)
})
}
Expand Down
15 changes: 9 additions & 6 deletions tests/ui/attributes/malformed-attrs.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,6 @@ error: malformed `debugger_visualizer` attribute input
LL | #[debugger_visualizer]
| ^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[debugger_visualizer(natvis_file = "...", gdb_script_file = "...")]`

error: malformed `automatically_derived` attribute input
--> $DIR/malformed-attrs.rs:191:1
|
LL | #[automatically_derived = 18]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[automatically_derived]`

error: malformed `thread_local` attribute input
--> $DIR/malformed-attrs.rs:203:1
|
Expand Down Expand Up @@ -546,6 +540,15 @@ LL | #[unsafe(ffi_const = 1)]
| | didn't expect any arguments here
| help: must be of the form: `#[ffi_const]`

error[E0565]: malformed `automatically_derived` attribute input
--> $DIR/malformed-attrs.rs:191:1
|
LL | #[automatically_derived = 18]
| ^^^^^^^^^^^^^^^^^^^^^^^^----^
| | |
| | didn't expect any arguments here
| help: must be of the form: `#[automatically_derived]`

error[E0565]: malformed `non_exhaustive` attribute input
--> $DIR/malformed-attrs.rs:197:1
|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,21 +121,6 @@ LL - #![rustc_main]
LL + #[rustc_main]
|

error: `automatically_derived` attribute cannot be used at crate level
--> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:23:1
|
LL | #![automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
...
LL | mod inline {
| ------ the inner attribute doesn't annotate this module
|
help: perhaps you meant to use an outer attribute
|
LL - #![automatically_derived]
LL + #[automatically_derived]
|

error: `repr` attribute cannot be used at crate level
--> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:19:1
|
Expand Down Expand Up @@ -166,6 +151,21 @@ LL - #![path = "3800"]
LL + #[path = "3800"]
|

error: `automatically_derived` attribute cannot be used at crate level
--> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:23:1
|
LL | #![automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
...
LL | mod inline {
| ------ the inner attribute doesn't annotate this module
|
help: perhaps you meant to use an outer attribute
|
LL - #![automatically_derived]
LL + #[automatically_derived]
|

error[E0518]: attribute should be applied to function or closure
--> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:42:17
|
Expand Down
24 changes: 12 additions & 12 deletions tests/ui/lint/unused/unused-attr-duplicate.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,6 @@ LL | #[should_panic]
| ^^^^^^^^^^^^^^^
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:70:1
|
LL | #[automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute
|
note: attribute also specified here
--> $DIR/unused-attr-duplicate.rs:69:1
|
LL | #[automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:14:1
|
Expand Down Expand Up @@ -190,6 +178,18 @@ note: attribute also specified here
LL | #[non_exhaustive]
| ^^^^^^^^^^^^^^^^^

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:70:1
|
LL | #[automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute
|
note: attribute also specified here
--> $DIR/unused-attr-duplicate.rs:69:1
|
LL | #[automatically_derived]
| ^^^^^^^^^^^^^^^^^^^^^^^^

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:74:1
|
Expand Down
Loading