Skip to content

Commit

Permalink
Support labeled lambdas in block-like scoping functions
Browse files Browse the repository at this point in the history
  • Loading branch information
nreid260 committed Jun 14, 2023
1 parent b6e5f35 commit 77f7514
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1415,16 +1415,26 @@ class KotlinInputAstVisitor(
if (expression.getPrevSiblingIgnoringWhitespace() is PsiComment) {
return false // Leading comments cause weird indentation.
}
if (expression is KtLambdaExpression) {
return true

var carry = expression
if (carry is KtCallExpression) {
if (
carry.valueArgumentList?.leftParenthesis == null &&
carry.lambdaArguments.isNotEmpty() &&
carry.typeArgumentList?.arguments.isNullOrEmpty()
) {
carry = carry.lambdaArguments[0].getArgumentExpression()
} else {
return false
}
}
if (expression is KtCallExpression &&
expression.valueArgumentList?.leftParenthesis == null &&
expression.lambdaArguments.isNotEmpty() &&
expression.typeArgumentList?.arguments.isNullOrEmpty() &&
expression.lambdaArguments.first().getArgumentExpression() is KtLambdaExpression) {
if (carry is KtLabeledExpression) {
carry = carry.baseExpression
}
if (carry is KtLambdaExpression) {
return true
}

return false
}

Expand All @@ -1433,18 +1443,22 @@ class KotlinInputAstVisitor(
val breakToExpr = genSym()
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent, Optional.of(breakToExpr))

val lambdaExpression =
when (expr) {
is KtLambdaExpression -> expr
is KtCallExpression -> {
visit(expr.calleeExpression)
builder.space()
expr.lambdaArguments[0].getLambdaExpression() ?: fail()
}
else -> throw AssertionError(expr)
}
var carry = expr
if (carry is KtCallExpression) {
visit(carry.calleeExpression)
builder.space()
carry = carry.lambdaArguments[0].getArgumentExpression()
}
if (carry is KtLabeledExpression) {
visit(carry.labelQualifier)
carry = carry.baseExpression ?: fail()
}
if (carry is KtLambdaExpression) {
visitLambdaExpressionInternal(carry, brokeBeforeBrace = breakToExpr)
return
}

visitLambdaExpressionInternal(lambdaExpression, brokeBeforeBrace = breakToExpr)
throw AssertionError(carry)
}

override fun visitClassOrObject(classOrObject: KtClassOrObject) {
Expand Down
12 changes: 12 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5321,6 +5321,7 @@ class FormatterTest {
.trimMargin(),
deduceMaxWidth = true)

//
@Test
fun `assignment of a scoping function`() =
assertFormatted(
Expand All @@ -5341,13 +5342,24 @@ class FormatterTest {
| //
|}
|
|fun foo() = scope label@{
| foo()
| //
|}
|
|fun foo() =
| coroutineScope { x ->
| foo()
| //
| }
|
|fun foo() =
| coroutineScope label@{
| foo()
| //
| }
|
|fun foo() =
| Runnable @Px {
| foo()
| //
Expand Down

0 comments on commit 77f7514

Please sign in to comment.