rust-lang / rustfmt

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

rustfmt eats comments in fn return type wrapped in parenthesis #5870

Open Centri3 opened 1 year ago

Centri3 commented 1 year ago

This code:

fn f() -> (/* is something */ bool) {}

Turns into this:

fn f() -> (bool) {}

Not too big of a deal as this isn't a tuple (due to the missing ,) and doesn't happen with tuples, but it should probably look for a comment here so it's retained after the programmer adds the , (and presumably other types, too)

Doesn't seem to happen in other places (like the type annotation for a local).

Centri3 commented 1 year ago

Hm, also happens with fn a() -> /* a */ bool {} but not if it's after the type

ytmimi commented 1 year ago

Thanks for the report.

To give a brief explanation; comments aren't explicitly represented in the AST rustfmt uses when formatting code so rustfmt needs to peek back into the original source code to find and recover comments. It seems that we're not recovering comments when rewriting ast::TyKind::Paren types.

https://github.com/rust-lang/rustfmt/blob/a72613be50f8afa39c2d46f732252463dc9cc14f/src/types.rs#L778-L810

Centri3 commented 1 year ago

Seems we're not checking for them right after the arrow as well, in the case of fn a() -> /* a */ bool {}

ytmimi commented 1 year ago

Seems we're not checking for them right after the arrow as well, in the case of fn a() -> / a / bool {}

Yup, that seems to be the case too. Though that's happening on a different code path and I think it might be better to open up a separate issue for that case.

ytmimi commented 1 year ago

@Centri3 Also want to highlight that comments after the type are also removed. e.g. fn f() -> (bool /* comment */) {} becomes fn f() -> (bool) {}

Centri3 commented 1 year ago

I'll open a separate issue for the other case.