Skip to content

Commit

Permalink
Skip UnnecessaryLambda findings for usages in enhanced for loops
Browse files Browse the repository at this point in the history
google#2518

PiperOrigin-RevId: 565804153
  • Loading branch information
cushon authored and Error Prone Team committed Sep 15, 2023
1 parent b8c865c commit 93ca62e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Expand Up @@ -43,6 +43,7 @@
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
Expand Down Expand Up @@ -101,15 +102,26 @@ public Description matchMethod(MethodTree tree, VisitorState state) {
if (state.isAndroidCompatible()) {
return NO_MATCH;
}
boolean[] usedInEnhancedForLoop = {false};
new TreePathScanner<Void, Void>() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {

if (Objects.equals(getSymbol(node), sym)) {
replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath()));
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof EnhancedForLoopTree
&& ((EnhancedForLoopTree) parent).getExpression().equals(node)) {
usedInEnhancedForLoop[0] = true;
} else {
replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath()));
}
}
return super.visitMethodInvocation(node, null);
}
}.scan(state.getPath().getCompilationUnit(), null);
if (usedInEnhancedForLoop[0]) {
return NO_MATCH;
}
lambdaToMethod(state, lambda, fix, name, type);
return describeMatch(tree, fix.build());
}
Expand Down
Expand Up @@ -388,4 +388,26 @@ public void e() {
"}")
.doTest();
}

@Test
public void iterable() {
testHelper
.addInputLines(
"Test.java",
"import java.util.stream.IntStream;",
"import java.util.ArrayList;",
"import java.util.stream.IntStream;",
"class Example {",
" void someLoopyCode() {",
" for (int i : someIterable()) {",
" // Do something.",
" }",
" }",
" private Iterable<Integer> someIterable() {",
" return () -> IntStream.range(0, 42).boxed().iterator();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}

0 comments on commit 93ca62e

Please sign in to comment.