Skip to content

Commit

Permalink
Fix a crash in UnnecessaryBoxedVariable
Browse files Browse the repository at this point in the history
Don't assume that return statements are enclosed by a method with a return
type, to handle statement lambdas inside constructors.

Fixes #3115

PiperOrigin-RevId: 442056569
  • Loading branch information
cushon authored and Error Prone Team committed Apr 15, 2022
1 parent 460d6c2 commit ed35fda
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
Expand Up @@ -21,6 +21,7 @@
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.findEnclosingMethod;
import static com.google.errorprone.util.ASTHelpers.getSymbol;

import com.google.common.collect.ArrayListMultimap;
Expand Down Expand Up @@ -429,11 +430,12 @@ public Void visitReturn(ReturnTree node, Void unused) {
// Don't count a return value as a boxed usage, except if we are returning a parameter, and
// the method's return type is boxed.
if (nodeSymbol.getKind() == ElementKind.PARAMETER) {
MethodTree enclosingMethod =
ASTHelpers.findEnclosingNode(getCurrentPath(), MethodTree.class);
Type returnType = ASTHelpers.getType(enclosingMethod.getReturnType());
if (!returnType.isPrimitive()) {
boxedUsageFound.add((VarSymbol) nodeSymbol);
MethodTree enclosingMethod = findEnclosingMethod(state.withPath(getCurrentPath()));
if (enclosingMethod != null) {
Type returnType = ASTHelpers.getType(enclosingMethod.getReturnType());
if (!returnType.isPrimitive()) {
boxedUsageFound.add((VarSymbol) nodeSymbol);
}
}
}
return null;
Expand Down
Expand Up @@ -69,4 +69,22 @@ public void lambdas() {
"}")
.doTest();
}

@Test
public void lambdaReturn() {
compilationTestHelper
.addSourceLines(
"Test.java",
"class Test {",
" interface F {",
" int f(Integer i);",
" }",
" Test() {",
" F f = (Integer i) -> {",
" return i;",
" };",
" }",
"}")
.doTest();
}
}

0 comments on commit ed35fda

Please sign in to comment.