Skip to content

Commit 2c3cc31

Browse files
cushongoogle-java-format Team
authored andcommitted
Remove single-parameter lambda parentheses in the cleanup pass.
Extend `Cleanups` to remove parentheses around single-parameter untyped lambda parameters (`(x) -> x` -> `x -> x`), preserving comments inside the parentheses and inserting a separating space when the opening parenthesis is immediately preceded by an identifier (e.g. `return(x) -> x` -> `return x -> x`). PiperOrigin-RevId: 1004624100
1 parent c3659a6 commit 2c3cc31

3 files changed

Lines changed: 130 additions & 1 deletion

File tree

‎core/src/main/java/com/google/googlejavaformat/java/CleanupScanner.java‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import com.sun.source.tree.CompilationUnitTree;
3737
import com.sun.source.tree.EmptyStatementTree;
3838
import com.sun.source.tree.ImportTree;
39+
import com.sun.source.tree.LambdaExpressionTree;
3940
import com.sun.source.tree.NewClassTree;
4041
import com.sun.source.tree.Tree;
4142
import com.sun.source.tree.VariableTree;
@@ -49,7 +50,7 @@
4950
import org.jspecify.annotations.Nullable;
5051

5152
/// Scans the compilation unit for non-whitespace cleanup opportunities, such as removing redundant
52-
/// semicolons and empty annotation parentheses.
53+
/// semicolons, empty annotation parentheses, and single-parameter lambda parentheses.
5354
final class CleanupScanner extends TreePathScanner<@Nullable Void, @Nullable Void> {
5455

5556
// Replace with Flags.IMPLICIT_CLASS once JDK 25 is the minimum supported version
@@ -316,6 +317,33 @@ private void deleteSemicolonsInGaps(int start, int end, RangeSet<Integer> validS
316317
return null;
317318
}
318319

320+
@Override
321+
public @Nullable Void visitLambdaExpression(LambdaExpressionTree tree, @Nullable Void unused) {
322+
super.visitLambdaExpression(tree, null);
323+
if (tree.getParameters().size() != 1) {
324+
return null;
325+
}
326+
int startPos = getStartPosition(tree);
327+
int lparenIdx = nextTokenIndex(tokIndexAtOrAfter(startPos));
328+
if (lparenIdx < 0 || !toks.get(lparenIdx).getText().equals("(")) {
329+
return null;
330+
}
331+
int paramIdx = nextTokenIndex(lparenIdx + 1);
332+
int rparenIdx = nextTokenIndex(paramIdx + 1);
333+
if (rparenIdx < 0 || !toks.get(rparenIdx).getText().equals(")")) {
334+
return null;
335+
}
336+
Tok lparen = toks.get(lparenIdx);
337+
Tok rparen = toks.get(rparenIdx);
338+
int lparenStart = lparen.getPosition();
339+
int rparenEnd = rparen.getPosition() + rparen.length();
340+
if (!hasCommentsInRange(lparenStart, rparenEnd) && inRange(lparenStart, rparenEnd)) {
341+
activeDeletions.add(Range.closedOpen(lparenStart, lparenStart + lparen.length()));
342+
activeDeletions.add(Range.closedOpen(rparen.getPosition(), rparenEnd));
343+
}
344+
return null;
345+
}
346+
319347
// Hand-rolled lower-bound binary search to avoid allocating a dummy Tok or wrapper list for
320348
// Collections.binarySearch.
321349
private int tokIndexAtOrAfter(int pos) {
@@ -332,6 +360,16 @@ private int tokIndexAtOrAfter(int pos) {
332360
return lo;
333361
}
334362

363+
private int nextTokenIndex(int startIdx) {
364+
for (int i = max(0, startIdx); i < toks.size(); i++) {
365+
Tok tok = toks.get(i);
366+
if (tok.isToken() && !tok.getText().isEmpty()) {
367+
return i;
368+
}
369+
}
370+
return -1;
371+
}
372+
335373
private @Nullable Tok findTokenAtOrAfter(int startPos, int endPos, String text) {
336374
for (int i = tokIndexAtOrAfter(startPos); i < toks.size(); i++) {
337375
Tok tok = toks.get(i);

‎core/src/test/java/com/google/googlejavaformat/java/CleanupsTest.java‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,20 +461,109 @@ void f(String @Anno ... xs) {}
461461
assertThat(formatWithCleanups(input)).isEqualTo(expected);
462462
}
463463

464+
@Test
465+
public void singleParameterLambdaParens() throws Exception {
466+
String input =
467+
"""
468+
import java.util.function.Function;
469+
import java.util.function.BiFunction;
470+
import java.util.function.Supplier;
471+
472+
class T {
473+
Function<String, String> f1 = (x) -> x;
474+
Function<String, String> f2 = (_) -> "";
475+
Function<String, String> f3 = (String x) -> x;
476+
Function<String, String> f4 = (var x) -> x;
477+
Function<String, String> f5 = (@Anno var x) -> x;
478+
Function<String, String> f6 = (/* keep */ x) -> x;
479+
BiFunction<String, String, String> f7 = (x, y) -> x;
480+
Supplier<String> f8 = () -> "";
481+
Function<String, Function<String, String>> f9 = (x) -> (y) -> y;
482+
483+
Function<String, String> g() {
484+
return(x) -> x;
485+
}
486+
}
487+
""";
488+
String expected =
489+
"""
490+
import java.util.function.BiFunction;
491+
import java.util.function.Function;
492+
import java.util.function.Supplier;
493+
494+
class T {
495+
Function<String, String> f1 = x -> x;
496+
Function<String, String> f2 = _ -> "";
497+
Function<String, String> f3 = (String x) -> x;
498+
Function<String, String> f4 = (var x) -> x;
499+
Function<String, String> f5 = (@Anno var x) -> x;
500+
Function<String, String> f6 = (/* keep */ x) -> x;
501+
BiFunction<String, String, String> f7 = (x, y) -> x;
502+
Supplier<String> f8 = () -> "";
503+
Function<String, Function<String, String>> f9 = x -> y -> y;
504+
505+
Function<String, String> g() {
506+
return x -> x;
507+
}
508+
}
509+
""";
510+
assertThat(formatWithCleanups(input)).isEqualTo(expected);
511+
}
512+
513+
@Test
514+
public void singleParameterLambdaParens_outsideRange() throws Exception {
515+
String input =
516+
"""
517+
class T {
518+
Function<String, String> f = (x) -> {
519+
return x;
520+
};
521+
}
522+
""";
523+
// Partial formatting of a lambda body reformats the enclosing statement, but the cleanup only
524+
// applies to the requested range, so the parentheses on the unrequested line are kept.
525+
String expected =
526+
"""
527+
class T {
528+
Function<String, String> f =
529+
(x) -> {
530+
return x;
531+
};
532+
}
533+
""";
534+
int start = input.indexOf("return");
535+
int end = input.indexOf(';', start) + 1;
536+
assertThat(new Formatter().formatSource(input, ImmutableList.of(Range.closedOpen(start, end))))
537+
.isEqualTo(expected);
538+
}
539+
464540
@Test
465541
public void aospStyleCleanups() throws Exception {
466542
String input =
467543
"""
544+
import java.util.function.Function;
545+
468546
@Anno()
469547
class T {
470548
int x;;
549+
void f() {
550+
Runnable r = () -> {};
551+
Function<String, String> fn = (s) -> s;
552+
}
471553
}
472554
""";
473555
String expected =
474556
"""
557+
import java.util.function.Function;
558+
475559
@Anno
476560
class T {
477561
int x;
562+
563+
void f() {
564+
Runnable r = () -> {};
565+
Function<String, String> fn = s -> s;
566+
}
478567
}
479568
""";
480569
assertThat(formatWithCleanupsAosp(input)).isEqualTo(expected);

‎core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ public class FormatterIntegrationTest {
7878
"i281")
7979
// Empty annotation parens (b/381242320)
8080
.add("B381242320")
81+
// Single-parameter lambda parentheses (b/154644558)
82+
.add("B21305044")
8183
.build();
8284

8385
@Parameters(name = "{index}: {0}")

0 commit comments

Comments
 (0)