Skip to content

Commit

Permalink
Merge branch 'main' into InlineOneTimeUsageVariable
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek authored Dec 4, 2024
2 parents 5aabe65 + b412e1d commit 675f200
Show file tree
Hide file tree
Showing 66 changed files with 2,834 additions and 896 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
insert_final_newline = true
trim_trailing_whitespace = true

[src/test*/java/**.java]
indent_size = 4
ij_continuation_indent_size = 2
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

This project implements a [Rewrite module](https://github.com/openrewrite/rewrite) that fixes SAST like issues automatically. Say goodbye to annoying reports from SonarQube, and hello to a world where they are fixed for you.

Browse [a selection of recipes available through this module in the recipe catalog](https://docs.openrewrite.org/recipes/staticanalysis-1).
Browse [a selection of recipes available through this module in the recipe catalog](https://docs.openrewrite.org/recipes/staticanalysis).

## Contributing

Expand Down
3 changes: 2 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ dependencies {

testImplementation("org.jetbrains:annotations:24.+")
testImplementation("org.openrewrite:rewrite-groovy")
testImplementation("org.junit-pioneer:junit-pioneer:2.0.1")
testImplementation("org.openrewrite:rewrite-test")
testImplementation("org.junit-pioneer:junit-pioneer:2.+")
testImplementation("junit:junit:4.13.2")

testImplementation("com.google.code.gson:gson:latest.release")
Expand Down
4 changes: 2 additions & 2 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
distributionSha256Sum=31c55713e40233a8303827ceb42ca48a47267a0ad4bab9177123121e71524c26
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
distributionSha256Sum=f397b287023acdba1e9f6fc5ea72d22dd63669d59ed4a289a29b1a76eee151c6
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*
* 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 org.jspecify.annotations.Nullable;
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";
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 "Add 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 JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDeclaration, ExecutionContext ctx) {
if (!methodDeclaration.hasModifier(J.Modifier.Type.Public) ||
methodDeclaration.getMethodType() == null ||
methodDeclaration.getMethodType().getReturnType() instanceof JavaType.Primitive ||
service(AnnotationService.class).matches(getCursor(), NULLABLE_ANNOTATION_MATCHER) ||
(methodDeclaration.getReturnTypeExpression() != null &&
service(AnnotationService.class).matches(new Cursor(null, methodDeclaration.getReturnTypeExpression()), NULLABLE_ANNOTATION_MATCHER))) {
return methodDeclaration;
}

J.MethodDeclaration md = super.visitMethodDeclaration(methodDeclaration, ctx);
updateCursor(md);
if (FindNullableReturnStatements.find(md.getBody(), getCursor().getParentTreeCursor())) {
J.MethodDeclaration annotatedMethod = JavaTemplate.builder("@" + NULLABLE_ANN_CLASS)
.javaParser(JavaParser.fromJavaVersion().dependsOn(
"package org.jspecify.annotations;public @interface Nullable {}"))
.build()
.apply(getCursor(), md.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
doAfterVisit(ShortenFullyQualifiedTypeReferences.modifyOnly(annotatedMethod));
return (J.MethodDeclaration) new NullableOnMethodReturnType().getVisitor().visitNonNull(annotatedMethod, ctx, getCursor().getParentTreeCursor());
}
return md;
}
};
}

private static class FindNullableReturnStatements extends JavaIsoVisitor<AtomicBoolean> {

private static final List<MethodMatcher> KNOWN_NULLABLE_METHODS = Arrays.asList(
// These mostly return a nullable current or previous value, which is more often null
new MethodMatcher("java.util.Map get(..)"),
new MethodMatcher("java.util.Map merge(..)"),
new MethodMatcher("java.util.Map put(..)"),
new MethodMatcher("java.util.Map putIfAbsent(..)"),

// These two return the current or computed value, which is less likely to be null in common usage
//new MethodMatcher("java.util.Map computeIfAbsent(..)"),
//new MethodMatcher("java.util.Map computeIfPresent(..)"),

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(..)")
);

static boolean find(@Nullable J subtree, Cursor parentTreeCursor) {
return new FindNullableReturnStatements().reduce(subtree, new AtomicBoolean(), parentTreeCursor).get();
}

@Override
public J.Lambda visitLambda(J.Lambda lambda, AtomicBoolean atomicBoolean) {
// Do not evaluate return statements in lambdas
return lambda;
}

@Override
public J.NewClass visitNewClass(J.NewClass newClass, AtomicBoolean atomicBoolean) {
// Do not evaluate return statements in new class expressions
return newClass;
}

@Override
public J.Return visitReturn(J.Return retrn, AtomicBoolean found) {
if (found.get()) {
return retrn;
}
J.Return r = super.visitReturn(retrn, found);
found.set(maybeIsNull(r.getExpression()));
return r;
}

private boolean maybeIsNull(@Nullable Expression returnExpression) {
if (returnExpression instanceof J.Literal) {
return ((J.Literal) returnExpression).getValue() == null;
}
if (returnExpression instanceof J.MethodInvocation) {
return isKnowNullableMethod((J.MethodInvocation) returnExpression);
}
return false;
}

private boolean isKnowNullableMethod(J.MethodInvocation methodInvocation) {
for (MethodMatcher m : KNOWN_NULLABLE_METHODS) {
if (m.matches(methodInvocation)) {
return true;
}
}
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,18 @@

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AtomicPrimitiveEqualsUsesGet extends Recipe {

private static final Set<String> ATOMIC_PRIMITIVE_TYPES = new HashSet<>(Arrays.asList(
"java.util.concurrent.atomic.AtomicBoolean",
"java.util.concurrent.atomic.AtomicInteger",
"java.util.concurrent.atomic.AtomicLong"
));
public static final String ATOMIC_ATOMIC_BOOLEAN = "java.util.concurrent.atomic.AtomicBoolean";
public static final String ATOMIC_ATOMIC_INTEGER = "java.util.concurrent.atomic.AtomicInteger";
public static final String ATOMIC_ATOMIC_LONG = "java.util.concurrent.atomic.AtomicLong";

private static final List<String> ATOMIC_PRIMITIVE_TYPES = Arrays.asList(
ATOMIC_ATOMIC_BOOLEAN, ATOMIC_ATOMIC_INTEGER, ATOMIC_ATOMIC_LONG
);

@Override
public String getDisplayName() {
Expand All @@ -59,9 +61,9 @@ public Set<String> getTags() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(Preconditions.or(
new UsesType<>("java.util.concurrent.atomic.AtomicBoolean", false),
new UsesType<>("java.util.concurrent.atomic.AtomicInteger", false),
new UsesType<>("java.util.concurrent.atomic.AtomicLong", false)
new UsesType<>(ATOMIC_ATOMIC_BOOLEAN, false),
new UsesType<>(ATOMIC_ATOMIC_INTEGER, false),
new UsesType<>(ATOMIC_ATOMIC_LONG, false)
), new JavaVisitor<ExecutionContext>() {
private final MethodMatcher aiMethodMatcher = new MethodMatcher("java.lang.Object equals(java.lang.Object)");

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* 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 com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import org.openrewrite.java.template.Primitive;
import org.openrewrite.java.template.RecipeDescriptor;

import java.io.BufferedWriter;
import java.io.IOException;

@RecipeDescriptor(
name = "Modernize `BufferedWriter` creation & prevent file descriptor leaks",
description = "The code `new BufferedWriter(new FileWriter(f))` creates a `BufferedWriter` that does not close the underlying `FileWriter` when it is closed. " +
"This can lead to file descriptor leaks as per [CWE-755](https://cwe.mitre.org/data/definitions/755.html). " +
"Use `Files.newBufferedWriter` to create a `BufferedWriter` that closes the underlying file descriptor when it is closed."
)
public class BufferedWriterCreation {

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(File))` to `Files.newBufferedWriter(Path)`",
description = "Convert `new BufferedWriter(new FileWriter(f))` to `Files.newBufferedWriter(f.toPath())`."
)
static class BufferedWriterFromNewFileWriterWithFileArgument {
@BeforeTemplate
BufferedWriter before(java.io.File f) throws IOException {
return new BufferedWriter(new java.io.FileWriter(f));
}

@AfterTemplate
BufferedWriter after(java.io.File f) throws IOException {
return java.nio.file.Files.newBufferedWriter(f.toPath());
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(String))` to `Files.newBufferedWriter(Path)`",
description = "Convert `new BufferedWriter(new FileWriter(s))` to `Files.newBufferedWriter(new java.io.File(s).toPath())`."
)
static class BufferedWriterFromNewFileWriterWithStringArgument {
@BeforeTemplate
BufferedWriter before(String s) throws IOException {
return new BufferedWriter(new java.io.FileWriter(s));
}

@AfterTemplate
BufferedWriter after(String s) throws IOException {
return java.nio.file.Files.newBufferedWriter(new java.io.File(s).toPath());
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(File, boolean))` to `Files.newBufferedWriter(Path, StandardOpenOption)`",
description = "Convert `new BufferedWriter(new FileWriter(f, b))` to `Files.newBufferedWriter(f.toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)`."
)
static class BufferedWriterFromNewFileWriterWithFileAndBooleanArguments {
@BeforeTemplate
BufferedWriter before(java.io.File f, @Primitive Boolean b) throws IOException {
return new BufferedWriter(new java.io.FileWriter(f, b));
}

@AfterTemplate
BufferedWriter after(java.io.File f, @Primitive Boolean b) throws IOException {
return java.nio.file.Files.newBufferedWriter(f.toPath(), b ?
java.nio.file.StandardOpenOption.APPEND : java.nio.file.StandardOpenOption.CREATE);
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(String, boolean))` to `Files.newBufferedWriter(Path, StandardOpenOption)`",
description = "Convert `new BufferedWriter(new FileWriter(s, b))` to `Files.newBufferedWriter(new java.io.File(s).toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)`."
)
static class BufferedWriterFromNewFileWriterWithStringAndBooleanArguments {
@BeforeTemplate
BufferedWriter before(String s, @Primitive Boolean b) throws IOException {
return new BufferedWriter(new java.io.FileWriter(s, b));
}

@AfterTemplate
BufferedWriter after(String s, @Primitive Boolean b) throws IOException {
return java.nio.file.Files.newBufferedWriter(new java.io.File(s).toPath(), b ?
java.nio.file.StandardOpenOption.APPEND : java.nio.file.StandardOpenOption.CREATE);
}
}

}
Loading

0 comments on commit 675f200

Please sign in to comment.