Skip to content

Commit

Permalink
Merge branch 'bugfix/newline_for_return_type' of github.com:cqfn/diKT…
Browse files Browse the repository at this point in the history
…at into bugfix/newline_for_return_type
  • Loading branch information
kgevorkyan committed Nov 16, 2021
2 parents fe6b93f + 77e48c3 commit aa2719a
Show file tree
Hide file tree
Showing 85 changed files with 411 additions and 202 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ class DiktatRuleSetProvider(private var diktatConfigFile: String = DIKTAT_ANALYS
@Suppress(
"LongMethod",
"TOO_LONG_FUNCTION",
"SpreadOperator")
"SpreadOperator"
)
override fun get(): RuleSet {
log.debug("Will run $DIKTAT_RULE_SET_ID with $diktatConfigFile" +
" (it can be placed to the run directory or the default file from resources will be used)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import java.io.File
class FileNaming(configRules: List<RulesConfig>) : DiktatRule(
"file-naming",
configRules,
listOf(FILE_NAME_INCORRECT, FILE_NAME_MATCH_CLASS)) {
listOf(FILE_NAME_INCORRECT, FILE_NAME_MATCH_CLASS)
) {
private lateinit var filePath: String

override fun logic(node: ASTNode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ class IdentifierNaming(configRules: List<RulesConfig>) : DiktatRule(
listOf(BACKTICKS_PROHIBITED, VARIABLE_NAME_INCORRECT, VARIABLE_NAME_INCORRECT_FORMAT, CONSTANT_UPPERCASE,
VARIABLE_HAS_PREFIX, CONFUSING_IDENTIFIER_NAMING, GENERIC_NAME, CLASS_NAME_INCORRECT,
ENUM_VALUE, EXCEPTION_SUFFIX, FUNCTION_BOOLEAN_PREFIX, FUNCTION_NAME_INCORRECT_CASE,
IDENTIFIER_LENGTH, OBJECT_NAME_INCORRECT, TYPEALIAS_NAME_INCORRECT_CASE)) {
IDENTIFIER_LENGTH, OBJECT_NAME_INCORRECT, TYPEALIAS_NAME_INCORRECT_CASE)
) {
private val allMethodPrefixes by lazy {
if (configuration.allowedBooleanPrefixes.isEmpty()) {
booleanMethodPrefixes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ class PackageNaming(configRules: List<RulesConfig>) : DiktatRule(
"package-naming",
configRules,
listOf(INCORRECT_PACKAGE_SEPARATOR, PACKAGE_NAME_INCORRECT_CASE, PACKAGE_NAME_MISSING,
PACKAGE_NAME_INCORRECT_PATH, PACKAGE_NAME_INCORRECT_PREFIX, PACKAGE_NAME_INCORRECT_SYMBOLS)) {
PACKAGE_NAME_INCORRECT_PATH, PACKAGE_NAME_INCORRECT_PREFIX, PACKAGE_NAME_INCORRECT_SYMBOLS)
) {
private lateinit var domainName: String

override fun logic(node: ASTNode) {
Expand Down Expand Up @@ -89,7 +90,8 @@ class PackageNaming(configRules: List<RulesConfig>) : DiktatRule(
private fun warnAndFixMissingPackageName(
initialPackageDirectiveNode: ASTNode,
realPackageName: List<String>,
filePath: String) {
filePath: String
) {
val fileName = filePath.substringAfterLast(File.separator)

// if the file path contains "buildSrc" - don't add the package name to the file
Expand Down Expand Up @@ -262,7 +264,8 @@ class PackageNaming(configRules: List<RulesConfig>) : DiktatRule(
*/
private fun checkFilePathMatchesWithPackageName(packageNameParts: List<ASTNode>,
realNameParts: List<String>,
packageDirective: ASTNode) {
packageDirective: ASTNode
) {
if (realNameParts.isNotEmpty() && packageNameParts.map { node -> node.text } != realNameParts) {
val realPackageNameStr = realNameParts.joinToString(PACKAGE_SEPARATOR)
val offset = packageNameParts[0].startOffset
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import org.slf4j.LoggerFactory
class CommentsRule(configRules: List<RulesConfig>) : DiktatRule(
"comments",
configRules,
listOf(COMMENTED_OUT_CODE)) {
listOf(COMMENTED_OUT_CODE)
) {
private lateinit var ktPsiFactory: KtPsiFactory

override fun logic(node: ASTNode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ class HeaderCommentRule(configRules: List<RulesConfig>) : DiktatRule(
"header-comment",
configRules,
listOf(HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE, HEADER_MISSING_OR_WRONG_COPYRIGHT, HEADER_NOT_BEFORE_PACKAGE,
HEADER_NOT_BEFORE_PACKAGE, HEADER_WRONG_FORMAT, WRONG_COPYRIGHT_YEAR)) {
HEADER_NOT_BEFORE_PACKAGE, HEADER_WRONG_FORMAT, WRONG_COPYRIGHT_YEAR)
) {
override fun logic(node: ASTNode) {
if (node.elementType == FILE && !node.getFilePath().isGradleScript()) {
checkCopyright(node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ class CommentsFormatting(configRules: List<RulesConfig>) : DiktatRule(
"kdoc-comments-codeblocks-formatting",
configRules,
listOf(COMMENT_WHITE_SPACE, FIRST_COMMENT_NO_BLANK_LINE,
IF_ELSE_COMMENTS, WRONG_NEWLINES_AROUND_KDOC)) {
IF_ELSE_COMMENTS, WRONG_NEWLINES_AROUND_KDOC)
) {
/**
* @param node
*/
Expand Down Expand Up @@ -143,7 +144,8 @@ class CommentsFormatting(configRules: List<RulesConfig>) : DiktatRule(
elseBlock: ASTNode,
elseKeyWord: ASTNode,
comment: ASTNode,
copyComment: ASTNode?) {
copyComment: ASTNode?
) {
if (elseBlock.hasChildOfType(BLOCK)) {
val elseCodeBlock = elseBlock.getFirstChildWithType(BLOCK)!!
elseCodeBlock.addChild(copyComment!!,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ import com.pinterest.ktlint.core.ast.ElementType.VAL_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.VAR_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE
import com.pinterest.ktlint.core.ast.parent
import com.pinterest.ktlint.core.ast.prevSibling
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.siblings

/**
* This rule checks the following features in KDocs:
Expand All @@ -50,12 +52,14 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
"kdoc-comments",
configRules,
listOf(KDOC_EXTRA_PROPERTY, KDOC_NO_CONSTRUCTOR_PROPERTY,
KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT, MISSING_KDOC_CLASS_ELEMENTS, MISSING_KDOC_TOP_LEVEL)) {
KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT, MISSING_KDOC_CLASS_ELEMENTS, MISSING_KDOC_TOP_LEVEL)
) {
private val config by lazy { configRules.getCommonConfiguration() }

/**
* @param node
*/
override fun logic(node: ASTNode) {
val config = configRules.getCommonConfiguration()
val filePath = node.getFilePath()
if (!node.hasTestAnnotation() && !isLocatedInTest(filePath.splitPathToDirs(), config.testAnchors)) {
when (node.elementType) {
Expand Down Expand Up @@ -86,34 +90,36 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
}

@Suppress("UnsafeCallOnNullableType", "ComplexMethod")
private fun checkValueParameter(node: ASTNode) {
if (node.parents().none { it.elementType == PRIMARY_CONSTRUCTOR } ||
!node.hasChildOfType(VAL_KEYWORD) && !node.hasChildOfType(VAR_KEYWORD)) {
private fun checkValueParameter(valueParameterNode: ASTNode) {
if (valueParameterNode.parents().none { it.elementType == PRIMARY_CONSTRUCTOR } ||
!valueParameterNode.hasChildOfType(VAL_KEYWORD) &&
!valueParameterNode.hasChildOfType(VAR_KEYWORD)
) {
return
}
val prevComment = if (node.treePrev.elementType == WHITE_SPACE &&
(node.treePrev.treePrev.elementType == EOL_COMMENT ||
node.treePrev.treePrev.elementType == BLOCK_COMMENT)) {
node.treePrev.treePrev
} else if (node.hasChildOfType(KDOC)) {
node.findChildByType(KDOC)!!
} else if (node.treePrev.elementType == BLOCK_COMMENT) {
node.treePrev
val prevComment = if (valueParameterNode.siblings(forward = false)
.takeWhile { it.elementType != EOL_COMMENT && it.elementType != BLOCK_COMMENT }
.all { it.elementType == WHITE_SPACE }
) {
// take previous comment, if it's immediately before `valueParameterNode` or separated only with white space
valueParameterNode.prevSibling { it.elementType == EOL_COMMENT || it.elementType == BLOCK_COMMENT }
} else if (valueParameterNode.hasChildOfType(KDOC)) {
valueParameterNode.findChildByType(KDOC)!!
} else {
null
}
val kdocBeforeClass = node.parent({ it.elementType == CLASS })!!.findChildByType(KDOC)
val kdocBeforeClass = valueParameterNode.parent({ it.elementType == CLASS })!!.findChildByType(KDOC)

prevComment?.let {
kdocBeforeClass?.let {
checkKdocBeforeClass(node, kdocBeforeClass, prevComment)
checkKdocBeforeClass(valueParameterNode, kdocBeforeClass, prevComment)
}
?: createKdocWithProperty(node, prevComment)
?: createKdocWithProperty(valueParameterNode, prevComment)
}
?: kdocBeforeClass?.let {
checkBasicKdocBeforeClass(node, kdocBeforeClass)
checkBasicKdocBeforeClass(valueParameterNode, kdocBeforeClass)
}
?: createKdocBasicKdoc(node)
?: createKdocBasicKdoc(valueParameterNode)
}

@Suppress("UnsafeCallOnNullableType")
Expand All @@ -133,7 +139,8 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
private fun checkKdocBeforeClass(
node: ASTNode,
kdocBeforeClass: ASTNode,
prevComment: ASTNode) {
prevComment: ASTNode
) {
val propertyInClassKdoc = kdocBeforeClass
.kDocTags()
.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
Expand Down Expand Up @@ -170,27 +177,20 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
}

@Suppress("UnsafeCallOnNullableType")
private fun createKdocWithProperty(node: ASTNode, prevComment: ASTNode) {
KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT.warnAndFix(configRules, emitWarn, isFixMode, prevComment.text, prevComment.startOffset, node) {
val classNode = node.parent({ it.elementType == CLASS })!!
private fun createKdocWithProperty(valueParameterNode: ASTNode, prevComment: ASTNode) {
KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT.warnAndFix(configRules, emitWarn, isFixMode, prevComment.text, prevComment.startOffset, valueParameterNode) {
val classNode = valueParameterNode.parent({ it.elementType == CLASS })!!
val newKdocText = if (prevComment.elementType == KDOC) {
prevComment.text
} else if (prevComment.elementType == EOL_COMMENT) {
"/**\n * @property ${node.findChildByType(IDENTIFIER)!!.text} ${prevComment.text.removePrefix("//")}\n */"
"/**\n * @property ${valueParameterNode.findChildByType(IDENTIFIER)!!.text} ${prevComment.text.removePrefix("//")}\n */"
} else {
"/**\n * @property ${node.findChildByType(IDENTIFIER)!!.text}${prevComment.text.removePrefix("/*").removeSuffix("*/")} */"
"/**\n * @property ${valueParameterNode.findChildByType(IDENTIFIER)!!.text}${prevComment.text.removePrefix("/*").removeSuffix("*/")} */"
}
val newKdoc = KotlinParser().createNode(newKdocText).findChildByType(KDOC)!!
classNode.addChild(PsiWhiteSpaceImpl("\n"), classNode.firstChildNode)
classNode.addChild(newKdoc, classNode.firstChildNode)
if (prevComment.elementType == EOL_COMMENT) {
node.treeParent.removeRange(prevComment, node)
} else {
if (prevComment.treeNext.elementType == WHITE_SPACE) {
node.removeChild(prevComment.treeNext)
}
node.removeChild(prevComment)
}
valueParameterNode.removeWithWhiteSpace(prevComment)
}
}

Expand All @@ -200,7 +200,8 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
prevComment: ASTNode,
kdocBeforeClass: ASTNode,
propertyInClassKdoc: ASTNode?,
propertyInLocalKdoc: ASTNode?) {
propertyInLocalKdoc: ASTNode?
) {
val kdocText = if (prevComment.elementType == KDOC) {
prevComment.text.removePrefix("/**").removeSuffix("*/").trim('\n', ' ')
} else {
Expand All @@ -209,17 +210,14 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
// if property is documented with KDoc, which has a property tag inside, then it can contain some additional more complicated
// structure, that will be hard to move automatically
val isFixable = propertyInLocalKdoc == null
KDOC_NO_CONSTRUCTOR_PROPERTY.warnAndFix(configRules, emitWarn, isFixable, prevComment.text, prevComment.startOffset, node, isFixable) {
KDOC_NO_CONSTRUCTOR_PROPERTY.warnAndFix(configRules, emitWarn, isFixMode, prevComment.text, prevComment.startOffset, node, isFixable) {
propertyInClassKdoc?.let {
// local docs should be appended to docs in class
appendKdocTagContent(propertyInClassKdoc, "\n$kdocText")
}
?: insertTextInKdoc(kdocBeforeClass, " * @property ${node.findChildByType(IDENTIFIER)!!.text} ${kdocText.removePrefix("*")}\n")

if (prevComment.treeNext.elementType == WHITE_SPACE) {
node.removeChild(prevComment.treeNext)
}
node.removeChild(prevComment)
node.removeWithWhiteSpace(prevComment)
}
}

Expand All @@ -228,7 +226,8 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
node: ASTNode,
kdocBeforeClass: ASTNode,
prevComment: ASTNode,
propertyInClassKdoc: ASTNode?) {
propertyInClassKdoc: ASTNode?
) {
propertyInClassKdoc?.let {
if (propertyInClassKdoc.hasChildOfType(KDOC_TEXT)) {
val kdocText = propertyInClassKdoc.findChildByType(KDOC_TEXT)!!
Expand All @@ -240,7 +239,7 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
?: run {
insertTextInKdoc(kdocBeforeClass, "* @property ${node.findChildByType(IDENTIFIER)!!.text} ${prevComment.text.removeRange(0, 2)}\n")
}
node.treeParent.removeRange(prevComment, node)
node.treeParent.removeChildMergingSurroundingWhitespaces(prevComment)
}

@Suppress("UnsafeCallOnNullableType")
Expand Down Expand Up @@ -330,3 +329,35 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
private val statementsToDocument = TokenSet.create(CLASS, FUN, PROPERTY)
}
}

private fun ASTNode.removeWithWhiteSpace(prevComment: ASTNode) {
if (prevComment.elementType == KDOC) {
if (prevComment.treeNext.elementType == WHITE_SPACE) {
removeChild(prevComment.treeNext)
}
removeChild(prevComment)
} else {
removeChildMergingSurroundingWhitespaces(prevComment)
}
}

/**
* If [child] node is surrounded by nodes with type `WHITE_SPACE`, remove [child] and merge surrounding nodes,
* preserving only a single newline if present (i.e. leaving no empty lines after merging). In any case, [child] is removed
* from the tree.
*/
private fun ASTNode.removeChildMergingSurroundingWhitespaces(child: ASTNode) {
with(child) {
if (treeNext?.elementType == WHITE_SPACE && treePrev?.elementType == WHITE_SPACE) {
val mergedText = (treePrev.text + treeNext.text)
val mergedSpace = if (mergedText.contains('\n')) {
'\n' + mergedText.substringAfterLast('\n')
} else {
mergedText
}
treeParent.replaceWhiteSpaceText(treePrev, mergedSpace)
}
treeParent.removeChild(treeNext)
}
removeChild(child)
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(
configRules,
listOf(KDOC_CONTAINS_DATE_OR_AUTHOR, KDOC_EMPTY_KDOC, KDOC_NEWLINES_BEFORE_BASIC_TAGS, KDOC_NO_DEPRECATED_TAG,
KDOC_NO_EMPTY_TAGS, KDOC_NO_NEWLINES_BETWEEN_BASIC_TAGS, KDOC_NO_NEWLINE_AFTER_SPECIAL_TAGS,
KDOC_WRONG_SPACES_AFTER_TAG, KDOC_WRONG_TAGS_ORDER)) {
KDOC_WRONG_SPACES_AFTER_TAG, KDOC_WRONG_TAGS_ORDER)
) {
private val basicTagsList = listOf(KDocKnownTag.PARAM, KDocKnownTag.RETURN, KDocKnownTag.THROWS)
private val specialTagNames = setOf("implSpec", "implNote", "apiNote")
private var versionRegex: Regex? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ class KdocMethods(configRules: List<RulesConfig>) : DiktatRule(
"kdoc-methods",
configRules,
listOf(KDOC_TRIVIAL_KDOC_ON_FUNCTION, KDOC_WITHOUT_PARAM_TAG, KDOC_WITHOUT_RETURN_TAG,
KDOC_WITHOUT_THROWS_TAG, MISSING_KDOC_ON_FUNCTION)) {
KDOC_WITHOUT_THROWS_TAG, MISSING_KDOC_ON_FUNCTION)
) {
/**
* @param node
*/
Expand Down Expand Up @@ -212,7 +213,8 @@ class KdocMethods(configRules: List<RulesConfig>) : DiktatRule(
kdoc: ASTNode?,
missingParameters: Collection<String?>,
kdocMissingParameters: List<KDocTag>,
kdocTags: Collection<KDocTag>?) {
kdocTags: Collection<KDocTag>?
) {
kdocMissingParameters.forEach {
KDOC_WITHOUT_PARAM_TAG.warn(configRules, emitWarn, false,
"${it.getSubjectName()} param isn't present in argument list", it.node.startOffset,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
class AnnotationNewLineRule(configRules: List<RulesConfig>) : DiktatRule(
"annotation-new-line",
configRules,
listOf(ANNOTATION_NEW_LINE)) {
listOf(ANNOTATION_NEW_LINE)
) {
override fun logic(node: ASTNode) {
when (node.elementType) {
CLASS, FUN, PRIMARY_CONSTRUCTOR, SECONDARY_CONSTRUCTOR -> checkAnnotation(node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ import org.jetbrains.kotlin.psi.KtTryExpression
class BlockStructureBraces(configRules: List<RulesConfig>) : DiktatRule(
"block-structure",
configRules,
listOf(BRACES_BLOCK_STRUCTURE_ERROR)) {
listOf(BRACES_BLOCK_STRUCTURE_ERROR)
) {
override fun logic(node: ASTNode) {
val configuration = BlockStructureBracesConfiguration(
configRules.getRuleConfig(BRACES_BLOCK_STRUCTURE_ERROR)?.configuration ?: emptyMap()
Expand Down Expand Up @@ -165,7 +166,8 @@ class BlockStructureBraces(configRules: List<RulesConfig>) : DiktatRule(
private fun checkOpenBraceOnSameLine(
node: ASTNode,
beforeType: IElementType,
configuration: BlockStructureBracesConfiguration) {
configuration: BlockStructureBracesConfiguration
) {
if (!configuration.openBrace) {
return
}
Expand Down Expand Up @@ -213,7 +215,8 @@ class BlockStructureBraces(configRules: List<RulesConfig>) : DiktatRule(
private fun checkMidBrace(
allMiddleSpace: List<ASTNode>,
node: ASTNode,
keyword: IElementType) {
keyword: IElementType
) {
allMiddleSpace.forEach { space ->
if (checkBraceNode(space, true)) {
BRACES_BLOCK_STRUCTURE_ERROR.warnAndFix(configRules, emitWarn, isFixMode, "incorrect new line after closing brace",
Expand Down
Loading

0 comments on commit aa2719a

Please sign in to comment.