Skip to content

Commit

Permalink
Lint code clean up
Browse files Browse the repository at this point in the history
Summary: After having turned on our internal Android Lint in ktfmt code, here's the code clean up round from it

Reviewed By: strulovich

Differential Revision: D61979521

fbshipit-source-id: 5182acacb7be7f30770d90e2f8983a649821e138
  • Loading branch information
Nivaldo Bondança authored and facebook-github-bot committed Sep 3, 2024
1 parent 9dcd261 commit 9830466
Show file tree
Hide file tree
Showing 27 changed files with 244 additions and 66 deletions.
2 changes: 1 addition & 1 deletion core/src/main/java/com/facebook/ktfmt/cli/ParsedArgs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ data class ParsedArgs(
return parseOptions(arguments)
}

val HELP_TEXT =
val HELP_TEXT: String =
"""
|ktfmt - command line Kotlin source code pretty-printer
|
Expand Down
12 changes: 7 additions & 5 deletions core/src/main/java/com/facebook/ktfmt/format/EnumEntryList.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private constructor(
) {
companion object {
fun extractParentList(enumEntry: KtEnumEntry): EnumEntryList {
return extractChildList(enumEntry.parent as KtClassBody)!!
return checkNotNull(extractChildList(enumEntry.parent as KtClassBody))
}

fun extractChildList(classBody: KtClassBody): EnumEntryList? {
Expand All @@ -61,10 +61,12 @@ private constructor(
var semicolon: PsiElement? = null
var comma: PsiElement? = null
val lastToken =
enumEntries
.last()
.lastChild
.getPrevSiblingIgnoringWhitespaceAndComments(withItself = true)!!
checkNotNull(
enumEntries
.last()
.lastChild
.getPrevSiblingIgnoringWhitespaceAndComments(withItself = true),
)
when (lastToken.text) {
"," -> {
comma = lastToken
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/com/facebook/ktfmt/format/Formatter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ object Formatter {
.let { dropRedundantElements(it, options) }
.let { prettyPrint(it, options, "\n") }
.let { addRedundantElements(it, options) }
.let { convertLineSeparators(it, Newlines.guessLineSeparator(kotlinCode)!!) }
.let { convertLineSeparators(it, checkNotNull(Newlines.guessLineSeparator(kotlinCode))) }
.let { if (shebang.isEmpty()) it else shebang + "\n" + it }
}

Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,9 @@ class KotlinInput(private val text: String, file: KtFile) : Input() {

override fun getText(): String = text

override fun getLineNumber(inputPosition: Int) =
override fun getLineNumber(inputPosition: Int): Int =
StringUtil.offsetToLineColumn(text, inputPosition).line + 1

override fun getColumnNumber(inputPosition: Int) =
override fun getColumnNumber(inputPosition: Int): Int =
StringUtil.offsetToLineColumn(text, inputPosition).column
}
Original file line number Diff line number Diff line change
Expand Up @@ -2427,9 +2427,9 @@ class KotlinInputAstVisitor(
visit(enumEntry.modifierList)
builder.token(enumEntry.nameIdentifier?.text ?: fail())
enumEntry.initializerList?.initializers?.forEach { visit(it) }
enumEntry.body?.let {
enumEntry.body?.let { enumBody ->
builder.space()
visit(it)
visit(enumBody)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/com/facebook/ktfmt/format/ParseError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class ParseError(val errorDescription: String, val lineColumn: LineColumn) :

companion object {
private fun positionOf(element: PsiElement): LineColumn {
val doc = element.containingFile.viewProvider.document!!
val doc = checkNotNull(element.containingFile.viewProvider.document)
val offset = element.textOffset
val lineZero = doc.getLineNumber(offset)
val colZero = offset - doc.getLineStartOffset(lineZero)
Expand Down
5 changes: 2 additions & 3 deletions core/src/main/java/com/facebook/ktfmt/format/Parser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,8 @@ object Parser {
fun parse(code: String): KtFile {
val virtualFile = LightVirtualFile("temp.kts", KotlinFileType.INSTANCE, code)
val ktFile = PsiManager.getInstance(env.project).findFile(virtualFile) as KtFile
ktFile.collectDescendantsOfType<PsiErrorElement>().let {
if (it.isNotEmpty()) throwParseError(code, it[0])
}
val descendants = ktFile.collectDescendantsOfType<PsiErrorElement>()
if (descendants.isNotEmpty()) throwParseError(code, descendants[0])
return ktFile
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,11 @@ internal class RedundantImportDetector(val enabled: Boolean) {
val identifierCounts =
importCleanUpCandidates.groupBy { it.identifier }.mapValues { it.value.size }

return importCleanUpCandidates.filter {
val isUsed = it.identifier in usedReferences
val isFromThisPackage = it.importedFqName?.parent() == thisPackage
val hasAlias = it.alias != null
val isOverload = requireNotNull(identifierCounts[it.identifier]) > 1
return importCleanUpCandidates.filter { importCandidate ->
val isUsed = importCandidate.identifier in usedReferences
val isFromThisPackage = importCandidate.importedFqName?.parent() == thisPackage
val hasAlias = importCandidate.alias != null
val isOverload = requireNotNull(identifierCounts[importCandidate.identifier]) > 1
// Remove if...
!isUsed || (isFromThisPackage && !hasAlias && !isOverload)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ object WhitespaceTombstones {
/** See [replaceTrailingWhitespaceWithTombstone]. */
const val SPACE_TOMBSTONE = '\u0003'

fun String.indexOfWhitespaceTombstone() = this.indexOf(SPACE_TOMBSTONE)
fun String.indexOfWhitespaceTombstone(): Int = this.indexOf(SPACE_TOMBSTONE)

/**
* Google-java-format removes trailing spaces when it emits formatted code, which is a problem for
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright (c) Tor Norbye.
*
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/com/facebook/ktfmt/kdoc/Escaping.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ object Escaping {

private const val STAR_SLASH_ESCAPE = "\u0005\u0004"

fun indexOfCommentEscapeSequences(s: String) =
fun indexOfCommentEscapeSequences(s: String): Int =
s.indexOfAny(listOf(SLASH_STAR_ESCAPE, STAR_SLASH_ESCAPE))

/**
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/kdoc/FormattingTask.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright (c) Tor Norbye.
*
Expand Down
26 changes: 21 additions & 5 deletions core/src/main/java/com/facebook/ktfmt/kdoc/KDocCommentsHelper.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright 2015 Google Inc.
*
Expand Down Expand Up @@ -33,11 +49,11 @@ class KDocCommentsHelper(private val lineSeparator: String, private val maxLineL

private val kdocFormatter =
KDocFormatter(
KDocFormattingOptions(maxLineLength, maxLineLength).also {
it.allowParamBrackets = true // TODO Do we want this?
it.convertMarkup = false
it.nestedListIndent = 4
it.optimal = false // Use greedy line breaking for predictability.
KDocFormattingOptions(maxLineLength, maxLineLength).apply {
allowParamBrackets = true // TODO Do we want this?
convertMarkup = false
nestedListIndent = 4
optimal = false // Use greedy line breaking for predictability.
})

override fun rewrite(tok: Tok, maxWidth: Int, column0: Int): String {
Expand Down
18 changes: 17 additions & 1 deletion core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright (c) Tor Norbye.
*
Expand Down Expand Up @@ -129,7 +145,7 @@ class KDocFormatter(private val options: KDocFormattingOptions) {
}
sb.append("*/")
} else if (sb.endsWith(lineSeparator)) {
@Suppress("ReturnValueIgnored") sb.removeSuffix(lineSeparator)
@Suppress("NoOp", "ReturnValueIgnored") sb.removeSuffix(lineSeparator)
}

val formatted =
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/kdoc/KDocToken.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright 2016 Google Inc.
*
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright 2016 Google Inc.
*
Expand Down
16 changes: 16 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/kdoc/NestingCounter.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright 2016 Google Inc.
*
Expand Down
10 changes: 5 additions & 5 deletions core/src/main/java/com/facebook/ktfmt/kdoc/Paragraph.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ class Paragraph(private val task: FormattingTask) {
private val options: KDocFormattingOptions
get() = task.options

var content = StringBuilder()
val text
var content: StringBuilder = StringBuilder()
val text: String
get() = content.toString()

var prev: Paragraph? = null
Expand Down Expand Up @@ -348,7 +348,7 @@ class Paragraph(private val task: FormattingTask) {
private fun reflow(words: List<String>, lineWidth: Int, hangingIndentSize: Int): List<String> {
if (options.alternate ||
!options.optimal ||
hanging && hangingIndentSize > 0 ||
(hanging && hangingIndentSize > 0) ||
// An unbreakable long word may make other lines shorter and won't look good
words.any { it.length > lineWidth }) {
// Switch to greedy if explicitly turned on, and for hanging indent
Expand Down Expand Up @@ -430,7 +430,7 @@ class Paragraph(private val task: FormattingTask) {

if (!word.first().isLetter()) {
val wordWithSpace = "$word " // for regex matching in below checks
if (wordWithSpace.isListItem() && !word.equals("<li>", true) || wordWithSpace.isQuoted()) {
if ((wordWithSpace.isListItem() && !word.equals("<li>", true)) || wordWithSpace.isQuoted()) {
return false
}
}
Expand Down Expand Up @@ -468,7 +468,7 @@ class Paragraph(private val task: FormattingTask) {
val end = words.size
while (from < end) {
val start =
if (from == 0 && (quoted || hanging && !text.isKDocTag())) {
if (from == 0 && (quoted || (hanging && !text.isKDocTag()))) {
from + 2
} else {
from + 1
Expand Down
18 changes: 17 additions & 1 deletion core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphList.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Portions Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* Copyright (c) Tor Norbye.
*
Expand All @@ -22,7 +38,7 @@ package com.facebook.ktfmt.kdoc
* front of it.
*/
class ParagraphList(private val paragraphs: List<Paragraph>) : Iterable<Paragraph> {
fun isSingleParagraph() = paragraphs.size <= 1
fun isSingleParagraph(): Boolean = paragraphs.size <= 1

override fun iterator(): Iterator<Paragraph> = paragraphs.iterator()

Expand Down
Loading

0 comments on commit 9830466

Please sign in to comment.