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

Fix parsing error of modifier before redundant parens #580

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -330,13 +330,6 @@ public J visitMethodDeclaration(K.MethodDeclaration methodDeclaration, PrintOutp
return delegate.visitMethodDeclaration0(methodDeclaration.getMethodDeclaration(), methodDeclaration.getTypeConstraints(), p);
}

@Override
public J visitParenthesizedTypeTree(J.ParenthesizedTypeTree parTree, PrintOutputCapture<P> p) {
visitSpace(parTree.getPrefix(), Space.Location.PARENTHESES_PREFIX, p);
visitParentheses(parTree.getParenthesizedType(), p);
return parTree;
}

@Override
public J visitProperty(K.Property property, PrintOutputCapture<P> p) {
beforeSyntax(property, KSpace.Location.PROPERTY_PREFIX, p);
Expand Down Expand Up @@ -1075,6 +1068,26 @@ public J visitNewClass(J.NewClass newClass, PrintOutputCapture<P> p) {
return newClass;
}

@SuppressWarnings("ConstantValue")
@Override
public J visitParenthesizedTypeTree(J.ParenthesizedTypeTree parTree, PrintOutputCapture<P> p) {
visitSpace(parTree.getPrefix(), Space.Location.PARENTHESES_PREFIX, p);
if (!parTree.getAnnotations().isEmpty()) {
for (J.Annotation anno : parTree.getAnnotations()) {
visitAnnotation(anno, p);
}
}

if (parTree.getModifiers() != null && !parTree.getModifiers().isEmpty()) {
for (J.Modifier mod : parTree.getModifiers()) {
visitModifier(mod, p);
}
}
visitParentheses(parTree.getParenthesizedType(), p);

return parTree;
}

@Override
public J visitReturn(J.Return return_, PrintOutputCapture<P> p) {
if (return_.getMarkers().findFirst(ImplicitReturn.class).isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -824,14 +824,14 @@ public J visitNullableType(KtNullableType nullableType, ExecutionContext data) {
throw new UnsupportedOperationException("This should never happen");
}

TypeTree typeTree = (TypeTree) requireNonNull(innerType).accept(this, data);
Set<PsiElement> consumedSpaces = new HashSet<>();
if (innerType.getNextSibling() != null &&
isSpace(innerType.getNextSibling().getNode()) &&
!(innerType instanceof KtNullableType)) {
consumedSpaces.add(innerType.getNextSibling());
}

TypeTree typeTree = (TypeTree) requireNonNull(innerType).accept(this, data);
if (typeTree instanceof K.FunctionType && nullableType.getModifierList() != null) {
List<J.Annotation> leadingAnnotations = new ArrayList<>();
List<J.Modifier> modifiers = mapModifiers(nullableType.getModifierList(), leadingAnnotations, emptyList(), data);
Expand All @@ -845,37 +845,7 @@ public J visitNullableType(KtNullableType nullableType, ExecutionContext data) {
typeTree = ((K.FunctionType) typeTree).withModifiers(modifiers).withLeadingAnnotations(leadingAnnotations);
}

// Handle parentheses or potential nested parentheses
Stack<Pair<Integer, Integer>> parenPairs = new Stack<>();
List<PsiElement> allChildren = getAllChildren(nullableType);

TypeTree j = typeTree;
int l = 0;
int r = allChildren.size() - 1;
while (l < r) {
l = findFirstLPAR(allChildren, l);
r = findLastRPAR(allChildren, r);
if (l * r < 0) {
throw new UnsupportedOperationException("Unpaired parentheses!");
}
if (l < 0 || r < 0) {
break;
}
parenPairs.add(new Pair<>(l++, r--));
}

while (!parenPairs.empty()) {
Pair<Integer, Integer> parenPair = parenPairs.pop();
PsiElement lPAR = allChildren.get(parenPair.getFirst());
PsiElement rPAR = allChildren.get(parenPair.getSecond());
j = new J.ParenthesizedTypeTree(randomId(),
Space.EMPTY,
Markers.EMPTY,
emptyList(),
new J.Parentheses<>(randomId(), prefix(lPAR), Markers.EMPTY, padRight(j, prefix(rPAR, consumedSpaces)))
);
}

TypeTree j = maybeNestedParensType(typeTree, nullableType, emptyList(), -1);
return new J.NullableType(randomId(),
merge(deepPrefix(nullableType), j.getPrefix()),
Markers.EMPTY,
Expand Down Expand Up @@ -3181,6 +3151,10 @@ public J visitTypeReference(KtTypeReference typeReference, ExecutionContext data
Set<PsiElement> consumedSpaces = preConsumedInfix(typeReference);

List<J.Modifier> modifiers = mapModifiers(typeReference.getModifierList(), leadingAnnotations, lastAnnotations, data);
int modifierOffSet = typeReference.getModifierList() != null ? typeReference.getModifierList().getTextOffset() : -1;
PsiElement maybeLastLPAR = findLastChild(typeReference, KotlinTreeParserVisitor::isLPAR);
boolean modifierBeforeParens = maybeLastLPAR != null && modifierOffSet > 0 && maybeLastLPAR.getTextOffset() > modifierOffSet;

if (!leadingAnnotations.isEmpty()) {
leadingAnnotations = ListUtils.mapFirst(leadingAnnotations, anno -> anno.withPrefix(prefix(typeReference)));
consumedSpaces.add(findFirstPrefixSpace(typeReference));
Expand All @@ -3202,7 +3176,12 @@ public J visitTypeReference(KtTypeReference typeReference, ExecutionContext data

if (j instanceof K.FunctionType && typeReference.getModifierList() != null) {
K.FunctionType functionType = (K.FunctionType) j;
functionType = functionType.withModifiers(modifiers).withLeadingAnnotations(leadingAnnotations);

if (!modifierBeforeParens) {
functionType = functionType.withModifiers(modifiers);
}

functionType = functionType.withLeadingAnnotations(leadingAnnotations);

if (functionType.getReceiver() != null) {
functionType = functionType.withReceiver(
Expand All @@ -3223,35 +3202,8 @@ public J visitTypeReference(KtTypeReference typeReference, ExecutionContext data
j = ((J.NullableType) j).withAnnotations(leadingAnnotations);
}

// Handle potential redundant nested parentheses
Stack<Pair<Integer, Integer>> parenPairs = new Stack<>();
List<PsiElement> allChildren = getAllChildren(typeReference);

int l = 0;
int r = allChildren.size() - 1;
while (l < r) {
l = findFirstLPAR(allChildren, l);
r = findLastRPAR(allChildren, r);
if (l * r < 0) {
throw new UnsupportedOperationException("Unpaired parentheses!");
}
if (l < 0 || r < 0) {
break;
}
parenPairs.add(new Pair<>(l++, r--));
}

while (!parenPairs.empty()) {
Pair<Integer, Integer> parenPair = parenPairs.pop();
PsiElement lPAR = allChildren.get(parenPair.getFirst());
PsiElement rPAR = allChildren.get(parenPair.getSecond());
TypeTree typeTree = j instanceof K.FunctionType ? ((K.FunctionType) j).withReturnType(((K.FunctionType) j).getReturnType().withAfter(Space.EMPTY)) : (TypeTree) j;
j = new J.ParenthesizedTypeTree(randomId(),
Space.EMPTY,
Markers.EMPTY,
emptyList(),
new J.Parentheses<>(randomId(), prefix(lPAR), Markers.EMPTY, padRight(typeTree, prefix(rPAR)))
);
if (j instanceof TypeTree) {
j = maybeNestedParensType((TypeTree) j, typeReference, modifiers, modifierOffSet);
}

return j.withPrefix(merge(prefix(typeReference, consumedSpaces), j.getPrefix()));
Expand Down Expand Up @@ -3765,6 +3717,54 @@ private boolean isSemicolon(@Nullable PsiElement element) {
return element instanceof LeafPsiElement && ((LeafPsiElement) element).getElementType() == KtTokens.SEMICOLON;
}

// Handle parentheses or potential nested parentheses
private TypeTree maybeNestedParensType(TypeTree typeTree, KtElement parent, List<J.Modifier> modifiers, int modifierOffset) {
Stack<Pair<Integer, Integer>> parenPairs = new Stack<>();
List<PsiElement> allChildren = getAllChildren(parent);
TypeTree j = typeTree;
int l = 0;
int r = allChildren.size() - 1;
while (l < r) {
l = findFirstLPAR(allChildren, l);
r = findLastRPAR(allChildren, r);
if (l * r < 0) {
throw new UnsupportedOperationException("Unpaired parentheses!");
}
if (l < 0 || r < 0) {
break;
}
parenPairs.add(new Pair<>(l++, r--));
}

while (!parenPairs.empty()) {
Pair<Integer, Integer> parenPair = parenPairs.pop();
PsiElement lPAR = allChildren.get(parenPair.getFirst());
PsiElement rPAR = allChildren.get(parenPair.getSecond());
TypeTree tt = j instanceof K.FunctionType ? ((K.FunctionType) j).withReturnType(((K.FunctionType) j).getReturnType().withAfter(Space.EMPTY)) : j;
List<J.Modifier> mods = emptyList();

if (modifierOffset > 0 && lPAR.getTextOffset() < modifierOffset) {
if (tt instanceof J.ParenthesizedTypeTree) {
tt = ((J.ParenthesizedTypeTree) j).withModifiers(modifiers);
}
modifierOffset = -1;
}

j = new J.ParenthesizedTypeTree(randomId(),
Space.EMPTY,
Markers.EMPTY,
emptyList(),
mods,
new J.Parentheses<>(randomId(), prefix(lPAR), Markers.EMPTY, padRight(tt, prefix(rPAR)))
);
}

if (modifierOffset > 0 && j instanceof J.ParenthesizedTypeTree) {
j = ((J.ParenthesizedTypeTree) j).withModifiers(modifiers);
}
return j;
}

private <T> JLeftPadded<T> padLeft(Space left, T tree) {
return new JLeftPadded<>(left, tree, Markers.EMPTY);
}
Expand Down
44 changes: 44 additions & 0 deletions src/test/java/org/openrewrite/kotlin/tree/ParenthesesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,48 @@ fun x ( input : ( ( ( ( ) -> String ? ) ? ) ? ) ) {
)
);
}

@Issue("https://github.com/openrewrite/rewrite-kotlin/issues/571")
@Test
void modifierBeforeRedundantParens() {
rewriteRun(
kotlin(
"""
class SomeReceiver
suspend inline fun SomeReceiver . method(
crossinline body : suspend ( SomeReceiver . () -> Unit )
) {}
"""
)
);
}

@Test
void modifierInRedundantParens() {
rewriteRun(
kotlin(
"""
class SomeReceiver
suspend inline fun SomeReceiver . method(
crossinline body : ( suspend SomeReceiver . () -> Unit )
) {}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite-kotlin/issues/571")
@Test
void modifierInNestedRedundantParens() {
rewriteRun(
kotlin(
"""
class SomeReceiver
suspend inline fun SomeReceiver . method(
crossinline body : ( ( suspend ( ( SomeReceiver . () -> Unit ) ) ) )
) {}
"""
)
);
}
}
Loading