Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / CommentedOutCodeDetector.kt

CommentedOutCodeDetector.kt187 lines · 7.4 KiBRaw
1package com.vayunmathur.lint
2
3import com.android.tools.lint.client.api.UElementHandler
4import com.android.tools.lint.detector.api.Category
5import com.android.tools.lint.detector.api.Detector
6import com.android.tools.lint.detector.api.Implementation
7import com.android.tools.lint.detector.api.Issue
8import com.android.tools.lint.detector.api.JavaContext
9import com.android.tools.lint.detector.api.Location
10import com.android.tools.lint.detector.api.Scope
11import com.android.tools.lint.detector.api.Severity
12import com.android.tools.lint.detector.api.SourceCodeScanner
13import com.intellij.psi.PsiComment
14import org.jetbrains.kotlin.psi.KtFile
15import org.jetbrains.uast.UElement
16import org.jetbrains.uast.UFile
17import java.io.File
18
19/**
20 * Flags commented-out Kotlin code.
21 *
22 * The tree is clean today but nothing enforces it, and version control makes
23 * commented-out code pure noise: stale copies rot, readers cannot tell whether
24 * the block is load-bearing documentation or a revert waiting to happen, and
25 * the history already keeps the old shape. Delete it; the commit that removed
26 * it is the backup.
27 *
28 * Heuristic: a `//` comment line whose body parses as the start of a Kotlin
29 * declaration or statement (val/var/fun/class/import/return/assignment/call).
30 * Two or more consecutive matching lines report once on the run. Single
31 * illustrative lines (e.g. `// e.g. foo.bar()`) stay silent, as do KDoc,
32 * block comments, section banners, and the repo's own exception markers.
33 *
34 * Comment-only via [CommentOnlyMatcher]: string literals are never scanned.
35 *
36 * Blocking: every finding is an error.
37 */
38class CommentedOutCodeDetector : Detector(), SourceCodeScanner {
39
40 override fun getApplicableUastTypes(): List<Class<out UElement>> =
41 listOf(UFile::class.java)
42
43 override fun createUastHandler(context: JavaContext): UElementHandler =
44 object : UElementHandler() {
45 override fun visitFile(node: UFile) {
46 val packageName = node.packageName
47 if (packageName.isEmpty()) return
48 if (!packageName.startsWith("com.vayunmathur.")) return
49 if (LintPackageExclusions.isExcluded(packageName)) return
50 val ktFile = node.sourcePsi as? KtFile ?: return
51 val source = ktFile.text
52 val file = context.file ?: return
53 val comments = CommentOnlyMatcher.commentsIn(ktFile)
54 var index = 0
55 while (index < comments.size) {
56 val run = collectRun(source, comments, index)
57 if (run != null) {
58 val (start, length, count) = run
59 report(
60 context, node, file, source, start, length,
61 "Commented-out code ($count consecutive lines). Delete it — " +
62 "version control keeps the old shape, and stale copies rot. " +
63 "If the block documents intent, rewrite it as prose instead.",
64 )
65 index = runEnd(source, comments, index)
66 } else {
67 index++
68 }
69 }
70 }
71 }
72
73 /** Start/length/line-count of a commented-code run at [index], or null. */
74 private fun collectRun(
75 source: String,
76 comments: List<PsiComment>,
77 index: Int,
78 ): Triple<Int, Int, Int>? {
79 val first = comments[index]
80 if (!isLineComment(first)) return null
81 if (!looksLikeCode(stripSlashes(first.text))) return null
82 var end = index
83 while (end + 1 < comments.size) {
84 val next = comments[end + 1]
85 if (!isLineComment(next)) break
86 if (!adjacentLine(source, comments[end], next)) break
87 if (!looksLikeCode(stripSlashes(next.text))) break
88 end++
89 }
90 if (end - index + 1 < MIN_RUN_LINES) return null
91 val start = comments[index].textRange.startOffset
92 val stop = comments[end].textRange.endOffset
93 return Triple(start, stop - start, end - index + 1)
94 }
95
96 /** Index just past the run starting at [index]. */
97 private fun runEnd(
98 source: String,
99 comments: List<PsiComment>,
100 index: Int,
101 ): Int {
102 var end = index
103 while (end + 1 < comments.size) {
104 val next = comments[end + 1]
105 if (!isLineComment(next)) break
106 if (!adjacentLine(source, comments[end], next)) break
107 if (!looksLikeCode(stripSlashes(next.text))) break
108 end++
109 }
110 return end + 1
111 }
112
113 private fun isLineComment(comment: PsiComment): Boolean =
114 comment.text.startsWith("//") && !comment.text.startsWith("///") && !comment.text.startsWith("//!")
115
116 private fun stripSlashes(text: String): String =
117 text.removePrefix("//").trimStart()
118
119 private fun adjacentLine(
120 source: String,
121 prev: PsiComment,
122 next: PsiComment,
123 ): Boolean {
124 val between = source.substring(prev.textRange.endOffset, next.textRange.startOffset)
125 return ADJACENT_LINE.matches(between)
126 }
127
128 /** Heuristic: body reads as the start of a Kotlin declaration/statement. */
129 private fun looksLikeCode(body: String): Boolean {
130 if (body.isEmpty()) return false
131 if (body.startsWith("----") || body.startsWith("====") || body.startsWith("****")) return false
132 if (body.contains("EXCEPTION")) return false
133 if (body.startsWith("e.g.") || body.startsWith("i.e.") || body.startsWith("see ")) return false
134 return CODE_LIKE.any { it.containsMatchIn(body) }
135 }
136
137 private fun report(
138 context: JavaContext,
139 node: UFile,
140 file: File,
141 source: String,
142 start: Int,
143 length: Int,
144 message: String,
145 ) {
146 context.report(
147 ISSUE,
148 node,
149 Location.create(file, source, start, start + length),
150 message,
151 )
152 }
153
154 companion object {
155 private const val MIN_RUN_LINES = 2
156
157 /** Only whitespace and exactly one line break between adjacent `//` lines. */
158 private val ADJACENT_LINE = Regex("^\\h*\\R\\h*$")
159
160 private val CODE_LIKE = listOf(
161 Regex("""^(val|var|fun|class|object|interface|enum|data|sealed|abstract|override|private|public|internal|protected|suspend|lateinit|const)\b"""),
162 Regex("""^import\s+[\w.]+"""),
163 Regex("""^return\b"""),
164 Regex("""^[A-Za-z_][\w<>?]*\s*[:=]\s*\S"""),
165 Regex("""^[A-Za-z_][\w.]*\s*\("""),
166 Regex("""^\}\s*(else\b|catch\b|finally\b)?"""),
167 )
168
169 val ISSUE: Issue = Issue.create(
170 id = "CommentedOutCode",
171 briefDescription = "Commented-out code",
172 explanation = """
173 Commented-out code rots: readers cannot tell whether the block is \
174 load-bearing documentation or a revert waiting to happen, and version \
175 control already keeps the old shape. Delete the block — the commit that \
176 removed it is the backup. If it documents intent, rewrite it as prose.
177 """.trimIndent(),
178 category = Category.PRODUCTIVITY,
179 priority = 4,
180 severity = Severity.ERROR,
181 implementation = Implementation(
182 CommentedOutCodeDetector::class.java,
183 Scope.JAVA_FILE_SCOPE,
184 ),
185 )
186 }
187}