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

Add new UseTargetNewOperator #403

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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,116 @@
package org.openrewrite.staticanalysis;
jevanlingen marked this conversation as resolved.
Show resolved Hide resolved

import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
jevanlingen marked this conversation as resolved.
Show resolved Hide resolved

import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;

public class RemoveRedundantTypeSpecificationVisitor extends JavaIsoVisitor<ExecutionContext> {
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
System.out.println(" >>>> SUPER visitVariableDeclarations: " + multiVariable);
J.VariableDeclarations varDecls = super.visitVariableDeclarations(multiVariable, ctx);
final TypedTree varDeclsTypeExpression = varDecls.getTypeExpression();
if (varDeclsTypeExpression != null &&
varDecls.getVariables().size() == 1 &&
varDecls.getVariables().get(0).getInitializer() != null &&
varDeclsTypeExpression instanceof J.ParameterizedType) {
varDecls = varDecls.withVariables(ListUtils.map(varDecls.getVariables(), nv -> {
if (nv.getInitializer() instanceof J.NewClass) {
nv = nv.withInitializer(maybeRemoveParams(parameterizedTypes((J.ParameterizedType) varDeclsTypeExpression), (J.NewClass) nv.getInitializer()));
}
return nv;
}));
}
return varDecls;
}

@Override
public J.Assignment visitAssignment(J.Assignment assignment, ExecutionContext ctx) {
System.out.println(" >>>> SUPER visitAssignment: " + assignment);
J.Assignment asgn = super.visitAssignment(assignment, ctx);
if (asgn.getAssignment() instanceof J.NewClass) {
J.NewClass nc = (J.NewClass) asgn.getAssignment();
if (nc.getClazz() instanceof J.ParameterizedType) {
JavaType.Parameterized assignmentType = TypeUtils.asParameterized(asgn.getType());
JavaType.Class assignmentTypeAsClass = TypeUtils.asClass(asgn.getType());
if (assignmentType != null) {
asgn = asgn.withAssignment(maybeRemoveParams(assignmentType.getTypeParameters(), nc));
} else if (assignmentTypeAsClass != null) {
asgn = asgn.withAssignment(maybeRemoveParams(assignmentTypeAsClass.getTypeParameters(), nc));
}
}
}
return asgn;
}

boolean hasEmptyBody(J.NewClass newClass) {
return newClass.getBody() == null;
}

J.NewClass removeRedundantType(J.NewClass newClass) {
J.ParameterizedType newClassType = (J.ParameterizedType) newClass.getClazz();
return newClass.withClazz(newClassType.withTypeParameters(singletonList(new J.Empty(randomId(), Space.EMPTY, Markers.EMPTY))));
}

@Nullable List<JavaType> parameterizedTypes(J.ParameterizedType parameterizedType) {
if (parameterizedType.getTypeParameters() == null) {
return null;
}
List<JavaType> types = new ArrayList<>(parameterizedType.getTypeParameters().size());
for (Expression typeParameter : parameterizedType.getTypeParameters()) {
types.add(typeParameter.getType());
}
return types;
}


J.NewClass maybeRemoveParams(@Nullable List<JavaType> paramTypes, J.NewClass newClass) {
if (paramTypes != null && hasEmptyBody(newClass) && newClass.getClazz() instanceof J.ParameterizedType) {
J.ParameterizedType newClassType = (J.ParameterizedType) newClass.getClazz();
if (newClassType.getTypeParameters() != null) {
if (paramTypes.size() != newClassType.getTypeParameters().size() || hasAnnotations(newClassType)) {
return newClass;
} else {
for (int i = 0; i < paramTypes.size(); i++) {
if (!TypeUtils.isAssignableTo(paramTypes.get(i), newClassType.getTypeParameters().get(i).getType())) {
return newClass;
}
}
}
newClassType.getTypeParameters().stream()
.map(e -> TypeUtils.asFullyQualified(e.getType()))
.forEach(this::maybeRemoveImport);
newClass = removeRedundantType(newClass);
}
}
return newClass;
}

