-
Notifications
You must be signed in to change notification settings - Fork 957
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 ([Tracking] Formatting failures with all-or-nothing fallback behavior #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
- Block comment removed from function signature when using unit #6667
- rustfmt removes comments from visibility annotation #6669
- rustfmt generates invalid code by moving comments #6670
- the inability to comment every non-obnoxious token without leftover whitespace before or after #6671
- Inconsistent comment handling in tuple field formatting #6642
- Rustfmt is … confused 😳 by
//
comment afterpub
and beforetrait
#5841 - trait bounds with comments are not formatted #2055
- Comments removed/eaten after generic trait header before body #5922
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.