[Tracking] Comment preservation and formatting issues
@shulaoda is already working on this.
Since Oct 10, 2025.
- Dominant language
- Rust
- Stars
- 7k
- Forks
- 1.1k
- Avg merge
- 2d 13h
- Merged PRs (30d)
- 24
Description
Summary
Rust allows both line comments (//) and block comments (/* */) to be placed between nearly any tokens in the syntax (e.g., pub(crate /* comment */), trait /* comment */ Name, pub // comment\ntrait). However, rustfmt currently struggles to preserve or correctly handle comments in many of these positions, leading to:
- Formatting produces invalid Rust code
- Comments are stripped during formatting
- Trailing whitespace errors (https://github.com/rust-lang/rustfmt/issues/6687)
Root Cause
Rust's flexible comment placement allows comments between virtually any tokens (as demonstrated in #6671 💀):
pub(crate /* .. */) /* .. */ unsafe /* .. */ auto /* .. */ trait /*..*/ Id /*..*/: /*..*/ Bound /*..*/ + Bound /* .. */ {
// ...
}
Rustfmt's current architecture has insufficient capabilities for handling comments in all possible positions. The current approach requires manually considering each comment placement scenario and stitching the formatted output together, which is fragile and error-prone.
Current Status
The rustfmt team is aware of these limitations and actively discussing architectural improvements on Zulip. However, comprehensively solving comment formatting across all possible token positions would require significant architectural changes, active contributors with deep understanding of the codebase, and substantial time and effort investment.
If you encounter comment formatting issues: Please report it with a minimal reproducible example and use conventional comment positions as a workaround. Simpler cases may be fixed individually over time, while comprehensive support requires long-term architectural improvements.
Related Issues
- https://github.com/rust-lang/rustfmt/issues/6667
- https://github.com/rust-lang/rustfmt/issues/6669
- https://github.com/rust-lang/rustfmt/issues/6670
- https://github.com/rust-lang/rustfmt/issues/6671
- https://github.com/rust-lang/rustfmt/issues/6642
- https://github.com/rust-lang/rustfmt/issues/5841
- https://github.com/rust-lang/rustfmt/issues/2055
- https://github.com/rust-lang/rustfmt/issues/5922
- https://github.com/rust-lang/rustfmt/issues/5934
Please feel free to modify the description to make it easier to understand or more accurate. If it's not necessary, please feel free to close it.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.