Skip to content

Commit ed35fda

Browse files
cushonError Prone Team
authored andcommitted
Fix a crash in UnnecessaryBoxedVariable
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
1 parent 460d6c2 commit ed35fda

2 files changed

Lines changed: 25 additions & 5 deletions

File tree

core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import static com.google.errorprone.matchers.Matchers.anyOf;
2222
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
2323
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
24+
import static com.google.errorprone.util.ASTHelpers.findEnclosingMethod;
2425
import static com.google.errorprone.util.ASTHelpers.getSymbol;
2526

2627
import com.google.common.collect.ArrayListMultimap;
@@ -429,11 +430,12 @@ public Void visitReturn(ReturnTree node, Void unused) {
429430
// Don't count a return value as a boxed usage, except if we are returning a parameter, and
430431
// the method's return type is boxed.
431432
if (nodeSymbol.getKind() == ElementKind.PARAMETER) {
432-
MethodTree enclosingMethod =
433-
ASTHelpers.findEnclosingNode(getCurrentPath(), MethodTree.class);
434-
Type returnType = ASTHelpers.getType(enclosingMethod.getReturnType());
435-
if (!returnType.isPrimitive()) {
436-
boxedUsageFound.add((VarSymbol) nodeSymbol);
433+
MethodTree enclosingMethod = findEnclosingMethod(state.withPath(getCurrentPath()));
434+
if (enclosingMethod != null) {
435+
Type returnType = ASTHelpers.getType(enclosingMethod.getReturnType());
436+
if (!returnType.isPrimitive()) {
437+
boxedUsageFound.add((VarSymbol) nodeSymbol);
438+
}
437439
}
438440
}
439441
return null;

core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariableTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,22 @@ public void lambdas() {
6969
"}")
7070
.doTest();
7171
}
72+
73+
@Test
74+
public void lambdaReturn() {
75+
compilationTestHelper
76+
.addSourceLines(
77+
"Test.java",
78+
"class Test {",
79+
" interface F {",
80+
" int f(Integer i);",
81+
" }",
82+
" Test() {",
83+
" F f = (Integer i) -> {",
84+
" return i;",
85+
" };",
86+
" }",
87+
"}")
88+
.doTest();
89+
}
7290
}

0 commit comments

Comments
 (0)