Skip to content

Commit

Permalink
Fix placement for comments within f-strings concatenations (#7047)
Browse files Browse the repository at this point in the history
## Summary

Restores the dangling comment handling for f-strings, which broke with
the parenthesized expression code.

Closes #6898.

## Test Plan

`cargo test`

No change in any of the similarity indexes or changed file counts:

| project | similarity index | total files | changed files |

|--------------|------------------:|------------------:|------------------:|
| cpython | 0.76083 | 1789 | 1632 |
| django | 0.99957 | 2760 | 67 |
| transformers | 0.99927 | 2587 | 468 |
| twine | 0.99982 | 33 | 1 |
| typeshed | 0.99978 | 3496 | 2173 |
| warehouse | 0.99818 | 648 | 24 |
| zulip | 0.99942 | 1437 | 32 |
  • Loading branch information
charliermarsh authored Sep 1, 2023
1 parent fbc9b5a commit dea6553
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,27 @@
# comment
''
)

(
f'{1}' # comment
f'{2}'
)

(
f'{1}'
f'{2}' # comment
)

(
1, ( # comment
f'{2}'
)
)

(
(
f'{1}'
# comment
),
2
)
14 changes: 14 additions & 0 deletions crates/ruff_python_formatter/src/comments/placement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,20 @@ fn handle_parenthesized_comment<'a>(
comment: DecoratedComment<'a>,
locator: &Locator,
) -> CommentPlacement<'a> {
// As a special-case, ignore comments within f-strings, like:
// ```python
// (
// f'{1}' # comment
// f'{2}'
// )
// ```
// These can't be parenthesized, as they must fall between two string tokens in an implicit
// concatenation. But the expression ranges only include the `1` and `2` above, so we also
// can't lex the contents between them.
if comment.enclosing_node().is_expr_f_string() {
return CommentPlacement::Default(comment);
}

let Some(preceding) = comment.preceding_node() else {
return CommentPlacement::Default(comment);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ result_f = (
# comment
''
)
(
f'{1}' # comment
f'{2}'
)
(
f'{1}'
f'{2}' # comment
)
(
1, ( # comment
f'{2}'
)
)
(
(
f'{1}'
# comment
),
2
)
```

## Output
Expand Down Expand Up @@ -76,6 +100,30 @@ result_f = (
# comment
""
)
(
f"{1}" # comment
f"{2}"
)
(
f"{1}" f"{2}" # comment
)
(
1,
( # comment
f"{2}"
),
)
(
(
f"{1}"
# comment
),
2,
)
```


Expand Down

0 comments on commit dea6553

Please sign in to comment.