rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
6.05k stars 888 forks source link

Newlines between commented code in call chains get removed #6380

Closed AeonSolstice closed 5 days ago

AeonSolstice commented 3 weeks ago
fn main() {
  let el = EventLoop::builder()
    .with_msg_hook(|msg| {
      let msg = msg as *const MSG;

      if unsafe { (*msg).message == WM_NCCALCSIZE && (*msg).wParam.0 == 1 } {
        return true;
      }

      false
    })
    .build()
    .unwrap();
}

Using vscode I comment out the following to test something quickly, and save

fn main() {
  let el = EventLoop::builder()
    // .with_msg_hook(|msg| {
    //   let msg = msg as *const MSG;

    //   if unsafe { (*msg).message == WM_NCCALCSIZE && (*msg).wParam.0 == 1 } {
    //     return true;
    //   }

    //   false
    // })
    .build()
    .unwrap();
}

Rustfmt produces the following output

fn main() {
  let el = EventLoop::builder()
    // .with_msg_hook(|msg| {
    //   let msg = msg as *const MSG;
    //   if unsafe { (*msg).message == WM_NCCALCSIZE && (*msg).wParam.0 == 1 } {
    //     return true;
    //   }
    //   false
    // })
    .build()
    .unwrap();
}

I finish testing. The commented code is still highlighted and I need to Ctrl-Z 2 times and save again to get my original, clear, code.

I would expect 2+(incl.) newlines to get reduced to 1, but single ones should be kept. Commented section does not necessarily need to be code.

$rustfmt --version
rustfmt 1.7.1-stable (f6e511e 2024-10-15)
ding-young commented 2 weeks ago

I think this is caused in the following part. https://github.com/rust-lang/rustfmt/blob/777e25a8c91af9923ad356eb4448ac2ed15167a9/src/chains.rs#L450 rustfmt intentionally trims the try operator and then removes the resulting blank line (the try operator is checked elsewhere and reattached later). However, it appears that it mistakenly removes the blank line even when there isn’t a try operator. —just my guess, though. https://github.com/rust-lang/rustfmt/blob/777e25a8c91af9923ad356eb4448ac2ed15167a9/src/chains.rs#L1015-L1038

ytmimi commented 5 days ago

Just now realizing that this is a duplicate of #4012