Java: fix one more case where "invert if" loses comment (IDEA-252033)

GitOrigin-RevId: 8bba0c15ca98a31a29ffc8a0d46effca9d96d27f
This commit is contained in:
Bas Leijdekkers
2024-08-06 10:48:28 +00:00
committed by intellij-monorepo-bot
parent e39764dd13
commit 5c96c794ed
3 changed files with 35 additions and 2 deletions
@@ -237,8 +237,8 @@ public final class InvertIfConditionAction extends PsiUpdateModCommandAction<Psi
element instanceof PsiForeachStatement && flow.getStartOffset(element) + 1 == endOffset) {
PsiStatement statement = factory.createStatementFromText("continue;", ifStatement);
statement = (PsiStatement)codeStyle.reformat(statement);
ifStatement = addAfterWithinCodeBlock(ifStatement, ct.markUnchanged(thenBranch), ct);
Objects.requireNonNull(ifStatement.getThenBranch()).replace(statement);
ifStatement = addAfterWithinCodeBlock(ifStatement, thenBranch, ct);
ct.replaceAndRestoreComments(Objects.requireNonNull(ifStatement.getThenBranch()), statement);
return ifStatement;
}
@@ -372,6 +372,18 @@ public final class InvertIfConditionAction extends PsiUpdateModCommandAction<Psi
ifStatement = (PsiIfStatement)wrapWithCodeBlock(ifStatement);
}
addAfter(ifStatement, branch, ct);
branch = ifStatement.getThenBranch();
if (branch instanceof PsiBlockStatement blockStatement) {
PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
PsiElement start = codeBlock.getFirstBodyElement();
PsiElement end = codeBlock.getLastBodyElement();
if (start != null && end != null) {
ct.markRangeUnchanged(start, end);
}
}
else {
ct.markUnchanged(branch);
}
return ifStatement;
}
@@ -0,0 +1,11 @@
// "Invert 'if' condition" "true"
class D {
private void f(char[] buffer) {
for (char c : buffer) {
if (false) {
continue; // THIS COMMENT DISAPPEARS
}
break;
}
}
}
@@ -0,0 +1,10 @@
// "Invert 'if' condition" "true"
class D {
private void f(char[] buffer) {
for (char c : buffer) {
if (true)<caret> {
break;
} // THIS COMMENT DISAPPEARS
}
}
}