From b6f6bae31aa95088ff015e97f223e0cdce3d7d32 Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Thu, 7 Feb 2019 16:46:55 +0100 Subject: [PATCH] invert if: ensure outer if becomes braces when nested if has no else brunch (IDEA-206882) --- .../intention/impl/InvertIfConditionAction.java | 6 +++++- .../invertIfCondition/afterNestedIf6.java | 13 +++++++++++++ .../invertIfCondition/beforeNestedIf6.java | 13 +++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 java/java-tests/testData/codeInsight/invertIfCondition/afterNestedIf6.java create mode 100644 java/java-tests/testData/codeInsight/invertIfCondition/beforeNestedIf6.java diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/InvertIfConditionAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/InvertIfConditionAction.java index 3e8841087d02..84cebb8c278a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/InvertIfConditionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/InvertIfConditionAction.java @@ -142,7 +142,11 @@ public class InvertIfConditionAction extends PsiElementBaseIntentionAction { elseBranch = Objects.requireNonNull(ifStatement.getElseBranch()).replace(elseBranch); if (emptyBlock(((PsiBlockStatement)elseBranch).getCodeBlock())) { - new CommentTracker().deleteAndRestoreComments(ifStatement.getElseBranch()); + PsiElement parent = ifStatement.getParent(); + if (parent instanceof PsiIfStatement && ((PsiIfStatement)parent).getElseBranch() != null) { + ifStatement = (PsiIfStatement)wrapWithCodeBlock(ifStatement); + } + new CommentTracker().deleteAndRestoreComments(Objects.requireNonNull(ifStatement.getElseBranch())); } } } diff --git a/java/java-tests/testData/codeInsight/invertIfCondition/afterNestedIf6.java b/java/java-tests/testData/codeInsight/invertIfCondition/afterNestedIf6.java new file mode 100644 index 000000000000..4d9ba4dd3551 --- /dev/null +++ b/java/java-tests/testData/codeInsight/invertIfCondition/afterNestedIf6.java @@ -0,0 +1,13 @@ +// "Invert 'if' condition" "true" +class Main { + void foo(boolean a1, boolean b1){ + if (a1) { + if (!b1) { + System.out.println("1"); + } + } + else { + System.out.println("2"); + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/invertIfCondition/beforeNestedIf6.java b/java/java-tests/testData/codeInsight/invertIfCondition/beforeNestedIf6.java new file mode 100644 index 000000000000..318313328f10 --- /dev/null +++ b/java/java-tests/testData/codeInsight/invertIfCondition/beforeNestedIf6.java @@ -0,0 +1,13 @@ +// "Invert 'if' condition" "true" +class Main { + void foo(boolean a1, boolean b1){ + if (a1) + if (b1) { + } else { + System.out.println("1"); + } + else { + System.out.println("2"); + } + } +} \ No newline at end of file