Skip to content

Add a few more examples, including a Kotlin Analysis API usage #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions checks/src/main/java/com/example/lint/checks/AvoidDateDetector.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* 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.
*/
package com.example.lint.checks

import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression

class AvoidDateDetector : Detector(), SourceCodeScanner {
companion object Issues {
private val IMPLEMENTATION =
Implementation(AvoidDateDetector::class.java, Scope.JAVA_FILE_SCOPE)

@JvmField
val ISSUE =
Issue.create(
id = "OldDate",
briefDescription = "Avoid Date and Calendar",
explanation =
"""
The `java.util.Date` and `java.util.Calendar` classes should not be used; instead \
use the `java.time` package, such as `LocalDate` and `LocalTime`.
""",
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.ERROR,
androidSpecific = true,
implementation = IMPLEMENTATION,
)
}

// java.util.Date()
override fun getApplicableConstructorTypes(): List<String> = listOf("java.util.Date")

override fun visitConstructor(
context: JavaContext,
node: UCallExpression,
constructor: PsiMethod,
) {
context.report(
ISSUE,
node,
context.getLocation(node),
"Don't use `Date`; use `java.time.*` instead",
fix()
.alternatives(
fix().replace().all().with("java.time.LocalTime.now()").shortenNames().build(),
fix().replace().all().with("java.time.LocalDate.now()").shortenNames().build(),
fix().replace().all().with("java.time.LocalDateTime.now()").shortenNames().build(),
),
)
}

// java.util.Calendar.getInstance()
override fun getApplicableMethodNames(): List<String> = listOf("getInstance")

override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
val evaluator = context.evaluator
if (!evaluator.isMemberInClass(method, "java.util.Calendar")) {
return
}
context.report(
ISSUE,
node,
context.getLocation(node),
"Don't use `Calendar.getInstance`; use `java.time.*` instead",
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* 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.
*/
package com.example.lint.checks

import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.codegen.optimization.common.analyze
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UPostfixExpression

class NotNullAssertionDetector : Detector(), SourceCodeScanner {
companion object Issues {
private val IMPLEMENTATION =
Implementation(NotNullAssertionDetector::class.java, Scope.JAVA_FILE_SCOPE)

@JvmField
val ISSUE =
Issue.create(
id = "NotNullAssertion",
briefDescription = "Avoid `!!`",
explanation =
"""
Do not use the `!!` operator. It can lead to null pointer exceptions. \
Please use the `?` operator instead, or assign to a local variable with \
`?:` initialization if necessary.
""",
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.WARNING,
implementation = IMPLEMENTATION,
)
}

override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UPostfixExpression::class.java)
}

override fun createUastHandler(context: JavaContext): UElementHandler {
return object : UElementHandler() {
override fun visitPostfixExpression(node: UPostfixExpression) {
if (node.operator.text == "!!") {
var message = "Do not use `!!`"

// Kotlin Analysis API example
val sourcePsi = node.operand.sourcePsi
if (sourcePsi is KtExpression) {
analyze(sourcePsi) {
val type = sourcePsi.getKtType()
if (type != null && !type.canBeNull) {
message += " -- it's not even needed here"
}
}
}

val incident = Incident(ISSUE, node, context.getLocation(node), message)
context.report(incident)
}
}
}
}
}
103 changes: 50 additions & 53 deletions checks/src/main/java/com/example/lint/checks/SampleCodeDetector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,64 +29,61 @@ import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.evaluateString

