-
Notifications
You must be signed in to change notification settings - Fork 93
Add AnnotateNullableMethods recipe
#364
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
Merged
timtebeek
merged 20 commits into
openrewrite:main
from
nielsdebruin:add-nullable-annotations
Oct 25, 2024
Merged
Changes from 7 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
8bf01d4
Add AnnotateNullableMethodsRecipe
ae890d7
Apply suggestions from code review
timtebeek efbda59
Merge branch 'main' into add-nullable-annotations
timtebeek 1a91452
Apply suggestions from code review
nielsdebruin 0bfebc4
Update src/test/java/org/openrewrite/staticanalysis/AnnotateNullableM…
nielsdebruin e2413d1
Apply suggestions from code review
nielsdebruin 21873f9
Process PR feedback
791b7fd
Apply formatting suggestions
timtebeek f2eb66a
Slight polish
timtebeek 341a056
Further polish
timtebeek 90a3e73
Polish tests
timtebeek 0de3a5f
Verify handling of J.NewClass with nested return
timtebeek 717a259
Update src/main/java/org/openrewrite/staticanalysis/AnnotateNullableM…
timtebeek 44cd307
Only visit method body, to avoid arguments with a nested return
timtebeek f3d71d1
Reduce using the updated parent tree cursor
timtebeek 4382ab2
Fix check for static return annotations
nielsdebruin f9a7d0b
Merge branch 'main' into add-nullable-annotations
timtebeek b7c993e
Insert a qualified annotation that we then possibly shorten
timtebeek 0e0e263
Limit scope of import fix
nielsdebruin aa52bfb
Add extra null check
nielsdebruin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
183 changes: 183 additions & 0 deletions
183
src/main/java/org/openrewrite/staticanalysis/AnnotateNullableMethods.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| /* | ||
| * Copyright 2024 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.staticanalysis; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import org.openrewrite.Cursor; | ||
| import org.openrewrite.ExecutionContext; | ||
| import org.openrewrite.Recipe; | ||
| import org.openrewrite.TreeVisitor; | ||
| import org.openrewrite.java.*; | ||
| import org.openrewrite.java.service.AnnotationService; | ||
| import org.openrewrite.java.tree.Expression; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaType; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
|
|
||
| public class AnnotateNullableMethods extends Recipe { | ||
|
|
||
| private static final String NULLABLE_ANN_CLASS = "org.jspecify.annotations.Nullable"; | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| private static final AnnotationMatcher NULLABLE_ANNOTATION_MATCHER = | ||
| new AnnotationMatcher("@" + NULLABLE_ANN_CLASS); | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Annotate methods which may return null with @Nullable"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Automatically adds the @org.jspecify.annotation.Nullable to non-private methods" + | ||
| "that may return null. This recipe scans for methods that do not already have a @Nullable" + | ||
| "annotation and checks their return statements for potential null values. It also" + | ||
| "identifies known methods from standard libraries that may return null, such as methods" + | ||
| "from Map, Queue, Deque, NavigableSet, and Spliterator. The return of streams, or lambdas" + | ||
| " are not taken into account."; | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new AnnotateNullableMethodsVisitor(); | ||
| } | ||
|
|
||
| private static class AnnotateNullableMethodsVisitor extends JavaIsoVisitor<ExecutionContext> { | ||
| AtomicBoolean annotatedNullable = new AtomicBoolean(false); | ||
|
|
||
| @Override | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration md, ExecutionContext ctx) { | ||
| if (!md.hasModifier(J.Modifier.Type.Public)) { | ||
| return md; | ||
| } | ||
|
|
||
| if (md.getMethodType() != null && md.getMethodType().getReturnType() instanceof JavaType.Primitive) { | ||
| return md; | ||
| } | ||
|
|
||
| if (service(AnnotationService.class).matches(getCursor(), NULLABLE_ANNOTATION_MATCHER)) { | ||
| return md; | ||
| } | ||
|
|
||
| md = super.visitMethodDeclaration(md, ctx); | ||
| updateCursor(md); | ||
|
|
||
| if (FindNullableReturnStatements.find(md).get()) { | ||
| maybeAddImport(NULLABLE_ANN_CLASS); | ||
| if (!annotatedNullable.getAndSet(true)) { | ||
| doAfterVisit(new NullableOnMethodReturnType().getVisitor()); | ||
| } | ||
| return JavaTemplate.builder("@Nullable") | ||
| .imports(NULLABLE_ANN_CLASS) | ||
| .javaParser(JavaParser.fromJavaVersion().classpath("jspecify")) | ||
| .build() | ||
| .apply(getCursor(), md.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))); | ||
| } | ||
| return md; | ||
| } | ||
| } | ||
|
|
||
| @AllArgsConstructor | ||
| private static class FindNullableReturnStatements extends JavaIsoVisitor<AtomicBoolean> { | ||
| private static final List<MethodMatcher> KNOWN_NULLABLE_METHODS = getMatchersKnownNullableMethods(); | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| static AtomicBoolean find(J subtree) { | ||
| return new FindNullableReturnStatements().reduce(subtree, new AtomicBoolean()); | ||
| } | ||
|
|
||
| private static List<MethodMatcher> getMatchersKnownNullableMethods() { | ||
| return Arrays.asList( | ||
| new MethodMatcher("java.util.Map computeIfAbsent(..)"), | ||
| new MethodMatcher("java.util.Map computeIfPresent(..)"), | ||
| new MethodMatcher("java.util.Map get(..)"), | ||
| new MethodMatcher("java.util.Map merge(..)"), | ||
| new MethodMatcher("java.util.Map put(..)"), | ||
| new MethodMatcher("java.util.Map putIfAbsent(..)"), | ||
|
|
||
| new MethodMatcher("java.util.Queue poll(..)"), | ||
| new MethodMatcher("java.util.Queue peek(..)"), | ||
|
|
||
| new MethodMatcher("java.util.Deque peekFirst(..)"), | ||
| new MethodMatcher("java.util.Deque pollFirst(..)"), | ||
| new MethodMatcher("java.util.Deque peekLast(..)"), | ||
|
|
||
| new MethodMatcher("java.util.NavigableSet lower(..)"), | ||
| new MethodMatcher("java.util.NavigableSet floor(..)"), | ||
| new MethodMatcher("java.util.NavigableSet ceiling(..)"), | ||
| new MethodMatcher("java.util.NavigableSet higher(..)"), | ||
| new MethodMatcher("java.util.NavigableSet pollFirst(..)"), | ||
| new MethodMatcher("java.util.NavigableSet pollLast(..)"), | ||
|
|
||
| new MethodMatcher("java.util.NavigableMap lowerEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap floorEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap ceilingEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap higherEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap lowerKey(..)"), | ||
| new MethodMatcher("java.util.NavigableMap floorKey(..)"), | ||
| new MethodMatcher("java.util.NavigableMap ceilingKey(..)"), | ||
| new MethodMatcher("java.util.NavigableMap higherKey(..)"), | ||
| new MethodMatcher("java.util.NavigableMap firstEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap lastEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap pollFirstEntry(..)"), | ||
| new MethodMatcher("java.util.NavigableMap pollLastEntry(..)"), | ||
|
|
||
| new MethodMatcher("java.util.Spliterator trySplit(..)") | ||
| ); | ||
| } | ||
|
|
||
| @Override | ||
| public J.Return visitReturn(J.Return retrn, AtomicBoolean containsNullableReturn) { | ||
| if (containsNullableReturn.get()) { | ||
| return retrn; | ||
| } | ||
|
|
||
| J.Return r = super.visitReturn(retrn, containsNullableReturn); | ||
| updateCursor(r); | ||
|
|
||
| // If the returns is contained within a lambda statement, we don't consider it. | ||
| Cursor ex = getCursor().dropParentUntil(e -> e instanceof J.MethodDeclaration || e instanceof J.Lambda); | ||
| if (!(ex.getValue() instanceof J.MethodDeclaration)) { | ||
| return r; | ||
| } | ||
|
|
||
| if (r.getExpression() != null && maybeIsNull(r.getExpression())) { | ||
| containsNullableReturn.set(true); | ||
| } | ||
|
|
||
| return r; | ||
| } | ||
|
|
||
| private boolean maybeIsNull(Expression returnExpression) { | ||
| if (returnExpression instanceof J.Literal && ((J.Literal) returnExpression).getValue() == null) { | ||
| return true; | ||
| } else if (returnExpression instanceof J.MethodInvocation) { | ||
| return isKnowNullableMethod((J.MethodInvocation) returnExpression); | ||
| } | ||
| return false; | ||
| } | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| private boolean isKnowNullableMethod(J.MethodInvocation methodInvocation) { | ||
| for (MethodMatcher m : KNOWN_NULLABLE_METHODS) { | ||
| if (m.matches(methodInvocation)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
197 changes: 197 additions & 0 deletions
197
src/test/java/org/openrewrite/staticanalysis/AnnotateNullableMethodsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| /* | ||
| * Copyright 2024 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.staticanalysis; | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| import org.junit.jupiter.api.Test; | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import org.openrewrite.DocumentExample; | ||
| import org.openrewrite.java.JavaParser; | ||
| import org.openrewrite.test.RecipeSpec; | ||
| import org.openrewrite.test.RewriteTest; | ||
|
|
||
| import static org.openrewrite.java.Assertions.java; | ||
|
|
||
| class AnnotateNullableMethodsTest implements RewriteTest { | ||
| @Override | ||
| public void defaults(RecipeSpec spec) { | ||
| spec.recipe(new AnnotateNullableMethods()).parser(JavaParser.fromJavaVersion().classpath("jspecify")); | ||
| } | ||
|
|
||
| @DocumentExample | ||
| @Test | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| void methodReturnsNullLiteral() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new AnnotateNullableMethods()), | ||
| //language=java | ||
| java( | ||
| """ | ||
| public class Test { | ||
|
|
||
| public String getString() { | ||
| return null; | ||
| } | ||
|
|
||
| public String getStringWithMultipleReturn() { | ||
| if (System.currentTimeMillis() % 2 == 0) { | ||
| return "Not null"; | ||
| } | ||
| return null; | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| public class Test { | ||
|
|
||
| public @Nullable String getString() { | ||
| return null; | ||
| } | ||
|
|
||
| public @Nullable String getStringWithMultipleReturn() { | ||
| if (System.currentTimeMillis() % 2 == 0) { | ||
| return "Not null"; | ||
| } | ||
| return null; | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void methodReturnNullButIsAlreadyAnnotated() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new AnnotateNullableMethods()), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| public class Test { | ||
| public @Nullable String getString() { | ||
| return null; | ||
| } | ||
|
|
||
| public @Nullable String getStringWithMultipleReturn() { | ||
| if (System.currentTimeMillis() % 2 == 0) { | ||
| return "Not null"; | ||
| } | ||
| return null; | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void methodDoesNotReturnNull() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new AnnotateNullableMethods()), | ||
| //language=java | ||
| java( | ||
| """ | ||
| package org.example; | ||
|
|
||
| public class Test { | ||
| public String getString() { | ||
| return "Hello"; | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void methodReturnsDelegateKnowNullableMethod() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new AnnotateNullableMethods()), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| public class Test { | ||
|
|
||
| public String getString() { | ||
| Map<String, String> map = new HashMap<>(); | ||
| return map.get("key"); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| public class Test { | ||
|
|
||
| public @Nullable String getString() { | ||
| Map<String, String> map = new HashMap<>(); | ||
| return map.get("key"); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void methodWithLambdaShouldNotBeAnnotated() { | ||
| rewriteRun( | ||
| //language=java | ||
| java( | ||
| """ | ||
| import java.util.stream.Stream; | ||
| class A { | ||
| public Runnable getRunnable() { | ||
| return () -> null; | ||
| } | ||
|
|
||
| public Integer someStream(){ | ||
| // Stream with lambda class. | ||
| return Stream.of(1, 2, 3) | ||
| .map(i -> {if (i == 2) return null; else return i;}) | ||
| .reduce((a, b) -> a + b) | ||
| .orElse(null); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void privateMethodsShouldNotBeAnnotated() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new AnnotateNullableMethods()), | ||
| //language=java | ||
| java( | ||
| """ | ||
| public class Test { | ||
| private String getString() { | ||
| return null; | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.