mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-19 01:51:30 +00:00
Fix attribute chain own line comments (#5340)
## Motation Previously, ```python x = ( a1 .a2 # a . # b # c a3 ) ``` got formatted as ```python x = a1.a2 # a . # b # c a3 ``` which is invalid syntax. This fixes that. ## Summary This implements a basic form of attribute chaining (<https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#call-chains>) by checking if any inner attribute access contains an own line comment, and if this is the case, adds parentheses around the outermost attribute access while disabling parentheses for all inner attribute expressions. We want to replace this with an implementation that uses recursion or a stack while formatting instead of in `needs_parentheses` and also includes calls rather sooner than later, but i'm fixing this now because i'm uncomfortable with having known invalid syntax generation in the formatter. ## Test Plan I added new fixtures.
This commit is contained in:
parent
8879927b9a
commit
a52cd47c7f
4 changed files with 258 additions and 18 deletions
|
@ -1077,7 +1077,19 @@ fn handle_attribute_comment<'a>(
|
|||
.expect("Expected the `.` character after the value");
|
||||
|
||||
if TextRange::new(dot.end(), attribute.attr.start()).contains(comment.slice().start()) {
|
||||
CommentPlacement::dangling(attribute.into(), comment)
|
||||
if comment.line_position().is_end_of_line() {
|
||||
// Attach to node with b
|
||||
// ```python
|
||||
// x322 = (
|
||||
// a
|
||||
// . # end-of-line dot comment 2
|
||||
// b
|
||||
// )
|
||||
// ```
|
||||
CommentPlacement::trailing(comment.enclosing_node(), comment)
|
||||
} else {
|
||||
CommentPlacement::dangling(attribute.into(), comment)
|
||||
}
|
||||
} else {
|
||||
CommentPlacement::Default(comment)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue