Skip to content

Commit

Permalink
feature(LambdaBlockToExpression): convert lambda with method invocati…
Browse files Browse the repository at this point in the history
…on as well (#241)

* add 2 test cases for method invocation

* add transform for lambdas with method invocation

* remove test with external dependency

the other test covers the expected behavior sufficiently

Co-authored-by: Tim te Beek <[email protected]>

* fix other test

* Retain original prefix to minimize diff

* Extract statement to local variable

---------

Co-authored-by: Tim te Beek <[email protected]>
Co-authored-by: Tim te Beek <[email protected]>
  • Loading branch information
3 people authored Jan 16, 2024
1 parent 4de0242 commit f1e53d2
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,22 @@ public J.Lambda visitLambda(J.Lambda lambda, ExecutionContext ctx) {
J.Lambda l = super.visitLambda(lambda, ctx);
if (lambda.getBody() instanceof J.Block) {
List<Statement> statements = ((J.Block) lambda.getBody()).getStatements();
if (statements.size() == 1 && statements.get(0) instanceof J.Return) {
Space prefix = statements.get(0).getPrefix();
if (prefix.getComments().isEmpty()) {
return l.withBody(((J.Return) statements.get(0)).getExpression());
} else {
return l.withBody(((J.Return) statements.get(0)).getExpression().withPrefix(prefix));
if (statements.size() == 1) {
Statement statement = statements.get(0);
Space prefix = statement.getPrefix();
if (statement instanceof J.Return) {
Expression expression = ((J.Return) statement).getExpression();
if (prefix.getComments().isEmpty()) {
return l.withBody(expression);
} else {
return l.withBody(expression.withPrefix(prefix));
}
} else if (statement instanceof J.MethodInvocation) {
if (prefix.getComments().isEmpty()) {
return l.withBody(statement);
} else {
return l.withBody(statement.withPrefix(prefix));
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,35 @@ void doTest() {
);
}

@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/236")
@Test
void simplifyLambdaBlockReturningVoidAsWell2() {
//language=java
rewriteRun(
java(
"""
public class Main {
public void run() {
Runnable runHelloWorld = () -> {
System.out.println("Hello world!");
};
runHelloWorld.run();
}
}
""",
"""
public class Main {
public void run() {
Runnable runHelloWorld = () ->
System.out.println("Hello world!");
runHelloWorld.run();
}
}
"""
)
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,9 @@ class Test {
void bar(Consumer<Integer> c) {
}
void foo() {
bar(i -> {
bar(i2 -> {
});
});
bar(i ->
bar(i2 -> {
}));
}
}
"""
Expand Down

0 comments on commit f1e53d2

Please sign in to comment.