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

CUSTOM_GETTERS_SETTERS false positive when a property has a backing field #1815

Merged
merged 5 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import com.saveourtool.diktat.ruleset.rules.DiktatRule
import com.saveourtool.diktat.ruleset.utils.*

import org.jetbrains.kotlin.KtNodeTypes.MODIFIER_LIST
import org.jetbrains.kotlin.KtNodeTypes.PROPERTY
import org.jetbrains.kotlin.KtNodeTypes.PROPERTY_ACCESSOR
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.lexer.KtTokens.GET_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.IDENTIFIER
import org.jetbrains.kotlin.lexer.KtTokens.OVERRIDE_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.PRIVATE_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.SET_KEYWORD
Expand All @@ -33,6 +35,21 @@ class CustomGetterSetterRule(configRules: List<RulesConfig>) : DiktatRule(
val isPrivateSetter = node.getFirstChildWithType(MODIFIER_LIST)?.hasAnyChildOfTypes(PRIVATE_KEYWORD) ?: false
val isOverrideGetter = node.treeParent.getFirstChildWithType(MODIFIER_LIST)?.hasAnyChildOfTypes(OVERRIDE_KEYWORD) ?: false

// find matching node
val propertyList = node.treeParent?.treeParent?.getAllChildrenWithType(PROPERTY)
val nodeName = node.treeParent?.getFirstChildWithType(IDENTIFIER)
nodeName?.let {
propertyList
?.forEach { propertyNode ->
val matchingNode = propertyNode.getFirstChildWithType(IDENTIFIER)
matchingNode?.let {
if (matchingNode.isCorrectBackingField(nodeName)) {
return
}
}
}
}

setter?.let {
// only private custom setters are allowed
if (!isPrivateSetter) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,38 @@ fun ASTNode.visit(visitor: AstNodeVisitor<Unit>) {
fun PsiElement.isLongStringTemplateEntry(): Boolean =
node.elementType == LONG_STRING_TEMPLATE_ENTRY

/**
* Checks that identifier is correct backing field
*
* @return true if the function is correct backing field
*/
internal fun ASTNode.isCorrectBackingField(variableName: ASTNode): Boolean {
val propertyNodes = this.treeParent.getAllChildrenWithType(KtNodeTypes.PROPERTY)
val variableNameCut = variableName.text.drop(1)
// check that backing field name is correct

if (variableName.text.startsWith("_") && variableNameCut.isLowerCamelCase()) {
val matchingNode = propertyNodes.find { propertyNode ->
val nodeType = this.getFirstChildWithType(KtNodeTypes.TYPE_REFERENCE)
val propertyType = propertyNode.getFirstChildWithType(KtNodeTypes.TYPE_REFERENCE)
// check that property and backing field has same type
val sameType = propertyType?.text == nodeType?.text
// check that property USER_TYPE is same as backing field NULLABLE_TYPE
val nodeNullableType = nodeType?.getFirstChildWithType(KtNodeTypes.NULLABLE_TYPE)
val sameTypeWithNullable = propertyType?.getFirstChildWithType(KtNodeTypes.USER_TYPE)?.text ==
nodeNullableType?.getFirstChildWithType(KtNodeTypes.USER_TYPE)?.text
val matchingNames = propertyNode.getFirstChildWithType(IDENTIFIER)?.text == variableNameCut
val isPrivate = this.getFirstChildWithType(MODIFIER_LIST)?.getFirstChildWithType(PRIVATE_KEYWORD) != null

matchingNames && (sameType || sameTypeWithNullable) && isPrivate &&
this.getFirstChildWithType(KtNodeTypes.PROPERTY_ACCESSOR) == null &&
propertyNode.getFirstChildWithType(KtNodeTypes.PROPERTY_ACCESSOR) != null
}
return matchingNode?.let { true } ?: false
}
return false
}

private fun ASTNode.isFollowedByNewlineCheck() =
this.treeNext.elementType == WHITE_SPACE && this.treeNext.text.contains("\n")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,64 @@ class CustomGetterSetterWarnTest : LintTestBase(::CustomGetterSetterRule) {
DiktatError(7, 9, ruleId, "${Warnings.CUSTOM_GETTERS_SETTERS.warnText()} get"),
)
}

@Test
@Tag(CUSTOM_GETTERS_SETTERS)
fun `should not trigger on property with backing field`() {
lintMethod(
"""
|package com.example
|
|class MutableTableContainer {
| private var _table: Map<String, Int>? = null
|
| val table: Map<String, Int>
| get() {
| if (_table == null) {
| _table = hashMapOf()
| }
| return _table ?: throw AssertionError("Set to null by another thread")
| }
| set(value) {
| field = value
| }
|
|}
""".trimMargin(),
)
}

@Test
@Tag(CUSTOM_GETTERS_SETTERS)
fun `should trigger on backing field with setter`() {
val code =
"""
|package com.example
|
|class MutableTableContainer {
| var _table: Map<String, Int>? = null
| set(value) {
| field = value
| }
|
| val table: Map<String, Int>
| get() {
| if (_table == null) {
| _table = hashMapOf()
| }
| return _table ?: throw AssertionError("Set to null by another thread")
| }
| set(value) {
| field = value
| }
|
|}
""".trimMargin()
lintMethod(code,
DiktatError(5, 17, ruleId, "${Warnings.CUSTOM_GETTERS_SETTERS.warnText()} set", false),
DiktatError(10, 8, ruleId, "${Warnings.CUSTOM_GETTERS_SETTERS.warnText()} get", false),
DiktatError(16, 8, ruleId, "${Warnings.CUSTOM_GETTERS_SETTERS.warnText()} set", false)
)
}
}