Skip to content

Commit 1d0500f

Browse files
authored
Update BlockStatementTemplateGeneratorAdd with support for templating while-loop condition expressions. (#2213)
1 parent f6bec65 commit 1d0500f

2 files changed

Lines changed: 47 additions & 4 deletions

File tree

rewrite-java-tck/src/main/kotlin/org/openrewrite/java/JavaTemplateTest.kt

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,7 @@ import org.junit.jupiter.api.Test
2525
import org.openrewrite.ExecutionContext
2626
import org.openrewrite.Issue
2727
import org.openrewrite.java.Assertions.java
28-
import org.openrewrite.java.tree.J
29-
import org.openrewrite.java.tree.JavaType
30-
import org.openrewrite.java.tree.Space
31-
import org.openrewrite.java.tree.TypeUtils
28+
import org.openrewrite.java.tree.*
3229
import org.openrewrite.test.RewriteTest
3330
import java.util.Comparator.comparing
3431

@@ -2436,4 +2433,44 @@ interface JavaTemplateTest : RewriteTest, JavaRecipeTest {
24362433
"""
24372434
)
24382435
)
2436+
2437+
@Suppress("LoopConditionNotUpdatedInsideLoop")
2438+
@Test
2439+
fun templatingWhileLoopCondition() = rewriteRun(
2440+
{ spec ->
2441+
spec.recipe(toRecipe {
2442+
object : JavaVisitor<ExecutionContext>() {
2443+
override fun visitBinary(binary: J.Binary, p: ExecutionContext): J {
2444+
if (binary.left is J.MethodInvocation) {
2445+
val mi = binary.left as J.MethodInvocation
2446+
return binary.withTemplate(
2447+
JavaTemplate.builder(this::getCursor, "!#{any(java.util.List)}.isEmpty()")
2448+
.build(), mi.coordinates.replace(), mi.select
2449+
)
2450+
} else if (binary.left is J.Unary) {
2451+
return binary.left
2452+
}
2453+
return binary
2454+
}
2455+
}
2456+
})
2457+
spec.expectedCyclesThatMakeChanges(2)
2458+
},
2459+
java("""
2460+
import java.util.List;
2461+
class T {
2462+
void m(List<?> l) {
2463+
while (l.size() != 0) {}
2464+
}
2465+
}
2466+
""",
2467+
"""
2468+
import java.util.List;
2469+
class T {
2470+
void m(List<?> l) {
2471+
while (!l.isEmpty()) {}
2472+
}
2473+
}
2474+
""")
2475+
)
24392476
}

rewrite-java/src/main/java/org/openrewrite/java/internal/template/BlockStatementTemplateGenerator.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,12 @@ else if (m.getSelect() == prior) {
337337
before.insert(0, "Object __b" + cursor.getPathAsStream().count() + "__ =");
338338
after.append(";");
339339
}
340+
} else if (j instanceof J.WhileLoop) {
341+
J.WhileLoop wl = (J.WhileLoop)j;
342+
if(referToSameElement(prior, wl.getCondition())) {
343+
before.insert(0, "Object __b" + cursor.getPathAsStream().count() + "__ =");
344+
after.append(";");
345+
}
340346
} else if(j instanceof J.Assignment) {
341347
J.Assignment as = (J.Assignment)j;
342348
if(referToSameElement(prior, as.getAssignment())) {

0 commit comments

Comments
 (0)