From 64e2d1b3bbe472f2e361fcd99d2e59e0f584224f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Apr 2015 17:56:53 +0200 Subject: [PATCH] IDEA-138521 Infer contracts for anonymous class methods resolved to from outside --- .../dataFlow/InferenceFromSourceUtil.java | 14 ++++++++++++-- .../ContractInferenceFromSourceTest.groovy | 12 ++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InferenceFromSourceUtil.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InferenceFromSourceUtil.java index fd03efe01839..ced253163b4a 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InferenceFromSourceUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InferenceFromSourceUtil.java @@ -44,8 +44,18 @@ public class InferenceFromSourceUtil { private static boolean isUnusedInAnonymousClass(@NotNull PsiMethod method) { PsiClass containingClass = method.getContainingClass(); - return containingClass instanceof PsiAnonymousClass && - MethodReferencesSearch.search(method, new LocalSearchScope(containingClass), false).findFirst() == null; + if (!(containingClass instanceof PsiAnonymousClass)) { + return false; + } + + if (containingClass.getParent() instanceof PsiNewExpression && + containingClass.getParent().getParent() instanceof PsiVariable && + !method.getHierarchicalMethodSignature().getSuperSignatures().isEmpty()) { + // references outside anonymous class can still resolve to this method, see com.intellij.psi.scope.util.PsiScopesUtil.setupAndRunProcessor() + return false; + } + + return MethodReferencesSearch.search(method, new LocalSearchScope(containingClass), false).findFirst() == null; } private static boolean isLibraryCode(@NotNull PsiMethod method) { diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/ContractInferenceFromSourceTest.groovy b/java/java-tests/testSrc/com/intellij/codeInspection/ContractInferenceFromSourceTest.groovy index 107671c0d18f..e893a2badee5 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/ContractInferenceFromSourceTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInspection/ContractInferenceFromSourceTest.groovy @@ -507,6 +507,18 @@ class Foo {{ assert ContractInference.inferContracts(method).collect { it as String } == [' -> null'] } + public void "test anonymous class methods potentially used from outside"() { + def method = PsiTreeUtil.findChildOfType(myFixture.addClass(""" +class Foo {{ + Runnable r = new Runnable() { + public void run() { + throw new RuntimeException(); + } + }; +}}"""), PsiAnonymousClass).methods[0] + assert ContractInference.inferContracts(method).collect { it as String } == [' -> fail'] + } + private String inferContract(String method) { return assertOneElement(inferContracts(method)) }