ManualMinMaxCalculationInspection: add type when else branch is a declaration statement (IDEA-273588)

GitOrigin-RevId: a244e83d87eeccb2c5f891bf9e76d0a4b1a0a03a
This commit is contained in:
Artemiy Sartakov
2021-10-06 05:27:36 +00:00
committed by intellij-monorepo-bot
parent 2bc48a119f
commit 5ef527edfa
3 changed files with 42 additions and 9 deletions
@@ -136,17 +136,28 @@ public class ManualMinMaxCalculationInspection extends AbstractBaseJavaLocalInsp
if (model == null) return;
String replacement = createReplacement(model.getCondition());
if (replacement == null) return;
PsiExpression toReplace = model.getThenExpression();
PsiStatement elseBranch = model.getElseBranch();
final PsiElement result;
if (elseBranch instanceof PsiDeclarationStatement) {
result = replace(ifStatement, elseBranch, model.getElseExpression(), replacement);
elseBranch.delete();
}
else {
result = replace(ifStatement, model.getThenBranch(), model.getThenExpression(), replacement);
if (!PsiTreeUtil.isAncestor(ifStatement, elseBranch, true)) {
new CommentTracker().deleteAndRestoreComments(elseBranch);
}
}
SimplifiableIfStatementInspection.tryJoinDeclaration(result);
}
private static @NotNull PsiElement replace(@NotNull PsiIfStatement ifStatement,
@NotNull PsiStatement branch, @NotNull PsiExpression toReplace,
@NotNull String replacement) {
PsiReplacementUtil.replaceExpression(toReplace, replacement, new CommentTracker());
CommentTracker tracker = new CommentTracker();
PsiStatement thenBranch = model.getThenBranch();
tracker.text(thenBranch);
PsiStatement elseBranch = model.getElseBranch();
if (!PsiTreeUtil.isAncestor(ifStatement, elseBranch, true)) {
new CommentTracker().deleteAndRestoreComments(elseBranch);
}
PsiElement result = PsiReplacementUtil.replaceStatement(ifStatement, thenBranch.getText(), tracker);
SimplifiableIfStatementInspection.tryJoinDeclaration(result);
tracker.text(branch);
return PsiReplacementUtil.replaceStatement(ifStatement, branch.getText(), tracker);
}
@Nullable
@@ -0,0 +1,12 @@
// "Replace with 'Math.min'" "true"
class Test {
void test(int maxDrain) {
/*2*/
/*3*/
/*4*/
/*5*/
/*6*/
int /*0*/drained = /*1*/Math.min(10, maxDrain);
}
}
@@ -0,0 +1,10 @@
// "Replace with 'Math.min'" "true"
class Test {
void test(int maxDrain) {
int /*0*/drained = /*1*/maxDrain;
if<caret> /*2*/(10/*3*/ < maxDrain) {
drained/*4*/ = 10/*5*/;
}/*6*/
}
}