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

Change mutable public collections to immutable versions: ref issue #2413 #3308

Closed
Show file tree
Hide file tree
Changes from 17 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
@@ -0,0 +1,83 @@
/*
* 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.recipes;

import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.J;

/**
* This recipe modifies the invocation of a method so that it returns an unmodifiable list, if the
* method returns a modifiable one.
Comment on lines +30 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps this is more of an issue with the original feature request rather than the recipe implementation, but I have some doubts if this recipe could do harm in certain situations. More details here: https://github.com/openrewrite/rewrite/issues/2413#issuecomment-1586767731

*/
@Value
@EqualsAndHashCode(callSuper = true)
public class ArraysAsListToImmutableRecipe extends Recipe {

@JsonCreator
public ArraysAsListToImmutableRecipe() {
}

@Override
public String getDisplayName() {
return "Wrap list to be unmodifiable";
}

@Override
public String getDescription() {
return "Return an unmodifiable list, if the method returns a modifiable list.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new UnmodifiableListVisitor();
}

private static class UnmodifiableListVisitor extends JavaIsoVisitor<ExecutionContext> {

final MethodMatcher asListMatcher = new MethodMatcher("java.util.Arrays asList(..)");
final MethodMatcher unmodifiableListMatcher =
new MethodMatcher("java.util.Collections unmodifiableList(..)");

@Override
public J.MethodInvocation visitMethodInvocation(
final J.MethodInvocation method, final ExecutionContext executionContext) {
J.MethodInvocation result = super.visitMethodInvocation(method, executionContext);
if (asListMatcher.matches(method, true)) {
final J.MethodInvocation parentInvocation =
getCursor().getParentOrThrow().firstEnclosing(J.MethodInvocation.class);
if (unmodifiableListMatcher.matches(parentInvocation, true)) {
return super.visitMethodInvocation(method, executionContext);
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
}
result =
JavaTemplate.builder("Collections.unmodifiableList(#{any()})")
.imports("java.util.Collections", "java.util.Arrays")
.contextSensitive()
.build()
.apply(getCursor(), method.getCoordinates().replace(), method);
maybeAddImport("java.util.Collections");
}
return result;
}
}
}
5 changes: 5 additions & 0 deletions rewrite-java/src/test/java/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
root = true

[*.java]
indent_size = 4
ij_continuation_indent_size = 2
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* 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.recipes;

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

import static org.openrewrite.java.Assertions.java;

class ArraysAsListToImmutableRecipeTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new ArraysAsListToImmutableRecipe());
}

@Test
void wrapArrayListToBeUnmodifiableWhenStrings() {
rewriteRun(
java("""
import java.util.Arrays;

class A {
public static final List<String> entries = Arrays.asList("A", "B");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC, Arrays.asList already returns a list that is unmodifiable.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I'm wrong, you can't append to it, but you can replace existing values.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed; more details discussed in this thread; I like your suggestion of using data flow to make this recipe safe to execute. I've not used data flow myself before, but would be good to explore here.

Copy link
Collaborator

@JLLeitschuh JLLeitschuh Jun 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To use data flow, this recipe would need to be moved to the cleanup package in rewrite-static-analysis repository

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's indeed perhaps a better place for this recipe; sorry about that @marynasavchenko . Would you mind targeting https://github.com/openrewrite/rewrite-static-analysis/tree/main/src/main/java/org/openrewrite/staticanalysis for these files?
As seen above that's necessary to use data flow, which we need to be sure we can safely apply this recipe.

}
""",
"""
import java.util.Arrays;
import java.util.Collections;

class A {
public static final List<String> entries = Collections.unmodifiableList(Arrays.asList("A", "B"));
}
"""
)
);
}

@Test
void wrapArrayListToBeUnmodifiableWhenNulls() {
rewriteRun(
java("""
import java.util.Arrays;

class A {
public static final List<String> entries = Arrays.asList("A", null);
}
""",
"""
import java.util.Arrays;
import java.util.Collections;

class A {
public static final List<String> entries = Collections.unmodifiableList(Arrays.asList("A", null));
}
"""
)
);
}


@Test
void wrapArrayListToBeUnmodifiableWhenIntegers() {
rewriteRun(
java("""
import java.util.Arrays;

class A {
public static final List<Integer> entries = Arrays.asList(1, 2);
}
""",
"""
import java.util.Arrays;
import java.util.Collections;

class A {
public static final List<Integer> entries = Collections.unmodifiableList(Arrays.asList(1, 2));
}
"""
)
);
}

@Test
void doNotWrapIfItIsAlreadyUnmodifiable() {
rewriteRun(
java("""
import java.util.Arrays;
import java.util.Collections;

class A {
public static final List<String> entries = Collections.unmodifiableList(Arrays.asList("A", "B"));
}
"""
)
);
}
}