Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parser does not handle annotated varargs correctly #4628

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,21 @@ class A {
)
);
}

@Test
void annotatedVargArgs() {
rewriteRun(
java(
"""
import org.jspecify.annotations.NonNull;

class ParserError {
private String method(@NonNull final String @NonNull[] arrayArgs, @NonNull final String @NonNull ... varArgs) {
return "";
}
}
"""
)
);
}
}
15 changes: 13 additions & 2 deletions rewrite-java/src/main/java/org/openrewrite/java/JavaPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,8 @@ protected void printStatementTerminator(Statement s, PrintOutputCapture<P> p) {
getCursor()
.dropParentUntil(
c -> c instanceof Switch ||
c instanceof SwitchExpression ||
c == Cursor.ROOT_VALUE
c instanceof SwitchExpression ||
c == Cursor.ROOT_VALUE
)
.getValue();
if (aSwitch instanceof SwitchExpression) {
Expand Down Expand Up @@ -848,6 +848,17 @@ public J visitVariableDeclarations(VariableDeclarations multiVariable, PrintOutp
p.append(']');
}
if (multiVariable.getVarargs() != null) {
if (!(multiVariable.getTypeExpression() instanceof ArrayType)) {
// The `visit(multiVariable.getTypeExpression(), p);` statement above does not know the
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
// enclosing VariableDeclarations is a vararg therefore we have to remove unnecessary dimensions here
if (p.out.charAt(p.out.length() - 1) == ']') {
if (p.out.charAt(p.out.length() - 2) == '[') {
p.out.delete(p.out.length() - 2, p.out.length());
} else {
throw new IllegalStateException("Vararg was interpreted with non empty dimensions");
}
}
}
visitSpace(multiVariable.getVarargs(), Space.Location.VARARGS, p);
p.append("...");
}
Expand Down