diff --git a/java/java-impl/src/com/intellij/codeInspection/enhancedSwitch/RedundantLabeledSwitchRuleCodeBlockInspection.java b/java/java-impl/src/com/intellij/codeInspection/enhancedSwitch/RedundantLabeledSwitchRuleCodeBlockInspection.java index 2b9147529322..e25b99ee9ba2 100644 --- a/java/java-impl/src/com/intellij/codeInspection/enhancedSwitch/RedundantLabeledSwitchRuleCodeBlockInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/enhancedSwitch/RedundantLabeledSwitchRuleCodeBlockInspection.java @@ -93,8 +93,14 @@ public class RedundantLabeledSwitchRuleCodeBlockInspection extends LocalInspecti private static void unwrapBreakValue(PsiStatement body, PsiBreakStatement breakStatement) { PsiExpression valueExpression = breakStatement.getValueExpression(); if (valueExpression != null) { + PsiElementFactory factory = JavaPsiFacade.getElementFactory(body.getProject()); + PsiExpressionStatement statement = (PsiExpressionStatement)factory.createStatementFromText("x=1;", body); + statement.getExpression().replace(valueExpression); + CommentTracker tracker = new CommentTracker(); - tracker.replaceAndRestoreComments(body, tracker.text(valueExpression) + ';'); + // replaceAndRestoreComments() will work with a copy of the expression so it won't see the original comments + tracker.markUnchanged(valueExpression); + tracker.replaceAndRestoreComments(body, statement); } } diff --git a/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/afterSwitchExpressionInExpression.java b/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/afterSwitchExpressionInExpression.java new file mode 100644 index 000000000000..7033e8b1ae63 --- /dev/null +++ b/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/afterSwitchExpressionInExpression.java @@ -0,0 +1,13 @@ +// "Unwrap code block of labeled rule" "LIKE_UNUSED_SYMBOL" +class C { + int foo(final int x, int n) { + return switch (x) { + case 0 -> /*1*/ /*3*/ //4 + switch (n) { // 2 + case 0 -> 0; + default -> 1; + }; + default -> 2; + }; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/beforeSwitchExpressionInExpression.java b/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/beforeSwitchExpressionInExpression.java new file mode 100644 index 000000000000..e5a8c4f4d917 --- /dev/null +++ b/java/java-tests/testData/inspection/redundantLabeledSwitchRuleCodeBlockFix/beforeSwitchExpressionInExpression.java @@ -0,0 +1,14 @@ +// "Unwrap code block of labeled rule" "LIKE_UNUSED_SYMBOL" +class C { + int foo(final int x, int n) { + return switch (x) { + case 0 -> { + break /*1*/ switch (n) { // 2 + case 0 -> 0; + default -> 1; + }/*3*/; //4 + } + default -> 2; + }; + } +} \ No newline at end of file