Skip to content

Commit

Permalink
Fix formatting of calls without parentheses
Browse files Browse the repository at this point in the history
In a call without parentheses (as for example in `it.name to it.get(this)` where `to` is the method) the trailing space should not be used to right-pad the last argument. Instead, that should belong as left padding of the following element. This is important to be able to correctly implement formatting.
  • Loading branch information
knutwannheden committed Oct 3, 2023
1 parent dace9d7 commit e1c5589
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,14 @@ class KotlinParserVisitor(
hasParentheses = true
lPAROffset = firstChild.node.startOffset
}
} else if (firCall.psi is KtArrayAccessExpression) {
hasParentheses = true
} else if (firCall.psi is KtCallExpression && (firCall.psi as KtCallExpression).valueArgumentList != null) {
val argList = (firCall.psi as KtCallExpression).valueArgumentList!!
if (argList.firstChild.node.elementType == KtTokens.LPAR) {
hasParentheses = true
lPAROffset = argList.firstChild.startOffset
}
}

val flattenedExpressions = firArguments.stream()
Expand Down Expand Up @@ -1498,7 +1506,8 @@ class KotlinParserVisitor(
} else {
var isTrailingLambda = false
for (i in flattenedExpressions.indices) {
isTrailingLambda = hasTrailingLambda && i == argumentCount - 1
val lastArg = i == argumentCount - 1
isTrailingLambda = hasTrailingLambda && lastArg
val expression = flattenedExpressions[i]

// Didn't find a way to proper reset the cursor, so have to do a hard reset here
Expand All @@ -1512,13 +1521,14 @@ class KotlinParserVisitor(
expressions.add(padRight(expr, Space.EMPTY))
break
}
val padding = whitespace()
// don't consume trailing space if the call doesn't have any parentheses
val padding = if (lastArg && !hasParentheses) Space.EMPTY else whitespace()
var trailingComma: TrailingComma? = null
if (!isInfix) {
if (isLastArgumentLambda && i == argumentCount - 2) {
trailingComma = if (skip(",")) TrailingComma(randomId(), whitespace()) else null
skip(closing)
} else if (i == argumentCount - 1) {
} else if (lastArg) {
trailingComma = if (skip(",")) TrailingComma(randomId(), whitespace()) else null
} else {
skip(",")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2198,4 +2198,19 @@ fun test0() {
)
);
}

@Test
void trailingLambdaCall() {
rewriteRun(
kotlin(
"""
inline fun <reified T : Any> T.destruct(): Map<String, Any?> {
return T::class.memberProperties.map {
it.name to it.get(this)
}.toMap()
}
"""
)
);
}
}

0 comments on commit e1c5589

Please sign in to comment.