rust-lang / rust-lang/rustfmt

Chain comments after `.` prevent chain from being formatted because comment would be lost

Open
#5,563 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-call-chains A-comments P-low
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

If a comment follows the . in a chain, then the chain is not formatted because a comment would be lost. This behavior can be seen when running rustfmt with error_on_unformatted=true. However the chain is rewritten if the comment comes before the .

tested using rustfmt 1.5.1-nightly (ef911542 2022-09-19).

Input

fn not_formatted() {
    let a = b./*cc*/       ddd;
    let e = f.// gg
hhh;
}

fn formated() {
    let i = j/*kk*/       .lll;
    let m = n// oo
.ppp;
}

Output

fn not_formatted() {
    let a = b./*cc*/       ddd;
    let e = f.// gg
hhh;
}

fn formated() {
    let i = j /*kk*/
        .lll;
    let m = n // oo
        .ppp;
}

Error Output

error[internal]: not formatted because a comment would be lost
 --> <stdin>:2
  |
2 |     let a = b./*cc*/       ddd;
  |
  = note: set `error_on_unformatted = false` to suppress the warning against comments or string literals

error[internal]: not formatted because a comment would be lost
 --> <stdin>:3
  |
3 |     let e = f.// gg
  |
  = note: set `error_on_unformatted = false` to suppress the warning against comments or string literals


I think the issue is that we don't expect to find comments after the . when rewriting ChainItem, and the examples above specifically highlight the ChainItemKind::StructField match arm:
https://github.com/rust-lang/rustfmt/blob/ef91154250977b3b5d05448dafbca524a1168b47/src/chains.rs#L246-L271

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/chains.rs at the ChainItemKind::StructField match arm referenced by the issue, and reproduce the examples with rustfmt and error_on_unformatted=true. Trace how comments after the dot are handled, then verify that both block and line comments remain preserved and the chain is formatted without the lost-comment error.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.