Fix formatter with-statement after-as own line comment instability (#6033)

**Summary** Fix an instability in with statement formatter when there is
an own line comment as the `as`
```python
with (
    a as
    # bad comment
    b):
```

**Test Plan** Added the comment to the test cases.
This commit is contained in:
konsti 2023-07-24 20:12:07 +02:00 committed by GitHub
parent a9f535997d
commit 7f3797185c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 11 deletions

View file

@ -1370,15 +1370,15 @@ fn handle_with_item_comment<'a>(
SimpleTokenKind::As,
);
// If before the `as` keyword, then it must be a trailing comment of the context expression.
if comment.end() < as_token.start() {
// If before the `as` keyword, then it must be a trailing comment of the context expression.
CommentPlacement::trailing(context_expr, comment)
}
// Trailing end of line comment coming after the `as` keyword`.
else if comment.line_position().is_end_of_line() {
CommentPlacement::dangling(comment.enclosing_node(), comment)
} else {
CommentPlacement::Default(comment)
CommentPlacement::leading(optional_vars, comment)
}
}

View file

@ -2,7 +2,7 @@ use rustpython_parser::ast::WithItem;
use ruff_formatter::{write, Buffer, FormatResult};
use crate::comments::trailing_comments;
use crate::comments::{leading_comments, trailing_comments};
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::prelude::*;
@ -27,14 +27,22 @@ impl FormatNodeRule<WithItem> for FormatWithItem {
if let Some(optional_vars) = optional_vars {
write!(
f,
[
space(),
text("as"),
trailing_comments(trailing_as_comments),
space(),
optional_vars.format(),
]
[space(), text("as"), trailing_comments(trailing_as_comments)]
)?;
let leading_var_comments = comments.leading_comments(optional_vars.as_ref());
if leading_var_comments.is_empty() {
write!(f, [space(), optional_vars.format()])?;
} else {
write!(
f,
[
// Otherwise the comment would end up on the same line as the `as`
hard_line_break(),
leading_comments(leading_var_comments),
optional_vars.format()
]
)?;
}
}
Ok(())
}