Skip to content

Commit

Permalink
Support varargs
Browse files Browse the repository at this point in the history
  • Loading branch information
jevanlingen committed Dec 27, 2024
1 parent 362bb54 commit ce70d77
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,23 @@ public void visitMethod(MethodNode method) {
} else {
paramType = visitTypeTree(param.getOriginType());
}

Space varargs = null;
if (paramType instanceof J.ArrayType) {
// E.g. foo(String... x)
if (source.startsWith("...", cursor - 3)) {
varargs = format(source, cursor - 3, cursor - 3);
paramType = ((J.ArrayType) paramType).withDimension(null);
}
// E.g. foo(String ... x)
else if (source.startsWith("...", indexOfNextNonWhitespace(cursor, source))) {
int varargStart = indexOfNextNonWhitespace(cursor, source);
varargs = format(source, cursor, varargStart);
paramType = ((J.ArrayType) paramType).withDimension(null);
cursor = varargStart + 3;
}
}

JRightPadded<J.VariableDeclarations.NamedVariable> paramName = JRightPadded.build(
new J.VariableDeclarations.NamedVariable(randomId(), EMPTY, Markers.EMPTY,
new J.Identifier(randomId(), whitespace(), Markers.EMPTY, emptyList(), param.getName(), null, null),
Expand All @@ -577,7 +594,7 @@ public void visitMethod(MethodNode method) {

params.add(JRightPadded.build((Statement) new J.VariableDeclarations(randomId(), EMPTY,
Markers.EMPTY, paramAnnotations, emptyList(), paramType,
null, emptyList(),
varargs, emptyList(),
singletonList(paramName))).withAfter(rightPad));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,18 @@ def foo(bar, baz) {
);
}

@Test
void varargsArguments() {
rewriteRun(
groovy(
"""
def foo(String... messages) {
}
"""
)
);
}

@Test
void defaultArgumentValues() {
rewriteRun(
Expand Down

0 comments on commit ce70d77

Please sign in to comment.