Fix formatting of comments between function and arguments (#6826)

## Summary

We now format comments between a function and its arguments as dangling.
Like with other strange placements, I've biased towards preserving the
existing formatting, rather than attempting to reorder the comments.

Closes https://github.com/astral-sh/ruff/issues/6818.

## Test Plan

`cargo test`

Before:

| project      | similarity index |
|--------------|------------------|
| cpython      | 0.76050          |
| django       | 0.99820          |
| transformers | 0.99800          |
| twine        | 0.99876          |
| typeshed     | 0.99953          |
| warehouse    | 0.99615          |
| zulip        | 0.99729          |

After:

| project      | similarity index |
|--------------|------------------|
| cpython      | 0.76050          |
| django       | 0.99820          |
| transformers | 0.99800          |
| twine        | 0.99876          |
| typeshed     | 0.99953          |
| warehouse    | 0.99615          |
| zulip        | 0.99729          |
This commit is contained in:
Charlie Marsh 2023-08-25 00:06:56 -04:00 committed by GitHub
parent f754ad5898
commit 59e70896c0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 186 additions and 32 deletions

View file

@ -4,7 +4,7 @@ use ruff_python_ast::{Constant, Expr, ExprAttribute, ExprConstant, Ranged};
use ruff_python_trivia::{find_only_token_in_range, SimpleTokenKind};
use ruff_text_size::TextRange;
use crate::comments::{dangling_comments, trailing_comments, SourceComment};
use crate::comments::{dangling_comments, SourceComment};
use crate::expression::parentheses::{
is_expression_parenthesized, NeedsParentheses, OptionalParentheses, Parentheses,
};
@ -88,10 +88,10 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
// (
// (
// a
// ) # `before_dot_end_of_line`
// # `before_dot_own_line`
// . # `after_dot_end_of_line`
// # `after_dot_own_line`
// ) # `before_dot`
// # `before_dot`
// . # `after_dot`
// # `after_dot`
// b
// )
// ```
@ -110,24 +110,12 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
)
};
let (before_dot_end_of_line, before_dot_own_line) = before_dot.split_at(
before_dot.partition_point(|comment| comment.line_position().is_end_of_line()),
);
let (after_dot_end_of_line, after_dot_own_line) = after_dot.split_at(
after_dot.partition_point(|comment| comment.line_position().is_end_of_line()),
);
write!(
f,
[
trailing_comments(before_dot_end_of_line),
(!before_dot.is_empty()).then_some(hard_line_break()),
dangling_comments(before_dot_own_line),
dangling_comments(before_dot),
text("."),
trailing_comments(after_dot_end_of_line),
(!after_dot.is_empty()).then_some(hard_line_break()),
dangling_comments(after_dot_own_line),
dangling_comments(after_dot),
attr.format()
]
)