/**
* Sample detector showing how to analyze Kotlin/Java code. This example
* flags all string literals in the code that contain the word "lint".
* Sample detector showing how to analyze Kotlin/Java code. This example flags all string literals
* in the code that contain the word "lint".
*/
@Suppress("UnstableApiUsage")
class SampleCodeDetector : Detector(), UastScanner {
override fun getApplicableUastTypes(): List<Class<out UElement?>> {
return listOf(ULiteralExpression::class.java)
}
override fun getApplicableUastTypes(): List<Class<out UElement?>> {
return listOf(ULiteralExpression::class.java)
}

override fun createUastHandler(context: JavaContext): UElementHandler {
// Note: Visiting UAST nodes is a pretty general purpose mechanism;
// Lint has specialized support to do common things like "visit every class
// that extends a given super class or implements a given interface", and
// "visit every call site that calls a method by a given name" etc.
// Take a careful look at UastScanner and the various existing lint check
// implementations before doing things the "hard way".
// Also be aware of context.getJavaEvaluator() which provides a lot of
// utility functionality.
return object : UElementHandler() {
override fun visitLiteralExpression(node: ULiteralExpression) {
val string = node.evaluateString() ?: return
if (string.contains("lint") && string.matches(Regex(".*\\blint\\b.*"))) {
context.report(
ISSUE, node, context.getLocation(node),
"This code mentions `lint`: **Congratulations**"
)
}
}
override fun createUastHandler(context: JavaContext): UElementHandler {
// Note: Visiting UAST nodes is a pretty general purpose mechanism;
// Lint has specialized support to do common things like "visit every class
// that extends a given super class or implements a given interface", and
// "visit every call site that calls a method by a given name" etc.
// Take a careful look at UastScanner and the various existing lint check
// implementations before doing things the "hard way".
// Also be aware of context.getJavaEvaluator() which provides a lot of
// utility functionality.
return object : UElementHandler() {
override fun visitLiteralExpression(node: ULiteralExpression) {
val string = node.evaluateString() ?: return
if (string.contains("lint") && string.matches(Regex(".*\\blint\\b.*"))) {
context.report(
ISSUE,
node,
context.getLocation(node),
"This code mentions `lint`: **Congratulations**",
)
}
}
}
}

companion object {
/**
* Issue describing the problem and pointing to the detector
* implementation.
*/
@JvmField
val ISSUE: Issue = Issue.create(
// ID: used in @SuppressLint warnings etc
id = "SampleId",
// Title -- shown in the IDE's preference dialog, as category headers in the
// Analysis results window, etc
briefDescription = "Lint Mentions",
// Full explanation of the issue; you can use some markdown markup such as
// `monospace`, *italic*, and **bold**.
explanation = """
This check highlights string literals in code which mentions the word `lint`. \
Blah blah blah.
companion object {
/** Issue describing the problem and pointing to the detector implementation. */
@JvmField
val ISSUE: Issue =
Issue.create(
// ID: used in @SuppressLint warnings etc
id = "SampleId",
// Title -- shown in the IDE's preference dialog, as category headers in the
// Analysis results window, etc
briefDescription = "Lint Mentions",
// Full explanation of the issue; you can use some markdown markup such as
// `monospace`, *italic*, and **bold**.
explanation =
"""
This check highlights string literals in code which mentions the word `lint`. \
Blah blah blah.

Another paragraph here.
""", // no need to .trimIndent(), lint does that automatically
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.WARNING,
implementation = Implementation(
SampleCodeDetector::class.java,
Scope.JAVA_FILE_SCOPE
)
)
}
Another paragraph here.
""", // no need to .trimIndent(), lint does that automatically
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.WARNING,
implementation = Implementation(SampleCodeDetector::class.java, Scope.JAVA_FILE_SCOPE),
)
}
}
25 changes: 13 additions & 12 deletions checks/src/main/java/com/example/lint/checks/SampleIssueRegistry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,22 @@ import com.android.tools.lint.detector.api.CURRENT_API
/*
* The list of issues that will be checked when running <code>lint</code>.
*/
@Suppress("UnstableApiUsage")
class SampleIssueRegistry : IssueRegistry() {
override val issues = listOf(SampleCodeDetector.ISSUE)
override val issues =
listOf(SampleCodeDetector.ISSUE, AvoidDateDetector.ISSUE, NotNullAssertionDetector.ISSUE)

override val api: Int
get() = CURRENT_API
override val api: Int
get() = CURRENT_API

override val minApi: Int
get() = 8 // works with Studio 4.1 or later; see com.android.tools.lint.detector.api.Api / ApiKt
override val minApi: Int
get() = 8 // works with Studio 4.1 or later; see com.android.tools.lint.detector.api.Api / ApiKt

// Requires lint API 30.0+; if you're still building for something
// older, just remove this property.
override val vendor: Vendor = Vendor(
vendorName = "Android Open Source Project",
feedbackUrl = "https://github.com/googlesamples/android-custom-lint-rules/issues",
contact = "https://github.com/googlesamples/android-custom-lint-rules"
// Requires lint API 30.0+; if you're still building for something
// older, just remove this property.
override val vendor: Vendor =
Vendor(
vendorName = "Android Open Source Project",
feedbackUrl = "https://github.com/googlesamples/android-custom-lint-rules/issues",
contact = "https://github.com/googlesamples/android-custom-lint-rules",
)
}
Loading
Loading