mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-27 04:19:18 +00:00
Fix comment formatting for yielded tuples (#6603)
## Summary Closes https://github.com/astral-sh/ruff/issues/6384, although I think the issue was fixed already on main, for the most part. The linked issue is around formatting expressions like: ```python def test(): ( yield #comment 1 * # comment 2 # comment 3 test # comment 4 ) ``` On main, prior to this PR, we now format like: ```python def test(): ( yield ( # comment 1 # comment 2 # comment 3 *test ) # comment 4 ) ``` Which strikes me as reasonable. (We can't test this, since it's a syntax error after for our parser, despite being a syntax error in both cases from CPython's perspective.) Meanwhile, Black does: ```python def test(): ( yield # comment 1 * # comment 2 # comment 3 test # comment 4 ) ``` So our formatting differs in that we move comments between the star and the expression above the star. As of this PR, we also support formatting this input, which is valid: ```python def test(): ( yield #comment 1 * # comment 2 # comment 3 test, # comment 4 1 ) ``` Like: ```python def test(): ( yield ( # comment 1 ( # comment 2 # comment 3 *test, # comment 4 1, ) ) ) ``` There were two fixes here: (1) marking starred comments as dangling and formatting them properly; and (2) supporting parenthesized comments for tuples that don't contain their own parentheses, as is often the case for yielded tuples (previously, we hit a debug assert). Note that this diff ## Test Plan cargo test
This commit is contained in:
parent
7ee2ae8395
commit
12f3c4c931
7 changed files with 88 additions and 21 deletions
|
@ -1,6 +1,6 @@
|
|||
use ruff_python_ast::ExprStarred;
|
||||
|
||||
use crate::comments::SourceComment;
|
||||
use crate::comments::{dangling_comments, SourceComment};
|
||||
use ruff_formatter::write;
|
||||
use ruff_python_ast::node::AnyNodeRef;
|
||||
|
||||
|
@ -20,7 +20,10 @@ impl FormatNodeRule<ExprStarred> for FormatExprStarred {
|
|||
ctx: _,
|
||||
} = item;
|
||||
|
||||
write!(f, [text("*"), value.format()])
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling = comments.dangling_comments(item);
|
||||
|
||||
write!(f, [text("*"), dangling_comments(dangling), value.format()])
|
||||
}
|
||||
|
||||
fn fmt_dangling_comments(
|
||||
|
|
|
@ -204,7 +204,7 @@ impl NeedsParentheses for ExprTuple {
|
|||
}
|
||||
|
||||
/// Check if a tuple has already had parentheses in the input
|
||||
fn is_tuple_parenthesized(tuple: &ExprTuple, source: &str) -> bool {
|
||||
pub(crate) fn is_tuple_parenthesized(tuple: &ExprTuple, source: &str) -> bool {
|
||||
let Some(elt) = tuple.elts.first() else {
|
||||
return false;
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue