├── .github ├── dependabot.yml └── workflows │ ├── gradle-wrapper-validation.yml │ └── gradle.yml ├── .gitignore ├── LICENSE ├── README.md ├── RELEASE.md ├── build.gradle ├── gradle ├── compile.gradle ├── dependencies.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── groovy │ └── org │ │ └── checkerframework │ │ └── gradle │ │ └── plugin │ │ ├── CheckerFrameworkExtension.groovy │ │ ├── CheckerFrameworkPlugin.groovy │ │ ├── CheckerFrameworkTaskExtension.groovy │ │ └── CreateManifestTask.groovy └── resources │ └── META-INF │ └── gradle-plugins │ └── org.checkerframework.properties └── test ├── groovy ├── org │ └── checkerframework │ │ └── gradle │ │ └── plugin │ │ ├── CheckerFrameworkExtensionSpec.groovy │ │ └── CheckerFrameworkPluginSpec.groovy └── test │ └── BaseSpecification.groovy └── resources └── maven ├── com └── google │ └── errorprone │ └── javac │ └── 9+181-r4173-1 │ ├── javac-9+181-r4173-1.jar │ └── javac-9+181-r4173-1.pom └── org ├── checkerframework └── update.sh └── sonatype └── oss └── oss-parent └── 7 └── oss-parent-7.pom /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /.github/workflows/gradle-wrapper-validation.yml: -------------------------------------------------------------------------------- 1 | name: "Validate Gradle Wrapper" 2 | on: [push, pull_request] 3 | 4 | permissions: 5 | contents: read 6 | 7 | jobs: 8 | validation: 9 | name: "Validation" 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: gradle/wrapper-validation-action@v1 14 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | gradle: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v3 11 | - name: Set up JDK 12 | uses: actions/setup-java@v3 13 | with: 14 | distribution: 'temurin' 15 | java-version: 8 16 | - name: Build with Gradle 17 | run: ./gradlew build --info --stacktrace --parallel 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Gradle project-specific cache directory 2 | .gradle 3 | 4 | # Ignore Gradle build output directory 5 | build 6 | 7 | # IDEA 8 | .idea/ 9 | *.iml -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gradle Checker Framework Plugin 2 | 3 | [![License](https://img.shields.io/badge/license-apache%202.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0) 4 | ![Build Status](https://github.com/kelloggm/checkerframework-gradle-plugin/actions/workflows/gradle.yml/badge.svg) 5 | 6 | This plugin configures `JavaCompile` tasks to use the [Checker Framework](https://checkerframework.org) for pluggable type-checking. 7 | 8 | ## Download 9 | 10 | Add the following to your `build.gradle` file: 11 | 12 | ```groovy 13 | plugins { 14 | // Checker Framework pluggable type-checking 15 | id 'org.checkerframework' version '0.6.55' 16 | } 17 | 18 | apply plugin: 'org.checkerframework' 19 | ``` 20 | 21 | The `org.checkerframework` plugin modifies existing Java 22 | compilation tasks. You should apply it *after* 23 | whatever plugins introduce your Java compilation tasks (usually the `java` 24 | or `java-library` plugin for non-Android builds). 25 | 26 | ## Configuration 27 | 28 | ### Configuring which checkers to use 29 | 30 | The `checkerFramework.checkers` property lists which checkers will be run. 31 | 32 | For example, using Groovy syntax in a `build.gradle` file: 33 | 34 | ```groovy 35 | checkerFramework { 36 | checkers = [ 37 | 'org.checkerframework.checker.nullness.NullnessChecker', 38 | 'org.checkerframework.checker.units.UnitsChecker' 39 | ] 40 | } 41 | ``` 42 | 43 | The same example, using Kotlin syntax in a `build.gradle.kts` file: 44 | 45 | ```kotlin 46 | // In Kotlin, you need to import CheckerFrameworkExtension explicitly: 47 | import org.checkerframework.gradle.plugin.CheckerFrameworkExtension 48 | 49 | configure { 50 | checkers = listOf( 51 | "org.checkerframework.checker.nullness.NullnessChecker", 52 | "org.checkerframework.checker.units.UnitsChecker" 53 | ) 54 | } 55 | ``` 56 | 57 | For a list of checkers, see the [Checker Framework Manual](https://checkerframework.org/manual/#introduction). 58 | 59 | ### Providing checker-specific options to the compiler 60 | 61 | You can set the `checkerFramework.extraJavacArgs` property in order to pass additional options to the compiler when running 62 | a typechecker. 63 | 64 | For example, to use a stub file: 65 | 66 | ```groovy 67 | checkerFramework { 68 | extraJavacArgs = [ 69 | '-Werror', 70 | '-Astubs=/path/to/my/stub/file.astub' 71 | ] 72 | } 73 | ``` 74 | 75 | ### Configuring third-party checkers 76 | 77 | To use a third-party typechecker (i.e. one that is not distributed with the Checker Framework), 78 | add a dependency to the `checkerFramework` dependency configuration. 79 | 80 | For example, to use the [Glacier](http://mcoblenz.github.io/Glacier/) immutability checker: 81 | 82 | ```groovy 83 | dependencies { 84 | ... 85 | checkerFramework 'edu.cmu.cs.glacier:glacier:0.1' 86 | } 87 | ``` 88 | 89 | You should also use a `checkerFramework` dependency for anything needed by a checker you 90 | are running. For example, if you are using the 91 | [Subtyping Checker](https://checkerframework.org/manual/#subtyping-checker) with 92 | custom type qualifiers, you should add a `checkerFramework` dependency referring to 93 | the definitions of the custom qualifiers. 94 | 95 | ### Specifying a Checker Framework version 96 | 97 | Version 0.6.55 of this plugin uses Checker Framework version 3.49.4 by default. 98 | Anytime you upgrade to a newer version of this plugin, 99 | it might use a different version of the Checker Framework. 100 | 101 | You can use a Checker Framework 102 | [version](https://github.com/typetools/checker-framework/releases) that is 103 | different than this plugin's default. For example, if you want to use Checker 104 | Framework version 3.4.0, then you should add the following text to 105 | `build.gradle`, after `apply plugin: 'org.checkerframework'`: 106 | 107 | ```groovy 108 | dependencies { 109 | compileOnly 'org.checkerframework:checker-qual:3.4.0' 110 | testCompileOnly 'org.checkerframework:checker-qual:3.4.0' 111 | checkerFramework 'org.checkerframework:checker:3.4.0' 112 | } 113 | ``` 114 | 115 | You can use the Checker Framework from the local Maven repository by first deploying it 116 | (run `./gradlew PublishToMavenLocal` in `.../checker-framework/`), then editing your 117 | project's buildfile to set the version number and to add 118 | 119 | ```groovy 120 | repositories { 121 | mavenLocal() 122 | } 123 | ``` 124 | 125 | You can also use a locally-built version of the Checker Framework: 126 | 127 | ```groovy 128 | // To use a locally-built Checker Framework, run gradle with "-PcfLocal". 129 | if (project.hasProperty("cfLocal")) { 130 | def cfHome = String.valueOf(System.getenv("CHECKERFRAMEWORK")) 131 | dependencies { 132 | compileOnly files(cfHome + "/checker/dist/checker-qual.jar") 133 | testCompileOnly files(cfHome + "/checker/dist/checker-qual.jar") 134 | checkerFramework files(cfHome + "/checker/dist/checker.jar") 135 | } 136 | } 137 | ``` 138 | 139 | The same example, using Kotlin syntax in a `build.gradle.kts` file: 140 | 141 | ```kotlin 142 | if (project.hasProperty("cfLocal")) { 143 | val cfHome = System.getenv("CHECKERFRAMEWORK") 144 | dependencies { 145 | compileOnly(files(cfHome + "/checker/dist/checker-qual.jar")) 146 | testCompileOnly(files(cfHome + "/checker/dist/checker-qual.jar")) 147 | checkerFramework(files(cfHome + "/checker/dist/checker.jar")) 148 | } 149 | } 150 | ``` 151 | 152 | You can also use a Checker Framework fork. For example, the "EISOP Framework" is a fork of the Checker Framework. To use it: 153 | 154 | ```groovy 155 | ext { 156 | versions = [ 157 | eisopVersion: '3.42.0-eisop1', 158 | ] 159 | } 160 | 161 | dependencies { 162 | compileOnly "io.github.eisop:checker-qual:${versions.eisopVersion}" 163 | testCompileOnly "io.github.eisop:checker-qual:${versions.eisopVersion}" 164 | checkerFramework "io.github.eisop:checker-qual:${versions.eisopVersion}" 165 | checkerFramework "io.github.eisop:checker:${versions.eisopVersion}" 166 | } 167 | ``` 168 | 169 | 170 | ### Incremental compilation 171 | 172 | By default, the plugin assumes that all checkers are "isolating incremental annotation processors" 173 | according to the Gradle terminology 174 | [here](https://docs.gradle.org/current/userguide/java_plugin.html#sec:incremental_annotation_processing). 175 | This assumption speeds up builds by enabling incremental compilation, but is unsafe: Gradle's 176 | documentation warns that annotation processors that use internal Javac APIs may crash, because 177 | Gradle wraps some of those APIs. The Checker Framework does use internal Javac APIs, so you 178 | might encounter such a crash, which would appear as a `ClassCastException` referencing some 179 | internal Javac class. If you encounter such a crash, you can disable incremental 180 | compilation in your build using the following code in your `checkerFramework` configuration block: 181 | 182 | ```groovy 183 | checkerFramework { 184 | incrementalize = false 185 | } 186 | ``` 187 | 188 | ### Per-Task Configuration 189 | 190 | You can also use a `checkerFramework` block to configure individual tasks. This 191 | can be useful for skipping the Checker Framework on generated code: 192 | 193 | ```build.gradle 194 | tasks.withType(JavaCompile).configureEach { 195 | // Don't run the checker on generated code. 196 | if (name.equals("compileMainGeneratedDataTemplateJava") 197 | || name.equals("compileMainGeneratedRestJava")) { 198 | checkerFramework { 199 | skipCheckerFramework = true 200 | } 201 | } 202 | } 203 | ``` 204 | 205 | Currently, the only supported option is `skipCheckerFramework`. 206 | 207 | ### Other options 208 | 209 | * You can disable the Checker Framework temporarily (e.g. when testing something unrelated) 210 | either in your build file or from the command line. In your build file: 211 | 212 | ```groovy 213 | checkerFramework { 214 | skipCheckerFramework = true 215 | } 216 | ``` 217 | 218 | From the command line, add `-PskipCheckerFramework` to your gradle invocation. 219 | This property can also take an argument: 220 | anything other than `false` results in the Checker Framework being skipped. 221 | 222 | * By default, the plugin applies the selected checkers to all `JavaCompile` targets, 223 | including test targets such as `testCompileJava`. 224 | 225 | Here is how to prevent checkers from being applied to test targets: 226 | 227 | ```groovy 228 | checkerFramework { 229 | excludeTests = true 230 | } 231 | ``` 232 | 233 | The check for test targets is entirely syntactic: this option will not apply the checkers 234 | to any task whose name includes "test", ignoring case. 235 | 236 | * If you encounter errors of the form `zip file name too long` when configuring your 237 | Gradle project, you can use the following code to skip this plugin's version check, 238 | which reads the manifest file of the version of the Checker Framework you are actually 239 | using: 240 | 241 | ```groovy 242 | checkerFramework { 243 | skipVersionCheck = true 244 | } 245 | ``` 246 | 247 | 248 | ### Multi-project builds 249 | 250 | In a project with subprojects, you should apply the project to each Java 251 | subproject (and to the top-level project, in the unlikely case that it is a Java 252 | project). Here are two approaches. 253 | 254 | **Approach 1:** 255 | All Checker Framework configuration (the `checkerFramework` block and any 256 | `dependencies`) remains in the top-level `build.gradle` file. Put it in a 257 | `subprojects` block (or an `allprojects` block in the unlikely case that the 258 | top-level project is a Java project). For example: 259 | 260 | ```groovy 261 | plugins { 262 | id 'org.checkerframework' version '0.6.55' apply false 263 | } 264 | 265 | subprojects { subproject -> 266 | apply plugin: 'org.checkerframework' 267 | 268 | checkerFramework { 269 | checkers = ['org.checkerframework.checker.index.IndexChecker'] 270 | } 271 | dependencies { 272 | checkerFramework 'org.checkerframework:checker:3.49.4' 273 | implementation 'org.checkerframework:checker-qual:3.49.4' 274 | } 275 | } 276 | ``` 277 | 278 | **Approach 2:** 279 | Apply the plugin in the `build.gradle` in each subproject as if it 280 | were a stand-alone project. You must do this if you require different configuration 281 | for different subprojects (for instance, if you want to run different checkers). 282 | 283 | ### Incompatibility with Error Prone 2.3.4 and earlier 284 | 285 | [Error Prone](https://errorprone.info/) 286 | uses the Checker Framework's dataflow analysis library. 287 | Unfortunately, Error Prone version 2.3.4 and earlier uses an old version of the library, so you 288 | cannot use both Error Prone and the current Checker Framework (because each 289 | one depends on a different version of the library). 290 | 291 | You can resolve this by: 292 | * upgrading to Error Prone version 2.4.0 or later, or 293 | * using a switch that causes your build to use either 294 | Error Prone or the Checker Framework, but not both. 295 | 296 | Here is an example of the latter approach: 297 | 298 | ``` 299 | plugins { 300 | id "net.ltgt.errorprone" version "1.1.1" apply false 301 | // To do Checker Framework pluggable type-checking (and disable Error Prone), run: 302 | // ./gradlew compileJava -PuseCheckerFramework=true 303 | id 'org.checkerframework' version '0.6.55' apply false 304 | } 305 | 306 | if (!project.hasProperty("useCheckerFramework")) { 307 | ext.useCheckerFramework = "false" 308 | } 309 | if ("true".equals(project.ext.useCheckerFramework)) { 310 | apply plugin: 'org.checkerframework' 311 | } else { 312 | apply plugin: 'net.ltgt.errorprone' 313 | } 314 | 315 | def errorProneVersion = "2.3.4" 316 | def checkerFrameworkVersion = "3.49.4" 317 | 318 | dependencies { 319 | if ("true".equals(project.ext.useCheckerFramework)) { 320 | checkerFramework 'org.checkerframework:checker:' + checkerFrameworkVersion 321 | checkerFramework 'org.checkerframework:checker-qual:' + checkerFrameworkVersion 322 | } else { 323 | errorprone group: 'com.google.errorprone', name: 'error_prone_core', version: errorProneVersion 324 | } 325 | } 326 | 327 | if ("true".equals(project.ext.useCheckerFramework)) { 328 | checkerFramework { 329 | checkers = [ 330 | 'org.checkerframework.checker.interning.InterningChecker', 331 | 'org.checkerframework.checker.signature.SignatureChecker' 332 | ] 333 | } 334 | } else { 335 | // Configuration for the Error Prone linter. 336 | tasks.withType(JavaCompile).each { t -> 337 | if (!t.name.equals("compileTestInputJava") && !t.name.startsWith("checkTypes")) { 338 | t.toolChain ErrorProneToolChain.create(project) 339 | t.options.compilerArgs += [ 340 | '-Xep:StringSplitter:OFF', 341 | '-Xep:ReferenceEquality:OFF' // use Interning Checker instead 342 | ] 343 | } 344 | } 345 | } 346 | ``` 347 | 348 | ## Java 9+ compatibility 349 | 350 | The Checker Framework inserts inferred annotations into bytecode even if none appear in source code, 351 | so you must make them known to the compiler even if you write no annotations in your code. 352 | When running the plugin on a Java 9+ project that uses modules, 353 | you need to add annotations to the module path. 354 | 355 | Add following to your `module-info.java`: 356 | 357 | ```java 358 | requires org.checkerframework.checker.qual; 359 | ``` 360 | 361 | The addition of `requires` is typcially enough. 362 | 363 | If it does not fix your compilation issues, you can additionally add the `checker-qual.jar` 364 | artifact (which only contains annotations) to the module path: 365 | 366 | ```groovy 367 | checkerFramework { 368 | configurations.compileOnly.setCanBeResolved(true) 369 | extraJavacArgs = [ 370 | '--module-path', configurations.compileOnly.asPath 371 | ] 372 | } 373 | ``` 374 | 375 | ## Lombok compatibility 376 | 377 | This plugin automatically interacts with 378 | the [Lombok Gradle Plugin](https://plugins.gradle.org/plugin/io.freefair.lombok) 379 | to delombok your source code before it is passed to the Checker Framework 380 | for typechecking. This plugin does not support any other use of Lombok. 381 | 382 | For the Checker Framework to work properly on delombok'd source code, 383 | you must include the following key in your project's `lombok.config` file: 384 | 385 | ``` 386 | lombok.addLombokGeneratedAnnotation = true 387 | ``` 388 | 389 | By default, Lombok suppresses all warnings in the code it generates. If you 390 | want to typecheck the code that Lombok generates, use the `suppressLombokWarnings` 391 | configuration key: 392 | 393 | ``` 394 | checkerFramework { 395 | suppressLombokWarnings = false 396 | } 397 | ``` 398 | 399 | Note that doing so will cause *all* tools (including Javac itself) to begin issuing 400 | warnings in the code that Lombok generates. 401 | 402 | ## Using a locally-built plugin 403 | 404 | You can build the plugin locally rather than downloading it from Maven Central. 405 | 406 | To build the plugin from source, run `./gradlew build`. 407 | 408 | If you want to use a locally-built version of the plugin, you can publish the plugin to your 409 | local Maven repository by running `./gradlew publishToMavenLocal`. Then, add the following to 410 | the `settings.gradle` file in the Gradle project that you want to use the plugin: 411 | 412 | ``` 413 | pluginManagement { 414 | repositories { 415 | mavenLocal() 416 | gradlePluginPortal() 417 | } 418 | } 419 | ``` 420 | 421 | ### JDK 8 vs JDK 9+ implementation details 422 | 423 | The plugin attempts to automatically configure the Checker Framework on both Java 8 and Java 9+ JVMs, 424 | following the [best practices in the Checker Framework manual](https://checkerframework.org/manual/#javac). 425 | In particular: 426 | * If both the JVM and target versions are 8, it applies the Java 8 annotated JDK. 427 | * If the JVM version is 9+ and the target version is 8 (and the Checker Framework 428 | version is >= 2.11.0), use the Error Prone javac compiler. 429 | * If the JVM version is 9+, use the `--add-opens` option to `javac`. 430 | 431 | ## Credits 432 | 433 | This project started as a fork of [an abandoned plugin built by jaredsburrows](https://github.com/jaredsburrows/gradle-checker-framework-plugin). 434 | [![Twitter Follow](https://img.shields.io/twitter/follow/jaredsburrows.svg?style=social)](https://twitter.com/jaredsburrows) 435 | 436 | 437 | ## License 438 | 439 | Licensed under the Apache License, Version 2.0 (the "License"); 440 | you may not use this file except in compliance with the License. 441 | You may obtain a copy of the License at 442 | 443 | http://www.apache.org/licenses/LICENSE-2.0 444 | 445 | Unless required by applicable law or agreed to in writing, software 446 | distributed under the License is distributed on an "AS IS" BASIS, 447 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 448 | See the License for the specific language governing permissions and 449 | limitations under the License. 450 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | ## Making and merging pull requests 2 | 3 | The Checker Framework Gradle plugin (which this repository contains) 4 | uses a continuous-delivery style of releases: any time that the 5 | behavior of the plugin changes, a new release is cut. 6 | 7 | ### Making a pull request 8 | 9 | All pull requests should be made from a feature branch. Never push 10 | directly to `master`. 11 | 12 | After you have made the changes you wish to merge into `master`, 13 | you should: 14 | 1. If your pull request will change any behavior of the plugin (including 15 | bug fixes, new features, or updated dependencies), you should choose a new version string. Please 16 | try to respect [semantic versioning](https://semver.org/). Do not augment 17 | the major version without explicit approval from all the maintainers. 18 | 2. If you changed the version string, search for the current plugin version 19 | in the directory containing this file, and replace all instances of it with 20 | the new version string (currently only in `README.md` and `build.gradle`). 21 | Commit the result. 22 | 3. Push to your feature branch. 23 | 4. Make a pull request against the `master` branch. 24 | 25 | ### Merging a pull request 26 | 27 | #### Prequisites 28 | 29 | * Copy the publishing credentials to your `~/.gradle/gradle.properties` file. 30 | The credentials are stored in the same place as the credentials used to make 31 | a Checker Framework release, in a `gradle.properties` file. 32 | To gain access to the credentials, contact one of the maintainers privately. 33 | 34 | #### Release process 35 | 36 | 1. Review the pull request. If you approve it, proceed. 37 | 2. Ensure that the GitHub Actions CI build passes in the pull request. 38 | 3. Ensure that the new version string in the pull request is not already in use. Check 39 | [the plugin's portal page](https://plugins.gradle.org/plugin/org.checkerframework) 40 | to see if this version has already been released. 41 | 4. If the version string is already in use, change it or ask the author of the pull 42 | request to do so. 43 | 5. Squash and merge the pull request. 44 | 6. On your local machine, check out the `master` branch and run `git pull origin master`. 45 | 7. Run `./gradlew publishPlugins` from the top-level project directory 46 | (which should also contain this file). 47 | 48 | ### Updating the Checker Framework version 49 | 50 | The default version of the Checker Framework used by the plugin 51 | should be updated after every Checker Framework release. 52 | The Checker Framework is typically released monthly. 53 | Updating the Checker Framework should 54 | be done like any other pull request. To update the plugin to 55 | use the [latest version](https://github.com/typetools/checker-framework/blob/master/docs/CHANGELOG.md) 56 | of the Checker Framework: 57 | * Create a feature branch. 58 | * Update the .jar and .pom files. 59 | Run: 60 | ```(cd src/test/resources/maven/org/checkerframework && update.sh NEW_CF_VERSION_NUMBER)``` 61 | (If you don't do this, you may get an error such as 62 | "Could not find org.checkerframework:checker:2.11.1.") 63 | You might need to wait for Maven Central to make the new `.jar` and `.pom` files available. 64 | * Replace the old version number anywhere it appears in this repository. 65 | * Update the version of the plugin, as for any pull request; see above for instructions. 66 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.github.ben-manes.versions' version '0.42.0' 3 | id 'com.gradle.plugin-publish' version '1.1.0' 4 | id 'java-gradle-plugin' 5 | id 'groovy' 6 | id 'maven-publish' 7 | } 8 | 9 | repositories { 10 | google() 11 | 12 | // The gradle plugin portal, so that we can depend on other plugins. 13 | maven { 14 | url "https://plugins.gradle.org/m2/" 15 | } 16 | } 17 | 18 | apply from: 'gradle/dependencies.gradle' 19 | 20 | sourceCompatibility = 1.8 21 | targetCompatibility = 1.8 22 | 23 | dependencies { 24 | implementation localGroovy() 25 | 26 | // The Lombok Gradle plugin, so that we can delombok sources if lombok would be applied. 27 | implementation 'io.freefair.gradle:lombok-plugin:5.3.3.3' 28 | 29 | testImplementation deps.android.tools.build.gradle 30 | testImplementation deps.spock 31 | testCompileOnly 'junit:junit:4.12' 32 | } 33 | 34 | group 'org.checkerframework' 35 | version '0.6.55' 36 | 37 | gradlePlugin { 38 | website = 'https://github.com/kelloggm/checkerframework-gradle-plugin/blob/master/README.md' 39 | vcsUrl = 'https://github.com/kelloggm/checkerframework-gradle-plugin' 40 | plugins { 41 | checkerframeworkPlugin { 42 | id = 'org.checkerframework' 43 | displayName = 'Checker Framework Gradle Plugin' 44 | description = 'Re-usable build logic for extending the Java type system via the Checker Framework,' + 45 | ' for Gradle builds' 46 | implementationClass = 'org.checkerframework.gradle.plugin.CheckerFrameworkPlugin' 47 | tags.set(['checkerframework', 'checker', 'typechecker', 'pluggable types', 'formal verification']) 48 | } 49 | } 50 | } 51 | 52 | apply from: 'gradle/compile.gradle' 53 | 54 | // Gradle 7+ requires a duplicates strategy whenever there might be duplication, 55 | // even if the cause is some other plugin (which I think is the case for us). 56 | // This setting (INCLUDE) was the default for Gradle 6 and earlier. 57 | tasks.withType(Copy).all { duplicatesStrategy = DuplicatesStrategy.INCLUDE} 58 | -------------------------------------------------------------------------------- /gradle/compile.gradle: -------------------------------------------------------------------------------- 1 | tasks.withType(JavaCompile) { 2 | sourceCompatibility = rootProject.versions.java 3 | targetCompatibility = rootProject.versions.java 4 | 5 | // Show all warnings except boot classpath 6 | configure(options) { 7 | compilerArgs << '-Xlint:all' // Turn on all warnings 8 | compilerArgs << '-Werror' // Turn warnings into errors 9 | encoding = 'utf-8' 10 | } 11 | } 12 | 13 | tasks.withType(GroovyCompile) { 14 | sourceCompatibility = rootProject.versions.java 15 | targetCompatibility = rootProject.versions.java 16 | 17 | // Show all warnings except boot classpath 18 | configure(options) { 19 | compilerArgs << '-Xlint:all' // Turn on all warnings 20 | compilerArgs << '-Werror' // Turn warnings into errors 21 | compilerArgs << '-proc:none' // Google AutoValue APs are leaking onto compile classpath, causing warning 22 | // from Gradle 23 | encoding = 'utf-8' 24 | } 25 | } 26 | 27 | tasks.withType(Test) { 28 | // Turn on logging for all tests, filter to show failures/skips only 29 | testLogging { 30 | exceptionFormat 'full' 31 | showCauses true 32 | showExceptions true 33 | showStackTraces true 34 | events 'failed', 'skipped', 'started', 'passed' 35 | } 36 | 37 | maxParallelForks = 32 38 | } 39 | 40 | tasks.withType(Groovydoc) { 41 | docTitle = "${project.name} ${project.version}" 42 | header = project.name 43 | link('http://docs.oracle.com/javase/8/docs/api/', 44 | 'http://docs.oracle.com/javaee/7/api/', 45 | 'http://groovy.codehaus.org/gapi/') 46 | exclude '**/*Spec.java' 47 | } 48 | -------------------------------------------------------------------------------- /gradle/dependencies.gradle: -------------------------------------------------------------------------------- 1 | ext.versions = [ 2 | 'java': '1.8' 3 | ] 4 | 5 | ext.deps = [ 6 | 'android': [ 7 | 'tools': [ 8 | 'build': [ 9 | 'gradle': 'com.android.tools.build:gradle:3.2.1', 10 | ] 11 | ] 12 | ], 13 | 'spock' : 'org.spockframework:spock-core:2.1-groovy-3.0', 14 | ] 15 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kelloggm/checkerframework-gradle-plugin/a81be3ce6c85f62943931da30c10b27bb500c42a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * 6 | * Detailed information about configuring a multi-project build in Gradle can be found 7 | * in the user guide at https://docs.gradle.org/5.0/userguide/multi_project_builds.html 8 | */ 9 | 10 | rootProject.name = 'checkerframework-gradle-plugin' 11 | -------------------------------------------------------------------------------- /src/main/groovy/org/checkerframework/gradle/plugin/CheckerFrameworkExtension.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | class CheckerFrameworkExtension { 4 | // Which checkers will be run. Each element is a fully-qualified class name, 5 | // such as "org.checkerframework.checker.nullness.NullnessChecker". 6 | List checkers = [] 7 | 8 | // A list of extra options to pass directly to javac when running typecheckers 9 | List extraJavacArgs = [] 10 | 11 | Boolean excludeTests = false 12 | 13 | // If you encounter "zip file too large" errors, you can set this flag to avoid 14 | // the standard version check which unzips a jar to look at its manifest. 15 | Boolean skipVersionCheck = false 16 | 17 | // If true, generate @SuppressWarnings("all") annotations on Lombok-generated code, 18 | // which is Lombok's default but could permit unsoundness from the Checker Framework. 19 | // For an example, see https://github.com/kelloggm/checkerframework-gradle-plugin/issues/85. 20 | Boolean suppressLombokWarnings = true 21 | 22 | // Flag to disable the CF easily, from e.g. the command-line. 23 | Boolean skipCheckerFramework = false 24 | 25 | // Flag to disable automatic incremental compilation. By default, the Checker Framework 26 | // assumes that all checkers are incremental with type "isolating". Gradle's documentation 27 | // suggests that annotation processors that interact with Javac APIs might crash because 28 | // Gradle wraps some Javac APIs, so if you encounter such a crash you can disable incremental 29 | // compilation using this flag. 30 | Boolean incrementalize = true 31 | } 32 | -------------------------------------------------------------------------------- /src/main/groovy/org/checkerframework/gradle/plugin/CheckerFrameworkPlugin.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | import org.gradle.api.Task 4 | import org.gradle.api.artifacts.DependencyResolutionListener 5 | import org.gradle.api.artifacts.ResolvableDependencies 6 | import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency 7 | import org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency 8 | import org.gradle.util.GradleVersion 9 | 10 | import java.util.jar.JarFile 11 | 12 | import org.gradle.api.Action 13 | import org.gradle.api.JavaVersion 14 | import org.gradle.api.Plugin 15 | import org.gradle.api.Project 16 | import org.gradle.api.logging.Logger 17 | import org.gradle.api.logging.Logging 18 | import org.gradle.api.tasks.compile.AbstractCompile 19 | 20 | import io.freefair.gradle.plugins.lombok.LombokPlugin 21 | 22 | final class CheckerFrameworkPlugin implements Plugin { 23 | // Handles pre-3.0 and 3.0+, "com.android.base" was added in AGP 3.0 24 | private static final def ANDROID_IDS = [ 25 | "com.android.application", 26 | "com.android.feature", 27 | "com.android.instantapp", 28 | "com.android.library", 29 | "com.android.test"] 30 | // Checker Framework configurations and dependencies 31 | 32 | // Whenever this line is changed, you need to change all occurrences in README.md. 33 | private final static def LIBRARY_VERSION = "3.49.4" 34 | 35 | private final static def ANNOTATED_JDK_NAME_JDK8 = "jdk8" 36 | private final static def ANNOTATED_JDK_CONFIGURATION = "checkerFrameworkAnnotatedJDK" 37 | private final static def ANNOTATED_JDK_CONFIGURATION_DESCRIPTION = "A copy of JDK classes with Checker Framework type qualifiers inserted." 38 | private final static def CONFIGURATION = "checkerFramework" 39 | private final static def CONFIGURATION_DESCRIPTION = "The Checker Framework: custom pluggable types for Java." 40 | private final static def JAVA_COMPILE_CONFIGURATION = "compileOnly" 41 | private final static def TEST_COMPILE_CONFIGURATION = "testCompileOnly" 42 | private final static def CHECKER_DEPENDENCY = "org.checkerframework:checker:${LIBRARY_VERSION}" 43 | private final static def CHECKER_QUAL_DEPENDENCY = "org.checkerframework:checker-qual:${LIBRARY_VERSION}" 44 | 45 | private final static Logger LOG = Logging.getLogger(CheckerFrameworkPlugin) 46 | 47 | private final static String checkerFrameworkManifestCreationTaskName = 'createCheckerFrameworkManifest' 48 | 49 | /** 50 | * Which subfolder of /build/ to put the Checker Framework manifest in. 51 | */ 52 | private final static def manifestLocation = "/checkerframework/" 53 | 54 | /** 55 | * Configure each task in {@code project} with the given {@code taskType}. 56 | *

57 | * We prefer to configure with {@link 58 | * org.gradle.api.tasks.TaskCollection#configureEach(org.gradle.api.Action)} 59 | * rather than {@link 60 | * org.gradle.api.tasks.TaskCollection#all(org.gradle.api.Action)}, but {@code 61 | * configureEach} is only available on Gradle 4.9 and newer, so this method 62 | * dynamically picks the better candidate based on the current Gradle version. 63 | *

64 | * See also: 65 | * Gradle documentation: Task Configuration Avoidance 66 | */ 67 | private static void configureTasks(Project project, Class taskType, Action configure) { 68 | // TODO: why does lazy configuration fail on Java 8 JVMs? https://github.com/typetools/checker-framework/pull/3557 69 | if (GradleVersion.current() < GradleVersion.version("4.9") 70 | || !JavaVersion.current().isJava9Compatible()) { 71 | project.tasks.withType(taskType).all configure 72 | } else { 73 | project.tasks.withType(taskType).configureEach configure 74 | } 75 | } 76 | 77 | @Override void apply(Project project) { 78 | // Either get an existing CF config, or create a new one if none exists 79 | CheckerFrameworkExtension userConfig = project.extensions.findByType(CheckerFrameworkExtension.class)?: 80 | project.extensions.create("checkerFramework", CheckerFrameworkExtension) 81 | boolean applied = false 82 | (ANDROID_IDS + "java").each { id -> 83 | project.pluginManager.withPlugin(id) { 84 | if (!applied) { 85 | LOG.info('Found plugin {}, applying checker compiler options.', id) 86 | configureProject(project, userConfig) 87 | applyToProject(project, userConfig) 88 | applied = true 89 | } 90 | } 91 | } 92 | 93 | if (!applied) { 94 | // Ensure that dependencies and configurations are available, even if no Java/Android plugins were found, 95 | // to support configuration in a super project with many Java/Android subprojects. 96 | configureProject(project, userConfig) 97 | } 98 | 99 | project.afterEvaluate { 100 | if (!applied) LOG.warn('No android or java plugins found in the project {}, checker compiler options will not be applied.', project.name) 101 | } 102 | } 103 | 104 | private static handleLombokPlugin(Project project, CheckerFrameworkExtension userConfig) { 105 | project.getPlugins().withType(io.freefair.gradle.plugins.lombok.LombokPlugin.class, new Action() { 106 | void execute(LombokPlugin lombokPlugin) { 107 | 108 | def warnAboutCMCLombokInteraction = 109 | (userConfig.checkers.contains('org.checkerframework.checker.objectconstruction.ObjectConstructionChecker') 110 | || userConfig.checkers.contains("org.checkerframework.checker.calledmethods.CalledMethodsChecker")) 111 | 112 | def cmcLombokInteractionWarningMessage = 113 | "The Object Construction or Called Methods Checker was enabled, but Lombok config generation is disabled. " + 114 | "Ensure that your lombok.config file contains 'lombok.addLombokGeneratedAnnotation = true', " + 115 | "or all warnings related to misuse of Lombok builders will be disabled." 116 | 117 | if (warnAboutCMCLombokInteraction) { 118 | // Because we don't know whether the user has done this or not, use the info logging level instead of warning, 119 | // as above, where we know that no config was generated. And, we want to avoid nagging the user. 120 | LOG.info(cmcLombokInteractionWarningMessage) 121 | } 122 | 123 | if (skipCheckerFramework(project, userConfig)) { 124 | return 125 | } 126 | 127 | def delombokTasks = project.getTasks().findAll { task -> 128 | task.name.contains("delombok") 129 | } 130 | 131 | if (delombokTasks.size() != 0) { 132 | 133 | // change every compile task so that it: 134 | // 1. depends on delombok, and 135 | // 2. uses the delombok'd source code as its source set 136 | 137 | project.tasks.withType(AbstractCompile).all { compile -> 138 | 139 | // find the right delombok task 140 | def delombokTask = delombokTasks.find { task -> 141 | 142 | if (task.name.endsWith("delombok")) { 143 | // special-case the main compile task because it's just named "compileJava" 144 | // without anything else 145 | compile.name.equals("compileJava") 146 | } else { 147 | // "delombok" is 8 characters. 148 | compile.name.contains(task.name.substring(8)) 149 | } 150 | } 151 | 152 | // delombokTask can still be null; for example, if the code contains a compileScala task 153 | // Also, if we're skipping test tasks, don't bother delombok'ing them. 154 | if (delombokTask != null && !compile.getSource().isEmpty() 155 | && !(userConfig.excludeTests && delombokTask.name.toLowerCase().contains("test"))) { 156 | 157 | // The lombok plugin's default formatting is pretty-printing, without the @Generated annotations 158 | // that we need to recognize lombok'd code. 159 | delombokTask.format.put('generated', 'generate') 160 | 161 | if (userConfig.suppressLombokWarnings) { 162 | // Also re-add suppress warnings annotations so that we don't get warnings from generated 163 | // code. 164 | delombokTask.format.put('suppressWarnings', 'generate') 165 | } 166 | 167 | compile.setSource(delombokTask.target.getAsFile().get()) 168 | compile.dependsOn(delombokTask) 169 | } 170 | } 171 | } 172 | // lombok-generated code will always cause these warnings, because their default formatting is wrong 173 | // and can't be changed 174 | def swKeys = userConfig.extraJavacArgs.find { option -> option.startsWith("-AsuppressWarnings")} 175 | if (swKeys == null) { 176 | userConfig.extraJavacArgs += "-AsuppressWarnings=type.anno.before.modifier" 177 | } else { 178 | userConfig.extraJavacArgs += swKeys + ",type.anno.before.modifier" 179 | } 180 | } 181 | }) 182 | } 183 | 184 | private static configureProject(Project project, CheckerFrameworkExtension userConfig) { 185 | 186 | // Create a map of the correct configurations with dependencies 187 | def dependencyMap = [ 188 | [name: "${ANNOTATED_JDK_CONFIGURATION}", descripion: "${ANNOTATED_JDK_CONFIGURATION_DESCRIPTION}"]: "org.checkerframework:${ANNOTATED_JDK_NAME_JDK8}:${LIBRARY_VERSION}", 189 | [name: "${CONFIGURATION}", descripion: "${ANNOTATED_JDK_CONFIGURATION_DESCRIPTION}"] : "${CHECKER_DEPENDENCY}", 190 | [name: "${JAVA_COMPILE_CONFIGURATION}", descripion: "${CONFIGURATION_DESCRIPTION}"] : "${CHECKER_QUAL_DEPENDENCY}", 191 | [name: "${TEST_COMPILE_CONFIGURATION}", descripion: "${CONFIGURATION_DESCRIPTION}"] : "${CHECKER_QUAL_DEPENDENCY}", 192 | [name: "errorProneJavac", descripion: "the Error Prone Java compiler"] : "com.google.errorprone:javac:9+181-r4173-1" 193 | ] 194 | 195 | // Add the configurations, if they don't exist, so that users can add to them. 196 | dependencyMap.each { configuration, dependency -> 197 | if (!project.configurations.find { it.name == "$configuration.name".toString() }) { 198 | project.configurations.create(configuration.name) { files -> 199 | files.description = configuration.descripion 200 | files.visible = false 201 | } 202 | } 203 | } 204 | 205 | // Immediately before resolving dependencies, add the dependencies to the relevant 206 | // configurations. 207 | project.getGradle().addListener(new DependencyResolutionListener() { 208 | @Override 209 | void beforeResolve(ResolvableDependencies resolvableDependencies) { 210 | dependencyMap.each { configuration, dependency -> 211 | def depGroup = dependency.tokenize(':')[0] 212 | def depName = dependency.tokenize(':')[1] 213 | // Only add the dependency if it isn't already present, to avoid overwriting user configuration. 214 | // The check for the current Gradle version was added because DefaultSelfResolvingDependency 215 | // was removed in Gradle 8.7, but we still want to support not overwriting Checker Framework 216 | // dependencies defined that way for earlier Gradle versions. 217 | if (project.configurations."$configuration.name".dependencies.matching({ 218 | if (it instanceof DefaultExternalModuleDependency) { 219 | it.name.equals(depName) && it.group.equals(depGroup) 220 | } else if (GradleVersion.current().compareTo(GradleVersion.version("8.7")) < 0 && it instanceof DefaultSelfResolvingDependency) { 221 | it.getFiles().any { file -> 222 | file.toString().endsWith(depName + ".jar") 223 | } 224 | } else { 225 | // not sure what to do in the default case... 226 | false 227 | } 228 | }).isEmpty()) { 229 | project.configurations."$configuration.name".dependencies.add( 230 | project.dependencies.create(dependency)) 231 | } 232 | } 233 | 234 | // Only attempt to add each dependency once. 235 | project.getGradle().removeListener(this) 236 | } 237 | 238 | @Override 239 | void afterResolve(ResolvableDependencies resolvableDependencies) {} 240 | }) 241 | 242 | handleLombokPlugin(project, userConfig) 243 | configureTasks(project, AbstractCompile, { AbstractCompile compile -> 244 | def ext = compile.extensions.findByName("checkerFramework") 245 | if (ext == null) { 246 | LOG.info("Adding checkerFramework extension to task {}", compile.name) 247 | compile.extensions.create("checkerFramework", CheckerFrameworkTaskExtension) 248 | } else if (ext instanceof CheckerFrameworkTaskExtension) { 249 | LOG.debug("Task {} in project {} already has checkerFramework added to it;" + 250 | " make sure you're applying the org.checkerframework plugin after the Java plugin", compile.name, 251 | compile.project) 252 | } else { 253 | throw new IllegalStateException("Task " + compile.name + " in project " + compile.project + 254 | " already has a checkerFramework extension, but it's of an incorrect type " + ext.class) 255 | } 256 | }) 257 | } 258 | 259 | /** 260 | * Always call this method rather than using the skipCheckerFramework property directly. 261 | * Allows the user to set the property from the command line instead of in the build file, 262 | * if desired. 263 | */ 264 | private static boolean skipCheckerFramework(Project project, CheckerFrameworkExtension userConfig) { 265 | if (project.hasProperty('skipCheckerFramework')) { 266 | userConfig.skipCheckerFramework = project['skipCheckerFramework'] != "false" 267 | } 268 | return userConfig.skipCheckerFramework 269 | } 270 | 271 | private static applyToProject(Project project, CheckerFrameworkExtension userConfig) { 272 | 273 | // Apply checker to project 274 | project.afterEvaluate { 275 | 276 | if (skipCheckerFramework(project, userConfig)) { 277 | LOG.info("skipping the Checker Framework because skipCheckerFramework property is set") 278 | return 279 | } 280 | 281 | JavaVersion javaSourceVersion = project.plugins.hasPlugin('com.android.application') 282 | || project.plugins.hasPlugin('com.android.library') ? 283 | project.android.compileOptions.sourceCompatibility : 284 | project.java.getSourceCompatibility() 285 | 286 | // Check Java version. 287 | if (!javaSourceVersion.isJava8Compatible()) { 288 | throw new IllegalStateException("The Checker Framework does not support Java versions before 8.") 289 | } 290 | 291 | JavaVersion jvmVersion = JavaVersion.current(); 292 | 293 | // https://docs.gradle.org/current/userguide/toolchains.html 294 | def toolchain = project.java?.toolchain 295 | if (toolchain != null && toolchain.isConfigured()) { 296 | def toolchainVersion = toolchain.getLanguageVersion().get() 297 | def toolchainVersionInt = Integer.parseInt(toolchainVersion.toString()) 298 | if (toolchainVersionInt < 8) { 299 | throw new IllegalStateException("The Checker Framework does not support Java versions before 8.") 300 | } else { 301 | jvmVersion = JavaVersion.toVersion(toolchainVersionInt) 302 | } 303 | } 304 | 305 | // Decide whether to use ErrorProne Javac once configurations have been populated. 306 | boolean needErrorProneJavac = false 307 | boolean needJdk8Jar = false 308 | 309 | // The version string computation has side-effects that need to happen even for Java 11, 310 | // so it can't be guarded by the isJava8 call below. 311 | def versionString 312 | try { 313 | def actualCFDependencySet = project.configurations.checkerFramework.getAllDependencies() 314 | // Only check the name of the dependency (not the group), to support forks 315 | // of the CF that use the same version scheme, such as the EISOP fork. 316 | .matching({ dep -> dep.getName().equals("checker")}) 317 | if (actualCFDependencySet.size() == 0) { 318 | if (userConfig.skipVersionCheck) { 319 | versionString = LIBRARY_VERSION 320 | } else { 321 | // This line has a side-effect that's necessary for the checker to 322 | // be invoked, sometimes? I don't really understand why. 323 | versionString = new JarFile(project.configurations.checkerFramework.asPath).getManifest().getMainAttributes().getValue('Implementation-Version') 324 | } 325 | } else { 326 | // The call to iterator.next() is safe because we added this dependency above if it 327 | // wasn't specified by the user. 328 | versionString = actualCFDependencySet.iterator().next().getVersion() 329 | } 330 | } catch (Exception e) { 331 | versionString = LIBRARY_VERSION 332 | LOG.debug("An error occurred while trying to determine Checker Framework version. Proceeding with default version. Error caused by: {}", e.toString()) 333 | LOG.warn("No explicit dependency on the Checker Framework found, using default version {}", LIBRARY_VERSION) 334 | } 335 | 336 | if (javaSourceVersion.java8 && jvmVersion.isJava8()) { 337 | try { 338 | // The array accesses are safe because all CF version strings have at least two . in them. 339 | def majorVersion = versionString.tokenize(".")[0].toInteger() 340 | def minorVersion = versionString.tokenize(".")[1].toInteger() 341 | needErrorProneJavac = majorVersion >= 3 || (majorVersion == 2 && minorVersion >= 11) 342 | needJdk8Jar = majorVersion < 3 || (majorVersion == 3 && minorVersion <= 3) 343 | } catch (Exception e) { 344 | // if for any reason it's not possible to figure out the actual CF version, assume 345 | // errorprone javac is required 346 | needErrorProneJavac = true 347 | LOG.warn("Defaulting to ErrorProne Javac, because on a Java 8 JVM and" + 348 | " cannot determine exact Checker Framework version.", e) 349 | } 350 | } 351 | 352 | // To keep the plugin idempotent, check if the task already exists. 353 | def createManifestTask = project.tasks.findByName(checkerFrameworkManifestCreationTaskName) 354 | if (createManifestTask == null) { 355 | createManifestTask = project.task(checkerFrameworkManifestCreationTaskName, type: CreateManifestTask) 356 | createManifestTask.checkers = userConfig.checkers 357 | createManifestTask.incrementalize = userConfig.incrementalize 358 | } 359 | 360 | configureTasks(project, AbstractCompile, { AbstractCompile compile -> 361 | if (compile.extensions.checkerFramework.skipCheckerFramework) { 362 | LOG.info("skipping the Checker Framework for task " + compile.name + 363 | " because skipCheckerFramework property is set") 364 | return 365 | } 366 | if(userConfig.excludeTests && compile.name.toLowerCase().contains("test")) { 367 | LOG.info("skipping the Checker Framework for task {} because excludeTests property is set", compile.name) 368 | return 369 | } 370 | if (compile.hasProperty('options')) { 371 | compile.options.annotationProcessorPath = compile.options.annotationProcessorPath == null ? 372 | project.configurations.checkerFramework : 373 | project.configurations.checkerFramework.plus(compile.options.annotationProcessorPath) 374 | // Check whether to use the Error Prone javac 375 | if (needErrorProneJavac) { 376 | compile.options.forkOptions.jvmArgs += [ 377 | "-Xbootclasspath/p:${project.configurations.errorProneJavac.asPath}".toString() 378 | ] 379 | } 380 | 381 | // When running on Java 9+ code, the Checker Framework needs reflective access 382 | // to some JDK classes. Pass the arguments that make that possible. 383 | if (jvmVersion.isJava9Compatible()) { 384 | compile.options.forkOptions.jvmArgs += [ 385 | "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", 386 | "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", 387 | "--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", 388 | "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED", 389 | "--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED", 390 | "--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED", 391 | "--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", 392 | "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", 393 | "--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED" 394 | ] 395 | } 396 | if (jvmVersion.isJava8() && javaSourceVersion.isJava8() && needJdk8Jar) { 397 | compile.options.compilerArgs += [ 398 | "-Xbootclasspath/p:${project.configurations.checkerFrameworkAnnotatedJDK.asPath}".toString() 399 | ] 400 | } 401 | if (!userConfig.checkers.empty) { 402 | 403 | // If the user has already specified a processor manually, then 404 | // auto-discovery won't work. Instead, augment the list of specified 405 | // processors. 406 | int processorArgLocation = compile.options.compilerArgs.indexOf('-processor') 407 | if (processorArgLocation != -1) { 408 | String oldProcessors = compile.options.compilerArgs.get(processorArgLocation + 1) 409 | String newProcessors = userConfig.checkers.join(",") 410 | compile.options.compilerArgs.set(processorArgLocation + 1, oldProcessors + ',' + newProcessors) 411 | } else { 412 | compile.dependsOn(createManifestTask) 413 | // Add the manifest file to the annotation processor path, so that the javac 414 | // annotation processor discovery mechanism finds the checkers to use and 415 | // runs them alongside any other auto-discovered annotation processors. 416 | // Using the -processor flag to specify checkers would make the plugin incompatible 417 | // with other auto-discovered annotation processors, because the plugin uses auto-discovery. 418 | // We should warn about this: https://github.com/kelloggm/checkerframework-gradle-plugin/issues/50 419 | compile.options.annotationProcessorPath = compile.options.annotationProcessorPath.plus(project.files("${project.buildDir}" + manifestLocation)) 420 | } 421 | } 422 | 423 | try { 424 | userConfig.extraJavacArgs.forEach({option -> compile.options.compilerArgs << option}) 425 | } catch (UnsupportedOperationException e) { 426 | LOG.error("The Checker Framework Plugin tried to add an extraJavacArgs element to the compilerArgs for " + 427 | "the compile task named \"" + compile.name + "\", but an UnsupportedOperationException was " + 428 | "thrown. Sometimes, this is caused by using Kotlin's `listOf` method to define a set of compiler " + 429 | "arguments; `listOf` produces an immutable list, which leads to the exception. Consider using " + 430 | "`mutableListOf` to set compiler arguments instead.") 431 | throw e 432 | } 433 | 434 | ANDROID_IDS.each { id -> 435 | project.plugins.withId(id) { 436 | compile.options.bootstrapClasspath = project.files(System.getProperty("sun.boot.class.path")) + compile.options.bootstrapClasspath 437 | } 438 | } 439 | compile.options.fork = true 440 | } 441 | }) 442 | } 443 | } 444 | } 445 | -------------------------------------------------------------------------------- /src/main/groovy/org/checkerframework/gradle/plugin/CheckerFrameworkTaskExtension.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | /** 4 | * A Gradle extension for Checker Framework configuration for compile tasks. 5 | */ 6 | class CheckerFrameworkTaskExtension { 7 | /** 8 | * If the Checker Framework should be skipped for this compile task. 9 | */ 10 | Boolean skipCheckerFramework = false 11 | } 12 | -------------------------------------------------------------------------------- /src/main/groovy/org/checkerframework/gradle/plugin/CreateManifestTask.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.tasks.Input 5 | import org.gradle.api.tasks.OutputFile 6 | import org.gradle.api.tasks.TaskAction 7 | 8 | /** 9 | * This task generates a manifest file in the style of 10 | * https://checkerframework.org/manual/#checker-auto-discovery. 11 | * Once the plugin places this directory containing it on the annotation processor path, 12 | * javac can find the checkers via annotation processor discovery. 13 | */ 14 | class CreateManifestTask extends DefaultTask { 15 | 16 | private final static String manifestDirectoryName = "checkerframework/META-INF/services/" 17 | private final static String manifestFileName = "javax.annotation.processing.Processor" 18 | 19 | // Mark the checkers as incremental annotation processors for Gradle 20 | private final static String gradleManifestDirectoryName = "checkerframework/META-INF/gradle/" 21 | private final static String gradleManifestFileName = "incremental.annotation.processors" 22 | 23 | @Input 24 | String[] checkers = [] 25 | 26 | @Input 27 | boolean incrementalize = true 28 | 29 | @Input 30 | final String buildDirLocation = project.layout.getBuildDirectory().get().toString() 31 | 32 | /** 33 | * Creates a manifest file listing all the checkers to run. 34 | */ 35 | @TaskAction 36 | def generateManifest() { 37 | def manifestDir = new File(buildDirLocation + File.separator + "${manifestDirectoryName}") 38 | manifestDir.mkdirs() 39 | def manifestFile = new File("${manifestDir.absolutePath}" + File.separator + "${manifestFileName}") 40 | if (!manifestFile.createNewFile()) { 41 | manifestFile.delete() 42 | manifestFile.createNewFile() 43 | } 44 | manifestFile << this.checkers.join('\n') 45 | 46 | if (incrementalize) { 47 | def gradleManifestDir = new File(buildDirLocation + File.separator + "${gradleManifestDirectoryName}") 48 | gradleManifestDir.mkdirs() 49 | def gradleManifestFile = 50 | new File("${gradleManifestDir.absolutePath}" + File.separator + "${gradleManifestFileName}") 51 | if (!gradleManifestFile.createNewFile()) { 52 | gradleManifestFile.delete() 53 | gradleManifestFile.createNewFile() 54 | } 55 | // The following code treats all checkers as isolating annotation processors. 56 | // I think this is the right decision: checkers should be reasoning about 57 | // each method in isolation. But, we provide a way to disable incremental 58 | // compilation in the event that this decision is breaking for some particular 59 | // checker. 60 | def gradleManifestFileContents = "" 61 | // do a join, but add ",ISOLATING" after each entry 62 | for (int i = 0; i < this.checkers.length; i++) { 63 | gradleManifestFileContents += checkers[i] + ",ISOLATING" 64 | if (i != checkers.length - 1) { 65 | gradleManifestFileContents += "\n" 66 | } 67 | } 68 | 69 | gradleManifestFile << gradleManifestFileContents 70 | } 71 | } 72 | 73 | /** 74 | * Required so that this can incrementalized correctly, and so that `gradle clean build` behaves 75 | * the same as `gradle clean ; gradle build`. 76 | */ 77 | @OutputFile 78 | def getManifestLocation() { 79 | return "${buildDirLocation}" + File.separator + "${manifestDirectoryName}" + File.separator + "${manifestFileName}" 80 | } 81 | 82 | /** 83 | * Required so that this can incrementalized correctly, and so that `gradle clean build` behaves 84 | * the same as `gradle clean ; gradle build`. 85 | */ 86 | @OutputFile 87 | def getGradleManifestLocation() { 88 | return "${buildDirLocation}" + File.separator + "${gradleManifestDirectoryName}" + File.separator + "${gradleManifestFileName}" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/org.checkerframework.properties: -------------------------------------------------------------------------------- 1 | implementation-class=org.checkerframework.gradle.plugin.CheckerFrameworkPlugin 2 | -------------------------------------------------------------------------------- /src/test/groovy/org/checkerframework/gradle/plugin/CheckerFrameworkExtensionSpec.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | import org.gradle.testkit.runner.GradleRunner 4 | import org.gradle.testkit.runner.TaskOutcome 5 | import org.junit.Rule 6 | import org.junit.rules.TemporaryFolder 7 | import spock.lang.Specification 8 | 9 | final class CheckerFrameworkExtensionSpec extends Specification { 10 | @Rule TemporaryFolder testProjectDir = new TemporaryFolder() 11 | def buildFile 12 | private class JavaCode { 13 | private static def FAILS_INDEX_CHECKER = 14 | """ 15 | import org.checkerframework.checker.index.qual.NonNegative; 16 | import org.checkerframework.checker.index.qual.Positive; 17 | 18 | public class FailsIndexChecker { 19 | public static void main(String[] args) { 20 | @NonNegative int t = 0; 21 | @NonNegative int i = 0; 22 | @Positive int s = t + i; // not valid 23 | System.out.println("t + i = " + s); 24 | } 25 | } 26 | """.stripIndent().trim() 27 | private static def FAILS_NULLNESS_CHECKER = 28 | """ 29 | import org.checkerframework.checker.nullness.qual.NonNull; 30 | import org.checkerframework.checker.nullness.qual.Nullable; 31 | 32 | public class FailsNullnessChecker { 33 | public static void main(String[] args) { 34 | @Nullable String x = null; 35 | System.out.println("X = " + takesNonNull(x)); 36 | } 37 | 38 | static String takesNonNull(@NonNull String s) { 39 | return s; 40 | } 41 | } 42 | """.stripIndent().trim() 43 | } 44 | private class JavaClassSuccessOutput { 45 | private static def FAILS_INDEX_CHECKER = "t + i = 0" 46 | private static def FAILS_NULLNESS_CHECKER = "X = null" 47 | } 48 | private class JavaClassErrorOutput { 49 | private static def FAILS_NULLNESS_CHECKER = "FailsNullnessChecker.java:7: error: [argument]" 50 | private static def FAILS_INDEX_CHECKER = "FailsIndexChecker.java:8: error: [assignment]" 51 | } 52 | 53 | def "setup"() { 54 | buildFile = testProjectDir.newFile("build.gradle") 55 | } 56 | 57 | def "Project configured to use the Nullness Checker"() { 58 | given: "a project that applies the plugin without any configuration and can run the FailsNullnessChecker class" 59 | buildFile << """ 60 | ${buildFileThatRunsClass("FailsNullnessChecker")} 61 | 62 | checkerFramework { 63 | checkers = ["org.checkerframework.checker.nullness.NullnessChecker"] 64 | } 65 | """.stripIndent() 66 | 67 | and: "The source code contains a class that fails the NullnessChecker" 68 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 69 | new File(javaSrcDir, "FailsNullnessChecker.java") << JavaCode.FAILS_NULLNESS_CHECKER 70 | 71 | when: "the project is built, trying to run the Java class but failing" 72 | def result = GradleRunner.create() 73 | .withProjectDir(testProjectDir.root) 74 | .withArguments("run") 75 | .withPluginClasspath() 76 | .buildAndFail() 77 | 78 | then: "the error message explains why the code did not compile" 79 | result.output.contains(JavaClassErrorOutput.FAILS_NULLNESS_CHECKER) 80 | } 81 | 82 | def "Project configured to use the Nullness Checker does not use the Index Checker"() { 83 | given: "a project that applies the plugin without any configuration and can run the FailsIndexChecker class" 84 | buildFile << """ 85 | ${buildFileThatRunsClass("FailsIndexChecker")} 86 | 87 | checkerFramework { 88 | checkers = ["org.checkerframework.checker.nullness.NullnessChecker"] 89 | } 90 | """.stripIndent() 91 | 92 | and: "The source code contains a class that fails the Index Checker" 93 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 94 | new File(javaSrcDir, "FailsIndexChecker.java") << JavaCode.FAILS_INDEX_CHECKER 95 | 96 | when: "the project is built, running the Java class" 97 | def result = GradleRunner.create() 98 | .withProjectDir(testProjectDir.root) 99 | .withArguments("run") 100 | .withPluginClasspath() 101 | .build() 102 | 103 | then: "the build should succeed because only the Nullness Checker should be enabled" 104 | result.task(":run").outcome == TaskOutcome.SUCCESS 105 | 106 | and: "the Java class actually ran" 107 | result.output.contains(JavaClassSuccessOutput.FAILS_INDEX_CHECKER) 108 | } 109 | 110 | def "Project configured to use the Index Checker fails to compile FailsIndexChecker"() { 111 | given: "a project that applies the plugin configuring the Index Checker and can run the FailsIndexChecker class" 112 | buildFile << """ 113 | ${buildFileThatRunsClass("FailsIndexChecker")} 114 | 115 | checkerFramework { 116 | checkers = ["org.checkerframework.checker.index.IndexChecker"] 117 | } 118 | """ 119 | 120 | and: "The source code contains a class that fails the IndexChecker" 121 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 122 | new File(javaSrcDir, "FailsIndexChecker.java") << JavaCode.FAILS_INDEX_CHECKER 123 | 124 | when: "the project is built, trying to run the Java class but failing" 125 | def result = GradleRunner.create() 126 | .withProjectDir(testProjectDir.root) 127 | .withArguments("run") 128 | .withPluginClasspath() 129 | .buildAndFail() 130 | 131 | then: "the error message explains why the code did not compile" 132 | result.output.contains(JavaClassErrorOutput.FAILS_INDEX_CHECKER) 133 | } 134 | 135 | def "Project configured to use the Index Checker can compile and run FailsNullnessChecker"() { 136 | given: "a project that applies the plugin configuring the Index Checker and can run the FailsNullnessChecker class" 137 | buildFile << """ 138 | ${buildFileThatRunsClass("FailsNullnessChecker")} 139 | 140 | checkerFramework { 141 | checkers = ["org.checkerframework.checker.index.IndexChecker"] 142 | } 143 | """ 144 | 145 | and: "The source code contains a class that fails the NullnessChecker but not the IndexChecker" 146 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 147 | new File(javaSrcDir, "FailsNullnessChecker.java") << JavaCode.FAILS_NULLNESS_CHECKER 148 | 149 | when: "the project is built, running the Java class" 150 | def result = GradleRunner.create() 151 | .withProjectDir(testProjectDir.root) 152 | .withArguments("run") 153 | .withPluginClasspath() 154 | .build() 155 | 156 | then: "the build should succeed because only the Index Checker should be enabled" 157 | result.task(":run").outcome == TaskOutcome.SUCCESS 158 | 159 | and: "the Java class actually ran" 160 | result.output.contains(JavaClassSuccessOutput.FAILS_NULLNESS_CHECKER) 161 | } 162 | 163 | def "Project configured to use both Index Checker and Nullness Checker rejects both kinds of errors"() { 164 | given: "a project that applies the plugin configuring both nullness and Index Checker" 165 | buildFile << """ 166 | ${buildFileThatRunsClass("FailsNullnessChecker")} 167 | 168 | checkerFramework { 169 | checkers = ["org.checkerframework.checker.index.IndexChecker", 170 | "org.checkerframework.checker.nullness.NullnessChecker"] 171 | } 172 | """.stripIndent() 173 | 174 | and: "The source code contains classes that fails both checkers" 175 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 176 | new File(javaSrcDir, "FailsNullnessChecker.java") << JavaCode.FAILS_NULLNESS_CHECKER 177 | new File(javaSrcDir, "FailsIndexChecker.java") << JavaCode.FAILS_INDEX_CHECKER 178 | 179 | when: "the project is built, trying to run the Java class but failing" 180 | def result = GradleRunner.create() 181 | .withProjectDir(testProjectDir.root) 182 | .withArguments("run") 183 | .withPluginClasspath() 184 | .buildAndFail() 185 | 186 | then: "the error message explains why the classes did not compile" 187 | result.output.contains(JavaClassErrorOutput.FAILS_INDEX_CHECKER) || 188 | result.output.contains(JavaClassErrorOutput.FAILS_NULLNESS_CHECKER) 189 | } 190 | 191 | def "Project configured to use no checkers compiles source that would fail Nullness Checker and Index Checker"() { 192 | given: "a project that applies the plugin configuring no checkers" 193 | buildFile << """ 194 | ${buildFileThatRunsClass("FailsNullnessChecker")} 195 | 196 | checkerFramework { 197 | checkers = [] 198 | } 199 | """.stripIndent() 200 | 201 | and: "The source code contains classes that fails both checkers" 202 | def javaSrcDir = testProjectDir.newFolder("src", "main", "java") 203 | new File(javaSrcDir, "FailsNullnessChecker.java") << JavaCode.FAILS_NULLNESS_CHECKER 204 | new File(javaSrcDir, "FailsIndexChecker.java") << JavaCode.FAILS_INDEX_CHECKER 205 | 206 | when: "the project is built, running the Java class" 207 | def result = GradleRunner.create() 208 | .withProjectDir(testProjectDir.root) 209 | .withArguments("run") 210 | .withPluginClasspath() 211 | .build() 212 | 213 | then: "the build should succeed because the Nullness Checker should be enabled" 214 | result.task(":run").outcome == TaskOutcome.SUCCESS 215 | 216 | and: "the Java class actually ran" 217 | result.output.contains(JavaClassSuccessOutput.FAILS_NULLNESS_CHECKER) 218 | } 219 | 220 | private static def buildFileThatRunsClass(String className) { 221 | """ 222 | plugins { 223 | id "java" 224 | id "application" 225 | id "org.checkerframework" 226 | } 227 | 228 | repositories { 229 | maven { 230 | url "${getClass().getResource("/maven/").toURI()}" 231 | } 232 | } 233 | 234 | mainClassName = "${className}" 235 | """.stripIndent() 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/test/groovy/org/checkerframework/gradle/plugin/CheckerFrameworkPluginSpec.groovy: -------------------------------------------------------------------------------- 1 | package org.checkerframework.gradle.plugin 2 | 3 | import org.gradle.testkit.runner.BuildResult 4 | import org.gradle.testkit.runner.GradleRunner 5 | import org.gradle.util.GradleVersion 6 | import spock.lang.Unroll 7 | import test.BaseSpecification 8 | 9 | final class CheckerFrameworkPluginSpec extends BaseSpecification { 10 | static final List TESTED_GRADLE_VERSIONS = [ 11 | '3.4', 12 | '4.0', 13 | '4.8', 14 | '4.9', 15 | '4.10', 16 | '5.0', 17 | '5.5', 18 | '6.0', 19 | '6.4', 20 | '6.5', 21 | ] 22 | 23 | @Unroll def "java project running licenseReport with gradle #gradleVersion"() { 24 | given: 25 | buildFile << 26 | """ 27 | plugins { 28 | id "java" 29 | id "org.checkerframework" 30 | } 31 | 32 | repositories { 33 | maven { 34 | url "${getClass().getResource("/maven/").toURI()}" 35 | } 36 | } 37 | """.stripIndent().trim() 38 | 39 | when: 40 | GradleRunner.create() 41 | .withGradleVersion(gradleVersion) 42 | .withProjectDir(testProjectDir.root) 43 | .withPluginClasspath() 44 | .build() 45 | 46 | then: 47 | noExceptionThrown() 48 | 49 | where: 50 | gradleVersion << TESTED_GRADLE_VERSIONS 51 | } 52 | 53 | @Unroll 54 | def 'without relevant plugin, compiler settings are not applied with version #gradleVersion'() { 55 | given: 56 | buildFile << 57 | """ 58 | plugins { 59 | id 'org.checkerframework' 60 | } 61 | 62 | repositories { 63 | maven { 64 | url "${getClass().getResource("/maven/").toURI()}" 65 | } 66 | } 67 | """.stripIndent().trim() 68 | 69 | when: 70 | BuildResult result = GradleRunner.create() 71 | .withGradleVersion(gradleVersion) 72 | .withProjectDir(testProjectDir.root) 73 | .withPluginClasspath() 74 | .build() 75 | 76 | then: 77 | result.output.contains('checker compiler options will not be applied') 78 | 79 | where: 80 | gradleVersion << TESTED_GRADLE_VERSIONS 81 | } 82 | 83 | @Unroll 84 | def 'with relevant plugin, compiler settings are applied with version #gradleVersion'() { 85 | given: 86 | buildFile << 87 | """ 88 | plugins { 89 | id 'java' 90 | id 'org.checkerframework' 91 | } 92 | 93 | repositories { 94 | maven { 95 | url "${getClass().getResource("/maven/").toURI()}" 96 | } 97 | } 98 | """.stripIndent().trim() 99 | 100 | when: 101 | BuildResult result = GradleRunner.create() 102 | .withGradleVersion(gradleVersion) 103 | .withProjectDir(testProjectDir.root) 104 | .withPluginClasspath() 105 | .withArguments('--info') 106 | .build() 107 | 108 | then: 109 | result.output.contains('applying checker compiler options') 110 | 111 | where: 112 | gradleVersion << TESTED_GRADLE_VERSIONS 113 | } 114 | 115 | @Unroll 116 | def 'with relevant plugin loaded subsequently, compiler settings are applied with gradle #gradleVersion'() { 117 | given: 118 | buildFile << 119 | """ 120 | plugins { 121 | id 'org.checkerframework' 122 | id 'java' 123 | } 124 | 125 | repositories { 126 | maven { 127 | url "${getClass().getResource("/maven/").toURI()}" 128 | } 129 | } 130 | """.stripIndent().trim() 131 | 132 | when: 133 | BuildResult result = GradleRunner.create() 134 | .withGradleVersion(gradleVersion) 135 | .withProjectDir(testProjectDir.root) 136 | .withPluginClasspath() 137 | .withArguments('--info') 138 | .build() 139 | 140 | then: 141 | result.output.contains('applying checker compiler options') 142 | 143 | where: 144 | gradleVersion << TESTED_GRADLE_VERSIONS 145 | } 146 | 147 | @Unroll 148 | def 'with resolved configuration dependencies, compilation settings are still applied with gradle #gradleVersion'() { 149 | given: 150 | buildFile << 151 | """ 152 | plugins { 153 | id 'java' 154 | id 'org.checkerframework' 155 | id 'application' 156 | } 157 | 158 | repositories { 159 | maven { 160 | url "${getClass().getResource("/maven/").toURI()}" 161 | } 162 | } 163 | // Trigger resolution of compile classpath 164 | println project.sourceSets.main.compileClasspath as List 165 | """.stripIndent().trim() 166 | 167 | when: 168 | BuildResult result = GradleRunner.create() 169 | .withGradleVersion(gradleVersion) 170 | .withProjectDir(testProjectDir.root) 171 | .withPluginClasspath() 172 | .withArguments('--info') 173 | .build() 174 | 175 | then: 176 | result.output.contains('applying checker compiler options') 177 | 178 | where: 179 | gradleVersion << TESTED_GRADLE_VERSIONS 180 | } 181 | 182 | @Unroll 183 | def 'skipCheckerFramework can be used to skip checking individual tasks with gradle #gradleVersion'() { 184 | given: 185 | buildFile << """ 186 | plugins { 187 | id 'java' 188 | id 'org.checkerframework' 189 | id 'application' 190 | } 191 | 192 | repositories { 193 | maven { 194 | url "${getClass().getResource("/maven/").toURI()}" 195 | } 196 | } 197 | 198 | tasks.withType(JavaCompile).all { 199 | configure { 200 | checkerFramework { 201 | skipCheckerFramework = true 202 | } 203 | } 204 | } 205 | """.stripIndent().trim() 206 | 207 | when: 208 | BuildResult result = GradleRunner.create() 209 | .withGradleVersion(gradleVersion) 210 | .withProjectDir(testProjectDir.root) 211 | .withPluginClasspath() 212 | .withArguments('--info') 213 | .build() 214 | 215 | then: 216 | result. 217 | output. 218 | contains('skipping the Checker Framework for task compileJava because skipCheckerFramework property is set') 219 | 220 | where: 221 | gradleVersion << TESTED_GRADLE_VERSIONS 222 | } 223 | 224 | @Unroll 225 | def 'plugin warns when applying org.checkerframework after java plugin with gradle #gradleVersion'() { 226 | given: 227 | buildFile << """ 228 | plugins { 229 | id 'org.checkerframework' 230 | id 'java' 231 | } 232 | 233 | repositories { 234 | maven { 235 | url "${getClass().getResource("/maven/").toURI()}" 236 | } 237 | } 238 | """.stripIndent().trim() 239 | 240 | when: 241 | BuildResult result = GradleRunner.create() 242 | .withGradleVersion(gradleVersion) 243 | .withProjectDir(testProjectDir.root) 244 | .withPluginClasspath() 245 | .withArguments('--debug') 246 | .build() 247 | 248 | then: 249 | result. 250 | output. 251 | contains("make sure you're applying the org.checkerframework plugin after the Java plugin") 252 | 253 | where: 254 | // This particular behavior only shows up on Gradle 6.4+ 255 | gradleVersion << TESTED_GRADLE_VERSIONS.stream().filter({ 256 | GradleVersion.version(it) >= GradleVersion.version("6.4") 257 | }) 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /src/test/groovy/test/BaseSpecification.groovy: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import org.junit.Rule 4 | import org.junit.rules.TemporaryFolder 5 | import spock.lang.Specification 6 | 7 | class BaseSpecification extends Specification { 8 | @Rule TemporaryFolder testProjectDir = new TemporaryFolder() 9 | def buildFile 10 | 11 | def "setup"() { 12 | buildFile = testProjectDir.newFile("build.gradle") 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/resources/maven/com/google/errorprone/javac/9+181-r4173-1/javac-9+181-r4173-1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kelloggm/checkerframework-gradle-plugin/a81be3ce6c85f62943931da30c10b27bb500c42a/src/test/resources/maven/com/google/errorprone/javac/9+181-r4173-1/javac-9+181-r4173-1.jar -------------------------------------------------------------------------------- /src/test/resources/maven/com/google/errorprone/javac/9+181-r4173-1/javac-9+181-r4173-1.pom: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 4.0.0 8 | 9 | 10 | org.sonatype.oss 11 | oss-parent 12 | 7 13 | 14 | 15 | Error Prone javac 16 | com.google.errorprone 17 | javac 18 | 9+181-r4173-1 19 | jar 20 | 21 | A repackaged copy of javac 22 | https://github.com/google/error-prone-javac 23 | 24 | 25 | 26 | GNU General Public License, version 2, with the Classpath Exception 27 | http://openjdk.java.net/legal/gplv2+ce.html 28 | 29 | 30 | 31 | 32 | https://github.com/google/error-prone-javac 33 | scm:git:git://github.com/google/error-prone-javac.git 34 | scm:git:ssh://git@github.com/google/error-prone-javac.git 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/test/resources/maven/org/checkerframework/update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This script updates the version of the Checker Framework used in the tests to the version 4 | # listed in the first argument. 5 | 6 | set -e 7 | 8 | NEW_CF_VERSION=$1 9 | 10 | rm -rf checker/* 11 | rm -rf checker-qual/* 12 | rm -rf checker-util/* 13 | 14 | mkdir -p "checker/${NEW_CF_VERSION}" 15 | mkdir -p "checker-qual/${NEW_CF_VERSION}" 16 | mkdir -p "checker-util/${NEW_CF_VERSION}" 17 | 18 | cd "checker/${NEW_CF_VERSION}" 19 | wget -O "checker-${NEW_CF_VERSION}.jar" "https://repo1.maven.org/maven2/org/checkerframework/checker/${NEW_CF_VERSION}/checker-${NEW_CF_VERSION}.jar" 20 | wget -O "checker-${NEW_CF_VERSION}.pom" "https://repo1.maven.org/maven2/org/checkerframework/checker/${NEW_CF_VERSION}/checker-${NEW_CF_VERSION}.pom" 21 | cd ../../ 22 | 23 | cd "checker-qual/${NEW_CF_VERSION}" 24 | wget -O "checker-qual-${NEW_CF_VERSION}.jar" "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/${NEW_CF_VERSION}/checker-qual-${NEW_CF_VERSION}.jar" 25 | wget -O "checker-qual-${NEW_CF_VERSION}.pom" "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/${NEW_CF_VERSION}/checker-qual-${NEW_CF_VERSION}.pom" 26 | cd ../../ 27 | 28 | cd "checker-util/${NEW_CF_VERSION}" 29 | wget -O "checker-util-${NEW_CF_VERSION}.jar" "https://repo1.maven.org/maven2/org/checkerframework/checker-util/${NEW_CF_VERSION}/checker-util-${NEW_CF_VERSION}.jar" 30 | wget -O "checker-util-${NEW_CF_VERSION}.pom" "https://repo1.maven.org/maven2/org/checkerframework/checker-util/${NEW_CF_VERSION}/checker-util-${NEW_CF_VERSION}.pom" 31 | cd ../../ 32 | 33 | -------------------------------------------------------------------------------- /src/test/resources/maven/org/sonatype/oss/oss-parent/7/oss-parent-7.pom: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 4.0.0 16 | 17 | org.sonatype.oss 18 | oss-parent 19 | 7 20 | pom 21 | 22 | Sonatype OSS Parent 23 | http://nexus.sonatype.org/oss-repository-hosting.html 24 | Sonatype helps open source projects to set up Maven repositories on https://oss.sonatype.org/ 25 | 26 | 27 | scm:svn:http://svn.sonatype.org/spice/tags/oss-parent-7 28 | scm:svn:https://svn.sonatype.org/spice/tags/oss-parent-7 29 | http://svn.sonatype.org/spice/tags/oss-parent-7 30 | 31 | 32 | 33 | 34 | sonatype-nexus-snapshots 35 | Sonatype Nexus Snapshots 36 | https://oss.sonatype.org/content/repositories/snapshots 37 | 38 | false 39 | 40 | 41 | true 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | sonatype-nexus-snapshots 50 | Sonatype Nexus Snapshots 51 | ${sonatypeOssDistMgmtSnapshotsUrl} 52 | 53 | 54 | sonatype-nexus-staging 55 | Nexus Release Repository 56 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-enforcer-plugin 65 | 1.0 66 | 67 | 68 | enforce-maven 69 | 70 | enforce 71 | 72 | 73 | 74 | 75 | (,2.1.0),(2.1.0,2.2.0),(2.2.0,) 76 | Maven 2.1.0 and 2.2.0 produce incorrect GPG signatures and checksums respectively. 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.apache.maven.plugins 88 | maven-release-plugin 89 | 2.1 90 | 91 | forked-path 92 | false 93 | -Psonatype-oss-release 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | UTF-8 102 | https://oss.sonatype.org/content/repositories/snapshots/ 103 | 104 | 105 | 106 | 107 | sonatype-oss-release 108 | 109 | 110 | 111 | org.apache.maven.plugins 112 | maven-source-plugin 113 | 2.1.2 114 | 115 | 116 | attach-sources 117 | 118 | jar-no-fork 119 | 120 | 121 | 122 | 123 | 124 | org.apache.maven.plugins 125 | maven-javadoc-plugin 126 | 2.7 127 | 128 | 129 | attach-javadocs 130 | 131 | jar 132 | 133 | 134 | 135 | 136 | 137 | org.apache.maven.plugins 138 | maven-gpg-plugin 139 | 1.1 140 | 141 | 142 | sign-artifacts 143 | verify 144 | 145 | sign 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | --------------------------------------------------------------------------------