Skip to content

Commit

Permalink
Emit a parsing error for calls with multiple trailing lambdas
Browse files Browse the repository at this point in the history
  • Loading branch information
nreid260 committed Apr 15, 2024
1 parent 6a639f0 commit 02ddc07
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -771,13 +771,17 @@ class KotlinInputAstVisitor(
}
}
}
if (lambdaArguments.isNotEmpty()) {
builder.space()
visitArgumentInternal(
lambdaArguments.single(),
wrapInBlock = false,
brokeBeforeBrace = brokeBeforeBrace,
)
when (lambdaArguments.size) {
0 -> {}
1 -> {
builder.space()
visitArgumentInternal(
lambdaArguments.single(),
wrapInBlock = false,
brokeBeforeBrace = brokeBeforeBrace,
)
}
else -> throw ParseError("Maximum one trailing lambda is allowed", lambdaArguments[1])
}
}
}
Expand Down
22 changes: 20 additions & 2 deletions core/src/main/java/com/facebook/ktfmt/format/ParseError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,25 @@
package com.facebook.ktfmt.format

import org.jetbrains.kotlin.com.intellij.openapi.util.text.LineColumn
import org.jetbrains.kotlin.com.intellij.psi.PsiElement

class ParseError(val errorDescription: String, val lineColumn: LineColumn) :
IllegalArgumentException(
"${lineColumn.line + 1}:${lineColumn.column + 1}: error: $errorDescription")
IllegalArgumentException(
"${lineColumn.line + 1}:${lineColumn.column + 1}: error: $errorDescription"
) {

constructor(
errorDescription: String,
element: PsiElement,
) : this(errorDescription, positionOf(element))

companion object {
private fun positionOf(element: PsiElement): LineColumn {
val doc = element.containingFile.viewProvider.document
val offset = element.textOffset
val lineZero = doc.getLineNumber(offset)
val colZero = offset - doc.getLineStartOffset(lineZero)
return LineColumn.of(lineZero, colZero)
}
}
}
12 changes: 12 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/cli/MainTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ class MainTest {
assertThat(err.toString(testCharset)).contains("foo.kt:1:14: error: ")
}

@Test
fun `Parsing error for multiple trailing lambdas`() {
val fooBar = root.resolve("foo.kt")
fooBar.writeText("val x = foo(bar { } { zap = 2 })")
val returnValue =
Main(emptyInput, PrintStream(out), PrintStream(err), arrayOf(fooBar.toString())).run()

assertThat(returnValue).isEqualTo(1)
assertThat(err.toString(testCharset))
.contains("foo.kt:1:21: error: Maximum one trailing lambda is allowed")
}

@Test
fun `all files in args are processed, even if one of them has an error`() {
val file1 = root.resolve("file1.kt")
Expand Down

0 comments on commit 02ddc07

Please sign in to comment.