Skip to content

Commit f68c4fb

Browse files
Groovy: fix parsing syntactic sugar of closure-call expressions (#7501)
1 parent 7fb338d commit f68c4fb

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2134,6 +2134,24 @@ public void visitMapExpression(MapExpression map) {
21342134

21352135
@Override
21362136
public void visitMethodCallExpression(MethodCallExpression call) {
2137+
// Groovy parses control-flow constructs inside a GString interpolation
2138+
// (e.g. ${if (cond) { a } else { b }}) as a synthetic implicit call() on
2139+
// a ClosureExpression that wraps the statement. The "call" method name
2140+
// does not appear in the source, so unwrap and visit the inner statement.
2141+
if (call.isImplicitThis() &&
2142+
call.getObjectExpression() instanceof ClosureExpression &&
2143+
"call".equals(call.getMethodAsString()) &&
2144+
call.getArguments() instanceof ArgumentListExpression &&
2145+
((ArgumentListExpression) call.getArguments()).getExpressions().isEmpty()) {
2146+
ClosureExpression closure = (ClosureExpression) call.getObjectExpression();
2147+
if (closure.getCode() instanceof BlockStatement) {
2148+
BlockStatement body = (BlockStatement) closure.getCode();
2149+
if (body.getStatements().size() == 1 && body.getStatements().get(0) instanceof IfStatement) {
2150+
body.getStatements().get(0).visit(this);
2151+
return;
2152+
}
2153+
}
2154+
}
21372155
queue.add(insideParentheses(call, fmt -> {
21382156
ImplicitDot implicitDot = null;
21392157
JRightPadded<Expression> select = null;

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,17 @@ void gStringWithStringLiteralsWithParentheses() {
279279
);
280280
}
281281

282+
@Test
283+
void gStringWithIfElseExpression() {
284+
rewriteRun(
285+
groovy(
286+
"""
287+
def x = "${if (true) { "a" } else { "b" }}"
288+
"""
289+
)
290+
);
291+
}
292+
282293
@Test
283294
void mapLiteral() {
284295
rewriteRun(

0 commit comments

Comments
 (0)