Skip to content

Commit

Permalink
Adding a check for Void return type and no return expression
Browse files Browse the repository at this point in the history
  • Loading branch information
mccartney committed Nov 17, 2024
1 parent 7112d6e commit bcc951a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.TypeUtils;

import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -58,7 +60,7 @@ private J.Block maybeRemoveReturnAsLastStatement(J.Block b) {
}
Statement lastStatement = statements.get(statements.size() - 1);
List<Statement> allButLast = statements.subList(0, statements.size() - 1);
if (lastStatement instanceof J.Return) {
if (lastStatement instanceof J.Return && ((J.Return) lastStatement).getExpression() == null) {
return b.withStatements(allButLast);
} else if (lastStatement instanceof J.If) {
J.If ifStatement = (J.If) lastStatement;
Expand All @@ -77,7 +79,11 @@ private J.Block maybeRemoveReturnAsLastStatement(J.Block b) {
@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx);
return m.withBody(maybeRemoveReturnAsLastStatement(m.getBody()));
if (TypeUtils.asPrimitive(m.getType()) == JavaType.Primitive.Void) {
return m.withBody(maybeRemoveReturnAsLastStatement(m.getBody()));
} else {
return m;
}
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,19 @@ void world(int i) {
}
"""));
}

@Test
void notChangingNonVoidMethods() {
//language=java
rewriteRun(
java(
"""
class Hello {
int world(int i) {
return i + 436;
}
}
"""));
}

}

0 comments on commit bcc951a

Please sign in to comment.