├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── google │ └── common │ └── annotations │ └── checkers │ ├── AnnotatedApiUsageChecker.java │ └── BetaChecker.java └── test └── java └── com └── google └── common └── annotations └── checkers ├── BetaCheckerTest.java └── TestCompiler.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | groups: 8 | dependencies: 9 | applies-to: version-updates 10 | patterns: 11 | - "*" 12 | - package-ecosystem: "github-actions" 13 | directory: "/" 14 | schedule: 15 | interval: "monthly" 16 | groups: 17 | github-actions: 18 | applies-to: version-updates 19 | patterns: 20 | - "*" 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | test: 13 | name: "JDK ${{ matrix.java }}" 14 | strategy: 15 | matrix: 16 | java: [ 17, 24 ] 17 | runs-on: ubuntu-latest 18 | steps: 19 | # Cancel any previous runs for the same branch that are still running. 20 | - name: 'Cancel previous runs' 21 | uses: styfle/cancel-workflow-action@85880fa0301c86cca9da44039ee3bb12d3bedbfa 22 | with: 23 | access_token: ${{ github.token }} 24 | - name: 'Check out repository' 25 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 26 | - name: 'Set up JDK ${{ matrix.java }}' 27 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 28 | with: 29 | java-version: ${{ matrix.java }} 30 | distribution: 'temurin' 31 | cache: 'maven' 32 | - name: 'Install' 33 | shell: bash 34 | run: mvn -B install -U -DskipTests=true 35 | - name: 'Test' 36 | shell: bash 37 | run: mvn -B verify -U -Dmaven.javadoc.skip=true 38 | 39 | publish_snapshot: 40 | name: 'Publish snapshot' 41 | needs: test 42 | if: github.event_name == 'push' && github.repository == 'google/guava-beta-checker' 43 | runs-on: ubuntu-latest 44 | steps: 45 | - name: 'Check out repository' 46 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 47 | - name: 'Set up JDK 17' 48 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 49 | with: 50 | java-version: 17 51 | distribution: 'temurin' 52 | cache: 'maven' 53 | server-id: sonatype-nexus-snapshots 54 | server-username: CI_DEPLOY_USERNAME 55 | server-password: CI_DEPLOY_PASSWORD 56 | - name: 'Publish' 57 | env: 58 | CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} 59 | CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} 60 | run: mvn -B clean source:jar javadoc:jar deploy -DskipTests=true 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Maven 2 | target/ 3 | *.ser 4 | *.ec 5 | 6 | # IntelliJ Idea 7 | .idea/ 8 | out/ 9 | *.ipr 10 | *.iws 11 | *.iml 12 | 13 | # Eclipse 14 | .classpath 15 | .project 16 | .settings/ 17 | .metadata/ 18 | 19 | # OS X 20 | .DS_Store 21 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/google/guava-beta-checker/workflows/CI/badge.svg?branch=master)](https://github.com/google/guava-beta-checker/actions) 2 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.google.guava/guava-beta-checker/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.google.guava/guava-beta-checker) 3 | 4 | # Guava Beta Checker 5 | 6 | An [Error Prone] plugin that checks for usages of [Guava] APIs that are 7 | annotated with the [`@Beta`] annotation. Such APIs should _never_ be used in 8 | library code that other projects may depend on; using the Beta Checker can help 9 | library projects ensure that they don't use them. 10 | 11 | Example error: 12 | 13 | ``` 14 | src/main/java/foo/MyClass.java:14: error: [BetaApi] @Beta APIs should not be used in library code as they are subject to change. 15 | Files.copy(a, b); 16 | ^ 17 | (see https://github.com/google/guava/wiki/PhilosophyExplained#beta-apis) 18 | ``` 19 | 20 | ## Usage 21 | 22 | Using the Beta Checker requires configuring your project to build with the Error 23 | Prone Java compiler. By default, this enables a lot of useful checks for a 24 | variety of common bugs. However, if you just want to use the Beta Checker, the 25 | other checks can be disabled. 26 | 27 | The usage examples below will show how to use the Beta Checker only, with notes 28 | for what to remove if you want all checks. 29 | 30 | ### Maven 31 | 32 | In `pom.xml`: 33 | 34 | ```xml 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-compiler-plugin 40 | 3.8.0 41 | 42 | 1.8 43 | 1.8 44 | 45 | 46 | com.google.errorprone 47 | error_prone_core 48 | 2.3.3 49 | 50 | 51 | com.google.guava 52 | guava-beta-checker 53 | ${betachecker.version} 54 | 55 | 56 | 57 | 58 | 59 | default-compile 60 | compile 61 | 62 | compile 63 | 64 | 65 | 66 | -XDcompilePolicy=simple 67 | 68 | -Xplugin:ErrorProne -XepDisableAllChecks -Xep:BetaApi:ERROR 69 | 70 | 71 | 72 | 73 | default-testCompile 74 | test-compile 75 | 76 | testCompile 77 | 78 | 79 | 81 | 82 | -XDcompilePolicy=simple 83 | 84 | -Xplugin:ErrorProne -XepDisableAllChecks -Xep:BetaApi:OFF 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | ``` 93 | 94 | ### Gradle 95 | 96 | Your `build.gradle` file(s) should have the following things. Add them to what's 97 | already in your files as appropriate. 98 | 99 |
100 | Using the Groovy DSL 101 | 102 | ```groovy 103 | plugins { 104 | id("java") 105 | id("net.ltgt.errorprone") version "0.8" 106 | } 107 | 108 | repositories { 109 | mavenCentral() 110 | } 111 | 112 | dependencies { 113 | errorprone "com.google.errorprone:error_prone_core:2.3.3" 114 | errorproneJavac "com.google.errorprone:javac:9+181-r4173-1" 115 | 116 | // Add dependency on the beta checker 117 | // NOTE: added here to `annotationProcessor` so it's only enabled for the main classes 118 | annotationProcessor "com.google.guava:guava-beta-checker:$betaCheckerVersion" 119 | } 120 | 121 | // Remove this block to keep all checks enabled (default behavior) 122 | tasks.named("compileJava").configure { 123 | options.errorprone.disableAllChecks = true 124 | options.errorprone.error("BetaApi") 125 | } 126 | ``` 127 | 128 |
129 |
130 | Using the Kotlin DSL 131 | 132 | ```kotlin 133 | import net.ltgt.gradle.errorprone.errorprone 134 | 135 | plugins { 136 | id("java") 137 | id("net.ltgt.errorprone") version "0.8" 138 | } 139 | 140 | repositories { 141 | mavenCentral() 142 | } 143 | 144 | dependencies { 145 | errorprone("com.google.errorprone:error_prone_core:2.3.3") 146 | errorproneJavac("com.google.errorprone:javac:9+181-r4173-1") 147 | 148 | // Add dependency on the beta checker 149 | // NOTE: added here to `annotationProcessor` so it's only enabled for the main classes 150 | annotationProcessor("com.google.guava:guava-beta-checker:$betaCheckerVersion") 151 | } 152 | 153 | // Remove this block to keep all checks enabled (default behavior) 154 | tasks.compileJava { 155 | options.errorprone.disableAllChecks.set(true) 156 | options.errorprone.error("BetaApi") 157 | } 158 | ``` 159 | 160 |
161 | 162 | ### Bazel 163 | 164 | Bazel Java targets use the Error Prone compiler by default. To use the Beta 165 | Checker with Bazel, you'll need to add a `maven_jar` dependency on the Beta 166 | Checker, then create a `java_plugin` target for it, and finally add that target 167 | to the `plugins` attribute of any Java targets it should run on. 168 | 169 | #### Example 170 | 171 | You'll need a `java_library` for the Beta Checker. You can get this using 172 | [generate-workspace], by running a command like: 173 | 174 | ```shell 175 | bazel run //generate_workspace -- \ 176 | -a com.google.guava:guava:$GUAVA_VERSION \ 177 | -a com.google.guava:guava-beta-checker:$BETA_CHECKER_VERSION \ 178 | -r https://repo.maven.apache.org/maven2/ 179 | ``` 180 | 181 | After putting the generated `generate_workspace.bzl` file in your project as 182 | described in the documentation, put the following in `third_party/BUILD`: 183 | 184 | ```bazel 185 | load("//:generate_workspace.bzl", "generated_java_libraries") 186 | generated_java_libraries() 187 | 188 | java_plugin( 189 | name = "guava_beta_checker_plugin", 190 | deps = [":com_google_guava_guava_beta_checker"], 191 | visibility = ["//visibility:public"], 192 | ) 193 | ``` 194 | 195 | Finally, add the plugin to the `plugins` attribute of any Java target you want 196 | to be checked for usages of `@Beta` APIs: 197 | 198 | ```bazel 199 | java_library( 200 | name = "foo", 201 | srcs = glob(["*.java"]), 202 | deps = [ 203 | "//third_party:com_google_guava_guava", 204 | ], 205 | plugins = [ 206 | "//third_party:guava_beta_checker_plugin", 207 | ], 208 | ) 209 | ``` 210 | 211 | [Error Prone]: https://github.com/google/error-prone 212 | [Guava]: https://github.com/google/guava 213 | [`@Beta`]: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/annotations/Beta.html 214 | [generate-workspace]: https://docs.bazel.build/versions/master/generate-workspace.html 215 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 20 | 4.0.0 21 | 22 | org.sonatype.oss 23 | oss-parent 24 | 9 25 | 26 | 27 | com.google.guava 28 | guava-beta-checker 29 | HEAD-SNAPSHOT 30 | 31 | Guava Beta Checker 32 | 33 | 34 | GitHub Issues 35 | https://github.com/google/guava-beta-checker/issues 36 | 37 | 38 | 39 | 40 | The Apache Software License, Version 2.0 41 | http://www.apache.org/licenses/LICENSE-2.0.txt 42 | repo 43 | 44 | 45 | 46 | 47 | scm:git:https://github.com/google/guava-beta-checker.git 48 | scm:git:git@github.com:google/guava-beta-checker.git 49 | https://github.com/google/guava-beta-checker 50 | 51 | 52 | 53 | UTF-8 54 | 2.38.0 55 | 56 | 57 | 58 | 59 | com.google.auto.service 60 | auto-service 61 | 1.1.1 62 | true 63 | 64 | 65 | com.google.guava 66 | guava 67 | 33.4.8-jre 68 | true 69 | 70 | 71 | com.google.errorprone 72 | error_prone_core 73 | ${errorprone.version} 74 | provided 75 | 76 | 77 | com.google.testing.compile 78 | compile-testing 79 | 0.21.0 80 | test 81 | 82 | 83 | junit 84 | junit 85 | 4.13.2 86 | test 87 | 88 | 89 | 90 | 91 | 92 | 93 | . 94 | 95 | LICENSE 96 | 97 | META-INF 98 | 99 | 100 | 101 | 102 | maven-compiler-plugin 103 | 3.14.0 104 | 105 | 17 106 | 17 107 | 108 | 109 | --add-exports=java.base/jdk.internal.javac=ALL-UNNAMED 110 | --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED 111 | --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED 112 | --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED 113 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 114 | --add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED 115 | --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED 116 | --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED 117 | --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED 118 | --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED 119 | --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED 120 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 121 | 122 | 123 | 124 | 125 | maven-javadoc-plugin 126 | 3.11.2 127 | 128 | 17 129 | true 130 | 131 | --add-exports=java.base/jdk.internal.javac=ALL-UNNAMED 132 | --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED 133 | --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED 134 | --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED 135 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 136 | --add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED 137 | --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED 138 | --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED 139 | --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED 140 | --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED 141 | --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED 142 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 143 | 144 | 145 | 146 | 147 | maven-surefire-plugin 148 | 3.5.3 149 | 150 | 151 | --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED 152 | --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED 153 | --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED 154 | --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED 155 | --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED 156 | --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED 157 | --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED 158 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 159 | --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED 160 | --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED 161 | --add-opens=java.base/java.math=ALL-UNNAMED 162 | --add-opens=java.base/java.nio=ALL-UNNAMED 163 | 164 | 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /src/main/java/com/google/common/annotations/checkers/AnnotatedApiUsageChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.annotations.checkers; 18 | 19 | import static com.google.errorprone.matchers.Description.NO_MATCH; 20 | import static com.google.errorprone.util.ASTHelpers.enclosingPackage; 21 | import static javax.lang.model.element.ElementKind.ANNOTATION_TYPE; 22 | import static javax.lang.model.element.ElementKind.CLASS; 23 | import static javax.lang.model.element.ElementKind.CONSTRUCTOR; 24 | import static javax.lang.model.element.ElementKind.ENUM; 25 | import static javax.lang.model.element.ElementKind.ENUM_CONSTANT; 26 | import static javax.lang.model.element.ElementKind.FIELD; 27 | import static javax.lang.model.element.ElementKind.INTERFACE; 28 | import static javax.lang.model.element.ElementKind.METHOD; 29 | 30 | import com.google.common.collect.ImmutableSet; 31 | import com.google.errorprone.VisitorState; 32 | import com.google.errorprone.bugpatterns.BugChecker; 33 | import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; 34 | import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; 35 | import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; 36 | import com.google.errorprone.matchers.Description; 37 | import com.google.errorprone.util.ASTHelpers; 38 | import com.sun.source.tree.IdentifierTree; 39 | import com.sun.source.tree.ImportTree; 40 | import com.sun.source.tree.MemberReferenceTree; 41 | import com.sun.source.tree.MemberSelectTree; 42 | import com.sun.source.tree.Tree; 43 | import com.sun.tools.javac.code.Symbol; 44 | import com.sun.tools.javac.util.Name; 45 | import java.util.Collections; 46 | import java.util.EnumSet; 47 | import java.util.Set; 48 | import javax.lang.model.element.AnnotationMirror; 49 | import javax.lang.model.element.ElementKind; 50 | 51 | /** 52 | * Abstract check for usages of APIs that are annotated with a specific annotation. 53 | * 54 | * @author Colin Decker 55 | */ 56 | public abstract class AnnotatedApiUsageChecker extends BugChecker 57 | implements MemberSelectTreeMatcher, IdentifierTreeMatcher, MemberReferenceTreeMatcher { 58 | 59 | private final String basePackage; 60 | private final String basePackagePlusDot; // Just to avoid creating this string repeatedly 61 | 62 | private final ImmutableSet annotationTypes; 63 | 64 | protected AnnotatedApiUsageChecker(String basePackage, String... annotationTypes) { 65 | this.basePackage = basePackage; 66 | this.basePackagePlusDot = basePackage + "."; 67 | this.annotationTypes = ImmutableSet.copyOf(annotationTypes); 68 | } 69 | 70 | @Override 71 | public final Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { 72 | if (ASTHelpers.findEnclosingNode(state.getPath(), ImportTree.class) != null) { 73 | return Description.NO_MATCH; 74 | } 75 | return matchTree(tree); 76 | } 77 | 78 | @Override 79 | public final Description matchIdentifier(IdentifierTree tree, VisitorState state) { 80 | // We don't match any call to super() because currently we have no good way of identifying 81 | // super() calls that are generated and not actually present in the source code. Originally, 82 | // we were using state.getEndPosition to check if the end position in source for the tree was 83 | // <= 0, but end positions are not guaranteed to be enabled in error-prone, in which case all 84 | // super() calls would be matched anyway. This isn't likely to matter much in practice unless 85 | // a class is subclassing a non-annotated class that has an annotated no-arg constructor. 86 | // TODO(cgdecker): Revisit this if/when we have a way of detecting generated super() calls. 87 | return isSuperCall(tree) ? NO_MATCH : matchTree(tree); 88 | } 89 | 90 | @Override 91 | public final Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { 92 | return matchTree(tree); 93 | } 94 | 95 | private Description matchTree(Tree tree) { 96 | Symbol symbol = ASTHelpers.getSymbol(tree); 97 | if (symbol != null && isInMatchingPackage(symbol) && isAnnotatedApi(symbol)) { 98 | return describeMatch(tree); 99 | } 100 | return NO_MATCH; 101 | } 102 | 103 | /** 104 | * Returns true if the given tree is a call to {@code super} in a constructor. 105 | */ 106 | private static boolean isSuperCall(IdentifierTree tree) { 107 | return tree.getName().contentEquals("super"); 108 | } 109 | 110 | /** 111 | * Returns true if the given symbol belongs to the base package for this checker or a package 112 | * under it. 113 | */ 114 | private boolean isInMatchingPackage(Symbol symbol) { 115 | String packageName = enclosingPackage(symbol).fullname.toString(); 116 | return !isIgnoredPackage(packageName) 117 | && (packageName.equals(basePackage) || packageName.startsWith(basePackagePlusDot)); 118 | } 119 | 120 | /** 121 | * May be overridden to ignore APIs under specific packages. Returns false by default. 122 | */ 123 | protected boolean isIgnoredPackage(String packageName) { 124 | return false; 125 | } 126 | 127 | /** 128 | * May be overridden to ignore specific types and their members. Returns false by default. 129 | */ 130 | protected boolean isIgnoredType(String fullyQualifiedTypeName) { 131 | return false; 132 | } 133 | 134 | /** 135 | * Returns true if the given symbol is annotated with the annotation or if it's a member of a type 136 | * annotated with the annotation. 137 | */ 138 | private boolean isAnnotatedApi(Symbol symbol) { 139 | Name name = symbol.getQualifiedName(); 140 | if (name != null && isIgnoredType(name.toString())) { 141 | return false; 142 | } 143 | 144 | for (AnnotationMirror annotation : symbol.getAnnotationMirrors()) { 145 | if (annotationTypes.contains(annotation.getAnnotationType().toString())) { 146 | return true; 147 | } 148 | } 149 | 150 | return isMemberOfAnnotatedApi(symbol); 151 | } 152 | 153 | /** 154 | * Kinds of elements that should be considered annotated if the element's owner (i.e. the class 155 | * it's declared in) is annotated. This is used to prevent things like type parameters that happen 156 | * to be declared in an annotated class from being flagged. 157 | */ 158 | private static final Set INHERITS_ANNOTATION_FROM_OWNER = 159 | Collections.unmodifiableSet( 160 | EnumSet.of( 161 | FIELD, METHOD, CONSTRUCTOR, ENUM_CONSTANT, CLASS, INTERFACE, ENUM, ANNOTATION_TYPE)); 162 | 163 | /** 164 | * Returns true if the given element is a member of an annotated class or interface. 165 | */ 166 | private boolean isMemberOfAnnotatedApi(Symbol symbol) { 167 | return symbol != null 168 | && INHERITS_ANNOTATION_FROM_OWNER.contains(symbol.getKind()) 169 | && isAnnotatedApi(symbol.owner); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/main/java/com/google/common/annotations/checkers/BetaChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.annotations.checkers; 18 | 19 | import static com.google.errorprone.BugPattern.LinkType.CUSTOM; 20 | import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 21 | 22 | import com.google.auto.service.AutoService; 23 | import com.google.errorprone.BugPattern; 24 | import com.google.errorprone.bugpatterns.BugChecker; 25 | import java.util.Arrays; 26 | import java.util.Collections; 27 | import java.util.HashSet; 28 | import java.util.Set; 29 | 30 | /** 31 | * Checks for usages of Guava {@code @Beta} APIs, which should never be used in library code. 32 | * 33 | * @author Colin Decker 34 | */ 35 | @AutoService(BugChecker.class) 36 | @BugPattern( 37 | name = "BetaApi", 38 | summary = "@Beta APIs should not be used in library code as they are subject to change", 39 | explanation = "@Beta APIs should not be used in library code as they are subject to change.", 40 | linkType = CUSTOM, 41 | link = "https://github.com/google/guava/wiki/PhilosophyExplained#beta-apis", 42 | severity = ERROR) 43 | public final class BetaChecker extends AnnotatedApiUsageChecker { 44 | 45 | /** Specific @Beta types to ignore. */ 46 | private static final Set IGNORED_TYPES = 47 | Collections.unmodifiableSet( 48 | new HashSet( 49 | Arrays.asList( 50 | "com.google.common.cache.Cache", "com.google.common.cache.LoadingCache"))); 51 | 52 | public BetaChecker() { 53 | super("com.google.common", "com.google.common.annotations.Beta"); 54 | } 55 | 56 | @Override 57 | protected boolean isIgnoredType(String fullyQualifiedTypeName) { 58 | // Cache/LoadingCache are currently in a weird beta state where they're frozen for users but 59 | // not implementers. Since the vast majority of users are likely not implementing Cache and 60 | // LoadingCache themselves, just suppress this check for those types. 61 | // TODO(cgdecker): Remove this once they come out of beta. 62 | return IGNORED_TYPES.contains(fullyQualifiedTypeName); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/google/common/annotations/checkers/BetaCheckerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.annotations.checkers; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import com.google.testing.compile.JavaFileObjects; 22 | import java.util.List; 23 | import javax.tools.Diagnostic; 24 | import javax.tools.JavaFileObject; 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | import org.junit.runners.JUnit4; 28 | 29 | /** 30 | * Tests for {@link AnnotatedApiUsageChecker} via the {@link BetaChecker} concrete class. 31 | * 32 | * @author Colin Decker 33 | */ 34 | 35 | @RunWith(JUnit4.class) 36 | public class BetaCheckerTest { 37 | 38 | private final TestCompiler compiler = new TestCompiler(BetaChecker.class); 39 | 40 | /** 41 | * Equivalent to the real @Beta annotation from Guava. 42 | */ 43 | public static final JavaFileObject BETA = JavaFileObjects.forSourceLines( 44 | "com.google.common.annotations.Beta", 45 | "package com.google.common.annotations;", 46 | "", 47 | "import java.lang.annotation.ElementType;", 48 | "import java.lang.annotation.Retention;", 49 | "import java.lang.annotation.RetentionPolicy;", 50 | "import java.lang.annotation.Target;", 51 | "", 52 | "@Retention(RetentionPolicy.CLASS)", 53 | "@Target({", 54 | " ElementType.ANNOTATION_TYPE,", 55 | " ElementType.CONSTRUCTOR,", 56 | " ElementType.FIELD,", 57 | " ElementType.METHOD,", 58 | " ElementType.TYPE})", 59 | "public @interface Beta {}"); 60 | 61 | /** 62 | * Class in a com.google.common package that is annotated with @Beta. 63 | */ 64 | public static final JavaFileObject ANNOTATED_CLASS = JavaFileObjects.forSourceLines( 65 | "com.google.common.foo.AnnotatedClass", 66 | "package com.google.common.foo;", 67 | "", 68 | "import com.google.common.annotations.Beta;", 69 | "", 70 | "@Beta", 71 | "public class AnnotatedClass {", 72 | "", 73 | " public static final String STATIC_FIELD = \"foo\";", 74 | "", 75 | " public static String staticMethod() {", 76 | " return \"foo\";", 77 | " }", 78 | "", 79 | " public final String instanceField = \"foo\";", 80 | "", 81 | " public String instanceMethod() {", 82 | " return \"foo\";", 83 | " }", 84 | "}"); 85 | 86 | @Test 87 | public void testCleanClass() { 88 | List> diagnostics = compiler.compile(BETA, 89 | JavaFileObjects.forSourceLines( 90 | "example.Test", 91 | "package example;", 92 | "", 93 | "import java.util.Arrays;", 94 | "", 95 | "public class Test {", 96 | " public static void main(String[] args) {", 97 | " System.out.println(Arrays.asList(args));", 98 | " }", 99 | "}") 100 | ); 101 | 102 | assertThat(diagnostics).isEmpty(); 103 | } 104 | 105 | @Test 106 | public void testAnnotatedClass_asParameter() { 107 | List> diagnostics = compiler.compile( 108 | BETA, ANNOTATED_CLASS, 109 | JavaFileObjects.forSourceLines( 110 | "example.Test", 111 | "package example;", 112 | "", 113 | "import com.google.common.foo.AnnotatedClass;", 114 | "", 115 | "public class Test {", 116 | " public static void foo(AnnotatedClass annotated) {", // error 117 | " }", 118 | "}") 119 | ); 120 | 121 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 6); 122 | } 123 | 124 | @Test 125 | public void testAnnotatedClass_asTypeArgument() { 126 | List> diagnostics = compiler.compile( 127 | BETA, ANNOTATED_CLASS, 128 | JavaFileObjects.forSourceLines( 129 | "example.Test", 130 | "package example;", 131 | "", 132 | "import com.google.common.foo.AnnotatedClass;", 133 | "", 134 | "import java.util.List;", 135 | "", 136 | "public class Test {", 137 | " public static void foo(List stuff) {", // error 138 | " }", 139 | "}") 140 | ); 141 | 142 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 8); 143 | } 144 | 145 | @Test 146 | public void testAnnotatedClass_extending() { 147 | List> diagnostics = compiler.compile( 148 | BETA, ANNOTATED_CLASS, 149 | JavaFileObjects.forSourceLines( 150 | "example.Test", 151 | "package example;", 152 | "", 153 | "import com.google.common.foo.AnnotatedClass;", 154 | "", 155 | "public class Test extends AnnotatedClass {", // error 156 | "}") 157 | ); 158 | 159 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5); 160 | } 161 | 162 | @Test 163 | public void testAnnotatedClass_extending_generatedSuperCallIsNotMatched() { 164 | List> diagnostics = compiler.compile( 165 | BETA, ANNOTATED_CLASS, 166 | JavaFileObjects.forSourceLines( 167 | "example.Test", 168 | "package example;", 169 | "", 170 | "import com.google.common.foo.AnnotatedClass;", 171 | "", 172 | "public class Test extends AnnotatedClass {", // error 173 | "", 174 | " private final String foo;", 175 | "", 176 | " public Test(String foo) {", // no error for implicit super() here 177 | " this.foo = foo;", 178 | " }", 179 | "}") 180 | ); 181 | 182 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5); 183 | } 184 | 185 | @Test 186 | public void testAnnotatedClass_asBoundInGenericType() { 187 | List> diagnostics = compiler.compile( 188 | BETA, ANNOTATED_CLASS, 189 | JavaFileObjects.forSourceLines("example.Test", 190 | "package example;", 191 | "", 192 | "import com.google.common.foo.AnnotatedClass;", 193 | "", 194 | "public class Test {", // error 195 | "}") 196 | ); 197 | 198 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5); 199 | } 200 | 201 | @Test 202 | public void testAnnotatedClass_asTypeArgInImplementedGenericInterface() { 203 | List> diagnostics = compiler.compile( 204 | BETA, ANNOTATED_CLASS, 205 | JavaFileObjects.forSourceLines("example.Test", 206 | "package example;", 207 | "", 208 | "import com.google.common.foo.AnnotatedClass;", 209 | "", 210 | "import java.util.List;", 211 | "", 212 | "public abstract class Test implements List {", // error 213 | "}") 214 | ); 215 | 216 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 217 | } 218 | 219 | @Test 220 | public void testAnnotatedClass_asBoundInGenericMethod() { 221 | List> diagnostics = compiler.compile( 222 | BETA, ANNOTATED_CLASS, 223 | JavaFileObjects.forSourceLines("example.Test", 224 | "package example;", 225 | "", 226 | "import com.google.common.foo.AnnotatedClass;", 227 | "", 228 | "public class Test {", 229 | " public static T foo(T t) {", // error 230 | " return null;", 231 | " }", 232 | "}") 233 | ); 234 | 235 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 6); 236 | } 237 | 238 | @Test 239 | public void testAnnotatedClass_asBoundInGenericParameter() { 240 | List> diagnostics = compiler.compile( 241 | BETA, ANNOTATED_CLASS, 242 | JavaFileObjects.forSourceLines("example.Test", 243 | "package example;", 244 | "", 245 | "import com.google.common.foo.AnnotatedClass;", 246 | "", 247 | "import java.util.List;", 248 | "", 249 | "public class Test {", 250 | " public static void foo(List list) {", // error 251 | " }", 252 | "}") 253 | ); 254 | 255 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 8); 256 | } 257 | 258 | @Test 259 | public void testAnnotatedClass_instantiation() { 260 | List> diagnostics = compiler.compile( 261 | BETA, ANNOTATED_CLASS, 262 | JavaFileObjects.forSourceLines("example.Test", 263 | "package example;", 264 | "", 265 | "import com.google.common.foo.AnnotatedClass;", 266 | "", 267 | "public class Test {", 268 | " public static void main(String[] args) {", 269 | " System.out.println(new AnnotatedClass());", // error 270 | " }", 271 | "}") 272 | ); 273 | 274 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 275 | } 276 | 277 | @Test 278 | public void testAnnotatedClass_staticMethodCall() { 279 | List> diagnostics = compiler.compile( 280 | BETA, ANNOTATED_CLASS, 281 | JavaFileObjects.forSourceLines("example.Test", 282 | "package example;", 283 | "", 284 | "import com.google.common.foo.AnnotatedClass;", 285 | "", 286 | "public class Test {", 287 | " public static void main(String[] args) {", 288 | " AnnotatedClass.staticMethod();", // 2 errors 289 | " }", 290 | "}") 291 | ); 292 | 293 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7, 7); 294 | } 295 | 296 | @Test 297 | public void testAnnotatedClass_instanceMethodCall() { 298 | List> diagnostics = compiler.compile( 299 | BETA, ANNOTATED_CLASS, 300 | JavaFileObjects.forSourceLines("example.Test", 301 | "package example;", 302 | "", 303 | "import com.google.common.foo.AnnotatedClass;", 304 | "", 305 | "public class Test {", 306 | " public static void foo(AnnotatedClass a) {", // error 307 | " a.instanceMethod();", // error 308 | " }", 309 | "}") 310 | ); 311 | 312 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 6, 7); 313 | } 314 | 315 | @Test 316 | public void testAnnotatedClass_staticMethodCall_fromStaticImport() { 317 | List> diagnostics = compiler.compile( 318 | BETA, ANNOTATED_CLASS, 319 | JavaFileObjects.forSourceLines("example.Test", 320 | "package example;", 321 | "", 322 | "import static com.google.common.foo.AnnotatedClass.staticMethod;", 323 | "", 324 | "public class Test {", 325 | " public static void main(String[] args) {", 326 | " staticMethod();", // error 327 | " }", 328 | "}") 329 | ); 330 | 331 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 332 | } 333 | 334 | @Test 335 | public void testAnnotatedClass_staticMethodCall_fromInstanceVariable() { 336 | List> diagnostics = compiler.compile( 337 | BETA, ANNOTATED_CLASS, 338 | JavaFileObjects.forSourceLines("example.Test", 339 | "package example;", 340 | "", 341 | "import com.google.common.foo.AnnotatedClass;", 342 | "", 343 | "public class Test {", 344 | " public static void foo(AnnotatedClass a) {", // error 345 | " a.staticMethod();", // error 346 | " }", 347 | "}") 348 | ); 349 | 350 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 6, 7); 351 | } 352 | 353 | @Test 354 | public void testAnnotatedClass_fullyQualifiedReferences() { 355 | List> diagnostics = compiler.compile( 356 | BETA, ANNOTATED_CLASS, 357 | JavaFileObjects.forSourceLines("example.Test", 358 | "package example;", 359 | "", 360 | "public class Test {", 361 | " public static void foo(com.google.common.foo.AnnotatedClass parameter) {", // error 362 | " com.google.common.foo.AnnotatedClass c = ", // error 363 | " new com.google.common.foo.AnnotatedClass();", // error 364 | " String s = com.google.common.foo.AnnotatedClass.staticMethod();", // 2 errors 365 | " }", 366 | "}") 367 | ); 368 | 369 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 4, 5, 6, 7, 7); 370 | } 371 | 372 | @Test 373 | public void testAnnotatedClass_importsAreNotMatched() { 374 | List> diagnostics = compiler.compile( 375 | BETA, ANNOTATED_CLASS, 376 | JavaFileObjects.forSourceLines("example.Test", 377 | "package example;", 378 | "", 379 | "import static com.google.common.foo.AnnotatedClass.staticMethod;", 380 | "", 381 | "import com.google.common.foo.AnnotatedClass;", 382 | "", 383 | "public class Test {", 384 | " public static void foo() {", 385 | " AnnotatedClass c = new AnnotatedClass();", // 2 errors 386 | " String s = staticMethod();", // error 387 | " }", 388 | "}") 389 | ); 390 | 391 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 9, 9, 10); 392 | } 393 | 394 | @Test 395 | public void testAnnotatedClass_methodReference() { 396 | List> diagnostics = compiler.compile( 397 | BETA, ANNOTATED_CLASS, 398 | JavaFileObjects.forSourceLines("example.Test", 399 | "package example;", 400 | "", 401 | "import static java.util.stream.Collectors.joining;", 402 | "", 403 | "import com.google.common.foo.AnnotatedClass;", 404 | "import java.util.List;", 405 | "", 406 | "public class Test {", 407 | " public static void foo(List list) {", // error 408 | " String s = list.stream()", 409 | " .map(AnnotatedClass::instanceMethod)", // error 410 | " .collect(joining(", "));", 411 | " }", 412 | "}") 413 | ); 414 | 415 | compiler.assertErrorsOnUniqueLines("example/Test.java", diagnostics, 9, 11); 416 | } 417 | 418 | @Test 419 | public void testAnnotatedClass_constructorReference() { 420 | List> diagnostics = compiler.compile( 421 | BETA, ANNOTATED_CLASS, 422 | JavaFileObjects.forSourceLines("example.Test", 423 | "package example;", 424 | "", 425 | "import com.google.common.foo.AnnotatedClass;", 426 | "import java.util.Optional;", 427 | "", 428 | "public class Test {", 429 | " public static void foo(Optional optional) {", // error 430 | " String s = optional", 431 | " .orElseGet(AnnotatedClass::new)", // error 432 | " .toString();", 433 | " }", 434 | "}") 435 | ); 436 | 437 | compiler.assertErrorsOnUniqueLines("example/Test.java", diagnostics, 7, 9); 438 | } 439 | 440 | /** 441 | * A class in a com.google.common package with some members that are annotated @Beta and some 442 | * that aren't. 443 | */ 444 | public static final JavaFileObject ANNOTATED_MEMBERS = JavaFileObjects.forSourceLines( 445 | "com.google.common.foo.AnnotatedMembers", 446 | "package com.google.common.foo;", 447 | "", 448 | "import com.google.common.annotations.Beta;", 449 | "", 450 | "public class AnnotatedMembers {", 451 | " public static final String STATIC_FIELD = \"foo\";", 452 | "", 453 | " @Beta", 454 | " public static final String ANNOTATED_STATIC_FIELD = \"foo\";", 455 | "", 456 | " public final String instanceField = \"foo\";", 457 | "", 458 | " @Beta", 459 | " public final String annotatedInstanceField = \"foo\";", 460 | "", 461 | " @Beta", 462 | " public AnnotatedMembers() {}", 463 | "", 464 | " public static String staticMethod() {", 465 | " return \"foo\";", 466 | " }", 467 | "", 468 | " @Beta", 469 | " public static String annotatedStaticMethod() {", 470 | " return \"foo\";", 471 | " }", 472 | "", 473 | " public String instanceMethod() {", 474 | " return \"foo\";", 475 | " }", 476 | "", 477 | " @Beta", 478 | " public String annotatedInstanceMethod() {", 479 | " return \"foo\";", 480 | " }", 481 | "}"); 482 | 483 | @Test 484 | public void testNonAnnotatedMembers() { 485 | List> diagnostics = compiler.compile( 486 | BETA, ANNOTATED_MEMBERS, 487 | JavaFileObjects.forSourceLines("example.Test", 488 | "package example;", 489 | "", 490 | "import com.google.common.foo.AnnotatedMembers;", 491 | "", 492 | "public class Test {", 493 | " public static void foo(AnnotatedMembers instance) {", 494 | " String a = AnnotatedMembers.staticMethod();", 495 | " String b = instance.instanceMethod();", 496 | " String c = AnnotatedMembers.STATIC_FIELD;", 497 | " String d = instance.instanceField;", 498 | " String e = instance.staticMethod();", 499 | " String f = instance.STATIC_FIELD;", 500 | " }", 501 | "}") 502 | ); 503 | 504 | assertThat(diagnostics).isEmpty(); 505 | } 506 | 507 | @Test 508 | public void testAnnotatedMembers_staticField() { 509 | List> diagnostics = compiler.compile( 510 | BETA, ANNOTATED_MEMBERS, 511 | JavaFileObjects.forSourceLines("example.Test", 512 | "package example;", 513 | "", 514 | "import com.google.common.foo.AnnotatedMembers;", 515 | "", 516 | "public class Test {", 517 | " public static void main(String[] args) {", 518 | " System.out.println(AnnotatedMembers.ANNOTATED_STATIC_FIELD);", // error 519 | " }", 520 | "}") 521 | ); 522 | 523 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 524 | } 525 | 526 | @Test 527 | public void testAnnotatedMembers_instanceField() { 528 | List> diagnostics = compiler.compile( 529 | BETA, ANNOTATED_MEMBERS, 530 | JavaFileObjects.forSourceLines("example.Test", 531 | "package example;", 532 | "", 533 | "import com.google.common.foo.AnnotatedMembers;", 534 | "", 535 | "public class Test {", 536 | " public static void foo(AnnotatedMembers instance) {", 537 | " System.out.println(instance.annotatedInstanceField);", // error 538 | " }", 539 | "}") 540 | ); 541 | 542 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 543 | } 544 | 545 | @Test 546 | public void testAnnotatedMembers_staticMethod() { 547 | List> diagnostics = compiler.compile( 548 | BETA, ANNOTATED_MEMBERS, 549 | JavaFileObjects.forSourceLines("example.Test", 550 | "package example;", 551 | "", 552 | "import com.google.common.foo.AnnotatedMembers;", 553 | "", 554 | "public class Test {", 555 | " public static void main(String[] args) {", 556 | " System.out.println(AnnotatedMembers.annotatedStaticMethod());", // error 557 | " }", 558 | "}") 559 | ); 560 | 561 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 562 | } 563 | 564 | @Test 565 | public void testAnnotatedMembers_instanceMethod() { 566 | List> diagnostics = compiler.compile( 567 | BETA, ANNOTATED_MEMBERS, 568 | JavaFileObjects.forSourceLines("example.Test", 569 | "package example;", 570 | "", 571 | "import com.google.common.foo.AnnotatedMembers;", 572 | "", 573 | "public class Test {", 574 | " public static void foo(AnnotatedMembers instance) {", 575 | " System.out.println(instance.annotatedInstanceMethod());", // error 576 | " }", 577 | "}") 578 | ); 579 | 580 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 581 | } 582 | 583 | @Test 584 | public void testAnnotatedMembers_staticField_fromStaticImport() { 585 | List> diagnostics = compiler.compile( 586 | BETA, ANNOTATED_MEMBERS, 587 | JavaFileObjects.forSourceLines("example.Test", 588 | "package example;", 589 | "", 590 | "import static com.google.common.foo.AnnotatedMembers.ANNOTATED_STATIC_FIELD;", 591 | "", 592 | "public class Test {", 593 | " public static void main(String[] args) {", 594 | " System.out.println(ANNOTATED_STATIC_FIELD);", // error 595 | " }", 596 | "}") 597 | ); 598 | 599 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 600 | } 601 | 602 | @Test 603 | public void testAnnotatedMembers_staticMethod_fromStaticImport() { 604 | List> diagnostics = compiler.compile( 605 | BETA, ANNOTATED_MEMBERS, 606 | JavaFileObjects.forSourceLines("example.Test", 607 | "package example;", 608 | "", 609 | "import static com.google.common.foo.AnnotatedMembers.annotatedStaticMethod;", 610 | "", 611 | "public class Test {", 612 | " public static void main(String[] args) {", 613 | " System.out.println(annotatedStaticMethod());", // error 614 | " }", 615 | "}") 616 | ); 617 | 618 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 7); 619 | } 620 | 621 | @Test 622 | public void testAnnotatedMembers_methodReference() { 623 | List> diagnostics = compiler.compile( 624 | BETA, ANNOTATED_MEMBERS, 625 | JavaFileObjects.forSourceLines("example.Test", 626 | "package example;", 627 | "", 628 | "import static java.util.stream.Collectors.joining;", 629 | "", 630 | "import com.google.common.foo.AnnotatedMembers;", 631 | "import java.util.List;", 632 | "", 633 | "public class Test {", 634 | " public static void foo(List list) {", 635 | " String s = list.stream()", 636 | " .map(AnnotatedMembers::annotatedInstanceMethod)", // error 637 | " .collect(joining(", "));", 638 | " }", 639 | "}") 640 | ); 641 | 642 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 11); 643 | } 644 | 645 | @Test 646 | public void testAnnotatedMembers_constructorReference() { 647 | List> diagnostics = compiler.compile( 648 | BETA, ANNOTATED_MEMBERS, 649 | JavaFileObjects.forSourceLines("example.Test", 650 | "package example;", 651 | "", 652 | "import com.google.common.foo.AnnotatedMembers;", 653 | "import java.util.Optional;", 654 | "", 655 | "public class Test {", 656 | " public static void foo(Optional optional) {", 657 | " String s = optional", 658 | " .orElseGet(AnnotatedMembers::new)", // error 659 | " .toString();", 660 | " }", 661 | "}") 662 | ); 663 | 664 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 9); 665 | } 666 | 667 | /** 668 | * An @Beta interface in a com.google.common package. 669 | */ 670 | private static final JavaFileObject ANNOTATED_INTERFACE = JavaFileObjects.forSourceLines( 671 | "com.google.common.foo.AnnotatedInterface", 672 | "package com.google.common.foo;", 673 | "", 674 | "import com.google.common.annotations.Beta;", 675 | "", 676 | "@Beta", 677 | "public interface AnnotatedInterface {", 678 | "}"); 679 | 680 | @Test 681 | public void testAnnotatedInterface_implementing() { 682 | List> diagnostics = compiler.compile( 683 | BETA, ANNOTATED_INTERFACE, 684 | JavaFileObjects.forSourceLines("example.Test", 685 | "package example;", 686 | "", 687 | "import com.google.common.foo.AnnotatedInterface;", 688 | "", 689 | "public class Test implements AnnotatedInterface {", // error 690 | "}") 691 | ); 692 | 693 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5); 694 | } 695 | 696 | @Test 697 | public void testAnnotatedInterface_extending() { 698 | List> diagnostics = compiler.compile( 699 | BETA, ANNOTATED_INTERFACE, 700 | JavaFileObjects.forSourceLines("example.Test", 701 | "package example;", 702 | "", 703 | "import com.google.common.foo.AnnotatedInterface;", 704 | "", 705 | "public interface Test extends AnnotatedInterface {", // error 706 | "}") 707 | ); 708 | 709 | compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5); 710 | } 711 | 712 | /** 713 | * These checkers only match usages in packages matching a specific regex, to avoid giving errors 714 | * on code with the annotations in other libraries or even in the user's code. The @Beta checker 715 | * should only match usages in packages under com.google.common. 716 | */ 717 | private static final JavaFileObject CLASS_IN_OTHER_PACKAGE = JavaFileObjects.forSourceLines( 718 | "foo.ClassInOtherPackage", 719 | "package foo;", 720 | "", 721 | "import com.google.common.annotations.Beta;", 722 | "", 723 | "@Beta", 724 | "public class ClassInOtherPackage {}"); 725 | 726 | @Test 727 | public void testUsageByPackage_nonMatchingPackage_doesNotMatch() { 728 | List> diagnostics = compiler.compile( 729 | BETA, CLASS_IN_OTHER_PACKAGE, 730 | JavaFileObjects.forSourceLines("example.Test", 731 | "package example;", 732 | "", 733 | "import foo.ClassInOtherPackage;", 734 | "", 735 | "public class Test {", 736 | " public static void main(String[] args) {", 737 | " System.out.println(new ClassInOtherPackage());", 738 | " }", 739 | "}") 740 | ); 741 | 742 | assertThat(diagnostics).isEmpty(); 743 | } 744 | 745 | private static final JavaFileObject IGNORED_TYPE = JavaFileObjects.forSourceLines( 746 | "com.google.common.cache.Cache", 747 | "package com.google.common.cache;", 748 | "", 749 | "import com.google.common.annotations.Beta;", 750 | "", 751 | "@Beta", 752 | "public interface Cache {", 753 | " V get(K key);", 754 | "}"); 755 | 756 | @Test 757 | public void testUsage_ignoredType() { 758 | List> diagnostics = compiler.compile( 759 | BETA, IGNORED_TYPE, 760 | JavaFileObjects.forSourceLines("example.Test", 761 | "package example;", 762 | "", 763 | "import com.google.common.cache.Cache;", 764 | "", 765 | "public class Test {", 766 | " public static void test(Cache cache) {", 767 | " System.out.println(cache.get(\"hello\"));", 768 | " }", 769 | "}") 770 | ); 771 | 772 | assertThat(diagnostics).isEmpty(); 773 | } 774 | } 775 | -------------------------------------------------------------------------------- /src/test/java/com/google/common/annotations/checkers/TestCompiler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.annotations.checkers; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | import static org.junit.Assert.assertEquals; 21 | import static org.junit.Assert.assertNotNull; 22 | 23 | import com.google.common.collect.ArrayListMultimap; 24 | import com.google.common.collect.ImmutableList; 25 | import com.google.common.collect.ImmutableMultiset; 26 | import com.google.common.collect.ListMultimap; 27 | import com.google.common.io.Files; 28 | import com.google.common.primitives.Longs; 29 | import com.google.errorprone.BaseErrorProneJavaCompiler; 30 | import com.google.errorprone.BugCheckerInfo; 31 | import com.google.errorprone.bugpatterns.BugChecker; 32 | import com.google.errorprone.scanner.ScannerSupplier; 33 | import java.io.File; 34 | import java.io.PrintWriter; 35 | import java.util.Arrays; 36 | import java.util.List; 37 | import java.util.Locale; 38 | import javax.tools.Diagnostic; 39 | import javax.tools.DiagnosticCollector; 40 | import javax.tools.JavaCompiler; 41 | import javax.tools.JavaCompiler.CompilationTask; 42 | import javax.tools.JavaFileObject; 43 | 44 | /** 45 | * Compiles Java sources with the {@link BetaChecker} and returns a list of diagnostics produced 46 | * by the compiler. 47 | * 48 | * @author Colin Decker 49 | */ 50 | final class TestCompiler { 51 | 52 | private final Class checker; 53 | 54 | TestCompiler(Class checker) { 55 | this.checker = checker; 56 | } 57 | 58 | // TODO(cgdecker): Would like to use compile-testing to avoid the need for this class 59 | 60 | /** 61 | * Compiles the given {@code sources} and returns a list of diagnostics produced by the compiler. 62 | */ 63 | public List> compile(JavaFileObject... sources) { 64 | return compile(Arrays.asList(sources)); 65 | } 66 | 67 | /** 68 | * Compiles the given {@code sources} and returns a list of diagnostics produced by the compiler. 69 | */ 70 | public List> compile( 71 | Iterable sources) { 72 | ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker); 73 | DiagnosticCollector collector = new DiagnosticCollector<>(); 74 | JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier); 75 | File tmpDir = Files.createTempDir(); 76 | CompilationTask task = 77 | compiler.getTask( 78 | new PrintWriter(System.err, true), 79 | null /*filemanager*/, 80 | collector, 81 | ImmutableList.of("-d", tmpDir.getAbsolutePath()), 82 | null /*classes*/, 83 | sources); 84 | try { 85 | task.call(); 86 | return collector.getDiagnostics(); 87 | } finally { 88 | File[] files = tmpDir.listFiles(); 89 | if (files != null) { 90 | for (File file : files) { 91 | file.delete(); 92 | } 93 | } 94 | tmpDir.delete(); 95 | } 96 | } 97 | 98 | private void assertErrorsOnLines( 99 | String file, 100 | List> diagnostics, 101 | long[] lines, 102 | boolean omitDuplicateLines) { 103 | ListMultimap actualErrors = ArrayListMultimap.create(); 104 | for (Diagnostic diagnostic : diagnostics) { 105 | String message = diagnostic.getMessage(Locale.US); 106 | 107 | // The source may be null, e.g. for diagnostics about command-line flags 108 | assertNotNull(message, diagnostic.getSource()); 109 | String sourceName = diagnostic.getSource().getName(); 110 | 111 | assertEquals( 112 | "unexpected error in source file " + sourceName + ": " + message, 113 | file, sourceName); 114 | 115 | long lineNumber = diagnostic.getLineNumber(); 116 | boolean omit = omitDuplicateLines && actualErrors.containsEntry(sourceName, lineNumber); 117 | if (!omit) { 118 | actualErrors.put(sourceName, lineNumber); 119 | } 120 | 121 | // any errors from the compiler that are not related to this checker should fail 122 | assertThat(message).contains("[" + BugCheckerInfo.create(checker).canonicalName() + "]"); 123 | } 124 | 125 | assertEquals( 126 | ImmutableMultiset.copyOf(Longs.asList(lines)), 127 | ImmutableMultiset.copyOf(actualErrors.get(file))); 128 | } 129 | 130 | /** 131 | * Asserts that the given diagnostics contain errors with a message containing "[CheckerName]" on 132 | * the given lines of the given file. If there should be multiple errors on a line, the line 133 | * number must appear multiple times. There may not be any errors in any other file. 134 | */ 135 | public void assertErrorsOnLines( 136 | String file, List> diagnostics, long... lines) { 137 | assertErrorsOnLines(file, diagnostics, lines, false); 138 | } 139 | 140 | /** 141 | * Asserts that the given diagnostics contain errors with a message containing "[CheckerName]" on 142 | * the given lines of the given file. Each line is only counted once, even if there are multiple 143 | * errors on it. 144 | */ 145 | public void assertErrorsOnUniqueLines( 146 | String file, List> diagnostics, long... lines) { 147 | assertErrorsOnLines(file, diagnostics, lines, true); 148 | } 149 | } 150 | --------------------------------------------------------------------------------