mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-23 04:55:09 +00:00
Fix zulip unstable formatting with end-of-line comments (#6386)
## Bug Given ```python x = () - (# ) ``` the comment is a dangling comment of the empty tuple. This is an end-of-line comment so it may move after the expression. It still expands the parent, so the operator breaks: ```python x = ( () - () # ) ``` In the next formatting pass, the comment is not a trailing tuple but a trailing bin op comment, so the bin op doesn't break anymore. The comment again expands the parent, so we still add the superfluous parentheses ```python x = ( () - () # ) ``` ## Fix The new formatting is to keep the comment on the empty tuple. This is a log uglier and again has additional outer parentheses, but it's stable: ```python x = ( () - ( # ) ) ``` ## Alternatives Black formats all the examples above as ```python x = () - () # ``` which i find better. I would be happy about any suggestions for better solutions than the current one. I'd mainly need a workaround for expand parent having an effect on the bin op instead of first moving the comment to the end and then applying expand parent to the assign statement.
This commit is contained in:
parent
2bd345358f
commit
90ba40c23c
11 changed files with 73 additions and 8 deletions
|
@ -253,6 +253,16 @@ impl<'ast> Format<PyFormatContext<'ast>> for EmptyWithDanglingComments<'_> {
|
|||
self.opening,
|
||||
// end-of-line comments
|
||||
trailing_comments(&self.comments[..end_of_line_split]),
|
||||
// Avoid unstable formatting with
|
||||
// ```python
|
||||
// x = () - (#
|
||||
// )
|
||||
// ```
|
||||
// Without this the comment would go after the empty tuple first, but still expand
|
||||
// the bin op. In the second formatting pass they are trailing bin op comments
|
||||
// so the bin op collapse. Suboptimally we keep parentheses around the bin op in
|
||||
// either case.
|
||||
(!self.comments[..end_of_line_split].is_empty()).then_some(hard_line_break()),
|
||||
// own line comments, which need to be indented
|
||||
soft_block_indent(&dangling_comments(&self.comments[end_of_line_split..])),
|
||||
self.closing
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue