From 2f498686de5943ae4a9f983098045c0bae25011e Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Wed, 27 Dec 2023 21:53:59 +0100 Subject: [PATCH 01/22] Inline JavaTemplate into RefasterTemplateProcessor --- .../java/template/internal/TemplateCode.java | 7 ++ .../processor/RefasterTemplateProcessor.java | 64 ++++++------------- .../template/processor/TemplateProcessor.java | 9 +-- 3 files changed, 26 insertions(+), 54 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java index 589b3181..29982f21 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java +++ b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java @@ -56,6 +56,13 @@ public static String process(T tree, List getVisitor() {\n"); recipe.append(" JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() {\n"); for (Map.Entry entry : beforeTemplates.entrySet()) { + JCTree.JCMethodDecl methodDecl = entry.getValue(); recipe.append(" final JavaTemplate ") .append(entry.getKey()) - .append(" = Semantics.") - .append(statementType(entry.getValue())) - .append("(this, \"") - .append(entry.getKey()).append("\", ") - .append(toLambda(entry.getValue())) - .append(").build();\n"); + .append(" = ") + .append(toJavaTemplateBuilder(methodDecl)) + .append("\n .build();\n"); } recipe.append(" final JavaTemplate ") .append(after) - .append(" = Semantics.") - .append(statementType(descriptor.afterTemplate)) - .append("(this, \"") - .append(after) - .append("\", ") - .append(toLambda(descriptor.afterTemplate)) - .append(").build();\n"); + .append(" = ") + .append(toJavaTemplateBuilder(descriptor.afterTemplate)) + .append("\n .build();\n"); recipe.append("\n"); List lstTypes = LST_TYPE_MAP.get(getType(descriptor.beforeTemplates.get(0))); @@ -312,6 +303,7 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { out.write("import org.openrewrite.Recipe;\n"); out.write("import org.openrewrite.TreeVisitor;\n"); out.write("import org.openrewrite.internal.lang.NonNullApi;\n"); + out.write("import org.openrewrite.java.JavaParser;\n"); out.write("import org.openrewrite.java.JavaTemplate;\n"); out.write("import org.openrewrite.java.JavaVisitor;\n"); out.write("import org.openrewrite.java.search.*;\n"); @@ -381,6 +373,15 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { } } + private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl) { + JCTree tree = methodDecl.getBody().getStatements().get(0); + if (tree instanceof JCTree.JCReturn) { + tree = ((JCTree.JCReturn) tree).getExpression(); + } + String javaTemplateBuilder = TemplateCode.process(tree, methodDecl.getParameters(), true); + return TemplateCode.indent(javaTemplateBuilder, 16); + } + private boolean simplifyBooleans(JCTree.JCMethodDecl template) { if (template.getReturnType().type.getTag() == TypeTag.BOOLEAN) { return true; @@ -651,35 +652,6 @@ private String statementType(JCTree.JCMethodDecl method) { return "expression"; } - private String toLambda(JCTree.JCMethodDecl method) { - StringBuilder builder = new StringBuilder(); - - StringJoiner joiner = new StringJoiner(", ", "(", ")"); - for (JCTree.JCVariableDecl parameter : method.getParameters()) { - String paramType = parameter.getType().type.toString(); - if (!getBoxedPrimitive(paramType).equals(paramType)) { - paramType = "@Primitive " + getBoxedPrimitive(paramType); - } else if (paramType.startsWith("java.lang.")) { - paramType = paramType.substring("java.lang.".length()); - } - joiner.add(paramType + " " + parameter.getName()); - } - builder.append(joiner); - builder.append(" -> "); - - JCTree.JCStatement statement = method.getBody().getStatements().get(0); - if (statement instanceof JCTree.JCReturn) { - builder.append(FQNPretty.toString(((JCTree.JCReturn) statement).getExpression())); - } else if (statement instanceof JCTree.JCThrow) { - String string = FQNPretty.toString(statement); - builder.append("{ ").append(string).append(" }"); - } else { - String string = FQNPretty.toString(statement); - builder.append(string); - } - return builder.toString(); - } - @Nullable private TemplateDescriptor getTemplateDescriptor(JCTree.JCClassDecl tree, Context context, JCCompilationUnit cu) { TemplateDescriptor result = new TemplateDescriptor(tree); diff --git a/src/main/java/org/openrewrite/java/template/processor/TemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/TemplateProcessor.java index dba28953..4dea5dc5 100644 --- a/src/main/java/org/openrewrite/java/template/processor/TemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/TemplateProcessor.java @@ -168,7 +168,7 @@ public void visitApply(JCTree.JCMethodInvocation tree) { out.write(" * @return the JavaTemplate builder.\n"); out.write(" */\n"); out.write(" public static JavaTemplate.Builder getTemplate() {\n"); - out.write(" return " + indent(templateCode, 12) + ";\n"); + out.write(" return " + TemplateCode.indent(templateCode, 12) + ";\n"); out.write(" }\n"); out.write("}\n"); out.flush(); @@ -181,13 +181,6 @@ public void visitApply(JCTree.JCMethodInvocation tree) { super.visitApply(tree); } - - private String indent(String code, int width) { - char[] indent = new char[width]; - Arrays.fill(indent, ' '); - String replacement = "$1" + new String(indent); - return code.replaceAll("(?m)(\\R)", replacement); - } }.scan(cu); } From 10d7be3ecfb0fb55b1b4fcb89cb1ff5dfc450184 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Wed, 27 Dec 2023 21:54:15 +0100 Subject: [PATCH 02/22] Adapt Refaster input and output tests --- src/test/resources/refaster/ArraysRecipe.java | 19 ++++-- .../resources/refaster/EscapesRecipes.java | 42 ++++++++++-- .../resources/refaster/MatchingRecipes.java | 27 ++++++-- .../refaster/MethodThrowsRecipe.java | 15 ++++- .../refaster/MultipleDereferencesRecipes.java | 50 ++++++++++++-- .../refaster/NestedPreconditionsRecipe.java | 19 +++++- .../refaster/ParameterReuseRecipe.java | 16 ++++- .../refaster/ShouldAddImportsRecipes.java | 67 ++++++++++++++++--- .../ShouldSupportNestedClassesRecipes.java | 37 ++++++++-- .../refaster/SimplifyBooleansRecipe.java | 16 ++++- .../refaster/UseStringIsEmptyRecipe.java | 14 +++- 11 files changed, 276 insertions(+), 46 deletions(-) diff --git a/src/test/resources/refaster/ArraysRecipe.java b/src/test/resources/refaster/ArraysRecipe.java index 0f690e16..5e039170 100644 --- a/src/test/resources/refaster/ArraysRecipe.java +++ b/src/test/resources/refaster/ArraysRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -33,12 +34,18 @@ import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*; + +/** + * OpenRewrite recipe created for Refaster template {@code Arrays}. + */ @SuppressWarnings("all") @NonNullApi public class ArraysRecipe extends Recipe { - public ArraysRecipe() { - } + /** + * Instantiates a new instance. + */ + public ArraysRecipe() {} @Override public String getDisplayName() { @@ -53,8 +60,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String[] strings) -> String.join(", ", strings)).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String[] strings) -> String.join(":", strings)).build(); + final JavaTemplate before = JavaTemplate + .builder("String.join(\", \", foo.Arrays.before.strings)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("String.join(\":\", foo.Arrays.after.strings)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/EscapesRecipes.java b/src/test/resources/refaster/EscapesRecipes.java index 82b89aaa..0056ee34 100644 --- a/src/test/resources/refaster/EscapesRecipes.java +++ b/src/test/resources/refaster/EscapesRecipes.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package foo; import org.openrewrite.ExecutionContext; @@ -20,6 +21,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -36,8 +38,14 @@ import com.sun.tools.javac.util.Convert; import com.sun.tools.javac.util.Constants; +/** + * OpenRewrite recipes created for Refaster template {@code foo.Escapes}. + */ @SuppressWarnings("all") public class EscapesRecipes extends Recipe { + /** + * Instantiates a new instance. + */ public EscapesRecipes() {} @Override @@ -58,9 +66,16 @@ public List getRecipeList() { ); } + /** + * OpenRewrite recipe created for Refaster template {@code Escapes.ConstantsFormat}. + */ @SuppressWarnings("all") @NonNullApi public static class ConstantsFormatRecipe extends Recipe { + + /** + * Instantiates a new instance. + */ public ConstantsFormatRecipe() {} @Override @@ -76,8 +91,14 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String value) -> String.format("\"%s\"", com.sun.tools.javac.util.Convert.quote(value))).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String value) -> com.sun.tools.javac.util.Constants.format(value)).build(); + final JavaTemplate before = JavaTemplate + .builder("String.format(\"\\\"%s\\\"\", com.sun.tools.javac.util.Convert.quote(foo.Escapes.ConstantsFormat.before.value))") + .javaParser(JavaParser.fromJavaVersion().classpath("tools")) + .build(); + final JavaTemplate after = JavaTemplate + .builder("com.sun.tools.javac.util.Constants.format(foo.Escapes.ConstantsFormat.after.value)") + .javaParser(JavaParser.fromJavaVersion().classpath("tools")) + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -106,9 +127,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code Escapes.Split}. + */ @SuppressWarnings("all") @NonNullApi public static class SplitRecipe extends Recipe { + + /** + * Instantiates a new instance. + */ public SplitRecipe() {} @Override @@ -124,8 +152,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s.split("[^\\S]+")).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> s.split("\\s+")).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.Escapes.Split.before.s.split(\"[^\\\\S]+\")") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.Escapes.Split.after.s.split(\"\\\\s+\")") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -149,4 +181,4 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } -} \ No newline at end of file +} diff --git a/src/test/resources/refaster/MatchingRecipes.java b/src/test/resources/refaster/MatchingRecipes.java index 5933f353..af3d86fe 100644 --- a/src/test/resources/refaster/MatchingRecipes.java +++ b/src/test/resources/refaster/MatchingRecipes.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -33,9 +34,15 @@ import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*; + +/** + * OpenRewrite recipes created for Refaster template {@code foo.Matching}. + */ @SuppressWarnings("all") public class MatchingRecipes extends Recipe { - + /** + * Instantiates a new instance. + */ public MatchingRecipes() {} @Override @@ -60,10 +67,16 @@ public List getRecipeList() { ); } + /** + * OpenRewrite recipe created for Refaster template {@code Matching.StringIsEmpty}. + */ @SuppressWarnings("all") @NonNullApi public static class StringIsEmptyRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public StringIsEmptyRecipe() {} @Override @@ -84,9 +97,15 @@ public Set getTags() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (@Primitive Integer i, String s) -> s.substring(i).isEmpty()).build(); - final JavaTemplate before2 = Semantics.expression(this, "before2", (@Primitive Integer i, String s) -> s.substring(i).isEmpty()).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> (s != null && s.length() == 0)).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.Matching.StringIsEmpty.before.s.substring(foo.Matching.StringIsEmpty.before.i).isEmpty()") + .build(); + final JavaTemplate before2 = JavaTemplate + .builder("foo.Matching.StringIsEmpty.before2.s.substring(foo.Matching.StringIsEmpty.before2.i).isEmpty()") + .build(); + final JavaTemplate after = JavaTemplate + .builder("(foo.Matching.StringIsEmpty.after.s != null && foo.Matching.StringIsEmpty.after.s.length() == 0)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/MethodThrowsRecipe.java b/src/test/resources/refaster/MethodThrowsRecipe.java index d13e5279..017ed8f5 100644 --- a/src/test/resources/refaster/MethodThrowsRecipe.java +++ b/src/test/resources/refaster/MethodThrowsRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -37,10 +38,16 @@ import java.nio.file.Path; import java.nio.charset.StandardCharsets; +/** + * OpenRewrite recipe created for Refaster template {@code MethodThrows}. + */ @SuppressWarnings("all") @NonNullApi public class MethodThrowsRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public MethodThrowsRecipe() {} @Override @@ -56,8 +63,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.statement(this, "before", (java.nio.file.Path path) -> java.nio.file.Files.readAllLines(path, java.nio.charset.StandardCharsets.UTF_8)).build(); - final JavaTemplate after = Semantics.statement(this, "after", (java.nio.file.Path path) -> java.nio.file.Files.readAllLines(path)).build(); + final JavaTemplate before = JavaTemplate + .builder("java.nio.file.Files.readAllLines(foo.MethodThrows.before.path, java.nio.charset.StandardCharsets.UTF_8)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("java.nio.file.Files.readAllLines(foo.MethodThrows.after.path)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/MultipleDereferencesRecipes.java b/src/test/resources/refaster/MultipleDereferencesRecipes.java index a9a9cbee..ea92e251 100644 --- a/src/test/resources/refaster/MultipleDereferencesRecipes.java +++ b/src/test/resources/refaster/MultipleDereferencesRecipes.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -36,9 +37,14 @@ import java.nio.file.Files; import java.nio.file.Path; +/** + * OpenRewrite recipes created for Refaster template {@code foo.MultipleDereferences}. + */ @SuppressWarnings("all") public class MultipleDereferencesRecipes extends Recipe { - + /** + * Instantiates a new instance. + */ public MultipleDereferencesRecipes() {} @Override @@ -60,10 +66,16 @@ public List getRecipeList() { ); } + /** + * OpenRewrite recipe created for Refaster template {@code MultipleDereferences.VoidType}. + */ @SuppressWarnings("all") @NonNullApi public static class VoidTypeRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public VoidTypeRecipe() {} @Override @@ -79,8 +91,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.statement(this, "before", (java.nio.file.Path p) -> java.nio.file.Files.delete(p)).build(); - final JavaTemplate after = Semantics.statement(this, "after", (java.nio.file.Path p) -> java.nio.file.Files.delete(p)).build(); + final JavaTemplate before = JavaTemplate + .builder("java.nio.file.Files.delete(foo.MultipleDereferences.VoidType.before.p)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("java.nio.file.Files.delete(foo.MultipleDereferences.VoidType.after.p)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -108,10 +124,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code MultipleDereferences.StringIsEmpty}. + */ @SuppressWarnings("all") @NonNullApi public static class StringIsEmptyRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public StringIsEmptyRecipe() {} @Override @@ -127,8 +149,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s.isEmpty()).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> s != null && s.length() == 0).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.MultipleDereferences.StringIsEmpty.before.s.isEmpty()") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.MultipleDereferences.StringIsEmpty.after.s != null && foo.MultipleDereferences.StringIsEmpty.after.s.length() == 0") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -152,10 +178,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code MultipleDereferences.EqualsItself}. + */ @SuppressWarnings("all") @NonNullApi public static class EqualsItselfRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public EqualsItselfRecipe() {} @Override @@ -171,8 +203,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (Object o) -> o == o).build(); - final JavaTemplate after = Semantics.expression(this, "after", (Object o) -> true).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.MultipleDereferences.EqualsItself.before.o == foo.MultipleDereferences.EqualsItself.before.o") + .build(); + final JavaTemplate after = JavaTemplate + .builder("true") + .build(); @Override public J visitBinary(J.Binary elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/NestedPreconditionsRecipe.java b/src/test/resources/refaster/NestedPreconditionsRecipe.java index 1bd44d33..c6fc6754 100644 --- a/src/test/resources/refaster/NestedPreconditionsRecipe.java +++ b/src/test/resources/refaster/NestedPreconditionsRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -38,10 +39,16 @@ import java.util.HashMap; import java.util.Hashtable; +/** + * OpenRewrite recipe created for Refaster template {@code NestedPreconditions}. + */ @SuppressWarnings("all") @NonNullApi public class NestedPreconditionsRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public NestedPreconditionsRecipe() {} @Override @@ -57,9 +64,15 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate hashMap = Semantics.expression(this, "hashMap", (@Primitive Integer size) -> new java.util.HashMap(size)).build(); - final JavaTemplate linkedHashMap = Semantics.expression(this, "linkedHashMap", (@Primitive Integer size) -> new java.util.LinkedHashMap(size)).build(); - final JavaTemplate hashtable = Semantics.expression(this, "hashtable", (@Primitive Integer size) -> new java.util.Hashtable(size)).build(); + final JavaTemplate hashMap = JavaTemplate + .builder("new java.util.HashMap(foo.NestedPreconditions.hashMap.size)") + .build(); + final JavaTemplate linkedHashMap = JavaTemplate + .builder("new java.util.LinkedHashMap(foo.NestedPreconditions.linkedHashMap.size)") + .build(); + final JavaTemplate hashtable = JavaTemplate + .builder("new java.util.Hashtable(foo.NestedPreconditions.hashtable.size)") + .build(); @Override public J visitExpression(Expression elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/ParameterReuseRecipe.java b/src/test/resources/refaster/ParameterReuseRecipe.java index c1c7b888..ca0e1eee 100644 --- a/src/test/resources/refaster/ParameterReuseRecipe.java +++ b/src/test/resources/refaster/ParameterReuseRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -33,10 +34,17 @@ import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*; + +/** + * OpenRewrite recipe created for Refaster template {@code ParameterReuse}. + */ @SuppressWarnings("all") @NonNullApi public class ParameterReuseRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public ParameterReuseRecipe() {} @Override @@ -52,8 +60,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s == s).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> s.equals(s)).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.ParameterReuse.before.s == foo.ParameterReuse.before.s") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.ParameterReuse.after.s.equals(foo.ParameterReuse.after.s)") + .build(); @Override public J visitBinary(J.Binary elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/ShouldAddImportsRecipes.java b/src/test/resources/refaster/ShouldAddImportsRecipes.java index 8d573dd4..1a5da964 100644 --- a/src/test/resources/refaster/ShouldAddImportsRecipes.java +++ b/src/test/resources/refaster/ShouldAddImportsRecipes.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -39,8 +40,14 @@ import static java.nio.file.Files.exists; import static java.util.Objects.hash; +/** + * OpenRewrite recipes created for Refaster template {@code foo.ShouldAddImports}. + */ @SuppressWarnings("all") public class ShouldAddImportsRecipes extends Recipe { + /** + * Instantiates a new instance. + */ public ShouldAddImportsRecipes() {} @Override @@ -63,10 +70,16 @@ public List getRecipeList() { ); } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldAddImports.StringValueOf}. + */ @SuppressWarnings("all") @NonNullApi public static class StringValueOfRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public StringValueOfRecipe() {} @Override @@ -82,8 +95,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> String.valueOf(s)).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> java.util.Objects.toString(s)).build(); + final JavaTemplate before = JavaTemplate + .builder("String.valueOf(foo.ShouldAddImports.StringValueOf.before.s)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("java.util.Objects.toString(foo.ShouldAddImports.StringValueOf.after.s)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -107,10 +124,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldAddImports.ObjectsEquals}. + */ @SuppressWarnings("all") @NonNullApi public static class ObjectsEqualsRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public ObjectsEqualsRecipe() {} @Override @@ -126,9 +149,15 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate equals = Semantics.expression(this, "equals", (@Primitive Integer a, @Primitive Integer b) -> java.util.Objects.equals(a, b)).build(); - final JavaTemplate compareZero = Semantics.expression(this, "compareZero", (@Primitive Integer a, @Primitive Integer b) -> Integer.compare(a, b) == 0).build(); - final JavaTemplate isis = Semantics.expression(this, "isis", (@Primitive Integer a, @Primitive Integer b) -> a == b).build(); + final JavaTemplate equals = JavaTemplate + .builder("java.util.Objects.equals(foo.ShouldAddImports.ObjectsEquals.equals.a, foo.ShouldAddImports.ObjectsEquals.equals.b)") + .build(); + final JavaTemplate compareZero = JavaTemplate + .builder("Integer.compare(foo.ShouldAddImports.ObjectsEquals.compareZero.a, foo.ShouldAddImports.ObjectsEquals.compareZero.b) == 0") + .build(); + final JavaTemplate isis = JavaTemplate + .builder("foo.ShouldAddImports.ObjectsEquals.isis.a == foo.ShouldAddImports.ObjectsEquals.isis.b") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -167,10 +196,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldAddImports.StaticImportObjectsHash}. + */ @SuppressWarnings("all") @NonNullApi public static class StaticImportObjectsHashRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public StaticImportObjectsHashRecipe() {} @Override @@ -186,8 +221,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> hash(s)).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> s.hashCode()).build(); + final JavaTemplate before = JavaTemplate + .builder("java.util.Objects.hash(foo.ShouldAddImports.StaticImportObjectsHash.before.s)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.ShouldAddImports.StaticImportObjectsHash.after.s.hashCode()") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { @@ -212,10 +251,16 @@ public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldAddImports.FileExists}. + */ @SuppressWarnings("all") @NonNullApi public static class FileExistsRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public FileExistsRecipe() {} @Override @@ -231,8 +276,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (java.nio.file.Path path) -> path.toFile().exists()).build(); - final JavaTemplate after = Semantics.expression(this, "after", (java.nio.file.Path path) -> exists(path)).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.ShouldAddImports.FileExists.before.path.toFile().exists()") + .build(); + final JavaTemplate after = JavaTemplate + .builder("java.nio.file.Files.exists(foo.ShouldAddImports.FileExists.after.path)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java index 7b0c083e..3a5c97e3 100644 --- a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java +++ b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -33,9 +34,15 @@ import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*; + +/** + * OpenRewrite recipes created for Refaster template {@code foo.ShouldSupportNestedClasses}. + */ @SuppressWarnings("all") public class ShouldSupportNestedClassesRecipes extends Recipe { - + /** + * Instantiates a new instance. + */ public ShouldSupportNestedClassesRecipes() {} @Override @@ -56,10 +63,16 @@ public List getRecipeList() { ); } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldSupportNestedClasses.NestedClass}. + */ @SuppressWarnings("all") @NonNullApi public static class NestedClassRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public NestedClassRecipe() {} @Override @@ -75,8 +88,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s.length() > 0).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> !s.isEmpty()).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.ShouldSupportNestedClasses.NestedClass.before.s.length() > 0") + .build(); + final JavaTemplate after = JavaTemplate + .builder("!foo.ShouldSupportNestedClasses.NestedClass.after.s.isEmpty()") + .build(); @Override public J visitBinary(J.Binary elem, ExecutionContext ctx) { @@ -100,10 +117,16 @@ public J visitBinary(J.Binary elem, ExecutionContext ctx) { } } + /** + * OpenRewrite recipe created for Refaster template {@code ShouldSupportNestedClasses.AnotherClass}. + */ @SuppressWarnings("all") @NonNullApi public static class AnotherClassRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public AnotherClassRecipe() {} @Override @@ -119,8 +142,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s.length() == 0).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> s.isEmpty()).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.ShouldSupportNestedClasses.AnotherClass.before.s.length() == 0") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.ShouldSupportNestedClasses.AnotherClass.after.s.isEmpty()") + .build(); @Override public J visitBinary(J.Binary elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/SimplifyBooleansRecipe.java b/src/test/resources/refaster/SimplifyBooleansRecipe.java index f72ade77..f42c9fe9 100644 --- a/src/test/resources/refaster/SimplifyBooleansRecipe.java +++ b/src/test/resources/refaster/SimplifyBooleansRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -33,10 +34,17 @@ import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*; + +/** + * OpenRewrite recipe created for Refaster template {@code SimplifyBooleans}. + */ @SuppressWarnings("all") @NonNullApi public class SimplifyBooleansRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public SimplifyBooleansRecipe() {} @Override @@ -52,8 +60,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s, String s1, String s2) -> s.replaceAll(s1, s2)).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s, String s1, String s2) -> s != null ? s.replaceAll(s1, s2) : s).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.SimplifyBooleans.before.s.replaceAll(foo.SimplifyBooleans.before.s1, foo.SimplifyBooleans.before.s2)") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.SimplifyBooleans.after.s != null ? foo.SimplifyBooleans.after.s.replaceAll(foo.SimplifyBooleans.after.s1, foo.SimplifyBooleans.after.s2) : foo.SimplifyBooleans.after.s") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/UseStringIsEmptyRecipe.java b/src/test/resources/refaster/UseStringIsEmptyRecipe.java index 200fe612..28981b5d 100644 --- a/src/test/resources/refaster/UseStringIsEmptyRecipe.java +++ b/src/test/resources/refaster/UseStringIsEmptyRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -35,12 +36,15 @@ /** - * OpenRewrite recipe created for Refaster template `UseStringIsEmpty`. + * OpenRewrite recipe created for Refaster template {@code UseStringIsEmpty}. */ @SuppressWarnings("all") @NonNullApi public class UseStringIsEmptyRecipe extends Recipe { + /** + * Instantiates a new instance. + */ public UseStringIsEmptyRecipe() {} @Override @@ -56,8 +60,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (String s) -> s.length() > 0).build(); - final JavaTemplate after = Semantics.expression(this, "after", (String s) -> !s.isEmpty()).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.UseStringIsEmpty.before.s.length() > 0") + .build(); + final JavaTemplate after = JavaTemplate + .builder("!foo.UseStringIsEmpty.after.s.isEmpty()") + .build(); @Override public J visitBinary(J.Binary elem, ExecutionContext ctx) { From 57c8e52468fe0a9a16f458d005c964b46b9efeae Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Wed, 27 Dec 2023 21:55:28 +0100 Subject: [PATCH 03/22] Remove unused method statementType --- .../processor/RefasterTemplateProcessor.java | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index 9a733b8f..75006a44 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -632,26 +632,6 @@ private Class getType(JCTree.JCMethodDecl method) { return type; } - private String statementType(JCTree.JCMethodDecl method) { - // for now excluding assignment expressions and prefix and postfix -- and ++ - Set> expressionStatementTypes = Stream.of( - JCTree.JCMethodInvocation.class, - JCTree.JCNewClass.class).collect(Collectors.toSet()); - - Class type = getType(method); - if (expressionStatementTypes.contains(type)) { - if (type == JCTree.JCMethodInvocation.class - && method.getBody().getStatements().last() instanceof JCTree.JCExpressionStatement - && !(method.getReturnType().type instanceof Type.JCVoidType)) { - return "expression"; - } - if (method.restype.type instanceof Type.JCVoidType || !JCTree.JCExpression.class.isAssignableFrom(type)) { - return "statement"; - } - } - return "expression"; - } - @Nullable private TemplateDescriptor getTemplateDescriptor(JCTree.JCClassDecl tree, Context context, JCCompilationUnit cu) { TemplateDescriptor result = new TemplateDescriptor(tree); From 6ce5044f7cb22efbedabb2b31870054094fe1402 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Fri, 29 Dec 2023 17:44:51 +0100 Subject: [PATCH 04/22] Resolve parameters, which now triggers NPE --- .../processor/RefasterTemplateProcessor.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index 75006a44..b5d1c0cc 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -26,7 +26,10 @@ import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Context; import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.java.template.internal.*; +import org.openrewrite.java.template.internal.ImportDetector; +import org.openrewrite.java.template.internal.JavacResolution; +import org.openrewrite.java.template.internal.TemplateCode; +import org.openrewrite.java.template.internal.UsedMethodDetector; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; @@ -103,6 +106,7 @@ public boolean process(Set annotations, RoundEnvironment void maybeGenerateTemplateSources(JCCompilationUnit cu) { Context context = javacProcessingEnv.getContext(); + JavacResolution res = new JavacResolution(context); new TreeScanner() { final Map> imports = new HashMap<>(); @@ -378,7 +382,16 @@ private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl) { if (tree instanceof JCTree.JCReturn) { tree = ((JCTree.JCReturn) tree).getExpression(); } - String javaTemplateBuilder = TemplateCode.process(tree, methodDecl.getParameters(), true); + List parameters = new ArrayList<>(methodDecl.getParameters().size()); + if (!methodDecl.getParameters().isEmpty()) { + Map parameterResolution = res.resolveAll(context, cu, methodDecl.getParameters()); + for (VariableTree p : methodDecl.getParameters()) { + JCTree p1 = (JCTree) p; + JCTree.JCVariableDecl e = (JCTree.JCVariableDecl) parameterResolution.get(p1); + parameters.add(e); + } + } + String javaTemplateBuilder = TemplateCode.process(tree, parameters, true); return TemplateCode.indent(javaTemplateBuilder, 16); } From 0ae56a8f737eac74ffa9525bd2c9bc54d758cd0c Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 2 Jan 2024 22:20:09 +0100 Subject: [PATCH 05/22] Revert JavacResolution for template parameters --- .../processor/RefasterTemplateProcessor.java | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index b5d1c0cc..fcfedc86 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -106,7 +106,6 @@ public boolean process(Set annotations, RoundEnvironment void maybeGenerateTemplateSources(JCCompilationUnit cu) { Context context = javacProcessingEnv.getContext(); - JavacResolution res = new JavacResolution(context); new TreeScanner() { final Map> imports = new HashMap<>(); @@ -382,16 +381,7 @@ private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl) { if (tree instanceof JCTree.JCReturn) { tree = ((JCTree.JCReturn) tree).getExpression(); } - List parameters = new ArrayList<>(methodDecl.getParameters().size()); - if (!methodDecl.getParameters().isEmpty()) { - Map parameterResolution = res.resolveAll(context, cu, methodDecl.getParameters()); - for (VariableTree p : methodDecl.getParameters()) { - JCTree p1 = (JCTree) p; - JCTree.JCVariableDecl e = (JCTree.JCVariableDecl) parameterResolution.get(p1); - parameters.add(e); - } - } - String javaTemplateBuilder = TemplateCode.process(tree, parameters, true); + String javaTemplateBuilder = TemplateCode.process(tree, methodDecl.getParameters(), true); return TemplateCode.indent(javaTemplateBuilder, 16); } From dfe8a22c642cd795488ff43e8f2141f56f15ff43 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 2 Jan 2024 22:33:33 +0100 Subject: [PATCH 06/22] Change input to ParameterReuseRecipe --- .../java/template/TemplateProcessorTest.java | 2 +- ...erReuse.java => ParameterReuseRecipe.java} | 24 +++++++------------ 2 files changed, 10 insertions(+), 16 deletions(-) rename src/test/resources/template/{ParameterReuse.java => ParameterReuseRecipe.java} (56%) diff --git a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java index 23c13edf..1a65076f 100644 --- a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java @@ -47,7 +47,7 @@ void qualification(String qualifier) { @Test void parameterReuse() { - Compilation compilation = compile("template/ParameterReuse.java"); + Compilation compilation = compile("template/ParameterReuseRecipe.java"); assertThat(compilation).succeeded(); assertThat(compilation) .generatedSourceFile("foo/ParameterReuseRecipe$1_before") diff --git a/src/test/resources/template/ParameterReuse.java b/src/test/resources/template/ParameterReuseRecipe.java similarity index 56% rename from src/test/resources/template/ParameterReuse.java rename to src/test/resources/template/ParameterReuseRecipe.java index ed1058f8..4b9deb59 100644 --- a/src/test/resources/template/ParameterReuse.java +++ b/src/test/resources/template/ParameterReuseRecipe.java @@ -15,20 +15,14 @@ */ package foo; -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.openrewrite.java.template.Matches; -import org.openrewrite.java.template.MethodInvocationMatcher; -import org.openrewrite.java.template.NotMatches; +import org.openrewrite.ExecutionContext; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.JavaTemplate; +import org.openrewrite.java.template.Semantics; -public class ParameterReuse { - @BeforeTemplate - boolean before(String s) { - return s.equals(s); - } - - @AfterTemplate - boolean after() { - return true; - } +public class ParameterReuseRecipe { + JavaIsoVisitor visitor = new JavaIsoVisitor() { + JavaTemplate.Builder before = Semantics.expression(this, "before", (String s) -> s.equals(s)); + JavaTemplate.Builder after = Semantics.expression(this, "after", (String s) -> true); + }; } From 5fb131c75c06bf93da0d64f939779b361cdfb85d Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 2 Jan 2024 23:01:08 +0100 Subject: [PATCH 07/22] Adapt three out of four remaining tests --- .../java/template/TemplateProcessorTest.java | 2 +- .../template/ShouldAddClasspath.java | 78 ------------------- .../template/ShouldAddClasspathRecipes.java | 63 +++++++++++++++ 3 files changed, 64 insertions(+), 79 deletions(-) delete mode 100644 src/test/resources/template/ShouldAddClasspath.java create mode 100644 src/test/resources/template/ShouldAddClasspathRecipes.java diff --git a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java index 1a65076f..03609623 100644 --- a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java @@ -35,7 +35,7 @@ class TemplateProcessorTest { }) void qualification(String qualifier) { // As per https://github.com/google/compile-testing/blob/v0.21.0/src/main/java/com/google/testing/compile/package-info.java#L53-L55 - Compilation compilation = compile("template/ShouldAddClasspath.java"); + Compilation compilation = compile("template/ShouldAddClasspathRecipes.java"); assertThat(compilation).succeeded(); assertThat(compilation) .generatedSourceFile("foo/ShouldAddClasspathRecipes$" + qualifier + "Recipe$1_before") diff --git a/src/test/resources/template/ShouldAddClasspath.java b/src/test/resources/template/ShouldAddClasspath.java deleted file mode 100644 index bb06e944..00000000 --- a/src/test/resources/template/ShouldAddClasspath.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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 foo; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.openrewrite.java.template.Primitive; -import org.slf4j.LoggerFactory; - -import java.util.regex.Pattern; - -import static java.util.regex.Pattern.DOTALL; -import static org.slf4j.LoggerFactory.getLogger; - -public class ShouldAddClasspath { - - class Unqualified { - @BeforeTemplate - void before(String message) { - System.out.println(message); - } - - @AfterTemplate - void after(String message) { - getLogger(message); - } - } - - class FullyQualified { - @BeforeTemplate - void before(String message) { - System.out.println(message); - } - - @AfterTemplate - void after(String message) { - org.slf4j.LoggerFactory.getLogger(message); - } - } - - class FullyQualifiedField { - @BeforeTemplate - void before(String message) { - Pattern.compile(message, DOTALL); - } - - @AfterTemplate - void after(String message) { - System.out.println(message); - } - } - - class Primitive { - @BeforeTemplate - void before(@org.openrewrite.java.template.Primitive int i) { - System.out.println(i); - } - - @AfterTemplate - void after(@org.openrewrite.java.template.Primitive int i) { - System.out.print(i); - } - } - -} \ No newline at end of file diff --git a/src/test/resources/template/ShouldAddClasspathRecipes.java b/src/test/resources/template/ShouldAddClasspathRecipes.java new file mode 100644 index 00000000..e1e0734f --- /dev/null +++ b/src/test/resources/template/ShouldAddClasspathRecipes.java @@ -0,0 +1,63 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * 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 + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * 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 foo; + +import com.google.errorprone.refaster.annotation.AfterTemplate; +import com.google.errorprone.refaster.annotation.BeforeTemplate; +import org.openrewrite.ExecutionContext; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.JavaTemplate; +import org.openrewrite.java.template.Semantics; + +import static java.util.regex.Pattern.DOTALL; +import static org.slf4j.LoggerFactory.getLogger; + +public class ShouldAddClasspathRecipes { + + class UnqualifiedRecipe { + JavaIsoVisitor visitor = new JavaIsoVisitor() { + JavaTemplate.Builder before = Semantics.statement(this, "before", (String message) -> System.out.println(message)); + JavaTemplate.Builder after = Semantics.statement(this, "after", (String message) -> getLogger(message)); + }; + } + + class FullyQualifiedRecipe { + JavaIsoVisitor visitor = new JavaIsoVisitor() { + JavaTemplate.Builder before = Semantics.statement(this, "before", (String message) -> System.out.println(message)); + JavaTemplate.Builder after = Semantics.statement(this, "after", (String message) -> org.slf4j.LoggerFactory.getLogger(message)); + }; + } + + class FullyQualifiedFieldRecipe { + JavaIsoVisitor visitor = new JavaIsoVisitor() { + JavaTemplate.Builder before = Semantics.statement(this, "before", (String message) -> java.util.regex.Pattern.compile(message, DOTALL)); + JavaTemplate.Builder after = Semantics.statement(this, "after", (String message) -> System.out.println(message)); + }; + } + + class Primitive { + @BeforeTemplate + void before(@org.openrewrite.java.template.Primitive int i) { + System.out.println(i); + } + + @AfterTemplate + void after(@org.openrewrite.java.template.Primitive int i) { + System.out.print(i); + } + } + +} \ No newline at end of file From 9bf620ba7ce8a779e6efd64c2d621ca5bd6c8aec Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 2 Jan 2024 23:06:03 +0100 Subject: [PATCH 08/22] Fix remaining test --- .../template/ShouldAddClasspathRecipes.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/test/resources/template/ShouldAddClasspathRecipes.java b/src/test/resources/template/ShouldAddClasspathRecipes.java index e1e0734f..327f585f 100644 --- a/src/test/resources/template/ShouldAddClasspathRecipes.java +++ b/src/test/resources/template/ShouldAddClasspathRecipes.java @@ -48,16 +48,11 @@ class FullyQualifiedFieldRecipe { }; } - class Primitive { - @BeforeTemplate - void before(@org.openrewrite.java.template.Primitive int i) { - System.out.println(i); - } - - @AfterTemplate - void after(@org.openrewrite.java.template.Primitive int i) { - System.out.print(i); - } + class PrimitiveRecipe { + JavaIsoVisitor visitor = new JavaIsoVisitor() { + JavaTemplate.Builder before = Semantics.statement(this, "before", (@org.openrewrite.java.template.Primitive Integer i) -> System.out.println(i)); + JavaTemplate.Builder after = Semantics.statement(this, "after", (@org.openrewrite.java.template.Primitive Integer i) -> System.out.print(i)); + }; } -} \ No newline at end of file +} From 01cef4bbc77830c5ce84316db30f4f1dc79ac1b4 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 2 Jan 2024 23:09:37 +0100 Subject: [PATCH 09/22] Update new test too --- .../refaster/SimplifyTernaryRecipes.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/test/resources/refaster/SimplifyTernaryRecipes.java b/src/test/resources/refaster/SimplifyTernaryRecipes.java index 3468514d..cd9517d0 100644 --- a/src/test/resources/refaster/SimplifyTernaryRecipes.java +++ b/src/test/resources/refaster/SimplifyTernaryRecipes.java @@ -21,6 +21,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -87,8 +88,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (@Primitive Boolean expr) -> expr ? true : false).build(); - final JavaTemplate after = Semantics.expression(this, "after", (@Primitive Boolean expr) -> expr).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.SimplifyTernary.SimplifyTernaryTrueFalse.before.expr ? true : false") + .build(); + final JavaTemplate after = JavaTemplate + .builder("foo.SimplifyTernary.SimplifyTernaryTrueFalse.after.expr") + .build(); @Override public J visitExpression(Expression elem, ExecutionContext ctx) { @@ -134,8 +139,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (@Primitive Boolean expr) -> expr ? false : true).build(); - final JavaTemplate after = Semantics.expression(this, "after", (@Primitive Boolean expr) -> !(expr)).build(); + final JavaTemplate before = JavaTemplate + .builder("foo.SimplifyTernary.SimplifyTernaryFalseTrue.before.expr ? false : true") + .build(); + final JavaTemplate after = JavaTemplate + .builder("!(foo.SimplifyTernary.SimplifyTernaryFalseTrue.after.expr)") + .build(); @Override public J visitExpression(Expression elem, ExecutionContext ctx) { From a21d6dbfd86c957a6eafdf471042af02d569e707 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sat, 6 Jan 2024 13:39:02 +0100 Subject: [PATCH 10/22] Add TODO --- .../openrewrite/java/template/internal/JavacResolution.java | 3 ++- .../java/template/processor/RefasterTemplateProcessor.java | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java index b09451a5..53254fe8 100644 --- a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java +++ b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java @@ -30,6 +30,7 @@ import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; +import org.openrewrite.internal.lang.Nullable; import javax.tools.JavaFileObject; import java.lang.reflect.Field; @@ -50,7 +51,7 @@ public JavacResolution(Context context) { this.log = Log.instance(context); } - public Map resolveAll(Context context, JCCompilationUnit cu, List trees) { + public @Nullable Map resolveAll(Context context, JCCompilationUnit cu, List trees) { AtomicReference> resolved = new AtomicReference<>(); new TreeScanner() { diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index 992db04e..6d9c37c0 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -780,6 +780,10 @@ private boolean resolve(Context context, JCCompilationUnit cu) { processingEnv.getMessager().printMessage(Kind.WARNING, "Had trouble type attributing the template."); return false; } + + // TODO Separately resolve template parameters here too? + + return true; } } From 676a18868663a040699b0ee9e7dd68eaf5bcc3d4 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Fri, 2 Feb 2024 21:50:42 +0100 Subject: [PATCH 11/22] Quick stash --- .../processor/RefasterTemplateProcessor.java | 2 +- .../RefasterTemplateProcessorTest.java | 8 +++- .../java/template/TemplateProcessorTest.java | 45 +++++++++++++++++++ .../resources/refaster/UseStringIsEmpty.java | 2 +- .../refaster/UseStringIsEmptyRecipe.java | 4 +- 5 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index 6d9c37c0..c785d37a 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -768,8 +768,8 @@ public void afterTemplate(JCTree.JCMethodDecl method) { } private boolean resolve(Context context, JCCompilationUnit cu) { + JavacResolution res = new JavacResolution(context); try { - JavacResolution res = new JavacResolution(context); beforeTemplates.replaceAll(key -> { Map resolved = res.resolveAll(context, cu, singletonList(key)); return (JCTree.JCMethodDecl) resolved.get(key); diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index 1c7b63f6..e695ce05 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -25,6 +25,7 @@ import org.openrewrite.java.template.processor.RefasterTemplateProcessor; import org.openrewrite.java.template.processor.TypeAwareProcessor; +import javax.tools.JavaFileObject; import java.io.File; import java.net.URL; import java.util.Arrays; @@ -99,6 +100,11 @@ private static Compilation compile(String resourceName) { static Compilation compile(String resourceName, TypeAwareProcessor processor) { // As per https://github.com/google/compile-testing/blob/v0.21.0/src/main/java/com/google/testing/compile/package-info.java#L53-L55 + JavaFileObject javaFileObject = JavaFileObjects.forResource(resourceName); + return compile(javaFileObject, processor); + } + + static Compilation compile(JavaFileObject javaFileObject, TypeAwareProcessor processor) { return javac() .withProcessors(processor) .withClasspath(Arrays.asList( @@ -110,7 +116,7 @@ static Compilation compile(String resourceName, TypeAwareProcessor processor) { fileForClass(org.slf4j.Logger.class), fileForClass(Primitive.class) )) - .compile(JavaFileObjects.forResource(resourceName)); + .compile(javaFileObject); } // As per https://github.com/google/auto/blob/auto-value-1.10.2/factory/src/test/java/com/google/auto/factory/processor/AutoFactoryProcessorTest.java#L99 diff --git a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java index 3139cd3d..b6d14a14 100644 --- a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java @@ -22,6 +22,8 @@ import org.junit.jupiter.params.provider.ValueSource; import org.openrewrite.java.template.processor.TemplateProcessor; +import javax.tools.JavaFileObject; + import static com.google.testing.compile.CompilationSubject.assertThat; import static org.openrewrite.java.template.RefasterTemplateProcessorTest.compile; @@ -95,4 +97,47 @@ void unnamedPackage() { .generatedSourceFile("UnnamedPackage$1_message") .hasSourceEquivalentTo(JavaFileObjects.forResource("template/UnnamedPackage$1_message.java")); } + + @Test + void inline() { + JavaFileObject javaFileObject = JavaFileObjects.forSourceString("foo.SomeRecipe", + //language=java + "package foo;" + + "import org.openrewrite.ExecutionContext;" + + "import org.openrewrite.java.JavaVisitor;" + + "import org.openrewrite.java.JavaTemplate;" + + "import org.openrewrite.java.template.Semantics;" + + "public class SomeRecipe {" + + " JavaVisitor visitor = new JavaVisitor() {" + + " JavaTemplate.Builder before = Semantics.statement(this, \"before\", (String s) -> System.out.println(s));" + + " };" + + "}"); + Compilation compilation = compile(javaFileObject, new TemplateProcessor()); + assertThat(compilation).succeeded(); + assertThat(compilation) + .generatedSourceFile("foo/SomeRecipe$1_before") + .hasSourceEquivalentTo(JavaFileObjects.forSourceString("/SOURCE_OUTPUT/foo/SomeRecipe$1_before", + "package foo;\n" + + "import org.openrewrite.java.*;\n" + + "\n" + + "/**\n" + + " * OpenRewrite `before` template created for {@code foo.SomeRecipe$1}.\n" + + " */\n" + + "@SuppressWarnings(\"all\")\n" + + "public class SomeRecipe$1_before {\n" + + " /**\n" + + " * Instantiates a new instance.\n" + + " */\n" + + " public SomeRecipe$1_before() {}\n" + + "\n" + + " /**\n" + + " * Get the {@code JavaTemplate.Builder} to match or replace.\n" + + " * @return the JavaTemplate builder.\n" + + " */\n" + + " public static JavaTemplate.Builder getTemplate() {\n" + + " return JavaTemplate\n" + + " .builder(\"System.out.println(#{s:any(java.lang.String)})\");\n" + + " }\n" + + "}")); + } } diff --git a/src/test/resources/refaster/UseStringIsEmpty.java b/src/test/resources/refaster/UseStringIsEmpty.java index e71be4a0..3b5ceb7a 100644 --- a/src/test/resources/refaster/UseStringIsEmpty.java +++ b/src/test/resources/refaster/UseStringIsEmpty.java @@ -36,6 +36,6 @@ boolean before(String s) { @AfterTemplate boolean after(String s) { - return !s.isEmpty(); + return !(s.isEmpty()); } } diff --git a/src/test/resources/refaster/UseStringIsEmptyRecipe.java b/src/test/resources/refaster/UseStringIsEmptyRecipe.java index 28981b5d..3f17be10 100644 --- a/src/test/resources/refaster/UseStringIsEmptyRecipe.java +++ b/src/test/resources/refaster/UseStringIsEmptyRecipe.java @@ -61,10 +61,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.UseStringIsEmpty.before.s.length() > 0") + .builder("#{s:any(java.lang.String)}).length() > 0") .build(); final JavaTemplate after = JavaTemplate - .builder("!foo.UseStringIsEmpty.after.s.isEmpty()") + .builder("!(#{s:any(java.lang.String)})).isEmpty()") .build(); @Override From 7cb1bbd5ffe64af523623406a51f82ec0912f24a Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 11 Feb 2024 20:54:33 +0100 Subject: [PATCH 12/22] Fix compilation issue --- .../java/template/RefasterTemplateProcessorTest.java | 6 +++--- .../java/template/TemplateProcessorTest.java | 12 +++++------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index 842e6b75..a33f6ec3 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -110,14 +110,14 @@ private static Compilation compileResource(String resourceName) { static Compilation compileResource(String resourceName, TypeAwareProcessor processor) { // As per https://github.com/google/compile-testing/blob/v0.21.0/src/main/java/com/google/testing/compile/package-info.java#L53-L55 - return compileResource(JavaFileObjects.forResource(resourceName), processor); + return compile(JavaFileObjects.forResource(resourceName), processor); } static Compilation compileSource(String fqn, @Language("java") String source, TypeAwareProcessor processor) { - return compileResource(JavaFileObjects.forSourceString(fqn, source), processor); + return compile(JavaFileObjects.forSourceString(fqn, source), processor); } - static Compilation compileResource(JavaFileObject javaFileObject, TypeAwareProcessor processor) { + static Compilation compile(JavaFileObject javaFileObject, TypeAwareProcessor processor) { return javac() .withProcessors(processor) .withClasspath(Arrays.asList( diff --git a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java index 5b0cfcbd..62872e1c 100644 --- a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java @@ -22,10 +22,8 @@ import org.junit.jupiter.params.provider.ValueSource; import org.openrewrite.java.template.processor.TemplateProcessor; -import javax.tools.JavaFileObject; - import static com.google.testing.compile.CompilationSubject.assertThat; -import static org.openrewrite.java.template.RefasterTemplateProcessorTest.compileResource; +import static org.openrewrite.java.template.RefasterTemplateProcessorTest.*; class TemplateProcessorTest { @ParameterizedTest @@ -100,8 +98,7 @@ void unnamedPackage() { @Test void inline() { - JavaFileObject javaFileObject = JavaFileObjects.forSourceString("foo.SomeRecipe", - //language=java + Compilation compilation = compileSource("foo.SomeRecipe", "package foo;" + "import org.openrewrite.ExecutionContext;" + "import org.openrewrite.java.JavaVisitor;" + @@ -111,12 +108,13 @@ void inline() { " JavaVisitor visitor = new JavaVisitor() {" + " JavaTemplate.Builder before = Semantics.statement(this, \"before\", (String s) -> System.out.println(s));" + " };" + - "}"); - Compilation compilation = compile(javaFileObject, new TemplateProcessor()); + "}", + new TemplateProcessor()); assertThat(compilation).succeeded(); assertThat(compilation) .generatedSourceFile("foo/SomeRecipe$1_before") .hasSourceEquivalentTo(JavaFileObjects.forSourceString("/SOURCE_OUTPUT/foo/SomeRecipe$1_before", + //language=java "package foo;\n" + "import org.openrewrite.java.*;\n" + "\n" + From e93e1482059da11fe1f5f91d96f8aa623f107503 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 11 Feb 2024 21:04:49 +0100 Subject: [PATCH 13/22] Add an inline test for RefaterTemplateProcessor as well --- .../RefasterTemplateProcessorTest.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index a33f6ec3..0bab9397 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -104,6 +104,107 @@ void stringIsEmptyPredicate() { assertEquals(0, compilation.generatedSourceFiles().size(), "Not yet supported"); } + @Test + void inline() { + Compilation compilation = compileSource("foo.UseStringIsEmpty", + "package foo;\n" + + "\n" + + "import com.google.errorprone.refaster.annotation.AfterTemplate;\n" + + "import com.google.errorprone.refaster.annotation.BeforeTemplate;\n" + + "\n" + + "public class UseStringIsEmpty {\n" + + " @BeforeTemplate\n" + + " boolean before(String s) {\n" + + " return s.length() > 0;\n" + + " }\n" + + "\n" + + " @AfterTemplate\n" + + " boolean after(String s) {\n" + + " return !(s.isEmpty());\n" + + " }\n" + + "}\n"); + assertThat(compilation).succeeded(); + assertThat(compilation) + .generatedSourceFile("foo/UseStringIsEmptyRecipe") + .hasSourceEquivalentTo(JavaFileObjects.forSourceString("/SOURCE_OUTPUT/foo/UseStringIsEmptyRecipe", + //language=java + "package foo;\n" + + "\n" + + "import org.openrewrite.ExecutionContext;\n" + + "import org.openrewrite.Preconditions;\n" + + "import org.openrewrite.Recipe;\n" + + "import org.openrewrite.TreeVisitor;\n" + + "import org.openrewrite.internal.lang.NonNullApi;\n" + + "import org.openrewrite.java.JavaParser;\n" + + "import org.openrewrite.java.JavaTemplate;\n" + + "import org.openrewrite.java.JavaVisitor;\n" + + "import org.openrewrite.java.search.*;\n" + + "import org.openrewrite.java.template.Primitive;\n" + + "import org.openrewrite.java.template.Semantics;\n" + + "import org.openrewrite.java.template.function.*;\n" + + "import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor;\n" + + "import org.openrewrite.java.tree.*;\n" + + "\n" + + "import java.util.*;\n" + + "\n" + + "import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*;\n" + + "\n" + + "\n" + + "/**\n" + + " * OpenRewrite recipe created for Refaster template {@code UseStringIsEmpty}.\n" + + " */\n" + + "@SuppressWarnings(\"all\")\n" + + "@NonNullApi\n" + + "public class UseStringIsEmptyRecipe extends Recipe {\n" + + "\n" + + " /**\n" + + " * Instantiates a new instance.\n" + + " */\n" + + " public UseStringIsEmptyRecipe() {}\n" + + "\n" + + " @Override\n" + + " public String getDisplayName() {\n" + + " return \"Refaster template `UseStringIsEmpty`\";\n" + + " }\n" + + "\n" + + " @Override\n" + + " public String getDescription() {\n" + + " return \"Recipe created for the following Refaster template:\\n```java\\npublic class UseStringIsEmpty {\\n \\n @BeforeTemplate()\\n boolean before(String s) {\\n return s.length() > 0;\\n }\\n \\n @AfterTemplate()\\n boolean after(String s) {\\n return !(s.isEmpty());\\n }\\n}\\n```\\n.\";\n" + + " }\n" + + "\n" + + " @Override\n" + + " public TreeVisitor getVisitor() {\n" + + " JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() {\n" + + " final JavaTemplate before = JavaTemplate\n" + + " .builder(\"#{s:any(java.lang.String)}.length() > 0\")\n" + + " .build();\n" + + " final JavaTemplate after = JavaTemplate\n" + + " .builder(\"!(#{s:any(java.lang.String)}.isEmpty())\")\n" + + " .build();\n" + + "\n" + + " @Override\n" + + " public J visitBinary(J.Binary elem, ExecutionContext ctx) {\n" + + " JavaTemplate.Matcher matcher;\n" + + " if ((matcher = before.matcher(getCursor())).find()) {\n" + + " return embed(\n" + + " after.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0)),\n" + + " getCursor(),\n" + + " ctx,\n" + + " REMOVE_PARENS, SHORTEN_NAMES, SIMPLIFY_BOOLEANS\n" + + " );\n" + + " }\n" + + " return super.visitBinary(elem, ctx);\n" + + " }\n" + + "\n" + + " };\n" + + " return Preconditions.check(\n" + + " new UsesMethod<>(\"java.lang.String length(..)\"),\n" + + " javaVisitor\n" + + " );\n" + + " }\n" + + "}")); + } + private static Compilation compileResource(String resourceName) { return compileResource(resourceName, new RefasterTemplateProcessor()); } @@ -113,6 +214,10 @@ static Compilation compileResource(String resourceName, TypeAwareProcessor proce return compile(JavaFileObjects.forResource(resourceName), processor); } + static Compilation compileSource(String fqn, @Language("java") String source) { + return compile(JavaFileObjects.forSourceString(fqn, source), new RefasterTemplateProcessor()); + } + static Compilation compileSource(String fqn, @Language("java") String source, TypeAwareProcessor processor) { return compile(JavaFileObjects.forSourceString(fqn, source), processor); } From f7c954a3e13eaf3c5aae312650da3ed2e6ae6519 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 20 Feb 2024 22:17:06 +0100 Subject: [PATCH 14/22] Add FIXME --- .../openrewrite/java/template/internal/TemplateCode.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java index 4165fd4f..21b3800f 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java +++ b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java @@ -90,8 +90,10 @@ public TemplateCodePrinter(Writer writer, List declaredPa public void visitIdent(JCIdent jcIdent) { try { Symbol sym = jcIdent.sym; - Optional param = declaredParameters.stream().filter(p -> p.sym == sym).findFirst(); - if (param.isPresent()) { + Optional param = declaredParameters.stream() + .filter(p -> p.sym == sym) + .findFirst(); + if (param.isPresent()) { // FIXME This ends up empty as the symbols are different instances & type = null print("#{" + sym.name); if (seenParameters.add(param.get())) { String type = param.get().type.toString(); From a7ac9092340a153d5644109600419f084af3630b Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 17:38:34 +0100 Subject: [PATCH 15/22] Add more analysis of what's going wrong --- .../java/template/internal/JavacResolution.java | 2 ++ .../java/template/internal/TreeMirrorMaker.java | 2 +- .../processor/RefasterTemplateProcessor.java | 14 ++++---------- .../template/RefasterTemplateProcessorTest.java | 4 ++-- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java index 53254fe8..a00beff8 100644 --- a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java +++ b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java @@ -66,6 +66,7 @@ public void scan(JCTree tree) { for (JCTree p : cursor) { p.accept(finder); } + // FIXME somehow the type for the method parameters ends up null here JCTree copy = mirrorMaker.copy(finder.copyAt()); JavaFileObject oldFileObject = log.useSource(cu.getSourceFile()); try { @@ -204,6 +205,7 @@ public void visitMethodDef(JCMethodDecl tree) { copyAt = tree; } + @Override public void visitVarDef(JCVariableDecl tree) { if (copyAt != null) { return; diff --git a/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java b/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java index 6135b3b9..d9223155 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java +++ b/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java @@ -113,7 +113,7 @@ public JCTree visitVariable(VariableTree node, Void p) { if (copy.sym != null) { copy.type = original.type; } - if (copy.type != null) { + if (copy.type != null) { // FIXME Copy of method declaration argument also lacks type boolean wipeSymAndType = copy.type.isErroneous(); if (!wipeSymAndType) { TypeTag typeTag = TypeTag.typeTag(copy.type); diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index aaebd743..c5a2f49e 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -786,20 +786,14 @@ public void afterTemplate(JCTree.JCMethodDecl method) { private boolean resolve(Context context, JCCompilationUnit cu) { JavacResolution res = new JavacResolution(context); try { - beforeTemplates.replaceAll(key -> { - Map resolved = res.resolveAll(context, cu, singletonList(key)); - return (JCTree.JCMethodDecl) resolved.get(key); - }); - Map resolved = res.resolveAll(context, cu, singletonList(afterTemplate)); - afterTemplate = (JCTree.JCMethodDecl) resolved.get(afterTemplate); + Map resolvedBefore = res.resolveAll(context, cu, beforeTemplates); + beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) resolvedBefore.get(key)); + Map resolvedAfter = res.resolveAll(context, cu, singletonList(afterTemplate)); + afterTemplate = (JCTree.JCMethodDecl) resolvedAfter.get(afterTemplate); } catch (Throwable t) { processingEnv.getMessager().printMessage(Kind.WARNING, "Had trouble type attributing the template."); return false; } - - // TODO Separately resolve template parameters here too? - - return true; } } diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index 0bab9397..373fb211 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -112,7 +112,7 @@ void inline() { "import com.google.errorprone.refaster.annotation.AfterTemplate;\n" + "import com.google.errorprone.refaster.annotation.BeforeTemplate;\n" + "\n" + - "public class UseStringIsEmpty {\n" + + "class UseStringIsEmpty {\n" + " @BeforeTemplate\n" + " boolean before(String s) {\n" + " return s.length() > 0;\n" + @@ -169,7 +169,7 @@ void inline() { "\n" + " @Override\n" + " public String getDescription() {\n" + - " return \"Recipe created for the following Refaster template:\\n```java\\npublic class UseStringIsEmpty {\\n \\n @BeforeTemplate()\\n boolean before(String s) {\\n return s.length() > 0;\\n }\\n \\n @AfterTemplate()\\n boolean after(String s) {\\n return !(s.isEmpty());\\n }\\n}\\n```\\n.\";\n" + + " return \"Recipe created for the following Refaster template:\\n```java\\nclass UseStringIsEmpty {\\n \\n @BeforeTemplate()\\n boolean before(String s) {\\n return s.length() > 0;\\n }\\n \\n @AfterTemplate()\\n boolean after(String s) {\\n return !(s.isEmpty());\\n }\\n}\\n```\\n.\";\n" + " }\n" + "\n" + " @Override\n" + From 71603fc18306a102b978727b9a731c0e9a953486 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 20:53:46 +0100 Subject: [PATCH 16/22] First working version --- .../template/internal/JavacResolution.java | 1 - .../java/template/internal/TemplateCode.java | 7 +++-- .../template/internal/TreeMirrorMaker.java | 2 +- .../processor/RefasterTemplateProcessor.java | 31 +++++++++++++------ 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java index a00beff8..f47e3b49 100644 --- a/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java +++ b/src/main/java/org/openrewrite/java/template/internal/JavacResolution.java @@ -66,7 +66,6 @@ public void scan(JCTree tree) { for (JCTree p : cursor) { p.accept(finder); } - // FIXME somehow the type for the method parameters ends up null here JCTree copy = mirrorMaker.copy(finder.copyAt()); JavaFileObject oldFileObject = log.useSource(cu.getSourceFile()); try { diff --git a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java index 21b3800f..12e980ff 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java +++ b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java @@ -93,11 +93,12 @@ public void visitIdent(JCIdent jcIdent) { Optional param = declaredParameters.stream() .filter(p -> p.sym == sym) .findFirst(); - if (param.isPresent()) { // FIXME This ends up empty as the symbols are different instances & type = null + if (param.isPresent()) { print("#{" + sym.name); if (seenParameters.add(param.get())) { - String type = param.get().type.toString(); - if (param.get().getModifiers().getAnnotations().stream().anyMatch(a -> a.attribute.type.tsym.getQualifiedName().toString().equals(PRIMITIVE_ANNOTATION))) { + String type = param.get().sym.type.toString(); + if (param.get().getModifiers().getAnnotations().stream() + .anyMatch(a -> a.attribute.type.tsym.getQualifiedName().toString().equals(PRIMITIVE_ANNOTATION))) { type = getUnboxedPrimitive(type); } print(":any(" + type + ")"); diff --git a/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java b/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java index d9223155..6135b3b9 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java +++ b/src/main/java/org/openrewrite/java/template/internal/TreeMirrorMaker.java @@ -113,7 +113,7 @@ public JCTree visitVariable(VariableTree node, Void p) { if (copy.sym != null) { copy.type = original.type; } - if (copy.type != null) { // FIXME Copy of method declaration argument also lacks type + if (copy.type != null) { boolean wipeSymAndType = copy.type.isErroneous(); if (!wipeSymAndType) { TypeTag typeTag = TypeTag.typeTag(copy.type); diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index c5a2f49e..3e442c51 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -211,17 +211,16 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { recipe.append(" public TreeVisitor getVisitor() {\n"); recipe.append(" JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() {\n"); for (Map.Entry entry : beforeTemplates.entrySet()) { - JCTree.JCMethodDecl methodDecl = entry.getValue(); recipe.append(" final JavaTemplate ") .append(entry.getKey()) .append(" = ") - .append(toJavaTemplateBuilder(methodDecl)) + .append(toJavaTemplateBuilder(entry.getValue(), descriptor.resolvedParameters)) .append("\n .build();\n"); } recipe.append(" final JavaTemplate ") .append(after) .append(" = ") - .append(toJavaTemplateBuilder(descriptor.afterTemplate)) + .append(toJavaTemplateBuilder(descriptor.afterTemplate, descriptor.resolvedParameters)) .append("\n .build();\n"); recipe.append("\n"); @@ -395,12 +394,19 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { } } - private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl) { + private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl, Map resolvedParameters) { JCTree tree = methodDecl.getBody().getStatements().get(0); if (tree instanceof JCTree.JCReturn) { tree = ((JCTree.JCReturn) tree).getExpression(); } - String javaTemplateBuilder = TemplateCode.process(tree, methodDecl.getParameters(), true); + + List parameters = methodDecl.getParameters(); + List mapped = parameters.stream() + .map(resolvedParameters::get) + .map(JCTree.JCVariableDecl.class::cast) + .collect(Collectors.toList()); + + String javaTemplateBuilder = TemplateCode.process(tree, mapped, true); return TemplateCode.indent(javaTemplateBuilder, 16); } @@ -682,6 +688,7 @@ class TemplateDescriptor { final JCTree.JCClassDecl classDecl; final List beforeTemplates = new ArrayList<>(); JCTree.JCMethodDecl afterTemplate; + Map resolvedParameters = new IdentityHashMap<>(); public TemplateDescriptor(JCTree.JCClassDecl classDecl) { this.classDecl = classDecl; @@ -786,10 +793,16 @@ public void afterTemplate(JCTree.JCMethodDecl method) { private boolean resolve(Context context, JCCompilationUnit cu) { JavacResolution res = new JavacResolution(context); try { - Map resolvedBefore = res.resolveAll(context, cu, beforeTemplates); - beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) resolvedBefore.get(key)); - Map resolvedAfter = res.resolveAll(context, cu, singletonList(afterTemplate)); - afterTemplate = (JCTree.JCMethodDecl) resolvedAfter.get(afterTemplate); + // Resolve parameters + res.resolveAll(context, cu, afterTemplate.getParameters()) + .forEach((k, v) -> resolvedParameters.put(v, k)); + beforeTemplates + .forEach(bt -> res.resolveAll(context, cu, bt.getParameters()) + .forEach((k, v) -> resolvedParameters.put(v, k))); + + // Resolve templates + beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) res.resolveAll(context, cu, singletonList(key)).get(key)); + afterTemplate = (JCTree.JCMethodDecl) res.resolveAll(context, cu, singletonList(afterTemplate)).get(afterTemplate); } catch (Throwable t) { processingEnv.getMessager().printMessage(Kind.WARNING, "Had trouble type attributing the template."); return false; From 6f7b6cb2b16bb0893ebbac14a401fc0a20581ef8 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:00:21 +0100 Subject: [PATCH 17/22] Update reference outputs --- src/test/resources/refaster/ArraysRecipe.java | 6 +++--- .../resources/refaster/EscapesRecipes.java | 11 +++++----- .../resources/refaster/GenericsRecipes.java | 9 +++++++-- .../resources/refaster/MatchingRecipes.java | 14 +++++++++---- .../refaster/MethodThrowsRecipe.java | 6 +++--- .../refaster/MultipleDereferencesRecipes.java | 12 +++++------ .../refaster/NestedPreconditionsRecipe.java | 8 ++++---- .../refaster/ParameterReuseRecipe.java | 6 +++--- .../refaster/ShouldAddImportsRecipes.java | 20 +++++++++---------- .../ShouldSupportNestedClassesRecipes.java | 10 +++++----- .../refaster/SimplifyBooleansRecipe.java | 6 +++--- .../refaster/SimplifyTernaryRecipes.java | 8 ++++---- .../refaster/UseStringIsEmptyRecipe.java | 8 ++++---- 13 files changed, 67 insertions(+), 57 deletions(-) diff --git a/src/test/resources/refaster/ArraysRecipe.java b/src/test/resources/refaster/ArraysRecipe.java index 5e039170..eb553c69 100644 --- a/src/test/resources/refaster/ArraysRecipe.java +++ b/src/test/resources/refaster/ArraysRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,10 +61,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("String.join(\", \", foo.Arrays.before.strings)") + .builder("String.join(\", \", #{strings:any(java.lang.String[])})") .build(); final JavaTemplate after = JavaTemplate - .builder("String.join(\":\", foo.Arrays.after.strings)") + .builder("String.join(\":\", #{strings:any(java.lang.String[])})") .build(); @Override diff --git a/src/test/resources/refaster/EscapesRecipes.java b/src/test/resources/refaster/EscapesRecipes.java index 0056ee34..826a5628 100644 --- a/src/test/resources/refaster/EscapesRecipes.java +++ b/src/test/resources/refaster/EscapesRecipes.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package foo; import org.openrewrite.ExecutionContext; @@ -92,11 +91,11 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("String.format(\"\\\"%s\\\"\", com.sun.tools.javac.util.Convert.quote(foo.Escapes.ConstantsFormat.before.value))") + .builder("String.format(\"\\\"%s\\\"\", com.sun.tools.javac.util.Convert.quote(#{value:any(java.lang.String)}))") .javaParser(JavaParser.fromJavaVersion().classpath("tools")) .build(); final JavaTemplate after = JavaTemplate - .builder("com.sun.tools.javac.util.Constants.format(foo.Escapes.ConstantsFormat.after.value)") + .builder("com.sun.tools.javac.util.Constants.format(#{value:any(java.lang.String)})") .javaParser(JavaParser.fromJavaVersion().classpath("tools")) .build(); @@ -153,10 +152,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.Escapes.Split.before.s.split(\"[^\\\\S]+\")") + .builder("#{s:any(java.lang.String)}.split(\"[^\\\\S]+\")") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.Escapes.Split.after.s.split(\"\\\\s+\")") + .builder("#{s:any(java.lang.String)}.split(\"\\\\s+\")") .build(); @Override diff --git a/src/test/resources/refaster/GenericsRecipes.java b/src/test/resources/refaster/GenericsRecipes.java index cd002e37..b6d9df93 100644 --- a/src/test/resources/refaster/GenericsRecipes.java +++ b/src/test/resources/refaster/GenericsRecipes.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -87,8 +88,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (java.util.List l) -> l.iterator().next()).build(); - final JavaTemplate after = Semantics.expression(this, "after", (java.util.List l) -> l.get(0)).build(); + final JavaTemplate before = JavaTemplate + .builder("#{l:any(java.util.List)}.iterator().next()") + .build(); + final JavaTemplate after = JavaTemplate + .builder("#{l:any(java.util.List)}.get(0)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/MatchingRecipes.java b/src/test/resources/refaster/MatchingRecipes.java index 6441d4c6..8eeb003d 100644 --- a/src/test/resources/refaster/MatchingRecipes.java +++ b/src/test/resources/refaster/MatchingRecipes.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,9 +97,15 @@ public Set getTags() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", (@Primitive Integer i, String s) -> s.substring(i).isEmpty()).build(); - final JavaTemplate before2 = Semantics.expression(this, "before2", (@Primitive Integer i, String s) -> s.substring(i).isEmpty()).build(); - final JavaTemplate after = Semantics.expression(this, "after", (@Primitive Integer i, String s) -> (s != null && s.length() == 0)).build(); + final JavaTemplate before = JavaTemplate + .builder("#{s:any(java.lang.String)}.substring(#{i:any(int)}).isEmpty()") + .build(); + final JavaTemplate before2 = JavaTemplate + .builder("#{s:any(java.lang.String)}.substring(#{i:any(int)}).isEmpty()") + .build(); + final JavaTemplate after = JavaTemplate + .builder("(#{s:any(java.lang.String)} != null && #{s}.length() == 0)") + .build(); @Override public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/MethodThrowsRecipe.java b/src/test/resources/refaster/MethodThrowsRecipe.java index 017ed8f5..724cca0b 100644 --- a/src/test/resources/refaster/MethodThrowsRecipe.java +++ b/src/test/resources/refaster/MethodThrowsRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,10 +64,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("java.nio.file.Files.readAllLines(foo.MethodThrows.before.path, java.nio.charset.StandardCharsets.UTF_8)") + .builder("java.nio.file.Files.readAllLines(#{path:any(java.nio.file.Path)}, java.nio.charset.StandardCharsets.UTF_8)") .build(); final JavaTemplate after = JavaTemplate - .builder("java.nio.file.Files.readAllLines(foo.MethodThrows.after.path)") + .builder("java.nio.file.Files.readAllLines(#{path:any(java.nio.file.Path)})") .build(); @Override diff --git a/src/test/resources/refaster/MultipleDereferencesRecipes.java b/src/test/resources/refaster/MultipleDereferencesRecipes.java index eaf45e99..326efa48 100644 --- a/src/test/resources/refaster/MultipleDereferencesRecipes.java +++ b/src/test/resources/refaster/MultipleDereferencesRecipes.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,10 +92,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("java.nio.file.Files.delete(foo.MultipleDereferences.VoidType.before.p)") + .builder("java.nio.file.Files.delete(#{p:any(java.nio.file.Path)})") .build(); final JavaTemplate after = JavaTemplate - .builder("java.nio.file.Files.delete(foo.MultipleDereferences.VoidType.after.p)") + .builder("java.nio.file.Files.delete(#{p:any(java.nio.file.Path)})") .build(); @Override @@ -150,10 +150,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.MultipleDereferences.StringIsEmpty.before.s.isEmpty()") + .builder("#{s:any(java.lang.String)}.isEmpty()") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.MultipleDereferences.StringIsEmpty.after.s != null && foo.MultipleDereferences.StringIsEmpty.after.s.length() == 0") + .builder("#{s:any(java.lang.String)} != null && #{s}.length() == 0") .build(); @Override @@ -204,7 +204,7 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.MultipleDereferences.EqualsItself.before.o == foo.MultipleDereferences.EqualsItself.before.o") + .builder("#{o:any(java.lang.Object)} == #{o}") .build(); final JavaTemplate after = JavaTemplate .builder("true") diff --git a/src/test/resources/refaster/NestedPreconditionsRecipe.java b/src/test/resources/refaster/NestedPreconditionsRecipe.java index bfb32643..17c9bbf7 100644 --- a/src/test/resources/refaster/NestedPreconditionsRecipe.java +++ b/src/test/resources/refaster/NestedPreconditionsRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,13 +65,13 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate hashMap = JavaTemplate - .builder("new java.util.HashMap(foo.NestedPreconditions.hashMap.size)") + .builder("new java.util.HashMap(#{size:any(int)})") .build(); final JavaTemplate linkedHashMap = JavaTemplate - .builder("new java.util.LinkedHashMap(foo.NestedPreconditions.linkedHashMap.size)") + .builder("new java.util.LinkedHashMap(#{size:any(int)})") .build(); final JavaTemplate hashtable = JavaTemplate - .builder("new java.util.Hashtable(foo.NestedPreconditions.hashtable.size)") + .builder("new java.util.Hashtable(#{size:any(int)})") .build(); @Override diff --git a/src/test/resources/refaster/ParameterReuseRecipe.java b/src/test/resources/refaster/ParameterReuseRecipe.java index ca0e1eee..686edeb2 100644 --- a/src/test/resources/refaster/ParameterReuseRecipe.java +++ b/src/test/resources/refaster/ParameterReuseRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,10 +61,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.ParameterReuse.before.s == foo.ParameterReuse.before.s") + .builder("#{s:any(java.lang.String)} == #{s}") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.ParameterReuse.after.s.equals(foo.ParameterReuse.after.s)") + .builder("#{s:any(java.lang.String)}.equals(#{s})") .build(); @Override diff --git a/src/test/resources/refaster/ShouldAddImportsRecipes.java b/src/test/resources/refaster/ShouldAddImportsRecipes.java index 1a5da964..73ce60b9 100644 --- a/src/test/resources/refaster/ShouldAddImportsRecipes.java +++ b/src/test/resources/refaster/ShouldAddImportsRecipes.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,10 +96,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("String.valueOf(foo.ShouldAddImports.StringValueOf.before.s)") + .builder("String.valueOf(#{s:any(java.lang.String)})") .build(); final JavaTemplate after = JavaTemplate - .builder("java.util.Objects.toString(foo.ShouldAddImports.StringValueOf.after.s)") + .builder("java.util.Objects.toString(#{s:any(java.lang.String)})") .build(); @Override @@ -150,13 +150,13 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate equals = JavaTemplate - .builder("java.util.Objects.equals(foo.ShouldAddImports.ObjectsEquals.equals.a, foo.ShouldAddImports.ObjectsEquals.equals.b)") + .builder("java.util.Objects.equals(#{a:any(int)}, #{b:any(int)})") .build(); final JavaTemplate compareZero = JavaTemplate - .builder("Integer.compare(foo.ShouldAddImports.ObjectsEquals.compareZero.a, foo.ShouldAddImports.ObjectsEquals.compareZero.b) == 0") + .builder("Integer.compare(#{a:any(int)}, #{b:any(int)}) == 0") .build(); final JavaTemplate isis = JavaTemplate - .builder("foo.ShouldAddImports.ObjectsEquals.isis.a == foo.ShouldAddImports.ObjectsEquals.isis.b") + .builder("#{a:any(int)} == #{b:any(int)}") .build(); @Override @@ -222,10 +222,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("java.util.Objects.hash(foo.ShouldAddImports.StaticImportObjectsHash.before.s)") + .builder("java.util.Objects.hash(#{s:any(java.lang.String)})") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.ShouldAddImports.StaticImportObjectsHash.after.s.hashCode()") + .builder("#{s:any(java.lang.String)}.hashCode()") .build(); @Override @@ -277,10 +277,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.ShouldAddImports.FileExists.before.path.toFile().exists()") + .builder("#{path:any(java.nio.file.Path)}.toFile().exists()") .build(); final JavaTemplate after = JavaTemplate - .builder("java.nio.file.Files.exists(foo.ShouldAddImports.FileExists.after.path)") + .builder("java.nio.file.Files.exists(#{path:any(java.nio.file.Path)})") .build(); @Override diff --git a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java index 3a5c97e3..7447c839 100644 --- a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java +++ b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,10 +89,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.ShouldSupportNestedClasses.NestedClass.before.s.length() > 0") + .builder("#{s:any(java.lang.String)}.length() > 0") .build(); final JavaTemplate after = JavaTemplate - .builder("!foo.ShouldSupportNestedClasses.NestedClass.after.s.isEmpty()") + .builder("!#{s:any(java.lang.String)}.isEmpty()") .build(); @Override @@ -143,10 +143,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.ShouldSupportNestedClasses.AnotherClass.before.s.length() == 0") + .builder("#{s:any(java.lang.String)}.length() == 0") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.ShouldSupportNestedClasses.AnotherClass.after.s.isEmpty()") + .builder("#{s:any(java.lang.String)}.isEmpty()") .build(); @Override diff --git a/src/test/resources/refaster/SimplifyBooleansRecipe.java b/src/test/resources/refaster/SimplifyBooleansRecipe.java index f42c9fe9..1b2134be 100644 --- a/src/test/resources/refaster/SimplifyBooleansRecipe.java +++ b/src/test/resources/refaster/SimplifyBooleansRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,10 +61,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.SimplifyBooleans.before.s.replaceAll(foo.SimplifyBooleans.before.s1, foo.SimplifyBooleans.before.s2)") + .builder("#{s:any(java.lang.String)}.replaceAll(#{s1:any(java.lang.String)}, #{s2:any(java.lang.String)})") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.SimplifyBooleans.after.s != null ? foo.SimplifyBooleans.after.s.replaceAll(foo.SimplifyBooleans.after.s1, foo.SimplifyBooleans.after.s2) : foo.SimplifyBooleans.after.s") + .builder("#{s:any(java.lang.String)} != null ? #{s}.replaceAll(#{s1:any(java.lang.String)}, #{s2:any(java.lang.String)}) : #{s}") .build(); @Override diff --git a/src/test/resources/refaster/SimplifyTernaryRecipes.java b/src/test/resources/refaster/SimplifyTernaryRecipes.java index 1c60cebb..1f9e17b5 100644 --- a/src/test/resources/refaster/SimplifyTernaryRecipes.java +++ b/src/test/resources/refaster/SimplifyTernaryRecipes.java @@ -88,10 +88,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.SimplifyTernary.SimplifyTernaryTrueFalse.before.expr ? true : false") + .builder("#{expr:any(boolean)} ? true : false") .build(); final JavaTemplate after = JavaTemplate - .builder("foo.SimplifyTernary.SimplifyTernaryTrueFalse.after.expr") + .builder("#{expr:any(boolean)}") .build(); @Override @@ -139,10 +139,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("foo.SimplifyTernary.SimplifyTernaryFalseTrue.before.expr ? false : true") + .builder("#{expr:any(boolean)} ? false : true") .build(); final JavaTemplate after = JavaTemplate - .builder("!(foo.SimplifyTernary.SimplifyTernaryFalseTrue.after.expr)") + .builder("!(#{expr:any(boolean)})") .build(); @Override diff --git a/src/test/resources/refaster/UseStringIsEmptyRecipe.java b/src/test/resources/refaster/UseStringIsEmptyRecipe.java index 3f17be10..0b4b3353 100644 --- a/src/test/resources/refaster/UseStringIsEmptyRecipe.java +++ b/src/test/resources/refaster/UseStringIsEmptyRecipe.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 the original author or authors. + * Copyright 2024 the original author or authors. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,10 +61,10 @@ public String getDescription() { public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { final JavaTemplate before = JavaTemplate - .builder("#{s:any(java.lang.String)}).length() > 0") + .builder("#{s:any(java.lang.String)}.length() > 0") .build(); final JavaTemplate after = JavaTemplate - .builder("!(#{s:any(java.lang.String)})).isEmpty()") + .builder("!(#{s:any(java.lang.String)}.isEmpty())") .build(); @Override @@ -75,7 +75,7 @@ public J visitBinary(J.Binary elem, ExecutionContext ctx) { after.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0)), getCursor(), ctx, - SHORTEN_NAMES, SIMPLIFY_BOOLEANS + REMOVE_PARENS, SHORTEN_NAMES, SIMPLIFY_BOOLEANS ); } return super.visitBinary(elem, ctx); From a72612266ac9bc88880da5d1aef4620a43baabd0 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:10:06 +0100 Subject: [PATCH 18/22] Handle recipes without parameters --- .../processor/RefasterTemplateProcessor.java | 15 ++++++++++----- .../refaster/CharacterEscapeAnnotationRecipe.java | 15 ++++++++++----- .../resources/refaster/UnnamedPackageRecipe.java | 9 +++++++-- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index 3e442c51..c65e7c5e 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -794,11 +794,16 @@ private boolean resolve(Context context, JCCompilationUnit cu) { JavacResolution res = new JavacResolution(context); try { // Resolve parameters - res.resolveAll(context, cu, afterTemplate.getParameters()) - .forEach((k, v) -> resolvedParameters.put(v, k)); - beforeTemplates - .forEach(bt -> res.resolveAll(context, cu, bt.getParameters()) - .forEach((k, v) -> resolvedParameters.put(v, k))); + for (JCTree.JCMethodDecl beforeTemplate : beforeTemplates) { + if (!beforeTemplate.getParameters().isEmpty()) { + res.resolveAll(context, cu, beforeTemplate.getParameters()) + .forEach((k, v) -> resolvedParameters.put(v, k)); + } + } + if (!afterTemplate.getParameters().isEmpty()) { + res.resolveAll(context, cu, afterTemplate.getParameters()) + .forEach((k, v) -> resolvedParameters.put(v, k)); + } // Resolve templates beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) res.resolveAll(context, cu, singletonList(key)).get(key)); diff --git a/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java b/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java index fe1dcabc..296e0f30 100644 --- a/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java +++ b/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java @@ -20,6 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -35,7 +36,7 @@ /** - * OpenRewrite recipe created for Refaster template {@code MultilineAnnotation}. + * OpenRewrite recipe created for Refaster template {@code CharacterEscapeAnnotation}. */ @SuppressWarnings("all") @NonNullApi @@ -44,7 +45,7 @@ public class CharacterEscapeAnnotationRecipe extends Recipe { /** * Instantiates a new instance. */ - public MultilineAnnotationRecipe() {} + public CharacterEscapeAnnotationRecipe() {} @Override public String getDisplayName() { @@ -53,7 +54,7 @@ public String getDisplayName() { @Override public String getDescription() { - return "A multiline annotation.\nSupported here too!\nIt also supports escaped quotations: \"I think therefore I am\" - Descartes.\nAnd escaped backslashes: C:\\Users\\JohnDoe\\Documents\\\nAnd escaped tabs: \"This is a string with a tab character\t\".\nAnd escaped carriage returns: \"This is a string with a carriage return character\r\".\nAnd escaped form feeds: \"This is a string with a form feed character\f\".\nAnd escaped backspace characters: \"This is a string with a backspace character\b\".\nAnd escaped null characters: \"This is a string with a null character\u0000\".\nAnd escaped octal characters: \"This is a string with an octal characterS\".\nAnd escaped unicode characters: \"This is a string with a unicode character\u1234\".\nAnd raw emoji: \"This is a string with an emoji\uD83D\uDE00\".\nAnd emojis: \"This is a string with an emoji\uD83D\uDE00\"."; + return "A multiline annotation.\nSupported here too!\nIt also supports escaped quotations: \"I think therefore I am\" - Descartes.\nAnd escaped backslashes: C:\\Users\\JohnDoe\\Documents\\\nAnd escaped tabs: \"This is a string with a tab character\t\".\nAnd escaped carriage returns: \"This is a string with a carriage return character\r\".\nAnd escaped form feeds: \"This is a string with a form feed character\f\".\nAnd escaped backspace characters: \"This is a string with a backspace character\b\".\nAnd escaped null characters: \"This is a string with a null character \".\nAnd escaped octal characters: \"This is a string with an octal characterS\".\nAnd escaped unicode characters: \"This is a string with a unicode characterሴ\".\nAnd raw emoji: \"This is a string with an emoji😀\".\nAnd emojis: \"This is a string with an emoji😀\"."; } @Override @@ -64,8 +65,12 @@ public Set getTags() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", () -> "The answer to life, the universe, and everything").build(); - final JavaTemplate after = Semantics.expression(this, "after", () -> "42").build(); + final JavaTemplate before = JavaTemplate + .builder("\"The answer to life, the universe, and everything\"") + .build(); + final JavaTemplate after = JavaTemplate + .builder("\"42\"") + .build(); @Override public J visitExpression(Expression elem, ExecutionContext ctx) { diff --git a/src/test/resources/refaster/UnnamedPackageRecipe.java b/src/test/resources/refaster/UnnamedPackageRecipe.java index c2d15255..e2673010 100644 --- a/src/test/resources/refaster/UnnamedPackageRecipe.java +++ b/src/test/resources/refaster/UnnamedPackageRecipe.java @@ -18,6 +18,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.NonNullApi; +import org.openrewrite.java.JavaParser; import org.openrewrite.java.JavaTemplate; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; @@ -57,8 +58,12 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() { - final JavaTemplate before = Semantics.expression(this, "before", () -> "This class is located in the default package").build(); - final JavaTemplate after = Semantics.expression(this, "after", () -> "And that doesn\'t cause any problems").build(); + final JavaTemplate before = JavaTemplate + .builder("\"This class is located in the default package\"") + .build(); + final JavaTemplate after = JavaTemplate + .builder("\"And that doesn\\'t cause any problems\"") + .build(); @Override public J visitExpression(Expression elem, ExecutionContext ctx) { From 261ad17a7393fa5db5553b8a58e3a646343ee4ea Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:19:31 +0100 Subject: [PATCH 19/22] Drop now unused import --- .../org/openrewrite/java/template/internal/TemplateCode.java | 4 +--- .../java/template/processor/RefasterTemplateProcessor.java | 1 - .../java/template/RefasterTemplateProcessorTest.java | 1 - src/test/resources/refaster/ArraysRecipe.java | 2 +- .../resources/refaster/CharacterEscapeAnnotationRecipe.java | 3 +-- src/test/resources/refaster/EscapesRecipes.java | 2 +- src/test/resources/refaster/GenericsRecipes.java | 2 +- src/test/resources/refaster/MatchingRecipes.java | 2 +- src/test/resources/refaster/MethodThrowsRecipe.java | 2 +- src/test/resources/refaster/MultipleDereferencesRecipes.java | 2 +- src/test/resources/refaster/NestedPreconditionsRecipe.java | 2 +- src/test/resources/refaster/ParameterReuseRecipe.java | 2 +- src/test/resources/refaster/ShouldAddImportsRecipes.java | 2 +- .../resources/refaster/ShouldSupportNestedClassesRecipes.java | 2 +- src/test/resources/refaster/SimplifyBooleansRecipe.java | 2 +- src/test/resources/refaster/SimplifyTernaryRecipes.java | 2 +- src/test/resources/refaster/UnnamedPackageRecipe.java | 2 +- src/test/resources/refaster/UseStringIsEmptyRecipe.java | 2 +- 18 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java index 12e980ff..5a9a46ac 100644 --- a/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java +++ b/src/main/java/org/openrewrite/java/template/internal/TemplateCode.java @@ -90,9 +90,7 @@ public TemplateCodePrinter(Writer writer, List declaredPa public void visitIdent(JCIdent jcIdent) { try { Symbol sym = jcIdent.sym; - Optional param = declaredParameters.stream() - .filter(p -> p.sym == sym) - .findFirst(); + Optional param = declaredParameters.stream().filter(p -> p.sym == sym).findFirst(); if (param.isPresent()) { print("#{" + sym.name); if (seenParameters.add(param.get())) { diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index c65e7c5e..bded4201 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -329,7 +329,6 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { out.write("import org.openrewrite.java.JavaVisitor;\n"); out.write("import org.openrewrite.java.search.*;\n"); out.write("import org.openrewrite.java.template.Primitive;\n"); - out.write("import org.openrewrite.java.template.Semantics;\n"); out.write("import org.openrewrite.java.template.function.*;\n"); out.write("import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor;\n"); out.write("import org.openrewrite.java.tree.*;\n"); diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index 373fb211..8e74d6c7 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -140,7 +140,6 @@ void inline() { "import org.openrewrite.java.JavaVisitor;\n" + "import org.openrewrite.java.search.*;\n" + "import org.openrewrite.java.template.Primitive;\n" + - "import org.openrewrite.java.template.Semantics;\n" + "import org.openrewrite.java.template.function.*;\n" + "import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor;\n" + "import org.openrewrite.java.tree.*;\n" + diff --git a/src/test/resources/refaster/ArraysRecipe.java b/src/test/resources/refaster/ArraysRecipe.java index eb553c69..f4283a73 100644 --- a/src/test/resources/refaster/ArraysRecipe.java +++ b/src/test/resources/refaster/ArraysRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java b/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java index 296e0f30..541aa369 100644 --- a/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java +++ b/src/test/resources/refaster/CharacterEscapeAnnotationRecipe.java @@ -25,7 +25,6 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; @@ -54,7 +53,7 @@ public String getDisplayName() { @Override public String getDescription() { - return "A multiline annotation.\nSupported here too!\nIt also supports escaped quotations: \"I think therefore I am\" - Descartes.\nAnd escaped backslashes: C:\\Users\\JohnDoe\\Documents\\\nAnd escaped tabs: \"This is a string with a tab character\t\".\nAnd escaped carriage returns: \"This is a string with a carriage return character\r\".\nAnd escaped form feeds: \"This is a string with a form feed character\f\".\nAnd escaped backspace characters: \"This is a string with a backspace character\b\".\nAnd escaped null characters: \"This is a string with a null character \".\nAnd escaped octal characters: \"This is a string with an octal characterS\".\nAnd escaped unicode characters: \"This is a string with a unicode characterሴ\".\nAnd raw emoji: \"This is a string with an emoji😀\".\nAnd emojis: \"This is a string with an emoji😀\"."; + return "A multiline annotation.\nSupported here too!\nIt also supports escaped quotations: \"I think therefore I am\" - Descartes.\nAnd escaped backslashes: C:\\Users\\JohnDoe\\Documents\\\nAnd escaped tabs: \"This is a string with a tab character\t\".\nAnd escaped carriage returns: \"This is a string with a carriage return character\r\".\nAnd escaped form feeds: \"This is a string with a form feed character\f\".\nAnd escaped backspace characters: \"This is a string with a backspace character\b\".\nAnd escaped null characters: \"This is a string with a null character\u0000\".\nAnd escaped octal characters: \"This is a string with an octal characterS\".\nAnd escaped unicode characters: \"This is a string with a unicode character\u1234\".\nAnd raw emoji: \"This is a string with an emoji\uD83D\uDE00\".\nAnd emojis: \"This is a string with an emoji\uD83D\uDE00\"."; } @Override diff --git a/src/test/resources/refaster/EscapesRecipes.java b/src/test/resources/refaster/EscapesRecipes.java index 826a5628..f66fc224 100644 --- a/src/test/resources/refaster/EscapesRecipes.java +++ b/src/test/resources/refaster/EscapesRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/GenericsRecipes.java b/src/test/resources/refaster/GenericsRecipes.java index b6d9df93..bd5153fb 100644 --- a/src/test/resources/refaster/GenericsRecipes.java +++ b/src/test/resources/refaster/GenericsRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/MatchingRecipes.java b/src/test/resources/refaster/MatchingRecipes.java index 8eeb003d..7064ed13 100644 --- a/src/test/resources/refaster/MatchingRecipes.java +++ b/src/test/resources/refaster/MatchingRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/MethodThrowsRecipe.java b/src/test/resources/refaster/MethodThrowsRecipe.java index 724cca0b..c9c1171a 100644 --- a/src/test/resources/refaster/MethodThrowsRecipe.java +++ b/src/test/resources/refaster/MethodThrowsRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/MultipleDereferencesRecipes.java b/src/test/resources/refaster/MultipleDereferencesRecipes.java index 326efa48..3eb865f1 100644 --- a/src/test/resources/refaster/MultipleDereferencesRecipes.java +++ b/src/test/resources/refaster/MultipleDereferencesRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/NestedPreconditionsRecipe.java b/src/test/resources/refaster/NestedPreconditionsRecipe.java index 17c9bbf7..8f9835f2 100644 --- a/src/test/resources/refaster/NestedPreconditionsRecipe.java +++ b/src/test/resources/refaster/NestedPreconditionsRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/ParameterReuseRecipe.java b/src/test/resources/refaster/ParameterReuseRecipe.java index 686edeb2..da56b237 100644 --- a/src/test/resources/refaster/ParameterReuseRecipe.java +++ b/src/test/resources/refaster/ParameterReuseRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/ShouldAddImportsRecipes.java b/src/test/resources/refaster/ShouldAddImportsRecipes.java index 73ce60b9..904843f3 100644 --- a/src/test/resources/refaster/ShouldAddImportsRecipes.java +++ b/src/test/resources/refaster/ShouldAddImportsRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java index 7447c839..bf9a4ab4 100644 --- a/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java +++ b/src/test/resources/refaster/ShouldSupportNestedClassesRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/SimplifyBooleansRecipe.java b/src/test/resources/refaster/SimplifyBooleansRecipe.java index 1b2134be..46227cfb 100644 --- a/src/test/resources/refaster/SimplifyBooleansRecipe.java +++ b/src/test/resources/refaster/SimplifyBooleansRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/SimplifyTernaryRecipes.java b/src/test/resources/refaster/SimplifyTernaryRecipes.java index 1f9e17b5..674aa4f1 100644 --- a/src/test/resources/refaster/SimplifyTernaryRecipes.java +++ b/src/test/resources/refaster/SimplifyTernaryRecipes.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/UnnamedPackageRecipe.java b/src/test/resources/refaster/UnnamedPackageRecipe.java index e2673010..7ba0b392 100644 --- a/src/test/resources/refaster/UnnamedPackageRecipe.java +++ b/src/test/resources/refaster/UnnamedPackageRecipe.java @@ -23,7 +23,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; diff --git a/src/test/resources/refaster/UseStringIsEmptyRecipe.java b/src/test/resources/refaster/UseStringIsEmptyRecipe.java index 0b4b3353..64ebc830 100644 --- a/src/test/resources/refaster/UseStringIsEmptyRecipe.java +++ b/src/test/resources/refaster/UseStringIsEmptyRecipe.java @@ -25,7 +25,7 @@ import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.search.*; import org.openrewrite.java.template.Primitive; -import org.openrewrite.java.template.Semantics; + import org.openrewrite.java.template.function.*; import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor; import org.openrewrite.java.tree.*; From 12223ca322aa4639ea613c8604b93fc1c24ed8b4 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:22:52 +0100 Subject: [PATCH 20/22] Drop inline tests again while text blocks are unavailable --- .../RefasterTemplateProcessorTest.java | 101 +----------------- .../java/template/TemplateProcessorTest.java | 43 -------- 2 files changed, 1 insertion(+), 143 deletions(-) diff --git a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java index 8e74d6c7..9cfe0f5d 100644 --- a/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/RefasterTemplateProcessorTest.java @@ -104,106 +104,6 @@ void stringIsEmptyPredicate() { assertEquals(0, compilation.generatedSourceFiles().size(), "Not yet supported"); } - @Test - void inline() { - Compilation compilation = compileSource("foo.UseStringIsEmpty", - "package foo;\n" + - "\n" + - "import com.google.errorprone.refaster.annotation.AfterTemplate;\n" + - "import com.google.errorprone.refaster.annotation.BeforeTemplate;\n" + - "\n" + - "class UseStringIsEmpty {\n" + - " @BeforeTemplate\n" + - " boolean before(String s) {\n" + - " return s.length() > 0;\n" + - " }\n" + - "\n" + - " @AfterTemplate\n" + - " boolean after(String s) {\n" + - " return !(s.isEmpty());\n" + - " }\n" + - "}\n"); - assertThat(compilation).succeeded(); - assertThat(compilation) - .generatedSourceFile("foo/UseStringIsEmptyRecipe") - .hasSourceEquivalentTo(JavaFileObjects.forSourceString("/SOURCE_OUTPUT/foo/UseStringIsEmptyRecipe", - //language=java - "package foo;\n" + - "\n" + - "import org.openrewrite.ExecutionContext;\n" + - "import org.openrewrite.Preconditions;\n" + - "import org.openrewrite.Recipe;\n" + - "import org.openrewrite.TreeVisitor;\n" + - "import org.openrewrite.internal.lang.NonNullApi;\n" + - "import org.openrewrite.java.JavaParser;\n" + - "import org.openrewrite.java.JavaTemplate;\n" + - "import org.openrewrite.java.JavaVisitor;\n" + - "import org.openrewrite.java.search.*;\n" + - "import org.openrewrite.java.template.Primitive;\n" + - "import org.openrewrite.java.template.function.*;\n" + - "import org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor;\n" + - "import org.openrewrite.java.tree.*;\n" + - "\n" + - "import java.util.*;\n" + - "\n" + - "import static org.openrewrite.java.template.internal.AbstractRefasterJavaVisitor.EmbeddingOption.*;\n" + - "\n" + - "\n" + - "/**\n" + - " * OpenRewrite recipe created for Refaster template {@code UseStringIsEmpty}.\n" + - " */\n" + - "@SuppressWarnings(\"all\")\n" + - "@NonNullApi\n" + - "public class UseStringIsEmptyRecipe extends Recipe {\n" + - "\n" + - " /**\n" + - " * Instantiates a new instance.\n" + - " */\n" + - " public UseStringIsEmptyRecipe() {}\n" + - "\n" + - " @Override\n" + - " public String getDisplayName() {\n" + - " return \"Refaster template `UseStringIsEmpty`\";\n" + - " }\n" + - "\n" + - " @Override\n" + - " public String getDescription() {\n" + - " return \"Recipe created for the following Refaster template:\\n```java\\nclass UseStringIsEmpty {\\n \\n @BeforeTemplate()\\n boolean before(String s) {\\n return s.length() > 0;\\n }\\n \\n @AfterTemplate()\\n boolean after(String s) {\\n return !(s.isEmpty());\\n }\\n}\\n```\\n.\";\n" + - " }\n" + - "\n" + - " @Override\n" + - " public TreeVisitor getVisitor() {\n" + - " JavaVisitor javaVisitor = new AbstractRefasterJavaVisitor() {\n" + - " final JavaTemplate before = JavaTemplate\n" + - " .builder(\"#{s:any(java.lang.String)}.length() > 0\")\n" + - " .build();\n" + - " final JavaTemplate after = JavaTemplate\n" + - " .builder(\"!(#{s:any(java.lang.String)}.isEmpty())\")\n" + - " .build();\n" + - "\n" + - " @Override\n" + - " public J visitBinary(J.Binary elem, ExecutionContext ctx) {\n" + - " JavaTemplate.Matcher matcher;\n" + - " if ((matcher = before.matcher(getCursor())).find()) {\n" + - " return embed(\n" + - " after.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0)),\n" + - " getCursor(),\n" + - " ctx,\n" + - " REMOVE_PARENS, SHORTEN_NAMES, SIMPLIFY_BOOLEANS\n" + - " );\n" + - " }\n" + - " return super.visitBinary(elem, ctx);\n" + - " }\n" + - "\n" + - " };\n" + - " return Preconditions.check(\n" + - " new UsesMethod<>(\"java.lang.String length(..)\"),\n" + - " javaVisitor\n" + - " );\n" + - " }\n" + - "}")); - } - private static Compilation compileResource(String resourceName) { return compileResource(resourceName, new RefasterTemplateProcessor()); } @@ -213,6 +113,7 @@ static Compilation compileResource(String resourceName, TypeAwareProcessor proce return compile(JavaFileObjects.forResource(resourceName), processor); } + @SuppressWarnings("unused") // use when text blocks are available static Compilation compileSource(String fqn, @Language("java") String source) { return compile(JavaFileObjects.forSourceString(fqn, source), new RefasterTemplateProcessor()); } diff --git a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java index 62872e1c..100e6cb7 100644 --- a/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java +++ b/src/test/java/org/openrewrite/java/template/TemplateProcessorTest.java @@ -95,47 +95,4 @@ void unnamedPackage() { .generatedSourceFile("UnnamedPackage$1_message") .hasSourceEquivalentTo(JavaFileObjects.forResource("template/UnnamedPackage$1_message.java")); } - - @Test - void inline() { - Compilation compilation = compileSource("foo.SomeRecipe", - "package foo;" + - "import org.openrewrite.ExecutionContext;" + - "import org.openrewrite.java.JavaVisitor;" + - "import org.openrewrite.java.JavaTemplate;" + - "import org.openrewrite.java.template.Semantics;" + - "public class SomeRecipe {" + - " JavaVisitor visitor = new JavaVisitor() {" + - " JavaTemplate.Builder before = Semantics.statement(this, \"before\", (String s) -> System.out.println(s));" + - " };" + - "}", - new TemplateProcessor()); - assertThat(compilation).succeeded(); - assertThat(compilation) - .generatedSourceFile("foo/SomeRecipe$1_before") - .hasSourceEquivalentTo(JavaFileObjects.forSourceString("/SOURCE_OUTPUT/foo/SomeRecipe$1_before", - //language=java - "package foo;\n" + - "import org.openrewrite.java.*;\n" + - "\n" + - "/**\n" + - " * OpenRewrite `before` template created for {@code foo.SomeRecipe$1}.\n" + - " */\n" + - "@SuppressWarnings(\"all\")\n" + - "public class SomeRecipe$1_before {\n" + - " /**\n" + - " * Instantiates a new instance.\n" + - " */\n" + - " public SomeRecipe$1_before() {}\n" + - "\n" + - " /**\n" + - " * Get the {@code JavaTemplate.Builder} to match or replace.\n" + - " * @return the JavaTemplate builder.\n" + - " */\n" + - " public static JavaTemplate.Builder getTemplate() {\n" + - " return JavaTemplate\n" + - " .builder(\"System.out.println(#{s:any(java.lang.String)})\");\n" + - " }\n" + - "}")); - } } From 0ea517290b26d6db0613893c880851c652aa0b0c Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:38:52 +0100 Subject: [PATCH 21/22] Only pass through matching resolved parameter types --- .../processor/RefasterTemplateProcessor.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index bded4201..a9f4a489 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -393,19 +393,19 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) { } } - private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl, Map resolvedParameters) { + private String toJavaTemplateBuilder(JCTree.JCMethodDecl methodDecl, + Map resolvedParameters) { JCTree tree = methodDecl.getBody().getStatements().get(0); if (tree instanceof JCTree.JCReturn) { tree = ((JCTree.JCReturn) tree).getExpression(); } - List parameters = methodDecl.getParameters(); - List mapped = parameters.stream() + List mappedParameters = methodDecl.getParameters().stream() .map(resolvedParameters::get) .map(JCTree.JCVariableDecl.class::cast) .collect(Collectors.toList()); - String javaTemplateBuilder = TemplateCode.process(tree, mapped, true); + String javaTemplateBuilder = TemplateCode.process(tree, mappedParameters, true); return TemplateCode.indent(javaTemplateBuilder, 16); } @@ -687,7 +687,7 @@ class TemplateDescriptor { final JCTree.JCClassDecl classDecl; final List beforeTemplates = new ArrayList<>(); JCTree.JCMethodDecl afterTemplate; - Map resolvedParameters = new IdentityHashMap<>(); + Map resolvedParameters = new IdentityHashMap<>(); public TemplateDescriptor(JCTree.JCClassDecl classDecl) { this.classDecl = classDecl; @@ -795,13 +795,19 @@ private boolean resolve(Context context, JCCompilationUnit cu) { // Resolve parameters for (JCTree.JCMethodDecl beforeTemplate : beforeTemplates) { if (!beforeTemplate.getParameters().isEmpty()) { - res.resolveAll(context, cu, beforeTemplate.getParameters()) - .forEach((k, v) -> resolvedParameters.put(v, k)); + for (Map.Entry e : res.resolveAll(context, cu, beforeTemplate.getParameters()).entrySet()) { + if (e.getKey() instanceof JCTree.JCVariableDecl && e.getValue() instanceof JCTree.JCVariableDecl) { + resolvedParameters.put((JCTree.JCVariableDecl) e.getValue(), (JCTree.JCVariableDecl) e.getKey()); + } + } } } if (!afterTemplate.getParameters().isEmpty()) { - res.resolveAll(context, cu, afterTemplate.getParameters()) - .forEach((k, v) -> resolvedParameters.put(v, k)); + for (Map.Entry e : res.resolveAll(context, cu, afterTemplate.getParameters()).entrySet()) { + if (e.getKey() instanceof JCTree.JCVariableDecl && e.getValue() instanceof JCTree.JCVariableDecl) { + resolvedParameters.put((JCTree.JCVariableDecl) e.getValue(), (JCTree.JCVariableDecl) e.getKey()); + } + } } // Resolve templates From 50fdf562518023a5fc837186b33684cd4e37ac1e Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 3 Mar 2024 21:44:06 +0100 Subject: [PATCH 22/22] Resolve all before templates at once --- .../java/template/processor/RefasterTemplateProcessor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java index a9f4a489..29a3c1db 100644 --- a/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java +++ b/src/main/java/org/openrewrite/java/template/processor/RefasterTemplateProcessor.java @@ -811,7 +811,8 @@ private boolean resolve(Context context, JCCompilationUnit cu) { } // Resolve templates - beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) res.resolveAll(context, cu, singletonList(key)).get(key)); + Map resolvedBeforeTemplates = res.resolveAll(context, cu, beforeTemplates); + beforeTemplates.replaceAll(key -> (JCTree.JCMethodDecl) resolvedBeforeTemplates.get(key)); afterTemplate = (JCTree.JCMethodDecl) res.resolveAll(context, cu, singletonList(afterTemplate)).get(afterTemplate); } catch (Throwable t) { processingEnv.getMessager().printMessage(Kind.WARNING, "Had trouble type attributing the template.");