From 697ae150aab87d16d0b4adda519843e0c37472cb Mon Sep 17 00:00:00 2001 From: Laurens Westerlaken Date: Fri, 20 Dec 2024 15:33:17 +0100 Subject: [PATCH 01/16] Refactor SpringReference (#4805) * Separating and clearer naming * Add license header * Review feedback --- ...Reference.java => SpringXmlReference.java} | 55 +++------------- .../openrewrite/xml/trait/XmlReference.java | 64 +++++++++++++++++++ .../org.openrewrite.trait.Reference$Provider | 2 +- ...eTest.java => SpringXmlReferenceTest.java} | 4 +- 4 files changed, 75 insertions(+), 50 deletions(-) rename rewrite-xml/src/main/java/org/openrewrite/xml/trait/{SpringReference.java => SpringXmlReference.java} (67%) create mode 100644 rewrite-xml/src/main/java/org/openrewrite/xml/trait/XmlReference.java rename rewrite-xml/src/test/java/org/openrewrite/xml/trait/{SpringReferenceTest.java => SpringXmlReferenceTest.java} (96%) diff --git a/rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringReference.java b/rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringXmlReference.java similarity index 67% rename from rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringReference.java rename to rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringXmlReference.java index a2a78481461..41523a89b8a 100644 --- a/rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringReference.java +++ b/rewrite-xml/src/main/java/org/openrewrite/xml/trait/SpringXmlReference.java @@ -18,9 +18,7 @@ import lombok.Value; import org.jspecify.annotations.Nullable; import org.openrewrite.Cursor; -import org.openrewrite.ExecutionContext; import org.openrewrite.SourceFile; -import org.openrewrite.Tree; import org.openrewrite.trait.Reference; import org.openrewrite.trait.SimpleTraitMatcher; import org.openrewrite.xml.XPathMatcher; @@ -32,54 +30,17 @@ import java.util.regex.Pattern; @Value -class SpringReference implements Reference { +public class SpringXmlReference extends XmlReference { + Cursor cursor; Kind kind; - @Override - public Tree getTree() { - return Reference.super.getTree(); - } - @Override public Kind getKind() { return kind; } - @Override - public String getValue() { - if (getTree() instanceof Xml.Attribute) { - Xml.Attribute attribute = (Xml.Attribute) getTree(); - return attribute.getValueAsString(); - } else if (getTree() instanceof Xml.Tag) { - Xml.Tag tag = (Xml.Tag) getTree(); - if (tag.getValue().isPresent()) { - return tag.getValue().get(); - } - } - throw new IllegalArgumentException("getTree() must be an Xml.Attribute or Xml.Tag: " + getTree().getClass()); - } - - @Override - public boolean supportsRename() { - return true; - } - - @Override - public Tree rename(Renamer renamer, Cursor cursor, ExecutionContext ctx) { - Tree tree = cursor.getValue(); - if (tree instanceof Xml.Attribute) { - Xml.Attribute attribute = (Xml.Attribute) tree; - String renamed = renamer.rename(this); - return attribute.withValue(attribute.getValue().withValue(renamed)); - } else if (tree instanceof Xml.Tag && ((Xml.Tag) tree).getValue().isPresent()) { - String renamed = renamer.rename(this); - return ((Xml.Tag) tree).withValue(renamed); - } - return tree; - } - - static class Matcher extends SimpleTraitMatcher { + static class Matcher extends SimpleTraitMatcher { private final Pattern referencePattern = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(?:\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*"); private final XPathMatcher classXPath = new XPathMatcher("//@class"); private final XPathMatcher typeXPath = new XPathMatcher("//@type"); @@ -88,14 +49,14 @@ static class Matcher extends SimpleTraitMatcher { private final XPathMatcher tags = new XPathMatcher("//value"); @Override - protected @Nullable SpringReference test(Cursor cursor) { + protected @Nullable SpringXmlReference test(Cursor cursor) { Object value = cursor.getValue(); if (value instanceof Xml.Attribute) { Xml.Attribute attrib = (Xml.Attribute) value; if (classXPath.matches(cursor) || typeXPath.matches(cursor) || keyTypeXPath.matches(cursor) || valueTypeXPath.matches(cursor)) { String stringVal = attrib.getValueAsString(); if (referencePattern.matcher(stringVal).matches()) { - return new SpringReference(cursor, determineKind(stringVal)); + return new SpringXmlReference(cursor, determineKind(stringVal)); } } } else if (value instanceof Xml.Tag) { @@ -103,15 +64,15 @@ static class Matcher extends SimpleTraitMatcher { if (tags.matches(cursor)) { Optional stringVal = tag.getValue(); if (stringVal.isPresent() && referencePattern.matcher(stringVal.get()).matches()) { - return new SpringReference(cursor, determineKind(stringVal.get())); + return new SpringXmlReference(cursor, determineKind(stringVal.get())); } } } return null; } - Kind determineKind(String value) { - return Character.isUpperCase(value.charAt(value.lastIndexOf('.') + 1)) ? Kind.TYPE : Kind.PACKAGE; + Reference.Kind determineKind(String value) { + return Character.isUpperCase(value.charAt(value.lastIndexOf('.') + 1)) ? Reference.Kind.TYPE : Reference.Kind.PACKAGE; } } diff --git a/rewrite-xml/src/main/java/org/openrewrite/xml/trait/XmlReference.java b/rewrite-xml/src/main/java/org/openrewrite/xml/trait/XmlReference.java new file mode 100644 index 00000000000..25b87149d2d --- /dev/null +++ b/rewrite-xml/src/main/java/org/openrewrite/xml/trait/XmlReference.java @@ -0,0 +1,64 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * 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 + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * 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.xml.trait; + +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Tree; +import org.openrewrite.trait.Reference; +import org.openrewrite.xml.tree.Xml; + +public abstract class XmlReference implements Reference { + + @Override + public Tree getTree() { + return Reference.super.getTree(); + } + + @Override + public String getValue() { + if (getTree() instanceof Xml.Attribute) { + Xml.Attribute attribute = (Xml.Attribute) getTree(); + return attribute.getValueAsString(); + } else if (getTree() instanceof Xml.Tag) { + Xml.Tag tag = (Xml.Tag) getTree(); + if (tag.getValue().isPresent()) { + return tag.getValue().get(); + } + } + throw new IllegalArgumentException("getTree() must be an Xml.Attribute or Xml.Tag: " + getTree().getClass()); + } + + @Override + public boolean supportsRename() { + return true; + } + + @Override + public Tree rename(Renamer renamer, Cursor cursor, ExecutionContext ctx) { + Tree tree = cursor.getValue(); + if (tree instanceof Xml.Attribute) { + Xml.Attribute attribute = (Xml.Attribute) tree; + String renamed = renamer.rename(this); + return attribute.withValue(attribute.getValue().withValue(renamed)); + } else if (tree instanceof Xml.Tag && ((Xml.Tag) tree).getValue().isPresent()) { + String renamed = renamer.rename(this); + return ((Xml.Tag) tree).withValue(renamed); + } + return tree; + } + +} diff --git a/rewrite-xml/src/main/resources/META-INF/services/org.openrewrite.trait.Reference$Provider b/rewrite-xml/src/main/resources/META-INF/services/org.openrewrite.trait.Reference$Provider index 72d76d75ee4..e8a9ab1dc42 100644 --- a/rewrite-xml/src/main/resources/META-INF/services/org.openrewrite.trait.Reference$Provider +++ b/rewrite-xml/src/main/resources/META-INF/services/org.openrewrite.trait.Reference$Provider @@ -1 +1 @@ -org.openrewrite.xml.trait.SpringReference$Provider \ No newline at end of file +org.openrewrite.xml.trait.SpringXmlReference$Provider \ No newline at end of file diff --git a/rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringReferenceTest.java b/rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringXmlReferenceTest.java similarity index 96% rename from rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringReferenceTest.java rename to rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringXmlReferenceTest.java index d60f5a2e8a9..000d242b16e 100644 --- a/rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringReferenceTest.java +++ b/rewrite-xml/src/test/java/org/openrewrite/xml/trait/SpringXmlReferenceTest.java @@ -23,11 +23,11 @@ import static org.openrewrite.xml.Assertions.xml; -class SpringReferenceTest implements RewriteTest { +class SpringXmlReferenceTest implements RewriteTest { @Override public void defaults(RecipeSpec spec) { - spec.recipe(RewriteTest.toRecipe(() -> new SpringReference.Matcher() + spec.recipe(RewriteTest.toRecipe(() -> new SpringXmlReference.Matcher() .asVisitor(springJavaTypeReference -> SearchResult.found(springJavaTypeReference.getTree(), springJavaTypeReference.getValue())))); } From 59273da0f6cfa2c0b4063fcdd8ea4bb9789d998d Mon Sep 17 00:00:00 2001 From: Shannon Pamperl Date: Fri, 20 Dec 2024 16:51:50 -0600 Subject: [PATCH 02/16] refactor: Update Gradle wrapper (#4808) Use this link to re-run the recipe: https://app.moderne.io/recipes/org.openrewrite.gradle.UpdateGradleWrapper?organizationId=T3BlblJld3JpdGU%3D#defaults=W3sibmFtZSI6ImFkZElmTWlzc2luZyIsInZhbHVlIjoiRmFsc2UifV0= Co-authored-by: Moderne --- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9751024bf3d..046b4f50491 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,8 +1,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionSha256Sum=f397b287023acdba1e9f6fc5ea72d22dd63669d59ed4a289a29b1a76eee151c6 +distributionSha256Sum=7a00d51fb93147819aab76024feece20b6b84e420694101f276be952e08bef03 From dd2886c193ea20f416171b5b280a49086e969710 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sat, 21 Dec 2024 17:42:41 +0100 Subject: [PATCH 03/16] Add recipe to remove Gradle Enterprise and Develocity (#4809) * Add recipe to remove Gradle Enterprise and Develocity * Remove left over java plugin --- .../RemoveDevelocityConfiguration.java | 57 +++++++++++ .../resources/META-INF/rewrite/gradle.yml | 15 +++ .../gradle/plugins/RemoveDevelocityTest.java | 95 +++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 rewrite-gradle/src/main/java/org/openrewrite/gradle/plugins/RemoveDevelocityConfiguration.java create mode 100644 rewrite-gradle/src/test/java/org/openrewrite/gradle/plugins/RemoveDevelocityTest.java diff --git a/rewrite-gradle/src/main/java/org/openrewrite/gradle/plugins/RemoveDevelocityConfiguration.java b/rewrite-gradle/src/main/java/org/openrewrite/gradle/plugins/RemoveDevelocityConfiguration.java new file mode 100644 index 00000000000..356c2dfab43 --- /dev/null +++ b/rewrite-gradle/src/main/java/org/openrewrite/gradle/plugins/RemoveDevelocityConfiguration.java @@ -0,0 +1,57 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * 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 + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * 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.gradle.plugins; + +import org.jspecify.annotations.Nullable; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Preconditions; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.gradle.IsBuildGradle; +import org.openrewrite.gradle.IsSettingsGradle; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.J; + +import static org.openrewrite.Preconditions.or; + +public class RemoveDevelocityConfiguration extends Recipe { + @Override + public String getDisplayName() { + return "Remove Develocity configuration"; + } + + @Override + public String getDescription() { + return "Remove Develocity configuration from a Gradle build."; + } + + @Override + public TreeVisitor getVisitor() { + return Preconditions.check( + or(new IsBuildGradle<>(), new IsSettingsGradle<>()), + new JavaIsoVisitor() { + @Override + public J.@Nullable MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { + if ("develocity".equals(method.getSimpleName()) || + "gradleEnterprise".equals(method.getSimpleName())) { + return null; + } + return super.visitMethodInvocation(method, ctx); + } + } + ); + } +} diff --git a/rewrite-gradle/src/main/resources/META-INF/rewrite/gradle.yml b/rewrite-gradle/src/main/resources/META-INF/rewrite/gradle.yml index 7240bdf3672..6fdf529b07e 100644 --- a/rewrite-gradle/src/main/resources/META-INF/rewrite/gradle.yml +++ b/rewrite-gradle/src/main/resources/META-INF/rewrite/gradle.yml @@ -42,3 +42,18 @@ recipeList: key: org.gradle.parallel value: true filePattern: gradle.properties +--- +type: specs.openrewrite.org/v1beta/recipe +name: org.openrewrite.gradle.plugins.RemoveDevelocity +displayName: Remove Develocity +description: Remove the Develocity plugin and configuration from the Gradle build and settings files. +recipeList: + - org.openrewrite.gradle.plugins.RemoveBuildPlugin: + pluginId: com.gradle.develocity + - org.openrewrite.gradle.plugins.RemoveSettingsPlugin: + pluginId: com.gradle.develocity + - org.openrewrite.gradle.plugins.RemoveBuildPlugin: + pluginId: com.gradle.enterprise + - org.openrewrite.gradle.plugins.RemoveSettingsPlugin: + pluginId: com.gradle.enterprise + - org.openrewrite.gradle.plugins.RemoveDevelocityConfiguration \ No newline at end of file diff --git a/rewrite-gradle/src/test/java/org/openrewrite/gradle/plugins/RemoveDevelocityTest.java b/rewrite-gradle/src/test/java/org/openrewrite/gradle/plugins/RemoveDevelocityTest.java new file mode 100644 index 00000000000..3c26e264f79 --- /dev/null +++ b/rewrite-gradle/src/test/java/org/openrewrite/gradle/plugins/RemoveDevelocityTest.java @@ -0,0 +1,95 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * 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 + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * 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.gradle.plugins; + +import org.junit.jupiter.api.Test; +import org.openrewrite.DocumentExample; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +import static org.openrewrite.gradle.Assertions.settingsGradle; +import static org.openrewrite.gradle.toolingapi.Assertions.withToolingApi; + +class RemoveDevelocityTest implements RewriteTest { + @Override + public void defaults(RecipeSpec spec) { + spec + .beforeRecipe(withToolingApi()) + .recipeFromResource("/META-INF/rewrite/gradle.yml", "org.openrewrite.gradle.plugins.RemoveDevelocity"); + } + + @Test + @DocumentExample + void removeGradleEnterprise() { + rewriteRun( + settingsGradle( + """ + plugins { + id 'com.gradle.enterprise' version '3.16' + } + gradleEnterprise { + server = 'https://ge.sam.com/' + allowUntrustedServer = true + buildScan { + publishAlways() + uploadInBackground = true + capture { + taskInputFiles = true + } + } + buildCache { + remote(gradleEnterprise.buildCache) { + enabled = true + push = System.getenv("CI") != null + } + } + } + """, + "" + ) + ); + } + + @Test + void removeDevelocity() { + rewriteRun( + settingsGradle( + """ + plugins { + id 'com.gradle.develocity' version '3.17.6' + } + develocity { + server = 'https://ge.sam.com/' + allowUntrustedServer = true + buildScan { + uploadInBackground = true + capture { + fileFingerprints = true + } + } + buildCache { + remote(develocity.buildCache) { + enabled = true + push = System.getenv("CI") != null + } + } + } + """, + "" + ) + ); + } +} From e93ec048be927787c80afbf35da4bcea1b789674 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sat, 21 Dec 2024 19:27:00 +0100 Subject: [PATCH 04/16] Add a UsesType precondition to ReplaceConstant --- .../main/java/org/openrewrite/java/ReplaceConstant.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rewrite-java/src/main/java/org/openrewrite/java/ReplaceConstant.java b/rewrite-java/src/main/java/org/openrewrite/java/ReplaceConstant.java index eedef216d95..b8f7f001e14 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/ReplaceConstant.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/ReplaceConstant.java @@ -19,6 +19,7 @@ import lombok.Value; import org.jspecify.annotations.Nullable; import org.openrewrite.*; +import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.JavaType; import org.openrewrite.java.tree.TypeUtils; @@ -53,7 +54,7 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { - return new JavaVisitor() { + JavaVisitor replacementVisitor = new JavaVisitor() { J.@Nullable Literal literal; @Override @@ -117,5 +118,9 @@ private J.Literal buildLiteral() { return literal; } }; + return Preconditions.check( + new UsesType<>(owningType, true), + replacementVisitor + ); } } From da6561eab8cbbae90bb5de17e2882860bf2b01dc Mon Sep 17 00:00:00 2001 From: Peter Streef Date: Mon, 23 Dec 2024 12:01:57 +0100 Subject: [PATCH 05/16] Allow file scheme in `RemoteArchive` to simplify testing (#4791) * Allow file scheme in `RemoteArchive` to simplify testing While it might look a bit controversial, the file scheme can also point to a remote (for instance a mounted network share) file. By allowing the `file://` scheme we can use `RemoteArchive` for those files. As a useful side effect, this makes testing RemoteArchive handling a lot easier. * fix test * Update rewrite-core/src/test/java/org/openrewrite/remote/RemoteArchiveTest.java Co-authored-by: Sam Snyder --------- Co-authored-by: Sam Snyder --- .../org/openrewrite/remote/RemoteArchive.java | 4 +++ .../openrewrite/remote/RemoteArchiveTest.java | 26 +++++++++++++----- .../openrewrite/remote/RemoteFileTest.java | 4 +-- rewrite-core/src/test/resources/zipfile.zip | Bin 0 -> 193 bytes 4 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 rewrite-core/src/test/resources/zipfile.zip diff --git a/rewrite-core/src/main/java/org/openrewrite/remote/RemoteArchive.java b/rewrite-core/src/main/java/org/openrewrite/remote/RemoteArchive.java index 23de1da8810..6e553fdac4b 100644 --- a/rewrite-core/src/main/java/org/openrewrite/remote/RemoteArchive.java +++ b/rewrite-core/src/main/java/org/openrewrite/remote/RemoteArchive.java @@ -34,6 +34,7 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; @@ -92,6 +93,9 @@ public InputStream getInputStream(ExecutionContext ctx) { try { Path localArchive = cache.compute(uri, () -> { //noinspection resource + if ("file".equals(uri.getScheme())) { + return Files.newInputStream(Paths.get(uri)); + } HttpSender.Response response = httpSender.send(httpSender.get(uri.toString()).build()); if (response.isSuccessful()) { return response.getBody(); diff --git a/rewrite-core/src/test/java/org/openrewrite/remote/RemoteArchiveTest.java b/rewrite-core/src/test/java/org/openrewrite/remote/RemoteArchiveTest.java index f96eea97f00..e09fc8454f5 100644 --- a/rewrite-core/src/test/java/org/openrewrite/remote/RemoteArchiveTest.java +++ b/rewrite-core/src/test/java/org/openrewrite/remote/RemoteArchiveTest.java @@ -21,10 +21,12 @@ import org.openrewrite.ExecutionContext; import org.openrewrite.HttpSenderExecutionContextView; import org.openrewrite.InMemoryExecutionContext; +import org.openrewrite.PrintOutputCapture; import org.openrewrite.test.MockHttpSender; import java.io.IOException; import java.io.InputStream; +import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; import java.util.concurrent.*; @@ -40,10 +42,6 @@ class RemoteArchiveTest { void gradleWrapper(String version) throws Exception { URL distributionUrl = requireNonNull(RemoteArchiveTest.class.getClassLoader().getResource("gradle-" + version + "-bin.zip")); ExecutionContext ctx = new InMemoryExecutionContext(); - RemoteExecutionContextView.view(ctx).setArtifactCache(new LocalRemoteArtifactCache( - Paths.get(System.getProperty("user.home") + "/.rewrite/remote/gradleWrapper"))); - HttpSenderExecutionContextView.view(ctx) - .setLargeFileHttpSender(new MockHttpSender(distributionUrl::openStream)); RemoteArchive remoteArchive = Remote .builder( @@ -58,10 +56,9 @@ void gradleWrapper(String version) throws Exception { @Test void gradleWrapperDownloadFails() throws Exception { - URL distributionUrl = requireNonNull(RemoteArchiveTest.class.getClassLoader().getResource("gradle-7.4.2-bin.zip")); + URL distributionUrl = new URL("http://example"); ExecutionContext ctx = new InMemoryExecutionContext(); - RemoteExecutionContextView.view(ctx).setArtifactCache(new LocalRemoteArtifactCache( - Paths.get(System.getProperty("user.home") + "/.rewrite/remote/gradleWrapperDownloadFails"))); + HttpSenderExecutionContextView.view(ctx) .setLargeFileHttpSender(new MockHttpSender(408)); @@ -116,6 +113,21 @@ void gradleWrapperConcurrent(String version) throws Exception { executorService.shutdown(); } + @Test + void printingRemoteArchive() throws URISyntaxException { + URL zipUrl = requireNonNull(RemoteArchiveTest.class.getClassLoader().getResource("zipfile.zip")); + + RemoteArchive remoteArchive = Remote + .builder( + Paths.get("content.txt"), + zipUrl.toURI() + ) + .build("content.txt"); + + String printed = remoteArchive.printAll(new PrintOutputCapture<>(0, PrintOutputCapture.MarkerPrinter.DEFAULT)); + assertThat(printed).isEqualTo("this is a zipped file"); + } + private Long getInputStreamSize(InputStream is) { BlackHoleOutputStream out = new BlackHoleOutputStream(); try { diff --git a/rewrite-core/src/test/java/org/openrewrite/remote/RemoteFileTest.java b/rewrite-core/src/test/java/org/openrewrite/remote/RemoteFileTest.java index 6e335a1eee3..de1b23476c8 100644 --- a/rewrite-core/src/test/java/org/openrewrite/remote/RemoteFileTest.java +++ b/rewrite-core/src/test/java/org/openrewrite/remote/RemoteFileTest.java @@ -55,10 +55,8 @@ void gradleWrapperProperties() throws Exception { @Test void gradleWrapperDownloadFails() throws Exception { - URL distributionUrl = requireNonNull(RemoteFileTest.class.getClassLoader().getResource("gradle-wrapper.properties")); + URL distributionUrl = new URL("http://example.com"); ExecutionContext ctx = new InMemoryExecutionContext(); - RemoteExecutionContextView.view(ctx).setArtifactCache(new LocalRemoteArtifactCache( - Paths.get(System.getProperty("user.home") + "/.rewrite/remote/gradleWrapperDownloadFails"))); HttpSenderExecutionContextView.view(ctx) .setLargeFileHttpSender(new MockHttpSender(408)); diff --git a/rewrite-core/src/test/resources/zipfile.zip b/rewrite-core/src/test/resources/zipfile.zip new file mode 100644 index 0000000000000000000000000000000000000000..028830c420ec4023f6e482cbe9dbbf38a606f654 GIT binary patch literal 193 zcmWIWW@h1H0DNs?36d)D(rZ%$(E!Z$>6LW?W`V0JSkN01aSR(g Date: Mon, 23 Dec 2024 18:21:51 +0100 Subject: [PATCH 06/16] Try alternative way of determining parenthesis level for `BinaryExpression` when AST doesn't provide `_INSIDE_PARENTHESES_LEVEL` flag (#4807) --- .../main/java/org/openrewrite/groovy/GroovyParserVisitor.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java index 2e8b26ae7b3..5ce8d628352 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java @@ -2540,6 +2540,10 @@ private int sourceLengthOfString(ConstantExpression expr) { } else if (node instanceof MethodCallExpression) { MethodCallExpression expr = (MethodCallExpression) node; return determineParenthesisLevel(expr.getObjectExpression().getLineNumber(), expr.getLineNumber(), expr.getObjectExpression().getColumnNumber(), expr.getColumnNumber()); + } else if (node instanceof BinaryExpression) { + BinaryExpression expr = (BinaryExpression) node; + return determineParenthesisLevel(expr.getLeftExpression().getLineNumber(), expr.getLineNumber(), expr.getLeftExpression().getColumnNumber(), expr.getColumnNumber()); + } return null; } From 804dea04bdda8eaab7bed8b1424c9b0fe3432c6a Mon Sep 17 00:00:00 2001 From: Jacob van Lingen Date: Tue, 24 Dec 2024 11:00:30 +0100 Subject: [PATCH 07/16] Add a `isClassAvailable` method to the ReflectionUtils (#4810) * Add a `isClassAvailable` method to the ReflectionUtils * Add a `isClassAvailable` method to the ReflectionUtils * Add a `isClassAvailable` method to the ReflectionUtils --- .../openrewrite/internal/ReflectionUtils.java | 17 ++++++-- .../internal/ReflectionUtilsTest.java | 41 +++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 rewrite-core/src/test/java/org/openrewrite/internal/ReflectionUtilsTest.java diff --git a/rewrite-core/src/main/java/org/openrewrite/internal/ReflectionUtils.java b/rewrite-core/src/main/java/org/openrewrite/internal/ReflectionUtils.java index 8cda946a88d..b207a7232e9 100644 --- a/rewrite-core/src/main/java/org/openrewrite/internal/ReflectionUtils.java +++ b/rewrite-core/src/main/java/org/openrewrite/internal/ReflectionUtils.java @@ -36,7 +36,18 @@ public class ReflectionUtils { * Cache for {@link Class#getDeclaredMethods()} plus equivalent default methods * from Java 8 based interfaces, allowing for fast iteration. */ - private static final Map, Method[]> declaredMethodsCache = new ConcurrentHashMap<>(256); + private static final Map, Method[]> DECLARED_METHODS_CACHE = new ConcurrentHashMap<>(256); + + public static boolean isClassAvailable(String fullyQualifiedClassName) { + try { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + ClassLoader classLoader = contextClassLoader == null ? ReflectionUtils.class.getClassLoader() : contextClassLoader; + Class.forName(fullyQualifiedClassName, false, classLoader); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } public static @Nullable Method findMethod(Class clazz, String name, Class... paramTypes) { Class searchType = clazz; @@ -54,7 +65,7 @@ public class ReflectionUtils { } private static Method[] getDeclaredMethods(Class clazz) { - Method[] result = declaredMethodsCache.get(clazz); + Method[] result = DECLARED_METHODS_CACHE.get(clazz); if (result == null) { try { Method[] declaredMethods = clazz.getDeclaredMethods(); @@ -70,7 +81,7 @@ private static Method[] getDeclaredMethods(Class clazz) { } else { result = declaredMethods; } - declaredMethodsCache.put(clazz, (result.length == 0 ? EMPTY_METHOD_ARRAY : result)); + DECLARED_METHODS_CACHE.put(clazz, (result.length == 0 ? EMPTY_METHOD_ARRAY : result)); } catch (Throwable ex) { throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + "] from ClassLoader [" + clazz.getClassLoader() + "]", ex); diff --git a/rewrite-core/src/test/java/org/openrewrite/internal/ReflectionUtilsTest.java b/rewrite-core/src/test/java/org/openrewrite/internal/ReflectionUtilsTest.java new file mode 100644 index 00000000000..83eb1763c75 --- /dev/null +++ b/rewrite-core/src/test/java/org/openrewrite/internal/ReflectionUtilsTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * 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 + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * 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.internal; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ReflectionUtilsTest { + + @Test + void classAvailable() { + boolean result = ReflectionUtils.isClassAvailable("org.openrewrite.internal.ReflectionUtilsTest"); + assertTrue(result); + } + + @Test + void classNotAvailable() { + boolean result = ReflectionUtils.isClassAvailable("org.openrewrite.internal.ReflectionUtilsTest2"); + assertFalse(result); + } + + @Test + void classNotAvailableWhenFQNOmitted() { + boolean result = ReflectionUtils.isClassAvailable("ReflectionUtilsTest"); + assertFalse(result); + } +} From da57352794a42b15957a5e9fd0e51e1e45580a62 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Tue, 24 Dec 2024 15:33:14 +0100 Subject: [PATCH 08/16] Update rewrite.yml to enforce CompareEnumsWithEqualityOperator --- rewrite.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rewrite.yml b/rewrite.yml index 6ed6b2ee876..9ad48193b27 100644 --- a/rewrite.yml +++ b/rewrite.yml @@ -27,6 +27,7 @@ recipeList: - org.openrewrite.recipes.RecipeNullabilityBestPracticesSubset #- org.openrewrite.java.OrderImports - org.openrewrite.java.format.EmptyNewlineAtEndOfFile + - org.openrewrite.staticanalysis.CompareEnumsWithEqualityOperator - org.openrewrite.staticanalysis.InlineVariable - org.openrewrite.staticanalysis.MissingOverrideAnnotation - org.openrewrite.staticanalysis.UseDiamondOperator @@ -75,4 +76,4 @@ recipeList: annotationPattern: '@org.jetbrains.annotations.NotNull' - org.openrewrite.java.RemoveAnnotation: annotationPattern: '@jakarta.annotation.Nonnull' - #- org.openrewrite.java.jspecify.MigrateToJspecify \ No newline at end of file + #- org.openrewrite.java.jspecify.MigrateToJspecify From ef0f8456cde7f9a4ed43a4903d7529d10e0e6126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Schn=C3=A9ider?= Date: Tue, 24 Dec 2024 17:15:02 -0500 Subject: [PATCH 09/16] Correctly map generic return and parameter types in `JavaReflectionTypeMapping` (#4812) --- .../java/org/openrewrite/java/JavaTypeMappingTest.java | 5 +++++ .../java/internal/JavaReflectionTypeMapping.java | 8 ++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java index 591d897bfc3..3783a9365cf 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java @@ -110,6 +110,11 @@ default void generic() { assertThat(generic.getName()).isEqualTo("?"); assertThat(generic.getVariance()).isEqualTo(COVARIANT); assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(0)).getFullyQualifiedName()).isEqualTo("org.openrewrite.java.C"); + + generic = (JavaType.GenericTypeVariable) TypeUtils.asParameterized(methodType("generic").getReturnType()).getTypeParameters().get(0); + assertThat(generic.getName()).isEqualTo("?"); + assertThat(generic.getVariance()).isEqualTo(COVARIANT); + assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(0)).getFullyQualifiedName()).isEqualTo("org.openrewrite.java.C"); } @Test diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java index a7fb142280a..440217560b4 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java @@ -472,13 +472,13 @@ private JavaType.Method method(Method method, JavaType.FullyQualified declaringT List parameterTypes = emptyList(); if (method.getParameters().length > 0) { parameterTypes = new ArrayList<>(method.getParameters().length); - for (Parameter parameter : method.getParameters()) { - Type parameterizedType = parameter.getParameterizedType(); - parameterTypes.add(type(parameterizedType == null ? parameter.getType() : parameterizedType)); + for (Type parameter : method.getGenericParameterTypes()) { + parameterTypes.add(type(parameter)); } } - mappedMethod.unsafeSet(declaringType, type(method.getReturnType()), parameterTypes, thrownExceptions, annotations); + JavaType returnType = type(method.getGenericReturnType()); + mappedMethod.unsafeSet(declaringType, returnType, parameterTypes, thrownExceptions, annotations); return mappedMethod; } } From 321c93b0e64817b5aafb89206c24010c935a1cae Mon Sep 17 00:00:00 2001 From: Jonathan Schneider Date: Tue, 24 Dec 2024 23:18:16 +0100 Subject: [PATCH 10/16] Polish formatting --- .../src/main/java/org/openrewrite/java/tree/JavaType.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java index 2fa596187f4..171a6a2198e 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java @@ -387,7 +387,6 @@ class Class extends FullyQualified { @NonFinal FullyQualified owningClass; - @NonFinal FullyQualified @Nullable [] annotations; @@ -1100,7 +1099,6 @@ class Method implements JavaType { @NonFinal JavaType returnType; - @NonFinal String @Nullable [] parameterNames; From 4ca0c8ec3d292d32a1db5017124b8112a9d32d12 Mon Sep 17 00:00:00 2001 From: Jonathan Schneider Date: Tue, 24 Dec 2024 23:19:16 +0100 Subject: [PATCH 11/16] Add more scenarios to JavaTypeGoat for simply typed fields and methods that return exceptions. --- .../src/main/java/org/openrewrite/java/JavaTypeGoat.java | 6 ++++++ rewrite-java-test/src/main/resources/JavaTypeGoat.java | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java index a32c6df44c4..8e8abd6fe37 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java @@ -15,6 +15,7 @@ */ package org.openrewrite.java; +import java.io.FileNotFoundException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,6 +26,8 @@ public abstract class JavaTypeGoat & C> { public static final PT parameterizedField = new PT() { }; + public static final Double PI = 3.14; + public static final double PI_PRIMITIVE = 3.14; public static abstract class InheritedJavaTypeGoat & C> extends JavaTypeGoat { public InheritedJavaTypeGoat() { @@ -73,6 +76,9 @@ public static class TypeB {} public abstract & C> U genericIntersection(U n); public abstract T genericT(T n); // remove after signatures are common. public abstract & Intersection> void recursiveIntersection(U n); + public abstract T nameShadow(T t); + public abstract void throwsException() throws FileNotFoundException; + public abstract void throwsGenericException() throws T, InterruptedException; } interface C { diff --git a/rewrite-java-test/src/main/resources/JavaTypeGoat.java b/rewrite-java-test/src/main/resources/JavaTypeGoat.java index 61953059cab..40e1696a15a 100644 --- a/rewrite-java-test/src/main/resources/JavaTypeGoat.java +++ b/rewrite-java-test/src/main/resources/JavaTypeGoat.java @@ -15,6 +15,7 @@ */ package org.openrewrite.java; +import java.io.FileNotFoundException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,6 +26,8 @@ public abstract class JavaTypeGoat & C> { public static final PT parameterizedField = new PT() { }; + public static final Double PI = 3.14; + public static final double PI_PRIMITIVE = 3.14; public static abstract class InheritedJavaTypeGoat & C> extends JavaTypeGoat { public InheritedJavaTypeGoat() { @@ -73,6 +76,9 @@ public static class TypeB {} public abstract & C> U genericIntersection(U n); public abstract T genericT(T n); // remove after signatures are common. public abstract & Intersection> void recursiveIntersection(U n); + public abstract T nameShadow(T t); + public abstract void throwsException() throws FileNotFoundException; + public abstract void throwsGenericException() throws T, InterruptedException; } interface C { From 15740e4b31de5a06cfa9f15a0800720637b2fc0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Schn=C3=A9ider?= Date: Wed, 25 Dec 2024 12:24:55 +0100 Subject: [PATCH 12/16] Support mapping of generic thrown exception types (#4813) --- .../openrewrite/groovy/GroovyTypeMapping.java | 2 +- .../isolated/ReloadableJava11TypeMapping.java | 36 +++--------------- .../isolated/ReloadableJava17TypeMapping.java | 38 ++++--------------- .../isolated/ReloadableJava21TypeMapping.java | 36 +++--------------- .../java/ReloadableJava8TypeMapping.java | 36 +++--------------- .../openrewrite/java/JavaTypeMappingTest.java | 24 ++++++++++++ .../java/JavaTemplateTest6Test.java | 4 +- .../org/openrewrite/java/JavaTypeVisitor.java | 2 +- .../java/UnsafeJavaTypeVisitor.java | 2 +- .../internal/JavaReflectionTypeMapping.java | 9 ++--- .../template/JavaTemplateJavaExtension.java | 4 +- .../org/openrewrite/java/tree/JavaType.java | 38 +++++++++---------- 12 files changed, 80 insertions(+), 151 deletions(-) diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyTypeMapping.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyTypeMapping.java index 872160fa148..882943a2fb6 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyTypeMapping.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyTypeMapping.java @@ -244,7 +244,7 @@ private JavaType genericType(GenericsType g, String signature) { } } - List thrownExceptions = null; + List thrownExceptions = null; if(node.getExceptions() != null) { for (ClassNode e : node.getExceptions()) { thrownExceptions = new ArrayList<>(node.getExceptions().length); diff --git a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java index d0b90bea744..00ba35afbd5 100644 --- a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java +++ b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java @@ -492,7 +492,7 @@ public JavaType.Primitive primitive(TypeTag tag) { JavaType returnType = null; List parameterTypes = null; - List exceptionTypes = null; + List exceptionTypes = null; if (selectType instanceof Type.MethodType) { Type.MethodType methodType = (Type.MethodType) selectType; @@ -512,20 +512,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } else if (selectType instanceof Type.UnknownType) { @@ -603,7 +591,7 @@ public JavaType.Primitive primitive(TypeTag tag) { ((Type.ForAll) methodSymbol.type).qtype : methodSymbol.type; - List exceptionTypes = null; + List exceptionTypes = null; Type selectType = methodSymbol.type; if (selectType instanceof Type.ForAll) { @@ -615,20 +603,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } diff --git a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java index 7d5ad9da3f6..d3a1ee1c9a7 100644 --- a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java +++ b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java @@ -500,7 +500,7 @@ public JavaType.Primitive primitive(TypeTag tag) { JavaType returnType = null; List parameterTypes = null; - List exceptionTypes = null; + List exceptionTypes = null; if (selectType instanceof Type.MethodType) { Type.MethodType methodType = (Type.MethodType) selectType; @@ -520,20 +520,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } else if (selectType instanceof Type.UnknownType) { @@ -590,7 +578,7 @@ public JavaType.Primitive primitive(TypeTag tag) { } else { try { defaultValues = Collections.singletonList(methodSymbol.getDefaultValue().getValue().toString()); - } catch(UnsupportedOperationException e) { + } catch (UnsupportedOperationException e) { // not all Attribute implementations define `getValue()` } } @@ -611,7 +599,7 @@ public JavaType.Primitive primitive(TypeTag tag) { ((Type.ForAll) methodSymbol.type).qtype : methodSymbol.type; - List exceptionTypes = null; + List exceptionTypes = null; Type selectType = methodSymbol.type; if (selectType instanceof Type.ForAll) { @@ -623,20 +611,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } diff --git a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java index 10d9b202c6f..bde8ecb7573 100644 --- a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java +++ b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java @@ -511,7 +511,7 @@ public JavaType.Primitive primitive(TypeTag tag) { JavaType returnType = null; List parameterTypes = null; - List exceptionTypes = null; + List exceptionTypes = null; if (selectType instanceof Type.MethodType) { Type.MethodType methodType = (Type.MethodType) selectType; @@ -531,20 +531,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } else if (selectType instanceof Type.UnknownType) { @@ -622,7 +610,7 @@ public JavaType.Primitive primitive(TypeTag tag) { ((Type.ForAll) methodSymbol.type).qtype : methodSymbol.type; - List exceptionTypes = null; + List exceptionTypes = null; Type selectType = methodSymbol.type; if (selectType instanceof Type.ForAll) { @@ -634,20 +622,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } diff --git a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java index 988b0920206..9beaba2727b 100644 --- a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java +++ b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java @@ -494,7 +494,7 @@ public JavaType.Primitive primitive(TypeTag tag) { JavaType returnType = null; List parameterTypes = null; - List exceptionTypes = null; + List exceptionTypes = null; if (selectType instanceof Type.MethodType) { Type.MethodType methodType = (Type.MethodType) selectType; @@ -514,20 +514,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } else if (selectType instanceof Type.UnknownType) { @@ -604,7 +592,7 @@ public JavaType.Primitive primitive(TypeTag tag) { ((Type.ForAll) methodSymbol.type).qtype : methodSymbol.type; - List exceptionTypes = null; + List exceptionTypes = null; Type selectType = methodSymbol.type; if (selectType instanceof Type.ForAll) { @@ -616,20 +604,8 @@ public JavaType.Primitive primitive(TypeTag tag) { if (!methodType.thrown.isEmpty()) { exceptionTypes = new ArrayList<>(methodType.thrown.size()); for (Type exceptionType : methodType.thrown) { - JavaType.FullyQualified javaType = TypeUtils.asFullyQualified(type(exceptionType)); - if (javaType == null) { - // if the type cannot be resolved to a class (it might not be on the classpath, or it might have - // been mapped to cyclic) - if (exceptionType instanceof Type.ClassType) { - Symbol.ClassSymbol sym = (Symbol.ClassSymbol) exceptionType.tsym; - javaType = new JavaType.Class(null, Flag.Public.getBitMask(), sym.flatName().toString(), JavaType.Class.Kind.Class, - null, null, null, null, null, null, null); - } - } - if (javaType != null) { - // if the exception type is not resolved, it is not added to the list of exceptions - exceptionTypes.add(javaType); - } + JavaType javaType = type(exceptionType); + exceptionTypes.add(javaType); } } } diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java index 3783a9365cf..2eba1ba1e0f 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java @@ -53,6 +53,16 @@ default JavaType firstMethodParameter(String methodName) { return methodType(methodName).getParameterTypes().get(0); } + @Test + default void declaringTypeRefersToParameterizedClass() { + JavaType.FullyQualified declaringType = methodType("nameShadow").getDeclaringType(); + assertThat(declaringType.getTypeParameters()) + .describedAs("If it points to the raw class, " + + "method level name shadowing of generic " + + "type variables cannot be detected.") + .isNotEmpty(); + } + @Test default void javaLangObjectHasNoSupertype() { assertThat(goatType().getSupertype().getSupertype()).isNull(); @@ -242,4 +252,18 @@ default void recursiveIntersection() { JavaType.GenericTypeVariable clazz = TypeUtils.asGeneric(firstMethodParameter("recursiveIntersection")); assertThat(clazz.toString()).isEqualTo("Generic{U extends org.openrewrite.java.JavaTypeGoat$Extension & org.openrewrite.java.Intersection}"); } + + @Test + default void throwsGenericExceptions() { + JavaType.Method method = methodType("throwsGenericException"); + JavaType ex = method.getThrownExceptions().get(0); + + assertThat(ex).isInstanceOf(JavaType.GenericTypeVariable.class); + + JavaType.GenericTypeVariable generic = (JavaType.GenericTypeVariable) ex; + assertThat(generic.getName()).isEqualTo("T"); + assertThat(generic.getVariance()).isEqualTo(COVARIANT); + assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(0)) + .getFullyQualifiedName()).isEqualTo("java.io.FileNotFoundException"); + } } diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest6Test.java b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest6Test.java index b6dd28e6764..4b8cdb9d754 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest6Test.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateTest6Test.java @@ -255,7 +255,9 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex })).afterRecipe(run -> { J.CompilationUnit cu = (J.CompilationUnit) run.getChangeset().getAllResults().get(0).getAfter(); J.MethodDeclaration testMethodDecl = (J.MethodDeclaration) cu.getClasses().get(0).getBody().getStatements().get(0); - assertThat(testMethodDecl.getMethodType().getThrownExceptions().stream().map(JavaType.FullyQualified::getFullyQualifiedName)) + assertThat(testMethodDecl.getMethodType().getThrownExceptions().stream() + .map(JavaType.FullyQualified.class::cast) + .map(JavaType.FullyQualified::getFullyQualifiedName)) .containsExactly("java.lang.Exception"); }), java( diff --git a/rewrite-java/src/main/java/org/openrewrite/java/JavaTypeVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/JavaTypeVisitor.java index f06a3501ec4..29ddbf14870 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/JavaTypeVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/JavaTypeVisitor.java @@ -148,7 +148,7 @@ public JavaType visitMethod(JavaType.Method method, P p) { m = m.withDeclaringType((JavaType.FullyQualified) visit(m.getDeclaringType(), p)); m = m.withReturnType(visit(m.getReturnType(), p)); m = m.withParameterTypes(ListUtils.map(m.getParameterTypes(), pt -> visit(pt, p))); - m = m.withThrownExceptions(ListUtils.map(m.getThrownExceptions(), t -> (JavaType.FullyQualified) visit(t, p))); + m = m.withThrownExceptions(ListUtils.map(m.getThrownExceptions(), t -> visit(t, p))); m = m.withAnnotations(ListUtils.map(m.getAnnotations(), a -> (JavaType.FullyQualified) visit(a, p))); return m; } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/UnsafeJavaTypeVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/UnsafeJavaTypeVisitor.java index 8eee53b3624..a28e6547241 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/UnsafeJavaTypeVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/UnsafeJavaTypeVisitor.java @@ -69,7 +69,7 @@ public JavaType visitMethod(JavaType.Method method, P p) { (JavaType.FullyQualified) visit(method.getDeclaringType(), p), visit(method.getReturnType(), p), mapInPlace(method.getParameterTypes().toArray(EMPTY_JAVA_TYPE_ARRAY), pt -> visit(pt, p)), - mapInPlace(method.getThrownExceptions().toArray(EMPTY_FULLY_QUALIFIED_ARRAY), t -> (JavaType.FullyQualified) visit(t, p)), + mapInPlace(method.getThrownExceptions().toArray(EMPTY_JAVA_TYPE_ARRAY), t -> visit(t, p)), mapInPlace(method.getAnnotations().toArray(EMPTY_FULLY_QUALIFIED_ARRAY), a -> (JavaType.FullyQualified) visit(a, p)) ); } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java index 440217560b4..ef7ee8de348 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java @@ -345,7 +345,7 @@ private JavaType.Method method(Constructor method, JavaType.FullyQualified de ); typeCache.put(signature, mappedMethod); - List thrownExceptions = null; + List thrownExceptions = null; if (method.getExceptionTypes().length > 0) { thrownExceptions = new ArrayList<>(method.getExceptionTypes().length); for (Class e : method.getExceptionTypes()) { @@ -451,12 +451,11 @@ private JavaType.Method method(Method method, JavaType.FullyQualified declaringT ); typeCache.put(signature, mappedMethod); - List thrownExceptions = null; + List thrownExceptions = null; if (method.getExceptionTypes().length > 0) { thrownExceptions = new ArrayList<>(method.getExceptionTypes().length); - for (Class e : method.getExceptionTypes()) { - JavaType.FullyQualified fullyQualified = (JavaType.FullyQualified) type(e); - thrownExceptions.add(fullyQualified); + for (Type e : method.getGenericExceptionTypes()) { + thrownExceptions.add(type(e)); } } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java index cfd9b9ea548..476aeaa2e03 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java @@ -354,11 +354,11 @@ public J visitMethodDeclaration(J.MethodDeclaration method, Integer p) { // Update method type information to reflect the new checked exceptions JavaType.Method type = m.getMethodType(); if (type != null) { - List newThrows = new ArrayList<>(); + List newThrows = new ArrayList<>(); List throws_ = (m.getThrows() == null) ? emptyList() : m.getThrows(); for (NameTree t : throws_) { J.Identifier exceptionIdent = (J.Identifier) t; - newThrows.add((JavaType.FullyQualified) exceptionIdent.getType()); + newThrows.add(exceptionIdent.getType()); } type = type.withThrownExceptions(newThrows); } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java index 171a6a2198e..95d936ff2df 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java @@ -323,16 +323,16 @@ public String getPackageName() { public boolean isAssignableTo(String fullyQualifiedName) { return TypeUtils.fullyQualifiedNamesAreEqual(getFullyQualifiedName(), fullyQualifiedName) || - getInterfaces().stream().anyMatch(anInterface -> anInterface.isAssignableTo(fullyQualifiedName)) || - (getSupertype() != null && getSupertype().isAssignableTo(fullyQualifiedName)); + getInterfaces().stream().anyMatch(anInterface -> anInterface.isAssignableTo(fullyQualifiedName)) || + (getSupertype() != null && getSupertype().isAssignableTo(fullyQualifiedName)); } public boolean isAssignableFrom(@Nullable JavaType type) { if (type instanceof FullyQualified) { FullyQualified clazz = (FullyQualified) type; return TypeUtils.fullyQualifiedNamesAreEqual(getFullyQualifiedName(), clazz.getFullyQualifiedName()) || - isAssignableFrom(clazz.getSupertype()) || - clazz.getInterfaces().stream().anyMatch(this::isAssignableFrom); + isAssignableFrom(clazz.getSupertype()) || + clazz.getInterfaces().stream().anyMatch(this::isAssignableFrom); } else if (type instanceof GenericTypeVariable) { GenericTypeVariable generic = (GenericTypeVariable) type; for (JavaType bound : generic.getBounds()) { @@ -576,7 +576,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Class aClass = (Class) o; return TypeUtils.fullyQualifiedNamesAreEqual(fullyQualifiedName, aClass.fullyQualifiedName) && - (typeParameters == null && aClass.typeParameters == null || typeParameters != null && Arrays.equals(typeParameters, aClass.typeParameters)); + (typeParameters == null && aClass.typeParameters == null || typeParameters != null && Arrays.equals(typeParameters, aClass.typeParameters)); } @Override @@ -853,7 +853,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; GenericTypeVariable that = (GenericTypeVariable) o; return name.equals(that.name) && variance == that.variance && - (variance == Variance.INVARIANT && bounds == null && that.bounds == null || bounds != null && Arrays.equals(bounds, that.bounds)); + (variance == Variance.INVARIANT && bounds == null && that.bounds == null || bounds != null && Arrays.equals(bounds, that.bounds)); } @Override @@ -1106,7 +1106,7 @@ class Method implements JavaType { JavaType @Nullable [] parameterTypes; @NonFinal - FullyQualified @Nullable [] thrownExceptions; + JavaType @Nullable [] thrownExceptions; @NonFinal FullyQualified @Nullable [] annotations; @@ -1118,7 +1118,7 @@ class Method implements JavaType { public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, @Nullable List parameterNames, - @Nullable List parameterTypes, @Nullable List thrownExceptions, + @Nullable List parameterTypes, @Nullable List thrownExceptions, @Nullable List annotations) { this(managedReference, flagsBitMap, declaringType, name, returnType, parameterNames, parameterTypes, thrownExceptions, annotations, null); @@ -1126,7 +1126,7 @@ public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable Fu public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, @Nullable List parameterNames, - @Nullable List parameterTypes, @Nullable List thrownExceptions, + @Nullable List parameterTypes, @Nullable List thrownExceptions, @Nullable List annotations, @Nullable List defaultValue) { this( managedReference, @@ -1144,7 +1144,7 @@ public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable Fu public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, String @Nullable [] parameterNames, - JavaType @Nullable [] parameterTypes, FullyQualified @Nullable [] thrownExceptions, + JavaType @Nullable [] parameterTypes, JavaType @Nullable [] thrownExceptions, FullyQualified @Nullable [] annotations, @Nullable List defaultValue) { this.managedReference = managedReference; this.flagsBitMap = flagsBitMap & Flag.VALID_FLAGS; @@ -1171,12 +1171,12 @@ public Method unsafeSetManagedReference(Integer id) { public Method unsafeSet(@Nullable FullyQualified declaringType, @Nullable JavaType returnType, @Nullable List parameterTypes, - @Nullable List thrownExceptions, + @Nullable List thrownExceptions, @Nullable List annotations) { this.declaringType = unknownIfNull(declaringType); this.returnType = unknownIfNull(returnType); this.parameterTypes = arrayOrNullIfEmpty(parameterTypes, EMPTY_JAVA_TYPE_ARRAY); - this.thrownExceptions = arrayOrNullIfEmpty(thrownExceptions, EMPTY_FULLY_QUALIFIED_ARRAY); + this.thrownExceptions = arrayOrNullIfEmpty(thrownExceptions, EMPTY_JAVA_TYPE_ARRAY); this.annotations = arrayOrNullIfEmpty(annotations, EMPTY_FULLY_QUALIFIED_ARRAY); return this; } @@ -1184,7 +1184,7 @@ public Method unsafeSet(@Nullable FullyQualified declaringType, public Method unsafeSet(@Nullable FullyQualified declaringType, @Nullable JavaType returnType, JavaType @Nullable [] parameterTypes, - FullyQualified @Nullable [] thrownExceptions, + JavaType @Nullable [] thrownExceptions, FullyQualified @Nullable [] annotations) { this.declaringType = unknownIfNull(declaringType); this.returnType = unknownIfNull(returnType); @@ -1312,12 +1312,12 @@ public Method withParameterTypes(@Nullable List parameterTypes) { this.parameterNames, parameterTypesArray, this.thrownExceptions, this.annotations, this.defaultValue); } - public List getThrownExceptions() { + public List getThrownExceptions() { return thrownExceptions == null ? emptyList() : Arrays.asList(thrownExceptions); } - public Method withThrownExceptions(@Nullable List thrownExceptions) { - FullyQualified[] thrownExceptionsArray = arrayOrNullIfEmpty(thrownExceptions, EMPTY_FULLY_QUALIFIED_ARRAY); + public Method withThrownExceptions(@Nullable List thrownExceptions) { + JavaType[] thrownExceptionsArray = arrayOrNullIfEmpty(thrownExceptions, EMPTY_JAVA_TYPE_ARRAY); if (Arrays.equals(thrownExceptionsArray, this.thrownExceptions)) { return this; } @@ -1356,9 +1356,9 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Method method = (Method) o; return Objects.equals(declaringType, method.declaringType) && - name.equals(method.name) && - Objects.equals(returnType, method.returnType) && - Arrays.equals(parameterTypes, method.parameterTypes); + name.equals(method.name) && + Objects.equals(returnType, method.returnType) && + Arrays.equals(parameterTypes, method.parameterTypes); } @Override From 5b14eb08401a4878367627e9762190a9bbbb4a43 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Wed, 25 Dec 2024 12:26:32 +0100 Subject: [PATCH 13/16] refactor: Enum values should be compared with "==" (#4811) Use this link to re-run the recipe: https://app.moderne.io/recipes/org.openrewrite.staticanalysis.CompareEnumsWithEqualityOperator?organizationId=T3BlblJld3JpdGU%3D Co-authored-by: Moderne --- .../openrewrite/SourceFileWithReferences.java | 2 +- .../config/YamlResourceLoader.java | 2 +- .../RemoveRedundantDependencyVersions.java | 8 ++--- .../groovy/GroovyParserVisitor.java | 2 +- .../java/org/openrewrite/hcl/HclTemplate.java | 10 +++--- .../hcl/format/AttributeSpaceVisitor.java | 4 +-- .../hcl/format/BracketsVisitor.java | 4 +-- .../hcl/format/TabsAndIndentsVisitor.java | 8 ++--- .../openrewrite/hcl/internal/HclPrinter.java | 2 +- .../openrewrite/hcl/tree/HclCoordinates.java | 2 +- .../java/org/openrewrite/hcl/tree/Space.java | 4 +-- ...ReloadableJava11ParserInputFileObject.java | 2 +- .../ReloadableJava11ParserVisitor.java | 2 +- ...ReloadableJava17ParserInputFileObject.java | 2 +- .../ReloadableJava17ParserVisitor.java | 2 +- ...ReloadableJava21ParserInputFileObject.java | 2 +- .../ReloadableJava21ParserVisitor.java | 2 +- .../java/Java8ParserInputFileObject.java | 2 +- .../java/ReloadableJava8Parser.java | 2 +- .../java/ReloadableJava8ParserVisitor.java | 2 +- .../org/openrewrite/java/JavaPrinter.java | 2 +- .../org/openrewrite/java/JavaVisitor.java | 2 +- .../org/openrewrite/java/PackageMatcher.java | 2 +- .../org/openrewrite/java/TypeMatcher.java | 2 +- .../openrewrite/java/VariableNameUtils.java | 2 +- .../java/format/TabsAndIndentsVisitor.java | 16 ++++----- .../BlockStatementTemplateGenerator.java | 2 +- .../template/JavaTemplateJavaExtension.java | 34 +++++++++---------- .../java/internal/template/Substitutions.java | 2 +- .../openrewrite/java/style/Autodetect.java | 2 +- .../java/tree/JavaCoordinates.java | 2 +- .../openrewrite/maven/RemoveDependency.java | 2 +- .../maven/RemoveManagedDependency.java | 2 +- .../RemoveRedundantDependencyVersions.java | 10 +++--- .../internal/InsertDependencyComparator.java | 2 +- .../org/openrewrite/xml/XmlParserTest.java | 4 +-- 36 files changed, 77 insertions(+), 77 deletions(-) diff --git a/rewrite-core/src/main/java/org/openrewrite/SourceFileWithReferences.java b/rewrite-core/src/main/java/org/openrewrite/SourceFileWithReferences.java index d53fa550e7a..0a8bb5faad8 100644 --- a/rewrite-core/src/main/java/org/openrewrite/SourceFileWithReferences.java +++ b/rewrite-core/src/main/java/org/openrewrite/SourceFileWithReferences.java @@ -45,7 +45,7 @@ public Collection findMatches(Reference.Matcher matcher, Reference.Ki private List findMatchesInternal(Reference.Matcher matcher, Reference.@Nullable Kind kind) { List list = new ArrayList<>(); for (Reference ref : references) { - if ((kind == null || ref.getKind().equals(kind)) && ref.matches(matcher) ) { + if ((kind == null || ref.getKind() == kind) && ref.matches(matcher) ) { list.add(ref); } } diff --git a/rewrite-core/src/main/java/org/openrewrite/config/YamlResourceLoader.java b/rewrite-core/src/main/java/org/openrewrite/config/YamlResourceLoader.java index 7d1f24d8ad1..1984d383600 100644 --- a/rewrite-core/src/main/java/org/openrewrite/config/YamlResourceLoader.java +++ b/rewrite-core/src/main/java/org/openrewrite/config/YamlResourceLoader.java @@ -200,7 +200,7 @@ private Collection> loadResources(ResourceType resourceType) for (Object resource : yaml.loadAll(yamlSource)) { if (resource instanceof Map) { @SuppressWarnings("unchecked") Map resourceMap = (Map) resource; - if (resourceType.equals(ResourceType.fromSpec((String) resourceMap.get("type")))) { + if (resourceType == ResourceType.fromSpec((String) resourceMap.get("type"))) { resources.add(resourceMap); } } diff --git a/rewrite-gradle/src/main/java/org/openrewrite/gradle/RemoveRedundantDependencyVersions.java b/rewrite-gradle/src/main/java/org/openrewrite/gradle/RemoveRedundantDependencyVersions.java index 3aaa09f6a4e..a2cd1dab3b3 100644 --- a/rewrite-gradle/src/main/java/org/openrewrite/gradle/RemoveRedundantDependencyVersions.java +++ b/rewrite-gradle/src/main/java/org/openrewrite/gradle/RemoveRedundantDependencyVersions.java @@ -292,7 +292,7 @@ private boolean matchesComparator(@Nullable String managedVersion, String reques if (managedVersion == null) { return false; } - if (comparator.equals(Comparator.ANY)) { + if (comparator == Comparator.ANY) { return true; } if (!isExact(managedVersion)) { @@ -301,11 +301,11 @@ private boolean matchesComparator(@Nullable String managedVersion, String reques int comparison = new LatestIntegration(null) .compare(null, managedVersion, requestedVersion); if (comparison < 0) { - return comparator.equals(Comparator.LT) || comparator.equals(Comparator.LTE); + return comparator == Comparator.LT || comparator == Comparator.LTE; } else if (comparison > 0) { - return comparator.equals(Comparator.GT) || comparator.equals(Comparator.GTE); + return comparator == Comparator.GT || comparator == Comparator.GTE; } else { - return comparator.equals(Comparator.EQ) || comparator.equals(Comparator.LTE) || comparator.equals(Comparator.GTE); + return comparator == Comparator.EQ || comparator == Comparator.LTE || comparator == Comparator.GTE; } } diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java index 5ce8d628352..af660485f32 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java @@ -1100,7 +1100,7 @@ public void visitBlockStatement(BlockStatement block) { J expr = visit(statement); if (i == blockStatements.size() - 1 && (expr instanceof Expression)) { if (parent instanceof ClosureExpression || (parent instanceof MethodNode && - !JavaType.Primitive.Void.equals(typeMapping.type(((MethodNode) parent).getReturnType())))) { + JavaType.Primitive.Void != typeMapping.type(((MethodNode) parent).getReturnType()))) { expr = new J.Return(randomId(), expr.getPrefix(), Markers.EMPTY, expr.withPrefix(EMPTY)); expr = expr.withMarkers(expr.getMarkers().add(new ImplicitReturn(randomId()))); diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/HclTemplate.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/HclTemplate.java index 5fb3297f4c3..e7b2dd0933e 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/HclTemplate.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/HclTemplate.java @@ -69,7 +69,7 @@ public H apply(Cursor scope, HclCoordinates coordinates, Object. @Override public Hcl visitConfigFile(Hcl.ConfigFile configFile, Integer p) { Hcl.ConfigFile c = (Hcl.ConfigFile) super.visitConfigFile(configFile, p); - if (loc.equals(Space.Location.CONFIG_FILE_EOF)) { + if (loc == Space.Location.CONFIG_FILE_EOF) { List gen = substitutions.unsubstitute(templateParser.parseBodyContent(substitutedTemplate)); if (coordinates.getComparator() != null) { @@ -100,7 +100,7 @@ public Hcl visitConfigFile(Hcl.ConfigFile configFile, Integer p) { ) ); } - } else if (loc.equals(Space.Location.CONFIG_FILE)) { + } else if (loc == Space.Location.CONFIG_FILE) { List gen = substitutions.unsubstitute(templateParser.parseBodyContent(substitutedTemplate)); c = c.withBody( ListUtils.concatAll( @@ -116,7 +116,7 @@ public Hcl visitConfigFile(Hcl.ConfigFile configFile, Integer p) { @Override public Hcl visitBlock(Hcl.Block block, Integer p) { Hcl.Block b = (Hcl.Block) super.visitBlock(block, p); - if (loc.equals(Space.Location.BLOCK_CLOSE)) { + if (loc == Space.Location.BLOCK_CLOSE) { if (b.isScope(insertionPoint)) { List gen = substitutions.unsubstitute(templateParser.parseBodyContent(substitutedTemplate)); @@ -145,7 +145,7 @@ public Hcl visitBlock(Hcl.Block block, Integer p) { .orElse(SpacesStyle.DEFAULT)).visit(b, p, getCursor().getParentOrThrow()); assert b != null; } - } else if (loc.equals(Space.Location.BLOCK)) { + } else if (loc == Space.Location.BLOCK) { if (b.isScope(insertionPoint)) { b = (Hcl.Block) autoFormat(templateParser.parseBodyContent(substitutedTemplate).get(0), p, getCursor().getParentOrThrow()); @@ -158,7 +158,7 @@ public Hcl visitBlock(Hcl.Block block, Integer p) { public Hcl visitExpression(Expression expression, Integer p) { Hcl e = super.visitExpression(expression, p); - if (loc.equals(Space.Location.EXPRESSION_PREFIX)) { + if (loc == Space.Location.EXPRESSION_PREFIX) { if (e.isScope(insertionPoint)) { e = templateParser.parseExpression(substitutedTemplate).withPrefix(expression.getPrefix()); } diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/AttributeSpaceVisitor.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/AttributeSpaceVisitor.java index dc497dd9af1..a384b1d7d4b 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/AttributeSpaceVisitor.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/AttributeSpaceVisitor.java @@ -52,7 +52,7 @@ public Hcl.Attribute visitAttribute(Hcl.Attribute attribute, P p) { if (parent instanceof Hcl.Block || parent instanceof Hcl.ObjectValue) { List siblingAttributes = getSiblingAttributes(parent); - if (attribute.getType().equals(Hcl.Attribute.Type.Assignment)) { + if (attribute.getType() == Hcl.Attribute.Type.Assignment) { HclLeftPadded type = a.getPadding().getType(); if (Boolean.TRUE.equals(style.getBodyContent().getColumnarAlignment())) { @@ -106,7 +106,7 @@ private List attributesInGroup(List siblings, Hcl. boolean groupFound = false; Hcl.Attribute perviousSibling = null; for (Hcl.Attribute sibling : siblings) { - if (sibling.getType().equals(Hcl.Attribute.Type.Assignment)) { + if (sibling.getType() == Hcl.Attribute.Type.Assignment) { boolean siblingPrefixHasNewLines = sibling.getPrefix().getWhitespace().split("\r\n|\r|\n").length > 2; boolean siblingIsMultiline = sibling.getValue().print(getCursor()).split("\r\n|\r|\n").length > 2; boolean previousSiblingIsMultiline = perviousSibling != null && perviousSibling.getValue().print(getCursor()).split("\r\n|\r|\n").length > 2; diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/BracketsVisitor.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/BracketsVisitor.java index 6bbd596c11e..cb885fa0818 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/BracketsVisitor.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/BracketsVisitor.java @@ -42,11 +42,11 @@ public BracketsVisitor(BracketsStyle style, @Nullable Tree stopAfter) { @Override public Space visitSpace(Space space, Space.Location loc, P p) { - if (loc.equals(Space.Location.BLOCK_CLOSE) && !space.getLastWhitespace().contains("\n")) { + if (loc == Space.Location.BLOCK_CLOSE && !space.getLastWhitespace().contains("\n")) { return space.withLastWhitespace("\n"); } - if (loc.equals(Space.Location.BLOCK_OPEN) && !space.getWhitespace().equals(" ")) { + if (loc == Space.Location.BLOCK_OPEN && !space.getWhitespace().equals(" ")) { return space.withWhitespace(" "); } diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/TabsAndIndentsVisitor.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/TabsAndIndentsVisitor.java index 8c2be10c242..1b561786f24 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/TabsAndIndentsVisitor.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/format/TabsAndIndentsVisitor.java @@ -103,7 +103,7 @@ public Space visitSpace(Space space, Space.Location loc, P p) { IndentType indentType = getCursor().getParentOrThrow().getNearestMessage("indentType", IndentType.ALIGN); // block spaces are always aligned to their parent - boolean alignBlockToParent = loc.equals(Space.Location.BLOCK_CLOSE) || loc.equals(Space.Location.OBJECT_VALUE_ATTRIBUTE_SUFFIX); + boolean alignBlockToParent = loc == Space.Location.BLOCK_CLOSE || loc == Space.Location.OBJECT_VALUE_ATTRIBUTE_SUFFIX; if (alignBlockToParent) { indentType = IndentType.ALIGN; @@ -266,7 +266,7 @@ private Space indentTo(Space space, int column, Space.Location spaceLocation) { space = space.withComments(ListUtils.map(space.getComments(), c -> { // The suffix of the last element in the comment list sets the whitespace for the end of the block. // The column for comments that come before the last element are incremented. - int incrementBy = spaceLocation.equals(Space.Location.BLOCK_CLOSE) && !c.equals(lastElement) ? style.getIndentSize() : 0; + int incrementBy = spaceLocation == Space.Location.BLOCK_CLOSE && !c.equals(lastElement) ? style.getIndentSize() : 0; return c.getStyle() == Comment.Style.INLINE ? indentMultilineComment(c, column + incrementBy) : indentSingleLineComment(c, column + incrementBy); @@ -274,8 +274,8 @@ private Space indentTo(Space space, int column, Space.Location spaceLocation) { // Prevent formatting trailing comments, the whitespace in a trailing comment won't have a new line character. // Compilation unit prefixes are an exception, since they do not exist in a block. - if (space.getWhitespace().contains("\n") || spaceLocation.equals(Space.Location.CONFIG_FILE)) { - int incrementBy = spaceLocation.equals(Space.Location.BLOCK_CLOSE) ? style.getIndentSize() : 0; + if (space.getWhitespace().contains("\n") || spaceLocation == Space.Location.CONFIG_FILE) { + int incrementBy = spaceLocation == Space.Location.BLOCK_CLOSE ? style.getIndentSize() : 0; int indent = getLengthOfWhitespace(space.getWhitespace()); if (indent != (column + incrementBy)) { int shift = column + incrementBy - indent; diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/internal/HclPrinter.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/internal/HclPrinter.java index 76bb09325a4..125040cbc4f 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/internal/HclPrinter.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/internal/HclPrinter.java @@ -90,7 +90,7 @@ public Hcl visitAttribute(Hcl.Attribute attribute, PrintOutputCapture

p) { beforeSyntax(attribute, Space.Location.ATTRIBUTE, p); visit(attribute.getName(), p); visitSpace(attribute.getPadding().getType().getBefore(), Space.Location.ATTRIBUTE_ASSIGNMENT, p); - p.append(attribute.getType().equals(Hcl.Attribute.Type.Assignment) ? "=" : ":"); + p.append(attribute.getType() == Hcl.Attribute.Type.Assignment ? "=" : ":"); visit(attribute.getValue(), p); if (attribute.getComma() != null) { visitSpace(attribute.getComma().getPrefix(), Space.Location.OBJECT_VALUE_ATTRIBUTE_COMMA, p); diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/HclCoordinates.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/HclCoordinates.java index 5616b533f28..39327ffbddb 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/HclCoordinates.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/HclCoordinates.java @@ -34,7 +34,7 @@ public class HclCoordinates implements Coordinates { Comparator comparator; public boolean isReplacement() { - return Mode.REPLACEMENT.equals(mode); + return Mode.REPLACEMENT == mode; } public enum Mode { diff --git a/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/Space.java b/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/Space.java index 48d5282eb67..1b4c56e5bdc 100644 --- a/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/Space.java +++ b/rewrite-hcl/src/main/java/org/openrewrite/hcl/tree/Space.java @@ -156,7 +156,7 @@ public static Space format(String formatting) { for (char c : charArray) { switch (c) { case '#': - if (Comment.Style.LINE_SLASH.equals(inLineSlashOrHashComment)) { + if (Comment.Style.LINE_SLASH == inLineSlashOrHashComment) { comment.append(c); } else { if (inSingleLineComment) { @@ -169,7 +169,7 @@ public static Space format(String formatting) { } break; case '/': - if (Comment.Style.LINE_HASH.equals(inLineSlashOrHashComment)) { + if (Comment.Style.LINE_HASH == inLineSlashOrHashComment) { comment.append(c); } else { if (inSingleLineComment) { diff --git a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserInputFileObject.java b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserInputFileObject.java index 6ff41fecbd5..e117030dc6f 100644 --- a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserInputFileObject.java +++ b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserInputFileObject.java @@ -111,7 +111,7 @@ public Kind getKind() { @Override public boolean isNameCompatible(String simpleName, Kind kind) { String baseName = simpleName + kind.extension; - return kind.equals(getKind()) && + return kind == getKind() && path.getFileName().toString().equals(baseName); } diff --git a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserVisitor.java b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserVisitor.java index 22086c5db31..ac0714e55af 100644 --- a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserVisitor.java +++ b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11ParserVisitor.java @@ -761,7 +761,7 @@ public J visitLiteral(LiteralTree node, Space fmt) { singletonList(new J.Literal.UnicodeEscape(1, valueSource.substring(3, valueSource.length() - 1))), type); } - } else if (JavaType.Primitive.String.equals(type)) { + } else if (JavaType.Primitive.String == type) { StringBuilder valueSourceWithoutSurrogates = new StringBuilder(); List unicodeEscapes = null; diff --git a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserInputFileObject.java b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserInputFileObject.java index 49e01f39290..f4e6faf4c6d 100644 --- a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserInputFileObject.java +++ b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserInputFileObject.java @@ -111,7 +111,7 @@ public Kind getKind() { @Override public boolean isNameCompatible(String simpleName, Kind kind) { String baseName = simpleName + kind.extension; - return kind.equals(getKind()) && + return kind == getKind() && path.getFileName().toString().equals(baseName); } diff --git a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java index 6dea46ebda4..673d84fff4e 100644 --- a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java +++ b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java @@ -826,7 +826,7 @@ public J visitLiteral(LiteralTree node, Space fmt) { singletonList(new J.Literal.UnicodeEscape(1, valueSource.substring(3, valueSource.length() - 1))), type); } - } else if (JavaType.Primitive.String.equals(type)) { + } else if (JavaType.Primitive.String == type) { StringBuilder valueSourceWithoutSurrogates = new StringBuilder(); List unicodeEscapes = null; diff --git a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserInputFileObject.java b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserInputFileObject.java index fbb8065f806..8e05405ad90 100644 --- a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserInputFileObject.java +++ b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserInputFileObject.java @@ -111,7 +111,7 @@ public Kind getKind() { @Override public boolean isNameCompatible(String simpleName, Kind kind) { String baseName = simpleName + kind.extension; - return kind.equals(getKind()) && + return kind == getKind() && path.getFileName().toString().equals(baseName); } diff --git a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java index 8fd8d2809d9..0eeba8521e6 100644 --- a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java +++ b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java @@ -823,7 +823,7 @@ public J visitLiteral(LiteralTree node, Space fmt) { singletonList(new J.Literal.UnicodeEscape(1, valueSource.substring(3, valueSource.length() - 1))), type); } - } else if (JavaType.Primitive.String.equals(type)) { + } else if (JavaType.Primitive.String == type) { StringBuilder valueSourceWithoutSurrogates = new StringBuilder(); List unicodeEscapes = null; diff --git a/rewrite-java-8/src/main/java/org/openrewrite/java/Java8ParserInputFileObject.java b/rewrite-java-8/src/main/java/org/openrewrite/java/Java8ParserInputFileObject.java index 122bdce7957..37e1eb655ae 100644 --- a/rewrite-java-8/src/main/java/org/openrewrite/java/Java8ParserInputFileObject.java +++ b/rewrite-java-8/src/main/java/org/openrewrite/java/Java8ParserInputFileObject.java @@ -110,7 +110,7 @@ public Kind getKind() { @Override public boolean isNameCompatible(String simpleName, Kind kind) { String baseName = simpleName + kind.extension; - return kind.equals(getKind()) && + return kind == getKind() && path.getFileName().toString().equals(baseName); } diff --git a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8Parser.java b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8Parser.java index 227b6f3609c..de46c937d0a 100644 --- a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8Parser.java +++ b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8Parser.java @@ -318,7 +318,7 @@ public String inferBinaryName(Location location, JavaFileObject file) { @Override public Iterable list(Location location, String packageName, Set kinds, boolean recurse) throws IOException { - if (StandardLocation.CLASS_PATH.equals(location)) { + if (StandardLocation.CLASS_PATH == location) { Iterable listed = super.list(location, packageName, kinds, recurse); return Stream.concat( classByteClasspath.stream() diff --git a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8ParserVisitor.java b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8ParserVisitor.java index e9123f68062..8a502fd31b8 100644 --- a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8ParserVisitor.java +++ b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8ParserVisitor.java @@ -761,7 +761,7 @@ public J visitLiteral(LiteralTree node, Space fmt) { singletonList(new J.Literal.UnicodeEscape(1, valueSource.substring(3, valueSource.length() - 1))), type); } - } else if (JavaType.Primitive.String.equals(type)) { + } else if (JavaType.Primitive.String == type) { StringBuilder valueSourceWithoutSurrogates = new StringBuilder(); List unicodeEscapes = null; diff --git a/rewrite-java/src/main/java/org/openrewrite/java/JavaPrinter.java b/rewrite-java/src/main/java/org/openrewrite/java/JavaPrinter.java index b75e24d02c3..71a1d56ccac 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/JavaPrinter.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/JavaPrinter.java @@ -537,7 +537,7 @@ public J visitClassDeclaration(ClassDeclaration classDecl, PrintOutputCapture

visitContainer("<", classDecl.getPadding().getTypeParameters(), JContainer.Location.TYPE_PARAMETERS, ",", ">", p); visitContainer("(", classDecl.getPadding().getPrimaryConstructor(), JContainer.Location.RECORD_STATE_VECTOR, ",", ")", p); visitLeftPadded("extends", classDecl.getPadding().getExtends(), JLeftPadded.Location.EXTENDS, p); - visitContainer(classDecl.getKind().equals(ClassDeclaration.Kind.Type.Interface) ? "extends" : "implements", + visitContainer(classDecl.getKind() == ClassDeclaration.Kind.Type.Interface ? "extends" : "implements", classDecl.getPadding().getImplements(), JContainer.Location.IMPLEMENTS, ",", null, p); visitContainer("permits", classDecl.getPadding().getPermits(), JContainer.Location.PERMITS, ",", null, p); visit(classDecl.getBody(), p); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/JavaVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/JavaVisitor.java index eec6aeb187d..be5ca459848 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/JavaVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/JavaVisitor.java @@ -1463,7 +1463,7 @@ protected boolean isInSameNameScope(Cursor base, Cursor child) { Object childScope = it.next(); if (childScope instanceof J.ClassDeclaration) { J.ClassDeclaration childClass = (J.ClassDeclaration) childScope; - if (!(childClass.getKind().equals(J.ClassDeclaration.Kind.Type.Class)) || + if (childClass.getKind() != J.ClassDeclaration.Kind.Type.Class || childClass.hasModifier(J.Modifier.Type.Static)) { //Short circuit the search if a terminating element is encountered. return false; diff --git a/rewrite-java/src/main/java/org/openrewrite/java/PackageMatcher.java b/rewrite-java/src/main/java/org/openrewrite/java/PackageMatcher.java index 9c5f91105dc..55a93b768ab 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/PackageMatcher.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/PackageMatcher.java @@ -38,7 +38,7 @@ public PackageMatcher(@Nullable String targetPackage, boolean recursive) { @Override public boolean matchesReference(Reference reference) { - if (reference.getKind().equals(Reference.Kind.TYPE) || reference.getKind().equals(Reference.Kind.PACKAGE)) { + if (reference.getKind() == Reference.Kind.TYPE || reference.getKind() == Reference.Kind.PACKAGE) { String recursivePackageNamePrefix = targetPackage + "."; if (reference.getValue().equals(targetPackage) || recursive && reference.getValue().startsWith(recursivePackageNamePrefix)) { return true; diff --git a/rewrite-java/src/main/java/org/openrewrite/java/TypeMatcher.java b/rewrite-java/src/main/java/org/openrewrite/java/TypeMatcher.java index 1a1b5aa6f40..4d4f0e4133b 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/TypeMatcher.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/TypeMatcher.java @@ -112,7 +112,7 @@ private static boolean isPlainIdentifier(MethodSignatureParser.TargetTypePattern @Override public boolean matchesReference(Reference reference) { - return reference.getKind().equals(Reference.Kind.TYPE) && matchesTargetTypeName(reference.getValue()); + return reference.getKind() == Reference.Kind.TYPE && matchesTargetTypeName(reference.getValue()); } @Override diff --git a/rewrite-java/src/main/java/org/openrewrite/java/VariableNameUtils.java b/rewrite-java/src/main/java/org/openrewrite/java/VariableNameUtils.java index e9a880d0600..fc4f1ddc048 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/VariableNameUtils.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/VariableNameUtils.java @@ -50,7 +50,7 @@ public static String generateVariableName(String baseName, Cursor scope, Generat Set namesInScope = findNamesInScope(scope); // Generate a new name to prevent namespace shadowing. String newName = baseName; - if (GenerationStrategy.INCREMENT_NUMBER.equals(strategy)) { + if (GenerationStrategy.INCREMENT_NUMBER == strategy) { StringBuilder postFix = new StringBuilder(); char[] charArray = baseName.toCharArray(); for (int i = charArray.length - 1; i >= 0; i--) { diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java index d333c9c04d9..a69183dd763 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java @@ -143,18 +143,18 @@ public Space visitSpace(Space space, Space.Location loc, P p) { // block spaces are always aligned to their parent Object value = getCursor().getValue(); - boolean alignBlockPrefixToParent = loc.equals(Space.Location.BLOCK_PREFIX) && space.getWhitespace().contains("\n") && + boolean alignBlockPrefixToParent = loc == Space.Location.BLOCK_PREFIX && space.getWhitespace().contains("\n") && // ignore init blocks. (value instanceof J.Block && !(getCursor().getParentTreeCursor().getValue() instanceof J.Block)); - boolean alignBlockToParent = loc.equals(Space.Location.BLOCK_END) || - loc.equals(Space.Location.NEW_ARRAY_INITIALIZER_SUFFIX) || - loc.equals(Space.Location.CATCH_PREFIX) || - loc.equals(Space.Location.TRY_FINALLY) || - loc.equals(Space.Location.ELSE_PREFIX); + boolean alignBlockToParent = loc == Space.Location.BLOCK_END || + loc == Space.Location.NEW_ARRAY_INITIALIZER_SUFFIX || + loc == Space.Location.CATCH_PREFIX || + loc == Space.Location.TRY_FINALLY || + loc == Space.Location.ELSE_PREFIX; - if ((loc.equals(Space.Location.EXTENDS) && space.getWhitespace().contains("\n")) || - Space.Location.EXTENDS.equals(getCursor().getParent().getMessage("lastLocation"))) { + if ((loc == Space.Location.EXTENDS && space.getWhitespace().contains("\n")) || + Space.Location.EXTENDS == getCursor().getParent().getMessage("lastLocation")) { indentType = IndentType.CONTINUATION_INDENT; } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/BlockStatementTemplateGenerator.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/BlockStatementTemplateGenerator.java index f586b011fcb..f0f22eceff2 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/BlockStatementTemplateGenerator.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/BlockStatementTemplateGenerator.java @@ -60,7 +60,7 @@ public String template(Cursor cursor, String template, Space.Location location, // for CoordinateBuilder.MethodDeclaration#replaceBody() if (cursor.getValue() instanceof J.MethodDeclaration && - location.equals(Space.Location.BLOCK_PREFIX)) { + location == Space.Location.BLOCK_PREFIX) { J.MethodDeclaration method = cursor.getValue(); J.MethodDeclaration m = method.withBody(null).withLeadingAnnotations(emptyList()).withPrefix(Space.EMPTY); before.insert(0, m.printTrimmed(cursor.getParentOrThrow()).trim() + '{'); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java index 476aeaa2e03..a3c8e1fd7ac 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/JavaTemplateJavaExtension.java @@ -55,7 +55,7 @@ public TreeVisitor getMixin() { return new JavaVisitor() { @Override public J visitAnnotation(J.Annotation annotation, Integer integer) { - if (loc.equals(ANNOTATION_PREFIX) && mode.equals(JavaCoordinates.Mode.REPLACEMENT) && + if (loc == ANNOTATION_PREFIX && mode == JavaCoordinates.Mode.REPLACEMENT && annotation.isScope(insertionPoint)) { List gen = substitutions.unsubstitute(templateParser.parseAnnotations(getCursor(), substitutedTemplate)); if (gen.isEmpty()) { @@ -64,7 +64,7 @@ public J visitAnnotation(J.Annotation annotation, Integer integer) { "\nUse JavaTemplate.Builder.doBeforeParseTemplate() to see what stub is being generated and include it in any bug report."); } return gen.get(0).withPrefix(annotation.getPrefix()); - } else if (loc.equals(ANNOTATION_ARGUMENTS) && mode.equals(JavaCoordinates.Mode.REPLACEMENT) && + } else if (loc == ANNOTATION_ARGUMENTS && mode == JavaCoordinates.Mode.REPLACEMENT && annotation.isScope(insertionPoint)) { List gen = substitutions.unsubstitute(templateParser.parseAnnotations(getCursor(), "@Example(" + substitutedTemplate + ")")); return annotation.withArguments(gen.get(0).getArguments()); @@ -144,7 +144,7 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, Integer p) { case ANNOTATIONS: { List gen = substitutions.unsubstitute(templateParser.parseAnnotations(getCursor(), substitutedTemplate)); J.ClassDeclaration c = classDecl; - if (mode.equals(JavaCoordinates.Mode.REPLACEMENT)) { + if (mode == JavaCoordinates.Mode.REPLACEMENT) { c = c.withLeadingAnnotations(gen); if (c.getTypeParameters() != null) { c = c.withTypeParameters(ListUtils.map(c.getTypeParameters(), tp -> tp.withAnnotations(emptyList()))); @@ -176,7 +176,7 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, Integer p) { .collect(toList()); J.ClassDeclaration c = classDecl; - if (mode.equals(JavaCoordinates.Mode.REPLACEMENT)) { + if (mode == JavaCoordinates.Mode.REPLACEMENT) { c = c.withImplements(implementings); //noinspection ConstantConditions c = c.getPadding().withImplements(c.getPadding().getImplements().withBefore(Space.EMPTY)); @@ -202,8 +202,8 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, Integer p) { @Override public J visitExpression(Expression expression, Integer p) { - if ((loc.equals(EXPRESSION_PREFIX) || - loc.equals(STATEMENT_PREFIX) && expression instanceof Statement) && + if ((loc == EXPRESSION_PREFIX || + loc == STATEMENT_PREFIX && expression instanceof Statement) && expression.isScope(insertionPoint)) { return autoFormat(substitutions.unsubstitute(templateParser.parseExpression( getCursor(), @@ -216,13 +216,13 @@ public J visitExpression(Expression expression, Integer p) { @Override public J visitFieldAccess(J.FieldAccess fa, Integer p) { - if (loc.equals(FIELD_ACCESS_PREFIX) && fa.isScope(insertionPoint)) { + if (loc == FIELD_ACCESS_PREFIX && fa.isScope(insertionPoint)) { return autoFormat(substitutions.unsubstitute(templateParser.parseExpression( getCursor(), substitutedTemplate, loc)) .withPrefix(fa.getPrefix()), p); - } else if (loc.equals(STATEMENT_PREFIX) && fa.isScope(insertionPoint)) { + } else if (loc == STATEMENT_PREFIX && fa.isScope(insertionPoint)) { // NOTE: while `J.FieldAccess` inherits from `Statement` they can only ever be used as expressions return autoFormat(substitutions.unsubstitute(templateParser.parseExpression( getCursor(), @@ -236,7 +236,7 @@ public J visitFieldAccess(J.FieldAccess fa, Integer p) { @Override public J visitIdentifier(J.Identifier ident, Integer p) { // ONLY for backwards compatibility, otherwise the same as expression replacement - if (loc.equals(IDENTIFIER_PREFIX) && ident.isScope(insertionPoint)) { + if (loc == IDENTIFIER_PREFIX && ident.isScope(insertionPoint)) { return autoFormat(substitutions.unsubstitute(templateParser.parseExpression( getCursor(), substitutedTemplate, @@ -248,7 +248,7 @@ public J visitIdentifier(J.Identifier ident, Integer p) { @Override public J visitLambda(J.Lambda lambda, Integer p) { - if (loc.equals(LAMBDA_PARAMETERS_PREFIX) && lambda.getParameters().isScope(insertionPoint)) { + if (loc == LAMBDA_PARAMETERS_PREFIX && lambda.getParameters().isScope(insertionPoint)) { return lambda.withParameters(substitutions.unsubstitute(templateParser.parseLambdaParameters(getCursor(), substitutedTemplate))); } return maybeReplaceStatement(lambda, J.class, 0); @@ -261,7 +261,7 @@ public J visitMethodDeclaration(J.MethodDeclaration method, Integer p) { case ANNOTATIONS: { List gen = substitutions.unsubstitute(templateParser.parseAnnotations(getCursor(), substitutedTemplate)); J.MethodDeclaration m = method; - if (mode.equals(JavaCoordinates.Mode.REPLACEMENT)) { + if (mode == JavaCoordinates.Mode.REPLACEMENT) { m = method.withLeadingAnnotations(gen); if (m.getTypeParameters() != null) { m = m.withTypeParameters(ListUtils.map(m.getTypeParameters(), tp -> tp.withAnnotations(emptyList()))); @@ -384,9 +384,9 @@ public J visitMethodDeclaration(J.MethodDeclaration method, Integer p) { @Override public J visitMethodInvocation(J.MethodInvocation method, Integer integer) { - if ((loc.equals(METHOD_INVOCATION_ARGUMENTS) || loc.equals(METHOD_INVOCATION_NAME)) && method.isScope(insertionPoint)) { + if ((loc == METHOD_INVOCATION_ARGUMENTS || loc == METHOD_INVOCATION_NAME) && method.isScope(insertionPoint)) { J.MethodInvocation m; - if (loc.equals(METHOD_INVOCATION_ARGUMENTS)) { + if (loc == METHOD_INVOCATION_ARGUMENTS) { m = substitutions.unsubstitute(templateParser.parseMethodArguments(getCursor(), substitutedTemplate, loc)); m = autoFormat(m, 0); m = method.withArguments(m.getArguments()).withMethodType(m.getMethodType()); @@ -433,7 +433,7 @@ public J visitNewClass(J.NewClass newClass, Integer p) { @Override public J visitPackage(J.Package pkg, Integer integer) { - if (loc.equals(PACKAGE_PREFIX) && pkg.isScope(insertionPoint)) { + if (loc == PACKAGE_PREFIX && pkg.isScope(insertionPoint)) { return pkg.withExpression(substitutions.unsubstitute(templateParser.parsePackage(getCursor(), substitutedTemplate))); } return super.visitPackage(pkg, integer); @@ -445,8 +445,8 @@ public J visitStatement(Statement statement, Integer p) { } private J3 maybeReplaceStatement(Statement statement, Class expected, Integer p) { - if (loc.equals(STATEMENT_PREFIX) && statement.isScope(insertionPoint)) { - if (mode.equals(JavaCoordinates.Mode.REPLACEMENT)) { + if (loc == STATEMENT_PREFIX && statement.isScope(insertionPoint)) { + if (mode == JavaCoordinates.Mode.REPLACEMENT) { List gen = substitutions.unsubstitute(templateParser.parseBlockStatements(getCursor(), expected, substitutedTemplate, loc, mode)); if (gen.size() != 1) { @@ -481,7 +481,7 @@ public J visitVariableDeclarations(J.VariableDeclarations multiVariable, Integer if (loc == ANNOTATIONS) { J.VariableDeclarations v = multiVariable; final List gen = substitutions.unsubstitute(templateParser.parseAnnotations(getCursor(), substitutedTemplate)); - if (mode.equals(JavaCoordinates.Mode.REPLACEMENT)) { + if (mode == JavaCoordinates.Mode.REPLACEMENT) { v = v.withLeadingAnnotations(gen); if (v.getTypeExpression() instanceof J.AnnotatedType) { v = v.withTypeExpression(((J.AnnotatedType) v.getTypeExpression()).getTypeExpression()); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java index 16a9a68438c..6331cc78d69 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java @@ -146,7 +146,7 @@ private String substituteTypedPattern(String key, int index, TemplateParameterPa String fqn = getTypeName(type); JavaType.Primitive primitive = JavaType.Primitive.fromKeyword(fqn); - s = primitive == null || primitive.equals(JavaType.Primitive.String) ? + s = primitive == null || primitive == JavaType.Primitive.String ? newObjectParameter(fqn, index) : newPrimitiveParameter(fqn, index); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/style/Autodetect.java b/rewrite-java/src/main/java/org/openrewrite/java/style/Autodetect.java index 34a3a10abf5..d545053d8b8 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/style/Autodetect.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/style/Autodetect.java @@ -577,7 +577,7 @@ public ImportLayoutStyle getImportLayoutStyle() { List countOfBlocksInStaticGroups = new ArrayList<>(); for (Block block : longestBlocks) { - if (BlockType.ImportStatic.equals(block.type)) { + if (BlockType.ImportStatic == block.type) { staticBlocks.add(block); countOfBlocksInStaticGroups.add(0); countOfBlocksInStaticGroups.set(staticCountPos, countOfBlocksInStaticGroups.get(staticCountPos) + 1); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaCoordinates.java b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaCoordinates.java index 04bf5e5e1f5..482bf3cfe43 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaCoordinates.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaCoordinates.java @@ -34,7 +34,7 @@ public class JavaCoordinates implements Coordinates { Comparator comparator; public boolean isReplacement() { - return Mode.REPLACEMENT.equals(mode); + return Mode.REPLACEMENT == mode; } /** diff --git a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveDependency.java b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveDependency.java index 0d015f4417d..d60df379b3c 100644 --- a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveDependency.java +++ b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveDependency.java @@ -70,7 +70,7 @@ public TreeVisitor getVisitor() { @Override public Validated validate() { return super.validate().and(Validated.test("scope", "Scope must be one of compile, runtime, test, or provided", - scope, s -> !Scope.Invalid.equals(Scope.fromName(s)))); + scope, s -> Scope.Invalid != Scope.fromName(s))); } private class RemoveDependencyVisitor extends MavenIsoVisitor { diff --git a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveManagedDependency.java b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveManagedDependency.java index f65fbf99269..2f1de67fc90 100644 --- a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveManagedDependency.java +++ b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveManagedDependency.java @@ -69,7 +69,7 @@ public TreeVisitor getVisitor() { @Override public Validated validate() { return super.validate().and(Validated.test("scope", "Scope must be one of compile, runtime, test, or provided", - scope, s -> !Scope.Invalid.equals(Scope.fromName(s)))); + scope, s -> Scope.Invalid != Scope.fromName(s))); } private class RemoveManagedDependencyVisitor extends MavenIsoVisitor { diff --git a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveRedundantDependencyVersions.java b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveRedundantDependencyVersions.java index d4e94d99975..dbe5719624e 100644 --- a/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveRedundantDependencyVersions.java +++ b/rewrite-maven/src/main/java/org/openrewrite/maven/RemoveRedundantDependencyVersions.java @@ -167,7 +167,7 @@ public Xml.Document visitDocument(Xml.Document document, ExecutionContext ctx) { if (d != document) { d = (Xml.Document) new RemoveEmptyDependenciesTags().visitNonNull(d, ctx); d = (Xml.Document) new RemoveEmptyPluginsTags().visitNonNull(d, ctx); - if (!comparator.equals(Comparator.EQ)) { + if (comparator != Comparator.EQ) { maybeUpdateModel(); } } @@ -323,7 +323,7 @@ private boolean matchesComparator(@Nullable String managedVersion, String reques if (managedVersion == null) { return false; } - if (comparator.equals(Comparator.ANY)) { + if (comparator == Comparator.ANY) { return true; } if (!isExact(managedVersion)) { @@ -333,11 +333,11 @@ private boolean matchesComparator(@Nullable String managedVersion, String reques .compare(null, managedVersion, Objects.requireNonNull(getResolutionResult().getPom().getValue(requestedVersion))); if (comparison < 0) { - return comparator.equals(Comparator.LT) || comparator.equals(Comparator.LTE); + return comparator == Comparator.LT || comparator == Comparator.LTE; } else if (comparison > 0) { - return comparator.equals(Comparator.GT) || comparator.equals(Comparator.GTE); + return comparator == Comparator.GT || comparator == Comparator.GTE; } else { - return comparator.equals(Comparator.EQ) || comparator.equals(Comparator.LTE) || comparator.equals(Comparator.GTE); + return comparator == Comparator.EQ || comparator == Comparator.LTE || comparator == Comparator.GTE; } } diff --git a/rewrite-maven/src/main/java/org/openrewrite/maven/internal/InsertDependencyComparator.java b/rewrite-maven/src/main/java/org/openrewrite/maven/internal/InsertDependencyComparator.java index 6669c1321af..d439dcb0154 100644 --- a/rewrite-maven/src/main/java/org/openrewrite/maven/internal/InsertDependencyComparator.java +++ b/rewrite-maven/src/main/java/org/openrewrite/maven/internal/InsertDependencyComparator.java @@ -71,7 +71,7 @@ public int compare(Content o1, Content o2) { private static final Comparator dependencyComparator = (d1, d2) -> { Scope scope1 = Scope.fromName(d1.getChildValue("scope").orElse(null)); Scope scope2 = Scope.fromName(d2.getChildValue("scope").orElse(null)); - if (!scope1.equals(scope2)) { + if (scope1 != scope2) { return scope1.compareTo(scope2); } diff --git a/rewrite-xml/src/test/java/org/openrewrite/xml/XmlParserTest.java b/rewrite-xml/src/test/java/org/openrewrite/xml/XmlParserTest.java index cff46087276..57ae47a0905 100755 --- a/rewrite-xml/src/test/java/org/openrewrite/xml/XmlParserTest.java +++ b/rewrite-xml/src/test/java/org/openrewrite/xml/XmlParserTest.java @@ -146,8 +146,8 @@ void javaReferenceDocument() { """, spec -> spec.afterRecipe(doc -> { assertThat(doc.getReferences().getReferences().stream().anyMatch(typeRef -> typeRef.getValue().equals("java.lang.String"))).isTrue(); - assertThat(doc.getReferences().getReferences().stream().anyMatch(typeRef -> typeRef.getKind().equals(Reference.Kind.TYPE))).isTrue(); - assertThat(doc.getReferences().getReferences().stream().anyMatch(typeRef -> typeRef.getKind().equals(Reference.Kind.PACKAGE))).isTrue(); + assertThat(doc.getReferences().getReferences().stream().anyMatch(typeRef -> typeRef.getKind() == Reference.Kind.TYPE)).isTrue(); + assertThat(doc.getReferences().getReferences().stream().anyMatch(typeRef -> typeRef.getKind() == Reference.Kind.PACKAGE)).isTrue(); }) ) ); From 6dc9d5064071df4dac16c06a0c5a292a5dbcfa72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Schn=C3=A9ider?= Date: Wed, 25 Dec 2024 16:20:35 +0100 Subject: [PATCH 14/16] Keep the names of generic type variables defined by methods. (#4814) * Make the same performance improvement to parameter names allocations that we previously made to Java 17/21 in #3345. --- .../isolated/ReloadableJava11TypeMapping.java | 37 +++++++---- .../isolated/ReloadableJava17TypeMapping.java | 16 ++++- .../isolated/ReloadableJava21TypeMapping.java | 16 ++++- .../java/ReloadableJava8TypeMapping.java | 37 ++++++++--- .../openrewrite/java/JavaTypeMappingTest.java | 15 +++++ .../internal/JavaReflectionTypeMapping.java | 18 +++++- .../org/openrewrite/java/tree/JavaType.java | 61 +++++++++++++++++-- 7 files changed, 167 insertions(+), 33 deletions(-) diff --git a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java index 00ba35afbd5..a37d73adf6e 100644 --- a/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java +++ b/rewrite-java-11/src/main/java/org/openrewrite/java/isolated/ReloadableJava11TypeMapping.java @@ -470,12 +470,14 @@ public JavaType.Primitive primitive(TypeTag tag) { return existing; } - List paramNames = null; + String[] paramNames = null; if (!methodSymbol.params().isEmpty()) { - paramNames = new ArrayList<>(methodSymbol.params().size()); - for (Symbol.VarSymbol p : methodSymbol.params()) { + paramNames = new String[methodSymbol.params().size()]; + com.sun.tools.javac.util.List params = methodSymbol.params(); + for (int i = 0; i < params.size(); i++) { + Symbol.VarSymbol p = params.get(i); String s = p.name.toString(); - paramNames.add(s); + paramNames[i] = s; } } @@ -486,7 +488,7 @@ public JavaType.Primitive primitive(TypeTag tag) { methodSymbol.isConstructor() ? "" : methodSymbol.getSimpleName().toString(), null, paramNames, - null, null, null, null + null, null, null, null, null ); typeCache.put(signature, method); @@ -551,12 +553,14 @@ public JavaType.Primitive primitive(TypeTag tag) { return existing; } - List paramNames = null; + String[] paramNames = null; if (!methodSymbol.params().isEmpty()) { - paramNames = new ArrayList<>(methodSymbol.params().size()); - for (Symbol.VarSymbol p : methodSymbol.params()) { + paramNames = new String[methodSymbol.params().size()]; + com.sun.tools.javac.util.List params = methodSymbol.params(); + for (int i = 0; i < params.size(); i++) { + Symbol.VarSymbol p = params.get(i); String s = p.name.toString(); - paramNames.add(s); + paramNames[i] = s; } } @@ -574,6 +578,17 @@ public JavaType.Primitive primitive(TypeTag tag) { } } } + + List declaredFormalTypeNames = null; + for (Symbol.TypeVariableSymbol typeParam : methodSymbol.getTypeParameters()) { + if(typeParam.owner == methodSymbol) { + if (declaredFormalTypeNames == null) { + declaredFormalTypeNames = new ArrayList<>(); + } + declaredFormalTypeNames.add(typeParam.name.toString()); + } + } + JavaType.Method method = new JavaType.Method( null, methodSymbol.flags_field, @@ -582,8 +597,8 @@ public JavaType.Primitive primitive(TypeTag tag) { null, paramNames, null, null, null, - // TODO: Figure out the correct thing to put here based on methodSymbol.defaultValue.getValue() - defaultValues + defaultValues, + declaredFormalTypeNames == null ? null : declaredFormalTypeNames.toArray(new String[0]) ); typeCache.put(signature, method); diff --git a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java index d3a1ee1c9a7..d4252e1bc0e 100644 --- a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java +++ b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17TypeMapping.java @@ -494,7 +494,7 @@ public JavaType.Primitive primitive(TypeTag tag) { methodSymbol.isConstructor() ? "" : methodSymbol.getSimpleName().toString(), null, paramNames, - null, null, null, null + null, null, null, null, null ); typeCache.put(signature, method); @@ -583,6 +583,17 @@ public JavaType.Primitive primitive(TypeTag tag) { } } } + + List declaredFormalTypeNames = null; + for (Symbol.TypeVariableSymbol typeParam : methodSymbol.getTypeParameters()) { + if(typeParam.owner == methodSymbol) { + if (declaredFormalTypeNames == null) { + declaredFormalTypeNames = new ArrayList<>(); + } + declaredFormalTypeNames.add(typeParam.name.toString()); + } + } + JavaType.Method method = new JavaType.Method( null, methodSymbol.flags_field, @@ -591,7 +602,8 @@ public JavaType.Primitive primitive(TypeTag tag) { null, paramNames, null, null, null, - defaultValues + defaultValues, + declaredFormalTypeNames == null ? null : declaredFormalTypeNames.toArray(new String[0]) ); typeCache.put(signature, method); diff --git a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java index bde8ecb7573..a7cbc01a00e 100644 --- a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java +++ b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21TypeMapping.java @@ -505,7 +505,7 @@ public JavaType.Primitive primitive(TypeTag tag) { methodSymbol.isConstructor() ? "" : methodSymbol.getSimpleName().toString(), null, paramNames, - null, null, null, null + null, null, null, null, null ); typeCache.put(signature, method); @@ -594,6 +594,17 @@ public JavaType.Primitive primitive(TypeTag tag) { } } } + + List declaredFormalTypeNames = null; + for (Symbol.TypeVariableSymbol typeParam : methodSymbol.getTypeParameters()) { + if(typeParam.owner == methodSymbol) { + if (declaredFormalTypeNames == null) { + declaredFormalTypeNames = new ArrayList<>(); + } + declaredFormalTypeNames.add(typeParam.name.toString()); + } + } + JavaType.Method method = new JavaType.Method( null, methodSymbol.flags_field, @@ -602,7 +613,8 @@ public JavaType.Primitive primitive(TypeTag tag) { null, paramNames, null, null, null, - defaultValues + defaultValues, + declaredFormalTypeNames == null ? null : declaredFormalTypeNames.toArray(new String[0]) ); typeCache.put(signature, method); diff --git a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java index 9beaba2727b..ca5db39ba80 100644 --- a/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java +++ b/rewrite-java-8/src/main/java/org/openrewrite/java/ReloadableJava8TypeMapping.java @@ -472,12 +472,14 @@ public JavaType.Primitive primitive(TypeTag tag) { return existing; } - List paramNames = null; + String[] paramNames = null; if (!methodSymbol.params().isEmpty()) { - paramNames = new ArrayList<>(methodSymbol.params().size()); - for (Symbol.VarSymbol p : methodSymbol.params()) { + paramNames = new String[methodSymbol.params().size()]; + com.sun.tools.javac.util.List params = methodSymbol.params(); + for (int i = 0; i < params.size(); i++) { + Symbol.VarSymbol p = params.get(i); String s = p.name.toString(); - paramNames.add(s); + paramNames[i] = s; } } @@ -488,7 +490,7 @@ public JavaType.Primitive primitive(TypeTag tag) { methodSymbol.isConstructor() ? "" : methodSymbol.getSimpleName().toString(), null, paramNames, - null, null, null, null + null, null, null, null, null ); typeCache.put(signature, method); @@ -554,14 +556,17 @@ public JavaType.Primitive primitive(TypeTag tag) { return existing; } - List paramNames = null; + String[] paramNames = null; if (!methodSymbol.params().isEmpty()) { - paramNames = new ArrayList<>(methodSymbol.params().size()); - for (Symbol.VarSymbol p : methodSymbol.params()) { + paramNames = new String[methodSymbol.params().size()]; + com.sun.tools.javac.util.List params = methodSymbol.params(); + for (int i = 0; i < params.size(); i++) { + Symbol.VarSymbol p = params.get(i); String s = p.name.toString(); - paramNames.add(s); + paramNames[i] = s; } } + List defaultValues = null; if(methodSymbol.getDefaultValue() != null) { if(methodSymbol.getDefaultValue() instanceof Attribute.Array) { @@ -576,6 +581,17 @@ public JavaType.Primitive primitive(TypeTag tag) { } } } + + List declaredFormalTypeNames = null; + for (Symbol.TypeVariableSymbol typeParam : methodSymbol.getTypeParameters()) { + if(typeParam.owner == methodSymbol) { + if (declaredFormalTypeNames == null) { + declaredFormalTypeNames = new ArrayList<>(); + } + declaredFormalTypeNames.add(typeParam.name.toString()); + } + } + JavaType.Method method = new JavaType.Method( null, methodSymbol.flags_field, @@ -584,7 +600,8 @@ public JavaType.Primitive primitive(TypeTag tag) { null, paramNames, null, null, null, - defaultValues + defaultValues, + declaredFormalTypeNames == null ? null : declaredFormalTypeNames.toArray(new String[0]) ); typeCache.put(signature, method); diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java index 2eba1ba1e0f..2097273e1a2 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java @@ -63,6 +63,21 @@ default void declaringTypeRefersToParameterizedClass() { .isNotEmpty(); } + @Test + default void shadowedDeclaredFormalTypeParameters() { + // this method overrides the class definition of the type variable T + assertThat(methodType("nameShadow").getDeclaredFormalTypeNames()) + .containsExactly("T"); + + // this method provides an unshadowed definition of U + assertThat(methodType("genericUnbounded").getDeclaredFormalTypeNames()) + .containsExactly("U"); + + // this method uses the definition of T from the class level + assertThat(methodType("genericT").getDeclaredFormalTypeNames()) + .isEmpty(); + } + @Test default void javaLangObjectHasNoSupertype() { assertThat(goatType().getSupertype().getSupertype()).isNull(); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java index ef7ee8de348..860d259af24 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java @@ -341,7 +341,7 @@ private JavaType.Method method(Constructor method, JavaType.FullyQualified de "", null, paramNames, - null, null, null, null + null, null, null, null, null ); typeCache.put(signature, mappedMethod); @@ -439,6 +439,17 @@ private JavaType.Method method(Method method, JavaType.FullyQualified declaringT defaultValues = Collections.singletonList(method.getDefaultValue().toString()); } } + + List declaredFormalTypeNames = null; + for (TypeVariable typeVariable : method.getTypeParameters()) { + if (typeVariable.getGenericDeclaration() == method) { + if (declaredFormalTypeNames == null) { + declaredFormalTypeNames = new ArrayList<>(); + } + declaredFormalTypeNames.add(typeVariable.getName()); + } + } + JavaType.Method mappedMethod = new JavaType.Method( null, method.getModifiers(), @@ -447,7 +458,10 @@ private JavaType.Method method(Method method, JavaType.FullyQualified declaringT null, paramNames, null, null, null, - defaultValues + defaultValues, + declaredFormalTypeNames == null ? + null : + declaredFormalTypeNames.toArray(new String[0]) ); typeCache.put(signature, mappedMethod); diff --git a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java index 95d936ff2df..f4a0eac5195 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java @@ -1116,6 +1116,33 @@ class Method implements JavaType { @NonFinal List defaultValue; + /** + * The names of the generic type variables declared by this method. These names + * will occur as the name in a {@link GenericTypeVariable} parameter, + * return type, or thrown exception declaration elsewhere in the method definition. We + * keep track of the names of those variables that were defined by this method in order + * to be able to distinguish them from generic type variables, potentially of the same + * name, defined on a containing class. Some examples: + *

+ *
+         * {@code
+         * interface Test {
+         *    U m1();   // [U] used as return type
+         *    void m2(U); // [U] used as parameter
+         *    void m3() throws U; // [U]
+         *
+         *   T m4(T);      // ∅ since T refers to the class definition of T
+         *    T m3(T);  // [T] since it shadows the class definition of T
+         *    U m4(T);  // [U] but not T because T refers to the class
+         * }
+         * }
+         * 
+ */ + @With + @NonFinal + String @Nullable [] declaredFormalTypeNames; + + @Deprecated public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, @Nullable List parameterNames, @Nullable List parameterTypes, @Nullable List thrownExceptions, @@ -1124,10 +1151,20 @@ public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable Fu thrownExceptions, annotations, null); } + @Deprecated public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, @Nullable List parameterNames, @Nullable List parameterTypes, @Nullable List thrownExceptions, @Nullable List annotations, @Nullable List defaultValue) { + this(managedReference, flagsBitMap, declaringType, name, returnType, parameterNames, parameterTypes, + thrownExceptions, annotations, defaultValue, null); + } + + public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, + @Nullable JavaType returnType, @Nullable List parameterNames, + @Nullable List parameterTypes, @Nullable List thrownExceptions, + @Nullable List annotations, @Nullable List defaultValue, + @Nullable List declaredFormalTypeNames) { this( managedReference, flagsBitMap, @@ -1138,14 +1175,16 @@ public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable Fu arrayOrNullIfEmpty(parameterTypes, EMPTY_JAVA_TYPE_ARRAY), arrayOrNullIfEmpty(thrownExceptions, EMPTY_FULLY_QUALIFIED_ARRAY), arrayOrNullIfEmpty(annotations, EMPTY_FULLY_QUALIFIED_ARRAY), - defaultValue + defaultValue, + arrayOrNullIfEmpty(declaredFormalTypeNames, EMPTY_STRING_ARRAY) ); } public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable FullyQualified declaringType, String name, @Nullable JavaType returnType, String @Nullable [] parameterNames, JavaType @Nullable [] parameterTypes, JavaType @Nullable [] thrownExceptions, - FullyQualified @Nullable [] annotations, @Nullable List defaultValue) { + FullyQualified @Nullable [] annotations, @Nullable List defaultValue, + String @Nullable [] declaredFormalTypeNames) { this.managedReference = managedReference; this.flagsBitMap = flagsBitMap & Flag.VALID_FLAGS; this.declaringType = unknownIfNull(declaringType); @@ -1156,6 +1195,7 @@ public Method(@Nullable Integer managedReference, long flagsBitMap, @Nullable Fu this.thrownExceptions = nullIfEmpty(thrownExceptions); this.annotations = nullIfEmpty(annotations); this.defaultValue = nullIfEmpty(defaultValue); + this.declaredFormalTypeNames = nullIfEmpty(declaredFormalTypeNames); } @JsonCreator @@ -1191,6 +1231,7 @@ public Method unsafeSet(@Nullable FullyQualified declaringType, this.parameterTypes = ListUtils.nullIfEmpty(parameterTypes); this.thrownExceptions = ListUtils.nullIfEmpty(thrownExceptions); this.annotations = ListUtils.nullIfEmpty(annotations); + this.declaredFormalTypeNames = ListUtils.nullIfEmpty(declaredFormalTypeNames); return this; } @@ -1290,13 +1331,18 @@ public List getParameterNames() { return parameterNames == null ? emptyList() : Arrays.asList(parameterNames); } + public List getDeclaredFormalTypeNames() { + return declaredFormalTypeNames == null ? emptyList() : Arrays.asList(declaredFormalTypeNames); + } + public Method withParameterNames(@Nullable List parameterNames) { String[] parameterNamesArray = arrayOrNullIfEmpty(parameterNames, EMPTY_STRING_ARRAY); if (Arrays.equals(parameterNamesArray, this.parameterNames)) { return this; } return new Method(this.managedReference, this.flagsBitMap, this.declaringType, this.name, this.returnType, - parameterNamesArray, this.parameterTypes, this.thrownExceptions, this.annotations, this.defaultValue); + parameterNamesArray, this.parameterTypes, this.thrownExceptions, this.annotations, this.defaultValue, + this.declaredFormalTypeNames); } public List getParameterTypes() { @@ -1309,7 +1355,8 @@ public Method withParameterTypes(@Nullable List parameterTypes) { return this; } return new Method(this.managedReference, this.flagsBitMap, this.declaringType, this.name, this.returnType, - this.parameterNames, parameterTypesArray, this.thrownExceptions, this.annotations, this.defaultValue); + this.parameterNames, parameterTypesArray, this.thrownExceptions, this.annotations, this.defaultValue, + this.declaredFormalTypeNames); } public List getThrownExceptions() { @@ -1322,7 +1369,8 @@ public Method withThrownExceptions(@Nullable List thrownExceptions) { return this; } return new Method(this.managedReference, this.flagsBitMap, this.declaringType, this.name, this.returnType, - this.parameterNames, this.parameterTypes, thrownExceptionsArray, this.annotations, this.defaultValue); + this.parameterNames, this.parameterTypes, thrownExceptionsArray, this.annotations, this.defaultValue, + this.declaredFormalTypeNames); } public List getAnnotations() { @@ -1335,7 +1383,8 @@ public Method withAnnotations(@Nullable List annotations) { return this; } return new Method(this.managedReference, this.flagsBitMap, this.declaringType, this.name, this.returnType, - this.parameterNames, this.parameterTypes, this.thrownExceptions, annotationsArray, this.defaultValue); + this.parameterNames, this.parameterTypes, this.thrownExceptions, annotationsArray, this.defaultValue, + this.declaredFormalTypeNames); } public boolean hasFlags(Flag... test) { From f4038c23c528303df0ea9be52622539beac36cfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Schn=C3=A9ider?= Date: Wed, 25 Dec 2024 16:44:39 +0100 Subject: [PATCH 15/16] Fix Java reflection mapping of generic typed fields. (#4815) --- .../java/org/openrewrite/java/JavaTypeGoat.java | 5 +++-- .../openrewrite/java/JavaTypeMappingTest.java | 16 +++++++++++++--- .../src/main/resources/JavaTypeGoat.java | 5 +++-- .../java/internal/JavaReflectionTypeMapping.java | 2 +- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java index 8e8abd6fe37..64a1d90452f 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeGoat.java @@ -26,8 +26,9 @@ public abstract class JavaTypeGoat & C> { public static final PT parameterizedField = new PT() { }; - public static final Double PI = 3.14; - public static final double PI_PRIMITIVE = 3.14; + + public static Double PI; + public static double PI_PRIMITIVE; public static abstract class InheritedJavaTypeGoat & C> extends JavaTypeGoat { public InheritedJavaTypeGoat() { diff --git a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java index 2097273e1a2..1c010267764 100644 --- a/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java +++ b/rewrite-java-test/src/main/java/org/openrewrite/java/JavaTypeMappingTest.java @@ -25,9 +25,7 @@ import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.CONTRAVARIANT; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.COVARIANT; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.INVARIANT; +import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.*; /** * Based on type attribution mappings of [JavaTypeGoat]. @@ -53,6 +51,18 @@ default JavaType firstMethodParameter(String methodName) { return methodType(methodName).getParameterTypes().get(0); } + @Test + default void declaredFields() { + JavaType.Parameterized goat = goatType(); + assertThat(goat.getMembers().stream().filter(m -> m.getName().equals("parameterizedField"))).anySatisfy(field -> + assertThat(field).isInstanceOfSatisfying(JavaType.Variable.class, variable -> + assertThat(variable.getType()).isInstanceOfSatisfying(JavaType.Parameterized.class, param -> + assertThat(param.getTypeParameters()).hasOnlyElementsOfType(JavaType.FullyQualified.class) + ) + ) + ); + } + @Test default void declaringTypeRefersToParameterizedClass() { JavaType.FullyQualified declaringType = methodType("nameShadow").getDeclaringType(); diff --git a/rewrite-java-test/src/main/resources/JavaTypeGoat.java b/rewrite-java-test/src/main/resources/JavaTypeGoat.java index 40e1696a15a..047fa6ada5e 100644 --- a/rewrite-java-test/src/main/resources/JavaTypeGoat.java +++ b/rewrite-java-test/src/main/resources/JavaTypeGoat.java @@ -26,8 +26,9 @@ public abstract class JavaTypeGoat & C> { public static final PT parameterizedField = new PT() { }; - public static final Double PI = 3.14; - public static final double PI_PRIMITIVE = 3.14; + + public static Double PI; + public static double PI_PRIMITIVE; public static abstract class InheritedJavaTypeGoat & C> extends JavaTypeGoat { public InheritedJavaTypeGoat() { diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java index 860d259af24..e242c73e335 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/JavaReflectionTypeMapping.java @@ -302,7 +302,7 @@ private JavaType.Variable field(Field field) { } } - mappedVariable.unsafeSet(type(field.getDeclaringClass()), type(field.getType()), annotations); + mappedVariable.unsafeSet(type(field.getDeclaringClass()), type(field.getGenericType()), annotations); return mappedVariable; } From b91499c728758cf6b52474707645bcf584a543b6 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Fri, 27 Dec 2024 11:48:54 +0100 Subject: [PATCH 16/16] Revert parenthesis changes (#4818) * Revert "Try alternative way of determining parenthesis level for `BinaryExpression` when AST doesn't provide `_INSIDE_PARENTHESES_LEVEL` flag (#4807)" This reverts commit e59e48b3a6e6be18ecb779ac329a243ed025da58. * Revert "Make Groovy Parser correctly handle nested parenthesis (#4801)" This reverts commit 91a031a3d517be1fe78656eb6b841141b336c085. --- .../org/openrewrite/internal/StringUtils.java | 10 -- .../groovy/GroovyParserVisitor.java | 146 ++++++------------ .../groovy/tree/AttributeTest.java | 25 ++- .../openrewrite/groovy/tree/BinaryTest.java | 31 +--- .../org/openrewrite/groovy/tree/CastTest.java | 17 +- .../org/openrewrite/groovy/tree/ListTest.java | 34 ---- .../openrewrite/groovy/tree/LiteralTest.java | 23 +++ .../openrewrite/groovy/tree/MapEntryTest.java | 7 - .../groovy/tree/MethodInvocationTest.java | 61 +------- .../openrewrite/groovy/tree/RangeTest.java | 2 + 10 files changed, 97 insertions(+), 259 deletions(-) diff --git a/rewrite-core/src/main/java/org/openrewrite/internal/StringUtils.java b/rewrite-core/src/main/java/org/openrewrite/internal/StringUtils.java index 4f0f76ae578..7cafdeb341a 100644 --- a/rewrite-core/src/main/java/org/openrewrite/internal/StringUtils.java +++ b/rewrite-core/src/main/java/org/openrewrite/internal/StringUtils.java @@ -720,14 +720,4 @@ public static String formatUriForPropertiesFile(String uri) { public static boolean hasLineBreak(@Nullable String s) { return s != null && LINE_BREAK.matcher(s).find(); } - - public static boolean containsWhitespace(String s) { - for (int i = 0; i < s.length(); ++i) { - if (Character.isWhitespace(s.charAt(i))) { - return true; - } - } - - return false; - } } diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java index af660485f32..c631e3998a1 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java @@ -34,7 +34,6 @@ import org.openrewrite.groovy.tree.G; import org.openrewrite.internal.EncodingDetectingInputStream; import org.openrewrite.internal.ListUtils; -import org.openrewrite.internal.StringUtils; import org.openrewrite.java.internal.JavaTypeCache; import org.openrewrite.java.marker.ImplicitReturn; import org.openrewrite.java.marker.OmitParentheses; @@ -1351,20 +1350,20 @@ public void visitConstantExpression(ConstantExpression expression) { jType = JavaType.Primitive.Short; } else if (type == ClassHelper.STRING_TYPE) { jType = JavaType.Primitive.String; + // String literals value returned by getValue()/getText() has already processed sequences like "\\" -> "\" + int length = sourceLengthOfString(expression); // this is an attribute selector - boolean attributeSelector = source.startsWith("@" + value, cursor); - int length = lengthAccordingToAst(expression); - Integer insideParenthesesLevel = getInsideParenthesesLevel(expression); - if (insideParenthesesLevel != null) { - length = length - insideParenthesesLevel * 2; + if (source.startsWith("@" + value, cursor)) { + length += 1; } - String valueAccordingToAST = source.substring(cursor, cursor + length + (attributeSelector ? 1 : 0)); - int delimiterLength = getDelimiterLength(); - if (StringUtils.containsWhitespace(valueAccordingToAST)) { - length = delimiterLength + expression.getValue().toString().length() + delimiterLength; - text = source.substring(cursor, cursor + length + (attributeSelector ? 1 : 0)); - } else { - text = valueAccordingToAST; + text = source.substring(cursor, cursor + length); + int delimiterLength = 0; + if (text.startsWith("$/")) { + delimiterLength = 2; + } else if (text.startsWith("\"\"\"") || text.startsWith("'''")) { + delimiterLength = 3; + } else if (text.startsWith("/") || text.startsWith("\"") || text.startsWith("'")) { + delimiterLength = 1; } value = text.substring(delimiterLength, text.length() - delimiterLength); } else if (expression.isNullExpression()) { @@ -1691,18 +1690,15 @@ public void visitGStringExpression(GStringExpression gstring) { @Override public void visitListExpression(ListExpression list) { - queue.add(insideParentheses(list, fmt -> { - skip("["); - if (list.getExpressions().isEmpty()) { - return new G.ListLiteral(randomId(), fmt, Markers.EMPTY, - JContainer.build(singletonList(new JRightPadded<>(new J.Empty(randomId(), EMPTY, Markers.EMPTY), sourceBefore("]"), Markers.EMPTY))), - typeMapping.type(list.getType())); - } else { - return new G.ListLiteral(randomId(), fmt, Markers.EMPTY, - JContainer.build(visitRightPadded(list.getExpressions().toArray(new ASTNode[0]), "]")), - typeMapping.type(list.getType())); - } - })); + if (list.getExpressions().isEmpty()) { + queue.add(new G.ListLiteral(randomId(), sourceBefore("["), Markers.EMPTY, + JContainer.build(singletonList(new JRightPadded<>(new J.Empty(randomId(), EMPTY, Markers.EMPTY), sourceBefore("]"), Markers.EMPTY))), + typeMapping.type(list.getType()))); + } else { + queue.add(new G.ListLiteral(randomId(), sourceBefore("["), Markers.EMPTY, + JContainer.build(visitRightPadded(list.getExpressions().toArray(new ASTNode[0]), "]")), + typeMapping.type(list.getType()))); + } } @Override @@ -1717,19 +1713,17 @@ public void visitMapEntryExpression(MapEntryExpression expression) { @Override public void visitMapExpression(MapExpression map) { - queue.add(insideParentheses(map, fmt -> { - skip("["); - JContainer entries; - if (map.getMapEntryExpressions().isEmpty()) { - entries = JContainer.build(Collections.singletonList(JRightPadded.build( - new G.MapEntry(randomId(), whitespace(), Markers.EMPTY, - JRightPadded.build(new J.Empty(randomId(), sourceBefore(":"), Markers.EMPTY)), - new J.Empty(randomId(), sourceBefore("]"), Markers.EMPTY), null)))); - } else { - entries = JContainer.build(visitRightPadded(map.getMapEntryExpressions().toArray(new ASTNode[0]), "]")); - } - return new G.MapLiteral(randomId(), fmt, Markers.EMPTY, entries, typeMapping.type(map.getType())); - })); + Space prefix = sourceBefore("["); + JContainer entries; + if (map.getMapEntryExpressions().isEmpty()) { + entries = JContainer.build(Collections.singletonList(JRightPadded.build( + new G.MapEntry(randomId(), whitespace(), Markers.EMPTY, + JRightPadded.build(new J.Empty(randomId(), sourceBefore(":"), Markers.EMPTY)), + new J.Empty(randomId(), sourceBefore("]"), Markers.EMPTY), null)))); + } else { + entries = JContainer.build(visitRightPadded(map.getMapEntryExpressions().toArray(new ASTNode[0]), "]")); + } + queue.add(new G.MapLiteral(randomId(), prefix, Markers.EMPTY, entries, typeMapping.type(map.getType()))); } @Override @@ -1907,24 +1901,23 @@ public void visitStaticMethodCallExpression(StaticMethodCallExpression call) { @Override public void visitAttributeExpression(AttributeExpression attr) { - queue.add(insideParentheses(attr, fmt -> { - Expression target = visit(attr.getObjectExpression()); - Space beforeDot = attr.isSafe() ? sourceBefore("?.") : - sourceBefore(attr.isSpreadSafe() ? "*." : "."); - J name = visit(attr.getProperty()); - if (name instanceof J.Literal) { - String nameStr = ((J.Literal) name).getValueSource(); - assert nameStr != null; - name = new J.Identifier(randomId(), name.getPrefix(), Markers.EMPTY, emptyList(), nameStr, null, null); - } - if (attr.isSpreadSafe()) { - name = name.withMarkers(name.getMarkers().add(new StarDot(randomId()))); - } - if (attr.isSafe()) { - name = name.withMarkers(name.getMarkers().add(new NullSafe(randomId()))); - } - return new J.FieldAccess(randomId(), fmt, Markers.EMPTY, target, padLeft(beforeDot, (J.Identifier) name), null); - })); + Space fmt = whitespace(); + Expression target = visit(attr.getObjectExpression()); + Space beforeDot = attr.isSafe() ? sourceBefore("?.") : + sourceBefore(attr.isSpreadSafe() ? "*." : "."); + J name = visit(attr.getProperty()); + if (name instanceof J.Literal) { + String nameStr = ((J.Literal) name).getValueSource(); + assert nameStr != null; + name = new J.Identifier(randomId(), name.getPrefix(), Markers.EMPTY, emptyList(), nameStr, null, null); + } + if (attr.isSpreadSafe()) { + name = name.withMarkers(name.getMarkers().add(new StarDot(randomId()))); + } + if (attr.isSafe()) { + name = name.withMarkers(name.getMarkers().add(new NullSafe(randomId()))); + } + queue.add(new J.FieldAccess(randomId(), fmt, Markers.EMPTY, target, padLeft(beforeDot, (J.Identifier) name), null)); } @Override @@ -2529,52 +2522,15 @@ private int sourceLengthOfString(ConstantExpression expr) { return lengthAccordingToAst; } - private @Nullable Integer getInsideParenthesesLevel(ASTNode node) { + private static @Nullable Integer getInsideParenthesesLevel(ASTNode node) { Object rawIpl = node.getNodeMetaData("_INSIDE_PARENTHESES_LEVEL"); if (rawIpl instanceof AtomicInteger) { // On Java 11 and newer _INSIDE_PARENTHESES_LEVEL is an AtomicInteger return ((AtomicInteger) rawIpl).get(); - } else if (rawIpl instanceof Integer) { + } else { // On Java 8 _INSIDE_PARENTHESES_LEVEL is a regular Integer return (Integer) rawIpl; - } else if (node instanceof MethodCallExpression) { - MethodCallExpression expr = (MethodCallExpression) node; - return determineParenthesisLevel(expr.getObjectExpression().getLineNumber(), expr.getLineNumber(), expr.getObjectExpression().getColumnNumber(), expr.getColumnNumber()); - } else if (node instanceof BinaryExpression) { - BinaryExpression expr = (BinaryExpression) node; - return determineParenthesisLevel(expr.getLeftExpression().getLineNumber(), expr.getLineNumber(), expr.getLeftExpression().getColumnNumber(), expr.getColumnNumber()); - - } - return null; - } - - /** - * @param childLineNumber the beginning line number of the first sub node - * @param parentLineNumber the beginning line number of the parent node - * @param childColumn the column on the {@code childLineNumber} line where the sub node starts - * @param parentColumn the column on the {@code parentLineNumber} line where the parent node starts - * @return the level of parenthesis parsed from the source - */ - private int determineParenthesisLevel(int childLineNumber, int parentLineNumber, int childColumn, int parentColumn) { - int saveCursor = cursor; - whitespace(); - int childBeginCursor = cursor; - if (childLineNumber > parentLineNumber) { - for (int i = 0; i < (childColumn - parentLineNumber); i++) { - childBeginCursor = source.indexOf('\n', childBeginCursor); - } - childBeginCursor += childColumn; - } else { - childBeginCursor += childColumn - parentColumn; - } - int count = 0; - for (int i = cursor; i < childBeginCursor; i++) { - if (source.charAt(i) == '(') { - count++; - } } - cursor = saveCursor; - return count; } private int getDelimiterLength() { diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/AttributeTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/AttributeTest.java index 2b7d4c82756..bfbadb76655 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/AttributeTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/AttributeTest.java @@ -20,26 +20,19 @@ import static org.openrewrite.groovy.Assertions.groovy; +@SuppressWarnings({"GroovyUnusedAssignment", "GrUnnecessarySemicolon"}) class AttributeTest implements RewriteTest { @Test - void attribute() { + void usingGroovyNode() { rewriteRun( - groovy("new User('Bob').@name") - ); - } - - @Test - void attributeInClosure() { - rewriteRun( - groovy("[new User('Bob')].collect { it.@name }") - ); - } - - @Test - void attributeWithParentheses() { - rewriteRun( - groovy("(new User('Bob').@name)") + groovy( + """ + def xml = new Node(null, "ivy") + def n = xml.dependencies.dependency.find { it.@name == 'test-module' } + n.@conf = 'runtime->default;docs->docs;sources->sources' + """ + ) ); } } diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/BinaryTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/BinaryTest.java index aca502d3571..13239c0fc76 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/BinaryTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/BinaryTest.java @@ -15,6 +15,7 @@ */ package org.openrewrite.groovy.tree; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.openrewrite.Issue; import org.openrewrite.test.RewriteTest; @@ -33,7 +34,6 @@ void insideParentheses() { // NOT inside parentheses, but verifies the parser's // test for "inside parentheses" condition - groovy("( 1 ) + 1"), groovy("(1) + 1"), // And combine the two cases groovy("((1) + 1)") @@ -216,35 +216,6 @@ void stringMultipliedInParentheses() { ); } - @Issue("https://github.com/openrewrite/rewrite/issues/4703") - @Test - void cxds() { - rewriteRun( - groovy( - """ - def differenceInDays(int time) { - return (int) ((time)/(1000*60*60*24)) - } - """ - ) - ); - } - - @Issue("https://github.com/openrewrite/rewrite/issues/4703") - @Test - void extraParensAroundInfixOxxxperator() { - rewriteRun( - groovy( - """ - def timestamp(int hours, int minutes, int seconds) { - 30 * (hours) - (((((hours))))) * 30 - } - """ - ) - ); - } - @Issue("https://github.com/openrewrite/rewrite/issues/4703") @Test void extraParensAroundInfixOperator() { diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/CastTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/CastTest.java index 4c009de95e3..5cf82ae85be 100755 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/CastTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/CastTest.java @@ -16,6 +16,7 @@ package org.openrewrite.groovy.tree; import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ExpectedToFail; import org.openrewrite.Issue; import org.openrewrite.test.RewriteTest; @@ -24,18 +25,6 @@ @SuppressWarnings({"UnnecessaryQualifiedReference", "GroovyUnusedAssignment", "GrUnnecessarySemicolon"}) class CastTest implements RewriteTest { - @Test - void cast() { - rewriteRun( - groovy( - """ - String foo = ( String ) "hallo" - String bar = "hallo" as String - """ - ) - ); - } - @Test void javaStyleCast() { rewriteRun( @@ -85,13 +74,14 @@ void groovyCastAndInvokeMethod() { rewriteRun( groovy( """ - ( "x" as String ).toString() + ( "" as String ).toString() """ ) ); } @Test + @ExpectedToFail("Parentheses with method invocation is not yet supported") void groovyCastAndInvokeMethodWithParentheses() { rewriteRun( groovy( @@ -113,6 +103,7 @@ void javaCastAndInvokeMethod() { ); } + @ExpectedToFail("Parentheses with method invocation is not yet supported") @Test void javaCastAndInvokeMethodWithParentheses() { rewriteRun( diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/ListTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/ListTest.java index d921377b661..b42f9579fd4 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/ListTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/ListTest.java @@ -23,29 +23,6 @@ @SuppressWarnings("GroovyUnusedAssignment") class ListTest implements RewriteTest { - @Test - void emptyListLiteral() { - rewriteRun( - groovy( - """ - def a = [] - def b = [ ] - """ - ) - ); - } - - @Test - void emptyListLiteralWithParentheses() { - rewriteRun( - groovy( - """ - def y = ([]) - """ - ) - ); - } - @Test void listLiteral() { rewriteRun( @@ -56,15 +33,4 @@ void listLiteral() { ) ); } - - @Test - void listLiteralTrailingComma() { - rewriteRun( - groovy( - """ - def a = [ "foo" /* "foo" suffix */ , /* "]" prefix */ ] - """ - ) - ); - } } diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/LiteralTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/LiteralTest.java index 12d638870d4..46851b2f65a 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/LiteralTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/LiteralTest.java @@ -216,6 +216,18 @@ void literalValueAndTypeAgree() { ); } + @Test + void emptyListLiteral() { + rewriteRun( + groovy( + """ + def a = [] + def b = [ ] + """ + ) + ); + } + @Test void multilineStringWithApostrophes() { rewriteRun( @@ -242,6 +254,17 @@ void mapLiteralTrailingComma() { ); } + @Test + void listLiteralTrailingComma() { + rewriteRun( + groovy( + """ + def a = [ "foo" /* "foo" suffix */ , /* "]" prefix */ ] + """ + ) + ); + } + @Test void gStringThatHasEmptyValueExpressionForUnknownReason() { rewriteRun( diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MapEntryTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MapEntryTest.java index 67ee80177cd..65bb4a17492 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MapEntryTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MapEntryTest.java @@ -55,13 +55,6 @@ void emptyMapLiteral() { ); } - @Test - void emptyMapLiteralWithParentheses() { - rewriteRun( - groovy("Map m = ([ : ])") - ); - } - @Test void mapAccess() { rewriteRun( diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodInvocationTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodInvocationTest.java index 42a73d160a0..a0714126901 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodInvocationTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodInvocationTest.java @@ -16,6 +16,7 @@ package org.openrewrite.groovy.tree; import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ExpectedToFail; import org.openrewrite.Issue; import org.openrewrite.test.RewriteTest; @@ -30,11 +31,11 @@ void gradle() { plugins { id 'java-library' } - + repositories { mavenCentral() } - + dependencies { implementation 'org.hibernate:hibernate-core:3.6.7.Final' api 'com.google.guava:guava:23.0' @@ -45,6 +46,7 @@ void gradle() { ); } + @ExpectedToFail("Parentheses with method invocation is not yet supported") @Test @Issue("https://github.com/openrewrite/rewrite/issues/4615") void gradleWithParentheses() { @@ -347,7 +349,7 @@ class StringUtils { static boolean isEmpty(String value) { return value == null || value.isEmpty() } - + static void main(String[] args) { isEmpty("") } @@ -357,29 +359,7 @@ static void main(String[] args) { ); } - @Issue("https://github.com/openrewrite/rewrite/issues/4703") - @Test - void insideParenthesesSimple() { - rewriteRun( - groovy( - """ - ((a.invoke "b" )) - """ - ) - ); - } - - @Test - void lotOfSpacesAroundConstantWithParentheses() { - rewriteRun( - groovy( - """ - ( ( ( "x" ) ).toString() ) - """ - ) - ); - } - + @ExpectedToFail("Parentheses with method invocation is not yet supported") @Issue("https://github.com/openrewrite/rewrite/issues/4703") @Test void insideParentheses() { @@ -395,21 +375,7 @@ static def foo(Map map) { ); } - @Test - void insideParenthesesWithNewline() { - rewriteRun( - groovy( - """ - static def foo(Map map) { - (( - map.containsKey("foo")) - && ((map.get("foo")).equals("bar"))) - } - """ - ) - ); - } - + @ExpectedToFail("Parentheses with method invocation is not yet supported") @Issue("https://github.com/openrewrite/rewrite/issues/4703") @Test void insideParenthesesWithoutNewLineAndEscapedMethodName() { @@ -421,17 +387,4 @@ static def foo(Map someMap) {((((((someMap.get("(bar")))) ).'equals' "baz" ) ) ) ); } - - @Test - void insideFourParenthesesAndEnters() { - rewriteRun( - groovy( - """ - (((( - something(a) - )))) - """ - ) - ); - } } diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/RangeTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/RangeTest.java index e0ff32f3d94..ac839e34d88 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/RangeTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/RangeTest.java @@ -16,6 +16,7 @@ package org.openrewrite.groovy.tree; import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ExpectedToFail; import org.openrewrite.test.RewriteTest; import static org.openrewrite.groovy.Assertions.groovy; @@ -47,6 +48,7 @@ void parenthesized() { ); } + @ExpectedToFail("Parentheses with method invocation is not yet supported") @Test void parenthesizedAndInvokeMethodWithParentheses() { rewriteRun(