try a different approach

This commit is contained in:
Brent Westbrook 2025-11-13 10:09:37 -05:00
parent 9bee558c3a
commit e0b0b54b25
No known key found for this signature in database
3 changed files with 44 additions and 20 deletions

View file

@ -1861,16 +1861,10 @@ fn handle_unary_op_comment<'a>(
| SimpleTokenKind::Plus
| SimpleTokenKind::Minus
)));
let lparen_start = tokenizer
let up_to = tokenizer
.find(|token| token.kind == SimpleTokenKind::LParen)
.map(|lparen| lparen.start());
let up_to = lparen_start.unwrap_or(unary_op.operand.start());
if lparen_start.is_none()
&& comment.end() < unary_op.operand.start()
&& comment.line_position().is_end_of_line()
{
CommentPlacement::dangling(unary_op, comment)
} else if comment.end() < up_to {
.map_or(unary_op.operand.start(), |lparen| lparen.start());
if comment.end() < up_to {
CommentPlacement::leading(unary_op, comment)
} else {
CommentPlacement::Default(comment)

View file

@ -836,7 +836,8 @@ impl<'a> Operand<'a> {
let leading = comments.leading(*expression);
if is_expression_parenthesized((*expression).into(), comments.ranges(), source) {
leading.iter().any(|comment| {
!comment.is_formatted()
comment.end() <= expression.start()
&& !comment.is_formatted()
&& matches!(
SimpleTokenizer::new(
source,
@ -922,7 +923,8 @@ impl Format<PyFormatContext<'_>> for Operand<'_> {
let leading_before_parentheses_end = leading
.iter()
.rposition(|comment| {
comment.is_unformatted()
comment.end() <= expression.start()
&& comment.is_unformatted()
&& matches!(
SimpleTokenizer::new(
f.context().source(),

View file

@ -200,10 +200,21 @@ def foo():
):
pass
# Regression test for https://github.com/astral-sh/ruff/issues/19226
# Regression tests for https://github.com/astral-sh/ruff/issues/19226
if '' and (not #
0):
pass
if '' and (not #
(0)
):
pass
if '' and (not
( #
0
)):
pass
```
## Output
@ -322,28 +333,31 @@ if (
## Trailing operator comments
if (
not aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # comment
if ( # comment
not aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
):
pass
if (
~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # comment
# comment
~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
):
pass
if (
-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # comment
# comment
-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
):
pass
if (
+aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # comment
# comment
+aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
):
pass
@ -368,7 +382,9 @@ if (
):
pass
if not a: # comment
if ( # comment
not a
):
pass
# Regression test for: https://github.com/astral-sh/ruff/issues/7423
@ -416,9 +432,21 @@ def foo():
pass
# Regression test for https://github.com/astral-sh/ruff/issues/19226
# Regression tests for https://github.com/astral-sh/ruff/issues/19226
if "" and ( #
not 0
):
pass
if "" and ( #
not (0)
):
pass
if "" and (
not 0 #
not ( #
0
)
):
pass
```