From 3592bfce19e8c5ddfdb5c3cf07e5fad83c812879 Mon Sep 17 00:00:00 2001 From: Patrick Date: Fri, 27 May 2022 13:26:14 -0700 Subject: [PATCH] Update UseDiamondOperator to ignore NewClass initializers for variables having a null or unknown type. (issue #1297) --- .../java/cleanup/UseDiamondOperator.java | 13 +++++++++---- .../java/cleanup/UseDiamondOperatorTest.kt | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/UseDiamondOperator.java b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/UseDiamondOperator.java index c776894517b5..537b47b2a4cb 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/UseDiamondOperator.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/UseDiamondOperator.java @@ -20,10 +20,7 @@ import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaVarKeyword; -import org.openrewrite.java.tree.Space; -import org.openrewrite.java.tree.TypeUtils; +import org.openrewrite.java.tree.*; import org.openrewrite.marker.Markers; import java.time.Duration; @@ -60,6 +57,14 @@ protected TreeVisitor getVisitor() { return new JavaIsoVisitor() { + @Override + public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) { + if (multiVariable.getType() == null || multiVariable.getType() instanceof JavaType.Unknown) { + return multiVariable; + } + return super.visitVariableDeclarations(multiVariable, executionContext); + } + @Override public J.NewClass visitNewClass(J.NewClass newClass, ExecutionContext executionContext) { J.NewClass n = super.visitNewClass(newClass, executionContext); diff --git a/rewrite-test/src/main/kotlin/org/openrewrite/java/cleanup/UseDiamondOperatorTest.kt b/rewrite-test/src/main/kotlin/org/openrewrite/java/cleanup/UseDiamondOperatorTest.kt index cca02a868960..05fbe1de73c5 100644 --- a/rewrite-test/src/main/kotlin/org/openrewrite/java/cleanup/UseDiamondOperatorTest.kt +++ b/rewrite-test/src/main/kotlin/org/openrewrite/java/cleanup/UseDiamondOperatorTest.kt @@ -16,6 +16,7 @@ package org.openrewrite.java.cleanup import org.junit.jupiter.api.Test +import org.openrewrite.Issue import org.openrewrite.Recipe import org.openrewrite.java.JavaParser import org.openrewrite.java.JavaRecipeTest @@ -54,6 +55,23 @@ interface UseDiamondOperatorTest: JavaRecipeTest { """ ) + @Issue("https://github.com/openrewrite/rewrite/issues/1297") + @Test + fun `do not use diamond operators for variables having null or unknown types`(jp: JavaParser) = assertUnchanged( + jp, + before = """ + import lombok.val; + import java.util.ArrayList; + + class Test { + void test() { + val ls = new ArrayList(); + UnknownThing o = new UnknownThing(); + } + } + """ + ) + @Test fun noLeftSide(jp: JavaParser) = assertUnchanged( parser = jp,