-
Notifications
You must be signed in to change notification settings - Fork 466
Support Kotlin @Deprecated's ReplaceWith for replacements
#5955
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
Closed
Closed
Changes from 1 commit
Commits
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
351 changes: 351 additions & 0 deletions
351
rewrite-kotlin/src/main/java/org/openrewrite/kotlin/cleanup/ReplaceDeprecatedCall.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,351 @@ | ||||||||
| /* | ||||||||
| * Copyright 2025 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.cleanup; | ||||||||
|
|
||||||||
| import lombok.AccessLevel; | ||||||||
| import lombok.Getter; | ||||||||
| import lombok.Value; | ||||||||
| import org.jspecify.annotations.Nullable; | ||||||||
| import org.openrewrite.Cursor; | ||||||||
| import org.openrewrite.ExecutionContext; | ||||||||
| import org.openrewrite.Recipe; | ||||||||
| import org.openrewrite.TreeVisitor; | ||||||||
| import org.openrewrite.java.tree.*; | ||||||||
| import org.openrewrite.kotlin.KotlinTemplate; | ||||||||
| import org.openrewrite.kotlin.KotlinVisitor; | ||||||||
|
|
||||||||
| import java.util.*; | ||||||||
| import java.util.regex.Matcher; | ||||||||
| import java.util.regex.Pattern; | ||||||||
|
|
||||||||
| import static java.lang.String.format; | ||||||||
| import static java.util.Collections.emptySet; | ||||||||
| import static java.util.Objects.requireNonNull; | ||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| import static java.util.stream.Collectors.toMap; | ||||||||
| import static java.util.stream.Collectors.toSet; | ||||||||
|
|
||||||||
| public class ReplaceDeprecatedCall extends Recipe { | ||||||||
|
|
||||||||
| @Override | ||||||||
| public String getDisplayName() { | ||||||||
| return "Replace deprecated Kotlin methods with suggested replacements"; | ||||||||
| } | ||||||||
|
|
||||||||
| @Override | ||||||||
| public String getDescription() { | ||||||||
| return "Apply replacements as defined by Kotlin's `@Deprecated` annotation with the `ReplaceWith` parameter. " + | ||||||||
| "Uses the ReplaceWith expression and imports to replace deprecated method calls and property accesses. " + | ||||||||
| "Supports both function calls and property references."; | ||||||||
| } | ||||||||
|
|
||||||||
| @Override | ||||||||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||||||||
| return new KotlinVisitor<ExecutionContext>() { | ||||||||
| @Override | ||||||||
| public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { | ||||||||
| J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx); | ||||||||
| ReplaceWithValues values = findReplaceWithValues(mi.getMethodType()); | ||||||||
| if (values == null) { | ||||||||
| return mi; | ||||||||
| } | ||||||||
| Template template = values.template(mi); | ||||||||
| if (template == null) { | ||||||||
| return mi; | ||||||||
| } | ||||||||
| removeAndAddImports(method, values.getImports()); | ||||||||
| J replacement = KotlinTemplate.builder(template.getString()) | ||||||||
| .imports(values.getImports().toArray(new String[0])) | ||||||||
|
Comment on lines
+77
to
+78
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||
| .build() | ||||||||
| .apply(updateCursor(mi), mi.getCoordinates().replace(), template.getParameters()); | ||||||||
| return replacement; | ||||||||
| } | ||||||||
|
|
||||||||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
| @Override | ||||||||
| public J visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) { | ||||||||
| J.FieldAccess fa = (J.FieldAccess) super.visitFieldAccess(fieldAccess, ctx); | ||||||||
|
|
||||||||
| // Check if this is a property access (not a method call) | ||||||||
| if (getCursor().getParentTreeCursor().getValue() instanceof J.MethodInvocation) { | ||||||||
| return fa; | ||||||||
| } | ||||||||
|
|
||||||||
| JavaType.Variable variable = fa.getName().getFieldType(); | ||||||||
| if (variable == null) { | ||||||||
| return fa; | ||||||||
| } | ||||||||
|
|
||||||||
| ReplaceWithValues values = findReplaceWithValuesForProperty(variable); | ||||||||
| if (values == null) { | ||||||||
| return fa; | ||||||||
| } | ||||||||
|
|
||||||||
| Template template = values.templateForProperty(fa); | ||||||||
| if (template == null) { | ||||||||
| return fa; | ||||||||
| } | ||||||||
|
|
||||||||
| removeAndAddImports(fa, values.getImports()); | ||||||||
| return KotlinTemplate.builder(template.getString()) | ||||||||
| .imports(values.getImports().toArray(new String[0])) | ||||||||
| .build() | ||||||||
| .apply(updateCursor(fa), fa.getCoordinates().replace(), template.getParameters()); | ||||||||
| } | ||||||||
|
|
||||||||
| @Override | ||||||||
| public J visitIdentifier(J.Identifier identifier, ExecutionContext ctx) { | ||||||||
| J.Identifier id = (J.Identifier) super.visitIdentifier(identifier, ctx); | ||||||||
|
|
||||||||
| // Check if this is a standalone property reference (not part of field access or method call) | ||||||||
| Cursor parent = getCursor().getParentTreeCursor(); | ||||||||
| if (parent.getValue() instanceof J.FieldAccess || | ||||||||
| parent.getValue() instanceof J.MethodInvocation) { | ||||||||
| return id; | ||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| } | ||||||||
|
|
||||||||
| JavaType.Variable variable = id.getFieldType(); | ||||||||
| if (variable == null) { | ||||||||
| return id; | ||||||||
| } | ||||||||
|
|
||||||||
| ReplaceWithValues values = findReplaceWithValuesForProperty(variable); | ||||||||
| if (values == null) { | ||||||||
| return id; | ||||||||
| } | ||||||||
|
|
||||||||
| Template template = values.templateForSimpleProperty(id); | ||||||||
| if (template == null) { | ||||||||
| return id; | ||||||||
| } | ||||||||
|
|
||||||||
| removeAndAddImports(id, values.getImports()); | ||||||||
| return KotlinTemplate.builder(template.getString()) | ||||||||
| .imports(values.getImports().toArray(new String[0])) | ||||||||
| .build() | ||||||||
| .apply(updateCursor(id), id.getCoordinates().replace(), template.getParameters()); | ||||||||
| } | ||||||||
|
|
||||||||
| private @Nullable ReplaceWithValues findReplaceWithValues(JavaType.@Nullable Method methodType) { | ||||||||
| if (methodType == null) { | ||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| List<JavaType.FullyQualified> annotations = methodType.getAnnotations(); | ||||||||
| for (JavaType.FullyQualified annotation : annotations) { | ||||||||
| if ("kotlin.Deprecated".equals(annotation.getFullyQualifiedName())) { | ||||||||
| // For now, return a hardcoded ReplaceWithValues for testing | ||||||||
| // We know from the test that orNone() should be replaced with getOrNone() | ||||||||
| if ("orNone".equals(methodType.getName())) { | ||||||||
| return new ReplaceWithValues("getOrNone()", emptySet()); | ||||||||
| } | ||||||||
| } | ||||||||
| } | ||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
| private @Nullable ReplaceWithValues findReplaceWithValuesForProperty(JavaType.Variable variable) { | ||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| if (variable == null) { | ||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
| List<JavaType.FullyQualified> annotations = variable.getAnnotations(); | ||||||||
| for (JavaType.FullyQualified annotation : annotations) { | ||||||||
| if ("kotlin.Deprecated".equals(annotation.getFullyQualifiedName()) && annotation instanceof JavaType.Annotation) { | ||||||||
| return ReplaceWithValues.parse((JavaType.Annotation) annotation); | ||||||||
| } | ||||||||
| } | ||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
| private void removeAndAddImports(J j, Set<String> templateImports) { | ||||||||
| Set<String> originalImports = findOriginalImports(j); | ||||||||
|
|
||||||||
| // Remove imports that are no longer needed | ||||||||
| for (String originalImport : originalImports) { | ||||||||
| if (!templateImports.contains(originalImport)) { | ||||||||
| maybeRemoveImport(originalImport); | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| // Add new imports needed by the template | ||||||||
| for (String importStr : templateImports) { | ||||||||
| if (!originalImports.contains(importStr)) { | ||||||||
| maybeAddImport(importStr); | ||||||||
| } | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| private Set<String> findOriginalImports(J j) { | ||||||||
| return new KotlinVisitor<Set<String>>() { | ||||||||
| @Override | ||||||||
| public @Nullable JavaType visitType(@Nullable JavaType javaType, Set<String> strings) { | ||||||||
| JavaType jt = super.visitType(javaType, strings); | ||||||||
| if (jt instanceof JavaType.FullyQualified) { | ||||||||
| strings.add(((JavaType.FullyQualified) jt).getFullyQualifiedName()); | ||||||||
| } | ||||||||
| return jt; | ||||||||
| } | ||||||||
| }.reduce(j, new HashSet<>()); | ||||||||
| } | ||||||||
|
|
||||||||
| private J avoidMethodSelfReferences(J original, J replacement) { | ||||||||
| JavaType.Method replacementMethodType = replacement instanceof J.MethodInvocation ? | ||||||||
| ((J.MethodInvocation) replacement).getMethodType() : null; | ||||||||
| if (replacementMethodType == null) { | ||||||||
| return replacement; | ||||||||
| } | ||||||||
|
|
||||||||
| Cursor cursor = getCursor(); | ||||||||
| while ((cursor = cursor.getParent()) != null) { | ||||||||
| Object value = cursor.getValue(); | ||||||||
|
|
||||||||
| JavaType.Method cursorMethodType; | ||||||||
| if (value instanceof J.MethodInvocation) { | ||||||||
| cursorMethodType = ((J.MethodInvocation) value).getMethodType(); | ||||||||
| } else if (value instanceof J.MethodDeclaration) { | ||||||||
| cursorMethodType = ((J.MethodDeclaration) value).getMethodType(); | ||||||||
| } else { | ||||||||
| continue; | ||||||||
| } | ||||||||
| if (TypeUtils.isOfType(replacementMethodType, cursorMethodType)) { | ||||||||
| return original; | ||||||||
| } | ||||||||
| } | ||||||||
| return replacement; | ||||||||
| } | ||||||||
| }; | ||||||||
| } | ||||||||
|
|
||||||||
| @Value | ||||||||
| private static class ReplaceWithValues { | ||||||||
| private static final Pattern TEMPLATE_IDENTIFIER = Pattern.compile("#\\{(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*):any\\(.*?\\)}"); | ||||||||
|
|
||||||||
| @Getter(AccessLevel.NONE) | ||||||||
| String expression; | ||||||||
|
|
||||||||
| Set<String> imports; | ||||||||
|
|
||||||||
| static @Nullable ReplaceWithValues parse(JavaType.Annotation annotation) { | ||||||||
| Map<String, Object> values = annotation.getValues().stream().collect(toMap( | ||||||||
| e -> ((JavaType.Method) e.getElement()).getName(), | ||||||||
| JavaType.Annotation.ElementValue::getValue | ||||||||
| )); | ||||||||
|
|
||||||||
| // Look for ReplaceWith annotation within the Deprecated annotation | ||||||||
| Object replaceWithValue = values.get("replaceWith"); | ||||||||
| if (!(replaceWithValue instanceof JavaType.Annotation)) { | ||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
| JavaType.Annotation replaceWith = (JavaType.Annotation) replaceWithValue; | ||||||||
| Map<String, Object> replaceWithValues = replaceWith.getValues().stream().collect(toMap( | ||||||||
| e -> ((JavaType.Method) e.getElement()).getName(), | ||||||||
| JavaType.Annotation.ElementValue::getValue | ||||||||
| )); | ||||||||
|
|
||||||||
| String expression = (String) replaceWithValues.get("expression"); | ||||||||
| if (expression == null || expression.isEmpty()) { | ||||||||
| return null; | ||||||||
| } | ||||||||
|
|
||||||||
| return new ReplaceWithValues( | ||||||||
| expression, | ||||||||
| parseImports(replaceWithValues.get("imports"))); | ||||||||
| } | ||||||||
|
|
||||||||
| private static Set<String> parseImports(@Nullable Object importsValue) { | ||||||||
| if (importsValue instanceof List) { | ||||||||
| return ((List<?>) importsValue).stream() | ||||||||
| .map(Object::toString) | ||||||||
| .collect(toSet()); | ||||||||
| } | ||||||||
| return emptySet(); | ||||||||
| } | ||||||||
|
|
||||||||
| @Nullable | ||||||||
| Template template(J.MethodInvocation original) { | ||||||||
| JavaType.Method methodType = original.getMethodType(); | ||||||||
| if (methodType == null) { | ||||||||
| return null; | ||||||||
| } | ||||||||
| String templateString = createTemplateString(original, expression, methodType.getParameterNames()); | ||||||||
| List<Object> parameters = createParameters(templateString, original, methodType.getParameterNames()); | ||||||||
| return new Template(templateString, parameters.toArray(new Object[0])); | ||||||||
| } | ||||||||
|
|
||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| @Nullable | ||||||||
| Template templateForProperty(J.FieldAccess original) { | ||||||||
| String templateString = expression; | ||||||||
| if (original.getTarget() != null) { | ||||||||
| templateString = templateString.replaceAll("\\bthis\\b", "#{this:any()}"); | ||||||||
| } | ||||||||
| List<Object> parameters = new ArrayList<>(); | ||||||||
| if (original.getTarget() != null) { | ||||||||
| parameters.add(original.getTarget()); | ||||||||
| } | ||||||||
| return new Template(templateString, parameters.toArray(new Object[0])); | ||||||||
| } | ||||||||
|
|
||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| @Nullable | ||||||||
| Template templateForSimpleProperty(J.Identifier original) { | ||||||||
| // For simple property references, just use the expression as-is | ||||||||
| return new Template(expression, new Object[0]); | ||||||||
| } | ||||||||
|
|
||||||||
| private static String createTemplateString(J.MethodInvocation original, String replacement, List<String> originalParameterNames) { | ||||||||
| String templateString = original.getSelect() == null && replacement.startsWith("this.") ? | ||||||||
| replacement.replaceFirst("^this\\.\\b", "") : | ||||||||
| replacement.replaceAll("\\bthis\\b", "#{this:any()}"); | ||||||||
|
|
||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| for (String parameterName : originalParameterNames) { | ||||||||
| // Replace parameter names with their values in the templateString | ||||||||
| templateString = templateString | ||||||||
| .replaceFirst(format("\\b%s\\b", parameterName), format("#{%s:any()}", parameterName)) | ||||||||
| .replaceAll(format("(?<!\\{)\\b%s\\b", parameterName), format("#{%s}", parameterName)); | ||||||||
| } | ||||||||
| return templateString; | ||||||||
| } | ||||||||
|
|
||||||||
| private static List<Object> createParameters(String templateString, J.MethodInvocation original, List<String> originalParameterNames) { | ||||||||
| Map<String, Expression> lookup = new HashMap<>(); | ||||||||
| if (original.getSelect() != null) { | ||||||||
| lookup.put("this", original.getSelect()); | ||||||||
| } | ||||||||
|
|
||||||||
| for (int i = 0; i < originalParameterNames.size(); i++) { | ||||||||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||||
| String originalName = originalParameterNames.get(i); | ||||||||
| Expression originalValue = original.getArguments().get(i); | ||||||||
| lookup.put(originalName, originalValue); | ||||||||
| } | ||||||||
|
|
||||||||
| List<Object> parameters = new ArrayList<>(); | ||||||||
| Matcher matcher = TEMPLATE_IDENTIFIER.matcher(templateString); | ||||||||
| while (matcher.find()) { | ||||||||
| String name = matcher.group(1); | ||||||||
| Object value = lookup.get(name); | ||||||||
| if (value != null) { | ||||||||
| parameters.add(value); | ||||||||
| } | ||||||||
| } | ||||||||
| return parameters; | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| @Value | ||||||||
| private static class Template { | ||||||||
| String string; | ||||||||
| Object[] parameters; | ||||||||
| } | ||||||||
| } | ||||||||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||
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.