[java-refactoring] Inline variable: improve behavior in the presence of compilation errors

1. Properly forward the AnalysisCancelledException
2. Allow inlining of never overwritten variable in the presence of syntax errors

Fixes IDEA-336815 "Inline variable" misleading error message when compile-errors are present

GitOrigin-RevId: 7510d497fce2dcd4bef38482cfadf162d47cc2c0
This commit is contained in:
Tagir Valeev
2023-11-02 20:34:04 +00:00
committed by intellij-monorepo-bot
parent cb548d0991
commit c6fbff80c0
5 changed files with 59 additions and 4 deletions
@@ -199,14 +199,26 @@ public class InlineLocalHandler extends JavaInlineActionHandler {
}
List<PsiElement> refsToInlineList = new ArrayList<>();
boolean simpleInlining = false;
if (mode == InlineMode.INLINE_ONE) {
refsToInlineList.add(refExpr);
} else {
try {
Collections.addAll(refsToInlineList, DefUseUtil.getRefs(containerBlock, local, defToInline));
if (defToInline == local.getInitializer()) {
// Do not rely on ref-def analysis in a simple case when we inline an initializer and there are no subsequent writes.
// This allows inlining in the presense of syntax errors.
List<PsiReferenceExpression> refs = VariableAccessUtils.getVariableReferences(local, containerBlock);
if (!ContainerUtil.exists(refs, ref -> PsiUtil.isAccessedForWriting(ref))) {
simpleInlining = true;
refsToInlineList.addAll(refs);
}
}
catch (RuntimeException e) {
return processWrappedAnalysisCanceledException(e);
if (!simpleInlining) {
try {
Collections.addAll(refsToInlineList, DefUseUtil.getRefs(containerBlock, local, defToInline, true));
}
catch (RuntimeException e) {
return processWrappedAnalysisCanceledException(e);
}
}
for (PsiElement innerClassUsage : innerClassUses.innerClassUsages()) {
if (!refsToInlineList.contains(innerClassUsage)) {
@@ -0,0 +1,11 @@
public class CompilationError {
public void test() {
public static void main(String[] args) {
int <caret>inlineMe = 3; // inline
int dd = 4 + inlineMe;
"Error".
}
}
}
@@ -0,0 +1,11 @@
public class CompilationError {
public void test() {
public static void main(String[] args) {
// inline
int dd = 4 + 3;
"Error".
}
}
}
@@ -0,0 +1,12 @@
public class CompilationError {
public void test() {
public static void main(String[] args) {
int inlineMe = 2;
<caret>inlineMe = 3; // inline
int dd = 4 + inlineMe;
"Error".
}
}
}
@@ -342,6 +342,15 @@ public class InlineLocalTest extends LightJavaCodeInsightTestCase {
public void testUnusedReassignmentInLoop() {
doTest();
}
public void testCompilationError() {
doTest();
}
public void testCompilationErrorAssignment() {
doTest("Cannot perform refactoring.\n" +
"Code contains syntax errors. Cannot perform necessary analysis.");
}
public void testEolComment() {
doTest();