Java: keep final if possible when reusing previous variable (IDEA-312181)

GitOrigin-RevId: 73e54a9e8850f2fa04ac2b642e712c285f5b24f6
This commit is contained in:
Bas Leijdekkers
2023-02-23 18:39:57 +00:00
committed by intellij-monorepo-bot
parent 8b8490c8cd
commit bf8816a076
3 changed files with 36 additions and 15 deletions
@@ -1,21 +1,8 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.intention.FileModifier;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
@@ -79,12 +66,18 @@ public class ReuseVariableDeclarationFix implements IntentionAction {
return;
}
boolean wasFinal = refVariable.hasModifierProperty(PsiModifier.FINAL);
PsiUtil.setModifierProperty(refVariable, PsiModifier.FINAL, false);
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(myVariable.getProject());
final PsiElement statement = factory.createStatementFromText(
myVariable.getName() + " = " +
ExpressionUtils.convertInitializerToExpression(initializer, factory, myVariable.getType()).getText() + ";", null);
myVariable.getParent().replace(statement);
if (wasFinal &&
refVariable instanceof PsiLocalVariable &&
HighlightControlFlowUtil.isEffectivelyFinal(refVariable, initializer, null)) {
PsiUtil.setModifierProperty(refVariable, PsiModifier.FINAL, true);
}
}
@Nullable
@@ -0,0 +1,14 @@
// "Reuse previous variable 'x' declaration" "true-preview"
import java.io.*;
class X {
public void demo() {
final boolean x;
if (true) {
x = false;
} else {
x = true;
}
}
}
@@ -0,0 +1,14 @@
// "Reuse previous variable 'x' declaration" "true-preview"
import java.io.*;
class X {
public void demo() {
final boolean x;
if (true) {
x = false;
} else {
boolean <caret>x = true;
}
}
}