From eb7bc9abf4c69866ddc5314893a1ecd5115958c3 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 27 Nov 2026 04:05:01 -0800 Subject: [PATCH] Hug single block lambda arguments on the first line of dereference chains with an extra `+4` indent, matching expression lambdas. Previously, calls staying on the first line of a dereference chain with trailing dereferences hugged single expression lambdas with `+4` (`huggedPlusIndent`), while suppressing hugging altogether for single block lambdas via `notHuggable`/`doNotHug`. That left block lambdas inconsistent with expression lambdas, inconsistent across the 4-character receiver break threshold (e.g. `item.withCallback(...)` vs. `someLongReceiverName` breaking before `.withCallback(...)`), and inconsistent between the chain head and subsequent chained calls. This change unifies block and expression lambdas under `huggedPlusIndent`, removing `notHuggable`, `doNotHug`, and `hasHuggedBlockLambda` and replacing the remaining class-body suppression with an explicit `allowBlockLambdaHug` parameter on `addArguments`. It also propagates `huggedPlusIndent` through `visitNewClass` for chained constructor calls, avoids double-indenting when the chain already broke at an earlier dot or type argument list, and covers chains where a prefix element is followed by a trailing dereference (e.g. `MyClass.computeItems(...).stream()`). PiperOrigin-RevId: 1031175750 --- .../java/JavaInputAstVisitor.java | 161 +++++++---------- .../java/testdata/LambdaHug.input | 11 ++ .../java/testdata/LambdaHug.output | 167 ++++++++++++------ 3 files changed, 195 insertions(+), 144 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index d8d81ef00..646ba27ad 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -66,7 +66,6 @@ import com.google.common.collect.PeekingIterator; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; -import com.google.common.collect.Sets; import com.google.common.collect.Streams; import com.google.common.collect.TreeRangeSet; import com.google.errorprone.annotations.CheckReturnValue; @@ -698,6 +697,11 @@ public Void visitTypeCast(TypeCastTree node, Void unused) { @Override public Void visitNewClass(NewClassTree node, Void unused) { + visitNewClass(node, ZERO); + return null; + } + + private void visitNewClass(NewClassTree node, Indent huggedPlusIndent) { sync(node); builder.open(ZERO); if (node.getEnclosingExpression() != null) { @@ -713,16 +717,18 @@ public Void visitNewClass(NewClassTree node, Void unused) { visitModifiers( node.getClassBody().getModifiers(), Direction.HORIZONTAL, Optional.empty()); visitAnnotations(annotations, BreakOrNot.NO, BreakOrNot.YES); - doNotHug(node); } scan(node.getIdentifier(), null); - addArguments(node.getArguments(), plusFour); + addArguments( + node.getArguments(), + plusFour, + huggedPlusIndent, + /* allowBlockLambdaHug= */ node.getClassBody() == null); builder.close(); if (node.getClassBody() != null) { addBodyDeclarations( node.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES); } - return null; } @Override @@ -826,10 +832,11 @@ private void visitEnumConstantDeclaration(VariableTree enumConstant) { builder.guessToken("("); builder.guessToken(")"); } else { - if (init.getClassBody() != null) { - doNotHug(init); - } - addArguments(init.getArguments(), plusFour); + addArguments( + init.getArguments(), + plusFour, + ZERO, + /* allowBlockLambdaHug= */ init.getClassBody() == null); } if (init.getClassBody() != null) { addBodyDeclarations( @@ -3083,10 +3090,15 @@ private void visitDot(ExpressionTree node0) { token("."); } else { builder.open(plusFour); - if (!stack.isEmpty()) { - doNotHug(node); + ExpressionTree base = getArrayBase(node); + if (!stack.isEmpty() && base instanceof NewClassTree newClass) { + // Constructor calls starting a chain with trailing dereferences (e.g. + // `new Thread(() -> { ... }).start()`) stay on the first line, so indent a hugged + // lambda argument by an extra +4 to distinguish it from the trailing dereferences. + visitNewClass(newClass, plusFour); + } else { + scan(base, null); } - scan(getArrayBase(node), null); builder.breakOp(); needDot = true; } @@ -3187,18 +3199,14 @@ private void visitRegularDot(List items, boolean needDot) { token("."); length++; } - if (!hasBroken && i < items.size() - 1) { - doNotHug(e); - } if (!fillFirstArgument(e, items, trailingDereferences ? ZERO : minusFour)) { BreakTag tyargTag = genSym(); dotExpressionUpToArgs(e, Optional.of(tyargTag)); - Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO); // Calls that stay on the first line of the chain indent hugged arguments by an extra +4, // to distinguish them from the trailing dereferences. dotExpressionArgsAndParen( e, - tyargIndent, + tyargTag, (trailingDereferences || needDot) ? plusFour : ZERO, (!hasBroken && i < items.size() - 1) ? plusFour : ZERO); } @@ -3232,8 +3240,8 @@ private boolean fillFirstArgument(ExpressionTree e, List items, || name.length() > 4 || !methodInvocation.getTypeArguments().isEmpty() || methodInvocation.getArguments().size() != 1 - // Huggable arguments are handled by addArguments, see canHugOnlyArgument. - || isHuggable(getOnlyElement(methodInvocation.getArguments()))) { + // Huggable arguments are handled by addArguments. + || canHugOnlyArgument(methodInvocation.getArguments(), /* allowBlockLambdaHug= */ true)) { return false; } builder.open(ZERO); @@ -3270,15 +3278,10 @@ private void visitDotWithPrefix( } Deque unconsumedPrefixes = new ArrayDeque<>(ImmutableSortedSet.copyOf(prefixes)); - boolean needDot0 = needDot; - BreakTag nameTag = genSym(); + Indent beforeFirstBreak = needDot ? ZERO : plusFour; for (int i = 0; i < items.size(); i++) { ExpressionTree e = items.get(i); - // Don't hug a block lambda if its call stays on the first line of the chain and has trailing - // dereferences. - if (!needDot0 && (i == 0 || prefixes.contains(i)) && i < items.size() - 1) { - doNotHug(e); - } + Indent argsIndent = trailingDereferences ? plusFour : ZERO; if (needDot) { FillMode fillMode; if (!unconsumedPrefixes.isEmpty() && i <= unconsumedPrefixes.peekFirst()) { @@ -3287,8 +3290,16 @@ private void visitDotWithPrefix( fillMode = FillMode.UNIFIED; } + BreakTag nameTag = genSym(); builder.breakOp(fillMode, "", ZERO, Optional.of(nameTag)); token("."); + if (!trailingDereferences) { + argsIndent = Indent.If.make(nameTag, plusFour, ZERO); + } + if (beforeFirstBreak != ZERO) { + beforeFirstBreak = + unconsumedPrefixes.isEmpty() ? ZERO : Indent.If.make(nameTag, ZERO, beforeFirstBreak); + } } BreakTag tyargTag = genSym(); dotExpressionUpToArgs(e, Optional.of(tyargTag)); @@ -3297,11 +3308,8 @@ private void visitDotWithPrefix( unconsumedPrefixes.removeFirst(); } - Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO); - Indent argsIndent = Indent.If.make(nameTag, plusFour, trailingDereferences ? plusFour : ZERO); - Indent huggedArgsIndent = - Indent.If.make(nameTag, ZERO, trailingDereferences ? plusFour : ZERO); - dotExpressionArgsAndParen(e, tyargIndent, argsIndent, huggedArgsIndent); + dotExpressionArgsAndParen( + e, tyargTag, argsIndent, i < items.size() - 1 ? beforeFirstBreak : ZERO); needDot = true; } @@ -3374,14 +3382,21 @@ private static ExpressionTree getArrayBase(ExpressionTree node) { } private void dotExpressionArgsAndParen( - ExpressionTree expression, Indent tyargIndent, Indent indent, Indent huggedIndent) { + ExpressionTree expression, BreakTag tyargTag, Indent indent, Indent huggedIndent) { Deque indices = getArrayIndices(expression); expression = getArrayBase(expression); switch (expression.getKind()) { case METHOD_INVOCATION -> { + Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO); + Indent huggedArgsIndent = + huggedIndent == ZERO ? ZERO : Indent.If.make(tyargTag, ZERO, huggedIndent); builder.open(tyargIndent); MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; - addArguments(methodInvocation.getArguments(), indent, huggedIndent); + addArguments( + methodInvocation.getArguments(), + indent, + huggedArgsIndent, + /* allowBlockLambdaHug= */ true); builder.close(); } default -> {} @@ -3436,28 +3451,26 @@ private void addTypeArguments(List typeArguments, Indent plusInd token(">"); } - private void addArguments(List arguments, Indent plusIndent) { - addArguments(arguments, plusIndent, ZERO); - } - /// Add arguments to a method invocation, etc. The arguments indented `plusFour`, filled, from the /// current indent. The arguments may be output two at a time if they seem to be arguments to a /// map constructor, etc. /// /// @param arguments the arguments /// @param plusIndent the extra indent for the arguments - /// @param huggedPlusIndent the extra indent when a single expression lambda argument is hugged + /// @param huggedPlusIndent the extra indent when a single lambda argument is hugged + /// @param allowBlockLambdaHug whether a single block lambda argument may be hugged (false when a + /// class body immediately follows the argument list) private void addArguments( - List arguments, Indent plusIndent, Indent huggedPlusIndent) { + List arguments, + Indent plusIndent, + Indent huggedPlusIndent, + boolean allowBlockLambdaHug) { boolean tabular = arguments.size() % 2 == 0 && argumentsAreTabular(arguments) == 2; - boolean hug = canHugOnlyArgument(arguments); + boolean hug = canHugOnlyArgument(arguments, allowBlockLambdaHug); if (hug) { ExpressionTree argument = getOnlyElement(arguments); builder.openHuggable( - plusIndent, - hasHuggedBlockLambda(arguments) ? ZERO : huggedPlusIndent, - hugPoint(argument), - /* fallbackIfFlatOnNextLine= */ true); + plusIndent, huggedPlusIndent, hugPoint(argument), /* fallbackIfFlatOnNextLine= */ true); } else { builder.open(plusIndent); } @@ -3521,57 +3534,17 @@ private void markHugPoint(Tree tree) { } } - /** - * Returns true for constructs that may be hugged, i.e. laid out starting on the line of the - * preceding content: lambdas. - */ - private static boolean isHuggable(ExpressionTree tree) { - return tree instanceof LambdaExpressionTree; - } - - /** - * Returns true if the argument list is a single argument that may be hugged, e.g. {@code f(x -> { - * ... })}. Lambdas preceded by other arguments aren't hugged: the preceding arguments would share - * a line with the lambda's head, and wouldn't line up with the lambda's body. - */ - private boolean canHugOnlyArgument(List arguments) { - return arguments.size() == 1 - && isHuggable(getOnlyElement(arguments)) - && !notHuggable.contains(getOnlyElement(arguments)); - } - - /** - * Constructs that may not be hugged even though {@link #isHuggable} is true for them; see {@link - * #doNotHug}. - */ - private final Set notHuggable = Sets.newIdentityHashSet(); - - /** - * Prevents hugging a block lambda argument of {@code call}. Used in two cases: - * - *
    - *
  • a call on the first line of a dereference chain with more dereferences after it (e.g. - * {@code new Thread(() -> { ... }).start()}) - *
  • a constructor or enum constant call with a class body (e.g. {@code new Thread(() -> { ... - * }) { ... }}) - *
- */ - private void doNotHug(ExpressionTree call) { - List arguments = - switch (getArrayBase(call)) { - case MethodInvocationTree invocation -> invocation.getArguments(); - case NewClassTree newClass -> newClass.getArguments(); - default -> ImmutableList.of(); - }; - if (hasHuggedBlockLambda(arguments)) { - notHuggable.add(getOnlyElement(arguments)); - } - } - - private static boolean hasHuggedBlockLambda(List arguments) { - return arguments.size() == 1 - && getOnlyElement(arguments) instanceof LambdaExpressionTree lambda - && lambda.getBodyKind() == LambdaExpressionTree.BodyKind.STATEMENT; + /// Returns true if the argument list is a single argument that may be hugged, e.g. `f(x -> { ... + /// })`. Lambdas preceded by other arguments aren't hugged: the preceding arguments would share a + /// line with the lambda's head, and wouldn't line up with the lambda's body. + private static boolean canHugOnlyArgument( + List arguments, boolean allowBlockLambdaHug) { + if (arguments.size() != 1) { + return false; + } + ExpressionTree argument = getOnlyElement(arguments); + return argument instanceof LambdaExpressionTree lambda + && (allowBlockLambdaHug || lambda.getBodyKind() != LambdaExpressionTree.BodyKind.STATEMENT); } private void argList(List arguments) { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.input index d24a90ea8..db3834ccb 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.input @@ -52,6 +52,15 @@ class LambdaHug { item.of(() -> Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")).spliterator()).expect("a", "b", "c", "d"); task(event -> { handle(event); handleAgain(event); handleOnceMore(event); }).handleFailure(failure); task(() -> Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")).spliterator()).expect("a"); + SomeVeryLongClassNameThatIsVeryLongAndForcesABreakBeforeMethod.someVeryLongStaticMethodNameThatWraps(x -> { handle(x); handleAgain(x); }).thenAccept(y -> { handle(y); handleAgain(y); }); + com.google.very.lengthy.pkg.name.that.is.extremely.wide.and.forces.a.wrap.somewhere.before.MyClass.computeItems(x -> { handle(x); handleAgain(x); }).thenAccept(y -> { handle(y); handleAgain(y); }); + new Receiver() { void f() {} }.computeItems(x -> { handle(x); handleAgain(x); }).stream().toList(); + new Foo(() -> Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")).spliterator()).expect("a"); + MyClass.computeItems(x -> { handle(x); handleAgain(x); }).stream(); + MyClass.computeItems(x -> Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")).spliterator()).stream(); + item.of(x -> { handle(x); handleAgain(x); }).register(); + doAnswer(invocation -> { handle(invocation); return null; }).when(mock).run(); + return trapExceptions(() -> { compute(); computeAgain(); }).then(x -> { handle(x); handleAgain(x); }).peek(cleanup); } void conditions() { @@ -69,6 +78,8 @@ class LambdaHug { do { process(); } while (anyMatch(c -> { return true; })); if (anyMatch(c -> check(x -> { handle(x); handleAgain(x); }))) { return; } if (anyMatch(param -> param.someLongMethodName(argumentNumberOne, argumentNumberTwo, argumentNumberThree))) { return; } + if (trapExceptions(() -> { compute(); return true; }).isOk()) { process(); } + if (other && trapExceptions(() -> { compute(); return true; }).isOk()) { process(); } } void nested() { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.output index b242f83f7..c88ce6ebd 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LambdaHug.output @@ -130,37 +130,32 @@ class LambdaHug { Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")) .spliterator()) .expect("a", "b", "c", "d"); - new Thread( - () -> { - assertThrows(CancellationException.class, future::get); - successLatch.countDown(); - }) + new Thread(() -> { + assertThrows(CancellationException.class, future::get); + successLatch.countDown(); + }) .start(); - return new Promise( - (resolve, reject) -> { - Futures.addCallback(this, callback, MoreExecutors.directExecutor()); - }) + return new Promise((resolve, reject) -> { + Futures.addCallback(this, callback, MoreExecutors.directExecutor()); + }) .then(onFulfilled, onRejected); - CompletableFuture.runAsync( - () -> { - doSomethingExpensive(); - doSomethingElseExpensive(); - }) + CompletableFuture.runAsync(() -> { + doSomethingExpensive(); + doSomethingElseExpensive(); + }) .join(); - CompletableFuture.supplyAsync( - () -> { - return computeSomethingExpensive(input, parameters); - }) + CompletableFuture.supplyAsync(() -> { + return computeSomethingExpensive(input, parameters); + }) .thenAccept(result -> { consume(result); consumeAgain(result); }); - this.process( - item -> { - handle(item); - handleAgain(item); - handleOnceMore(item); - }) + this.process(item -> { + handle(item); + handleAgain(item); + handleOnceMore(item); + }) .andThen(cleanup); someLongReceiverName .withCallback(event -> { @@ -168,17 +163,15 @@ class LambdaHug { handleAgain(event); }) .register(); - item.withCallback( - event -> { - handle(event); - handleAgain(event); - }) + item.withCallback(event -> { + handle(event); + handleAgain(event); + }) .register(); - withCallback( - event -> { - handle(event); - handleAgain(event); - }) + withCallback(event -> { + handle(event); + handleAgain(event); + }) .register(); someLongReceiverName .computeItems(x -> { @@ -187,18 +180,16 @@ class LambdaHug { }) .stream() .toList(); - MyClass.computeItems( - x -> { - handle(x); - handleAgain(x); - }) + MyClass.computeItems(x -> { + handle(x); + handleAgain(x); + }) .stream() .toList(); - computeItems( - x -> { - handle(x); - handleAgain(x); - }) + computeItems(x -> { + handle(x); + handleAgain(x); + }) .stream() .toList(); new Receiver() @@ -212,17 +203,77 @@ class LambdaHug { Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")) .spliterator()) .expect("a", "b", "c", "d"); - task( - event -> { - handle(event); - handleAgain(event); - handleOnceMore(event); - }) + task(event -> { + handle(event); + handleAgain(event); + handleOnceMore(event); + }) .handleFailure(failure); task(() -> Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")) .spliterator()) .expect("a"); + SomeVeryLongClassNameThatIsVeryLongAndForcesABreakBeforeMethod + .someVeryLongStaticMethodNameThatWraps(x -> { + handle(x); + handleAgain(x); + }) + .thenAccept(y -> { + handle(y); + handleAgain(y); + }); + com.google.very.lengthy.pkg.name.that.is.extremely.wide.and.forces.a.wrap.somewhere.before + .MyClass.computeItems(x -> { + handle(x); + handleAgain(x); + }) + .thenAccept(y -> { + handle(y); + handleAgain(y); + }); + new Receiver() { + void f() {} + }.computeItems(x -> { + handle(x); + handleAgain(x); + }) + .stream() + .toList(); + new Foo(() -> + Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")) + .spliterator()) + .expect("a"); + MyClass.computeItems(x -> { + handle(x); + handleAgain(x); + }) + .stream(); + MyClass.computeItems(x -> + Streams.concat(Stream.of("a"), Stream.of("b"), Stream.empty(), Stream.of("c", "d")) + .spliterator()) + .stream(); + item. + of(x -> { + handle(x); + handleAgain(x); + }) + .register(); + doAnswer(invocation -> { + handle(invocation); + return null; + }) + .when(mock) + .run(); + return trapExceptions(() -> { + compute(); + computeAgain(); + }) + .then(x -> { + handle(x); + handleAgain(x); + }) + .peek(cleanup); } void conditions() { @@ -322,6 +373,22 @@ class LambdaHug { param.someLongMethodName(argumentNumberOne, argumentNumberTwo, argumentNumberThree))) { return; } + if (trapExceptions( + () -> { + compute(); + return true; + }) + .isOk()) { + process(); + } + if (other + && trapExceptions(() -> { + compute(); + return true; + }) + .isOk()) { + process(); + } } void nested() {