Skip to content

Commit

Permalink
Fix crash when optional semicolon is used in a long single-line lambda
Browse files Browse the repository at this point in the history
Summary:
Whenever a lambda:
1. Has a single statement
2. Can't be collapsed due to length
3. Uses an optional semicolon

It fails with:
```
com.google.googlejavaformat.FormattingError: 16:5: error: expected token: ';'; generated } instead
```

This fixes that by slightly reworking how statements are visited.

Reviewed By: hick209

Differential Revision: D32708821

fbshipit-source-id: d3f84dbfdea9e17c1e3919b4918e8f6c09cb6ade
  • Loading branch information
davidtorosyan authored and facebook-github-bot committed Nov 30, 2021
1 parent 187551e commit 582f0f1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,11 @@ open class KotlinInputAstVisitorBase(
}
}

private fun visitStatement(statement: PsiElement) {
builder.block(ZERO) { statement.accept(this) }
builder.guessToken(";")
}

private fun visitStatements(statements: Array<PsiElement>) {
var first = true
builder.guessToken(";")
Expand All @@ -401,8 +406,7 @@ open class KotlinInputAstVisitorBase(
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
}
first = false
builder.block(ZERO) { statement.accept(this) }
builder.guessToken(";")
visitStatement(statement)
}
}

Expand Down Expand Up @@ -831,7 +835,7 @@ open class KotlinInputAstVisitorBase(
if (statements.size == 1 &&
statements.first() !is KtReturnExpression &&
lambdaExpression.bodyExpression?.startsWithComment() != true) {
statements[0].accept(this)
visitStatement(statements[0])
} else {
visitStatements(statements)
}
Expand Down
6 changes: 6 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3073,6 +3073,9 @@ class FormatterKtTest {
| when {
| true -> "1"; false -> "0"
| }
| someLongVariableName.let {
| someReallyLongFunctionNameThatMakesThisNotFitInOneLineWithTheAboveVariable();
| }
|} ;
|
|""".trimMargin()
Expand All @@ -3097,6 +3100,9 @@ class FormatterKtTest {
| true -> "1"
| false -> "0"
| }
| someLongVariableName.let {
| someReallyLongFunctionNameThatMakesThisNotFitInOneLineWithTheAboveVariable()
| }
|}
|""".trimMargin()
assertThatFormatting(code).isEqualTo(expected)
Expand Down

0 comments on commit 582f0f1

Please sign in to comment.