Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / CommentOnlyMatcher.kt
CommentOnlyMatcher.kt52 lines · 1.9 KiBRaw
| 1 | package com.vayunmathur.lint |
| 2 | |
| 3 | import com.intellij.openapi.util.TextRange |
| 4 | import com.intellij.psi.PsiComment |
| 5 | import com.intellij.psi.PsiRecursiveElementVisitor |
| 6 | import org.jetbrains.kotlin.psi.KtFile |
| 7 | |
| 8 | /** |
| 9 | * Shared comment-only matching for marker-based detectors. |
| 10 | * |
| 11 | * Several detectors historically used whole-file `KtFile.text.contains(MARKER)`, |
| 12 | * which cannot tell a marker inside a `//` comment from the same text inside a |
| 13 | * string literal — a string containing e.g. `"// TOAST EXCEPTION:"` would |
| 14 | * silently opt the file out. All marker checks must go through here so they |
| 15 | * only look at PSI comment elements. |
| 16 | * |
| 17 | * KDoc is covered: in the Kotlin PSI it surfaces as a [PsiComment] subtype, |
| 18 | * so a single [PsiComment] walk sees `//`, block comments, and KDoc alike. |
| 19 | */ |
| 20 | object CommentOnlyMatcher { |
| 21 | |
| 22 | /** |
| 23 | * All comment elements in [file] in source order. |
| 24 | */ |
| 25 | fun commentsIn(file: KtFile): List<PsiComment> { |
| 26 | val out = mutableListOf<PsiComment>() |
| 27 | file.accept( |
| 28 | object : PsiRecursiveElementVisitor() { |
| 29 | override fun visitComment(comment: PsiComment) { |
| 30 | super.visitComment(comment) |
| 31 | out.add(comment) |
| 32 | } |
| 33 | }, |
| 34 | ) |
| 35 | return out |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Text ranges of every comment in [file], for offset-in-comment checks |
| 40 | * (e.g. skipping `androidx.room.` matches that live in KDoc). |
| 41 | */ |
| 42 | fun commentRangesIn(file: KtFile): List<TextRange> = |
| 43 | commentsIn(file).map { it.textRange } |
| 44 | |
| 45 | /** True if any comment in [file] contains [marker] verbatim. */ |
| 46 | fun containsMarkerInComments(file: KtFile, marker: String): Boolean = |
| 47 | commentsIn(file).any { it.text.contains(marker) } |
| 48 | |
| 49 | /** True if [offset] falls inside any of [ranges]. */ |
| 50 | fun isInRanges(offset: Int, ranges: List<TextRange>): Boolean = |
| 51 | ranges.any { it.startOffset <= offset && offset < it.endOffset } |
| 52 | } |