-
Notifications
You must be signed in to change notification settings - Fork 519
Add recipes for Kotlinx coroutines and serialization, based on ReplaceWith
#6561
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
a21ff07
Add `ReplaceDeprecatedKotlinMethod` with `template` argument
timtebeek 51041ac
Update recipes.csv
timtebeek b70b120
Move and add scanner/generator for faster iterations
timtebeek 83de309
Merge branch 'main' into replace-deprecated-kotlin-methods
timtebeek 0b66606
Improve the scanner, generator and replacement recipe
timtebeek 8e75c0d
Apply suggestions from code review
timtebeek 51ca8f9
Apply suggestions from code review
timtebeek a820940
Move filter to scanner; keep Kotlin types and use `*` for generic types
timtebeek 364226d
Handle extension functions and receivers
timtebeek 5fb24c8
Add comments to show original expression
timtebeek aee2c6d
Apply suggestions from code review
timtebeek 29b8a9e
Special handling for suspend and coroutines
timtebeek 58ac501
Add recipes for Kotlinx
timtebeek 4525d2c
Polish `ReplaceDeprecatedKotlinMethod`
timtebeek f3a3ef1
Also support replacements for constructors
timtebeek ff456ea
Rename recipe
timtebeek 75f43f5
Add a test for constructor replacement
timtebeek 0add258
Quick renames
timtebeek 090f83f
Expect explicit groupId passed in
timtebeek 86a26a8
Apply formatter
timtebeek 7d5c0f3
Polish DeprecatedMethodScanner
timtebeek eb2cce6
Collapse catch blocks
timtebeek 7c6a578
Use `<init>`
timtebeek fc59b9c
Merge branch 'main' into replace-deprecated-kotlin-methods
timtebeek d721c4e
Exclude transitive kotlin-stdlib from kotlin-metadata-jvm (#6726)
timtebeek d5fd61b
Comment out the testRuntime dependencies when not generating
timtebeek 58a95a6
Increase heap size
timtebeek 7773471
Merge branch 'main' into replace-deprecated-kotlin-methods
timtebeek 90f971c
Update recipes.csv
timtebeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
273 changes: 273 additions & 0 deletions
273
...te-kotlin/src/main/java/org/openrewrite/kotlin/replace/ReplaceDeprecatedKotlinMethod.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,273 @@ | ||
| /* | ||
| * Copyright 2026 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * <p> | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * <p> | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.openrewrite.kotlin.replace; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.jspecify.annotations.Nullable; | ||
| import org.openrewrite.*; | ||
| import org.openrewrite.java.MethodMatcher; | ||
| import org.openrewrite.java.search.UsesMethod; | ||
| import org.openrewrite.java.tree.Expression; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaType; | ||
| import org.openrewrite.kotlin.KotlinParser; | ||
| import org.openrewrite.kotlin.KotlinTemplate; | ||
| import org.openrewrite.kotlin.KotlinVisitor; | ||
|
|
||
| import java.util.*; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import static java.util.Objects.requireNonNull; | ||
|
|
||
| /** | ||
| * Replaces deprecated Kotlin method calls based on {@code @Deprecated(replaceWith=ReplaceWith(...))} annotations. | ||
| * <p> | ||
| * This recipe takes a method pattern to match and a replacement expression that follows the Kotlin | ||
| * {@code ReplaceWith} annotation format. | ||
| */ | ||
| @Incubating(since = "8.43.0") | ||
| @EqualsAndHashCode(callSuper = false) | ||
| @Value | ||
| public class ReplaceDeprecatedKotlinMethod extends Recipe { | ||
|
|
||
| private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("\\b(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)\\b"); | ||
| private static final Pattern TEMPLATE_PLACEHOLDER = Pattern.compile("#\\{([^}]+)}"); | ||
|
|
||
| @Option(displayName = "Method pattern", | ||
| description = "A method pattern that is used to find matching method invocations.", | ||
| example = "arrow.core.MapKt mapOrAccumulate(kotlin.Function2)") | ||
| String methodPattern; | ||
|
|
||
| @Option(displayName = "Replacement", | ||
| description = "The replacement expression from `@Deprecated(replaceWith=ReplaceWith(...))`. " + | ||
| "Parameter names from the original method can be used directly.", | ||
| example = "mapValuesOrAccumulate(transform)") | ||
| String replacement; | ||
|
|
||
| @Option(displayName = "Imports", | ||
| description = "List of imports to add when the replacement is made.", | ||
| required = false, | ||
| example = "[\"arrow.core.Either\"]") | ||
| @Nullable | ||
| List<String> imports; | ||
|
|
||
| @Option(displayName = "Classpath from resources", | ||
| description = "List of classpath resource names for parsing the replacement template.", | ||
| required = false, | ||
| example = "[\"arrow-core-2\"]") | ||
| @Nullable | ||
| List<String> classpathFromResources; | ||
|
|
||
| String displayName = "Replace deprecated Kotlin method"; | ||
| String description = "Replaces deprecated Kotlin method calls based on `@Deprecated(replaceWith=ReplaceWith(...))` annotations."; | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| MethodMatcher matcher = new MethodMatcher(methodPattern, true); | ||
| return Preconditions.check(new UsesMethod<>(methodPattern), new KotlinVisitor<ExecutionContext>() { | ||
|
|
||
| @Override | ||
| public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { | ||
| J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx); | ||
| if (matcher.matches(mi)) { | ||
| return replaceMethod(mi, ctx); | ||
| } | ||
| return mi; | ||
| } | ||
|
|
||
| private J replaceMethod(J.MethodInvocation method, ExecutionContext ctx) { | ||
| JavaType.Method methodType = method.getMethodType(); | ||
| if (methodType == null) { | ||
| return method; | ||
| } | ||
|
|
||
| // Build the template string and extract parameters | ||
| TemplateConversion conversion = convertToTemplate(method, methodType); | ||
| if (conversion == null) { | ||
| return method; | ||
| } | ||
|
|
||
| // Add imports if specified | ||
| if (imports != null) { | ||
| for (String imp : imports) { | ||
| int lastDot = imp.lastIndexOf('.'); | ||
| if (lastDot > 0) { | ||
| maybeAddImport(imp.substring(0, lastDot), imp.substring(lastDot + 1), false); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Build and apply the template | ||
| KotlinTemplate.Builder templateBuilder = KotlinTemplate.builder(conversion.templateString); | ||
| if (imports != null) { | ||
| templateBuilder.imports(imports.toArray(new String[0])); | ||
| } | ||
| if (classpathFromResources != null && !classpathFromResources.isEmpty()) { | ||
| templateBuilder.parser(KotlinParser.builder() | ||
| .classpathFromResources(ctx, classpathFromResources.toArray(new String[0]))); | ||
| } | ||
|
|
||
| J result = templateBuilder.build() | ||
| .apply(getCursor(), method.getCoordinates().replace(), conversion.parameters.toArray()); | ||
|
|
||
| return result.withPrefix(method.getPrefix()); | ||
| } | ||
|
|
||
| private TemplateConversion convertToTemplate(J.MethodInvocation method, JavaType.Method methodType) { | ||
| String templateString = replacement; | ||
| List<Object> parameters = new ArrayList<>(); | ||
| Map<String, Expression> parameterLookup = new HashMap<>(); | ||
|
|
||
| // Map 'this' to the select expression (receiver) | ||
| Expression select = method.getSelect(); | ||
| if (select != null) { | ||
| parameterLookup.put("this", select); | ||
| } | ||
|
|
||
| // Map parameter names to their argument expressions | ||
| List<String> parameterNames = methodType.getParameterNames(); | ||
| List<Expression> arguments = method.getArguments(); | ||
| for (int i = 0; i < parameterNames.size() && i < arguments.size(); i++) { | ||
| parameterLookup.put(parameterNames.get(i), arguments.get(i)); | ||
| } | ||
|
|
||
| // Also support positional references like p0, p1, etc. | ||
| for (int i = 0; i < arguments.size(); i++) { | ||
| parameterLookup.put("p" + i, arguments.get(i)); | ||
| } | ||
|
|
||
| // Determine if this is an instance method call that needs a receiver | ||
| boolean needsReceiver = select != null && !replacement.startsWith("this.") && | ||
| !replacement.contains(".") && !isStaticReplacement(replacement); | ||
|
|
||
| // Convert the replacement expression to a template | ||
| // Replace 'this.' prefix with receiver placeholder | ||
| if (templateString.startsWith("this.")) { | ||
| if (select != null) { | ||
| templateString = "#{any()}." + templateString.substring(5); | ||
| parameters.add(select); | ||
| } else { | ||
| // No select, just remove 'this.' | ||
| templateString = templateString.substring(5); | ||
| } | ||
| } else if (needsReceiver) { | ||
| // Prepend the receiver for instance method calls | ||
| templateString = "#{any()}." + templateString; | ||
| parameters.add(select); | ||
| } | ||
|
|
||
| // Now replace 'this' references that appear elsewhere | ||
| if (templateString.contains("this") && select != null) { | ||
| int thisCount = countOccurrences(templateString, "this"); | ||
| templateString = templateString.replaceAll("\\bthis\\b", "#{any()}"); | ||
| for (int i = 0; i < thisCount; i++) { | ||
| parameters.add(select); | ||
| } | ||
| } | ||
|
|
||
| // Find all identifiers in the template and replace with placeholders | ||
| Set<String> processedParams = new HashSet<>(); | ||
| StringBuilder result = new StringBuilder(); | ||
| java.util.regex.Matcher identifierMatcher = IDENTIFIER_PATTERN.matcher(templateString); | ||
| int lastEnd = 0; | ||
|
|
||
| while (identifierMatcher.find()) { | ||
| String identifier = identifierMatcher.group(1); | ||
|
|
||
| // Skip if already a placeholder or a keyword | ||
| if (identifier.equals("any") || identifier.equals("this") || | ||
|
timtebeek marked this conversation as resolved.
Outdated
timtebeek marked this conversation as resolved.
Outdated
timtebeek marked this conversation as resolved.
Outdated
|
||
| isKotlinKeyword(identifier) || processedParams.contains(identifier)) { | ||
| continue; | ||
| } | ||
|
|
||
| Expression expr = parameterLookup.get(identifier); | ||
| if (expr != null && !processedParams.contains(identifier)) { | ||
| // This identifier is a parameter reference | ||
| result.append(templateString, lastEnd, identifierMatcher.start()); | ||
| result.append("#{any()}"); | ||
| parameters.add(expr); | ||
| processedParams.add(identifier); | ||
| lastEnd = identifierMatcher.end(); | ||
| } | ||
| } | ||
| result.append(templateString.substring(lastEnd)); | ||
| templateString = result.toString(); | ||
|
|
||
| return new TemplateConversion(templateString, parameters); | ||
| } | ||
|
|
||
| private int countOccurrences(String str, String sub) { | ||
| int count = 0; | ||
| int idx = 0; | ||
| while ((idx = str.indexOf(sub, idx)) != -1) { | ||
| count++; | ||
| idx += sub.length(); | ||
| } | ||
| return count; | ||
| } | ||
|
|
||
| private boolean isStaticReplacement(String replacement) { | ||
| // Check if the replacement looks like a static call or fully qualified reference | ||
| // e.g., "SomeClass.method()" or "somePackage.function()" | ||
| return replacement.contains(".") || | ||
| (replacement.length() > 0 && Character.isUpperCase(replacement.charAt(0))); | ||
| } | ||
|
|
||
| private boolean isKotlinKeyword(String identifier) { | ||
| switch (identifier) { | ||
| case "as": | ||
| case "break": | ||
| case "class": | ||
| case "continue": | ||
| case "do": | ||
| case "else": | ||
| case "false": | ||
| case "for": | ||
| case "fun": | ||
| case "if": | ||
| case "in": | ||
| case "interface": | ||
| case "is": | ||
| case "null": | ||
| case "object": | ||
| case "package": | ||
| case "return": | ||
| case "super": | ||
| case "this": | ||
| case "throw": | ||
| case "true": | ||
| case "try": | ||
| case "typealias": | ||
| case "typeof": | ||
| case "val": | ||
| case "var": | ||
| case "when": | ||
| case "while": | ||
| return true; | ||
| default: | ||
| return false; | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| @Value | ||
| private static class TemplateConversion { | ||
| String templateString; | ||
| List<Object> parameters; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.