├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ └── com
│ │ │ └── serchinastico
│ │ │ └── lin
│ │ │ └── TestActivity.kt
│ │ └── AndroidManifest.xml
└── build.gradle
├── dsl
├── .gitignore
├── src
│ └── main
│ │ └── kotlin
│ │ └── com
│ │ └── serchinastico
│ │ └── lin
│ │ └── dsl
│ │ ├── LinCategory.kt
│ │ ├── visitor.kt
│ │ ├── extensions.kt
│ │ ├── match.kt
│ │ └── dsl.kt
└── build.gradle
├── test
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── serchinastico
│ └── lin
│ └── test
│ └── LintTest.kt
├── annotations
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── serchinastico
│ └── lin
│ └── annotations
│ └── Detector.kt
├── processor
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── serchinastico
│ └── lin
│ └── processor
│ └── DetectorProcessor.kt
├── detectors
├── .gitignore
├── src
│ ├── main
│ │ └── kotlin
│ │ │ └── com
│ │ │ └── serchinastico
│ │ │ └── lin
│ │ │ └── detectors
│ │ │ ├── JavaFileToAvoidCompilationFailure.java
│ │ │ ├── LinIssueRegistry.kt
│ │ │ ├── noDataFrameworksFromAndroidClassDetector.kt
│ │ │ ├── onlyConstantsInTypeOrFileDetector.kt
│ │ │ ├── noPublicViewPropertiesDetector.kt
│ │ │ ├── noElseInSwitchWithEnumOrSealedDetector.kt
│ │ │ ├── noPrintStackTraceCallsDetector.kt
│ │ │ ├── noSetOnClickListenerCallsDetector.kt
│ │ │ ├── noMoreThanOneDateInstanceDetector.kt
│ │ │ ├── noFindViewByIdCallsDetector.kt
│ │ │ ├── noMoreThanOneGsonInstanceDetector.kt
│ │ │ └── wrongSyntheticViewReference.kt
│ └── test
│ │ └── kotlin
│ │ └── com
│ │ └── serchinastico
│ │ └── lin
│ │ └── detectors
│ │ ├── WrongSyntheticViewReferenceDetectorTest.kt
│ │ ├── NoDataFrameworksFromAndroidClassDetectorTest.kt
│ │ ├── NoPublicViewPropertiesDetectorTest.kt
│ │ ├── NoPrintStackTraceCallsDetectorTest.kt
│ │ ├── NoSetOnClickListenerCallsDetectorTest.kt
│ │ ├── NoMoreThanOneDateInstanceDetectorTest.kt
│ │ ├── NoMoreThanOneGsonInstanceDetectorTest.kt
│ │ ├── NoFindViewByIdCallsDetectorTest.kt
│ │ ├── NoElseInSwitchWithEnumOrSealedDetectorTest.kt
│ │ └── OnlyConstantsInTypeDetectorTest.kt
└── build.gradle
├── readme
└── logo.png
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .travis.yml
├── .github
├── PULL_REQUEST_TEMPLATE.md
├── ISSUE_TEMPLATE
│ ├── detector_request.md
│ ├── bug_report.md
│ └── feature_request.md
└── CONTRIBUTING.md
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── CODE_OF_CONDUCT.md
├── gradlew
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/dsl/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/test/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/annotations/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/processor/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/detectors/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /bin
3 |
--------------------------------------------------------------------------------
/readme/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/readme/logo.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':dsl', ':detectors', ':annotations', ':processor', ':test'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Lin
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/JavaFileToAvoidCompilationFailure.java:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors;
2 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Serchinastico/Lin/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/annotations/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'kotlin'
3 |
4 | dependencies {
5 | implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.21"
6 | }
--------------------------------------------------------------------------------
/dsl/src/main/kotlin/com/serchinastico/lin/dsl/LinCategory.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.dsl
2 |
3 | import com.android.tools.lint.detector.api.Category
4 |
5 | val LinCategory = Category(null, "Lin", 100)
--------------------------------------------------------------------------------
/annotations/src/main/kotlin/com/serchinastico/lin/annotations/Detector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.annotations
2 |
3 | @Retention(AnnotationRetention.SOURCE)
4 | @Target(AnnotationTarget.FUNCTION)
5 | annotation class Detector
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Mar 20 21:00:23 CET 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 |
3 | android:
4 | components:
5 | - tools
6 | - platform-tools
7 | - build-tools-28.0.3
8 | - android-28
9 | - extra
10 |
11 | script:
12 | - ./gradlew test
13 |
14 | after_success:
15 | - bash <(curl -s https://codecov.io/bash)
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | :pushpin: **References**
2 |
3 | * Issue: _your issue goes here_
4 | * Other PRs: _your other PRs go here_
5 |
6 | :cyclone: **Git merge message**
7 |
8 | * _Explain the whats and the whys for this branch_
9 |
10 | :memo: **Notes**
11 |
12 | * _Additional information for reviewers such as how to test the new feature_
13 |
--------------------------------------------------------------------------------
/test/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'kotlin'
2 |
3 | dependencies {
4 | implementation 'com.android.tools.lint:lint:26.3.0'
5 | implementation 'com.android.tools.lint:lint-api:26.3.0'
6 | implementation 'com.android.tools.lint:lint-checks:26.3.0'
7 | implementation 'com.android.tools.lint:lint-tests:26.3.0'
8 | implementation 'com.android.tools:testutils:26.3.0'
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/serchinastico/lin/TestActivity.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.View
6 |
7 | class TestClass : Activity() {
8 | lateinit var asd: String
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | findViewById(R.id.action_bar)
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/processor/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'kotlin'
3 | apply plugin: 'kotlin-kapt'
4 |
5 | dependencies {
6 | compile project(":annotations")
7 | compile project(":dsl")
8 | implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.21"
9 | implementation "com.squareup:kotlinpoet:1.0.0"
10 | implementation "com.google.auto.service:auto-service:1.0-rc4"
11 | kapt "com.google.auto.service:auto-service:1.0-rc4"
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/detector_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Detector request
3 | about: Suggest a new detector
4 |
5 | ---
6 |
7 | **Describe what should the detector look for**
8 | A clear and concise description of what the detector does. Ex. Prevent the usage of this pattern.
9 |
10 | **Describe what problem is this detector trying to prevent**
11 | A clear and concise description of what problems is this detector trying to solve.
12 |
13 | **Example code**
14 | A code snippet where this detector would report an error.
15 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve the library
4 |
5 | ---
6 |
7 | **Steps to reproduce**
8 | Include code snippets to fully understand what the problem might be
9 |
10 | **Expected behavior**
11 | What should the library do
12 |
13 | **Actual behaviour**
14 | What is it actually doing
15 |
16 | **Module**
17 | Module that you are using, if you are using more than one, specify them all
18 |
19 | **Version**
20 | Version of every module you are using
21 |
--------------------------------------------------------------------------------
/dsl/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'kotlin'
2 |
3 | dependencies {
4 | compileOnly 'com.android.tools.lint:lint:26.3.2'
5 | compileOnly 'com.android.tools.lint:lint-api:26.3.2'
6 | compileOnly 'com.android.tools.lint:lint-checks:26.3.2'
7 |
8 | testImplementation 'junit:junit:4.12'
9 | testImplementation 'org.assertj:assertj-core:3.3.0'
10 | testImplementation 'org.mockito:mockito-core:2.23.4'
11 | testImplementation 'com.android.tools.lint:lint:26.3.2'
12 | testImplementation 'com.android.tools.lint:lint-tests:26.3.2'
13 | testImplementation 'com.android.tools:testutils:26.3.2'
14 | }
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # Kotlin code style for this project: "official" or "obsolete":
15 | kotlin.code.style=official
16 |
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/LinIssueRegistry.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.client.api.IssueRegistry
4 | import com.android.tools.lint.detector.api.CURRENT_API
5 | import com.android.tools.lint.detector.api.Issue
6 |
7 | class LinIssueRegistry : IssueRegistry() {
8 | override val api: Int
9 | get() = CURRENT_API
10 |
11 | override val minApi: Int
12 | get() = CURRENT_API
13 |
14 | override val issues: List = listOf(
15 | NoDataFrameworksFromAndroidClassDetector.issue,
16 | NoElseInSwitchWithEnumOrSealedDetector.issue,
17 | NoFindViewByIdCallsDetector.issue,
18 | NoMoreThanOneDateInstanceDetector.issue,
19 | NoMoreThanOneGsonInstanceDetector.issue,
20 | NoPrintStackTraceCallsDetector.issue,
21 | NoPublicViewPropertiesDetector.issue,
22 | NoSetOnClickListenerCallsDetector.issue,
23 | OnlyConstantsInTypeOrFileDetector.issue,
24 | WrongSyntheticViewReferenceDetector.issue
25 | )
26 | }
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noDataFrameworksFromAndroidClassDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.detector
6 | import com.serchinastico.lin.dsl.isAndroidFrameworkType
7 | import com.serchinastico.lin.dsl.isFrameworkLibraryImport
8 | import com.serchinastico.lin.dsl.issue
9 |
10 | @Detector
11 | fun noDataFrameworksFromAndroidClass() = detector(
12 | issue(
13 | Scope.JAVA_FILE_SCOPE,
14 | """Framework classes to get or store data should never be called from Activities, Fragments or any other
15 | | Android related view.""".trimMargin(),
16 | """Your Android classes should not be responsible for retrieving or storing information, that should be
17 | | responsibility of another classes.""".trimMargin()
18 | )
19 | ) {
20 | import { suchThat { it.isFrameworkLibraryImport } }
21 | type { suchThat { node -> node.uastSuperTypes.any { it.isAndroidFrameworkType } } }
22 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 28
7 | defaultConfig {
8 | applicationId "com.serchinastico.lin"
9 | minSdkVersion 19
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | lintChecks project(':detectors')
25 | lintClassPath project(":dsl")
26 |
27 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.21"
28 | implementation 'com.android.support:appcompat-v7:28.0.0'
29 | testImplementation 'junit:junit:4.12'
30 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
31 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
32 | }
33 |
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/onlyConstantsInTypeOrFileDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.detector
6 | import com.serchinastico.lin.dsl.issue
7 | import org.jetbrains.uast.UClass
8 | import org.jetbrains.uast.UEnumConstant
9 |
10 | @Detector
11 | fun onlyConstantsInTypeOrFile() = detector(
12 | issue(
13 | Scope.JAVA_FILE_SCOPE,
14 | "Using a class/file to store only constants is bad practice",
15 | """Classes holding only constant values are often a code smell. Constant values should be placed on the class
16 | | they are being used instead and, if there is more than one place where the constant is used, move them
17 | | to wherever they make more sense.
18 | """.trimMargin()
19 | )
20 | ) {
21 | type { suchThat { it.onlyHasStaticFinalFields } }
22 | }
23 |
24 | private inline val UClass.onlyHasStaticFinalFields: Boolean
25 | get() = methods.all { it.isConstructor } &&
26 | fields.isNotEmpty() &&
27 | fields.all { it.isStatic && it.isFinal && it !is UEnumConstant }
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noPublicViewPropertiesDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.*
6 | import org.jetbrains.uast.UField
7 |
8 | @Detector
9 | fun noPublicViewProperties() = detector(
10 | issue(
11 | Scope.JAVA_FILE_SCOPE,
12 | "View properties should always be private",
13 | """Exposing views to other classes, be it from activities or custom views is leaking too much
14 | | information to other classes and is prompt to break if the inner implementation of
15 | | the layout changes, the only exception is if those views are part of an implemented
16 | | interface or abstract class""".trimMargin()
17 | )
18 | ) {
19 | field { suchThat { it.isNonPrivateViewField } }
20 | }
21 |
22 | private inline val UField.isNonPrivateViewField: Boolean
23 | get() {
24 | val isPrivateField = isPrivate
25 | val isOverrideField = isOverride
26 | val isViewType = isClassOrSubclassOf("android.view.View")
27 |
28 | return !isPrivateField && isViewType && !isOverrideField
29 | }
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noElseInSwitchWithEnumOrSealedDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.*
6 | import org.jetbrains.uast.USwitchExpression
7 |
8 | @Detector
9 | fun noElseInSwitchWithEnumOrSealed() = detector(
10 | issue(
11 | Scope.JAVA_FILE_SCOPE,
12 | "There should not be else/default branches on a switch statement checking for enum/sealed class values",
13 | """Adding an else/default branch breaks extensibility because it won't let you know if there is a missing
14 | | implementation when adding new types to the enum/sealed class""".trimMargin()
15 | )
16 | ) {
17 | switchExpression { suchThat { it.hasElseWithEnumOrSealedExpression } }
18 | }
19 |
20 | private inline val USwitchExpression.hasElseWithEnumOrSealedExpression: Boolean
21 | get() {
22 | val classReferenceType = expression?.getExpressionType() ?: return false
23 |
24 | if (!classReferenceType.isEnum && !classReferenceType.isSealed) {
25 | return false
26 | }
27 |
28 | return clauses.any { clause -> clause.isElseBranch }
29 | }
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noPrintStackTraceCallsDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.detector
6 | import com.serchinastico.lin.dsl.isClassOrSubclassOf
7 | import com.serchinastico.lin.dsl.issue
8 | import org.jetbrains.uast.UCallExpression
9 |
10 | @Detector
11 | fun noPrintStackTraceCalls() = detector(
12 | issue(
13 | Scope.JAVA_FILE_SCOPE,
14 | "There should not be calls to the printStackTrace method in Throwable instances",
15 | "Errors should be logged with a configured logger or sent to the backend for faster response"
16 | )
17 | ) {
18 | callExpression { suchThat { it.isPrintStackTraceCall } }
19 | }
20 |
21 | private inline val UCallExpression.isPrintStackTraceCall: Boolean
22 | get() {
23 | val receiverType = receiverType ?: return false
24 |
25 | val isReceiverChildOfThrowable = receiverType.isClassOrSubclassOf("java.lang.Throwable", "kotlin.Throwable")
26 | val isMethodPrintStackTrace = methodIdentifier?.name == "printStackTrace"
27 |
28 | return isReceiverChildOfThrowable && isMethodPrintStackTrace
29 | }
30 |
--------------------------------------------------------------------------------
/detectors/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'jacoco'
2 | apply plugin: 'kotlin'
3 | apply plugin: 'kotlin-kapt'
4 |
5 | sourceSets {
6 | main {
7 | java {
8 | srcDirs = [
9 | "src/main/kotlin",
10 | "${buildDir.absolutePath}/generated/source/kapt/main/"]
11 | }
12 | }
13 | }
14 |
15 | dependencies {
16 | compileOnly project(":dsl")
17 | compileOnly project(":annotations")
18 | kapt project(":processor")
19 |
20 | compileOnly 'com.android.tools.lint:lint:26.3.2'
21 | compileOnly 'com.android.tools.lint:lint-api:26.3.2'
22 | compileOnly 'com.android.tools.lint:lint-checks:26.3.2'
23 |
24 | testImplementation project(":dsl")
25 | testImplementation project(":test")
26 | testImplementation 'junit:junit:4.12'
27 | testImplementation 'org.assertj:assertj-core:3.3.0'
28 | testImplementation 'org.mockito:mockito-core:2.23.4'
29 | testImplementation 'com.android.tools.lint:lint:26.3.2'
30 | testImplementation 'com.android.tools.lint:lint-tests:26.3.2'
31 | testImplementation 'com.android.tools:testutils:26.3.2'
32 | }
33 |
34 | test.finalizedBy jacocoTestReport
35 |
36 | jar {
37 | manifest {
38 | attributes("Lint-Registry-v2": "com.serchinastico.lin.detectors.LinIssueRegistry")
39 | }
40 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # VSCode
46 | .vscode/
47 |
48 | # Keystore files
49 | # Uncomment the following line if you do not want to check your keystore files in.
50 | #*.jks
51 |
52 | # External native build folder generated in Android Studio 2.2 and later
53 | .externalNativeBuild
54 |
55 | # Google Services (e.g. APIs or Firebase)
56 | google-services.json
57 |
58 | # Freeline
59 | freeline.py
60 | freeline/
61 | freeline_project_description.json
62 |
63 | # fastlane
64 | fastlane/report.xml
65 | fastlane/Preview.html
66 | fastlane/screenshots
67 | fastlane/test_output
68 | fastlane/readme.md
69 |
70 | # VSCode
71 | .classpath
72 | .project
73 | .settings
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noSetOnClickListenerCallsDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.detector
6 | import com.serchinastico.lin.dsl.isClassOrSubclassOf
7 | import com.serchinastico.lin.dsl.issue
8 | import org.jetbrains.uast.UCallExpression
9 |
10 |
11 | @Detector
12 | fun noSetOnClickListenerCalls() = detector(
13 | issue(
14 | Scope.JAVA_FILE_SCOPE,
15 | "There should not be calls to setOnClickListener",
16 | """Nowadays there are better ways to synthetize these calls into a more concise declaration with tools
17 | | like ButterKnife or Data Binding. See https://github.com/JakeWharton/butterknife or
18 | | https://developer.android.com/topic/libraries/data-binding/""".trimMargin()
19 | )
20 | ) {
21 | callExpression { suchThat { it.isSetOnClickListenerCall } }
22 | }
23 |
24 | private inline val UCallExpression.isSetOnClickListenerCall: Boolean
25 | get() {
26 | val receiverType = receiverType ?: return false
27 |
28 | val isReceivedChildOfAndroidView = receiverType.isClassOrSubclassOf("android.view.View")
29 | val isMethodNameSetOnClickListener = methodIdentifier?.name == "setOnClickListener"
30 |
31 | return isReceivedChildOfAndroidView && isMethodNameSetOnClickListener
32 | }
33 |
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noMoreThanOneDateInstanceDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.Quantifier.Companion.moreThan
6 | import com.serchinastico.lin.dsl.RuleSet.Companion.anyOf
7 | import com.serchinastico.lin.dsl.detector
8 | import com.serchinastico.lin.dsl.file
9 | import com.serchinastico.lin.dsl.issue
10 | import org.jetbrains.uast.UCallExpression
11 | import org.jetbrains.uast.util.isConstructorCall
12 |
13 | @Detector
14 | fun noMoreThanOneDateInstance() = detector(
15 | issue(
16 | Scope.JAVA_FILE_SCOPE,
17 | "Date should only be initialized only once",
18 | """Creating multiple instances of Date is an indicator of not injecting your time on your code. That's a
19 | | classic issue when testing date/time related code. Centralize the creation of date objects on a single
20 | | class to be able to replace it in testing time.
21 | """.trimMargin()
22 | ),
23 | anyOf(
24 | file(moreThan(1)) { callExpression { suchThat { it.isDateConstructor } } },
25 | file { callExpression(moreThan(1)) { suchThat { it.isDateConstructor } } }
26 | )
27 | )
28 |
29 | private inline val UCallExpression.isDateConstructor: Boolean
30 | get() {
31 | val returnTypeCanonicalName = returnType?.canonicalText ?: return false
32 | return isConstructorCall() && returnTypeCanonicalName == "java.util.Date"
33 | }
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noFindViewByIdCallsDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.detector
6 | import com.serchinastico.lin.dsl.isClassOrSubclassOf
7 | import com.serchinastico.lin.dsl.issue
8 | import org.jetbrains.uast.UCallExpression
9 |
10 | @Detector
11 | fun noFindViewByIdCalls() = detector(
12 | issue(
13 | Scope.JAVA_FILE_SCOPE,
14 | "There should not be calls to findViewById",
15 | """Nowadays there are better ways to synthetize these calls into a more concise declaration with tools
16 | | like ButterKnife. See https://github.com/JakeWharton/butterknife or
17 | | https://kotlinlang.org/docs/tutorials/android-plugin.html#view-binding""".trimMargin()
18 | )
19 | ) {
20 | callExpression { suchThat { it.isFindViewByIdCall } }
21 | }
22 |
23 | private inline val UCallExpression.isFindViewByIdCall: Boolean
24 | get() {
25 | val receiverType = receiverType ?: return false
26 |
27 | val isReceiverChildOfActivityOrView =
28 | receiverType.isClassOrSubclassOf("android.app.Activity", "android.view.View")
29 | val isMethodFindViewById = methodIdentifier?.name == "findViewById"
30 | val isNotAndroidContentId = valueArguments.firstOrNull()?.asSourceString() == "android.R.id.content"
31 |
32 | return isReceiverChildOfActivityOrView && isMethodFindViewById && !isNotAndroidContentId
33 | }
34 |
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/noMoreThanOneGsonInstanceDetector.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.Quantifier.Companion.moreThan
6 | import com.serchinastico.lin.dsl.RuleSet.Companion.anyOf
7 | import com.serchinastico.lin.dsl.detector
8 | import com.serchinastico.lin.dsl.file
9 | import com.serchinastico.lin.dsl.issue
10 | import org.jetbrains.uast.UCallExpression
11 | import org.jetbrains.uast.util.isConstructorCall
12 |
13 | @Detector
14 | fun noMoreThanOneGsonInstance() = detector(
15 | issue(
16 | Scope.JAVA_FILE_SCOPE,
17 | "Gson should only be initialized only once",
18 | """Creating multiple instances of Gson may hurt performance and it's a common mistake to instantiate it for
19 | | simple serialization/deserialization. Use a single instance, be it with a classic singleton pattern or
20 | | other mechanism your dependency injector framework provides. This way you can also share the common
21 | | type adapters.
22 | """.trimMargin()
23 | ),
24 | anyOf(
25 | file(moreThan(1)) { callExpression { suchThat { it.isGsonConstructor } } },
26 | file { callExpression(moreThan(1)) { suchThat { it.isGsonConstructor } } }
27 | )
28 | )
29 |
30 | private inline val UCallExpression.isGsonConstructor: Boolean
31 | get() {
32 | val returnTypeCanonicalName = returnType?.canonicalText ?: return false
33 | return isConstructorCall() && returnTypeCanonicalName == "com.google.gson.Gson"
34 | }
--------------------------------------------------------------------------------
/dsl/src/main/kotlin/com/serchinastico/lin/dsl/visitor.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.dsl
2 |
3 | import org.jetbrains.uast.UElement
4 | import org.jetbrains.uast.visitor.UastVisitor
5 | import kotlin.reflect.KClass
6 | import kotlin.reflect.full.isSuperclassOf
7 |
8 | data class LinVisitor(val detector: LinDetector) : UastVisitor {
9 |
10 | private val validUElementClassNames: Set> by lazy {
11 | detector.roots.flatMap { it.allUElementSuperClasses() }.toSet()
12 | }
13 | private var root: MutableList = mutableListOf()
14 | private var currentNode: TreeNode? = null
15 |
16 | val reportedNodes: List
17 | get() {
18 | return detector.roots.matchesAny(root)
19 | }
20 |
21 | operator fun plusAssign(localVisitor: LinVisitor) {
22 | root.addAll(localVisitor.root)
23 | }
24 |
25 | override fun visitElement(node: UElement): Boolean {
26 | if (!validUElementClassNames.any { it.isSuperclassOf(node::class) }) {
27 | return false
28 | }
29 |
30 | val newChild = TreeNode(node, currentNode, mutableListOf())
31 | val newChildParent = currentNode.let { it?.children ?: root }
32 | newChildParent.add(newChild)
33 | currentNode = newChild
34 | return false
35 | }
36 |
37 | override fun afterVisitElement(node: UElement) {
38 | if (!validUElementClassNames.any { it.isSuperclassOf(node::class) }) {
39 | return
40 | }
41 | currentNode = currentNode?.parent
42 | }
43 | }
44 |
45 | fun LinRule.allUElementSuperClasses(): List> {
46 | val superClasses = mutableSetOf>()
47 | val nodesToProcess = mutableListOf(this)
48 |
49 | while (nodesToProcess.isNotEmpty()) {
50 | val currentNode = nodesToProcess.removeAt(0)
51 | superClasses.add(currentNode.elementType)
52 | nodesToProcess.addAll(currentNode.children)
53 | }
54 |
55 | return superClasses.toList()
56 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/test/src/main/kotlin/com/serchinastico/lin/test/LintTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.test
2 |
3 | import com.android.tools.lint.checks.infrastructure.TestFiles.java
4 | import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin
5 | import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
6 | import com.android.tools.lint.detector.api.Issue
7 |
8 | interface LintTest {
9 |
10 | val issue: Issue
11 |
12 | data class Snippet(val code: String, val language: Language)
13 |
14 | val String.inJava: Snippet get() = Snippet(this.trimMargin(), Language.Java)
15 | val String.inKotlin: Snippet get() = Snippet(this.trimMargin(), Language.Kotlin)
16 |
17 | data class ExpectBuilder(val issue: Issue, val snippets: List) {
18 | infix fun toHave(expectation: Expectation) {
19 | val result = lint()
20 | .files(
21 | *snippets.map {
22 | when (it.language) {
23 | Language.Java -> java(it.code)
24 | Language.Kotlin -> kotlin(it.code)
25 | }
26 | }.toTypedArray()
27 | )
28 | .issues(issue)
29 | .run()
30 |
31 | when (expectation) {
32 | Expectation.NoErrors -> result.expectClean()
33 | is Expectation.SomeWarning -> result.expectWarningCount(1)
34 | is Expectation.SomeError -> result.expectErrorCount(1)
35 | }.exhaustive
36 | }
37 |
38 | }
39 |
40 | fun expect(snippet: Snippet): ExpectBuilder = ExpectBuilder(issue, listOf(snippet))
41 | fun expect(vararg snippets: Snippet): ExpectBuilder = ExpectBuilder(issue, snippets.toList())
42 |
43 | enum class Language {
44 | Java, Kotlin
45 | }
46 |
47 | sealed class Expectation {
48 | object NoErrors : Expectation()
49 | data class SomeWarning(val fileName: String) : Expectation()
50 | data class SomeError(val fileName: String) : Expectation()
51 | }
52 | }
53 |
54 | private val Any?.exhaustive get() = Unit
--------------------------------------------------------------------------------
/detectors/src/main/kotlin/com/serchinastico/lin/detectors/wrongSyntheticViewReference.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.android.tools.lint.detector.api.Scope
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.Storage
6 | import com.serchinastico.lin.dsl.detector
7 | import com.serchinastico.lin.dsl.issue
8 | import org.jetbrains.uast.UExpression
9 | import org.jetbrains.uast.UImportStatement
10 |
11 | private val KOTLINX_SYNTHETIC_VIEW_IMPORT = """kotlinx\.android\.synthetic\.main\.(.*)""".toRegex()
12 | private val LAYOUT_EXPRESSION = """R\.layout\.(.*)""".toRegex()
13 |
14 | @Detector
15 | fun wrongSyntheticViewReference() = detector(
16 | issue(
17 | Scope.JAVA_FILE_SCOPE,
18 | "References to synthetic views not directly defined in this class or its ancestors layout",
19 | """Imports to kotlinx synthetic views other than the ones defined in the layout referenced in this
20 | | or its ancestor classes is mostly a typo. If you want to reference views from custom views abstract them
21 | | with methods in order to keep a low coupling with its specific implementation.
22 | """.trimMargin()
23 | )
24 | ) {
25 | import {
26 | suchThat {
27 |
28 | val importedLayout = storeImportedLayout(it) ?: return@suchThat false
29 | storage["Imported Layout"] = importedLayout
30 | it.isSyntheticViewImport
31 | }
32 | }
33 |
34 | expression {
35 | suchThat {
36 | it.isDifferentThanImportedLayout(storage) }
37 | }
38 | }
39 |
40 | private val UImportStatement.isSyntheticViewImport: Boolean
41 | get() {
42 | val importedString = importReference?.asRenderString() ?: return false
43 | return KOTLINX_SYNTHETIC_VIEW_IMPORT.matches(importedString)
44 | }
45 |
46 | private fun storeImportedLayout(node: UImportStatement): String? {
47 | val importedString = node.importReference?.asRenderString() ?: return null
48 | return KOTLINX_SYNTHETIC_VIEW_IMPORT
49 | .matchEntire(importedString)
50 | ?.groups
51 | ?.get(1)
52 | ?.value
53 | }
54 |
55 | private fun UExpression.isDifferentThanImportedLayout(
56 | storage: Storage
57 | ): Boolean {
58 | val importedLayout = storage["Imported Layout"] ?: return false
59 | val usedLayout = LAYOUT_EXPRESSION.matchEntire(asRenderString())
60 | ?.groups
61 | ?.get(1)
62 | ?.value ?: return false
63 | return usedLayout != importedLayout
64 | }
65 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Contributing
2 | ============
3 |
4 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
5 |
6 | If you would like to contribute code to this repository you can do so through GitHub by
7 | forking the repository and sending a pull request or opening an issue.
8 |
9 | When submitting code, please make every effort to follow existing conventions
10 | and style in order to keep the code as readable as possible. Please also make
11 | sure your code compiles, passes the tests and the checkstyle configured for this repository.
12 |
13 | Some tips that will help you to contribute to this repository:
14 |
15 | * Write clean code and test it.
16 | * Follow the repository code style.
17 | * Write descriptive commit messages.
18 | * No PR will be merged if automatic checks are not passing.
19 | * Review if your changes affects the repository documentation and update it.
20 | * Describe the PR content and don't hesitate to add comments to explain us why you've added or changed something.
21 |
22 | Code of conduct
23 | ---------------
24 |
25 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
26 |
27 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
28 |
29 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
30 |
31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
32 |
33 | This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
34 |
35 | Instances of abusive, harassing, or otherwise unacceptable behavior can be reported by sending me a message at [twitter](https://twitter.com/AtSerchinastico).
36 |
37 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org/version/1/3/0/), version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/](http://contributor-covenant.org/version/1/3/0/).
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/WrongSyntheticViewReferenceDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class WrongSyntheticViewReferenceDetectorTest : LintTest {
9 |
10 | private val resourcesFile = """
11 | |package foo;
12 | |
13 | |public final class R {
14 | | public static final class layout {
15 | | public static final int activity_test_1=0x7f010000;
16 | | public static final int activity_test_2=0x7f020000;
17 | | }
18 | |}
19 | """.inJava
20 |
21 | override val issue = WrongSyntheticViewReferenceDetector.issue
22 |
23 | @Test
24 | fun inKotlinActivity_whenImportReferencesFromDifferentLayout_detectsError() {
25 | expect(
26 | resourcesFile,
27 | """
28 | |package foo
29 | |
30 | |import foo.R
31 | |import kotlinx.android.synthetic.main.activity_test_2.*
32 | |
33 | |class TestClass: Activity() {
34 | | override val layoutId = R.layout.activity_test_1
35 | |}
36 | """.inKotlin
37 | ) toHave SomeError("src/foo/TestClass.kt")
38 | }
39 |
40 | @Test
41 | fun inKotlinActivity_whenImportReferencesFromBothSameAndDifferentLayout_detectsError() {
42 | expect(
43 | resourcesFile,
44 | """
45 | |package foo
46 | |
47 | |import foo.R
48 | |import kotlinx.android.synthetic.main.activity_test_1.*
49 | |import kotlinx.android.synthetic.main.activity_test_2.*
50 | |
51 | |class TestClass: Activity() {
52 | | override val layoutId = R.layout.activity_test_1
53 | |}
54 | """.inKotlin
55 | ) toHave SomeError("src/foo/TestClass.kt")
56 | }
57 |
58 | @Test
59 | fun inKotlinActivity_whenImportReferencesFromSameLayout_detectsNoErrors() {
60 | expect(
61 | resourcesFile,
62 | """
63 | |package foo
64 | |
65 | |import foo.R
66 | |import kotlinx.android.synthetic.main.activity_test_1.*
67 | |
68 | |class TestClass: Activity() {
69 | | override val layoutId = R.layout.activity_test_1
70 | |}
71 | """.inKotlin
72 | ) toHave NoErrors
73 | }
74 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoDataFrameworksFromAndroidClassDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoDataFrameworksFromAndroidClassDetectorTest : LintTest {
9 |
10 | override val issue = NoDataFrameworksFromAndroidClassDetector.issue
11 |
12 | @Test
13 | fun inJavaNonAndroidClass_whenFileHasFrameworkImport_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |import com.squareup.retrofit2.*;
19 | """.inJava
20 | ) toHave NoErrors
21 | }
22 |
23 | @Test
24 | fun inJavaAndroidClass_whenFileHasNoFrameworkImport_detectsNoErrors() {
25 | expect(
26 | """
27 | |package foo;
28 | |
29 | |import android.app.Activity;
30 | |import android.os.Bundle;
31 | |import android.view.View;
32 | |
33 | |public class TestClass extends Activity {}
34 | """.inJava
35 | ) toHave NoErrors
36 | }
37 |
38 | @Test
39 | fun inJavaAndroidClass_whenFileHasFrameworkImport_detectsErrors() {
40 | expect(
41 | """
42 | |package foo;
43 | |
44 | |import android.app.Activity;
45 | |import android.os.Bundle;
46 | |import android.view.View;
47 | |import com.squareup.retrofit2.*;
48 | |
49 | |public class TestClass extends Activity {}
50 | """.inJava
51 | ) toHave SomeError("src/foo/TestClass.java")
52 | }
53 |
54 | @Test
55 | fun inKotlinNonAndroidClass_whenFileHasFrameworkImport_detectsNoErrors() {
56 | expect(
57 | """
58 | |package foo
59 | |
60 | |import com.squareup.retrofit2.*
61 | """.inKotlin
62 | ) toHave NoErrors
63 | }
64 |
65 | @Test
66 | fun inKotlinAndroidClass_whenFileHasNoFrameworkImport_detectsNoErrors() {
67 | expect(
68 | """
69 | |package foo
70 | |
71 | |import android.app.Activity
72 | |import android.os.Bundle
73 | |import android.view.View
74 | |
75 | |class TestClass : Activity()
76 | """.inKotlin
77 | ) toHave NoErrors
78 | }
79 |
80 | @Test
81 | fun inKotlinAndroidClass_whenFileHasFrameworkImport_detectsErrors() {
82 | expect(
83 | """
84 | |package foo
85 | |
86 | |import android.app.Activity
87 | |import android.os.Bundle
88 | |import android.view.View
89 | |import com.squareup.retrofit2.*;
90 | |
91 | |class TestClass : Activity()
92 | """.inKotlin
93 | ) toHave SomeError("src/foo/TestClass.kt")
94 | }
95 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoPublicViewPropertiesDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoPublicViewPropertiesDetectorTest : LintTest {
9 |
10 | override val issue = NoPublicViewPropertiesDetector.issue
11 |
12 | @Test
13 | fun inJavaClass_whenViewFieldIsPrivate_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |import android.view.View;
19 | |
20 | |class TestClass {
21 | | private View view;
22 | |}
23 | """.inJava
24 | ) toHave NoErrors
25 | }
26 |
27 | @Test
28 | fun inJavaClass_whenViewFieldIsNonPrivate_detectsErrors() {
29 | expect(
30 | """
31 | |package foo;
32 | |
33 | |import android.view.View;
34 | |
35 | |class TestClass {
36 | | View view;
37 | |}
38 | """.inJava
39 | ) toHave SomeError("src/foo/TestClass.java")
40 | }
41 |
42 | @Test
43 | fun inJavaClass_whenViewFieldIsOverriding_detectsNoErrors() {
44 | expect(
45 | """
46 | |package foo;
47 | |
48 | |import java.lang.Override;
49 | |import android.view.View;
50 | |
51 | |class TestClass {
52 | | @Override View view;
53 | |}
54 | """.inJava
55 | ) toHave NoErrors
56 | }
57 |
58 | @Test
59 | fun inKotlinClass_whenViewFieldIsPrivate_detectsNoErrors() {
60 | expect(
61 | """
62 | |package foo
63 | |
64 | |import android.view.View
65 | |
66 | |class TestClass {
67 | | private val view: View = View()
68 | |}
69 | """.inKotlin
70 | ) toHave NoErrors
71 | }
72 |
73 | @Test
74 | fun inKotlinClass_whenViewFieldIsNotPrivate_detectsErrors() {
75 | expect(
76 | """
77 | |package foo
78 | |
79 | |import android.view.View
80 | |
81 | |class TestClass {
82 | | public val view: View = View(null)
83 | |}
84 | """.inKotlin
85 | ) toHave SomeError("src/foo/TestClass.kt")
86 | }
87 |
88 | @Test
89 | fun inKotlinClass_whenViewFieldIsOverriding_detectsErrors() {
90 | expect(
91 | """
92 | |package foo
93 | |
94 | |import android.view.View
95 | |
96 | |class TestClass {
97 | | public override val view: View = View(null)
98 | |}
99 | """.inKotlin
100 | ) toHave NoErrors
101 | }
102 | }
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at lin.dsl.project@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoPrintStackTraceCallsDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoPrintStackTraceCallsDetectorTest : LintTest {
9 |
10 | override val issue = NoPrintStackTraceCallsDetector.issue
11 |
12 | @Test
13 | fun inJavaNonThrowableClass_whenCallIsPrintStackTrace_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |class TestClass {
19 | | public static void main(String[] args) {
20 | | new TestClass().printStackTrace();
21 | | }
22 | |
23 | | private void printStackTrace() {}
24 | |}
25 | """.inJava
26 | ) toHave NoErrors
27 | }
28 |
29 | @Test
30 | fun inJavaThrowableChildClass_whenCallIsPrintStackTrace_detectsErrors() {
31 | expect(
32 | """
33 | |package foo;
34 | |
35 | |class TestClass extends java.lang.Throwable {
36 | | public static void main(String[] args) {
37 | | new TestClass().printStackTrace();
38 | | }
39 | |}
40 | """.inJava
41 | ) toHave SomeError("src/foo/TestClass.java")
42 | }
43 |
44 | @Test
45 | fun inJavaThrowableClass_whenCallIsPrintStackTrace_detectsErrors() {
46 | expect(
47 | """
48 | |package foo;
49 | |
50 | |class TestClass {
51 | | public static void main(String[] args) {
52 | | new java.lang.Throwable().printStackTrace();
53 | | }
54 | |}
55 | """.inJava
56 | ) toHave SomeError("src/foo/TestClass.java")
57 | }
58 |
59 | @Test
60 | fun inKotlinNonThrowableClass_whenCallIsPrintStackTrace_detectsNoErrors() {
61 | expect(
62 | """
63 | |package foo
64 | |
65 | |class TestClass {
66 | | fun main(args: Array) {
67 | | TestClass().printStackTrace();
68 | | }
69 | |
70 | | private fun printStackTrace() {}
71 | |}
72 | """.inKotlin
73 | ) toHave NoErrors
74 | }
75 |
76 | @Test
77 | fun inKotlinThrowableChildClass_whenCallIsPrintStackTrace_detectsErrors() {
78 | expect(
79 | """
80 | |package foo
81 | |
82 | |class TestClass: kotlin.Throwable() {
83 | | fun main(args: Array) {
84 | | TestClass().printStackTrace();
85 | | }
86 | |}
87 | """.inKotlin
88 | ) toHave SomeError("src/foo/TestClass.kt")
89 | }
90 |
91 | @Test
92 | fun inKotlinThrowableClass_whenCallIsPrintStackTrace_detectsErrors() {
93 | expect(
94 | """
95 | |package foo
96 | |
97 | |class TestClass {
98 | | fun main(args: Array) {
99 | | kotlin.Throwable().printStackTrace();
100 | | }
101 | |}
102 | """.inKotlin
103 | ) toHave SomeError("src/foo/TestClass.kt")
104 | }
105 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoSetOnClickListenerCallsDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoSetOnClickListenerCallsDetectorTest : LintTest {
9 |
10 | override val issue = NoSetOnClickListenerCallsDetector.issue
11 |
12 | @Test
13 | fun inJavaClass_whenCallIsNotSetOnClickListener_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |import android.view.View;
19 | |
20 | |class TestClass implements View.OnClickListener {
21 | | private View view;
22 | |
23 | | public void main(String[] args) {
24 | | view.doNotSetOnClickListener(this);
25 | | }
26 | |}
27 | """.inJava
28 | ) toHave NoErrors
29 | }
30 |
31 | @Test
32 | fun inJavaClass_whenCallIsSetOnClickListener_detectsError() {
33 | expect(
34 | """
35 | |package foo;
36 | |
37 | |import android.view.View;
38 | |
39 | |class TestClass implements View.OnClickListener {
40 | | private View view;
41 | |
42 | | public void main(String[] args) {
43 | | view.setOnClickListener(this);
44 | | }
45 | |}
46 | """.inJava
47 | ) toHave SomeError("src/foo/TestClass.java")
48 | }
49 |
50 | @Test
51 | fun inJavaClass_whenCallIsNotAndroidViewSetOnClickListener_detectsNoErrors() {
52 | expect(
53 | """
54 | |package foo;
55 | |
56 | |class TestClass implements View.OnClickListener {
57 | | public void main(String[] args) {
58 | | setOnClickListener(this);
59 | | }
60 | |
61 | | private void setOnClickListener(View.OnClickListener listener) {}
62 | |}
63 | """.inJava
64 | ) toHave NoErrors
65 | }
66 |
67 | @Test
68 | fun inKotlinClass_whenCallIsNotSetOnClickListener_detectsNoErrors() {
69 | expect(
70 | """
71 | |package foo
72 | |
73 | |import android.view.View
74 | |
75 | |class TestClass: View.OnClickListener {
76 | | private lateinit var view: View
77 | |
78 | | public fun main(args: Array) {
79 | | view.doNotSetOnClickListener(this)
80 | | }
81 | |}
82 | """.inKotlin
83 | ) toHave NoErrors
84 | }
85 |
86 | @Test
87 | fun inKotlinClass_whenCallIsSetOnClickListener_detectsError() {
88 | expect(
89 | """
90 | |package foo
91 | |
92 | |import android.view.View
93 | |
94 | |class TestClass: View.OnClickListener {
95 | | private lateinit var view: View
96 | |
97 | | public fun main(args: Array) {
98 | | view.setOnClickListener(this)
99 | | }
100 | |}
101 | """.inKotlin
102 | ) toHave SomeError("src/foo/TestClass.kt")
103 | }
104 |
105 | @Test
106 | fun inKotlinClass_whenCallIsNotAndroidViewSetOnClickListener_detectsNoErrors() {
107 | expect(
108 | """
109 | |package foo
110 | |
111 | |class TestClass: View.OnClickListener {
112 | | public fun main(args: Array) {
113 | | setOnClickListener(this)
114 | | }
115 | |
116 | | private fun setOnClickListener(listener: View.OnClickListener) {}
117 | |}
118 | """.inKotlin
119 | ) toHave NoErrors
120 | }
121 | }
--------------------------------------------------------------------------------
/dsl/src/main/kotlin/com/serchinastico/lin/dsl/extensions.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.dsl
2 |
3 | import com.android.tools.lint.detector.api.*
4 | import com.intellij.lang.Language
5 | import com.intellij.psi.PsiType
6 | import com.intellij.psi.impl.source.PsiClassReferenceType
7 | import com.intellij.psi.impl.source.PsiImmediateClassType
8 | import org.jetbrains.kotlin.asJava.classes.KtLightClass
9 | import org.jetbrains.kotlin.psi.KtClass
10 | import org.jetbrains.uast.*
11 | import org.jetbrains.uast.java.JavaUDefaultCaseExpression
12 | import org.jetbrains.uast.kotlin.KotlinUClass
13 |
14 | val Any?.exhaustive get() = Unit
15 |
16 | fun Context.report(issue: Issue, position: Location, source: UElement) {
17 | report(
18 | issue,
19 | Location.create(file, position.start ?: DefaultPosition(0, 0, 0), position.end).withSource(source),
20 | issue.getBriefDescription(TextFormat.TEXT)
21 | )
22 | }
23 |
24 | val USwitchExpression.clauses: List
25 | get() = body.expressions.mapNotNull { it as? USwitchClauseExpression }
26 |
27 | val USwitchClauseExpression.isElseBranch: Boolean
28 | get() = caseValues.isEmpty() || caseValues.any { it is JavaUDefaultCaseExpression }
29 |
30 | val PsiType.isSealed: Boolean
31 | get() = when (this) {
32 | is PsiClassReferenceType -> {
33 | val resolvedType = resolve()
34 | when (resolvedType) {
35 | is KtLightClass -> (resolvedType.kotlinOrigin as? KtClass)?.isSealed() ?: false
36 | else -> false
37 | }
38 | }
39 | else -> false
40 | }
41 |
42 | val PsiType.isEnum: Boolean
43 | get() = when (this) {
44 | is PsiImmediateClassType -> resolve()?.isEnum ?: false
45 | is PsiClassReferenceType -> resolve()?.isEnum ?: false
46 | else -> false
47 | }
48 |
49 | val UField.isPrivate: Boolean
50 | get() {
51 | when {
52 | language.isJava -> return visibility == UastVisibility.PRIVATE
53 | language.isKotlin -> {
54 | val parent = (uastParent ?: return false) as? KotlinUClass ?: return false
55 |
56 | val propertyAccessorName = "get${name.capitalize()}"
57 | val propertyAccessor = parent.methods
58 | .filter { it.name == propertyAccessorName }
59 | .filter { it.parameters.isEmpty() }
60 | .firstOrNull { it.returnType == type }
61 |
62 | val accessor: UDeclaration = propertyAccessor ?: this
63 | return accessor.visibility == UastVisibility.PRIVATE
64 | }
65 | else -> return false
66 | }
67 | }
68 |
69 | val UField.isOverride: Boolean
70 | get() = when {
71 | language.isJava -> annotations.any { it.qualifiedName == Override::class.qualifiedName }
72 | // The only way to see if a property is overriding in kotlin is to see if it has the same
73 | // signature than any ancestor class property. This is a quick correct-in-most-cases fix
74 | language.isKotlin -> text.contains("override ")
75 | else -> false
76 | }
77 |
78 | val Language.isKotlin: Boolean
79 | get() = this == Language.findLanguageByID("kotlin")
80 | val Language.isJava: Boolean
81 | get() = this == Language.findLanguageByID("JAVA")
82 |
83 | fun UVariable.isClassOrSubclassOf(vararg fullyQualifiedNames: String): Boolean =
84 | allIsATypes.any { type -> fullyQualifiedNames.asList().any { type.canonicalText == it } }
85 |
86 | fun PsiType.isClassOrSubclassOf(vararg fullyQualifiedNames: String): Boolean =
87 | allIsATypes.any { type -> fullyQualifiedNames.asList().any { type.canonicalText == it } }
88 |
89 | val UVariable.allIsATypes: List
90 | get() = typeReference?.type?.allIsATypes ?: type.allIsATypes
91 |
92 | val PsiType.allIsATypes: List
93 | get() = superTypes.asList() + this
94 |
95 | val UTypeReferenceExpression.isAndroidFrameworkType: Boolean
96 | get() = getQualifiedName()?.let { name ->
97 | listOf(
98 | "android.app.",
99 | "android.support.v4.app"
100 | ).any { name.startsWith(it) }
101 | } ?: false
102 |
103 | val UImportStatement.isFrameworkLibraryImport: Boolean
104 | get() {
105 | val importedPackageName = importReference?.asRenderString() ?: return false
106 |
107 | return listOf(
108 | "com.squareup.retrofit",
109 | "com.squareup.retrofit2",
110 | "com.squareup.okhttp",
111 | "com.android.volley",
112 | "com.mcxiaoke.volley",
113 | "androidx.room",
114 | "android.arch.persistence.room",
115 | "android.content.SharedPreferences",
116 | "android.database",
117 | "java.net"
118 | ).any { importedPackageName.startsWith(it) }
119 | }
120 |
121 | val UElement.classesInSameFile: List
122 | get() = getContainingUFile()?.classes ?: emptyList()
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoMoreThanOneDateInstanceDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoMoreThanOneDateInstanceDetectorTest : LintTest {
9 |
10 | override val issue = NoMoreThanOneDateInstanceDetector.issue
11 |
12 | @Test
13 | fun inJavaClass_whenDateIsNotInstantiated_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |import java.util.Date;
19 | |
20 | |class TestClass {
21 | | public void main(String[] args) {}
22 | |}
23 | """.inJava
24 | ) toHave NoErrors
25 | }
26 |
27 | @Test
28 | fun inJavaClass_whenDateIsInstantiatedOnce_detectsNoErrors() {
29 | expect(
30 | """
31 | |package foo;
32 | |
33 | |import java.util.Date;
34 | |
35 | |class TestClass {
36 | | public void main(String[] args) {
37 | | new Date();
38 | | }
39 | |}
40 | """.inJava
41 | ) toHave NoErrors
42 | }
43 |
44 | @Test
45 | fun inJavaClass_whenDateIsInstantiatedTwice_detectsError() {
46 | expect(
47 | """
48 | |package foo;
49 | |
50 | |import java.util.Date;
51 | |
52 | |class TestClass {
53 | | public void main(String[] args) {
54 | | new Date();
55 | | new Date();
56 | | }
57 | |}
58 | """.inJava
59 | ) toHave SomeError("src/foo/TestClass.java")
60 | }
61 |
62 | @Test
63 | fun inJavaClass_whenDateIsInstantiatedTwiceInDifferentFiles_detectsErrors() {
64 | expect(
65 | """
66 | |package foo;
67 | |
68 | |import java.util.Date;
69 | |
70 | |class TestClass1 {
71 | | public void main(String[] args) {
72 | | new Date();
73 | | }
74 | |}
75 | """.inJava,
76 | """
77 | |package foo;
78 | |
79 | |import java.util.Date;
80 | |
81 | |class TestClass2 {
82 | | public void main(String[] args) {
83 | | new Date();
84 | | }
85 | |}
86 | """.inJava
87 | ) toHave SomeError("project0")
88 | }
89 |
90 | @Test
91 | fun inKotlinClass_whenDateIsNotInstantiated_detectsNoErrors() {
92 | expect(
93 | """
94 | |package foo
95 | |
96 | |import java.util.Date;
97 | |
98 | |class TestClass {
99 | | public fun main(args: Array) {}
100 | |}
101 | """.inKotlin
102 | ) toHave NoErrors
103 | }
104 |
105 | @Test
106 | fun inKotlinClass_whenDateIsInstantiatedOnce_detectsNoErrors() {
107 | expect(
108 | """
109 | |package foo
110 | |
111 | |import java.util.Date;
112 | |
113 | |class TestClass {
114 | | public fun main(args: Array) {
115 | | Date()
116 | | }
117 | |}
118 | """.inKotlin
119 | ) toHave NoErrors
120 | }
121 |
122 | @Test
123 | fun inKotlinClass_whenDateIsInstantiatedTwice_detectsError() {
124 | expect(
125 | """
126 | |package foo
127 | |
128 | |import java.util.Date;
129 | |
130 | |class TestClass {
131 | | public fun main(args: Array) {
132 | | val date1 = Date()
133 | | val date2 = Date()
134 | | }
135 | |}
136 | """.inKotlin
137 | ) toHave SomeError("src/foo/TestClass.kt")
138 | }
139 |
140 | @Test
141 | fun inKotlinClass_whenDateIsInstantiatedTwiceInTwoFiles_detectsErrors() {
142 | expect(
143 | """
144 | |package foo
145 | |
146 | |import java.util.Date;
147 | |
148 | |class TestClass1 {
149 | | public fun main(args: Array) {
150 | | Date()
151 | | }
152 | |}
153 | """.inKotlin,
154 | """
155 | |package foo
156 | |
157 | |import java.util.Date;
158 | |
159 | |class TestClass2 {
160 | | public fun main(args: Array) {
161 | | Date()
162 | | }
163 | |}
164 | """.inKotlin
165 | ) toHave SomeError("project0")
166 | }
167 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoMoreThanOneGsonInstanceDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoMoreThanOneGsonInstanceDetectorTest : LintTest {
9 |
10 | override val issue = NoMoreThanOneGsonInstanceDetector.issue
11 |
12 | private val gsonLibrary =
13 | """|package com.google.gson
14 | |
15 | |class Gson
16 | """.inKotlin
17 |
18 | @Test
19 | fun inJavaClass_whenGsonIsNotInstantiated_detectsNoErrors() {
20 | expect(
21 | gsonLibrary,
22 | """
23 | |package foo;
24 | |
25 | |import com.google.gson.Gson;
26 | |
27 | |class TestClass {
28 | | public void main(String[] args) {}
29 | |}
30 | """.inJava
31 | ) toHave NoErrors
32 | }
33 |
34 | @Test
35 | fun inJavaClass_whenGsonIsInstantiatedOnce_detectsNoErrors() {
36 | expect(
37 | gsonLibrary,
38 | """
39 | |package foo;
40 | |
41 | |import com.google.gson.Gson;
42 | |
43 | |class TestClass {
44 | | public void main(String[] args) {
45 | | new Gson();
46 | | }
47 | |}
48 | """.inJava
49 | ) toHave NoErrors
50 | }
51 |
52 | @Test
53 | fun inJavaClass_whenGsonIsInstantiatedTwice_detectsError() {
54 | expect(
55 | gsonLibrary,
56 | """
57 | |package foo;
58 | |
59 | |import com.google.gson.Gson;
60 | |
61 | |class TestClass {
62 | | public void main(String[] args) {
63 | | new Gson();
64 | | new Gson();
65 | | }
66 | |}
67 | """.inJava
68 | ) toHave SomeError("src/foo/TestClass.java")
69 | }
70 |
71 | @Test
72 | fun inJavaClass_whenGsonIsInstantiatedTwiceInDifferentFiles_detectsErrors() {
73 | expect(
74 | gsonLibrary,
75 | """
76 | |package foo;
77 | |
78 | |import com.google.gson.Gson;
79 | |
80 | |class TestClass1 {
81 | | public void main(String[] args) {
82 | | new Gson();
83 | | }
84 | |}
85 | """.inJava,
86 | """
87 | |package foo;
88 | |
89 | |import com.google.gson.Gson;
90 | |
91 | |class TestClass2 {
92 | | public void main(String[] args) {
93 | | new Gson();
94 | | }
95 | |}
96 | """.inJava
97 | ) toHave SomeError("project0")
98 | }
99 |
100 | @Test
101 | fun inKotlinClass_whenGsonIsNotInstantiated_detectsNoErrors() {
102 | expect(
103 | gsonLibrary,
104 | """
105 | |package foo
106 | |
107 | |import com.google.gson.Gson
108 | |
109 | |class TestClass {
110 | | public fun main(args: Array) {}
111 | |}
112 | """.inKotlin
113 | ) toHave NoErrors
114 | }
115 |
116 | @Test
117 | fun inKotlinClass_whenGsonIsInstantiatedOnce_detectsNoErrors() {
118 | expect(
119 | gsonLibrary,
120 | """
121 | |package foo
122 | |
123 | |import com.google.gson.Gson
124 | |
125 | |class TestClass {
126 | | public fun main(args: Array) {
127 | | Gson()
128 | | }
129 | |}
130 | """.inKotlin
131 | ) toHave NoErrors
132 | }
133 |
134 | @Test
135 | fun inKotlinClass_whenGsonIsInstantiatedTwice_detectsError() {
136 | expect(
137 | gsonLibrary,
138 | """
139 | |package foo
140 | |
141 | |import com.google.gson.Gson
142 | |
143 | |class TestClass {
144 | | public fun main(args: Array) {
145 | | val gson1 = Gson()
146 | | val gson2 = Gson()
147 | | }
148 | |}
149 | """.inKotlin
150 | ) toHave SomeError("src/foo/TestClass.kt")
151 | }
152 |
153 | @Test
154 | fun inKotlinClass_whenGsonIsInstantiatedTwiceInTwoFiles_detectsErrors() {
155 | expect(
156 | gsonLibrary,
157 | """
158 | |package foo
159 | |
160 | |import com.google.gson.Gson
161 | |
162 | |class TestClass1 {
163 | | public fun main(args: Array) {
164 | | Gson()
165 | | }
166 | |}
167 | """.inKotlin,
168 | """
169 | |package foo
170 | |
171 | |import com.google.gson.Gson
172 | |
173 | |class TestClass2 {
174 | | public fun main(args: Array) {
175 | | Gson()
176 | | }
177 | |}
178 | """.inKotlin
179 | ) toHave SomeError("project0")
180 | }
181 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoFindViewByIdCallsDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoFindViewByIdCallsDetectorTest : LintTest {
9 |
10 | override val issue = NoFindViewByIdCallsDetector.issue
11 |
12 | private val resourcesFile = """
13 | |package foo;
14 | |
15 | |public final class R {
16 | | public static final class id {
17 | | public static final int my_button=0x7f010000;
18 | | }
19 | |}
20 | """.inJava
21 | private val androidResourcesFile = """
22 | |package android;
23 | |
24 | |public final class R {
25 | | public static final class id {
26 | | public static final int content=0x7f010000;
27 | | }
28 | |}
29 | """.inJava
30 |
31 |
32 | @Test
33 | fun inJavaClass_whenCallIsNotFindViewById_detectsNoErrors() {
34 | expect(
35 | resourcesFile,
36 | """
37 | |package foo;
38 | |
39 | |import android.view.View;
40 | |import foo.R;
41 | |
42 | |class TestClass {
43 | | private View view;
44 | |
45 | | public void main(String[] args) {
46 | | view.doNotFindViewById(R.id.my_button);
47 | | }
48 | |}
49 | """.inJava
50 | ) toHave NoErrors
51 | }
52 |
53 | @Test
54 | fun inJavaClass_whenCallIsFindViewById_detectsError() {
55 | expect(
56 | resourcesFile,
57 | """
58 | |package foo;
59 | |
60 | |import android.view.View;
61 | |import foo.R;
62 | |
63 | |class TestClass {
64 | | private View view;
65 | |
66 | | public void main(String[] args) {
67 | | view.findViewById(R.id.my_button);
68 | | }
69 | |}
70 | """.inJava
71 | ) toHave SomeError("src/foo/TestClass.java")
72 | }
73 |
74 | @Test
75 | fun inJavaClass_whenCallIsFindViewByIdToAndroidContent_detectsNoError() {
76 | expect(
77 | androidResourcesFile,
78 | resourcesFile,
79 | """
80 | |package foo;
81 | |
82 | |import android.view.View;
83 | |
84 | |class TestClass {
85 | | private View view;
86 | |
87 | | public void main(String[] args) {
88 | | view.findViewById(android.R.id.content);
89 | | }
90 | |}
91 | """.inJava
92 | ) toHave NoErrors
93 | }
94 |
95 | @Test
96 | fun inJavaClass_whenCallIsNotAndroidViewSetOnClickListener_detectsNoErrors() {
97 | expect(
98 | resourcesFile,
99 | """
100 | |package foo;
101 | |
102 | |import foo.R;
103 | |
104 | |class TestClass {
105 | | public void main(String[] args) {
106 | | findViewById(R.id.my_button);
107 | | }
108 | |
109 | | private void findViewById(int id) {}
110 | |}
111 | """.inJava
112 | ) toHave NoErrors
113 | }
114 |
115 | @Test
116 | fun inKotlinClass_whenCallIsNotFindViewById_detectsNoErrors() {
117 | expect(
118 | resourcesFile,
119 | """
120 | |package foo
121 | |
122 | |import android.view.View
123 | |import foo.R
124 | |
125 | |class TestClass {
126 | | private lateinit var view: View
127 | |
128 | | public fun main(args: Array) {
129 | | view.doNotFindViewById(R.id.my_button)
130 | | }
131 | |}
132 | """.inKotlin
133 | ) toHave NoErrors
134 | }
135 |
136 | @Test
137 | fun inKotlinClass_whenCallIsFindViewById_detectsError() {
138 | expect(
139 | resourcesFile,
140 | """
141 | |package foo
142 | |
143 | |import android.view.View
144 | |import foo.R
145 | |
146 | |class TestClass {
147 | | private lateinit var view: View
148 | |
149 | | public fun main(args: Array) {
150 | | view.findViewById(R.id.my_button)
151 | | }
152 | |}
153 | """.inKotlin
154 | ) toHave SomeError("src/foo/TestClass.kt")
155 | }
156 |
157 | @Test
158 | fun inKotlinClass_whenCallIsFindViewByIdToAndroidContent_detectsNoError() {
159 | expect(
160 | androidResourcesFile,
161 | resourcesFile,
162 | """
163 | |package foo
164 | |
165 | |import android.view.View
166 | |
167 | |class TestClass {
168 | | private lateinit var view: View
169 | |
170 | | public fun main(args: Array) {
171 | | view.findViewById(android.R.id.content)
172 | | }
173 | |}
174 | """.inKotlin
175 | ) toHave NoErrors
176 | }
177 |
178 | @Test
179 | fun inKotlinClass_whenCallIsNotAndroidViewSetOnClickListener_detectsNoErrors() {
180 | expect(
181 | """
182 | |package foo
183 | |
184 | |import foo.R
185 | |
186 | |class TestClass {
187 | | public fun main(args: Array) {
188 | | findViewById(R.id.my_button)
189 | | }
190 | |
191 | | private fun findViewById(id: Int) {}
192 | |}
193 | """.inKotlin
194 | ) toHave NoErrors
195 | }
196 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/NoElseInSwitchWithEnumOrSealedDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class NoElseInSwitchWithEnumOrSealedDetectorTest : LintTest {
9 |
10 | override val issue = NoElseInSwitchWithEnumOrSealedDetector.issue
11 |
12 | @Test
13 | fun inJavaSwitchStatement_whenAllCasesAreCovered_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |class TestClass {
19 | | public static void main(String[] args) {
20 | | NumberUpToFive number = NumberUpToFive.Four;
21 | | switch (number) {
22 | | case One: System.out.println("One"); break;
23 | | case Two: System.out.println("Two"); break;
24 | | case Three: System.out.println("Three"); break;
25 | | case Four: System.out.println("Four"); break;
26 | | case Five: System.out.println("Five"); break;
27 | | }
28 | | }
29 | |
30 | | private enum NumberUpToFive {
31 | | One, Two, Three, Four, Five
32 | | }
33 | |}
34 | """.inJava
35 | ) toHave NoErrors
36 | }
37 |
38 | @Test
39 | fun inJavaSwitchStatement_whenDefaultCaseIsUsed_detectsErrors() {
40 | expect(
41 | """
42 | |package foo;
43 | |
44 | |class TestClass {
45 | | public static void main(String[] args) {
46 | | NumberUpToFive number = NumberUpToFive.Four;
47 | | switch (number) {
48 | | case One: System.out.println("One"); break;
49 | | case Two: System.out.println("Two"); break;
50 | | case Three: System.out.println("Three"); break;
51 | | case Four: System.out.println("Four"); break;
52 | | default: System.out.println("Five"); break;
53 | | }
54 | | }
55 | |
56 | | private enum NumberUpToFive {
57 | | One, Two, Three, Four, Five
58 | | }
59 | |}
60 | """.inJava
61 | ) toHave SomeError("src/foo/TestClass.java")
62 | }
63 |
64 | @Test
65 | fun inJavaSwitchStatement_whenSwitchArgumentIsFunctionParameter_detectsNoErrors() {
66 | expect(
67 | """
68 | |package foo;
69 | |
70 | |class TestClass {
71 | | public static void main(NumberUpToFive number) {
72 | | switch (number) {
73 | | case One: System.out.println("One"); break;
74 | | case Two: System.out.println("Two"); break;
75 | | case Three: System.out.println("Three"); break;
76 | | case Four: System.out.println("Four"); break;
77 | | case Five: System.out.println("Five"); break;
78 | | }
79 | | }
80 | |
81 | | private enum NumberUpToFive {
82 | | One, Two, Three, Four, Five
83 | | }
84 | |}
85 | """.inJava
86 | ) toHave NoErrors
87 | }
88 |
89 | @Test
90 | fun inKotlinWhenStatement_whenAllCasesAreCovered_detectsNoErrors() {
91 | expect(
92 | """
93 | |package foo
94 | |
95 | |class TestClass {
96 | | fun main(args: Array) {
97 | | val number = NumberUpToFive.Four
98 | | when (number) {
99 | | One -> System.out.println("One")
100 | | Two -> System.out.println("Two")
101 | | Three -> System.out.println("Three")
102 | | Four -> System.out.println("Four")
103 | | Five -> System.out.println("Five")
104 | | }
105 | | }
106 | |
107 | | enum class NumberUpToFive {
108 | | One, Two, Three, Four, Five
109 | | }
110 | |}
111 | """.inKotlin
112 | ) toHave NoErrors
113 | }
114 |
115 | @Test
116 | fun inKotlinWhenStatement_whenElseIsUsed_detectsErrors() {
117 | expect(
118 | """
119 | |package foo
120 | |
121 | |class TestClass {
122 | | fun main(args: Array) {
123 | | val number = NumberUpToFive.Four
124 | | when (number) {
125 | | One -> System.out.println("One")
126 | | Two -> System.out.println("Two")
127 | | Three -> System.out.println("Three")
128 | | Four -> System.out.println("Four")
129 | | else -> System.out.println("Five")
130 | | }
131 | | }
132 | |
133 | | enum class NumberUpToFive {
134 | | One, Two, Three, Four, Five
135 | | }
136 | |}
137 | """.inKotlin
138 | ) toHave SomeError("src/foo/TestClass.kt")
139 | }
140 |
141 |
142 | @Test
143 | fun inKotlinWhenExpression_whenWhenArgumentIsFunctionParameter_detectsErrors() {
144 | expect(
145 | """
146 | |package foo
147 | |
148 | |class TestClass {
149 | | fun main(number: NumberUpToFive) = when (number) {
150 | | One -> System.out.println("One")
151 | | Two -> System.out.println("Two")
152 | | Three -> System.out.println("Three")
153 | | Four -> System.out.println("Four")
154 | | else -> System.out.println("Five")
155 | | }
156 | |
157 | | enum class NumberUpToFive {
158 | | One, Two, Three, Four, Five
159 | | }
160 | |}
161 | """.inKotlin
162 | ) toHave SomeError("src/foo/TestClass.kt")
163 | }
164 |
165 | @Test
166 | fun inKotlinWhenExpression_whenArgumentTypeIsSealedClass_detectsErrors() {
167 | expect(
168 | """
169 | |package foo
170 | |
171 | |class TestClass {
172 | | fun main(number: NumberUpToFive) = when (number) {
173 | | One -> System.out.println("One")
174 | | Two -> System.out.println("Two")
175 | | Three -> System.out.println("Three")
176 | | Four -> System.out.println("Four")
177 | | else -> System.out.println("Five")
178 | | }
179 | |
180 | | sealed class NumberUpToFive {
181 | | object One: NumberUpToFive()
182 | | object Two: NumberUpToFive()
183 | | object Three: NumberUpToFive()
184 | | object Four: NumberUpToFive()
185 | | object Five: NumberUpToFive()
186 | | }
187 | |}
188 | """.inKotlin
189 | ) toHave SomeError("src/foo/TestClass.kt")
190 | }
191 | }
--------------------------------------------------------------------------------
/dsl/src/main/kotlin/com/serchinastico/lin/dsl/match.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.dsl
2 |
3 | import com.serchinastico.lin.dsl.MatchResult.Companion.NoMatch
4 | import com.serchinastico.lin.dsl.MatchResult.Companion.maybe
5 | import org.jetbrains.uast.UElement
6 | import kotlin.reflect.full.isSuperclassOf
7 |
8 |
9 | data class TreeNode(
10 | val element: UElement,
11 | var parent: TreeNode?,
12 | val children: MutableList
13 | ) {
14 | override fun toString(): String {
15 | return "TreeNode(children=$children, element=$element)"
16 | }
17 | }
18 |
19 | private data class MatchLinContext(
20 | override val storage: Storage = mutableMapOf(),
21 | val counterOfQuantifiers: Counters = mapOf()
22 | ) : LinContext {
23 | fun plus(quantifier: Quantifier): MatchLinContext =
24 | copy(counterOfQuantifiers = counterOfQuantifiers.plusOne(quantifier))
25 | }
26 |
27 | private data class MatchResult(
28 | val didFoundMatch: Boolean,
29 | val elementsMatching: List
30 | ) {
31 | companion object {
32 | val NoMatch: MatchResult = MatchResult(false, emptyList())
33 | fun maybe(didMatch: Boolean) = MatchResult(didMatch, emptyList())
34 | }
35 |
36 | fun and(block: (MatchResult) -> MatchResult): MatchResult {
37 | return if (didFoundMatch) {
38 | plus(block(this))
39 | } else {
40 | this
41 | }
42 | }
43 |
44 | fun plus(result: MatchResult): MatchResult =
45 | copy(
46 | didFoundMatch = didFoundMatch && result.didFoundMatch,
47 | elementsMatching = elementsMatching.plus(result.elementsMatching)
48 | )
49 |
50 | fun plus(element: UElement): MatchResult =
51 | copy(elementsMatching = elementsMatching.plus(element))
52 | }
53 |
54 | private typealias Counters = Map
55 |
56 | private fun Counters.getCount(quantifier: Quantifier): Int = this.getOrDefault(quantifier, 0)
57 | private fun Counters.plusOne(quantifier: Quantifier): Counters = plus(quantifier to getCount(quantifier) + 1)
58 |
59 | fun List>.matchesAny(code: List): List =
60 | stream()
61 | .map { matchesAll(code, listOf(it)) }
62 | .filter { it.isNotEmpty() }
63 | .findFirst()
64 | .orElse(emptyList())
65 |
66 | private fun matchesAll(codeNodes: List, rules: List>): List =
67 | matchesAll(codeNodes, rules, MatchLinContext()).let { if (it.didFoundMatch) it.elementsMatching else emptyList() }
68 |
69 | private fun matchesAll(
70 | codeNodes: List,
71 | rules: List>,
72 | context: MatchLinContext
73 | ): MatchResult {
74 | // We finished processing rules and found a match, we succeeded as long as quantifiers match their requirements
75 | if (rules.isEmpty()) {
76 | return maybe(context.counterOfQuantifiers.allQualifiersMeetRequirements(rules))
77 | }
78 |
79 | // We don't have more code and there are still rules, see if there are missing matches
80 | if (codeNodes.isEmpty()) {
81 | return maybe(rules.none { it.quantifier == Quantifier.Any } &&
82 | context.counterOfQuantifiers.allQualifiersMeetRequirements(rules))
83 | }
84 |
85 | val headCodeNode = codeNodes.first()
86 | val tailCodeNodes = codeNodes.drop(1)
87 |
88 | val applicableRules = rules.filter { it.elementType.isSuperclassOf(headCodeNode.element::class) }
89 |
90 | // We first check if there is any rule that is impossible to continue matching
91 | // e.g. All rule failing, Times rule greater than its counter
92 | val isPossibleToContinueMatching = applicableRules
93 | .all { it.isPossibleToContinueMatching(headCodeNode.element, context) }
94 |
95 | if (!isPossibleToContinueMatching) {
96 | return NoMatch
97 | }
98 |
99 | val result = applicableRules
100 | .map { it to context.copy() }
101 | .filter { it.first.matches(headCodeNode.element, it.second) }
102 | .stream()
103 | .map { it.first.matchesChildren(headCodeNode, tailCodeNodes, rules, it.second) }
104 | .findFirst()
105 | .orElse(NoMatch)
106 |
107 | return when {
108 | result.didFoundMatch -> result.plus(headCodeNode.element)
109 | rules.none { it.quantifier == Quantifier.All } -> matchesAll(tailCodeNodes, rules, context.copy())
110 | else -> NoMatch
111 | }
112 | }
113 |
114 | private fun LinRule.matchesChildren(
115 | head: TreeNode,
116 | tail: List,
117 | rules: List>,
118 | context: MatchLinContext
119 | ): MatchResult {
120 | return when (quantifier) {
121 | Quantifier.All ->
122 | matchesAll(head.children, children, context)
123 | .and { matchesAll(tail, rules, context) }
124 | Quantifier.Any ->
125 | matchesAll(head.children, children, context)
126 | .and { matchesAll(tail, rules.minus(this@matchesChildren), context) }
127 | is Quantifier.Times, is Quantifier.AtLeast, is Quantifier.AtMost ->
128 | matchesAll(head.children, children, context)
129 | .and {
130 | matchesAll(
131 | tail,
132 | rules,
133 | context.copy(counterOfQuantifiers = context.counterOfQuantifiers.plusOne(quantifier))
134 | )
135 | }
136 | }
137 | }
138 |
139 | private fun Counters.allQualifiersMeetRequirements(rules: List>): Boolean = rules.all { rule ->
140 | val quantifier = rule.quantifier
141 | when (quantifier) {
142 | Quantifier.All, Quantifier.Any -> true
143 | is Quantifier.Times -> getCount(quantifier) == quantifier.times
144 | is Quantifier.AtLeast -> getCount(quantifier) >= quantifier.times
145 | is Quantifier.AtMost -> getCount(quantifier) <= quantifier.times
146 | }
147 | }
148 |
149 | private fun LinRule.isPossibleToContinueMatching(
150 | element: UElement,
151 | context: MatchLinContext
152 | ): Boolean = quantifier.let {
153 | when (it) {
154 | Quantifier.All -> ruleMatchesAll(this, element, context)
155 | is Quantifier.Times -> context.counterOfQuantifiers.getCount(it) < it.times
156 | is Quantifier.AtMost -> context.counterOfQuantifiers.getCount(it) < it.times
157 | Quantifier.Any, is Quantifier.AtLeast -> true
158 | }
159 | }
160 |
161 | private fun LinRule.matches(
162 | element: UElement,
163 | context: MatchLinContext
164 | ): Boolean = quantifier.let { quantifier ->
165 | return when (quantifier) {
166 | Quantifier.All -> ruleMatchesAll(this, element, context)
167 | Quantifier.Any -> ruleMatchesAny(this, element, context)
168 | is Quantifier.Times -> ruleMatchTimes(this, element, quantifier, context)
169 | is Quantifier.AtLeast -> ruleMatchAtLeast(this, element, context)
170 | is Quantifier.AtMost -> ruleMatchAtMost(this, element, quantifier, context)
171 | }
172 | }
173 |
174 | private fun ruleMatchesAll(
175 | rule: LinRule,
176 | element: UElement,
177 | context: MatchLinContext
178 | ): Boolean = rule.reportingPredicate(context, element)
179 |
180 | private fun ruleMatchesAny(
181 | rule: LinRule,
182 | element: UElement,
183 | context: MatchLinContext
184 | ): Boolean = rule.reportingPredicate(context, element)
185 |
186 | private fun ruleMatchTimes(
187 | rule: LinRule,
188 | element: UElement,
189 | quantifier: Quantifier.Times,
190 | context: MatchLinContext
191 | ): Boolean {
192 | if (!rule.reportingPredicate(context, element)) {
193 | return false
194 | }
195 |
196 | return context.counterOfQuantifiers.getCount(quantifier) < quantifier.times
197 | }
198 |
199 | private fun ruleMatchAtLeast(
200 | rule: LinRule,
201 | element: UElement,
202 | context: MatchLinContext
203 | ): Boolean = rule.reportingPredicate(context, element)
204 |
205 | private fun ruleMatchAtMost(
206 | rule: LinRule,
207 | element: UElement,
208 | quantifier: Quantifier.AtMost,
209 | context: MatchLinContext
210 | ): Boolean {
211 | if (!rule.reportingPredicate(context, element)) {
212 | return false
213 | }
214 |
215 | return context.counterOfQuantifiers.getCount(quantifier) < quantifier.times - 1
216 | }
--------------------------------------------------------------------------------
/detectors/src/test/kotlin/com/serchinastico/lin/detectors/OnlyConstantsInTypeDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.detectors
2 |
3 | import com.serchinastico.lin.test.LintTest
4 | import com.serchinastico.lin.test.LintTest.Expectation.NoErrors
5 | import com.serchinastico.lin.test.LintTest.Expectation.SomeError
6 | import org.junit.Test
7 |
8 | class OnlyConstantsInTypeDetectorTest : LintTest {
9 |
10 | override val issue = OnlyConstantsInTypeOrFileDetector.issue
11 |
12 | @Test
13 | fun inJavaClass_whenClassHasMethods_detectsNoErrors() {
14 | expect(
15 | """
16 | |package foo;
17 | |
18 | |class TestClass {
19 | | public static final String str = "";
20 | |
21 | | public void main(String[] args) {}
22 | |}
23 | """.inJava
24 | ) toHave NoErrors
25 | }
26 |
27 | @Test
28 | fun inJavaClass_whenClassHasNonStaticFields_detectsNoErrors() {
29 | expect(
30 | """
31 | |package foo;
32 | |
33 | |class TestClass {
34 | | public static final String str = "";
35 | | private String nonStaticStr;
36 | |}
37 | """.inJava
38 | ) toHave NoErrors
39 | }
40 |
41 | @Test
42 | fun inJavaClass_whenClassHasNoFieldsNorMethods_detectsError() {
43 | expect(
44 | """
45 | |package foo;
46 | |
47 | |class TestClass {
48 | | public static final String str;
49 | |}
50 | """.inJava
51 | ) toHave SomeError("src/foo/TestClass.java")
52 | }
53 |
54 | @Test
55 | fun inKotlinClass_whenClassHasMethods_detectsNoErrors() {
56 | expect(
57 | """
58 | |package foo
59 | |
60 | |class TestClass {
61 | |
62 | | companion object {
63 | | const val str: String = ""
64 | | }
65 | |
66 | | public fun main(args: Array) {}
67 | |}
68 | """.inKotlin
69 | ) toHave NoErrors
70 | }
71 |
72 | @Test
73 | fun inKotlinClass_whenClassHasNonStaticFields_detectsNoErrors() {
74 | expect(
75 | """
76 | |package foo
77 | |
78 | |class TestClass {
79 | |
80 | | companion object {
81 | | const val str: String = ""
82 | | }
83 | |
84 | | val anotherStr: String = ""
85 | |}
86 | """.inKotlin
87 | ) toHave NoErrors
88 | }
89 |
90 | @Test
91 | fun inKotlinClass_whenClassHasNoFieldsNorMethods_detectsErrors() {
92 | expect(
93 | """
94 | |package foo
95 | |
96 | |class TestClass {
97 | | companion object {
98 | | const val str: String = ""
99 | | }
100 | |}
101 | """.inKotlin
102 | ) toHave SomeError("src/foo/TestClass.kt")
103 | }
104 |
105 | @Test
106 | fun inKotlinObject_whenItHasNoFieldsNorMethods_detectsErrors() {
107 | expect(
108 | """
109 | |package foo
110 | |
111 | |object TestClass {
112 | | const val str: String = ""
113 | |}
114 | """.inKotlin
115 | ) toHave SomeError("src/foo/TestClass.kt")
116 | }
117 |
118 | @Test
119 | fun inKotlinSealedClass_whenItHasNoFields_detectsNoErrors() {
120 | expect(
121 | """
122 | |package foo
123 | |
124 | |sealed class ActionStatus {
125 | | class Ready : ActionStatus()
126 | | class OnGoing : ActionStatus()
127 | | class Finished(val value: T) : ActionStatus()
128 | |}
129 | """.inKotlin
130 | ) toHave NoErrors
131 | }
132 |
133 | @Test
134 | fun inKotlinInterface_whenItHasNoFields_detectsNoErrors() {
135 | expect(
136 | """
137 | |package foo
138 |
139 | |import okhttp3.RequestBody
140 | |import retrofit2.Call
141 | |import retrofit2.http.Body
142 | |import retrofit2.http.GET
143 | |import retrofit2.http.PUT
144 | |import retrofit2.http.Path
145 | |import retrofit2.http.Query
146 | |import retrofit2.http.Url
147 | |
148 | |interface SomeRetrofitApi {
149 | | @GET("some/url")
150 | | fun someApiCall(
151 | | @Query("param1") param1: String,
152 | | @Query("param2") param2: String
153 | | ): Call
154 | |}
155 | |
156 | |typealias SomeResponse = Map
157 | """.inKotlin
158 | ) toHave NoErrors
159 | }
160 |
161 | @Test
162 | fun inKotlinDataClass_whenItHasNoFields_detectsNoErrors() {
163 | expect(
164 | """
165 | |package foo
166 | |
167 | |import org.joda.time.LocalDate
168 | |
169 | |typealias SomeMap = Map>
170 | |
171 | |data class SomeDataClass(
172 | | val someProperty: String,
173 | | val someOtherProperty: String
174 | |)
175 | |
176 | |data class OtherDataClass(
177 | | val someProperty: String,
178 | | val someOtherProperty: String
179 | |)
180 | |
181 | |data class YetAnotherDataClass(
182 | | val someProperty: String,
183 | | private val someOtherProperty: String
184 | |) {
185 | | val someNonConstructorProperty: String = ""
186 | |}
187 | """.inKotlin
188 | ) toHave NoErrors
189 | }
190 |
191 | @Test
192 | fun inKotlinEnum_whenItHasNoFields_detectsNoErrors() {
193 | expect(
194 | """
195 | |enum class LegalNoticeStatus {
196 | | NONE, INSTRUCTIONS_SELECTED
197 | |}
198 | """.inKotlin
199 | ) toHave NoErrors
200 | }
201 |
202 | @Test
203 | fun inKotlinFile_whenThereIsAGlobalConstant_detectsNoErrors() {
204 | /*
205 | * UAST interprets global functions and properties are part of a UClass that is the file.
206 | * As long as there are other things in the file we are considering it ok.
207 | */
208 | expect(
209 | """
210 | |package foo
211 | |
212 | |import android.arch.persistence.room.Database
213 | |import android.arch.persistence.room.RoomDatabase
214 | |import android.arch.persistence.room.TypeConverters
215 | |import foo.Converters
216 | |import foo.SomeDao
217 | |import foo.SomeEntity
218 | |
219 | |const val APP_DATABASE_VERSION = 1
220 | |fun foo() {}
221 | |
222 | |@Database(entities = [
223 | | SomeEntity::class],
224 | | version = APP_DATABASE_VERSION)
225 | |@TypeConverters(Converters::class)
226 | |abstract class AppDatabase : RoomDatabase() {
227 | | abstract fun someDao(): SomeDao
228 | |}
229 | """.inKotlin
230 | ) toHave NoErrors
231 | }
232 |
233 | @Test
234 | fun inKotlinFile_whenThereIsOnlyAGlobalConstant_detectsError() {
235 | /*
236 | * UAST interprets global functions and properties are part of a UClass that is the file.
237 | * If the constant is the only thing defined in this "type" then we raise an error.
238 | */
239 | expect(
240 | """
241 | |package foo
242 | |
243 | |const val APP_DATABASE_VERSION = 1
244 | """.inKotlin
245 | ) toHave SomeError("src/foo/TestClass.kt")
246 | }
247 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ---------------
4 |
5 | [](https://travis-ci.org/Serchinastico/Lin)
6 | [](https://codecov.io/gh/Serchinastico/Lin)
7 | [](https://jitpack.io/#Serchinastico/Lin)
8 | [](https://github.com/Serchinastico/Lin)
9 |
10 | Lin is an Android Lint tool made simpler. It has two different goals:
11 |
12 | 1. To create a set of highly opinionated detectors to apply to your Android projects.
13 | 2. To offer a Kotlin DSL to write your own detectors in a much easier way.
14 |
15 | ## How to use
16 |
17 | Add the JitPack repository to your build file:
18 |
19 | ```groovy
20 | allprojects {
21 | repositories {
22 | ...
23 | maven { url 'https://jitpack.io' }
24 | }
25 | }
26 | ```
27 |
28 | ### Lin - Detectors
29 |
30 | Add the `detectors` module dependencies to your project and the `dsl` module as part of the lint classpath:
31 |
32 | ```groovy
33 | dependencies {
34 | lintChecks 'com.github.serchinastico.lin:detectors:0.0.6'
35 | }
36 | ```
37 |
38 | ### Lin - DSL (Domain Specific Language)
39 |
40 | If you want to write your own detectors with Lin just add the `dsl`, `annotations` and `processor` modules to your linting project:
41 |
42 | ```groovy
43 | dependencies {
44 | compileOnly 'com.github.serchinastico.lin:dsl:0.0.6'
45 | compileOnly 'com.github.serchinastico.lin:annotations:0.0.6'
46 | kapt 'com.github.serchinastico.lin:processor:0.0.6'
47 | }
48 | ```
49 |
50 | You will also need to export classes defined in the `dsl` dependency into your linting module. To do so, pack the `dsl` files inside the jar along with the definition of your `Lint-Registry-v2` file:
51 |
52 | ```groovy
53 | jar {
54 | manifest {
55 | attributes("Lint-Registry-v2": "com.your.project.IssueRegistry")
56 | }
57 |
58 | from {
59 | configurations.compileOnly.filter {
60 | it.absolutePath.contains("com.github.serchinastico.lin/dsl")
61 | }.collect {
62 | it.isDirectory() ? it : zipTree(it)
63 | }
64 | }
65 | }
66 | ```
67 |
68 | ## How to write your own detectors
69 |
70 | Lin offers a DSL (Domain Specific Language) to write your own detectors easily. The API is focused on representing your rules as concisely as possible. Let's bisect an example of a detector to understand how it works:
71 |
72 | ```kotlin
73 | @Detector
74 | fun noElseInSwitchWithEnumOrSealed() = detector(
75 | // Define the issue:
76 | issue(
77 | // 1. What files should the detector check
78 | Scope.JAVA_FILE_SCOPE,
79 | // 2. A brief description of the issue
80 | "There should not be else/default branches on a switch statement checking for enum/sealed class values",
81 | // 3. A more in-detail explanation of why are we detecting the issue
82 | "Adding an else/default branch breaks extensibility because it won't let you know if there is a missing " +
83 | "implementation when adding new types to the enum/sealed class",
84 | // The category this issue falls into
85 | Category.CORRECTNESS
86 | )
87 | ) {
88 | /* The rule definition using the DSL. Define the
89 | * AST node you want to look for and include a
90 | * suchThat definition returning true when you want
91 | * your rule to report an issue.
92 | * The best way to see what nodes you have
93 | * available is by using your IDE autocomplete
94 | * function.
95 | */
96 | switch {
97 | suchThat { node ->
98 | val classReferenceType = node.expression?.getExpressionType() ?: (return@suchThat false)
99 |
100 | if (!classReferenceType.isEnum && !classReferenceType.isSealed) {
101 | return@suchThat false
102 | }
103 |
104 | node.clauses.any { clause -> clause.isElseBranch }
105 | }
106 | }
107 | }
108 | ```
109 |
110 | ### Quantifiers
111 |
112 | You can specify your rules using quantifiers, that is, numeric restrictions to how many times you are expecting a specific rule to appear in order to be reported.
113 |
114 | ```kotlin
115 | @Detector
116 | fun noMoreThanOneGsonInstance() = detector(
117 | issue(
118 | Scope.JAVA_FILE_SCOPE,
119 | "Gson should only be initialized only once",
120 | """Creating multiple instances of Gson may hurt performance and it's a common mistake to instantiate it for
121 | | simple serialization/deserialization. Use a single instance, be it with a classic singleton pattern or
122 | | other mechanism your dependency injector framework provides. This way you can also share the common
123 | | type adapters.
124 | """.trimMargin(),
125 | Category.PERFORMANCE
126 | ),
127 | // We can use anyOf to report if any of the rules
128 | // included is found.
129 | anyOf(
130 | // This rule will only report if more than one
131 | // file has any call expression matching the
132 | // suchThat predicate.
133 | file(moreThan(1)) { callExpression { suchThat { it.isGsonConstructor } } },
134 | // On the other hand, this rule will only
135 | // report if there is any file with more than
136 | // one call expression matching the suchThat
137 | // predicate.
138 | file { callExpression(moreThan(1)) { suchThat { it.isGsonConstructor } } }
139 | )
140 | )
141 | ```
142 |
143 | The list of available quantifiers is:
144 |
145 | ```kotlin
146 | val any // The default quantifier, if a rule matches any number of times then it's reported
147 | val all // It should appear in every single appearance of the node
148 | fun times(times: Int) // Match the rule an exact number of "times"
149 | fun atMost(times: Int) // matches <= "times"
150 | fun atLeast(times: Int) // matches >= "times"
151 | fun lessThan(times: Int) // matches < "times"
152 | fun moreThan(times: Int) // matches > "times"
153 | val none // No matches
154 | ```
155 |
156 | ### Storage
157 |
158 | Lin detectors can store and retrieve information from a provided map. This is really useful if you have dependant rules where one of them might depend on the value of another, e.g. an activity class name having the same name as the layout it renders.
159 |
160 | Because Lin uses backtracking on the process of finding the best match for rules **it's highly discouraged to store information by yourself**, intead you should use the `storage` property provided in the `suchThat` block.
161 |
162 | ```kotlin
163 | {
164 | import {
165 | suchThat { node ->
166 | val importedString = node.importReference?.asRenderString() ?: return@suchThat false
167 | val importedLayout = KOTLINX_SYNTHETIC_VIEW_IMPORT
168 | .matchEntire(importedString)
169 | ?.groups
170 | ?.get(1)
171 | ?.value ?: return@suchThat false
172 | // Here we have access to the LinContext object that holds
173 | // a reference to a map of values where you can store
174 | // string values.
175 | params["Imported Layout"] = importedLayout
176 | it.isSyntheticViewImport
177 | }
178 | }
179 |
180 | expression {
181 | suchThat { node ->
182 | // We retrieve the information we stored previously
183 | // It's the same value we stored when the rule returned
184 | // true so we are sure it's the one we need.
185 | val importedLayout = params["Imported Layout"] ?: return@suchThat false
186 | val usedLayout = LAYOUT_EXPRESSION.matchEntire(node.asRenderString())
187 | ?.groups
188 | ?.get(1)
189 | ?.value ?: return@suchThat false
190 | return usedLayout != importedLayout
191 | }
192 | }
193 | }
194 | ```
195 |
196 | The `storage` property is just a `MutableMap`. The matching algorithm takes care of keeping the map in a coherent state while doing the search so that you won't find values stored in failing rules. **All siblings and child nodes will see stored values.**
197 |
198 | It's also important to keep in mind that Lin will try to match rules in any order. The most important implication is that even if you define a rule in a specific order Lin might find matches in the opposite:
199 |
200 | ```kotlin
201 | {
202 | expression {
203 | suchThat {
204 | storage["node"] = it.asRenderString()
205 | true
206 | }
207 | }
208 |
209 | expression {
210 | suchThat { "MyExpression" == storage["node"] }
211 | }
212 | }
213 | ```
214 |
215 | Even if the expression storing things in the storage is defined before, that order is not honored when looking for the best match of rules, so it might happen that `storage["node"]` is null.
216 |
217 | ### Lin - Testing
218 |
219 | Internally, Lin uses a DSL for tests that makes a bit easier the simplest scenarios. You can use it by adding the dependency to your project:
220 |
221 | ```groovy
222 | dependencies {
223 | testImplementation 'com.github.serchinastico.lin:test:0.0.6'
224 | // You might still need to load the official Android Lint dependencies for tests
225 | testImplementation 'com.android.tools.lint:lint:26.3.0'
226 | testImplementation 'com.android.tools.lint:lint-tests:26.3.0'
227 | testImplementation 'com.android.tools:testutils:26.3.0'
228 | }
229 | ```
230 |
231 | Creating a test with the `test` module is pretty easy, just look at an example:
232 |
233 | ```kotlin
234 | class SomeDetectorTest : LintTest {
235 | // Specify the issue we are covering, in this case an issue created with Lin
236 | override val issue = SomeDetector.issue
237 |
238 | @Test
239 | fun inJavaClass_whenSomethingHappens_detectsNoErrors() {
240 | // `expect` can load multiple files to the test project
241 | expect(
242 | someSharedFile,
243 | """
244 | |package foo;
245 | |
246 | |import java.util.Date;
247 | |
248 | |class TestClass {
249 | | public void main(String[] args) {}
250 | |}
251 | """.inJava // Specify the language in which the file is written e.g. `inJava` or `inKotlin`
252 | ) toHave NoErrors /* Three possible values here:
253 | * > `NoErrors` No expected reports
254 | * > `SomeWarning(fileName)` Expect at least one warning in the specified file
255 | * > `SomeError(fileName)` Expect at least one error in the specified file
256 | */
257 | }
258 | }
259 | ```
260 |
261 | Lin tests are used with this very same DSL so you can take a look to the `detectors` module tests to see many more examples.
262 |
263 | ### Badge
264 |
265 | Show the world you're using Lin.
266 |
267 | [](https://github.com/Serchinastico/Lin)
268 |
269 | ```md
270 | [](https://github.com/Serchinastico/Lin)
271 | ```
272 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/processor/src/main/kotlin/com/serchinastico/lin/processor/DetectorProcessor.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.processor
2 |
3 | import com.google.auto.service.AutoService
4 | import com.serchinastico.lin.annotations.Detector
5 | import com.serchinastico.lin.dsl.IssueBuilder
6 | import com.serchinastico.lin.dsl.LinDetector
7 | import com.serchinastico.lin.dsl.LinVisitor
8 | import com.squareup.kotlinpoet.*
9 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
10 | import javax.annotation.processing.*
11 | import javax.lang.model.SourceVersion
12 | import javax.lang.model.element.ExecutableElement
13 | import javax.lang.model.element.TypeElement
14 | import javax.tools.Diagnostic
15 | import javax.tools.StandardLocation
16 |
17 |
18 | @AutoService(Processor::class)
19 | @SupportedSourceVersion(SourceVersion.RELEASE_8)
20 | @SupportedOptions(DetectorProcessor.KAPT_KOTLIN_GENERATED_OPTION_NAME)
21 | @SupportedAnnotationTypes("com.serchinastico.lin.annotations.Detector")
22 | class DetectorProcessor : AbstractProcessor() {
23 |
24 | companion object {
25 | const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
26 |
27 | val LIN_DETECTOR_CLASS_NAME = ClassName("com.serchinastico.lin.dsl", "LinDetector")
28 | val ISSUE_CLASS_NAME = ClassName("com.android.tools.lint.detector.api", "Issue")
29 | val DETECTOR_CLASS_NAME = ClassName("com.android.tools.lint.detector.api", "Detector")
30 | val UAST_SCANNER_CLASS_NAME = ClassName("com.android.tools.lint.detector.api.Detector", "UastScanner")
31 | val U_ELEMENT_HANDLER_CLASS_NAME = ClassName("com.android.tools.lint.client.api", "UElementHandler")
32 | val U_ELEMENT_OUT_CLASS_NAME = WildcardTypeName.producerOf(ClassName("org.jetbrains.uast", "UElement"))
33 | val JAVA_CONTEXT_CLASS_NAME = ClassName("com.android.tools.lint.detector.api", "JavaContext")
34 | val CLASS_CLASS_NAME = ClassName("java.lang", "Class")
35 | val LIST_CLASS_NAME = ClassName("kotlin.collections", "List")
36 | val ENUM_SET_CLASS_NAME = ClassName("java.util", "EnumSet")
37 | val SCOPE_CLASS_NAME = ClassName("com.android.tools.lint.detector.api", "Scope")
38 | }
39 |
40 | override fun process(annotations: MutableSet?, roundEnvironment: RoundEnvironment?): Boolean {
41 | roundEnvironment ?: return false
42 |
43 | val annotatedElements = roundEnvironment.getElementsAnnotatedWith(Detector::class.java)
44 |
45 | val generatedSourcesRoot: String = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME].orEmpty()
46 | if (ensureOutputDirectoryExists(generatedSourcesRoot)) return false
47 |
48 | annotatedElements
49 | .mapNotNull { it as? ExecutableElement }
50 | .forEach { element ->
51 | val returnTypeName = element.returnType.asTypeName()
52 |
53 | if (returnTypeName != LIN_DETECTOR_CLASS_NAME) {
54 | printError("${Detector::class.simpleName} annotation has to be applied to a function returning a ${LinDetector::class.simpleName} instance.")
55 | return false
56 | }
57 |
58 | val issueId = element.simpleName.toString().capitalize()
59 | val packageName = processingEnv.elementUtils.getPackageOf(element).qualifiedName.toString()
60 |
61 | val className = "${issueId}Detector"
62 | val detectorFile = FileSpec.builder(packageName, className)
63 | .addImport("com.serchinastico.lin.dsl", "LinVisitor")
64 | .addImport("com.serchinastico.lin.dsl", "report")
65 | .addType(
66 | TypeSpec.classBuilder(className)
67 | .superclass(DETECTOR_CLASS_NAME)
68 | .addSuperinterface(UAST_SCANNER_CLASS_NAME)
69 | .addCompanionObject {
70 | addDetectorProperty(element.simpleName.toString())
71 | .addIssueBuilderProperty()
72 | .addIssueProperty(className)
73 | }
74 | .addVisitorProperty()
75 | .addJavaContextProperty()
76 | .addDidReportFileVisitor()
77 | .addGetApplicableFilesFunction()
78 | .addGetApplicableUastTypes()
79 | .addAfterCheckEachProject()
80 | .addCreateUastHandler()
81 | .build()
82 | )
83 | .build()
84 |
85 | val kotlinFileObject =
86 | processingEnv.filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, "$className.kt")
87 | val writer = kotlinFileObject.openWriter()
88 | detectorFile.writeTo(writer)
89 | writer.close()
90 | }
91 |
92 | return true
93 | }
94 |
95 | private fun TypeSpec.Builder.addCompanionObject(block: TypeSpec.Builder.() -> TypeSpec.Builder): TypeSpec.Builder =
96 | addType(TypeSpec.companionObjectBuilder().block().build())
97 |
98 | private fun TypeSpec.Builder.addDetectorProperty(detectorText: String): TypeSpec.Builder =
99 | addProperty(
100 | PropertySpec.builder("detector", LinDetector::class)
101 | .delegate(
102 | CodeBlock.builder()
103 | .beginControlFlow("lazy")
104 | .add("$detectorText()")
105 | .endControlFlow()
106 | .build()
107 | )
108 | .build()
109 | )
110 |
111 | private fun TypeSpec.Builder.addIssueBuilderProperty(): TypeSpec.Builder =
112 | addProperty(
113 | PropertySpec.builder("issueBuilder", IssueBuilder::class)
114 | .delegate(
115 | CodeBlock.builder()
116 | .beginControlFlow("lazy")
117 | .add("detector.issueBuilder")
118 | .endControlFlow()
119 | .build()
120 | )
121 | .build()
122 | )
123 |
124 | private fun TypeSpec.Builder.addIssueProperty(className: String): TypeSpec.Builder =
125 | addProperty(
126 | PropertySpec.builder("issue", ISSUE_CLASS_NAME)
127 | .delegate(
128 | CodeBlock.builder()
129 | .beginControlFlow("lazy")
130 | .add("detector.issueBuilder.build($className::class)")
131 | .endControlFlow()
132 | .build()
133 | )
134 | .build()
135 | )
136 |
137 | private fun TypeSpec.Builder.addVisitorProperty(): TypeSpec.Builder =
138 | addProperty(
139 | PropertySpec.builder("projectVisitor", LinVisitor::class)
140 | .initializer("LinVisitor(detector)")
141 | .build()
142 | )
143 |
144 | private fun TypeSpec.Builder.addJavaContextProperty(): TypeSpec.Builder =
145 | addProperty(
146 | PropertySpec.builder("javaContext", JAVA_CONTEXT_CLASS_NAME)
147 | .mutable(true)
148 | .addModifiers(KModifier.LATEINIT)
149 | .build()
150 | )
151 |
152 | private fun TypeSpec.Builder.addDidReportFileVisitor(): TypeSpec.Builder =
153 | addProperty(
154 | PropertySpec.builder("didReportWithFileVisitor", Boolean::class)
155 | .mutable(true)
156 | .initializer("false")
157 | .build()
158 | )
159 |
160 | private fun TypeSpec.Builder.addGetApplicableFilesFunction(): TypeSpec.Builder =
161 | addFunction(
162 | FunSpec.builder("getApplicableFiles")
163 | .addModifiers(KModifier.OVERRIDE)
164 | .addCode("return issueBuilder.scope")
165 | .returns(ENUM_SET_CLASS_NAME.parameterizedBy(SCOPE_CLASS_NAME))
166 | .build()
167 | )
168 |
169 | private fun TypeSpec.Builder.addGetApplicableUastTypes(): TypeSpec.Builder =
170 | addFunction(
171 | FunSpec.builder("getApplicableUastTypes")
172 | .addModifiers(KModifier.OVERRIDE)
173 | .addCode("return detector.applicableTypes")
174 | .returns(LIST_CLASS_NAME.parameterizedBy(CLASS_CLASS_NAME.parameterizedBy(U_ELEMENT_OUT_CLASS_NAME)))
175 | .build()
176 | )
177 |
178 | private fun TypeSpec.Builder.addAfterCheckEachProject(): TypeSpec.Builder =
179 | addFunction(
180 | FunSpec.builder("afterCheckEachProject")
181 | .addModifiers(KModifier.OVERRIDE)
182 | .addParameter(
183 | "context",
184 | ClassName("com.android.tools.lint.detector.api", "Context")
185 | )
186 | .addCode(
187 | """
188 | |val reportedNodes = projectVisitor.reportedNodes
189 | |if (!didReportWithFileVisitor && reportedNodes.isNotEmpty()) {
190 | | context.report(issue, javaContext.getLocation(reportedNodes.first()), reportedNodes.first())
191 | |}
192 | """.trimMargin()
193 | )
194 | .build()
195 | )
196 |
197 | private fun TypeSpec.Builder.addCreateUastHandler(): TypeSpec.Builder =
198 | addFunction(
199 | FunSpec.builder("createUastHandler")
200 | .addModifiers(KModifier.OVERRIDE)
201 | .addParameter(
202 | "context",
203 | ClassName("com.android.tools.lint.detector.api", "JavaContext")
204 | )
205 | .addCode(
206 | "return %L",
207 | getElementHandlerType()
208 | )
209 | .returns(
210 | ClassName("com.android.tools.lint.client.api", "UElementHandler").copy(nullable = true)
211 | )
212 | .build()
213 | )
214 |
215 | private fun getElementHandlerType(): TypeSpec =
216 | TypeSpec.anonymousClassBuilder()
217 | .superclass(U_ELEMENT_HANDLER_CLASS_NAME)
218 | .addFunction(
219 | FunSpec.builder("visitFile")
220 | .addModifiers(KModifier.OVERRIDE)
221 | .addParameter(
222 | "node",
223 | ClassName("org.jetbrains.uast", "UFile")
224 | )
225 | .addShouldReportFunction()
226 | .build()
227 | )
228 | .build()
229 |
230 | private fun FunSpec.Builder.addShouldReportFunction(): FunSpec.Builder =
231 | addCode(
232 | """ |javaContext = context
233 | |val fileVisitor = LinVisitor(detector)
234 | |node.accept(fileVisitor)
235 | |val reportedNodes = fileVisitor.reportedNodes
236 | |if (reportedNodes.isNotEmpty()) {
237 | | context.report(issue, context.getNameLocation(reportedNodes.first()), reportedNodes.first())
238 | | didReportWithFileVisitor = true
239 | |}
240 | |projectVisitor += fileVisitor
241 | """.trimMargin()
242 | )
243 |
244 | private fun ensureOutputDirectoryExists(generatedSourcesRoot: String): Boolean =
245 | if (generatedSourcesRoot.isEmpty()) {
246 | printError("Can't find the target directory for generated Kotlin files.")
247 | true
248 | } else {
249 | false
250 | }
251 |
252 | private fun printError(message: String) {
253 | processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, message)
254 | }
255 | }
--------------------------------------------------------------------------------
/dsl/src/main/kotlin/com/serchinastico/lin/dsl/dsl.kt:
--------------------------------------------------------------------------------
1 | package com.serchinastico.lin.dsl
2 |
3 | import com.android.tools.lint.detector.api.*
4 | import org.jetbrains.uast.*
5 | import java.util.*
6 | import kotlin.reflect.KClass
7 |
8 | fun detector(
9 | issueBuilder: IssueBuilder,
10 | ruleSet: RuleSet
11 | ): LinDetector = LinDetector(issueBuilder, ruleSet.rules)
12 |
13 | fun detector(
14 | issueBuilder: IssueBuilder,
15 | block: LinRule.File.() -> LinRule<*>
16 | ): LinDetector = LinDetector(issueBuilder, listOf(LinRule.File().block()))
17 |
18 | data class LinDetector(val issueBuilder: IssueBuilder, val roots: List>) {
19 | val applicableTypes: List> = listOf(UFile::class.java)
20 | }
21 |
22 | data class RuleSet(val rules: List>) {
23 | companion object {
24 | fun anyOf(vararg rules: LinRule<*>) = RuleSet(rules.toList())
25 | }
26 | }
27 |
28 | fun issue(
29 | scope: EnumSet,
30 | description: String,
31 | explanation: String
32 | ): IssueBuilder = IssueBuilder(scope, description, explanation)
33 |
34 | data class IssueBuilder(
35 | val scope: EnumSet,
36 | val description: String,
37 | val explanation: String,
38 | val category: Category = LinCategory,
39 | var priority: Int = 5,
40 | var severity: Severity = Severity.ERROR
41 | ) {
42 | fun build(detectorClass: KClass): Issue =
43 | Issue.create(
44 | detectorClass.simpleName ?: "RuleWithNoId",
45 | description,
46 | explanation,
47 | category,
48 | priority,
49 | severity,
50 | Implementation(detectorClass.java, scope)
51 | )
52 | }
53 |
54 | sealed class Quantifier {
55 | object All : Quantifier()
56 | object Any : Quantifier()
57 | data class Times(val times: Int) : Quantifier()
58 | data class AtMost(val times: Int) : Quantifier()
59 | data class AtLeast(val times: Int) : Quantifier()
60 |
61 | companion object {
62 | val all = All
63 | val any = Any
64 | fun times(times: Int) = Times(times)
65 | fun atMost(times: Int) = AtMost(times)
66 | fun atLeast(times: Int) = AtLeast(times)
67 | fun lessThan(times: Int) = AtMost(times - 1)
68 | fun moreThan(times: Int) = AtLeast(times + 1)
69 | val none = times(0)
70 | }
71 | }
72 |
73 | fun file(quantifier: Quantifier = Quantifier.Any, block: LinRule.File.() -> LinRule) =
74 | LinRule.File().block().also { it.quantifier = quantifier }
75 |
76 | typealias Storage = MutableMap
77 |
78 | interface LinContext {
79 | val storage: Storage
80 | }
81 |
82 | sealed class LinRule(val elementType: KClass) {
83 |
84 | var children = mutableListOf>()
85 | var reportingPredicate: LinContext.(UElement) -> Boolean = { true }
86 | var quantifier: Quantifier = Quantifier.Any
87 |
88 | fun suchThat(predicate: LinContext.(T) -> Boolean): LinRule {
89 | reportingPredicate = { element -> predicate(element as T) }
90 | return this
91 | }
92 |
93 | fun import(
94 | quantifier: Quantifier = Quantifier.Any,
95 | block: Import.() -> LinRule
96 | ): LinRule {
97 | children.add(Import().block().also { it.quantifier = quantifier })
98 | return this
99 | }
100 |
101 | fun declaration(
102 | quantifier: Quantifier = Quantifier.Any,
103 | block: Declaration.() -> LinRule
104 | ): LinRule {
105 | children.add(Declaration().block().also { it.quantifier = quantifier })
106 | return this
107 | }
108 |
109 | fun type(quantifier: Quantifier = Quantifier.Any, block: LinRule.Type.() -> LinRule): LinRule {
110 | children.add(LinRule.Type().block().also { it.quantifier = quantifier })
111 | return this
112 | }
113 |
114 | fun initializer(
115 | quantifier: Quantifier = Quantifier.Any,
116 | block: LinRule.Initializer.() -> LinRule
117 | ): LinRule {
118 | children.add(LinRule.Initializer().block().also { it.quantifier = quantifier })
119 | return this
120 | }
121 |
122 | fun method(quantifier: Quantifier = Quantifier.Any, block: LinRule.Method.() -> LinRule): LinRule {
123 | children.add(LinRule.Method().block().also { it.quantifier = quantifier })
124 | return this
125 | }
126 |
127 | fun variable(
128 | quantifier: Quantifier = Quantifier.Any,
129 | block: LinRule.Variable.() -> LinRule
130 | ): LinRule {
131 | children.add(LinRule.Variable().block().also { it.quantifier = quantifier })
132 | return this
133 | }
134 |
135 | fun parameter(
136 | quantifier: Quantifier = Quantifier.Any,
137 | block: LinRule.Parameter.() -> LinRule
138 | ): LinRule {
139 | children.add(LinRule.Parameter().block().also { it.quantifier = quantifier })
140 | return this
141 | }
142 |
143 | fun field(quantifier: Quantifier = Quantifier.Any, block: LinRule.Field.() -> LinRule): LinRule {
144 | children.add(LinRule.Field().block().also { it.quantifier = quantifier })
145 | return this
146 | }
147 |
148 | fun localVariable(
149 | quantifier: Quantifier = Quantifier.Any,
150 | block: LinRule.LocalVariable.() -> LinRule
151 | ): LinRule {
152 | children.add(LinRule.LocalVariable().block().also { it.quantifier = quantifier })
153 | return this
154 | }
155 |
156 | fun enumConstant(
157 | quantifier: Quantifier = Quantifier.Any,
158 | block: LinRule.EnumConstant.() -> LinRule
159 | ): LinRule {
160 | children.add(LinRule.EnumConstant().block().also { it.quantifier = quantifier })
161 | return this
162 | }
163 |
164 | fun annotation(
165 | quantifier: Quantifier = Quantifier.Any,
166 | block: LinRule.Annotation.() -> LinRule
167 | ): LinRule {
168 | children.add(LinRule.Annotation().block().also { it.quantifier = quantifier })
169 | return this
170 | }
171 |
172 | fun expression(
173 | quantifier: Quantifier = Quantifier.Any,
174 | block: LinRule.Expression.() -> LinRule
175 | ): LinRule {
176 | children.add(LinRule.Expression().block().also { it.quantifier = quantifier })
177 | return this
178 | }
179 |
180 | fun labeledExpression(
181 | quantifier: Quantifier = Quantifier.Any,
182 | block: LinRule.LabeledExpression.() -> LinRule
183 | ): LinRule {
184 | children.add(LinRule.LabeledExpression().block().also { it.quantifier = quantifier })
185 | return this
186 | }
187 |
188 | fun declarationsExpression(
189 | quantifier: Quantifier = Quantifier.Any,
190 | block: LinRule.DeclarationsExpression.() -> LinRule
191 | ): LinRule {
192 | children.add(LinRule.DeclarationsExpression().block().also { it.quantifier = quantifier })
193 | return this
194 | }
195 |
196 | fun blockExpression(
197 | quantifier: Quantifier = Quantifier.Any,
198 | block: LinRule.BlockExpression.() -> LinRule
199 | ): LinRule {
200 | children.add(LinRule.BlockExpression().block().also { it.quantifier = quantifier })
201 | return this
202 | }
203 |
204 | fun qualifiedReferenceExpression(
205 | quantifier: Quantifier = Quantifier.Any,
206 | block: LinRule.QualifiedReferenceExpression.() -> LinRule
207 | ): LinRule {
208 | children.add(LinRule.QualifiedReferenceExpression().block().also { it.quantifier = quantifier })
209 | return this
210 | }
211 |
212 | fun simpleNameReferenceExpression(
213 | quantifier: Quantifier = Quantifier.Any,
214 | block: LinRule.SimpleNameReferenceExpression.() -> LinRule
215 | ): LinRule {
216 | children.add(LinRule.SimpleNameReferenceExpression().block().also { it.quantifier = quantifier })
217 | return this
218 | }
219 |
220 | fun typeReferenceExpression(
221 | quantifier: Quantifier = Quantifier.Any,
222 | block: LinRule.TypeReferenceExpression.() -> LinRule
223 | ): LinRule {
224 | children.add(LinRule.TypeReferenceExpression().block().also { it.quantifier = quantifier })
225 | return this
226 | }
227 |
228 | fun callExpression(
229 | quantifier: Quantifier = Quantifier.Any, block: LinRule.CallExpression.() -> LinRule
230 | ): LinRule {
231 | children.add(LinRule.CallExpression().block().also { it.quantifier = quantifier }.also {
232 | it.quantifier = quantifier
233 | })
234 | return this
235 | }
236 |
237 | fun binaryExpression(
238 | quantifier: Quantifier = Quantifier.Any,
239 | block: LinRule.BinaryExpression.() -> LinRule
240 | ): LinRule {
241 | children.add(LinRule.BinaryExpression().block().also { it.quantifier = quantifier })
242 | return this
243 | }
244 |
245 | fun polyadicExpression(
246 | quantifier: Quantifier = Quantifier.Any,
247 | block: LinRule.PolyadicExpression.() -> LinRule
248 | ): LinRule {
249 | children.add(LinRule.PolyadicExpression().block().also { it.quantifier = quantifier })
250 | return this
251 | }
252 |
253 | fun parenthesizedExpression(
254 | quantifier: Quantifier = Quantifier.Any,
255 | block: LinRule.ParenthesizedExpression.() -> LinRule
256 | ): LinRule {
257 | children.add(LinRule.ParenthesizedExpression().block().also { it.quantifier = quantifier })
258 | return this
259 | }
260 |
261 | fun unaryExpression(
262 | quantifier: Quantifier = Quantifier.Any,
263 | block: LinRule.UnaryExpression.() -> LinRule
264 | ): LinRule {
265 | children.add(LinRule.UnaryExpression().block().also { it.quantifier = quantifier })
266 | return this
267 | }
268 |
269 | fun binaryExpressionWithType(
270 | quantifier: Quantifier = Quantifier.Any,
271 | block: LinRule.BinaryExpressionWithType.() -> LinRule
272 | ): LinRule {
273 | children.add(LinRule.BinaryExpressionWithType().block().also { it.quantifier = quantifier })
274 | return this
275 | }
276 |
277 | fun prefixExpression(
278 | quantifier: Quantifier = Quantifier.Any,
279 | block: LinRule.PrefixExpression.() -> LinRule
280 | ): LinRule {
281 | children.add(LinRule.PrefixExpression().block().also { it.quantifier = quantifier })
282 | return this
283 | }
284 |
285 | fun postfixExpression(
286 | quantifier: Quantifier = Quantifier.Any,
287 | block: LinRule.PostfixExpression.() -> LinRule
288 | ): LinRule {
289 | children.add(LinRule.PostfixExpression().block().also { it.quantifier = quantifier })
290 | return this
291 | }
292 |
293 | fun expressionList(
294 | quantifier: Quantifier = Quantifier.Any,
295 | block: LinRule.ExpressionList.() -> LinRule
296 | ): LinRule {
297 | children.add(LinRule.ExpressionList().block().also { it.quantifier = quantifier })
298 | return this
299 | }
300 |
301 | fun ifExpression(
302 | quantifier: Quantifier = Quantifier.Any,
303 | block: LinRule.IfExpression.() -> LinRule
304 | ): LinRule {
305 | children.add(LinRule.IfExpression().block().also { it.quantifier = quantifier })
306 | return this
307 | }
308 |
309 | fun switchExpression(
310 | quantifier: Quantifier = Quantifier.Any,
311 | block: LinRule.SwitchExpression.() -> LinRule
312 | ): LinRule {
313 | children.add(LinRule.SwitchExpression().block().also { it.quantifier = quantifier })
314 | return this
315 | }
316 |
317 | fun switchClauseExpression(
318 | quantifier: Quantifier = Quantifier.Any,
319 | block: LinRule.SwitchClauseExpression.() -> LinRule
320 | ): LinRule {
321 | children.add(LinRule.SwitchClauseExpression().block().also { it.quantifier = quantifier })
322 | return this
323 | }
324 |
325 | fun whileExpression(
326 | quantifier: Quantifier = Quantifier.Any,
327 | block: LinRule.WhileExpression.() -> LinRule
328 | ): LinRule {
329 | children.add(LinRule.WhileExpression().block().also { it.quantifier = quantifier })
330 | return this
331 | }
332 |
333 | fun doWhileExpression(
334 | quantifier: Quantifier = Quantifier.Any,
335 | block: LinRule.DoWhileExpression.() -> LinRule
336 | ): LinRule {
337 | children.add(LinRule.DoWhileExpression().block().also { it.quantifier = quantifier })
338 | return this
339 | }
340 |
341 | fun forExpression(
342 | quantifier: Quantifier = Quantifier.Any,
343 | block: LinRule.ForExpression.() -> LinRule
344 | ): LinRule {
345 | children.add(LinRule.ForExpression().block().also { it.quantifier = quantifier })
346 | return this
347 | }
348 |
349 | fun forEachExpression(
350 | quantifier: Quantifier = Quantifier.Any,
351 | block: LinRule.ForEachExpression.() -> LinRule
352 | ): LinRule {
353 | children.add(LinRule.ForEachExpression().block().also { it.quantifier = quantifier })
354 | return this
355 | }
356 |
357 | fun tryExpression(
358 | quantifier: Quantifier = Quantifier.Any,
359 | block: LinRule.TryExpression.() -> LinRule
360 | ): LinRule {
361 | children.add(LinRule.TryExpression().block().also { it.quantifier = quantifier })
362 | return this
363 | }
364 |
365 | fun catchClause(
366 | quantifier: Quantifier = Quantifier.Any,
367 | block: LinRule.CatchClause.() -> LinRule
368 | ): LinRule {
369 | children.add(LinRule.CatchClause().block().also { it.quantifier = quantifier })
370 | return this
371 | }
372 |
373 | fun literalExpression(
374 | quantifier: Quantifier = Quantifier.Any,
375 | block: LinRule.LiteralExpression.() -> LinRule
376 | ): LinRule {
377 | children.add(LinRule.LiteralExpression().block().also { it.quantifier = quantifier })
378 | return this
379 | }
380 |
381 | fun thisExpression(
382 | quantifier: Quantifier = Quantifier.Any,
383 | block: LinRule.ThisExpression.() -> LinRule
384 | ): LinRule {
385 | children.add(LinRule.ThisExpression().block().also { it.quantifier = quantifier })
386 | return this
387 | }
388 |
389 | fun superExpression(
390 | quantifier: Quantifier = Quantifier.Any,
391 | block: LinRule.SuperExpression.() -> LinRule
392 | ): LinRule {
393 | children.add(LinRule.SuperExpression().block().also { it.quantifier = quantifier })
394 | return this
395 | }
396 |
397 | fun returnExpression(
398 | quantifier: Quantifier = Quantifier.Any,
399 | block: LinRule.ReturnExpression.() -> LinRule
400 | ): LinRule {
401 | children.add(LinRule.ReturnExpression().block().also { it.quantifier = quantifier })
402 | return this
403 | }
404 |
405 | fun breakExpression(
406 | quantifier: Quantifier = Quantifier.Any,
407 | block: LinRule.BreakExpression.() -> LinRule
408 | ): LinRule {
409 | children.add(LinRule.BreakExpression().block().also { it.quantifier = quantifier })
410 | return this
411 | }
412 |
413 | fun continueExpression(
414 | quantifier: Quantifier = Quantifier.Any,
415 | block: LinRule.ContinueExpression.() -> LinRule
416 | ): LinRule {
417 | children.add(LinRule.ContinueExpression().block().also { it.quantifier = quantifier })
418 | return this
419 | }
420 |
421 | fun throwExpression(
422 | quantifier: Quantifier = Quantifier.Any,
423 | block: LinRule.ThrowExpression.() -> LinRule
424 | ): LinRule {
425 | children.add(LinRule.ThrowExpression().block().also { it.quantifier = quantifier })
426 | return this
427 | }
428 |
429 | fun arrayAccessExpression(
430 | quantifier: Quantifier = Quantifier.Any,
431 | block: LinRule.ArrayAccessExpression.() -> LinRule
432 | ): LinRule {
433 | children.add(LinRule.ArrayAccessExpression().block().also { it.quantifier = quantifier })
434 | return this
435 | }
436 |
437 | fun callableReferenceExpression(
438 | quantifier: Quantifier = Quantifier.Any,
439 | block: LinRule.CallableReferenceExpression.() -> LinRule
440 | ): LinRule {
441 | children.add(LinRule.CallableReferenceExpression().block().also { it.quantifier = quantifier })
442 | return this
443 | }
444 |
445 | fun classLiteralExpression(
446 | quantifier: Quantifier = Quantifier.Any,
447 | block: LinRule.ClassLiteralExpression.() -> LinRule
448 | ): LinRule {
449 | children.add(LinRule.ClassLiteralExpression().block().also { it.quantifier = quantifier })
450 | return this
451 | }
452 |
453 | fun lambdaExpression(
454 | quantifier: Quantifier = Quantifier.Any,
455 | block: LinRule.LambdaExpression.() -> LinRule
456 | ): LinRule {
457 | children.add(LinRule.LambdaExpression().block().also { it.quantifier = quantifier })
458 | return this
459 | }
460 |
461 | fun objectLiteralExpression(
462 | quantifier: Quantifier = Quantifier.Any,
463 | block: LinRule.ObjectLiteralExpression.() -> LinRule
464 | ): LinRule {
465 | children.add(LinRule.ObjectLiteralExpression().block().also { it.quantifier = quantifier })
466 | return this
467 | }
468 |
469 | class File : LinRule(UFile::class)
470 | class Import : LinRule(UImportStatement::class)
471 | class Declaration : LinRule(UDeclaration::class)
472 | class Type : LinRule(UClass::class)
473 | class Initializer : LinRule(UClassInitializer::class)
474 | class Method : LinRule(UMethod::class)
475 | class Variable : LinRule(UVariable::class)
476 | class Parameter : LinRule(UParameter::class)
477 | class Field : LinRule(UField::class)
478 | class LocalVariable : LinRule(ULocalVariable::class)
479 | class EnumConstant : LinRule(ULocalVariable::class)
480 | class Annotation : LinRule(UAnnotation::class)
481 | class Expression : LinRule(UExpression::class)
482 | class LabeledExpression : LinRule(ULabeledExpression::class)
483 | class DeclarationsExpression : LinRule(UDeclarationsExpression::class)
484 | class BlockExpression : LinRule(UBlockExpression::class)
485 | class QualifiedReferenceExpression : LinRule(UQualifiedReferenceExpression::class)
486 | class SimpleNameReferenceExpression :
487 | LinRule(USimpleNameReferenceExpression::class)
488 |
489 | class TypeReferenceExpression : LinRule(UTypeReferenceExpression::class)
490 | class CallExpression : LinRule(UCallExpression::class)
491 | class BinaryExpression : LinRule(UBinaryExpression::class)
492 | class BinaryExpressionWithType : LinRule(UBinaryExpressionWithType::class)
493 | class PolyadicExpression : LinRule(UPolyadicExpression::class)
494 | class ParenthesizedExpression : LinRule(UParenthesizedExpression::class)
495 | class UnaryExpression : LinRule(UUnaryExpression::class)
496 | class PrefixExpression : LinRule(UPrefixExpression::class)
497 | class PostfixExpression : LinRule(UPostfixExpression::class)
498 | class ExpressionList : LinRule(UExpressionList::class)
499 | class IfExpression : LinRule(UIfExpression::class)
500 | class SwitchExpression : LinRule(USwitchExpression::class)
501 | class SwitchClauseExpression : LinRule(USwitchClauseExpression::class)
502 | class WhileExpression : LinRule(UWhileExpression::class)
503 | class DoWhileExpression : LinRule(UDoWhileExpression::class)
504 | class ForExpression : LinRule(UForExpression::class)
505 | class ForEachExpression : LinRule(UForEachExpression::class)
506 | class TryExpression : LinRule(UTryExpression::class)
507 | class CatchClause : LinRule(UCatchClause::class)
508 | class LiteralExpression : LinRule(ULiteralExpression::class)
509 | class ThisExpression : LinRule(UThisExpression::class)
510 | class SuperExpression : LinRule(USuperExpression::class)
511 | class ReturnExpression : LinRule(UReturnExpression::class)
512 | class BreakExpression : LinRule(UBreakExpression::class)
513 | class ContinueExpression : LinRule(UContinueExpression::class)
514 | class ThrowExpression : LinRule(UThrowExpression::class)
515 | class ArrayAccessExpression : LinRule(UArrayAccessExpression::class)
516 | class CallableReferenceExpression : LinRule(UCallableReferenceExpression::class)
517 | class ClassLiteralExpression : LinRule(UClassLiteralExpression::class)
518 | class LambdaExpression : LinRule(ULambdaExpression::class)
519 | class ObjectLiteralExpression : LinRule(UObjectLiteralExpression::class)
520 | }
--------------------------------------------------------------------------------