SplitDeclarationAndInitializationIntention: do not suggest when we are too deep from the field

This commit is contained in:
Tagir Valeev
2018-12-13 17:42:27 +07:00
parent 2bb71bfc15
commit 57eac872d1
5 changed files with 38 additions and 4 deletions
@@ -15,6 +15,7 @@
*/
package com.siyeh.ipp.initialization;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
@@ -41,6 +42,12 @@ public class SplitDeclarationAndInitializationIntention extends Intention {
return new SplitDeclarationAndInitializationPredicate();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
return PsiTreeUtil.getParentOfType(element, PsiField.class, false, PsiCodeBlock.class) != null &&
super.isAvailable(project, editor, element);
}
@Override
public void processIntention(@NotNull PsiElement element) {
final PsiField field = (PsiField)element.getParent();
@@ -66,9 +73,6 @@ public class SplitDeclarationAndInitializationIntention extends Intention {
if (initializerIsStatic == fieldIsStatic) {
Predicate<PsiReference> usedBeforeInitializer = ref -> {
PsiElement refElement = ref.getElement();
if (refElement == null) {
return true;
}
TextRange textRange = refElement.getTextRange();
return textRange == null || textRange.getStartOffset() < initializerOffset;
};
@@ -80,7 +84,7 @@ public class SplitDeclarationAndInitializationIntention extends Intention {
}
final PsiManager manager = field.getManager();
final Project project = manager.getProject();
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
if (classInitializer == null) {
if (PsiUtil.isJavaToken(PsiTreeUtil.skipWhitespacesForward(field), JavaTokenType.COMMA)) {
field.normalizeDeclaration();
@@ -0,0 +1,8 @@
class X {
Object obj = new Object() {
String toString() {
String message = "<caret>foo";
return message;
}
};
}
@@ -0,0 +1,8 @@
class X {
Object obj = new Object<caret>() {
String toString() {
String message = "foo";
return message;
}
};
}
@@ -0,0 +1,12 @@
class X {
Object obj<caret>;
{
obj = new Object() {
String toString() {
String message = "foo";
return message;
}
};
}
}
@@ -31,6 +31,8 @@ public class SplitDeclarationAndInitializationIntentionTest extends IPPTestCase
public void testMultipleFieldsSingleDeclaration() { doTest(); }
public void testMultipleFieldsSingleDeclaration2() { doTest(); }
public void testMultipleFieldsSingleDeclaration3() { doTest(); }
public void testNotInsideCodeBlock() { doTest(); }
public void testInsideCodeBlock() { assertIntentionNotAvailable(); }
@Override
protected String getRelativePath() {