TryFinallyCanBeTryWithResourcesInspection: non resources variables used outside of try should stay out of try

GitOrigin-RevId: ff020cfb29ee85113ba63296308efdc3cf28dbb9
This commit is contained in:
Roman.Ivanov
2019-05-20 09:05:23 +03:00
committed by intellij-monorepo-bot
parent 1267e002aa
commit e3cf68bf1b
2 changed files with 30 additions and 0 deletions
@@ -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));
}
@@ -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();
}
}