Skip to content

Commit

Permalink
Merge pull request #117 from openrewrite/java-template-only
Browse files Browse the repository at this point in the history
Adjust to new OpenRewrite 8.0 `JavaTemplate` API
  • Loading branch information
kunli2 authored Jun 1, 2023
2 parents d267c8f + 0f1da8f commit 9e15e8a
Show file tree
Hide file tree
Showing 36 changed files with 197 additions and 243 deletions.
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies {

testImplementation("org.openrewrite:rewrite-groovy")
testImplementation("org.junit-pioneer:junit-pioneer:2.0.0")
testImplementation("junit:junit:4.13.2")

testRuntimeOnly("org.openrewrite:rewrite-java-17")
testRuntimeOnly("com.google.code.findbugs:jsr305:latest.release")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Set<String> getTags() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
final JavaTemplate template = JavaTemplate.builder("private static final long serialVersionUID = 1;").context(this::getCursor).build();
final JavaTemplate template = JavaTemplate.builder("private static final long serialVersionUID = 1;").contextSensitive().build();

@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) {
Expand Down Expand Up @@ -90,7 +90,7 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
return s;
})));
if (needsSerialVersionId.get()) {
c = c.withTemplate(template, getCursor(), c.getBody().getCoordinates().firstStatement());
c = template.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement());
}
return c;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
JavaType.FullyQualified fqt = TypeUtils.asFullyQualified(mi.getSelect().getType());
if (fqt != null) {
String templateString = "#{any(" + fqt.getFullyQualifiedName() + ")}.get() == #{any(" + fqt.getFullyQualifiedName() + ")}.get()";
return mi.withTemplate(JavaTemplate.builder(templateString)
.imports(fqt.getFullyQualifiedName()).build(),
getCursor(), mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0));
return JavaTemplate.builder(templateString)
.imports(fqt.getFullyQualifiedName()).build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0));
}
}
return mi;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,8 @@ public Expression visitExpression(Expression expression, ExecutionContext ctx) {
Expression e = (Expression) super.visitExpression(expression, ctx);
if (TypeUtils.isOfClassType(e.getType(), "java.lang.Boolean")) {
if (isControlExpression(expression)) {
return e.withTemplate(
JavaTemplate.builder("Boolean.TRUE.equals(#{any(java.lang.Boolean)})").build(),
getCursor(),
e.getCoordinates().replace(),
e
);
return JavaTemplate.apply("Boolean.TRUE.equals(#{any(java.lang.Boolean)})",
updateCursor(e), e.getCoordinates().replace(), e);
}
}
return e;
Expand All @@ -74,12 +70,8 @@ public Expression visitExpression(Expression expression, ExecutionContext ctx) {
public J visitUnary(J.Unary unary, ExecutionContext executionContext) {
J.Unary un = (J.Unary) super.visitUnary(unary, executionContext);
if (J.Unary.Type.Not == un.getOperator() && TypeUtils.isOfClassType(un.getExpression().getType(), "java.lang.Boolean")) {
return un.withTemplate(
JavaTemplate.builder("Boolean.FALSE.equals(#{any(java.lang.Boolean)})").build(),
getCursor(),
un.getCoordinates().replace(),
un.getExpression()
);
return JavaTemplate.apply("Boolean.FALSE.equals(#{any(java.lang.Boolean)})",
updateCursor(un), un.getCoordinates().replace(), un.getExpression());
}
return un;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,17 @@ public Duration getEstimatedEffortPerOccurrence() {
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>("java.math.BigDecimal", false), new JavaIsoVisitor<ExecutionContext>() {
private final JavaTemplate twoArgDivide = JavaTemplate.builder("#{any(java.math.BigDecimal)}, #{}")
.context(this::getCursor)
.contextSensitive()
.imports("java.math.RoundingMode")
.build();

private final JavaTemplate twoArgScale = JavaTemplate.builder("#{any(int)}, #{}")
.context(this::getCursor)
.contextSensitive()
.imports("java.math.RoundingMode")
.build();

private final JavaTemplate threeArg = JavaTemplate.builder("#{any(java.math.BigDecimal)}, #{any(int)}, #{}")
.context(this::getCursor)
.contextSensitive()
.imports("java.math.RoundingMode").build();

@Override
Expand All @@ -83,25 +83,22 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
if (roundingModeEnum == null) {
return m;
}
m = m.withTemplate(twoArgDivide, getCursor(), m.getCoordinates().replaceArguments(),
m.getArguments().get(0), roundingModeEnum);
m = twoArgDivide.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), roundingModeEnum);
maybeAddImport("java.math.RoundingMode");
} else if (BIG_DECIMAL_SET_SCALE.matches(m) && isConvertibleBigDecimalConstant(m.getArguments().get(1))) {
String roundingModeEnum = getTemplateText(m.getArguments().get(1));
if (roundingModeEnum == null) {
return m;
}
m = m.withTemplate(twoArgScale, getCursor(), m.getCoordinates().replaceArguments(),
m.getArguments().get(0), roundingModeEnum);
m = twoArgScale.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), roundingModeEnum);
maybeAddImport("java.math.RoundingMode");
} else if (BIG_DECIMAL_DIVIDE_WITH_SCALE.matches(m) &&
isConvertibleBigDecimalConstant(m.getArguments().get(2))) {
String roundingModeEnum = getTemplateText(m.getArguments().get(2));
if (roundingModeEnum == null) {
return m;
}
m = m.withTemplate(threeArg, getCursor(), m.getCoordinates().replaceArguments(),
m.getArguments().get(0), m.getArguments().get(1), roundingModeEnum);
m = threeArg.apply(updateCursor(m), m.getCoordinates().replaceArguments(), m.getArguments().get(0), m.getArguments().get(1), roundingModeEnum);
maybeAddImport("java.math.RoundingMode");
}
return m;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,11 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
executionContext.putMessage("REMOVE_UNARY_NOT", parent.getValue());
}
String code = "#{any()} " + (isNot ? "!=" : "==") + " #{any()}";
return autoFormat(m.withTemplate(
JavaTemplate
.builder(code)
.context(getCursor())
.build(),
getCursor(),
m.getCoordinates().replace(),
m.getSelect(), m.getArguments().get(0)
), executionContext);
return autoFormat(JavaTemplate
.builder(code)
.contextSensitive()
.build()
.apply(updateCursor(m), m.getCoordinates().replace(), m.getSelect(), m.getArguments().get(0)), executionContext);
}
return m;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.openrewrite.staticanalysis;

import org.openrewrite.Cursor;
import org.openrewrite.Incubating;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
Expand Down Expand Up @@ -45,8 +46,8 @@ private static class ChangeCovariantEqualsMethodVisitor<P> extends JavaIsoVisito
private static final AnnotationMatcher OVERRIDE_ANNOTATION = new AnnotationMatcher("@java.lang.Override");
private static final String EQUALS_BODY_PREFIX_TEMPLATE =
"if (#{} == this) return true;\n" +
"if (#{} == null || getClass() != #{}.getClass()) return false;\n" +
"#{} #{} = (#{}) #{};\n";
"if (#{} == null || getClass() != #{}.getClass()) return false;\n" +
"#{} #{} = (#{}) #{};\n";

private final J.ClassDeclaration enclosingClass;

Expand All @@ -69,16 +70,14 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P

String ecfqn = type.getFullyQualifiedName();
if (new MethodMatcher(ecfqn + " equals(" + ecfqn + ")").matches(m, enclosingClass) &&
m.hasModifier(J.Modifier.Type.Public) &&
m.getReturnTypeExpression() != null &&
JavaType.Primitive.Boolean.equals(m.getReturnTypeExpression().getType())) {
m.hasModifier(J.Modifier.Type.Public) &&
m.getReturnTypeExpression() != null &&
JavaType.Primitive.Boolean.equals(m.getReturnTypeExpression().getType())) {

if (m.getAllAnnotations().stream().noneMatch(OVERRIDE_ANNOTATION::matches)) {
m = m.withTemplate(
JavaTemplate.builder("@Override").build(),
getCursor(),
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))
);
m = JavaTemplate.builder("@Override").build()
.apply(updateCursor(m),
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
}

/*
Expand All @@ -88,18 +87,17 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P
*/
J.VariableDeclarations.NamedVariable oldParamName = ((J.VariableDeclarations) m.getParameters().iterator().next()).getVariables().iterator().next();
String paramName = "obj".equals(oldParamName.getSimpleName()) ? "other" : "obj";
m = m.withTemplate(
JavaTemplate.builder("Object #{}").context(() -> getCursor().getParentOrThrow()).build(),
getCursor(),
m.getCoordinates().replaceParameters(),
paramName);
m = JavaTemplate.builder("Object #{}").contextSensitive().build()
.apply(updateCursor(m),
m.getCoordinates().replaceParameters(),
paramName);

/*
* We'll prepend this type-check and type-cast to the beginning of the existing
* equals(..) method body statements, and let the existing equals(..) method definition continue
* with the logic doing what it was doing.
*/
JavaTemplate equalsBodySnippet = JavaTemplate.builder(EQUALS_BODY_PREFIX_TEMPLATE).context(this::getCursor).build();
JavaTemplate equalsBodySnippet = JavaTemplate.builder(EQUALS_BODY_PREFIX_TEMPLATE).contextSensitive().build();

assert m.getBody() != null;
Object[] params = new Object[]{
Expand All @@ -112,9 +110,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P
paramName
};

m = m.withTemplate(
equalsBodySnippet,
getCursor(),
m = equalsBodySnippet.apply(new Cursor(getCursor().getParent(), m),
m.getBody().getStatements().get(0).getCoordinates().before(),
params);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@
public class EmptyBlockVisitor<P> extends JavaIsoVisitor<P> {
EmptyBlockStyle emptyBlockStyle;
JavaTemplate throwException = JavaTemplate.builder("throw new #{}(#{any(String)});")
.context(this::getCursor)
.contextSensitive()
.imports("java.io.UncheckedIOException")
.build();
JavaTemplate continueStatement = JavaTemplate.builder("continue;").context(this::getCursor).build();
JavaTemplate continueStatement = JavaTemplate.builder("continue;").contextSensitive().build();

@Override
public J.WhileLoop visitWhileLoop(J.WhileLoop whileLoop, P p) {
J.WhileLoop w = super.visitWhileLoop(whileLoop, p);

if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralWhile()) && isEmptyBlock(w.getBody())) {
J.Block body = (J.Block) w.getBody();
w = w.withTemplate(continueStatement, getCursor(), body.getCoordinates().lastStatement());
w = continueStatement.apply(updateCursor(w), body.getCoordinates().lastStatement());
}

return w;
Expand All @@ -65,7 +65,7 @@ public J.DoWhileLoop visitDoWhileLoop(J.DoWhileLoop doWhileLoop, P p) {

if (Boolean.TRUE.equals(emptyBlockStyle.getLiteralWhile()) && isEmptyBlock(w.getBody())) {
J.Block body = (J.Block) w.getBody();
w = w.withTemplate(continueStatement, getCursor(), body.getCoordinates().lastStatement());
w = continueStatement.apply(updateCursor(w), body.getCoordinates().lastStatement());
}

return w;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(GET_BYTES), new JavaIsoVisitor<ExecutionContext>() {
final JavaTemplate WITH_ENCODING = JavaTemplate
.builder("getBytes(StandardCharsets.#{})")
.context(this::getCursor)
.contextSensitive()
.imports("java.nio.charset.StandardCharsets")
.build();

Expand All @@ -62,8 +62,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
J.MethodInvocation m = super.visitMethodInvocation(method, ctx);
if (GET_BYTES.matches(method)) {
maybeAddImport("java.nio.charset.StandardCharsets");
m = m.withTemplate(WITH_ENCODING, getCursor(), method.getCoordinates().replaceMethod(),
encoding == null ? "UTF_8" : encoding);
m = WITH_ENCODING.apply(updateCursor(m), m.getCoordinates().replaceMethod(), encoding == null ? "UTF_8" : encoding);
}
return m;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,10 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
}
}
if (!hasFinalUninitializedFieldVar && !hasNoArgsConstructor(cd) && parentClassHasNoArgsConstructor(cd)) {
cd = cd.withTemplate(JavaTemplate.builder("public " + cd.getSimpleName() + "() {}").context(getCursor()).build(), getCursor(), cd.getBody().getCoordinates().lastStatement());
cd = JavaTemplate.builder("public " + cd.getSimpleName() + "() {}")
.contextSensitive()
.build()
.apply(updateCursor(cd), cd.getBody().getCoordinates().lastStatement());
if (firstMethodDeclarationIndex != null) {
statements.add(firstMethodDeclarationIndex, cd.getBody().getStatements().remove(cd.getBody().getStatements().size() - 1));
cd = cd.withBody(cd.getBody().withStatements(statements));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,10 @@ private static class UtilityClassWithImplicitDefaultConstructorVisitor<P> extend
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, P p) {
if (UtilityClassMatcher.hasImplicitDefaultConstructor(classDecl) &&
!J.ClassDeclaration.Kind.Type.Enum.equals(classDecl.getKind())) {
classDecl = classDecl.withTemplate(JavaTemplate.builder("private #{}() {}").context(getCursor()).build(),
getCursor(),
classDecl.getBody().getCoordinates().lastStatement(),
classDecl.getSimpleName()
);
classDecl = JavaTemplate.builder("private #{}() {}")
.contextSensitive()
.build()
.apply(getCursor(), classDecl.getBody().getCoordinates().lastStatement(), classDecl.getSimpleName());
}
return classDecl;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,12 @@ public J.Binary visitBinary(J.Binary binary, ExecutionContext ctx) {
b.getRight() instanceof J.Literal && isValueNotCompliant((J.Literal) b.getRight())) {

J.MethodInvocation m = (J.MethodInvocation) b.getLeft();
b = b.withLeft(m.withTemplate(JavaTemplate.builder("#{any(java.lang.String)}, #{any(int)}").build(),
getCursor(),
m.getCoordinates().replaceArguments(),
m.getArguments().get(0),
b.getRight()));
Cursor cursor = new Cursor(getCursor(), b.getLeft());
b = b.withLeft(JavaTemplate.builder("#{any(java.lang.String)}, #{any(int)}").build()
.apply(cursor,
m.getCoordinates().replaceArguments(),
m.getArguments().get(0),
b.getRight()));

b = b.withRight(new J.Literal(
Tree.randomId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ public J visitBinary(J.Binary binary, ExecutionContext ctx) {
boolean isGreaterThanNegativeOne = asBinary.getOperator() == J.Binary.Type.GreaterThan && "-1".equals(valueSource);
boolean isGreaterThanOrEqualToZero = asBinary.getOperator() == J.Binary.Type.GreaterThanOrEqual && "0".equals(valueSource);
if (isGreaterThanNegativeOne || isGreaterThanOrEqualToZero) {
j = mi.withTemplate(STRING_INDEX_MATCHER.matches(mi) ? stringContains : listContains,
getCursor(), mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0)).withPrefix(asBinary.getPrefix());
Cursor cursor = new Cursor(updateCursor(asBinary), asBinary.getLeft());
j = (STRING_INDEX_MATCHER.matches(mi) ? stringContains : listContains)
.apply(cursor, mi.getCoordinates().replace(), mi.getSelect(), mi.getArguments().get(0))
.withPrefix(asBinary.getPrefix());
}
}
}
Expand Down
Loading

0 comments on commit 9e15e8a

Please sign in to comment.