Skip to content

Commit

Permalink
Allow comment before parameter list in function literal (`function-li…
Browse files Browse the repository at this point in the history
…teral`) (#2894)

Merging an EOL comment before the parameter list with the actual parameter list results in code that no longer compiles.

Closes #2850
  • Loading branch information
paul-dingemans authored Dec 3, 2024
1 parent 5cb8c49 commit f4cb520
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe
import com.pinterest.ktlint.ruleset.standard.StandardRule
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.psi.psiUtil.siblings

private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()

Expand Down Expand Up @@ -343,8 +344,8 @@ public class FunctionLiteralRule :
) {
require(parameterList.elementType == VALUE_PARAMETER_LIST)
parameterList
.prevSibling { it.isWhiteSpace() }
?.takeIf { it.isWhiteSpaceWithNewline() }
.takeUnless { it.isPrecededByComment() }
?.prevSibling { it.isWhiteSpaceWithNewline() }
?.let { whitespaceBeforeParameterList ->
emit(parameterList.startOffset, "No newline expected before parameter", true)
.ifAutocorrectAllowed {
Expand All @@ -362,6 +363,8 @@ public class FunctionLiteralRule :
}
}

private fun ASTNode.isPrecededByComment() = siblings(forward = false).any { it.isPartOfComment() }

private fun visitArrow(
arrow: ASTNode,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> AutocorrectDecision,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,4 +597,30 @@ class FunctionLiteralRuleTest {
LintViolation(4, 7, "Arrow is redundant when parameter list is empty"),
).isFormattedAs(formattedCode)
}

@Test
fun `Issue 2850 - Given function literal with a comment before the parameter list which contains a redundant parameter then do remove the redundant parameter but keep the comment`() {
val code =
"""
val foo1 =
{
// some comment
foo: String -> "foo = " + foo
}
val foo2 =
{ // some comment
foo: String -> "foo = " + foo
}
val foo3 =
{
/* some comment */
foo: String -> "foo = " + foo
}
val foo4 =
{ /* some comment */
foo: String -> "foo = " + foo
}
""".trimIndent()
functionLiteralRuleAssertThat(code).hasNoLintViolations()
}
}

0 comments on commit f4cb520

Please # to comment.