diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py index a60efa1cdd..f808f11e94 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py @@ -33,3 +33,27 @@ result_f = ( # comment '' ) + +( + f'{1}' # comment + f'{2}' +) + +( + f'{1}' + f'{2}' # comment +) + +( + 1, ( # comment + f'{2}' + ) +) + +( + ( + f'{1}' + # comment + ), + 2 +) diff --git a/crates/ruff_python_formatter/src/comments/placement.rs b/crates/ruff_python_formatter/src/comments/placement.rs index 1fb7fb7f4c..e1f299e531 100644 --- a/crates/ruff_python_formatter/src/comments/placement.rs +++ b/crates/ruff_python_formatter/src/comments/placement.rs @@ -70,6 +70,20 @@ fn handle_parenthesized_comment<'a>( comment: DecoratedComment<'a>, locator: &Locator, ) -> CommentPlacement<'a> { + // As a special-case, ignore comments within f-strings, like: + // ```python + // ( + // f'{1}' # comment + // f'{2}' + // ) + // ``` + // These can't be parenthesized, as they must fall between two string tokens in an implicit + // concatenation. But the expression ranges only include the `1` and `2` above, so we also + // can't lex the contents between them. + if comment.enclosing_node().is_expr_f_string() { + return CommentPlacement::Default(comment); + } + let Some(preceding) = comment.preceding_node() else { return CommentPlacement::Default(comment); }; diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap index aa3f0a5133..37fa5a5e40 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap @@ -39,6 +39,30 @@ result_f = ( # comment '' ) + +( + f'{1}' # comment + f'{2}' +) + +( + f'{1}' + f'{2}' # comment +) + +( + 1, ( # comment + f'{2}' + ) +) + +( + ( + f'{1}' + # comment + ), + 2 +) ``` ## Output @@ -76,6 +100,30 @@ result_f = ( # comment "" ) + +( + f"{1}" # comment + f"{2}" +) + +( + f"{1}" f"{2}" # comment +) + +( + 1, + ( # comment + f"{2}" + ), +) + +( + ( + f"{1}" + # comment + ), + 2, +) ```