Skip to content

Commit 275bf84

Browse files
Groovy: add support for @memoize annotation
1 parent ec4fb3d commit 275bf84

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,6 +1180,13 @@ class B { class B {
11801180
} else {
11811181
body = bodyVisitor.doVisit(method.getCode());
11821182
}
1183+
} else if (annotations.stream().anyMatch(a -> TypeUtils.isOfClassType(a.getAnnotationType().getType(), "groovy.transform.Memoized"))) {
1184+
// The @Memoized AST transformation moves the original body into a synthetic
1185+
// `memoizedMethodPriv$<name>` method (optionally prefixed with `_` on naming collisions)
1186+
// and replaces the original method body with cache-lookup logic that has no source
1187+
// positions. Find the private helper and visit its body so source positions align.
1188+
MethodNode original = findMemoizedOriginalMethod(method);
1189+
body = bodyVisitor.doVisit(original != null ? original.getCode() : method.getCode());
11831190
} else {
11841191
body = bodyVisitor.doVisit(method.getCode());
11851192
}
@@ -1206,6 +1213,22 @@ class B { class B {
12061213
private <T> T pollQueue() {
12071214
return (T) queue.poll();
12081215
}
1216+
1217+
private @Nullable MethodNode findMemoizedOriginalMethod(MethodNode method) {
1218+
String suffix = "memoizedMethodPriv$" + method.getName();
1219+
for (MethodNode candidate : method.getDeclaringClass().getMethods()) {
1220+
String name = candidate.getName();
1221+
int start = 0;
1222+
while (start < name.length() && name.charAt(start) == '_') {
1223+
start++;
1224+
}
1225+
if (name.substring(start).equals(suffix) &&
1226+
candidate.getParameters().length == method.getParameters().length) {
1227+
return candidate;
1228+
}
1229+
}
1230+
return null;
1231+
}
12091232
}
12101233

12111234
private class RewriteGroovyVisitor extends CodeVisitorSupport {

rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/AnnotationTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,24 @@ void run() {}
3939
);
4040
}
4141

42+
@Test
43+
void memoizedMethod() {
44+
rewriteRun(
45+
groovy(
46+
"""
47+
import groovy.transform.Memoized
48+
49+
class Foo {
50+
@Memoized
51+
Object bar() {
52+
return null
53+
}
54+
}
55+
"""
56+
)
57+
);
58+
}
59+
4260
@Test
4361
void simpleFQN() {
4462
rewriteRun(

0 commit comments

Comments
 (0)