Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

do not remove try block if there are resources #161

Merged
merged 5 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ public J.Block visitBlock(J.Block block, P p) {
public J.Try visitTry(J.Try tryable, P p) {
J.Try t = super.visitTry(tryable, p);

if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralTry()) && isEmptyBlock(t.getBody())) {
if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralTry()) &&
isEmptyBlock(t.getBody()) &&
(t.getResources() == null || t.getResources().isEmpty())) {
doAfterVisit(new DeleteStatement<>(tryable));
} else if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralFinally()) && t.getFinally() != null
&& !t.getCatches().isEmpty() && isEmptyBlock(t.getFinally())) {
Expand Down Expand Up @@ -211,7 +213,7 @@ public J.Switch visitSwitch(J.Switch switch_, P p) {

private boolean isEmptyBlock(Statement blockNode) {
if (blockNode instanceof J.Block) {
J.Block block = (J.Block)blockNode;
J.Block block = (J.Block) blockNode;
if (EmptyBlockStyle.BlockPolicy.STATEMENT.equals(emptyBlockStyle.getBlockPolicy())) {
return block.getStatements().isEmpty();
} else if (EmptyBlockStyle.BlockPolicy.TEXT.equals(emptyBlockStyle.getBlockPolicy())) {
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/org/openrewrite/staticanalysis/EmptyBlockTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,27 @@ public class A {
)
);
}

@Test
void emptyTryWithResources() {
rewriteRun(
//language=java
java(
"""
import java.io.FileInputStream;import java.io.IOException;import java.io.UncheckedIOException;public class A {
private final InputStream stdin = new FileInputStream("test.in");
private final InputStream stdout = new FileInputStream("test.out");

public void destroy() {
// close all streams in a try-with-resources
try (stdin; stdout) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
"""
)
);
}
}
Loading