From 05951dd3387055a3ab0b5a01666eaa01ae5576a3 Mon Sep 17 00:00:00 2001 From: qdegraaf <34540841+qdegraaf@users.noreply.github.com> Date: Fri, 8 Sep 2023 11:40:58 +0200 Subject: [PATCH] Fix inconsistent `expr_lambda` formatting (#6318) --- .../test/fixtures/ruff/expression/lambda.py | 35 +++++++++ .../src/expression/expr_lambda.rs | 5 ++ .../format@expression__lambda.py.snap | 73 ++++++++++++++++++- 3 files changed, 109 insertions(+), 4 deletions(-) diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py index 32a57bed4a..12e167d413 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py @@ -118,3 +118,38 @@ lambda a, /, c: a # 4 None # 5 ) + +( + lambda + # comment + *x: x +) + +( + lambda + # comment 1 + * + # comment 2 + x: + # comment 3 + x +) + +( + lambda # comment 1 + * # comment 2 + x: # comment 3 + x +) + +lambda *x\ + :x + +( + lambda + # comment + *\ + x: x +) + + diff --git a/crates/ruff_python_formatter/src/expression/expr_lambda.rs b/crates/ruff_python_formatter/src/expression/expr_lambda.rs index 54cd619b13..d2244596e0 100644 --- a/crates/ruff_python_formatter/src/expression/expr_lambda.rs +++ b/crates/ruff_python_formatter/src/expression/expr_lambda.rs @@ -43,6 +43,11 @@ impl FormatNodeRule for FormatExprLambda { write!(f, [dangling_comments(dangling)])?; } + // Insert hard line break if body has leading comment to ensure consistent formatting + if comments.has_leading(body.as_ref()) { + write!(f, [hard_line_break()])?; + } + write!(f, [body.format()]) } diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap index 73e3bcc04d..7585e7f371 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap @@ -124,6 +124,41 @@ lambda a, /, c: a # 4 None # 5 ) + +( + lambda + # comment + *x: x +) + +( + lambda + # comment 1 + * + # comment 2 + x: + # comment 3 + x +) + +( + lambda # comment 1 + * # comment 2 + x: # comment 3 + x +) + +lambda *x\ + :x + +( + lambda + # comment + *\ + x: x +) + + ``` ## Output @@ -185,7 +220,8 @@ lambda x: lambda y: lambda z: ( # Trailing a = ( - lambda: # Dangling + lambda: + # Dangling 1 ) @@ -232,22 +268,51 @@ lambda a, /, c: a # Dangling comments without parameters. ( - lambda: # 3 + lambda: + # 3 None ) ( - lambda: # 3 + lambda: + # 3 None ) ( - lambda: # 1 + lambda: + # 1 # 2 # 3 # 4 None # 5 ) + +( + lambda # comment + *x: x +) + +( + lambda # comment 1 + # comment 2 + *x: + # comment 3 + x +) + +( + lambda # comment 1 + # comment 2 + *x: x # comment 3 +) + +lambda *x: x + +( + lambda # comment + *x: x +) ```