Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New rule for complex expression #680

Merged
merged 14 commits into from
Jan 15, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions diktat-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@
enabled: true
configuration:
maxParametersInOneLine: 2
- name: COMPLEX_EXPRESSION
enabled: true
- name: TOO_MANY_CONSECUTIVE_SPACES
enabled: true
configuration:
Expand Down
2 changes: 2 additions & 0 deletions diktat-rules/src/main/kotlin/generated/WarningNames.kt
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ public object WarningNames {

public const val WRONG_NEWLINES: String = "WRONG_NEWLINES"

public const val COMPLEX_EXPRESSION: String = "COMPLEX_EXPRESSION"

public const val STRING_CONCATENATION: String = "STRING_CONCATENATION"

public const val TOO_MANY_BLANK_LINES: String = "TOO_MANY_BLANK_LINES"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ enum class Warnings(
LONG_LINE(true, "3.5.1", "this line is longer than allowed"),
REDUNDANT_SEMICOLON(true, "3.6.2", "there should be no redundant semicolon at the end of lines"),
WRONG_NEWLINES(true, "3.6.2", "incorrect line breaking"),
COMPLEX_EXPRESSION(false, "3.6.3", "complex dot qualified expression can be replace with variable"),
kentr0w marked this conversation as resolved.
Show resolved Hide resolved

// FixMe: autofixing will be added for this rule
STRING_CONCATENATION(false, "3.15.1", "strings should not be concatenated using plus operator - use string templates instead if the statement fits one line"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.ListOfList
import org.cqfn.diktat.ruleset.constants.Warnings.REDUNDANT_SEMICOLON
import org.cqfn.diktat.ruleset.constants.Warnings.WRONG_NEWLINES
import org.cqfn.diktat.ruleset.constants.Warnings.COMPLEX_EXPRESSION
import org.cqfn.diktat.ruleset.utils.*

import com.pinterest.ktlint.core.Rule
Expand All @@ -18,10 +19,10 @@ import com.pinterest.ktlint.core.ast.ElementType.BLOCK_COMMENT
import com.pinterest.ktlint.core.ast.ElementType.CALLABLE_REFERENCE_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.CALL_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.CLASS
import com.pinterest.ktlint.core.ast.ElementType.CLASS_BODY
import com.pinterest.ktlint.core.ast.ElementType.COLON
import com.pinterest.ktlint.core.ast.ElementType.COLONCOLON
import com.pinterest.ktlint.core.ast.ElementType.COMMA
import com.pinterest.ktlint.core.ast.ElementType.CONDITION
import com.pinterest.ktlint.core.ast.ElementType.DIV
import com.pinterest.ktlint.core.ast.ElementType.DIVEQ
import com.pinterest.ktlint.core.ast.ElementType.DOT
Expand Down Expand Up @@ -51,19 +52,19 @@ import com.pinterest.ktlint.core.ast.ElementType.PLUS
import com.pinterest.ktlint.core.ast.ElementType.PLUSEQ
import com.pinterest.ktlint.core.ast.ElementType.POSTFIX_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.PRIMARY_CONSTRUCTOR
import com.pinterest.ktlint.core.ast.ElementType.RBRACE
import com.pinterest.ktlint.core.ast.ElementType.RETURN
import com.pinterest.ktlint.core.ast.ElementType.RETURN_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.SAFE_ACCESS
import com.pinterest.ktlint.core.ast.ElementType.SAFE_ACCESS_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.SECONDARY_CONSTRUCTOR
import com.pinterest.ktlint.core.ast.ElementType.SEMICOLON
import com.pinterest.ktlint.core.ast.ElementType.SUPER_TYPE_LIST
import com.pinterest.ktlint.core.ast.ElementType.VALUE_ARGUMENT
import com.pinterest.ktlint.core.ast.ElementType.VALUE_ARGUMENT_LIST
import com.pinterest.ktlint.core.ast.ElementType.VALUE_PARAMETER
import com.pinterest.ktlint.core.ast.ElementType.VALUE_PARAMETER_LIST
import com.pinterest.ktlint.core.ast.ElementType.WHEN
import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE
import com.pinterest.ktlint.core.ast.isWhiteSpace
import com.pinterest.ktlint.core.ast.isWhiteSpaceWithNewline
import com.pinterest.ktlint.core.ast.nextCodeSibling
import com.pinterest.ktlint.core.ast.parent
Expand Down Expand Up @@ -92,6 +93,7 @@ import org.jetbrains.kotlin.psi.psiUtil.siblings
* 7. Ensures that in multiline lambda newline follows arrow or, in case of lambda without explicit parameters, opening brace
* 8. Checks that functions with single `return` are simplified to functions with expression body
* 9. parameter or argument lists and supertype lists that have more than 2 elements should be separated by newlines
* 10. Complex expression inside condition replaced with new variable
*/
@Suppress("ForbiddenComment")
class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines") {
Expand Down Expand Up @@ -162,6 +164,9 @@ class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines"
val isIncorrect = (if (node.elementType == ELVIS) node.treeParent else node).run {
if (isCallsChain()) {
val isSingleLineIfElse = parent({ it.elementType == IF }, true)?.isSingleLineIfElse() ?: false
if (node.isInBrackets()) {
COMPLEX_EXPRESSION.warn(configRules, emitWarn, isFixMode, node.text, node.startOffset, node)
}
// to follow functional style these operators should be started by newline
(isFollowedByNewline() || !isBeginByNewline()) && !isSingleLineIfElse &&
(!isFirstCall() || !isMultilineLambda(treeParent))
Expand Down Expand Up @@ -375,11 +380,11 @@ class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines"
if (psi.children.isNotEmpty() && (!psi.isFirstChildElementType(DOT_QUALIFIED_EXPRESSION) &&
!psi.isFirstChildElementType(SAFE_ACCESS_EXPRESSION))) {
val firstChild = psi.firstChild
if (firstChild.isFirstChildElementType(DOT_QUALIFIED_EXPRESSION) ||
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
firstChild.isFirstChildElementType(SAFE_ACCESS_EXPRESSION)) {
getOrderedCallExpressions(firstChild.firstChild, result)
}
if (firstChild.isFirstChildElementType(POSTFIX_EXPRESSION)) {
if (firstChild.isFirstChildElementType(DOT_QUALIFIED_EXPRESSION) ||
firstChild.isFirstChildElementType(SAFE_ACCESS_EXPRESSION)) {
getOrderedCallExpressions(firstChild.firstChild, result)
}
result.add(firstChild.node)
}
result.add(firstChild.node
Expand Down Expand Up @@ -449,7 +454,7 @@ class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines"
}
}
// fixme: we can't distinguish fully qualified names (like java.lang) from chain of property accesses (like list.size) for now
?.dropWhile { !it.treeParent.textContains('(') && !it.treeParent.textContains('{') }
//?.dropWhile { !it.treeParent.textContains('(') && !it.treeParent.textContains('{') }
kentr0w marked this conversation as resolved.
Show resolved Hide resolved

private fun List<ASTNode>.isNotValidCalls(node: ASTNode): Boolean {
if (this.size == 1) {
Expand Down Expand Up @@ -504,6 +509,16 @@ class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines"
firstChildNode.elementType == IDENTIFIER &&
treeParent.elementType == BINARY_EXPRESSION

/**
* This method checks that complex expression should be replace with new variable
*/
private fun ASTNode.isInBrackets() =
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
parent({it.elementType == DOT_QUALIFIED_EXPRESSION || it.elementType == SAFE_ACCESS_EXPRESSION})
?.treeParent
?.elementType
?.let { it in bracketsTypes }
?: false

/**
* [RuleConfiguration] for newlines placement
*/
Expand All @@ -527,5 +542,6 @@ class NewlinesRule(private val configRules: List<RulesConfig>) : Rule("newlines"
private val expressionTypes = TokenSet.create(DOT_QUALIFIED_EXPRESSION, SAFE_ACCESS_EXPRESSION, CALLABLE_REFERENCE_EXPRESSION, BINARY_EXPRESSION)
private val chainExpressionTypes = TokenSet.create(DOT_QUALIFIED_EXPRESSION, SAFE_ACCESS_EXPRESSION)
private val dropChainValues = TokenSet.create(EOL_COMMENT, WHITE_SPACE, BLOCK_COMMENT, KDOC)
private val bracketsTypes = TokenSet.create(CONDITION, WHEN ,VALUE_ARGUMENT)
}
}
2 changes: 2 additions & 0 deletions diktat-rules/src/main/resources/diktat-analysis-huawei.yml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@
enabled: true
configuration:
maxParametersInOneLine: 2
- name: COMPLEX_EXPRESSION
enabled: true
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
- name: TOO_MANY_CONSECUTIVE_SPACES
enabled: true
configuration:
Expand Down
2 changes: 2 additions & 0 deletions diktat-rules/src/main/resources/diktat-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@
enabled: true
configuration:
maxParametersInOneLine: 2
- name: COMPLEX_EXPRESSION
enabled: true
- name: TOO_MANY_CONSECUTIVE_SPACES
enabled: true
configuration:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.cqfn.diktat.ruleset.chapter3.files

import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.ruleset.constants.Warnings.COMPLEX_EXPRESSION
import org.cqfn.diktat.ruleset.constants.Warnings.REDUNDANT_SEMICOLON
import org.cqfn.diktat.ruleset.constants.Warnings.WRONG_NEWLINES
import org.cqfn.diktat.ruleset.rules.DIKTAT_RULE_SET_ID
Expand All @@ -11,6 +12,7 @@ import com.pinterest.ktlint.core.LintError
import generated.WarningNames
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Tags
import org.junit.jupiter.api.Test

@Suppress("LargeClass")
Expand Down Expand Up @@ -955,4 +957,28 @@ class NewlinesRuleWarnTest : LintTestBase(::NewlinesRule) {
rulesConfigList = rulesConfigListShort
)
}

@Test
@Tags(Tag(WarningNames.WRONG_NEWLINES), Tag(WarningNames.COMPLEX_EXPRESSION))
fun `complex expression in condition`() {
lintMethod(
"""
|fun foo() {
| if(a.b.c) {}
| while(a?.b?.c) {}
| when(a.b!!.c) {}
| goo(a?.b.c)
|}
""".trimMargin(),
LintError(2, 10, ruleId, "${COMPLEX_EXPRESSION.warnText()} .", false),
LintError(2, 10, ruleId, "$functionalStyleWarn .", true),
LintError(3, 14, ruleId, "${COMPLEX_EXPRESSION.warnText()} ?.", false),
LintError(3, 14, ruleId, "$functionalStyleWarn ?.", true),
LintError(4, 14, ruleId, "${COMPLEX_EXPRESSION.warnText()} .", false),
LintError(4, 14, ruleId, "$functionalStyleWarn .", true),
LintError(5, 12, ruleId, "${COMPLEX_EXPRESSION.warnText()} .", false),
LintError(5, 12, ruleId, "$functionalStyleWarn .", true),
rulesConfigList = rulesConfigListShort
)
}
}
1 change: 1 addition & 0 deletions info/available-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
| 3 | 3.5.1 | LONG_LINE | Check: warns if length doesn't exceed the specified length | no | lineLength | handle json method in KDoc |
| 3 | 3.6.2 | REDUNDANT_SEMICOLON | Check: warns if semicolons are used at the end of line.<br>Fix: removes semicolon. | yes | no | - |
| 3 | 3.6.2 | WRONG_NEWLINES | Check: warns if line breaks do not follow code style guid.<br>Fix: fixes incorrect line breaks. | yes | no | - |
| 3 | 3.6.2 | COMPLEX_EXPRESSION | Check: warns if long dot expression using in condition or as arguments | no | no | - |
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
| 3 | 3.15.1 | STRING_CONCATENATION | Check: warns if in a single line concatenation of strings is used | yes | no | - |
| 3 | 3.7.1 | TOO_MANY_BLANK_LINES | Check: warns if blank lines are used placed incorrectly.<br>Fix: removes redundant blank lines. | yes | no | |
| 3 | 3.8.1 | WRONG_WHITESPACE | Check: warns if usage of horizontal spaces violates code style guide.<br>Fix: fixes incorrect whitespaces. | yes | no | - |
Expand Down
13 changes: 13 additions & 0 deletions info/guide/guide-chapter-3.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,19 @@ Note that all comparison operators, such as `==`, `>`, `<`, should not be split.
```kotlin
if (condition) list.map { foo(it) }.filter { bar(it) } else list.drop(1)
```

**Note:** If dot qualified expression is inside condition or passed as an argument - replace with new vatiable
kentr0w marked this conversation as resolved.
Show resolved Hide resolved

**Invalid example**:
```kotlin
if (node.text.length.dec() != 0) {}
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
```

**Valid example**:
```kotlin
val nodeLen = node.text.length.dec()
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
if (nodeLen != 0) {}
```

2) Newlines should be placed after the assignment operator (`=`).
3) In function or class declarations, the name of a function or constructor should not be split by a newline from the opening brace `(`.
Expand Down