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

Use getFirst() instead of stream().findFirst().orElseThrow() #403

Merged
merged 3 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -25,6 +25,7 @@
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

public class IteratorNext extends Recipe {
Expand Down Expand Up @@ -57,13 +58,13 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
J.MethodInvocation nextInvocation = super.visitMethodInvocation(method, ctx);
if (NEXT_MATCHER.matches(nextInvocation) && ITERATOR_MATCHER.matches(nextInvocation.getSelect())) {
J.MethodInvocation iteratorInvocation = (J.MethodInvocation) nextInvocation.getSelect();
if (TypeUtils.isAssignableTo("java.util.SequencedCollection", iteratorInvocation.getSelect().getType())) {
J.MethodInvocation getFirstInvocation = nextInvocation.withSelect(iteratorInvocation.getSelect())
.withName(nextInvocation.getName().withSimpleName("getFirst"))
.withMethodType(nextInvocation.getMethodType()
.withName("getFirst")
.withDeclaringType(iteratorInvocation.getMethodType().getDeclaringType()));
return getFirstInvocation;
Expression iteratorSelect = iteratorInvocation.getSelect();
if (TypeUtils.isAssignableTo("java.util.SequencedCollection", iteratorSelect.getType())) {
JavaType.Method getFirst = iteratorInvocation.getMethodType().withName("getFirst");
return iteratorInvocation
.withName(iteratorInvocation.getName().withSimpleName("getFirst").withType(getFirst))
.withMethodType(getFirst)
.withPrefix(nextInvocation.getPrefix());
}
}
return nextInvocation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
*/
package org.openrewrite.java.migrate.util;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.*;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesJavaVersion;
Expand Down Expand Up @@ -109,7 +106,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
.withParameterNames(null)
.withParameterTypes(null);
}
return mi.withName(mi.getName().withSimpleName(operation + firstOrLast))
return mi.withName(mi.getName().withSimpleName(operation + firstOrLast).withType(newMethodType))
.withArguments(arguments)
.withMethodType(newMethodType);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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.java.migrate.util;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesJavaVersion;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

public class StreamFindFirst extends Recipe {
private static final MethodMatcher COLLECTION_STREAM_MATCHER = new MethodMatcher("java.util.Collection stream()", true);
private static final MethodMatcher STREAM_FIND_FIRST_MATCHER = new MethodMatcher("java.util.stream.Stream findFirst()", true);
private static final MethodMatcher OPTIONAL_OR_ELSE_THROW_MATCHER = new MethodMatcher("java.util.Optional orElseThrow()", true);

@Override
public String getDisplayName() {
return "Use `getFirst()` instead of `stream().findFirst().orElseThrow()`";
}

@Override
public String getDescription() {
return "For SequencedCollections, use `collection.getFirst()` instead of `collection.stream().findFirst().orElseThrow()`.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
JavaIsoVisitor<ExecutionContext> javaIsoVisitor = new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);

if (!OPTIONAL_OR_ELSE_THROW_MATCHER.matches(mi) || !(mi.getSelect() instanceof J.MethodInvocation)) {
return mi;
}
J.MethodInvocation optional = (J.MethodInvocation) mi.getSelect();
if (!STREAM_FIND_FIRST_MATCHER.matches(optional) || !(optional.getSelect() instanceof J.MethodInvocation)) {
return mi;
}
J.MethodInvocation stream = (J.MethodInvocation) optional.getSelect();
if (!COLLECTION_STREAM_MATCHER.matches(stream) ||
!TypeUtils.isOfClassType(stream.getSelect().getType(), "java.util.SequencedCollection")) {
return mi;
}
JavaType.Method methodType = stream.getMethodType().withName("getFirst");
return stream
.withName(stream.getName().withSimpleName("getFirst").withType(methodType))
.withMethodType(methodType)
.withPrefix(mi.getPrefix());
}


};
return Preconditions.check(
Preconditions.and(
new UsesJavaVersion<>(21),
new UsesMethod<>(COLLECTION_STREAM_MATCHER),
new UsesMethod<>(STREAM_FIND_FIRST_MATCHER),
new UsesMethod<>(OPTIONAL_OR_ELSE_THROW_MATCHER)
),
javaIsoVisitor);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ void bar(Collection<String> collection) {
}

@Test
void nextCommentRetained() {
void nextCommentList() {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
rewriteRun(
//language=java
java(
Expand All @@ -102,7 +102,6 @@ void bar(List<String> collection) {
class Foo {
void bar(List<String> collection) {
String first = collection
// Next comment
.getFirst();
}
}
Expand All @@ -112,7 +111,7 @@ void bar(List<String> collection) {
}

@Test
void iteratorCommentLost() {
void iteratorCommentRetained() {
rewriteRun(
//language=java
java(
Expand All @@ -134,6 +133,7 @@ void bar(List<String> collection) {
class Foo {
void bar(List<String> collection) {
String first = collection
// Iterator comment
.getFirst();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.java.Assertions.javaVersion;


@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/243")
@EnabledForJreRange(min = JRE.JAVA_21)
class ListFirstAndLastTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new ListFirstAndLast())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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.java.migrate.util;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

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

@EnabledForJreRange(min = JRE.JAVA_21)
class StreamFindFirstTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec
.recipe(new StreamFindFirst())
.parser(JavaParser.fromJavaVersion().logCompilationWarningsAndErrors(true))
.allSources(src -> src.markers(javaVersion(21)));
}

@Test
void sequencedCollection() {
rewriteRun(
//language=java
java(
"""
import java.util.*;

class Foo {
void bar(SequencedCollection<String> collection) {
String first = collection.stream().findFirst().orElseThrow();
}
}
""",
"""
import java.util.*;

class Foo {
void bar(SequencedCollection<String> collection) {
String first = collection.getFirst();
}
}
"""
)
);
}

@Test
void regularCollection() {
rewriteRun(
//language=java
java(
"""
import java.util.*;

class Foo {
void bar(Collection<String> collection) {
String first = collection.stream().findFirst().orElseThrow();
}
}
"""
)
);
}
}
Loading