From f499f0ca6086e6044ed4cc394367a95f5fdd3bad Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Wed, 8 Nov 2023 20:25:23 -0800 Subject: [PATCH] Avoid inserting trailing commas within f-strings (#8574) Closes https://github.com/astral-sh/ruff/issues/8556. --- .../test/fixtures/flake8_commas/COM81.py | 9 ++++++++- .../flake8_commas/rules/trailing_commas.rs | 17 +++++++++++++++-- ...__rules__flake8_commas__tests__COM81.py.snap | 2 +- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py b/crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py index 8bc53dcd34760..72d9eff40fe3e 100644 --- a/crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py +++ b/crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py @@ -42,7 +42,7 @@ 4, ) -foo = 3, +foo = 3, class A(object): foo = 3 @@ -639,3 +639,10 @@ def foo( :20 ], ) + +# Make sure we don't insert commas within f-strings. +f"""This is a test. { + "Another sentence." + if True else + "Alternative route!" +}""" diff --git a/crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs b/crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs index e3fdd58a7e256..51c706d31d327 100644 --- a/crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs +++ b/crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs @@ -223,11 +223,24 @@ pub(crate) fn trailing_commas( tokens: &[LexResult], locator: &Locator, ) { + let mut fstrings = 0u32; let tokens = tokens .iter() .flatten() - // Completely ignore comments -- they just interfere with the logic. - .filter(|&r| !matches!(r, (Tok::Comment(_), _))) + .filter(|(tok, _)| match tok { + // Completely ignore comments -- they just interfere with the logic. + Tok::Comment(_) => false, + // Ignore content within f-strings. + Tok::FStringStart => { + fstrings = fstrings.saturating_add(1); + false + } + Tok::FStringEnd => { + fstrings = fstrings.saturating_sub(1); + false + } + _ => fstrings == 0, + }) .map(Token::from_spanned); let tokens = [Token::irrelevant(), Token::irrelevant()] .into_iter() diff --git a/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap b/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap index d9e4fe146fa65..b584c99c8b34f 100644 --- a/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap +++ b/crates/ruff_linter/src/rules/flake8_commas/snapshots/ruff_linter__rules__flake8_commas__tests__COM81.py.snap @@ -106,7 +106,7 @@ COM81.py:45:8: COM818 Trailing comma on bare tuple prohibited | 43 | ) 44 | -45 | foo = 3, +45 | foo = 3, | ^ COM818 46 | 47 | class A(object):