Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -18,10 +18,7 @@
import org.openrewrite.Cursor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.java.internal.template.BlockStatementTemplateGenerator;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.*;

import java.util.Collection;
import java.util.Set;
Expand All @@ -32,17 +29,19 @@ public GroovyBlockStatementTemplateGenerator(Set<String> imports, boolean contex
}

@Override
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after) {
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after, JavaCoordinates.Mode mode) {
if (j instanceof J.MethodInvocation) {
before.insert(0, "class Template {\n");
JavaType.Method methodType = ((J.MethodInvocation) j).getMethodType();
if (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void) {
if (mode == JavaCoordinates.Mode.REPLACEMENT && (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void)) {
before.append("Object o = ");
}
after.append(";\n}");
} else if (j instanceof Expression && !(j instanceof J.Assignment)) {
before.insert(0, "class Template {\n");
before.append("Object o = ");
if(mode == JavaCoordinates.Mode.REPLACEMENT) {
before.append("Object o = ");
}
after.append(";\n}");
} else if (j instanceof J.ClassDeclaration || j instanceof G.ClassDeclaration) {
throw new IllegalArgumentException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public String template(Cursor cursor, String template, Collection<JavaType.Gener
if (contextSensitive) {
contextTemplate(next(cursor), cursor.getValue(), before, after, cursor.getValue(), mode);
} else {
contextFreeTemplate(next(cursor), cursor.getValue(), typeVariables, before, after);
contextFreeTemplate(next(cursor), cursor.getValue(), typeVariables, before, after, mode);
}

return before.toString().trim() +
Expand Down Expand Up @@ -207,7 +207,7 @@ private boolean isTemplateStopComment(Comment comment) {
}

@SuppressWarnings("DataFlowIssue")
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after) {
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after, JavaCoordinates.Mode mode) {
String classDeclaration = typeVariables.isEmpty() ? "Template" :
"Template<" + typeVariables.stream().map(TypeUtils::toGenericTypeString).collect(joining(", ")) + ">";
if (j instanceof J.Lambda && "Object".equals(bindType)) {
Expand All @@ -223,13 +223,15 @@ protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.Gener
} else if (j instanceof J.MethodInvocation) {
before.insert(0, String.format("class %s {{\n", classDeclaration));
JavaType.Method methodType = ((J.MethodInvocation) j).getMethodType();
if (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void) {
if (mode == REPLACEMENT && (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void)) {
before.append(bindType).append(" o = ");
}
after.append(";\n}}");
} else if (j instanceof Expression && !(j instanceof J.Assignment)) {
before.insert(0, String.format("class %s {\n", classDeclaration));
before.append(bindType).append(" o = ");
if (mode == REPLACEMENT) {
before.append(bindType).append(" o = ");
}
after.append(";\n}");
} else if ((j instanceof J.MethodDeclaration || j instanceof J.VariableDeclarations || j instanceof J.Block || j instanceof J.ClassDeclaration) &&
cursor.getValue() instanceof J.Block &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Copyright 2025 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java;

import org.junit.jupiter.api.Test;
import org.openrewrite.ExecutionContext;
import org.openrewrite.java.tree.J;
import org.openrewrite.test.AdHocRecipe;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class AddFirstStatementTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new AdHocRecipe("Test", "Test", false, () -> new JavaIsoVisitor<>(){
@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
J.MethodDeclaration md = super.visitMethodDeclaration(method, ctx);
if(md.getBody() != null && md.getBody().getStatements().size() == 1) {
md = JavaTemplate.builder("String newLine = \"test\";")
.javaParser(JavaParser.fromJavaVersion())
.build()
.apply(getCursor(), md.getBody().getCoordinates().firstStatement());
}
return md;
}
}, null, null));
}

// Without the change this test succeeds
@Test
void firstStatementIsMethodInvocationWithAssignment() {
//language=java
rewriteRun(
java(
"""
public class Subject {
@Override
public void doSomething(Data o) {
int r = o.get();
}

private static interface Data {
int get();
}
}
""",
"""
public class Subject {
@Override
public void doSomething(Data o) {
String newLine = "test";
int r = o.get();
}

private static interface Data {
int get();
}
}
"""
)
);
}

// Without the change this test fails
// The reason is that the new statement is an assignment:
// String newLine = "test";
// The javacoordinates are at md.getBody().getCoordinates().firstStatement():
// o.get();
// The template does not know what you want to do at this point. You might want to replace the method invocation with a constant "123" which would result in invalid code.
// The template will automatically prefix the statement with "Object o = " to make sure the code compiles.
// This is correct when replacing the statement, the end result would be:
// Object o = "123";
// In this case we are not replacing the statement, but prepending it. Because the block generator had no information about the mode, it would still apply the prefix:
// Object o = String newLine = "test";
// The fix to add the mode makes sure that when not replacing, the provided template should be valid in itself, so no modification is required.
@Test
void firstStatementIsMethodInvocationWithReturnTypeWithoutAssignment() {
//language=java
rewriteRun(
java(
"""
public class Subject {
@Override
public void doSomething(Data o) {
o.get();
}

private static interface Data {
int get();
}
}
""",
"""
public class Subject {
@Override
public void doSomething(Data o) {
String newLine = "test";
o.get();
}

private static interface Data {
int get();
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@

import org.openrewrite.Cursor;
import org.openrewrite.java.internal.template.BlockStatementTemplateGenerator;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.*;
import org.openrewrite.kotlin.tree.K;

import java.util.Collection;
Expand All @@ -32,17 +29,19 @@ public KotlinBlockStatementTemplateGenerator(Set<String> imports, boolean contex
}

@Override
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after) {
protected void contextFreeTemplate(Cursor cursor, J j, Collection<JavaType.GenericTypeVariable> typeVariables, StringBuilder before, StringBuilder after, JavaCoordinates.Mode mode) {
if (j instanceof J.MethodInvocation) {
before.insert(0, "class Template {\n");
JavaType.Method methodType = ((J.MethodInvocation) j).getMethodType();
if (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void) {
if (mode == JavaCoordinates.Mode.REPLACEMENT && (methodType == null || methodType.getReturnType() != JavaType.Primitive.Void)) {
before.append("var o : Any = ");
}
after.append(";\n}");
} else if (j instanceof Expression && !(j instanceof J.Assignment)) {
before.insert(0, "class Template {\n");
before.append("var o : Any = ");
if(mode == JavaCoordinates.Mode.REPLACEMENT) {
before.append("var o : Any = ");
}
after.append(";\n}");
} else if (j instanceof J.ClassDeclaration || j instanceof K.ClassDeclaration) {
throw new IllegalArgumentException(
Expand Down