Skip to content

Commit 20a886e

Browse files
Groovy: fix parsing of command expressions with args in parens (#7503)
1 parent 86bec62 commit 20a886e

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2186,6 +2186,7 @@ public void visitMethodCallExpression(MethodCallExpression call) {
21862186
source.charAt(cursor) == '(' && (cursor + methodName.length() > source.length() ||
21872187
!methodName.equals(source.substring(cursor, cursor + methodName.length())))
21882188
);
2189+
Space spaceBeforeArgs = null;
21892190
if (implicitCall) {
21902191
// This is an implicit call() method - create identifier but it doesn't get printed
21912192
name = new J.Identifier(randomId(), prefix, Markers.EMPTY, emptyList(), "", null, null);
@@ -2195,6 +2196,10 @@ public void visitMethodCallExpression(MethodCallExpression call) {
21952196
name = new J.Identifier(randomId(), prefix, Markers.EMPTY, emptyList(), methodName, null, null);
21962197
} else if (select != null && select.getElement() instanceof J.Identifier) {
21972198
name = (J.Identifier) select.getElement();
2199+
// Closure-style command expression like `x foo(c)` parses as `x.call(foo(c))`.
2200+
// The whitespace captured as select's right-padding is the space between
2201+
// the closure name and its argument list, which has no parens.
2202+
spaceBeforeArgs = select.getAfter();
21982203
select = null;
21992204
} else {
22002205
throw new IllegalArgumentException("Unable to parse method call");
@@ -2239,6 +2244,9 @@ public void visitMethodCallExpression(MethodCallExpression call) {
22392244
markers = handlesCaseWhereEmptyParensAheadOfClosure(args, markers);
22402245
}
22412246
JContainer<Expression> args = doVisit(call.getArguments());
2247+
if (spaceBeforeArgs != null && !spaceBeforeArgs.getWhitespace().isEmpty()) {
2248+
args = args.withBefore(spaceBeforeArgs);
2249+
}
22422250

22432251
MethodNode methodNode = (MethodNode) call.getNodeMetaData().get(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
22442252
JavaType.Method methodType = null;

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,4 +771,16 @@ void methodNameStartingWithClassKeyword() {
771771
)
772772
);
773773
}
774+
775+
@Test
776+
void commandExpressionWithParenthesizedArgument() {
777+
rewriteRun(
778+
groovy(
779+
"""
780+
def x
781+
x foo(c)
782+
"""
783+
)
784+
);
785+
}
774786
}

0 commit comments

Comments
 (0)