When detecting field dependencies, check method calls used in initializer whether they have references on class fields (IDEA-135442)

This commit is contained in:
Yaroslav Lepenkin
2015-01-26 19:47:21 +03:00
parent 237e80615c
commit f761339f62
2 changed files with 48 additions and 0 deletions
@@ -274,12 +274,21 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor {
final Set<PsiField> containingClassFields = classFields;
fieldInitializer.accept(new JavaRecursiveElementVisitor() {
public int myCurrentMethodLookupDepth;
private static final int MAX_METHOD_LOOKUP_DEPTH = 3;
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
PsiElement ref = expression.resolve();
if (ref instanceof PsiField && containingClassFields.contains(ref)) {
referencedElements.add((PsiField)ref);
}
else if (ref instanceof PsiMethod && myCurrentMethodLookupDepth < MAX_METHOD_LOOKUP_DEPTH) {
myCurrentMethodLookupDepth++;
visitMethod((PsiMethod)ref);
myCurrentMethodLookupDepth--;
}
super.visitReferenceExpression(expression);
}
});
@@ -409,4 +409,43 @@ public class FormatTest {
]
)
}
void "test field dependency through method call"() {
doTest(
initial: '''
public class TmpTest {
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
static final String SUB_MESSAGE_REQUEST_SNAPSHOT = create(1);
private static String create(int i) {
return Integer.toString(i + EMPTY_OBJECT_ARRAY.length);
}
public static void main(String[] args) {
System.out.println(SUB_MESSAGE_REQUEST_SNAPSHOT);
}
}
''',
expected: '''
public class TmpTest {
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
static final String SUB_MESSAGE_REQUEST_SNAPSHOT = create(1);
public static void main(String[] args) {
System.out.println(SUB_MESSAGE_REQUEST_SNAPSHOT);
}
private static String create(int i) {
return Integer.toString(i + EMPTY_OBJECT_ARRAY.length);
}
}
''',
rules: [
rule(FIELD),
rule(PRIVATE, FIELD),
rule(PUBLIC, METHOD),
rule(PRIVATE, METHOD)
]
);
}
}