Do not split try when expression is in the first resource without catch/finally

It's unnecessary and otherwise try-block is automatically unwrapped
(see com.intellij.psi.impl.source.tree.java.PsiTryStatementImpl.deleteChildInternal) causing EA-235365 - PIEAE: LazyParseablePsiElement.getContainingFile

GitOrigin-RevId: 4ea3e54f8ea27854e23537a8de22f2923feaf842
This commit is contained in:
Tagir Valeev
2020-07-20 12:04:11 +07:00
committed by intellij-monorepo-bot
parent 773d84e8a3
commit f801cdb18f
3 changed files with 45 additions and 1 deletions

View File

@@ -0,0 +1,22 @@
// "Fix all 'Stream API call chain can be replaced with loop' problems in file" "true"
import java.util.*;
public class Main {
interface MyAutoCloseable {
void close();
}
void test(List<MyAutoCloseable> list) {
MyAutoCloseable found = null;
for (MyAutoCloseable myAutoCloseable : list) {
if (myAutoCloseable != null) {
found = myAutoCloseable;
break;
}
}
try(MyAutoCloseable ac = found) {
System.out.println(ac);
}
}
}

View File

@@ -0,0 +1,15 @@
// "Fix all 'Stream API call chain can be replaced with loop' problems in file" "true"
import java.util.*;
public class Main {
interface MyAutoCloseable {
void close();
}
void test(List<MyAutoCloseable> list) {
try(MyAutoCloseable ac = list<caret>.stream().filter(Objects::nonNull).findFirst().orElse(null)) {
System.out.println(ac);
}
}
}

View File

@@ -19,6 +19,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
@@ -237,7 +238,13 @@ public abstract class CodeBlockSurrounder {
if (parent instanceof PsiResourceVariable) {
PsiResourceList list = ObjectUtils.tryCast(parent.getParent(), PsiResourceList.class);
if (list != null && list.getParent() instanceof PsiTryStatement) {
return new SplitTrySurrounder(expression, (PsiResourceVariable)parent, (PsiTryStatement)list.getParent());
Iterator<PsiResourceListElement> iterator = list.iterator();
PsiTryStatement tryStatement = (PsiTryStatement)list.getParent();
if (iterator.hasNext() && iterator.next() == parent && tryStatement.getCatchBlocks().length == 0
&& tryStatement.getFinallyBlock() == null) {
return forStatement(tryStatement, expression);
}
return new SplitTrySurrounder(expression, (PsiResourceVariable)parent, tryStatement);
}
return null;
}