Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
4dcad6a
Create replace for `@InlineMe` annotations
timtebeek Jul 7, 2025
f14bcc6
Implement conversion from replacement string to templated
timtebeek Jul 7, 2025
f122b98
Small tweaks
timtebeek Jul 7, 2025
171791d
Drop JetBrains annotation
timtebeek Jul 7, 2025
8b075ff
Make `createTemplateString` static as well
timtebeek Jul 7, 2025
422e156
Update Inlinings.java
timtebeek Jul 7, 2025
aac36ab
Additional test cases
timtebeek Jul 10, 2025
78bd090
Merge branch 'main' into recipe-for-InlineMe-annotation
timtebeek Jul 10, 2025
e9ac12f
Add support for constructors as well
timtebeek Jul 10, 2025
506797a
Merge branch 'main' into recipe-for-InlineMe-annotation
timtebeek Jul 17, 2025
76d8972
Update InliningsTest.java
timtebeek Jul 17, 2025
c83ce5a
Add an even simpler document example test case
timtebeek Aug 10, 2025
d7eacf8
Merge branch 'main' into recipe-for-InlineMe-annotation
timtebeek Aug 10, 2025
a3468ef
Show initial passing test
timtebeek Aug 10, 2025
939f31f
Fix template when select is null
timtebeek Aug 10, 2025
576cb71
Show more tests passing
timtebeek Aug 10, 2025
1a791d6
Show all tests passing
timtebeek Aug 10, 2025
7fec2ca
Avoid self referential replacements
timtebeek Aug 10, 2025
f4bc91b
Switch to `latest.release`
timtebeek Aug 10, 2025
439a911
Show problematic case for Guava
timtebeek Aug 10, 2025
1dc2878
Rename recipe
timtebeek Aug 10, 2025
2524fe3
Explicitly show parameter names are not available
timtebeek Aug 10, 2025
6ee0d51
Merge branch 'main' into recipe-for-InlineMe-annotation
timtebeek Aug 18, 2025
9dc3314
Apply code suggestion
timtebeek Aug 18, 2025
2aca035
Quit early when we encounter `arg0`
timtebeek Aug 18, 2025
30b9b79
Remove imports before adding imports
timtebeek Aug 18, 2025
b406699
Add support for adding static imports
timtebeek Aug 19, 2025
4086d65
Add support for removing static imports
timtebeek Aug 19, 2025
6a7ed9f
Merge the visitors for regular and static import removal
timtebeek Aug 19, 2025
5a4359f
Pull out a separate recipe to `findOriginalImports`
timtebeek Aug 19, 2025
739a032
Create a Guava recipe to inline methods and move the tests there
timtebeek Aug 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ dependencies {

testImplementation("org.assertj:assertj-core:latest.release")

testImplementation("com.google.guava:guava:33.0.0-jre")
testImplementation("com.google.errorprone:error_prone_annotations:latest.release")
testImplementation("com.google.guava:guava:33.4.8-jre")
testImplementation("joda-time:joda-time:2.12.3")
testImplementation("org.threeten:threeten-extra:1.8.0")

Expand Down
309 changes: 309 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/InlineMethodCalls.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,309 @@
/*
* Copyright 2025 the original author or authors.
* <p>
* Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license
* <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.java.migrate;

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.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;

public class InlineMethodCalls extends Recipe {

private static final String INLINE_ME = "com.google.errorprone.annotations.InlineMe";

@Override
public String getDisplayName() {
return "Inline methods annotated with `@InlineMe`";
}

@Override
public String getDescription() {
return "Apply inlinings defined by Error Prone's [`@InlineMe` annotation](https://errorprone.info/docs/inlineme).";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
// XXX Preconditions can not yet pick up the `@InlineMe` annotation on methods used
return new JavaVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
InlineMeValues values = findInlineMeValues(mi.getMethodType());
if (values == null) {
return mi;
}
Template template = values.template(mi);
if (template == null) {
return mi;
}
removeAndAddImports(method, values.getImports(), values.getStaticImports());
J replacement = JavaTemplate.builder(template.getString())
.contextSensitive()
.imports(values.getImports().toArray(new String[0]))
.staticImports(values.getStaticImports().toArray(new String[0]))
.javaParser(JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()))
.build()
.apply(updateCursor(mi), mi.getCoordinates().replace(), template.getParameters());
return avoidMethodSelfReferences(mi, replacement);
}

@Override
public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
J.NewClass nc = (J.NewClass) super.visitNewClass(newClass, ctx);
InlineMeValues values = findInlineMeValues(nc.getConstructorType());
if (values == null) {
return nc;
}
Template template = values.template(nc);
if (template == null) {
return nc;
}
removeAndAddImports(newClass, values.getImports(), values.getStaticImports());
J replacement = JavaTemplate.builder(template.getString())
.contextSensitive()
.imports(values.getImports().toArray(new String[0]))
.staticImports(values.getStaticImports().toArray(new String[0]))
.javaParser(JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()))
.build()
.apply(updateCursor(nc), nc.getCoordinates().replace(), template.getParameters());
return avoidMethodSelfReferences(nc, replacement);
}

private @Nullable InlineMeValues findInlineMeValues(JavaType.@Nullable Method methodType) {
if (methodType == null) {
return null;
}
List<String> parameterNames = methodType.getParameterNames();
if (!parameterNames.isEmpty() && "arg0".equals(parameterNames.get(0))) {
return null; // We need `-parameters` before we're able to substitute parameters in the template
}

List<JavaType.FullyQualified> annotations = methodType.getAnnotations();
for (JavaType.FullyQualified annotation : annotations) {
if (INLINE_ME.equals(annotation.getFullyQualifiedName())) {
return InlineMeValues.parse((JavaType.Annotation) annotation);
}
}
return null;
}

private void removeAndAddImports(MethodCall method, Set<String> templateImports, Set<String> templateStaticImports) {
Set<String> originalImports = findOriginalImports(method);

// Remove regular and static imports that are no longer needed
for (String originalImport : originalImports) {
if (!templateImports.contains(originalImport) &&
!templateStaticImports.contains(originalImport)) {
maybeRemoveImport(originalImport);
}
}

// Add new regular imports needed by the template
for (String importStr : templateImports) {
if (!originalImports.contains(importStr)) {
maybeAddImport(importStr);
}
}

// Add new static imports needed by the template
for (String staticImport : templateStaticImports) {
if (!originalImports.contains(staticImport)) {
int lastDot = staticImport.lastIndexOf('.');
if (0 < lastDot) {
maybeAddImport(
staticImport.substring(0, lastDot),
staticImport.substring(lastDot + 1));
}
}
}
}

private Set<String> findOriginalImports(MethodCall method) {
// Collect all regular and static imports used in the original method call
return new JavaVisitor<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;
}

@Override
public J visitMethodInvocation(J.MethodInvocation methodInvocation, Set<String> staticImports) {
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(methodInvocation, staticImports);
// Check if this is a static method invocation without a select (meaning it might be statically imported)
JavaType.Method methodType = mi.getMethodType();
if (mi.getSelect() == null && methodType != null && methodType.hasFlags(Flag.Static)) {
staticImports.add(String.format("%s.%s",
methodType.getDeclaringType().getFullyQualifiedName(),
methodType.getName()));
}
return mi;
}

@Override
public J visitIdentifier(J.Identifier identifier, Set<String> staticImports) {
J.Identifier id = (J.Identifier) super.visitIdentifier(identifier, staticImports);
// Check if this is a static field reference
JavaType.Variable fieldType = id.getFieldType();
if (fieldType != null && fieldType.hasFlags(Flag.Static)) {
if (fieldType.getOwner() instanceof JavaType.FullyQualified) {
staticImports.add(String.format("%s.%s",
((JavaType.FullyQualified) fieldType.getOwner()).getFullyQualifiedName(),
fieldType.getName()));
}
}
return id;
}
}.reduce(method, new HashSet<>());
}

private J avoidMethodSelfReferences(MethodCall original, J replacement) {
JavaType.Method replacementMethodType = replacement instanceof MethodCall ?
((MethodCall) 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 MethodCall) {
cursorMethodType = ((MethodCall) 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 InlineMeValues {
private static final Pattern TEMPLATE_IDENTIFIER = Pattern.compile("#\\{(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*):any\\(.*?\\)}");

@Getter(AccessLevel.NONE)
String replacement;

Set<String> imports;
Set<String> staticImports;

static InlineMeValues parse(JavaType.Annotation annotation) {
Map<String, Object> collect = annotation.getValues().stream().collect(toMap(
e -> ((JavaType.Method) e.getElement()).getName(),
JavaType.Annotation.ElementValue::getValue
));
// Parse imports and static imports from the annotation values
return new InlineMeValues(
(String) collect.get("replacement"),
parseImports(collect.get("imports")),
parseImports(collect.get("staticImports")));
}

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(MethodCall original) {
JavaType.Method methodType = original.getMethodType();
if (methodType == null) {
return null;
}
String templateString = createTemplateString(original, replacement, methodType.getParameterNames());
List<Object> parameters = createParameters(templateString, original);
return new Template(templateString, parameters.toArray(new Object[0]));
}

private static String createTemplateString(MethodCall original, String replacement, List<String> originalParameterNames) {
String templateString = original instanceof J.MethodInvocation &&
((J.MethodInvocation) original).getSelect() == null &&
replacement.startsWith("this.") ?
replacement.replaceFirst("^this.\\b", "") :
replacement.replaceAll("\\bthis\\b", "#{this:any()}");
for (String parameterName : originalParameterNames) {
// Replace parameter names with their values in the templateString
templateString = templateString.replaceAll(
String.format("\\b%s\\b", parameterName),
String.format("#{%s:any()}", parameterName)); // TODO 2nd, 3rd etc should use shorthand `#{a}`
}
return templateString;
}

private static List<Object> createParameters(String templateString, MethodCall original) {
Map<String, Expression> lookup = new HashMap<>();
if (original instanceof J.MethodInvocation) {
Expression select = ((J.MethodInvocation) original).getSelect();
if (select != null) {
lookup.put("this", select);
}
}
List<String> originalParameterNames = requireNonNull(original.getMethodType()).getParameterNames();
for (int i = 0; i < originalParameterNames.size(); i++) {
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()) {
Expression o = lookup.get(matcher.group(1));
if (o != null) {
parameters.add(o);
}
}
return parameters;
}
}

@Value
private static class Template {
String string;
Object[] parameters;
}
}
15 changes: 15 additions & 0 deletions src/main/resources/META-INF/rewrite/no-guava.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ recipeList:
- org.openrewrite.java.migrate.guava.NoGuavaJava21
- org.openrewrite.java.migrate.guava.NoGuavaCreateTempDir
- org.openrewrite.java.migrate.guava.NoGuavaDirectExecutor
- org.openrewrite.java.migrate.guava.NoGuavaInlineMeMethods
- org.openrewrite.java.migrate.guava.NoGuavaListsNewArrayList
- org.openrewrite.java.migrate.guava.NoGuavaListsNewCopyOnWriteArrayList
- org.openrewrite.java.migrate.guava.NoGuavaListsNewLinkedList
Expand Down Expand Up @@ -108,6 +109,20 @@ recipeList:
- org.openrewrite.java.migrate.guava.NoMapsAndSetsWithExpectedSize
- org.openrewrite.java.migrate.guava.PreferMathClamp

---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.migrate.guava.NoGuavaInlineMeMethods
displayName: Inline Guava method calls
description: >-
Inline Guava method calls that are annotated with `@InlineMe` to their replacement method.
tags:
- guava
preconditions:
- org.openrewrite.analysis.search.FindMethods:
methodPattern: com.google.common..* *(..)
recipeList:
- org.openrewrite.java.migrate.InlineMethodCalls

---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.migrate.guava.PreferJavaNioCharsetStandardCharsets
Expand Down
Loading