private boolean hasAnnotations(J type) {
if (type instanceof J.ParameterizedType) {
J.ParameterizedType parameterizedType = (J.ParameterizedType) type;
if (hasAnnotations(parameterizedType.getClazz())) {
return true;
} else if (parameterizedType.getTypeParameters() != null) {
for (Expression typeParameter : parameterizedType.getTypeParameters()) {
if (hasAnnotations(typeParameter)) {
return true;
}
}
}
} else {
return type instanceof J.AnnotatedType;
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* 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.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.Space;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.Markers;
Comment on lines +26 to +27
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.Markers;

import org.openrewrite.staticanalysis.csharp.CSharpFileChecker;

import java.time.Duration;

import static org.openrewrite.Tree.randomId;

public class UseTargetNewOperator extends Recipe {

@Override
public String getDisplayName() {
return "Use the target-typed new operator";
}

@Override
public String getDescription() {
return "Replaces full typed objects with the target-typed new operator (new()).";
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(1);
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new CSharpFileChecker<>(), new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
J.VariableDeclarations varDecls = super.visitVariableDeclarations(multiVariable, ctx);
if (varDecls.getVariables().size() == 1 && varDecls.getVariables().get(0).getInitializer() != null && varDecls.getTypeExpression() instanceof J.ParameterizedType) {
varDecls = varDecls.withVariables(ListUtils.map(varDecls.getVariables(), nv -> {
if (nv.getInitializer() instanceof J.NewClass) {
nv = nv.withInitializer(maybeRemoveParams((J.NewClass) nv.getInitializer()));
}
return nv;
}));
}
return varDecls;
}

@Override
public J.Assignment visitAssignment(J.Assignment assignment, ExecutionContext ctx) {
J.Assignment asgn = super.visitAssignment(assignment, ctx);
if (asgn.getAssignment() instanceof J.NewClass && ((J.NewClass) asgn.getAssignment()).getClazz() instanceof J.ParameterizedType) {
asgn = asgn.withAssignment(maybeRemoveParams((J.NewClass) asgn.getAssignment()));
}
return asgn;
}

J.NewClass maybeRemoveParams(J.NewClass newClass) {
if (newClass.getBody() == null && newClass.getClazz() instanceof J.ParameterizedType) {
J.ParameterizedType newClassType = (J.ParameterizedType) newClass.getClazz();
if (newClassType.getTypeParameters() != null) {
newClassType.getTypeParameters().stream()
.map(e -> TypeUtils.asFullyQualified(e.getType()))
.forEach(this::maybeRemoveImport);
newClass = newClass.withClazz(new J.Empty(randomId(), Space.EMPTY, Markers.EMPTY));
}
}
return newClass;
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,14 @@ void useDiamondOperatorTest2() {
import java.util.function.Predicate;
import java.util.List;
import java.util.Map;

class Foo<T> {
Map<String, Integer> map;
Map unknownMap;
public Foo(Predicate<T> p) {}
public void something(Foo<List<String>> foos){}
public void somethingEasy(List<List<String>> l){}

Foo getFoo() {
// variable type initializer
Foo<List<String>> f = new Foo<List<String>>(it -> it.stream().anyMatch(baz -> true));
Expand All @@ -137,7 +137,7 @@ Foo getFoo() {
// return type unknown
return new Foo<List<String>>(it -> it.stream().anyMatch(baz -> true));
}

Foo<List<String>> getFoo2() {
// return type expression
return new Foo<List<String>>(it -> it.stream().anyMatch(baz -> true));
Expand All @@ -150,14 +150,14 @@ Foo<List<String>> getFoo2() {
import java.util.function.Predicate;
import java.util.List;
import java.util.Map;

class Foo<T> {
Map<String, Integer> map;
Map unknownMap;
public Foo(Predicate<T> p) {}
public void something(Foo<List<String>> foos){}
public void somethingEasy(List<List<String>> l){}

Foo getFoo() {
// variable type initializer
Foo<List<String>> f = new Foo<>(it -> it.stream().anyMatch(baz -> true));
Expand All @@ -172,7 +172,7 @@ Foo getFoo() {
// return type unknown
return new Foo<List<String>>(it -> it.stream().anyMatch(baz -> true));
}

Foo<List<String>> getFoo2() {
// return type expression
return new Foo<>(it -> it.stream().anyMatch(baz -> true));
Expand All @@ -193,13 +193,13 @@ void returnTypeParamsDoNotMatchNewClassParams() {
"""
import java.util.List;
import java.util.function.Predicate;

class Test {
interface MyInterface<T> { }
class MyClass<S, T> implements MyInterface<T>{
public MyClass(Predicate<S> p, T check) {}
}

public MyInterface<Integer> a() {
return new MyClass<List<String>, Integer>(l -> l.stream().anyMatch(String::isEmpty), 0);
}
Expand All @@ -211,13 +211,13 @@ public MyClass<List<String>, Integer> b() {
"""
import java.util.List;
import java.util.function.Predicate;

class Test {
interface MyInterface<T> { }
class MyClass<S, T> implements MyInterface<T>{
public MyClass(Predicate<S> p, T check) {}
}

public MyInterface<Integer> a() {
return new MyClass<List<String>, Integer>(l -> l.stream().anyMatch(String::isEmpty), 0);
}
Expand All @@ -242,7 +242,19 @@ void doNotUseDiamondOperatorsForVariablesHavingNullOrUnknownTypes() {

class Test<X, Y> {
void test() {
var ls = new ArrayList<String>();
var ls1 = new ArrayList<String>();
List<String> ls2 = new ArrayList<String>();
}
}
""",
"""
import lombok.val;
import java.util.ArrayList;

class Test<X, Y> {
void test() {
var ls1 = new ArrayList<String>();
List<String> ls2 = new ArrayList<>();
}
}
"""
Expand Down Expand Up @@ -386,6 +398,7 @@ void method() {
void anonymousNewClassJava9Plus() {
rewriteRun(
spec -> spec.allSources(s -> s.markers(javaVersion(11))),
//language=java
java(
"""
import java.util.*;
Expand All @@ -409,6 +422,7 @@ class Foo {
void anonymousNewClassInferTypesJava9Plus() {
rewriteRun(
spec -> spec.allSources(s -> s.markers(javaVersion(11))),
//language=java
java(
"""
interface Serializer<T> {
Expand All @@ -421,6 +435,7 @@ public static void setSerializerConcreteType(Serializer<Integer> serializer) {}
}
"""
),
//language=java
java(
"""
class Test {
Expand Down Expand Up @@ -473,6 +488,7 @@ class kotlinTest {
@Test
void doNotChange() {
rewriteRun(
//language=kotlin
kotlin(
"""
class test {
Expand Down Expand Up @@ -532,7 +548,7 @@ void doNotChangeAnnotatedTypeParameters() {
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;

class Test {
private void test(Object t) {
List<List<String>> l = new ArrayList<List<@Nullable String>>();
Expand Down
Loading
Loading