Skip to content

fix: replace_derive_with_manual_impl drops #[cfg] on Debug (and other traits) - #22859

Open
xunilrj wants to merge 5 commits into
rust-lang:masterfrom
xunilrj:fix-replace-derive-with-manual-impl-with-cfg
Open

fix: replace_derive_with_manual_impl drops #[cfg] on Debug (and other traits)#22859
xunilrj wants to merge 5 commits into
rust-lang:masterfrom
xunilrj:fix-replace-derive-with-manual-impl-with-cfg

Conversation

@xunilrj

@xunilrj xunilrj commented Jul 19, 2026

Copy link
Copy Markdown

This PR fixes a problem when struct/enum fields/variants have #[cfg(...)] attributes. In theses cases replace_derive_with_manual_impl access the field/variant directly without the attribute. Example:

  struct Foo {
      bar: String,
      #[cfg(feature = "baz")]
      baz: u32,
  }

  impl Debug for Foo {
      fn fmt(&self, f: &mut Formatter<'_>) -> Result {
          f.debug_struct("Foo").field("bar", &self.bar).field("baz", &self.baz).finish()
      }
  }

One case were I was not able to fix is the case of #[cfg(...)] inside tuple structs. Unfortunately rustc does not accept #[cfg(...)] when pattern matching:

match self {  
      //            v `rustc` complains here
      Self::V(arg0, #[cfg(feature = "x")] arg1) => { ... } 
  }

That would demand something like the below, which becomes very complex, very quickly. I think makes more sense to remove this limitation in rustc directly. Later, I will see if am able to do this.

match self {
      #[cfg(feature = "x")]
      Self::V(arg0, arg1) => { .. }
      #[cfg(not(feature = "x"))]
      Self::V(arg0) => {  ... }
  }

The same problem happens for other traits: Clone, Default, Hash, PartialEq, PartialOrd. If this PR is merged I can create the next ones, as they are very similar.

Another case is #[cfg_attr] which is very similar but it is much harder to deal with. Not sure if we want to support it or not.

One problem I had was that I was not able to find an easy way to create statements with attributes in one go, something like make::stmt_with_attrs(...). That made the code more complex than necessary as I first create blocks, and then splice statements with their attributes.

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jul 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants