mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-01 06:11:43 +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
|
@ -600,8 +600,13 @@ def test(x, y):
|
|||
def other(y, z):
|
||||
if y == z:
|
||||
pass
|
||||
# Trailing `if` comment
|
||||
# Trailing `other` function comment
|
||||
# Trailing `pass` comment
|
||||
# Trailing `if` statement comment
|
||||
|
||||
class Test:
|
||||
def func():
|
||||
pass
|
||||
# Trailing `func` function comment
|
||||
|
||||
test(10, 20)
|
||||
"#;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue