Skip to content

Commit

Permalink
New AnnotationService (#3837)
Browse files Browse the repository at this point in the history
* New `AnnotationService`

* Deprecate `getAllAnnotations()` methods

* Optimize `JavaVisitor#service()`

* Optimize `JavaVisitor#service()`

* Polish

* Add `@deprecated` Javadoc tags
  • Loading branch information
knutwannheden authored Dec 21, 2023
1 parent 6892a98 commit 946e627
Show file tree
Hide file tree
Showing 10 changed files with 196 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.openrewrite.ExecutionContext;
import org.openrewrite.Issue;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.SourceSpec;

Expand Down Expand Up @@ -267,8 +268,9 @@ public class TypeAnnotationTest {
spec -> spec.afterRecipe(cu -> new JavaIsoVisitor<>() {
@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Object o) {
assertThat(method.getAllAnnotations()).hasSize(1);
assertThat(method.getAllAnnotations().get(0).getSimpleName()).isEqualTo("Deprecated");
AnnotationService service = cu.service(AnnotationService.class);
assertThat(service.getAllAnnotations(method)).hasSize(1);
assertThat(service.getAllAnnotations(method).get(0).getSimpleName()).isEqualTo("Deprecated");
return method;
}
}.visit(cu, 0))
Expand Down Expand Up @@ -308,26 +310,27 @@ public class A {
public @interface Multi2 {}
""",
spec -> spec.afterRecipe(cu -> {
AnnotationService service = cu.service(AnnotationService.class);
J.VariableDeclarations field = (J.VariableDeclarations) cu.getClasses().get(0).getBody().getStatements().get(0);
assertThat(field.getAllAnnotations()).satisfiesExactly(
assertThat(service.getAllAnnotations(field)).satisfiesExactly(
leading -> assertThat(leading.getSimpleName()).isEqualTo("Leading")
);
J.ParameterizedType fieldType = (J.ParameterizedType) field.getTypeExpression();
assertThat(fieldType).isNotNull();
J.AnnotatedType annotatedType = (J.AnnotatedType) fieldType.getClazz();
assertThat(annotatedType.getAllAnnotations()).satisfiesExactly(
assertThat(service.getAllAnnotations(annotatedType)).satisfiesExactly(
multi1 -> assertThat(multi1.getSimpleName()).isEqualTo("Multi1"),
multi2 -> assertThat(multi2.getSimpleName()).isEqualTo("Multi2")
);

J.MethodDeclaration method = (J.MethodDeclaration) cu.getClasses().get(0).getBody().getStatements().get(1);
assertThat(method.getAllAnnotations()).satisfiesExactly(
assertThat(service.getAllAnnotations(method)).satisfiesExactly(
leading -> assertThat(leading.getSimpleName()).isEqualTo("Leading")
);
J.ParameterizedType returnType = (J.ParameterizedType) method.getReturnTypeExpression();
assertThat(returnType).isNotNull();
annotatedType = (J.AnnotatedType) returnType.getClazz();
assertThat(annotatedType.getAllAnnotations()).satisfiesExactly(
assertThat(service.getAllAnnotations(annotatedType)).satisfiesExactly(
multi1 -> assertThat(multi1.getSimpleName()).isEqualTo("Multi1"),
multi2 -> assertThat(multi2.getSimpleName()).isEqualTo("Multi2")
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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.service;

import org.junit.jupiter.api.Test;
import org.openrewrite.test.RewriteTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.java.Assertions.java;

public class AnnotationServiceTest implements RewriteTest {

@Test
void classAnnotations() {
rewriteRun(
java(
"""
import javax.annotation.processing.Generated;
@SuppressWarnings("all")
public @Generated("foo") class T {}
""",
spec -> spec.afterRecipe(cu -> {
AnnotationService service = cu.service(AnnotationService.class);
assertThat(service.getAllAnnotations(cu)).isEmpty();
assertThat(service.getAllAnnotations(cu.getClasses().get(0))).satisfiesExactly(
ann0 -> assertThat(ann0.getSimpleName()).isEqualTo("SuppressWarnings"),
ann1 -> assertThat(ann1.getSimpleName()).isEqualTo("Generated")
);
})
)
);
}
}
25 changes: 20 additions & 5 deletions rewrite-java/src/main/java/org/openrewrite/java/JavaVisitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.*;

@SuppressWarnings("unused")
public class JavaVisitor<P> extends TreeVisitor<J, P> {
Expand Down Expand Up @@ -137,7 +135,24 @@ public void maybeAddImport(@Nullable String packageName, String typeName, @Nulla

@Incubating(since = "8.2.0")
public <S> S service(Class<S> service) {
return getCursor().firstEnclosingOrThrow(JavaSourceFile.class).service(service);
for (Cursor c = getCursor(); c.getParent() != null; c = c.getParent()) {
Map<Class<?>, Object> services = c.getMessage("__services");
if (services != null && services.containsKey(service)) {
//noinspection unchecked
return (S) services.get(service);
}
if (c.getValue() instanceof JavaSourceFile) {
S found = ((JavaSourceFile) c.getValue()).service(service);
services = getCursor().getMessage("__services");
if (services == null) {
c.putMessage("__services", services = new HashMap<>());
}
services.put(service, found);
return found;
}
}

throw new IllegalArgumentException("No JavaSourceFile parent found");
}

public void maybeRemoveImport(@Nullable JavaType.FullyQualified clazz) {
Expand Down Expand Up @@ -660,7 +675,7 @@ public J visitParenthesizedTypeTree(J.ParenthesizedTypeTree parTree, P p) {
return temp;
} else {
//noinspection unchecked
t = t.withParenthesizedType((J.Parentheses<TypeTree>)temp);
t = t.withParenthesizedType((J.Parentheses<TypeTree>) temp);
}
return t;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;
Expand All @@ -30,6 +31,9 @@
@Value
@EqualsAndHashCode(callSuper = true)
public class RemoveImplements extends Recipe {

private static final AnnotationMatcher OVERRIDE_MATCHER = new AnnotationMatcher("java.lang.Override");

@Override
public String getDisplayName() {
return "Remove interface implementations";
Expand Down Expand Up @@ -69,8 +73,14 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDeclarat
return super.visitClassDeclaration(classDeclaration, ctx);
}
}, new JavaIsoVisitor<ExecutionContext>() {
@Nullable
AnnotationService annotationService;

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration cd, ExecutionContext ctx) {
if (annotationService == null) {
annotationService = service(AnnotationService.class);
}
if (!(cd.getType() instanceof JavaType.Class) || cd.getImplements() == null) {
return super.visitClassDeclaration(cd, ctx);
}
Expand Down Expand Up @@ -104,7 +114,8 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration md, Execut
if (md.getName().getType() != null) {
md = md.withName(md.getName().withType(mt));
}
if (md.getAllAnnotations().stream().noneMatch(ann -> isOfClassType(ann.getType(), "java.lang.Override")) || TypeUtils.isOverride(md.getMethodType())) {
assert annotationService != null;
if (!annotationService.matches(md, OVERRIDE_MATCHER) || TypeUtils.isOverride(md.getMethodType())) {
return super.visitMethodDeclaration(md, ctx);
}
md = (J.MethodDeclaration) new RemoveAnnotation("@java.lang.Override").getVisitor().visitNonNull(md, ctx, getCursor().getParentOrThrow());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,24 @@
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.TypeMatcher;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.NameTree;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.SearchResult;

import java.util.Iterator;
import java.util.List;

@Value
@EqualsAndHashCode(callSuper = true)
public class FindDeprecatedClasses extends Recipe {

private static final AnnotationMatcher DEPRECATED_MATCHER = new AnnotationMatcher("java.lang.Deprecated");

@Option(displayName = "Type pattern",
description = "A type pattern that is used to find matching classes.",
example = "org.springframework..*",
Expand Down Expand Up @@ -94,12 +98,10 @@ public <N extends NameTree> N visitTypeName(N nameTree, ExecutionContext ctx) {
Iterator<Object> cursorPath = getCursor().getPath();
while (cursorPath.hasNext()) {
Object ancestor = cursorPath.next();
if (ancestor instanceof J.MethodDeclaration &&
isDeprecated(((J.MethodDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.MethodDeclaration && isDeprecated((J) ancestor)) {
return nameTree;
}
if (ancestor instanceof J.ClassDeclaration &&
isDeprecated(((J.ClassDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.ClassDeclaration && isDeprecated((J) ancestor)) {
return nameTree;
}
}
Expand All @@ -114,13 +116,8 @@ public <N extends NameTree> N visitTypeName(N nameTree, ExecutionContext ctx) {
return nameTree;
}

private boolean isDeprecated(List<J.Annotation> annotations) {
for (J.Annotation annotation : annotations) {
if (TypeUtils.isOfClassType(annotation.getType(), "java.lang.Deprecated")) {
return true;
}
}
return false;
private boolean isDeprecated(J j) {
return service(AnnotationService.class).matches(j, DEPRECATED_MATCHER);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,26 @@
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.TypeMatcher;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.SearchResult;

import java.util.Iterator;
import java.util.List;

import static java.util.Objects.requireNonNull;

@Value
@EqualsAndHashCode(callSuper = true)
public class FindDeprecatedFields extends Recipe {

private static final AnnotationMatcher DEPRECATED_MATCHER = new AnnotationMatcher("java.lang.Deprecated");

@Option(displayName = "Type pattern",
description = "A type pattern that is used to find matching field uses.",
example = "org.springframework..*",
Expand Down Expand Up @@ -98,12 +102,10 @@ public J.Identifier visitIdentifier(J.Identifier identifier, ExecutionContext ct
Iterator<Object> cursorPath = getCursor().getPath();
while (cursorPath.hasNext()) {
Object ancestor = cursorPath.next();
if (ancestor instanceof J.MethodDeclaration &&
isDeprecated(((J.MethodDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.MethodDeclaration && isDeprecated((J) ancestor)) {
return i;
}
if (ancestor instanceof J.ClassDeclaration &&
isDeprecated(((J.ClassDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.ClassDeclaration && isDeprecated((J) ancestor)) {
return i;
}
}
Expand All @@ -117,13 +119,8 @@ public J.Identifier visitIdentifier(J.Identifier identifier, ExecutionContext ct
return i;
}

private boolean isDeprecated(List<J.Annotation> annotations) {
for (J.Annotation annotation : annotations) {
if (TypeUtils.isOfClassType(annotation.getType(), "java.lang.Deprecated")) {
return true;
}
}
return false;
private boolean isDeprecated(J j) {
return service(AnnotationService.class).matches(j, DEPRECATED_MATCHER);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,25 @@
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.service.AnnotationService;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.SearchResult;

import java.util.Iterator;
import java.util.List;

import static java.util.Objects.requireNonNull;

@Value
@EqualsAndHashCode(callSuper = true)
public class FindDeprecatedMethods extends Recipe {
private static final AnnotationMatcher DEPRECATED_MATCHER = new AnnotationMatcher("java.lang.Deprecated");

@Option(displayName = "Method pattern",
description = "A method pattern that is used to find matching method invocations.",
example = "java.util.List add(..)",
Expand Down Expand Up @@ -89,12 +92,10 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
Iterator<Object> cursorPath = getCursor().getPath();
while (cursorPath.hasNext()) {
Object ancestor = cursorPath.next();
if (ancestor instanceof J.MethodDeclaration &&
isDeprecated(((J.MethodDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.MethodDeclaration && isDeprecated((J) ancestor)) {
return m;
}
if (ancestor instanceof J.ClassDeclaration &&
isDeprecated(((J.ClassDeclaration) ancestor).getAllAnnotations())) {
if (ancestor instanceof J.ClassDeclaration && isDeprecated((J) ancestor)) {
return m;
}
}
Expand All @@ -107,13 +108,8 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
return m;
}

private boolean isDeprecated(List<J.Annotation> annotations) {
for (J.Annotation annotation : annotations) {
if (TypeUtils.isOfClassType(annotation.getType(), "java.lang.Deprecated")) {
return true;
}
}
return false;
private boolean isDeprecated(J j) {
return service(AnnotationService.class).matches(j, DEPRECATED_MATCHER);
}
});
}
Expand Down
Loading

0 comments on commit 946e627

Please sign in to comment.