Skip to content

[Tracking] Comment preservation and formatting issues #6688

@shulaoda

Description

@shulaoda

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:

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

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.

Metadata

Metadata

Assignees

Labels

C-tracking-issueCategory: tracking issue; a meta issue intended to track other issues or some kind of progress

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions