mirror of
https://gitflic.ru/project/openide/openide.git
synced 2026-09-27 10:03:11 +07:00
TryFinallyCanBeTryWithResourcesInspection: non resources variables used outside of try should stay out of try
GitOrigin-RevId: ff020cfb29ee85113ba63296308efdc3cf28dbb9
This commit is contained in:
committed by
intellij-monorepo-bot
parent
1267e002aa
commit
e3cf68bf1b
+12
@@ -315,6 +315,18 @@ public class TryFinallyCanBeTryWithResourcesInspection extends BaseInspection {
|
||||
if (!initializersAreAtTheBeginning(initializerPositions)) return null;
|
||||
|
||||
Collections.sort(resourceVariables, Comparator.comparing(o -> o.getInitializedElement(), PsiElementOrderComparator.getInstance()));
|
||||
Optional<ResourceVariable> lastNonTryVar = StreamEx.of(ContainerUtil.reverse(resourceVariables))
|
||||
.findFirst(r -> !PsiTreeUtil.isAncestor(tryStatement, r.myVariable, false));
|
||||
if (lastNonTryVar.isPresent()) {
|
||||
PsiVariable variable = lastNonTryVar.get().myVariable;
|
||||
PsiStatement statement = PsiTreeUtil.getParentOfType(variable, PsiStatement.class);
|
||||
List<PsiStatement> statements = collectStatementsBetween(statement, tryStatement);
|
||||
boolean varUsedNotInTry = StreamEx.of(statements)
|
||||
.flatMap(stmt -> StreamEx.ofTree((PsiElement)stmt, e -> StreamEx.of(e.getChildren())))
|
||||
.select(PsiLocalVariable.class)
|
||||
.anyMatch(variable1 -> isVariableUsedOutsideContext(variable1, tryStatement));
|
||||
if (varUsedNotInTry) return null;
|
||||
}
|
||||
return new Context(resourceVariables, new HashSet<>(statementsToDelete));
|
||||
}
|
||||
|
||||
|
||||
+18
@@ -101,4 +101,22 @@ class FinallyContainsTry {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class NonResourceBeforeTry {
|
||||
public static String test(String str) throws IOException {
|
||||
final InputStream stream = new ByteArrayInputStream(str.getBytes());
|
||||
final StringBuilder res = new StringBuilder();
|
||||
try {
|
||||
int entry;
|
||||
while ((entry = stream.read()) > -1) {
|
||||
res.append(entry).append("\n");
|
||||
}
|
||||
}
|
||||
finally {
|
||||
stream.close();
|
||||
}
|
||||
|
||||
return res.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user