Fix Comment Preservation in PatKind::Paren Patterns
Fixes #6110
Description:
This pull request resolves an issue where rustfmt was removing comments inside parentheses in PatKind::Paren patterns. The fix ensures that comments are preserved during formatting, maintaining the original code structure and readability.
Changes:
- [x] Modified the formatting logic for PatKind::Paren to correctly handle comments within parentheses.
- [x] Added tests to verify that comments are preserved in PatKind::Paren patterns.
@yuvraj-wale unfortunately we can't accept these changes as is since they modify the formatting of already formatted code. rustfmt has strong guarantees about not introducing stable formatting changes so you'll likely need to come up with a different approach to solve this one.
One idea you could try is to manually write the comment recovery code.
We might be able to move forward with these changes if they were version gated, though I'd want some clarify from the style team on whether or not the new formatting is what's expected based on the Rust Style Guide
Thanks for the feedback! I will look into recovering comments manually and try to update the PR.
Great. Let me know if you need any pointers on how to get started
Hey @ytmimi, I've been digging into this issue for a while now, and I've successfully preserved comments in PatKind::Paren patterns. However, I'm encountering difficulties with their formatting, particularly regarding newlines and whitespaces. Could you provide some guidance on how to apply proper formatting? I suspect it involves selecting the appropriate tactics and utilizing ListFormatting for effective formatting if I am not wrong.
I'm wondering if overflow::rewrite_with_parens is the right thing to call here since it seems to be the source of a lot of the issues you're running into. You might only want to call it after conditionally determining that there are comments before or after the inner pattern.
Another approach to preserve comments within the PatKind::Paren would be to return the contents of the Span unformatted with Some(context.snippet(span).to_owned()). This wouldn't apply any formatting, and would therefore keep the comments.
@ytmimi Ah, I see what you mean about modifying the formatting of already formatted code. I was heading in a different direction initially. What I've done now is to extract the pre and post snippets around the inner pattern, which is formatted as usual according to the original implementation. By combining these snippets with the inner pattern, the comments are preserved while the formatting is still applied. Do you think this is the right approach and implementation? I apologize if I've misunderstood anything again. Thanks!
@yuvraj-wale possibly. I think you'll need to add test cases to this PR to know for sure.