Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ dependencies {

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

testImplementation("com.google.errorprone:error_prone_annotations:2.39.0")
testImplementation("com.google.guava:guava:33.0.0-jre")
testImplementation("joda-time:joda-time:2.12.3")
testImplementation("org.threeten:threeten-extra:1.8.0")
Expand Down
170 changes: 170 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/Inlinings.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/*
* 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.jetbrains.annotations.NotNull;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Inlinings 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() {
return //Preconditions.check(
// new UsesType<>(INLINE_ME, true), // FIXME Not picked up that we're calling an annotated method
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
InlineMeValues values = findInlineMeValues(mi.getMethodType());
if (values == null) {
return mi;
}
Template template = values.template(mi);
if (template == null) {
return mi;
}
return JavaTemplate.builder(template.getString())
.doBeforeParseTemplate(System.out::println)
.contextSensitive()
.imports(values.getImports())
.staticImports(values.getStaticImports())
.build()
.apply(getCursor(), mi.getCoordinates().replace(), template.getParameters());
}

private @Nullable InlineMeValues findInlineMeValues(JavaType.@Nullable Method methodType) {
if (methodType == null) {
return null;
}
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;
}
}
/*)*/;
}

@Value
private static class InlineMeValues {
private static final Pattern TEMPLATE_IDENTIFIER = Pattern.compile("#\\{(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*):any\\(\\)}");
@Getter(AccessLevel.NONE)
String replacement;
String[] imports;
String[] staticImports;

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

@Nullable
Template template(J.MethodInvocation original) {
JavaType.Method methodType = original.getMethodType();
if (methodType == null) {
return null;
}

List<String> originalParameterNames = methodType.getParameterNames();
String templateString = createTemplateString(originalParameterNames);
Expression[] parameters = createParameters(templateString, originalParameterNames, original);
return new Template(templateString, parameters);
}

private @NotNull String createTemplateString(List<String> originalParameterNames) {
String templateString = 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 Expression[] createParameters(String templateString, List<String> originalParameterNames, J.MethodInvocation original) {
Map<String, Expression> lookup = new HashMap<>();
if (original.getSelect() != null) {
lookup.put("this", original.getSelect());
}
for (int i = 0; i < originalParameterNames.size(); i++) {
String originalName = originalParameterNames.get(i);
Expression originalValue = original.getArguments().get(i);
lookup.put(originalName, originalValue);
}
List<Expression> 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);
} else {
throw new IllegalStateException(
"No parameter found for " + matcher.group(1) + " in template: " + templateString);
}
}
return parameters.toArray(new Expression[0]);
}
}

@Value
private static class Template {
String string;
Object[] parameters;
}
}
83 changes: 83 additions & 0 deletions src/test/java/org/openrewrite/java/migrate/InliningsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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 org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.SourceSpec;

import static org.openrewrite.java.Assertions.java;

class InliningsTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new Inlinings())
.parser(JavaParser.fromJavaVersion().classpath("guava", "error_prone_annotations"));
}

@Test
@DocumentExample
void inlineMe() {
//language=java
rewriteRun(
java(
"""
package m;

import com.google.errorprone.annotations.InlineMe;
import java.time.Duration;

public final class MyClass {
private final Duration deadline;

public Duration getDeadline() {
return deadline;
}

@Deprecated
@InlineMe(replacement = "this.getDeadline().toMillis()")
public long getDeadlineMillis() {
return getDeadline().toMillis();
}
}
""",
SourceSpec::skip
),
java(
"""
import m.MyClass;
class Foo {
void foo(MyClass myClass) {
myClass.getDeadlineMillis();
}
}
""",
"""
import m.MyClass;
class Foo {
void foo(MyClass myClass) {
myClass.getDeadline().toMillis();
}
}
"""
)
);
}
}
Loading