Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of concept for @Matches annotation #29

Merged
merged 7 commits into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -274,60 +274,79 @@ public void visitClassDef(JCTree.JCClassDecl classDecl) {
}

recipe.append(" JavaTemplate.Matcher matcher;\n");
String predicate = befores.keySet().stream().map(b -> "(matcher = " + b + ".matcher(getCursor())).find()").collect(Collectors.joining(" || "));
recipe.append(" if (" + predicate + ") {\n");
Set<String> beforeImports = imports.entrySet().stream()
.filter(e -> descriptor.beforeTemplates.contains(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
Set<String> afterImports = imports.entrySet().stream()
.filter(e -> descriptor.afterTemplate == e.getKey())
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
for (String import_ : imports.values().stream().flatMap(Set::stream).collect(Collectors.toSet())) {
if (import_.startsWith("java.lang.")) {
continue;
for (Map.Entry<String, JCTree.JCMethodDecl> entry : befores.entrySet()) {
recipe.append(" if (" + "(matcher = " + entry.getKey() + ".matcher(getCursor())).find()" + ") {\n");
for (JCTree.JCVariableDecl param : entry.getValue().getParameters()) {
com.sun.tools.javac.util.List<JCTree.JCAnnotation> annotations = param.getModifiers().getAnnotations();
for (int i = 0; i < annotations.size(); i++) {
JCTree.JCAnnotation jcAnnotation = annotations.get(i);
String annotationType = jcAnnotation.attribute.type.tsym.getQualifiedName().toString();
if (annotationType.equals("org.openrewrite.java.template.NotMatches")) {
String matcher = ((Type.ClassType) jcAnnotation.attribute.getValue().values.get(0).snd.getValue()).tsym.getQualifiedName().toString();
recipe.append(" if (new " + matcher + "().matches((Expression) matcher.parameter(" + i + "))) {\n");
recipe.append(" return super.visit" + methodSuffix + "(elem, ctx);\n");
recipe.append(" }\n");
} else if (annotationType.equals("org.openrewrite.java.template.Matches")) {
String matcher = ((Type.ClassType) jcAnnotation.attribute.getValue().values.get(0).snd.getValue()).tsym.getQualifiedName().toString();
recipe.append(" if (!new " + matcher + "().matches((Expression) matcher.parameter(" + i + "))) {\n");
recipe.append(" return super.visit" + methodSuffix + "(elem, ctx);\n");
recipe.append(" }\n");
}
}
}
if (beforeImports.contains(import_) && afterImports.contains(import_)) {
} else if (beforeImports.contains(import_)) {
recipe.append(" maybeRemoveImport(\"" + import_ + "\");\n");
} else if (afterImports.contains(import_)) {
recipe.append(" maybeAddImport(\"" + import_ + "\");\n");
Set<String> beforeImports = imports.entrySet().stream()
.filter(e -> entry.getValue().equals(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
Set<String> afterImports = imports.entrySet().stream()
.filter(e -> descriptor.afterTemplate == e.getKey())
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
for (String import_ : imports.values().stream().flatMap(Set::stream).collect(Collectors.toSet())) {
if (import_.startsWith("java.lang.")) {
continue;
}
if (beforeImports.contains(import_) && afterImports.contains(import_)) {
} else if (beforeImports.contains(import_)) {
recipe.append(" maybeRemoveImport(\"" + import_ + "\");\n");
} else if (afterImports.contains(import_)) {
recipe.append(" maybeAddImport(\"" + import_ + "\");\n");
}
}
}
beforeImports = staticImports.entrySet().stream()
.filter(e -> descriptor.beforeTemplates.contains(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
afterImports = staticImports.entrySet().stream()
.filter(e -> descriptor.afterTemplate == e.getKey())
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
for (String import_ : staticImports.values().stream().flatMap(Set::stream).collect(Collectors.toSet())) {
int dot = import_.lastIndexOf('.');
if (import_.startsWith("java.lang.")) {
continue;
beforeImports = staticImports.entrySet().stream()
.filter(e -> entry.getValue().equals(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
afterImports = staticImports.entrySet().stream()
.filter(e -> descriptor.afterTemplate == e.getKey())
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
for (String import_ : staticImports.values().stream().flatMap(Set::stream).collect(Collectors.toSet())) {
int dot = import_.lastIndexOf('.');
if (import_.startsWith("java.lang.")) {
continue;
}
if (beforeImports.contains(import_) && afterImports.contains(import_)) {
} else if (beforeImports.contains(import_)) {
recipe.append(" maybeRemoveImport(\"" + import_ + "\");\n");
} else if (afterImports.contains(import_)) {
recipe.append(" maybeAddImport(\"" + import_.substring(0, dot) + "\", \"" + import_.substring(dot + 1) + "\");\n");
}
}
if (beforeImports.contains(import_) && afterImports.contains(import_)) {
} else if (beforeImports.contains(import_)) {
recipe.append(" maybeRemoveImport(\"" + import_ + "\");\n");
} else if (afterImports.contains(import_)) {
recipe.append(" maybeAddImport(\"" + import_.substring(0, dot) + "\", \"" + import_.substring(dot + 1) + "\");\n");
for (String doAfterVisit : DO_AFTER_VISIT) {
recipe.append(" doAfterVisit(" + doAfterVisit + ");\n");
}
if (parameters.isEmpty()) {
recipe.append(" return " + after + ".apply(getCursor(), elem.getCoordinates().replace());\n");
} else {
recipe.append(" return " + after + ".apply(getCursor(), elem.getCoordinates().replace(), " + parameters + ");\n");
}
recipe.append(" }\n");
}
for (String doAfterVisit : DO_AFTER_VISIT) {
recipe.append(" doAfterVisit(" + doAfterVisit + ");\n");
}
if (parameters.isEmpty()) {
recipe.append(" return " + after + ".apply(getCursor(), elem.getCoordinates().replace());\n");
} else {
recipe.append(" return " + after + ".apply(getCursor(), elem.getCoordinates().replace(), " + parameters + ");\n");
}
recipe.append(" }\n");
recipe.append(" return super.visit" + methodSuffix + "(elem, ctx);\n");
recipe.append(" }\n");
recipe.append("\n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ public void scan(JCTree tree) {
}
}

if (tree instanceof JCTree.JCAnnotation) {
// completely skip annotations for now
return;
}

if (tree instanceof JCIdent) {
if (tree.type == null || !(tree.type.tsym instanceof Symbol.ClassSymbol)) {
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2023 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.template;

import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;

public class MethodInvocationMatcher implements Matcher<Expression> {
@Override
public boolean matches(Expression expr) {
return expr instanceof J.MethodInvocation;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ void generateRecipe(String recipeName) {
"ShouldSupportNestedClasses",
"ShouldAddImports",
"MultipleDereferences",
"Matching",
})
void nestedRecipes(String recipeName) {
Compilation compilation = javac()
Expand Down
28 changes: 28 additions & 0 deletions src/test/resources/recipes/Matching.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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;

public class Matching {

public static class StringIsEmpty {
@BeforeTemplate
boolean before(@NotMatches(MethodInvocationMatcher.class) String s) {
return s.isEmpty();
}

@BeforeTemplate
boolean before2(@Matches(MethodInvocationMatcher.class) String s) {
return s.isEmpty();
}

@AfterTemplate
boolean after(String s) {
return s != null && s.length() == 0;
}
}

}
85 changes: 85 additions & 0 deletions src/test/resources/recipes/MatchingRecipes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package foo;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.*;
import org.openrewrite.java.template.Primitive;
import org.openrewrite.java.tree.*;

import java.util.Arrays;
import java.util.List;


public final class MatchingRecipes extends Recipe {

@Override
public String getDisplayName() {
return "`Matching` Refaster recipes";
}

@Override
public String getDescription() {
return "Refaster template recipes for `foo.Matching`.";
}


@Override
public List<Recipe> getRecipeList() {
return Arrays.asList(
new StringIsEmptyRecipe()
);
}

public static class StringIsEmptyRecipe extends Recipe {

@Override
public String getDisplayName() {
return "Refaster template `Matching.StringIsEmpty`";
}

@Override
public String getDescription() {
return "Recipe created for the following Refaster template:\n```java\npublic static class StringIsEmpty {\n \n @BeforeTemplate()\n boolean before(@NotMatches(value = MethodInvocationMatcher.class)\n String s) {\n return s.isEmpty();\n }\n \n @BeforeTemplate()\n boolean before2(@Matches(value = MethodInvocationMatcher.class)\n String s) {\n return s.isEmpty();\n }\n \n @AfterTemplate()\n boolean after(String s) {\n return s != null && s.length() == 0;\n }\n}\n```\n.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
JavaVisitor<ExecutionContext> javaVisitor = new JavaVisitor<ExecutionContext>() {
final JavaTemplate before = JavaTemplate.compile(this, "before", (JavaTemplate.F1<?, ?>) (String s) -> s.isEmpty()).build();
final JavaTemplate before2 = JavaTemplate.compile(this, "before2", (JavaTemplate.F1<?, ?>) (String s) -> s.isEmpty()).build();
final JavaTemplate after = JavaTemplate.compile(this, "after", (String s) -> s != null && s.length() == 0).build();

@Override
public J visitMethodInvocation(J.MethodInvocation elem, ExecutionContext ctx) {
JavaTemplate.Matcher matcher;
if ((matcher = before.matcher(getCursor())).find()) {
if (new org.openrewrite.java.template.MethodInvocationMatcher().matches((Expression) matcher.parameter(0))) {
return super.visitMethodInvocation(elem, ctx);
}
doAfterVisit(new org.openrewrite.java.ShortenFullyQualifiedTypeReferences().getVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParenthesesVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.SimplifyBooleanExpressionVisitor());
return after.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0), matcher.parameter(0));
}
if ((matcher = before2.matcher(getCursor())).find()) {
if (!new org.openrewrite.java.template.MethodInvocationMatcher().matches((Expression) matcher.parameter(0))) {
return super.visitMethodInvocation(elem, ctx);
}
doAfterVisit(new org.openrewrite.java.ShortenFullyQualifiedTypeReferences().getVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParenthesesVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.SimplifyBooleanExpressionVisitor());
return after.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0), matcher.parameter(0));
}
return super.visitMethodInvocation(elem, ctx);
}

};
return javaVisitor;
}
}

}
18 changes: 11 additions & 7 deletions src/test/resources/recipes/NestedPreconditionsRecipe.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package foo;

import org.openrewrite.ExecutionContext;
Expand Down Expand Up @@ -38,23 +37,28 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
@Override
public J visitExpression(Expression elem, ExecutionContext ctx) {
JavaTemplate.Matcher matcher;
if ((matcher = hashMap.matcher(getCursor())).find() || (matcher = linkedHashMap.matcher(getCursor())).find()) {
maybeRemoveImport("java.util.LinkedHashMap");
if ((matcher = hashMap.matcher(getCursor())).find()) {
maybeRemoveImport("java.util.HashMap");
maybeAddImport("java.util.Hashtable");
doAfterVisit(new org.openrewrite.java.ShortenFullyQualifiedTypeReferences().getVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParenthesesVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.SimplifyBooleanExpressionVisitor());
return hashtable.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0));
}
if ((matcher = linkedHashMap.matcher(getCursor())).find()) {
maybeRemoveImport("java.util.LinkedHashMap");
maybeAddImport("java.util.Hashtable");
doAfterVisit(new org.openrewrite.java.ShortenFullyQualifiedTypeReferences().getVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.UnnecessaryParenthesesVisitor());
doAfterVisit(new org.openrewrite.java.cleanup.SimplifyBooleanExpressionVisitor());
return hashtable.apply(getCursor(), elem.getCoordinates().replace(), matcher.parameter(0));
}
return super.visitExpression(elem, ctx);
}

};
return Preconditions.check(
Preconditions.or(
Preconditions.and(new UsesType<>("java.util.HashMap", true), new UsesType<>("java.util.Map", true)),
Preconditions.and(new UsesType<>("java.util.LinkedHashMap", true), new UsesType<>("java.util.Map", true))),
Preconditions.or(Preconditions.and(new UsesType<>("java.util.HashMap", true), new UsesType<>("java.util.Map", true)), Preconditions.and(new UsesType<>("java.util.LinkedHashMap", true), new UsesType<>("java.util.Map", true))),
javaVisitor);
}
}
}
Loading