surround with if: fix for expression lambda (IDEA-160218)

This commit is contained in:
Anna Kozlova
2016-08-24 15:14:38 +03:00
parent 7fee43ed06
commit 08a18bc8bd
3 changed files with 29 additions and 3 deletions
@@ -26,6 +26,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ipp.trivialif.MergeIfAndIntention;
import org.jetbrains.annotations.NonNls;
@@ -51,11 +52,16 @@ public class SurroundWithIfFix implements LocalQuickFix {
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
PsiStatement anchorStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class);
PsiElement anchorStatement = RefactoringUtil.getParentStatement(element, false);
LOG.assertTrue(anchorStatement != null);
Editor editor = PsiUtilBase.findEditor(element);
if (anchorStatement.getParent() instanceof PsiLambdaExpression) {
final PsiElement body = ((PsiLambdaExpression)RefactoringUtil.expandExpressionLambdaToCodeBlock(anchorStatement)).getBody();
LOG.assertTrue(body instanceof PsiCodeBlock);
anchorStatement = ((PsiCodeBlock)body).getStatements()[0];
}
Editor editor = PsiUtilBase.findEditor(anchorStatement);
if (editor == null) return;
PsiFile file = element.getContainingFile();
PsiFile file = anchorStatement.getContainingFile();
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
Document document = documentManager.getDocument(file);
if (document == null || !FileModificationService.getInstance().prepareFileForWrite(file)) return;
@@ -0,0 +1,12 @@
// "Surround with 'if (i != null)'" "true"
import org.jetbrains.annotations.Nullable;
class A {
void foo(@Nullable String i) {
Runnable r = () -> {
if (i != null) {
i.length();
}
};
}
}
@@ -0,0 +1,8 @@
// "Surround with 'if (i != null)'" "true"
import org.jetbrains.annotations.Nullable;
class A {
void foo(@Nullable String i) {
Runnable r = () -> i.<caret>length();
}
}