Fix unstable f-string formatting for expressions containing a trailing comma (#15545)

This commit is contained in:
Micha Reiser 2025-01-17 10:08:09 +01:00 committed by GitHub
parent fdb9f4e404
commit 1ecb7ce645
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 45 additions and 0 deletions

View file

@ -206,6 +206,20 @@ impl<'fmt, 'ast, 'buf> JoinCommaSeparatedBuilder<'fmt, 'ast, 'buf> {
pub(crate) fn finish(&mut self) -> FormatResult<()> {
self.result.and_then(|()| {
// Don't add a magic trailing comma when formatting an f-string expression
// that always must be flat because the `expand_parent` forces enclosing
// groups to expand, e.g. `print(f"{(a,)} ")` would format the f-string in
// flat mode but the `print` call gets expanded because of the `expand_parent`.
if self
.fmt
.context()
.f_string_state()
.can_contain_line_breaks()
== Some(false)
{
return Ok(());
}
if let Some(last_end) = self.entries.position() {
let magic_trailing_comma = has_magic_trailing_comma(
TextRange::new(last_end, self.sequence_end),

View file

@ -147,6 +147,17 @@ pub(crate) enum FStringState {
Outside,
}
impl FStringState {
pub(crate) fn can_contain_line_breaks(self) -> Option<bool> {
match self {
FStringState::InsideExpressionElement(context) => {
Some(context.can_contain_line_breaks())
}
FStringState::Outside => None,
}
}
}
/// The position of a top-level statement in the module.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
pub(crate) enum TopLevelStatementPosition {