Skip to content

Commit

Permalink
Ignore reference expressions in chain-method-continuation (pinteres…
Browse files Browse the repository at this point in the history
…t#2569)

Simple reference expressions like properties and enum values should be ignored by this rule as they are no method calls.

Closes pinterest#2455
  • Loading branch information
paul-dingemans authored Feb 27, 2024
1 parent 773fd1d commit befa71d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ public class ChainMethodContinuationRule :
chainedExpression
.chainOperators
.filterNot { it.isJavaClassReferenceExpression() }
.filterNot { it.isSimpleReferenceExpression() }
.forEach { chainOperator ->
when {
chainOperator.shouldBeOnSameLineAsClosingElementOfPreviousExpressionInMethodChain() -> {
Expand All @@ -160,6 +161,11 @@ public class ChainMethodContinuationRule :
nextCodeSibling()?.elementType == REFERENCE_EXPRESSION &&
nextCodeSibling()?.firstChildLeafOrSelf()?.text == "java"

private fun ASTNode.isSimpleReferenceExpression() =
treeParent.elementType == DOT_QUALIFIED_EXPRESSION &&
prevCodeSibling()?.elementType == REFERENCE_EXPRESSION &&
nextCodeSibling()?.elementType == REFERENCE_EXPRESSION

private fun ChainedExpression.wrapBeforeChainOperator() =
when {
hasNewlineBetweenFirstAndLastChainOperator -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1011,4 +1011,31 @@ class ChainMethodContinuationRuleTest {
LintViolation(6, 46, "Exceeded max line length (45)", false),
).hasNoLintViolationsExceptInAdditionalRules()
}

@Test
fun `Issue 2455 - Given a chained method including some simple reference expressions then do not wrap simple reference expressions`() {
val code =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
fun buildBar(): Foo.Bar = Foo.Bar.builder().baz().baz.build()
""".trimIndent()
val formattedCode =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
fun buildBar(): Foo.Bar = Foo.Bar
.builder()
.baz()
.baz
.build()
""".trimIndent()
chainMethodContinuationRuleAssertThat(code)
.setMaxLineLength()
.addAdditionalRuleProvider { MaxLineLengthRule() }
.hasLintViolations(
LintViolation(2, 34, "Expected newline before '.'"),
LintViolation(2, 44, "Expected newline before '.'"),
LintViolation(2, 50, "Expected newline before '.'"),
LintViolation(2, 54, "Expected newline before '.'"),
).isFormattedAs(formattedCode)
}
}

0 comments on commit befa71d

Please sign in to comment.