Do not consider f-strings with escaped newlines as multiline (#14624)

## Summary

This PR fixes a bug in the f-string formatting to not consider the
escaped newlines for `is_multiline`. This is done by checking if the
f-string is triple-quoted or not similar to normal string literals.

This is not required to be gated behind preview because the logic change
for `is_multiline` was added in
https://github.com/astral-sh/ruff/pull/14454.

## Test Plan

Add a test case which formats differently on `main`:
https://play.ruff.rs/ea3c55c2-f0fe-474e-b6b8-e3365e0ede5e
This commit is contained in:
Dhruv Manilawala 2024-11-27 15:55:38 +05:30 committed by GitHub
parent 4cd2b9926e
commit f96fa6b0e2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 124 additions and 5 deletions

View file

@ -113,10 +113,12 @@ impl StringLikeExtensions for ast::StringLike<'_> {
fn contains_line_break_or_comments(
elements: &ast::FStringElements,
context: &PyFormatContext,
is_triple_quoted: bool,
) -> bool {
elements.iter().any(|element| match element {
ast::FStringElement::Literal(literal) => {
context.source().contains_line_break(literal.range())
is_triple_quoted
&& context.source().contains_line_break(literal.range())
}
ast::FStringElement::Expression(expression) => {
// Expressions containing comments can't be joined.
@ -132,7 +134,11 @@ impl StringLikeExtensions for ast::StringLike<'_> {
// ```
context.comments().contains_comments(expression.into())
|| expression.format_spec.as_deref().is_some_and(|spec| {
contains_line_break_or_comments(&spec.elements, context)
contains_line_break_or_comments(
&spec.elements,
context,
is_triple_quoted,
)
})
|| expression.debug_text.as_ref().is_some_and(|debug_text| {
memchr2(b'\n', b'\r', debug_text.leading.as_bytes()).is_some()
@ -144,7 +150,11 @@ impl StringLikeExtensions for ast::StringLike<'_> {
}
if is_f_string_formatting_enabled(context) {
contains_line_break_or_comments(&f_string.elements, context)
contains_line_break_or_comments(
&f_string.elements,
context,
f_string.flags.is_triple_quoted(),
)
} else {
context.source().contains_line_break(f_string.range())
}