Hug closing } when f-string expression has a format specifier (#18704)

This commit is contained in:
Micha Reiser 2025-06-17 07:39:42 +02:00 committed by GitHub
parent 2b731d19b9
commit c22f809049
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 323 additions and 198 deletions

View file

@ -321,28 +321,33 @@ fn handle_enclosed_comment<'a>(
},
AnyNodeRef::FString(fstring) => CommentPlacement::dangling(fstring, comment),
AnyNodeRef::TString(tstring) => CommentPlacement::dangling(tstring, comment),
AnyNodeRef::InterpolatedElement(_) => {
// Handle comments after the format specifier (should be rare):
//
// ```python
// f"literal {
// expr:.3f
// # comment
// }"
// ```
//
// This is a valid comment placement.
if matches!(
comment.preceding_node(),
Some(
AnyNodeRef::InterpolatedElement(_)
| AnyNodeRef::InterpolatedStringLiteralElement(_)
)
) {
CommentPlacement::trailing(comment.enclosing_node(), comment)
} else {
handle_bracketed_end_of_line_comment(comment, source)
AnyNodeRef::InterpolatedElement(element) => {
if let Some(preceding) = comment.preceding_node() {
if comment.line_position().is_own_line() && element.format_spec.is_some() {
return if comment.following_node().is_some() {
// Own line comment before format specifier
// ```py
// aaaaaaaaaaa = f"""asaaaaaaaaaaaaaaaa {
// aaaaaaaaaaaa + bbbbbbbbbbbb + ccccccccccccccc + dddddddd
// # comment
// :.3f} cccccccccc"""
// ```
CommentPlacement::trailing(preceding, comment)
} else {
// TODO: This can be removed once format specifiers with a newline are a syntax error.
// This is to handle cases like:
// ```py
// x = f"{x !s
// :>0
// # comment 21
// }"
// ```
CommentPlacement::trailing(element, comment)
};
}
}
handle_bracketed_end_of_line_comment(comment, source)
}
AnyNodeRef::ExprList(_)