Skip to content

Commit

Permalink
Fixed StatelessClassesRule (#1741)
Browse files Browse the repository at this point in the history
- removed usage of copyElement
- reused ASTFactory
  • Loading branch information
nulls authored Sep 21, 2023
1 parent dd5542b commit 2e563f2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import org.jetbrains.kotlin.KtNodeTypes.FUN
import org.jetbrains.kotlin.KtNodeTypes.OBJECT_DECLARATION
import org.jetbrains.kotlin.KtNodeTypes.SUPER_TYPE_ENTRY
import org.jetbrains.kotlin.KtNodeTypes.SUPER_TYPE_LIST
import org.jetbrains.kotlin.com.intellij.lang.ASTFactory
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.CompositeElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.lexer.KtTokens.CLASS_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.IDENTIFIER
import org.jetbrains.kotlin.lexer.KtTokens.INTERFACE_KEYWORD
Expand Down Expand Up @@ -50,14 +49,16 @@ class StatelessClassesRule(configRules: List<RulesConfig>) : DiktatRule(
if (isClassExtendsValidInterface(node, interfaces) && isStatelessClass(node)) {
OBJECT_IS_PREFERRED.warnAndFix(configRules, emitWarn, isFixMode,
"class ${(node.psi as KtClass).name!!}", node.startOffset, node) {
val newObjectNode = CompositeElement(OBJECT_DECLARATION)
val newObjectNode = ASTFactory.composite(OBJECT_DECLARATION)
val children = node.children().toList()
node.treeParent.addChild(newObjectNode, node)
node.children().forEach {
newObjectNode.addChild(it.copyElement(), null)
children.forEach {
if (it.elementType == CLASS_KEYWORD) {
newObjectNode.addChild(ASTFactory.leaf(OBJECT_KEYWORD, "object"))
} else {
newObjectNode.addChild(it)
}
}
newObjectNode.addChild(LeafPsiElement(OBJECT_KEYWORD, "object"),
newObjectNode.getFirstChildWithType(CLASS_KEYWORD))
newObjectNode.removeChild(newObjectNode.getFirstChildWithType(CLASS_KEYWORD)!!)
node.treeParent.removeChild(node)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import com.saveourtool.diktat.ruleset.rules.chapter6.classes.StatelessClassesRul
import com.saveourtool.diktat.util.FixTestBase

import generated.WarningNames.OBJECT_IS_PREFERRED
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test

class StatelessClassesRuleFixTest : FixTestBase("test/chapter6/stateless_classes", ::StatelessClassesRule) {
@Test
@Tag(OBJECT_IS_PREFERRED)
@Disabled("https://github.com/saveourtool/diktat/issues/1737")
fun `fix class to object keyword`() {
fixAndCompare("StatelessClassExpected.kt", "StatelessClassTest.kt")
}
Expand Down

0 comments on commit 2e563f2

Please sign in to comment.