mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-24 05:25:17 +00:00
Fix formatter instability with half-indented comment (#6460)
## Summary The bug was happening in this [loop](75f402eb82/crates/ruff_python_formatter/src/comments/placement.rs (L545)
). Basically, In the first iteration of the loop, the `comment_indentation` is bigger than `child_indentation` (`comment_indentation` is 7 and `child_indentation` is 4) making the `Ordering::Greater` branch execute. Inside the `Ordering::Greater` branch, the `if` block gets executed, resulting in the update of these variables. ```rust parent_body = current_body; current_body = Some(last_child_in_current_body); last_child_in_current_body = nested_child; ``` In the second iteration of the loop, `comment_indentation` is smaller than `child_indentation` (`comment_indentation` is 7 and `child_indentation` is 8) making the `Ordering::Less` branch execute. Inside the `Ordering::Less` branch, the `if` block gets executed, this is where the bug was happening. At this point `parent_body` should be a `StmtFunctionDef` but it was a `StmtClassDef`. Causing the comment to be incorrectly formatted. That happened for the following code: ```python class A: def f(): pass # strangely indented comment print() ``` There is only one problem that I couldn't figure it out a solution, the variable `current_body` in this [line](75f402eb82/crates/ruff_python_formatter/src/comments/placement.rs (L542C5-L542C49)
) now gives this warning _"value assigned to `current_body` is never read maybe it is overwritten before being read?"_ Any tips on how to solve that? Closes #5337 ## Test Plan Add new test case. --------- Co-authored-by: konstin <konstin@mailbox.org>
This commit is contained in:
parent
0ef6af807b
commit
b05574babd
5 changed files with 79 additions and 26 deletions
|
@ -109,6 +109,18 @@ else:
|
|||
if True: print("a") # 1
|
||||
elif True: print("b") # 2
|
||||
else: print("c") # 3
|
||||
|
||||
# Regression test for https://github.com/astral-sh/ruff/issues/5337
|
||||
if parent_body:
|
||||
if current_body:
|
||||
child_in_body()
|
||||
last_child_in_current_body() # may or may not have children on its own
|
||||
# a
|
||||
# b
|
||||
# c
|
||||
# d
|
||||
# e
|
||||
#f
|
||||
```
|
||||
|
||||
## Output
|
||||
|
@ -224,6 +236,18 @@ elif True:
|
|||
print("b") # 2
|
||||
else:
|
||||
print("c") # 3
|
||||
|
||||
# Regression test for https://github.com/astral-sh/ruff/issues/5337
|
||||
if parent_body:
|
||||
if current_body:
|
||||
child_in_body()
|
||||
last_child_in_current_body() # may or may not have children on its own
|
||||
# e
|
||||
# f
|
||||
# c
|
||||
# d
|
||||
# a
|
||||
# b
|
||||
```
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue