Skip to content

Commit

Permalink
Merge pull request #161 from openrewrite/bug/removed-try-with-non-emp…
Browse files Browse the repository at this point in the history
…ty-resources

do not remove try block if there are resources
  • Loading branch information
sambsnyd committed Aug 24, 2023
2 parents a58e9c5 + 8d16fdd commit 31491f3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.DeleteStatement;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
Expand Down Expand Up @@ -97,7 +98,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()) &&
isEmptyResources(t.getResources())) {
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 +214,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 All @@ -221,6 +224,10 @@ private boolean isEmptyBlock(Statement blockNode) {
return false;
}

private boolean isEmptyResources(@Nullable List<J.Try.Resource> resources) {
return resources == null || resources.isEmpty();
}

private static class ExtractSideEffectsOfIfCondition<P> extends JavaVisitor<P> {
private final J.Block enclosingBlock;
private final J.If toExtract;
Expand Down
23 changes: 22 additions & 1 deletion src/test/java/org/openrewrite/staticanalysis/EmptyBlockTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ void emptyTry() {
public class A {
{
final String fileName = "fileName";
try(FileInputStream fis = new FileInputStream(fileName)) {
try {
} catch (IOException e) {
}
}
Expand Down Expand Up @@ -414,4 +414,25 @@ public class A {
)
);
}

@Test
void emptyTryWithResources() {
rewriteRun(
//language=java
java(
"""
import java.io.*;
public class A {
{
final String fileName = "fileName";
try (FileInputStream fis = new FileInputStream(fileName)) {
} catch (IOException e) {
}
}
}
"""
)
);
}
}

0 comments on commit 31491f3

Please sign in to comment.