From ce70d77d6ca8385b64b6e0cdec7c9799d6dd8e07 Mon Sep 17 00:00:00 2001 From: lingenj Date: Fri, 27 Dec 2024 16:54:15 +0100 Subject: [PATCH] Support varargs --- .../groovy/GroovyParserVisitor.java | 19 ++++++++++++++++++- .../groovy/tree/MethodDeclarationTest.java | 12 ++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java index 39d3b18f619..e854d09b6d1 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/GroovyParserVisitor.java @@ -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 paramName = JRightPadded.build( new J.VariableDeclarations.NamedVariable(randomId(), EMPTY, Markers.EMPTY, new J.Identifier(randomId(), whitespace(), Markers.EMPTY, emptyList(), param.getName(), null, null), @@ -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)); } diff --git a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodDeclarationTest.java b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodDeclarationTest.java index ff2bf380095..f73e14cfbd7 100644 --- a/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodDeclarationTest.java +++ b/rewrite-groovy/src/test/java/org/openrewrite/groovy/tree/MethodDeclarationTest.java @@ -110,6 +110,18 @@ def foo(bar, baz) { ); } + @Test + void varargsArguments() { + rewriteRun( + groovy( + """ + def foo(String... messages) { + } + """ + ) + ); + } + @Test void defaultArgumentValues() { rewriteRun(