Skip to content

Add Support for sorting #[derive(...)] #6574

Open
@maksym-arutyunyan

Description

@maksym-arutyunyan

Hi rustfmt team,

This idea has come up regularly since 2017 — users keep asking for #[derive(...)] traits to be sorted automatically, just like imports. And each time, it’s been closed with the same core concern: that the order of derive macros might matter, and reordering them could break things.

#1867, #4112, rust-lang/style-team#154

That concern made sense back then. But a lot has changed since.

To work around the lack of native support, several community tools have emerged:

These tools are helpful, but they come with limitations. They usually operate via regex or simple token logic, which means they can't match the accuracy or safety of a proper syntax-aware formatter. More importantly, each tool may use a slightly different sorting convention, which introduces fragmentation and inconsistency across projects and teams.

Having this behavior built into rustfmt would solve both problems:

  • It would ensure consistency across the Rust ecosystem.
  • It would offer users a reliable, idiomatic way to enforce ordering — just like how import sorting works today.

In the last relevant discussion rust-lang/style-team#154 (comment), it was acknowledged that most of the original blockers no longer apply. The one remaining edge case — where one derive macro implicitly enables another — is:

  • Extremely rare
  • Easy to detect and fix (just add an import)
  • A hard error at compile time, not a subtle bug

Given this, I believe it’s now safe and timely to reconsider.

Would you be open to adding support for sorting derive traits in rustfmt?
Or if there’s still a concrete reason this can’t be done safely, could you share a specific example?

Thanks again for all your work on rustfmt — it’s a tool we use and appreciate every day.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions