Skip to content

Commit

Permalink
exclude anonymous classes/lambdas
Browse files Browse the repository at this point in the history
  • Loading branch information
carterkozak committed Nov 7, 2019
1 parent 2136499 commit dec2f11
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import java.lang.reflect.InvocationHandler;
Expand Down Expand Up @@ -77,10 +79,15 @@ public final class InvocationHandlerDelegation extends BugChecker implements Bug
ExpressionTree.class, UNWRAP_ITE);

private static final Matcher<MethodTree> HANDLES_ITE =
Matchers.contains(TryTree.class, (Matcher<TryTree>) (tree, state) ->
Matchers.anyOf(
Matchers.contains(TryTree.class, (Matcher<TryTree>) (tree, state) ->
CONTAINS_METHOD_INVOKE.matches(tree.getBlock(), state)
&& tree.getCatches().stream()
.anyMatch(catchTree -> CONTAINS_UNWRAP_ITE.matches(catchTree.getBlock(), state)));
.anyMatch(catchTree -> CONTAINS_UNWRAP_ITE.matches(catchTree.getBlock(), state))),
// If Method.invoke occurs in a lambda or anonymous class, we don't have enough
// conviction that it's a bug.
Matchers.contains(LambdaExpressionTree.class, CONTAINS_METHOD_INVOKE::matches),
Matchers.contains(NewClassTree.class, CONTAINS_METHOD_INVOKE::matches));

private static final Matcher<MethodInvocationTree> MATCHER = Matchers.allOf(
METHOD_INVOKE_ENCLOSED_BY_INVOCATION_HANDLER,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,26 @@ void testCorrectInvocationHandler_doesntRethrow() {
"}")
.doTest();
}

@Test
void testCorrectInvocationHandler_lambda() {
helper().addSourceLines(
"Test.java",
"import java.lang.reflect.*;",
"import com.google.common.util.concurrent.*;",
"abstract class Test implements InvocationHandler {",
" @Override",
" public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {",
// Avoid flagging invocations nested in anonymous classes or lambdas
" return FluentFuture.from(executor().submit(() -> method.invoke(this, args)))",
" .catching(InvocationTargetException.class, ignored -> null, MoreExecutors.directExecutor())",
" .get();",
" }",
" abstract ListeningExecutorService executor();",
"}")
.doTest();
}

private CompilationTestHelper helper() {
return CompilationTestHelper.newInstance(InvocationHandlerDelegation.class, getClass());
}
Expand Down

0 comments on commit dec2f11

Please sign in to comment.