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

@ -227,6 +227,7 @@ fn handle_enclosed_comment<'a>(
}
AnyNodeRef::StmtImportFrom(import_from) => handle_import_from_comment(comment, import_from),
AnyNodeRef::StmtWith(with_) => handle_with_comment(comment, with_),
AnyNodeRef::ExprCall(_) => handle_call_comment(comment),
AnyNodeRef::ExprConstant(_) => {
if let Some(AnyNodeRef::ExprFString(fstring)) = comment.enclosing_parent() {
CommentPlacement::dangling(fstring, comment)
@ -984,6 +985,29 @@ fn handle_dict_unpacking_comment<'a>(
}
}
/// Handle comments between a function call and its arguments. For example, attach the following as
/// dangling on the call:
/// ```python
/// (
/// func
/// # dangling
/// ()
/// )
/// ```
fn handle_call_comment(comment: DecoratedComment) -> CommentPlacement {
if comment.line_position().is_own_line() {
if comment.preceding_node().is_some_and(|preceding| {
comment.following_node().is_some_and(|following| {
preceding.end() < comment.start() && comment.end() < following.start()
})
}) {
return CommentPlacement::dangling(comment.enclosing_node(), comment);
}
}
CommentPlacement::Default(comment)
}
/// Own line comments coming after the node are always dangling comments
/// ```python
/// (