Compare commits

...

609 Commits

Author SHA1 Message Date
Stephan Schroevers
8c6bd1b6e7 [maven-release-plugin] prepare release v0.9.0 2023-03-31 09:30:59 +02:00
Picnic-Bot
0c1817c589 Upgrade Pitest Git plugins 1.0.6 -> 1.0.7 (#556) 2023-03-31 08:50:04 +02:00
Stephan Schroevers
73cf28e7ff Introduce DirectReturn check (#513) 2023-03-30 20:51:04 +02:00
Picnic-Bot
8a0abf5957 Upgrade Byte Buddy 1.14.2 -> 1.14.3 (#555)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.14.3
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.14.2...byte-buddy-1.14.3
2023-03-30 20:39:49 +02:00
Picnic-Bot
5fb4aed3ad Upgrade extra-enforcer-rules 1.6.1 -> 1.6.2 (#554)
See:
- https://github.com/mojohaus/extra-enforcer-rules/releases/tag/1.6.2
- https://github.com/mojohaus/extra-enforcer-rules/compare/extra-enforcer-rules-1.6.1...1.6.2
2023-03-30 09:34:58 +02:00
Picnic-Bot
aef9c5da7a Upgrade Forbidden APIs plugin 3.4 -> 3.5 (#553)
See:
- https://github.com/policeman-tools/forbidden-apis/wiki/Changes
- https://github.com/policeman-tools/forbidden-apis/compare/3.4...3.5
2023-03-28 08:09:28 +02:00
Picnic-Bot
7069e7a6d8 Upgrade pitest-maven-plugin 1.11.6 -> 1.11.7 (#552)
See:
- https://github.com/hcoles/pitest/releases/tag/1.11.7
- https://github.com/hcoles/pitest/compare/1.11.6...1.11.7
2023-03-28 07:32:21 +02:00
Bastien Diederichs
334c374ca1 Extend null check Refaster rules (#523)
Summary of changes:
- Replace `CheckNotNull` with `RequireNonNull{,WithMessage}{,Statement}`.
- Extend `Is{,Not}Null`.

Fixes #437.
2023-03-27 22:08:34 +02:00
Mohamed Sameh
57cd084f82 Extend StepVerifierStepIdentity Refaster rule (#541)
By flagging expressions of the form `step.expectNextCount(0)`.
2023-03-27 10:30:25 +02:00
Picnic-Bot
0b3be1b75b Upgrade Spring Boot 2.7.9 -> 2.7.10 (#549)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.10
- https://github.com/spring-projects/spring-boot/compare/v2.7.9...v2.7.10
2023-03-27 10:09:28 +02:00
Picnic-Bot
902538fd4a Upgrade maven-deploy-plugin 3.1.0 -> 3.1.1 (#546)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEPLOY%20AND%20fixVersion%20%3E%203.1.0%20AND%20fixVersion%20%3C%3D%203.1.1
- https://github.com/apache/maven-deploy-plugin/releases/tag/maven-deploy-plugin-3.1.1
- https://github.com/apache/maven-deploy-plugin/compare/maven-deploy-plugin-3.1.0...maven-deploy-plugin-3.1.1
2023-03-27 09:47:22 +02:00
Picnic-Bot
50f6b770e4 Upgrade maven-install-plugin 3.1.0 -> 3.1.1 (#547)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MINSTALL%20AND%20fixVersion%20%3E%203.1.0%20AND%20fixVersion%20%3C%3D%203.1.1
- https://github.com/apache/maven-install-plugin/releases/tag/maven-install-plugin-3.1.1
- https://github.com/apache/maven-install-plugin/compare/maven-install-plugin-3.1.0...maven-install-plugin-3.1.1
2023-03-27 09:30:46 +02:00
Picnic-Bot
47e0a779bd Upgrade maven-resources-plugin 3.3.0 -> 3.3.1 (#548)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MRESOURCES%20AND%20fixVersion%20%3E%203.3.0%20AND%20fixVersion%20%3C%3D%203.3.1
- https://github.com/apache/maven-resources-plugin/releases/tag/maven-resources-plugin-3.3.1
- https://github.com/apache/maven-resources-plugin/compare/maven-resources-plugin-3.3.0...maven-resources-plugin-3.3.1
2023-03-27 09:09:20 +02:00
Picnic-Bot
973d3c3cd9 Upgrade maven-release-plugin 2.5.3 -> 3.0.0 (#540)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MRELEASE%20AND%20fixVersion%20%3E%202.5.3%20AND%20fixVersion%20%3C%3D%203.0.0
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M1
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M2
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M3
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M4
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M5
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M6
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0-M7
- https://github.com/apache/maven-release/releases/tag/maven-release-3.0.0
- https://github.com/apache/maven-release/compare/maven-release-2.5.3...maven-release-3.0.0
2023-03-27 08:44:43 +02:00
Picnic-Bot
edb7290e2e Upgrade Checkstyle 10.9.2 -> 10.9.3 (#551)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.9.3
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.9.2...checkstyle-10.9.3
2023-03-27 08:32:43 +02:00
Picnic-Bot
d5c45e003f Upgrade modernizer-maven-plugin 2.5.0 -> 2.6.0 (#550)
See:
- https://github.com/gaul/modernizer-maven-plugin/releases/tag/modernizer-maven-plugin-2.6.0
- https://github.com/gaul/modernizer-maven-plugin/compare/modernizer-maven-plugin-2.5.0...modernizer-maven-plugin-2.6.0
2023-03-26 19:22:16 +02:00
Picnic-Bot
f784c64150 Upgrade pitest-maven-plugin 1.11.5 -> 1.11.6 (#544)
See:
- https://github.com/hcoles/pitest/releases/tag/1.11.6
- https://github.com/hcoles/pitest/compare/1.11.5...1.11.6
2023-03-25 19:57:48 +01:00
Guillaume Toison
978c90db9d Extend set of parameter types recognized by RequestMappingAnnotation (#543)
Additional types recognized:
- `jakarta.servlet.http.HttpServletRequest`
- `jakarta.servlet.http.HttpServletResponse`
- `org.springframework.ui.Model`
- `org.springframework.validation.BindingResult`
2023-03-25 19:48:00 +01:00
Picnic-Bot
ae89a37934 Upgrade swagger-annotations 1.6.9 -> 1.6.10 (#542)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.10
- https://github.com/swagger-api/swagger-core/compare/v1.6.9...v1.6.10
2023-03-23 09:22:22 +01:00
Bastien Diederichs
8f1d1df747 Introduce BugCheckerRules Refaster rule collection (#526) 2023-03-23 09:01:18 +01:00
Picnic-Bot
04368e9243 Upgrade SLF4J API 2.0.6 -> 2.0.7 (#536)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_2.0.6...v_2.0.7
2023-03-22 18:52:40 +01:00
Picnic-Bot
156df71616 Upgrade Spring 5.3.25 -> 5.3.26 (#539)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.26
- https://github.com/spring-projects/spring-framework/compare/v5.3.25...v5.3.26
2023-03-21 17:28:18 +01:00
Picnic-Bot
64b1c7eea4 Upgrade swagger-annotations 2.2.8 -> 2.2.9 (#538)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.9
- https://github.com/swagger-api/swagger-core/compare/v2.2.8...v2.2.9
2023-03-21 17:15:44 +01:00
Picnic-Bot
80d0d85826 Upgrade Checkstyle 10.9.1 -> 10.9.2 (#537)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.9.2
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.9.1...checkstyle-10.9.2
2023-03-21 11:44:37 +01:00
Stephan Schroevers
d30c99a28f Introduce AssertThatPathContent{,Utf8} Refaster rules (#530) 2023-03-20 13:48:41 +01:00
Picnic-Bot
29c23542da Upgrade pitest-maven-plugin 1.11.4 -> 1.11.5 (#534)
While there, fix `run-mutation-tests.sh` for compatibility with Surefire 3.0.0.

See:
- https://github.com/hcoles/pitest/releases/tag/1.11.5
- https://github.com/hcoles/pitest/compare/1.11.4...1.11.5
2023-03-18 15:10:16 +01:00
Picnic-Bot
62c1c277ae Upgrade Checkstyle 10.8.1 -> 10.9.1 (#535)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.9.0
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.9.1
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.8.1...checkstyle-10.9.1
2023-03-18 14:23:16 +01:00
Picnic-Bot
8580e89008 Upgrade Project Reactor 2022.0.4 -> 2022.0.5 (#533)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.5
- https://github.com/reactor/reactor/compare/2022.0.4...2022.0.5
2023-03-16 15:48:01 +01:00
Stephan Schroevers
06c8b164e9 Upgrade JDKs used by GitHub Actions builds (#521)
Additionally:
- Update the example version numbers mentioned in the issue template.
- Drop some redundant whitespace from `SourceCodeTest` test code.
- Sort some compiler arguments.

See:
- https://www.oracle.com/java/technologies/javase/11-0-17-relnotes.html
- https://www.oracle.com/java/technologies/javase/11-0-18-relnotes.html
- https://www.oracle.com/java/technologies/javase/17-0-5-relnotes.html
- https://www.oracle.com/java/technologies/javase/17-0-6-relnotes.html
- https://www.oracle.com/java/technologies/javase/19-0-1-relnotes.html
- https://www.oracle.com/java/technologies/javase/19-0-2-relnotes.html
2023-03-15 13:26:40 +01:00
Picnic-Bot
fd9d3157bc Upgrade Surefire 2.22.2 -> 3.0.0 (#532)
While there, drop an unnecessary JUnit configuration parameter.

See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20SUREFIRE%20AND%20fixVersion%20%3E%202.22.2%20AND%20fixVersion%20%3C%3D%203.0.0
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M1
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M2
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M3
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M4
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M5
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M6
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M7
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M8
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0-M9
- https://github.com/apache/maven-surefire/releases/tag/surefire-3.0.0
- https://github.com/apache/maven-surefire/compare/surefire-2.22.2..surefire-3.0.0
2023-03-15 13:01:20 +01:00
Picnic-Bot
a623f73c1c Upgrade Byte Buddy 1.14.1 -> 1.14.2 (#531)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.14.2
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.14.1...byte-buddy-1.14.2
2023-03-15 10:39:02 +01:00
Picnic-Bot
f9d0cd99d6 Upgrade Mockito 5.1.1 -> 5.2.0 (#529)
See:
- https://github.com/mockito/mockito/releases/tag/v5.2.0
- https://github.com/mockito/mockito/compare/v5.1.1...v5.2.0
2023-03-13 15:15:29 +01:00
Picnic-Bot
9bec3de372 Upgrade Pitest Git plugins 1.0.5 -> 1.0.6 (#522) 2023-03-13 10:33:22 +01:00
Picnic-Bot
4164514c5b Upgrade Checkstyle 10.8.0 -> 10.8.1 (#528)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.8.1
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.8.0...checkstyle-10.8.1
2023-03-13 09:58:38 +01:00
Picnic-Bot
c3cd535b16 Upgrade NullAway 0.10.9 -> 0.10.10 (#524)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.9...v0.10.10
2023-03-09 10:04:48 +01:00
Picnic-Bot
64195279cc Upgrade Byte Buddy 1.14.0 -> 1.14.1 (#525)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.14.1
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.14.0...byte-buddy-1.14.1
2023-03-09 08:36:25 +01:00
Pieter Dirk Soels
61c9f67f66 Introduce MockitoMockClassReference check (#454)
Flags Mockito mock and spy creation expressions that explicitly specify the
type of mock or spy to create, while this information can also be inferred from
context.
2023-03-06 09:54:26 +01:00
Picnic-Bot
4bb14b01ec Upgrade pitest-maven-plugin 1.11.3 -> 1.11.4 (#520)
See:
- https://github.com/hcoles/pitest/releases/tag/1.11.4
- https://github.com/hcoles/pitest/compare/1.11.3...1.11.4
2023-03-04 14:19:29 +01:00
Bastien Diederichs
b267b4dba8 Introduce ImmutableMapCopyOfMapsFilter{Keys,Values} Refaster rules (#517) 2023-03-03 13:09:44 +01:00
Picnic-Bot
03f0e0493b Upgrade Checker Framework Annotations 3.31.0 -> 3.32.0 (#519)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.32.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.31.0...checker-framework-3.32.0
2023-03-03 10:17:22 +01:00
Picnic-Bot
2111c81784 Upgrade pitest-maven-plugin 1.11.1 -> 1.11.3 (#514)
See:
- https://github.com/hcoles/pitest/releases/tag/1.11.2
- https://github.com/hcoles/pitest/releases/tag/1.11.3
- https://github.com/hcoles/pitest/compare/1.11.1...1.11.3
2023-03-03 08:53:01 +01:00
Picnic-Bot
43d50f2ef9 Upgrade Project Reactor 2022.0.3 -> 2022.0.4 (#518)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.4
- https://github.com/reactor/reactor/compare/2022.0.3...2022.0.4
2023-03-03 08:35:36 +01:00
Gijs de Jong
2d972fd975 Introduce JUnitValueSource check (#188)
This new check replaces JUnit `@MethodSource` usages with an equivalent
`@ValueSource` annotation where possible.
2023-03-02 10:45:35 +01:00
Bastien Diederichs
ee265a87ae Introduce FluxCountMapMathToIntExact Refaster rule (#516) 2023-03-02 08:48:33 +01:00
Picnic-Bot
6b4fba62da Upgrade pitest-maven-plugin 1.11.0 -> 1.11.1 (#509)
See:
- https://github.com/hcoles/pitest/releases/tag/1.11.1
- https://github.com/hcoles/pitest/compare/1.11.0...1.11.1
2023-02-27 16:47:31 +01:00
Picnic-Bot
e883e28e34 Upgrade Checkstyle 10.7.0 -> 10.8.0 (#512)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.8.0
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.7.0...checkstyle-10.8.0
2023-02-27 07:46:00 +01:00
Picnic-Bot
d84de6efba Upgrade Google Java Format 1.15.0 -> 1.16.0 (#511)
See:
- https://github.com/google/google-java-format/releases/tag/v1.16.0
- https://github.com/google/google-java-format/compare/v1.15.0...v1.16.0
2023-02-26 14:40:42 +01:00
Picnic-Bot
4dca61a144 Upgrade New Relic Java Agent 8.0.0 -> 8.0.1 (#508)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v8.0.1
- https://github.com/newrelic/newrelic-java-agent/compare/v8.0.0...v8.0.1
2023-02-25 12:23:02 +01:00
Picnic-Bot
dc9597a603 Upgrade Spring Boot 2.7.8 -> 2.7.9 (#510)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.9
- https://github.com/spring-projects/spring-boot/compare/v2.7.8...v2.7.9
2023-02-24 17:52:45 +01:00
Picnic-Bot
ec9853ac88 Upgrade versions-maven-plugin 2.14.2 -> 2.15.0 (#506)
See:
- https://github.com/mojohaus/versions/releases/tag/2.15.0
- https://github.com/mojohaus/versions-maven-plugin/compare/2.14.2...2.15.0
2023-02-22 08:55:17 +01:00
Giovanni Zotta
5bb1dd1a10 Introduce StreamMapTo{Double,Int,Long}Sum Refaster rules (#497)
As well as a new `IsLambdaExpressionOrMethodReference` matcher.
2023-02-21 16:35:29 +01:00
Picnic-Bot
fd6a45ebd8 Upgrade Project Reactor 2022.0.2 -> 2022.0.3 (#499)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.3
- https://github.com/reactor/reactor/compare/2022.0.2...2022.0.3
2023-02-20 18:58:23 +01:00
Benedek Halasi
82d4677509 Introduce FluxImplicitBlock check (#472) 2023-02-20 10:17:17 +01:00
Picnic-Bot
1fdf1016b7 Upgrade Byte Buddy 1.13.0 -> 1.14.0 (#505)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.14.0
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.13.0...byte-buddy-1.14.0
2023-02-20 08:46:28 +01:00
Picnic-Bot
80e537fce2 Upgrade Pitest Git plugins 1.0.4 -> 1.0.5 (#504) 2023-02-19 12:51:22 +01:00
Picnic-Bot
d85897ea62 Upgrade Checker Framework Annotations 3.30.0 -> 3.31.0 (#502)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.31.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.30.0...checker-framework-3.31.0
2023-02-18 14:38:57 +01:00
Picnic-Bot
c5bde3999d Upgrade maven-javadoc-plugin 3.4.1 -> 3.5.0 (#500)
See:
- https://github.com/apache/maven-javadoc-plugin/releases/tag/maven-javadoc-plugin-3.5.0
- https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.4.1...maven-javadoc-plugin-3.5.0
2023-02-17 13:28:27 +01:00
Rick Ossendrijver
575d494303 Upgrade Maven API 3.8.6 -> 3.8.7 (#498)
See:
- https://maven.apache.org/docs/3.8.7/release-notes.html
- https://github.com/apache/maven/releases/tag/maven-3.8.7
- https://github.com/apache/maven/compare/maven-3.8.6...maven-3.8.7
2023-02-16 13:44:25 +01:00
Picnic-Bot
844ef84d55 Upgrade maven-deploy-plugin 3.0.0 -> 3.1.0 (#495)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEPLOY%20AND%20fixVersion%20%3E%203.0.0%20AND%20fixVersion%20%3C%3D%203.1.0
- https://github.com/apache/maven-deploy-plugin/releases/tag/maven-deploy-plugin-3.1.0
- https://github.com/apache/maven-deploy-plugin/compare/maven-deploy-plugin-3.0.0...maven-deploy-plugin-3.1.0
2023-02-14 11:19:11 +01:00
Eric Staffas
29469cbbfd Introduce ConflictDetection utility class (#478) 2023-02-13 12:43:17 +01:00
Picnic-Bot
da9a6dd270 Upgrade Byte Buddy 1.12.23 -> 1.13.0 (#496)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.13.0
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.12.23...byte-buddy-1.13.0
2023-02-13 11:35:27 +01:00
Gökhun Çelik
0cb03aa132 Add Gradle installation instructions to README (#430) 2023-02-13 11:18:36 +01:00
Rick Ossendrijver
0f15070883 Introduce documentation-support module (#428)
This new module provides the initial version of a framework for the extraction 
of data from bug checkers and Refaster rules, to be used as input for website
generation.
2023-02-13 09:27:08 +01:00
Stephan Schroevers
14b5fa1feb Update .mvn/maven.config for compatibility with Maven 3.9.0 (#493)
See https://issues.apache.org/jira/browse/MNG-7684
2023-02-08 09:08:09 +01:00
Stephan Schroevers
d1f513373f Enable additional maven-enforcer-plugin rules (#489) 2023-02-06 14:16:05 +01:00
Picnic-Bot
cd1593009b Upgrade Pitest Git plugins 1.0.3 -> 1.0.4 (#490) 2023-02-06 11:49:37 +01:00
Picnic-Bot
0d52414c04 Upgrade Byte Buddy 1.12.22 -> 1.12.23 (#492)
See:
- https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.12.23
- https://github.com/raphw/byte-buddy/compare/byte-buddy-1.12.22...byte-buddy-1.12.23
2023-02-06 08:17:38 +01:00
Picnic-Bot
a55ed9cea9 Upgrade maven-enforcer-plugin 3.1.0 -> 3.2.1 (#487)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MENFORCER%20AND%20fixVersion%20%3E%203.1.0%20AND%20fixVersion%20%3C%3D%203.2.1%20
- https://github.com/apache/maven-enforcer/releases/tag/enforcer-3.2.1
- https://github.com/apache/maven-enforcer/compare/enforcer-3.1.0...enforcer-3.2.1
2023-02-04 10:33:11 +01:00
Picnic-Bot
9b191f46aa Upgrade Checker Framework Annotations 3.29.0 -> 3.30.0 (#488)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.30.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.29.0...checker-framework-3.30.0
2023-02-03 09:37:00 +01:00
Picnic-Bot
6ea756f3ce Upgrade sortpom-maven-plugin 3.2.0 -> 3.2.1 (#481)
See:
- https://github.com/Ekryd/sortpom/wiki/Versions
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.2.1
- https://github.com/Ekryd/sortpom/compare/sortpom-parent-3.2.0...sortpom-parent-3.2.1
2023-02-03 09:06:17 +01:00
Picnic-Bot
adbcc4a94f Upgrade Checkstyle 10.6.0 -> 10.7.0 (#486)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.7.0
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.6.0...checkstyle-10.7.0
2023-02-02 10:19:11 +01:00
Picnic-Bot
0ed2788dbd Upgrade NullAway 0.10.8 -> 0.10.9 (#485)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.8...v0.10.9
2023-02-02 09:22:00 +01:00
Picnic-Bot
04749ffcf5 Upgrade pitest-maven-plugin 1.10.4 -> 1.11.0 (#483)
See https://github.com/hcoles/pitest/compare/1.10.4...1.11.0
2023-01-31 08:49:11 +01:00
Picnic-Bot
37077bd03c Upgrade Mockito 5.1.0 -> 5.1.1 (#482)
See:
- https://github.com/mockito/mockito/releases/tag/v5.1.1
- https://github.com/mockito/mockito/compare/v5.1.0...v5.1.1
2023-01-31 08:30:51 +01:00
Picnic-Bot
4798f7cf5f Upgrade Jackson 2.14.1 -> 2.14.2 (#479)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.14.2
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.14.1...jackson-bom-2.14.2
2023-01-30 09:36:53 +01:00
Picnic-Bot
ac285f0c50 Upgrade Mockito 5.0.0 -> 5.1.0 (#480)
See:
- https://github.com/mockito/mockito/releases/tag/v5.1.0
- https://github.com/mockito/mockito/compare/v5.0.0...v5.1.0
2023-01-30 09:25:08 +01:00
Picnic-Bot
1f3fb08082 Upgrade New Relic Java Agent 7.11.1 -> 8.0.0 (#477)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v8.0.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.11.1...v8.0.0
2023-01-28 10:08:14 +01:00
Stephan Schroevers
9a397aa047 [maven-release-plugin] prepare for next development iteration 2023-01-27 09:20:57 +01:00
Stephan Schroevers
60e74332de [maven-release-plugin] prepare release v0.8.0 2023-01-27 09:20:54 +01:00
Stephan Schroevers
3a94aad3b0 Document MonoFlatMapToFlux Refaster rule limitation (#473) 2023-01-24 15:38:52 +01:00
Picnic-Bot
a5b5f43974 Upgrade TestNG 7.4.0 -> 7.7.1 (#469)
See:
- https://github.com/cbeust/testng/blob/master/CHANGES.txt
- https://github.com/cbeust/testng/releases/tag/7.6.0
- https://github.com/cbeust/testng/releases/tag/7.6.1
- https://github.com/cbeust/testng/releases/tag/7.7.0
- https://github.com/cbeust/testng/releases/tag/7.7.1
- https://github.com/cbeust/testng/compare/7.4.0...7.7.1
2023-01-24 09:45:13 +01:00
Rick Ossendrijver
c212b9a171 Enable Checkstyle's JavadocStyle module (#451)
See: 
- https://checkstyle.org/config_javadoc.html#JavadocStyle
- https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.html
2023-01-23 11:16:12 +01:00
Picnic-Bot
499f922328 Upgrade Spring 5.3.24 -> 5.3.25 (#460)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.25
- https://github.com/spring-projects/spring-framework/compare/v5.3.24...v5.3.25
2023-01-20 09:59:49 +01:00
Picnic-Bot
5720732b48 Upgrade Spring Boot 2.7.7 -> 2.7.8 (#471)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.8
- https://github.com/spring-projects/spring-boot/compare/v2.7.7...v2.7.8
2023-01-20 08:47:55 +01:00
Phil Werli
81ffd04fe4 Extend MonoIdentity Refaster rule (#470)
By flagging expressions of the form `mono.flux().singleOrEmpty()`.
2023-01-19 13:49:57 +01:00
Picnic-Bot
b2f514f0a5 Upgrade Mockito 4.11.0 -> 5.0.0 (#463)
See:
- https://github.com/mockito/mockito/releases/tag/v5.0.0
- https://github.com/mockito/mockito/compare/v4.11.0...v5.0.0
2023-01-19 10:59:24 +01:00
Picnic-Bot
dad92b5fa6 Upgrade maven-dependency-plugin 3.4.0 -> 3.5.0 (#461)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEP%20AND%20fixVersion%20%3E%203.4.0%20AND%20fixVersion%20%3C%3D%203.5.0%20AND%20statusCategory%20%3D%20Done%20
- https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.4.0...maven-dependency-plugin-3.5.0
2023-01-18 17:13:44 +01:00
Picnic-Bot
6d699f75ad Upgrade maven-checkstyle-plugin 3.2.0 -> 3.2.1 (#459)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MCHECKSTYLE%20AND%20fixVersion%20%3E%203.2.0%20AND%20fixVersion%20%3C%3D%203.2.1
- https://github.com/apache/maven-checkstyle-plugin/compare/maven-checkstyle-plugin-3.2.0...maven-checkstyle-plugin-3.2.1
2023-01-18 16:38:54 +01:00
Picnic-Bot
cad0c74dc0 Upgrade nohttp-checkstyle 0.0.10 -> 0.0.11 (#458)
See https://github.com/spring-io/nohttp/compare/0.0.10...0.0.11
2023-01-17 09:15:00 +01:00
Picnic-Bot
a3a1f495f1 Upgrade errorprone-slf4j 0.1.17 -> 0.1.18 (#466)
See:
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.18
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.17...v0.1.18
2023-01-17 08:48:31 +01:00
Picnic-Bot
b2a646fc21 Upgrade AssertJ 3.24.1 -> 3.24.2 (#467)
See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://assertj.github.io/doc/#assertj-guava-release-notes
- https://github.com/assertj/assertj/compare/assertj-build-3.24.1...assertj-build-3.24.2
2023-01-17 08:15:38 +01:00
Picnic-Bot
1194b0c83c Upgrade NullAway 0.10.7 -> 0.10.8 (#464)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.7...v0.10.8
2023-01-17 08:01:48 +01:00
Phil Werli
82a07fde25 Extend MonoIdentity Refaster rule (#465)
By flagging expressions of the form `mono.flux().next()`.
2023-01-17 07:33:56 +01:00
Picnic-Bot
dec3220b5b Upgrade pitest-junit5-plugin 1.1.1 -> 1.1.2 (#462)
See https://github.com/pitest/pitest-junit5-plugin/compare/1.1.1...1.1.2
2023-01-16 08:42:14 +01:00
Stephan Schroevers
79356ac553 Upgrade Error Prone 2.17.0 -> 2.18.0 (#455)
See:
- https://github.com/google/error-prone/releases/tag/v2.18.0
- https://github.com/google/error-prone/compare/v2.17.0...v2.18.0
- https://github.com/PicnicSupermarket/error-prone/compare/v2.17.0-picnic-1...v2.18.0-picnic-1
2023-01-11 19:12:39 +01:00
Picnic-Bot
f079c53914 Upgrade Project Reactor 2022.0.1 -> 2022.0.2 (#456)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.2
- https://github.com/reactor/reactor/compare/2022.0.1...2022.0.2
2023-01-11 13:58:41 +01:00
Picnic-Bot
8e24da907d Upgrade JUnit Jupiter 5.9.1 -> 5.9.2 (#457)
See:
- https://junit.org/junit5/docs/current/release-notes/index.html
- https://github.com/junit-team/junit5/releases/tag/r5.9.2
- https://github.com/junit-team/junit5/compare/r5.9.1...r5.9.2
2023-01-11 11:16:10 +01:00
Picnic-Bot
3c89a1c80d Upgrade AssertJ 3.24.0 -> 3.24.1 (#453)
See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://github.com/assertj/assertj/compare/assertj-build-3.24.0...assertj-build-3.24.1
2023-01-09 09:05:59 +01:00
Rick Ossendrijver
9bd4b16001 Inline most {BugCheckerRefactoring,Compilation}TestHelper fields (#442) 2023-01-08 12:40:20 +01:00
Picnic-Bot
6370452803 Upgrade swagger-annotations 2.2.7 -> 2.2.8 (#452)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.8
- https://github.com/swagger-api/swagger-core/compare/v2.2.7...v2.2.8
2023-01-08 12:16:52 +01:00
Benedek Halasi
feb9abfa91 Introduce MapGetOrDefault Refaster rule (#439)
Fixes #431.
2023-01-06 14:57:12 +01:00
Stephan Schroevers
560f52bad0 [maven-release-plugin] prepare for next development iteration 2023-01-06 11:29:12 +01:00
Stephan Schroevers
2356c61314 [maven-release-plugin] prepare release v0.7.0 2023-01-06 11:29:09 +01:00
Stephan Schroevers
9a9ef3c59d Have apply-error-prone-suggestions.sh download JitPack-hosted artifacts (#441)
While there, tweak the usage message of both `apply-error-prone-suggestions.sh`
and `run-mutation-tests.sh`.
2023-01-06 10:38:54 +01:00
Rick Ossendrijver
e9a1d54035 Add @OnlineDocumentation to TestNGToAssertJRules (#447) 2023-01-06 10:28:21 +01:00
Picnic-Bot
e9733f7426 Upgrade AssertJ Core 3.23.1 -> 3.24.0 (#448)
While there, use the new BOM.

See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://github.com/joel-costigliola/assertj-core/compare/assertj-core-3.23.1...assertj-build-3.24.0
2023-01-06 09:12:29 +01:00
Picnic-Bot
534ebb62a1 Upgrade Checker Framework Annotations 3.28.0 -> 3.29.0 (#449)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.29.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.28.0...checker-framework-3.29.0
2023-01-06 08:40:54 +01:00
Rick Ossendrijver
1ed1e6cd03 Update year to 2023 in footer_custom.html and LICENSE.md (#446) 2023-01-05 14:47:26 +01:00
Picnic-Bot
85e3db6f0a Upgrade pitest-maven-plugin 1.10.3 -> 1.10.4 (#445)
See:
- https://github.com/hcoles/pitest/releases/tag/1.10.4
- https://github.com/hcoles/pitest/compare/1.10.3...1.10.4
2023-01-05 09:58:06 +01:00
Picnic-Bot
6f4db8fc4d Upgrade NullAway 0.10.6 -> 0.10.7 (#444)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.6...v0.10.7
2023-01-05 08:32:46 +01:00
chamil-prabodha
9d08e8fd4d Have RequestParamType ignore parameter types with custom deserialization support (#426)
While there, introduce and use a new `Flags` utility class; various checks'
list flags now better support empty lists.
2023-01-04 11:13:44 +01:00
Picnic-Bot
9992ff49ce Upgrade pitest-junit5-plugin 1.1.0 -> 1.1.1 (#440)
See https://github.com/pitest/pitest-junit5-plugin/compare/1.1.0...1.1.1
2023-01-04 10:21:44 +01:00
jarmilakaiser
190b47870b Show original Cody in README and on website home page (#438)
This reverts commit 0153c1495f.
2023-01-04 09:27:21 +01:00
Stephan Schroevers
becfcb5374 Upgrade Error Prone 2.16 -> 2.17.0 (#432)
See:
- https://github.com/google/error-prone/releases/tag/v2.17.0
- https://github.com/google/error-prone/compare/v2.16...v2.17.0
- https://github.com/PicnicSupermarket/error-prone/compare/v2.16-picnic-2...v2.17.0-picnic-1
2023-01-03 13:47:21 +01:00
Benedek Halasi
d45682143d Introduce/extend RequireNonNullElse{,Get} Refaster rules (#425)
Fixes #364.
2023-01-02 10:25:10 +01:00
Picnic-Bot
4237732c5b Upgrade errorprone-slf4j 0.1.16 -> 0.1.17 (#433)
See:
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.17
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.16...v0.1.17
2023-01-02 10:04:51 +01:00
Picnic-Bot
d7c86c4854 Upgrade Checkstyle 10.5.0 -> 10.6.0 (#435)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.6.0
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.5.0...checkstyle-10.6.0
2023-01-02 09:33:21 +01:00
Christos Giallouros
e6e50717d3 Introduce JUnitToAssertJRules Refaster rule collection (#417) 2023-01-02 08:51:46 +01:00
Picnic-Bot
834f9ae49b Upgrade NullAway 0.10.5 -> 0.10.6 (#429)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.5...v0.10.6
2022-12-30 12:22:12 +01:00
Pieter Dirk Soels
601fcf2648 Update website styling and add Google site verification (#408) 2022-12-30 08:46:27 +01:00
Picnic-Bot
27c6c48e68 Upgrade Mockito 4.10.0 -> 4.11.0 (#427)
See:
- https://github.com/mockito/mockito/releases/tag/v4.11.0
- https://github.com/mockito/mockito/compare/v4.10.0...v4.11.0
2022-12-29 08:02:16 +01:00
Picnic-Bot
b22078657a Upgrade AspectJ 1.9.9.1 -> 1.9.19 (#422)
See:
- https://github.com/eclipse/org.aspectj/releases/tag/V1_9_19
- https://github.com/eclipse/org.aspectj/compare/V1_9_9_1...V1_9_19
2022-12-27 08:51:16 +01:00
Picnic-Bot
165a003f6a Upgrade Spring Boot 2.7.6 -> 2.7.7 (#423)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.7
- https://github.com/spring-projects/spring-boot/compare/v2.7.6...v2.7.7
2022-12-27 08:34:41 +01:00
Picnic-Bot
ecb8820d80 Upgrade versions-maven-plugin 2.14.1 -> 2.14.2 (#424)
See:
- https://github.com/mojohaus/versions/releases/tag/2.14.2
- https://github.com/mojohaus/versions-maven-plugin/compare/2.14.1...2.14.2
2022-12-27 06:38:04 +01:00
Stephan Schroevers
6313bd56d8 Improve JUnitMethodDeclaration check (#406)
Implemented changes:
- Ignore method overrides even if not annotated with `@Override`.
- Don't rename methods to `true`, `false` or `null`.
- Don't rename methods to a name declared in a super type. This
  prevents e.g. renaming `testToString` to `toString`.
2022-12-22 08:34:11 +01:00
Stephan Schroevers
5665470fe4 Improve IdentityConversion check (#407)
If the result of an explicit boxing operation is immediately
dereferenced, then the explicit conversion operation is not redundant.
2022-12-21 09:44:30 +01:00
EvgheniiShipilov
d0a89da24d Have IdentityConversion flag com.google.errorprone.matchers.Matchers#{allOf,anyOf} (#420)
While there, sort and rename some (test) code.

Fixes #340.
2022-12-20 11:14:46 +01:00
Picnic-Bot
7c40fdc033 Upgrade Arcmutate 1.0.1 -> 1.0.2 (#418) 2022-12-19 21:02:39 +01:00
Picnic-Bot
8724701baf Upgrade Immutables Annotations 2.9.2 -> 2.9.3 (#413)
See:
- https://github.com/immutables/immutables/releases/tag/2.9.3
- https://github.com/immutables/immutables/compare/2.9.2...2.9.3
2022-12-19 14:12:40 +01:00
Picnic-Bot
e9ae238c2b Upgrade Mockito 4.9.0 -> 4.10.0 (#416)
See:
- https://github.com/mockito/mockito/releases/tag/v4.10.0
- https://github.com/mockito/mockito/compare/v4.9.0...v4.10.0
2022-12-19 13:52:49 +01:00
Picnic-Bot
ff2ed6f82c Upgrade JSpecify 0.2.0 -> 0.3.0 (#415)
See:
- https://github.com/jspecify/jspecify/releases/tag/v0.3.0-alpha-1
- https://github.com/jspecify/jspecify/releases/tag/v0.3.0-alpha-2
- https://github.com/jspecify/jspecify/releases/tag/v0.3.0-alpha-3
- https://github.com/jspecify/jspecify/releases/tag/v0.3.0
- https://github.com/jspecify/jspecify/compare/v0.2.0...v0.3.0
2022-12-19 13:14:50 +01:00
Picnic-Bot
17aeeb9ea9 Upgrade versions-maven-plugin 2.13.0 -> 2.14.1 (#414)
See:
- https://github.com/mojohaus/versions/releases/tag/2.14.0
- https://github.com/mojohaus/versions/releases/tag/2.14.1
- https://github.com/mojohaus/versions-maven-plugin/compare/2.13.0...2.14.1
2022-12-19 12:56:03 +01:00
Stephan Schroevers
fd2946a9c8 Disable failing JDK 20-ea build for now (#419)
The build fails due to
openjdk/jdk20@2cb64a7557; the upcoming
Error Prone release includes a workaround for this:
google/error-prone@df033f03cb.
2022-12-19 09:37:03 +01:00
Guillaume Toison
870d16a0b6 Prevent NestedOptionals from throwing an NPE (#412)
Previously, a `NullPointerException` was thrown if during compilation the
`java.util.Optional` class was not loaded at all.
2022-12-16 09:40:05 +01:00
Picnic-Bot
96114235c5 Upgrade Project Reactor 2022.0.0 -> 2022.0.1 (#411)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.1
- https://github.com/reactor/reactor/compare/2022.0.0...2022.0.1
2022-12-14 07:18:40 +01:00
Picnic-Bot
bfbf748d47 Upgrade SLF4J API 2.0.5 -> 2.0.6 (#409)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_2.0.5...v_2.0.6
2022-12-13 17:11:06 +01:00
Stephan Schroevers
8d0f1d78e6 Upgrade Error Prone fork v2.16-picnic-1 -> v2.16-picnic-2 (#410)
See:
- https://github.com/PicnicSupermarket/error-prone/releases/tag/v2.16-picnic-2
- https://github.com/PicnicSupermarket/error-prone/compare/v2.16-picnic-1...v2.16-picnic-2
2022-12-13 12:51:50 +01:00
Stephan Schroevers
ec00a5522f [maven-release-plugin] prepare for next development iteration 2022-12-12 09:57:05 +01:00
Stephan Schroevers
465b16c471 [maven-release-plugin] prepare release v0.6.0 2022-12-12 09:57:03 +01:00
Paco van Beckhoven
2cbd48ec47 Introduce MonoIdentity and MonoThen Refaster rules (#405)
The `MonoIdentity` rule is a generalization of the existing
`MonoSwitchIfEmptyOfEmptyPublisher` rule.
2022-12-12 08:52:56 +01:00
jarmilakaiser
0153c1495f Show Christmas Cody in README and on website home page (#404) 2022-12-09 16:27:51 +01:00
Rick Ossendrijver
81450285be Fix suggestions emitted by the StringCaseLocaleUsage check (#400)
The suggested `Locale` arguments are now always located in the correct place.
2022-12-09 14:35:35 +01:00
Bastien Diederichs
096acfb14f Improve IsInstanceLambdaUsage check (#401)
Fixes #399.
2022-12-09 13:27:46 +01:00
Shang Xiang
17bcdb6faa Introduce Flux and Stream Refaster rules to suggest filtering before sorting (#393)
Fixes #386.
2022-12-09 13:07:31 +01:00
Rick Ossendrijver
3ee527fda2 Drop indentation in feature request issue template (#403)
While there, add "Improve performance" as a rewrite reason.
2022-12-09 08:55:12 +01:00
Stephan Schroevers
b1c815770b Prevent ReverseOrder Refaster rule from introducing a static import (#397)
This is a workaround for the issue resolved by google/error-prone#3584.

After application of this Refaster rule, any static imports of
`java.util.Collections.reverseOrder` are obsolete. These can be removed by
running Google Java Format or Error Prone's `RemoveUnusedImports` check.

Where possible, subsequent application of the `StaticImport` check will
statically import `java.util.Comparator.reverseOrder`.
2022-12-08 09:06:19 +01:00
Vincent Koeman
bc1f204877 Prefer BigDecimal.valueOf(double) over new BigDecimal(double) (#394)
See https://rules.sonarsource.com/java/RSPEC-2111
2022-12-07 18:58:54 +01:00
Picnic-Bot
cf995ece2b Upgrade actions/setup-java v3.6.0 -> v3.8.0 (#395)
See:
- https://github.com/actions/setup-java/releases/tag/v3.8.0
- https://github.com/actions/setup-java/compare/v3.6.0...v3.8.0
2022-12-07 11:48:55 +01:00
Stephan Schroevers
d427e298e2 Introduce additional Refaster rules to ComparatorRules (#388) 2022-12-07 11:38:25 +01:00
Picnic-Bot
ae327d8d64 Upgrade pitest-maven-plugin 1.9.11 -> 1.10.3 (#378)
See:
- https://github.com/hcoles/pitest/releases/tag/1.10.0
- https://github.com/hcoles/pitest/releases/tag/1.10.1
- https://github.com/hcoles/pitest/releases/tag/1.10.2
- https://github.com/hcoles/pitest/releases/tag/1.10.3
- https://github.com/hcoles/pitest/compare/1.9.11...1.10.3
2022-12-06 11:58:47 +01:00
Gonzalo Amestoy
a6f794de3d Introduce CollectionForEach Refaster rule (#390)
Fixes #387.
2022-12-06 09:28:24 +01:00
Picnic-Bot
1794d36053 Upgrade Pitest Git plugins 1.0.2 -> 1.0.3 (#391) 2022-12-06 09:04:37 +01:00
Phil Werli
ee62af4a86 Introduce MonoFromOptionalSwitchIfEmpty and OptionalMapMonoJust Refaster rules (#384) 2022-12-06 08:26:34 +01:00
Phil Werli
1afce12b52 Introduce Mono{Empty,Just,JustOrEmpty} Refaster rules (#385) 2022-12-06 08:15:39 +01:00
Rick Ossendrijver
f585306a1f Downgrade actions/setup-java v3.7.0 -> v3.6.0 (#392)
This reverts commit 5afa7e1878. Tag v3.7.0 was
deleted; see actions/setup-java#422 for details.
2022-12-06 08:06:58 +01:00
Luke Prananta
4f9aba83ec Introduce StringCaseLocaleUsage check (#376) 2022-12-05 13:49:20 +01:00
Stephan Schroevers
066591c379 Improve mutation testing setup (#383)
Summary of changes:
- Enable Pitest's built-in `STRONGER` mutator group.
- Enable Arcmutate's `EXTENDED` mutator group.
- Enable Arcmutate's JUnit 5 Accelerator Plugin.
- Modify `MoreTypesTest` such that it is impacted by mutations of the
  `MoreTypes` class.

See:
- https://pitest.org/quickstart/mutators/
- https://docs.arcmutate.com/docs/extended-operators.html
- https://docs.arcmutate.com/docs/accelerator.html
2022-12-05 09:11:51 +01:00
Picnic-Bot
789f8c86f2 Upgrade Pitest Git plugins 1.0.1 -> 1.0.2 (#380) 2022-12-05 09:01:20 +01:00
Picnic-Bot
0ccebcc9c4 Upgrade Checker Framework Annotations 3.27.0 -> 3.28.0 (#382)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.28.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.27.0...checker-framework-3.28.0
2022-12-04 19:57:42 +01:00
Gijs de Jong
8803d23a8e Introduce JUnitClassModifiers check (#214) 2022-12-04 16:49:01 +01:00
Picnic-Bot
5afa7e1878 Upgrade actions/setup-java v3.6.0 -> v3.7.0 (#381)
See:
- https://github.com/actions/setup-java/releases/tag/v3.7.0
- https://github.com/actions/setup-java/compare/v3.6.0...v3.7.0
2022-12-02 09:49:13 +01:00
Picnic-Bot
8e3beb9d5c Upgrade ruby/setup-ruby v1.123.0 -> v1.126.0 (#379)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.124.0
- https://github.com/ruby/setup-ruby/releases/tag/v1.125.0
- https://github.com/ruby/setup-ruby/releases/tag/v1.126.0
- https://github.com/ruby/setup-ruby/compare/v1.123.0...v1.126.0
2022-12-01 09:01:08 +01:00
Picnic-Bot
96ab66cdcf Upgrade maven-dependency-plugin 3.3.0 -> 3.4.0 (#377)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEP%20AND%20fixVersion%20%3E%203.3.0%20AND%20fixVersion%20%3C%3D%203.4.0%20AND%20statusCategory%20%3D%20Done%20
- https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.3.0...maven-dependency-plugin-3.4.0
2022-11-30 16:44:09 +01:00
Stephan Schroevers
330328329f Report mutation test coverage of proposed changes (#346)
Thanks to a free Arcmutate OSS license, GitHub Actions now runs Pitest against
files changed in the context of a PR. 

While there, update Pitest's configuration to ignore Refaster rule collection
classes, as mutations of those classes will not impact the associated unit
tests.

See:
- https://www.arcmutate.com
- https://pitest.org
2022-11-30 09:14:58 +01:00
Phil Werli
f46859ae3a Introduce some Refaster rules that avoid nested Publishers (#374) 2022-11-28 16:24:55 +01:00
Christos Giallouros
6d15cfe7ff Introduce {Mono,Flux}DefaultIfEmpty Refaster rules (#370)
Resolves #363.
2022-11-28 13:15:25 +01:00
Picnic-Bot
fa1bb8aa94 Upgrade Spring Boot 2.7.5 -> 2.7.6 (#372)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.6
- https://github.com/spring-projects/spring-boot/compare/v2.7.5...v2.7.6
2022-11-28 13:01:20 +01:00
Picnic-Bot
415ae35906 Upgrade SLF4J API 2.0.4 -> 2.0.5 (#371)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_2.0.4...v_2.0.5
2022-11-28 12:46:35 +01:00
Picnic-Bot
7cc8abc3de Upgrade Checkstyle 10.4 -> 10.5.0 (#375)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.5.0
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.4...checkstyle-10.5.0
2022-11-28 09:04:31 +01:00
Picnic-Bot
16c8bb0b27 Upgrade actions/configure-pages v2.1.2 -> v2.1.3 (#316)
See:
- https://github.com/actions/configure-pages/releases/tag/v2.1.3
- https://github.com/actions/configure-pages/compare/v2.1.2...v2.1.3
2022-11-24 08:37:02 +01:00
Rick Ossendrijver
609d80c9fa Drop unused Palantir {assertj,baseline}-error-prone dependencies (#367) 2022-11-23 16:20:04 +01:00
Picnic-Bot
793bda50d2 Upgrade Jackson 2.14.0 -> 2.14.1 (#366)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.14.1
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.14.0...jackson-bom-2.14.1
2022-11-23 08:14:27 +01:00
Picnic-Bot
5d86a66791 Upgrade actions/deploy-pages v1.2.2 -> v1.2.3 (#365)
See:
- https://github.com/actions/deploy-pages/releases/tag/v1.2.3
- https://github.com/actions/deploy-pages/compare/v1.2.2...v1.2.3
2022-11-22 14:27:40 +01:00
Eric Staffas
84d425e4ca Introduce More{ASTHelpers,JUnitMatchers,Matchers} utility classes (#335) 2022-11-22 13:35:03 +01:00
Picnic-Bot
4fead24e73 Upgrade maven-install-plugin 3.0.1 -> 3.1.0 (#362)
See:
- https://github.com/apache/maven-install-plugin/releases/tag/maven-install-plugin-3.1.0
- https://github.com/apache/maven-install-plugin/compare/maven-install-plugin-3.0.1...maven-install-plugin-3.1.0
2022-11-21 22:23:25 +01:00
Picnic-Bot
92df829801 Upgrade SLF4J API 2.0.3 -> 2.0.4 (#360)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_2.0.3...v_2.0.4
2022-11-21 15:44:14 +01:00
Stephan Schroevers
98185b92ae Improve Tree deletion suggestions (#347)
When suggesting to remove a method or method annotation, also remove any
trailing whitespace. This avoids the possible introduction of an empty
line right at the start of a code block.
2022-11-21 13:01:32 +01:00
Picnic-Bot
1b6356a876 Upgrade NullAway 0.10.4 -> 0.10.5 (#359)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.4...v0.10.5
2022-11-19 13:31:29 +01:00
Picnic-Bot
919a7c7ebe Upgrade AutoValue 1.10 -> 1.10.1 (#361)
See:
- https://github.com/google/auto/releases/tag/auto-value-1.10.1
- https://github.com/google/auto/compare/auto-value-1.10...auto-value-1.10.1
2022-11-19 13:16:30 +01:00
Phil Werli
79b0123f41 Extend MonoFlux Refaster rule (#358) 2022-11-19 11:56:44 +01:00
Picnic-Bot
3967542edf Upgrade Spring 5.3.23 -> 5.3.24 (#355)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.24
- https://github.com/spring-projects/spring-framework/compare/v5.3.23...v5.3.24
2022-11-19 10:30:34 +01:00
Rick Ossendrijver
0f05d15dd2 Have Renovate file ruby/setup-ruby upgrade PRs at most once a month (#357) 2022-11-18 14:16:20 +01:00
Picnic-Bot
5bdb90634a Upgrade New Relic Java Agent 7.11.0 -> 7.11.1 (#350)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.11.1
- https://github.com/newrelic/newrelic-java-agent/compare/v7.11.0...v7.11.1
2022-11-18 10:44:45 +01:00
Picnic-Bot
1808164c0d Upgrade swagger-annotations 1.6.8 -> 1.6.9 (#352)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.9
- https://github.com/swagger-api/swagger-core/compare/v1.6.8...v1.6.9
2022-11-18 10:21:53 +01:00
Picnic-Bot
f451b4cb73 Upgrade ruby/setup-ruby v1.121.0 -> v1.123.0 (#345)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.122.0
- https://github.com/ruby/setup-ruby/releases/tag/v1.123.0
- https://github.com/ruby/setup-ruby/compare/v1.121.0...v1.123.0
2022-11-18 09:39:42 +01:00
Picnic-Bot
d4c95299eb Upgrade pitest-maven-plugin 1.9.10 -> 1.9.11 (#354)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.11
- https://github.com/hcoles/pitest/compare/1.9.10...1.9.11
2022-11-18 09:16:08 +01:00
Picnic-Bot
1b93843d62 Upgrade swagger-annotations 2.2.6 -> 2.2.7 (#351)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.7
- https://github.com/swagger-api/swagger-core/compare/v2.2.6...v2.2.7
2022-11-17 16:37:39 +01:00
Picnic-Bot
3929b39e62 Upgrade actions/upload-pages-artifact v1.0.4 -> v1.0.5 (#353)
See:
- https://github.com/actions/upload-pages-artifact/releases/tag/v1.0.5
- https://github.com/actions/upload-pages-artifact/compare/v1.0.4...v1.0.5
2022-11-17 14:22:02 +01:00
Picnic-Bot
81f701fd9e Upgrade Mockito 4.8.1 -> 4.9.0 (#349)
See:
- https://github.com/mockito/mockito/releases/tag/v4.9.0
- https://github.com/mockito/mockito/compare/v4.8.1...v4.9.0
2022-11-15 09:19:39 +01:00
Picnic-Bot
b040648400 Upgrade modernizer-maven-plugin 2.4.0 -> 2.5.0 (#348)
See:
- https://github.com/gaul/modernizer-maven-plugin/releases/tag/modernizer-maven-plugin-2.5.0
- https://github.com/gaul/modernizer-maven-plugin/compare/modernizer-maven-plugin-2.4.0...modernizer-maven-plugin-2.5.0
2022-11-14 09:41:07 +01:00
Picnic-Bot
79ca98d20f Upgrade pitest-maven-plugin 1.9.9 -> 1.9.10 (#344)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.10
- https://github.com/hcoles/pitest/compare/1.9.9...1.9.10
2022-11-12 16:08:30 +01:00
Picnic-Bot
a6122270a9 Upgrade Project Reactor 2020.0.24 -> 2022.0.0 (#342)
See:
- https://github.com/reactor/reactor/releases/tag/2022.0.0
- https://github.com/reactor/reactor/compare/2020.0.24...2022.0.0
2022-11-12 15:50:15 +01:00
Picnic-Bot
4c0f2c966c Upgrade ruby/setup-ruby v1.120.1 -> v1.121.0 (#343)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.121.0
- https://github.com/ruby/setup-ruby/compare/v1.120.1...v1.121.0
2022-11-12 13:38:33 +01:00
Picnic-Bot
778a6e7043 Upgrade ruby/setup-ruby v1.120.0 -> v1.120.1 (#341)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.120.1
- https://github.com/ruby/setup-ruby/compare/v1.120.0...v1.120.1
2022-11-10 07:45:10 +01:00
Luke Prananta
b6146efaf6 Introduce MapIsEmpty Refaster rule (#339) 2022-11-09 10:45:53 +01:00
Stephan Schroevers
fcaa1f7068 Improve and extend Refaster Map rules (#337)
Summary of changes:
- Move relevant rules from `AssertJRules` to `AssertJMapRules` and introduce 
  associated tests.
- Extract relevant rules from `AssortedRules` to the new `MapRules` Refaster 
  rule collection.
- Add a few new rules to both `AssertJMapRules` and `MapRules`.
2022-11-09 08:54:43 +01:00
Picnic-Bot
ece33b0061 Upgrade Jackson 2.13.4.20221013 -> 2.14.0 (#338)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.14
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.13.4.20221013...jackson-bom-2.14.0
2022-11-07 10:34:44 +01:00
Phil Werli
48772a044e Introduce Optional{Filter,Map} Refaster rules (#327) 2022-11-04 19:41:23 +01:00
Shang Xiang
281534aeca Introduce Refaster rules to streamline java.time type creation (#322) 2022-11-04 19:27:20 +01:00
Bastien Diederichs
42e632e5db Introduce IsInstanceLambdaUsage check (#323) 2022-11-04 11:47:29 +01:00
Hervé Boutemy
7febccb7ff Add Reproducible Builds badge to README (#333) 2022-11-03 20:27:45 +01:00
Guillaume Toison
d5c1c858d5 Configure documentation URL for StringJoin check (#331) 2022-11-03 16:15:59 +01:00
Picnic-Bot
55d2622380 Upgrade Checker Framework Annotations 3.26.0 -> 3.27.0 (#330)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.27.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.26.0...checker-framework-3.27.0
2022-11-03 08:56:18 +01:00
Picnic-Bot
f10f2c9209 Upgrade NullAway 0.10.3 -> 0.10.4 (#328)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.3...v0.10.4
2022-11-03 08:18:25 +01:00
Picnic-Bot
99f85614fd Upgrade swagger-annotations 2.2.4 -> 2.2.6 (#329)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.5
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.6
- https://github.com/swagger-api/swagger-core/compare/v2.2.4...v2.2.6
2022-11-03 08:00:58 +01:00
Stephan Schroevers
be24edadae [maven-release-plugin] prepare for next development iteration 2022-11-01 08:56:43 +01:00
Stephan Schroevers
068c03708b [maven-release-plugin] prepare release v0.5.0 2022-11-01 08:56:40 +01:00
Picnic-Bot
9c330981ea Upgrade Checkstyle 10.3.4 -> 10.4 (#325)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.4
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.3.4...checkstyle-10.4
2022-10-31 08:15:38 +01:00
Bastien Diederichs
b780c05dc0 Introduce assorted Reactor error handling Refaster rules (#318) 2022-10-30 16:45:40 +01:00
Picnic-Bot
16955a9cfa Upgrade NullAway 0.10.2 -> 0.10.3 (#324)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.2...v0.10.3
2022-10-30 16:34:31 +01:00
Stephan Schroevers
8fa3ff3702 By default, prevent BugCheckers from introducing new dependencies (#308) 2022-10-29 13:42:51 +02:00
Picnic-Bot
022a3d293e Upgrade New Relic Java Agent 7.10.0 -> 7.11.0 (#320)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.11.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.10.0...v7.11.0
2022-10-28 08:56:32 +02:00
Picnic-Bot
81227cdd94 Upgrade tidy-maven-plugin 1.1.0 -> 1.2.0 (#271)
See:
- https://github.com/mojohaus/tidy-maven-plugin/releases/tag/tidy-maven-plugin-1.2.0
- https://github.com/mojohaus/tidy-maven-plugin/compare/tidy-maven-plugin-1.1.0...tidy-maven-plugin-1.2.0
2022-10-27 16:28:43 +02:00
Stephan Schroevers
04d886c031 Improve build and deployment concurrency handling (#284)
Builds for the same branch are now serialized. Among other things this prevents
concurrent deployments.

While there, reduce the permission assigned to each of the two jobs.
2022-10-27 10:31:06 +02:00
Cernat Catalin Stefan
afb2a28dcf Introduce {Mono,Flux}Map{,NotNull} Refaster rules (#142) 2022-10-26 17:11:16 +02:00
Phil Werli
dc0f90e981 Introduce {Mono,Flux}#zipWith{,Iterable} Refaster rules (#293) 2022-10-26 10:53:27 +02:00
Elena Liashenko
2196bbd8f9 Have FluxFlatMapUsage better handle nested Publishers (#224) 2022-10-26 10:40:09 +02:00
Picnic-Bot
f3b81304b9 Upgrade pitest-maven-plugin 1.9.8 -> 1.9.9 (#136)
See https://github.com/hcoles/pitest/compare/1.9.8...1.9.9
2022-10-26 10:00:34 +02:00
Picnic-Bot
b0d374040a Upgrade ruby/setup-ruby v1.118.0 -> v1.120.0 (#317)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.119.0
- https://github.com/ruby/setup-ruby/releases/tag/v1.120.0
- https://github.com/ruby/setup-ruby/compare/v1.118.0...v1.120.0
2022-10-26 09:19:33 +02:00
Eric Staffas
45dfc53d40 Prefer Flux#take(long, boolean) over Flux#take(long) to limit upstream generation (#314) 2022-10-26 08:28:35 +02:00
Rick Ossendrijver
6cb10ffe2f Build and test on additional platforms and against additional JDKs (#301) 2022-10-25 17:51:24 +02:00
Stephan Schroevers
92f2b0ab0f Introduce MoreTypes utility class (#234)
The static methods of this class allow one to construct complex types,
against which expression types can subsequently be matched.
2022-10-25 17:13:43 +02:00
chamil-prabodha
21388273c5 Have TimeZoneUsage check flag {OffsetDate,Offset,ZonedDate}Time#now (#311) 2022-10-25 16:54:28 +02:00
Stephan Schroevers
b2e15607c1 Migrate from JSR 305 to JSpecify (#181)
JSpecify's annotations have more well-defined semantics. Its `@Nullable`
annotation is also a type-use annotation recognized by Google Java
Format, so the formatter places it after any field or method modifiers.

See https://jspecify.dev
2022-10-25 10:18:22 +02:00
Stephan Schroevers
50e730fb40 Have LexicographicalAnnotationListing sort TYPE_USE annotations last (#182)
This ensures compatibility with Error Prone's `AnnotationPosition`
check.
2022-10-25 10:01:23 +02:00
Picnic-Bot
a844b9e532 Upgrade actions/configure-pages v2.1.1 -> v2.1.2 (#312)
See:
- https://github.com/actions/configure-pages/releases/tag/v2.1.2
- https://github.com/actions/configure-pages/compare/v2.1.1...v2.1.2
2022-10-25 09:24:43 +02:00
Stephan Schroevers
671ee1eedb Don't update project.build.outputTimestamp on mvn versions:set (#310)
As we rely on the value of `git.commit.time` instead.
2022-10-24 13:31:35 +02:00
Picnic-Bot
7fe61c226a Upgrade versions-maven-plugin 2.12.0 -> 2.13.0 (#309)
See:
- https://github.com/mojohaus/versions-maven-plugin/releases/tag/2.13.0
- https://github.com/mojohaus/versions-maven-plugin/compare/versions-maven-plugin-2.12.0...2.13.0
2022-10-24 13:21:55 +02:00
Picnic-Bot
8fcc91febf Upgrade Spring Boot 2.7.4 -> 2.7.5 (#307)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.5
- https://github.com/spring-projects/spring-boot/compare/v2.7.4...v2.7.5
2022-10-24 10:14:17 +02:00
Rick Ossendrijver
e00aba12c3 Make the build JDK 18+ compatible (#304) 2022-10-23 18:15:38 +02:00
Phil Werli
0118cc6c10 Introduce Reactor ContextEmpty Refaster rule (#306) 2022-10-23 17:30:01 +02:00
Picnic-Bot
91e009cab0 Upgrade actions/setup-java v3.5.1 -> v3.6.0 (#305)
See:
- https://github.com/actions/setup-java/releases/tag/v3.6.0
- https://github.com/actions/setup-java/compare/v3.5.1...v3.6.0
2022-10-20 09:13:00 +02:00
Phil Werli
68dca3204e Introduce Guava Preconditions Refaster rules (#292) 2022-10-20 08:55:49 +02:00
Picnic-Bot
e6ccb523fd Upgrade Mockito 4.8.0 -> 4.8.1 (#303)
See:
- https://github.com/mockito/mockito/releases/tag/v4.8.1
- https://github.com/mockito/mockito/compare/v4.8.0...v4.8.1
2022-10-20 08:46:03 +02:00
Picnic-Bot
d0533f7190 Upgrade actions/deploy-pages v1.2.1 -> v1.2.2 (#302)
See:
- https://github.com/actions/deploy-pages/releases/tag/v1.2.2
- https://github.com/actions/deploy-pages/compare/v1.2.1...v1.2.2
2022-10-20 08:12:58 +02:00
Picnic-Bot
759e7ea2ff Upgrade swagger-annotations 2.2.3 -> 2.2.4 (#299)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.4
- https://github.com/swagger-api/swagger-core/compare/v2.2.3...v2.2.4
2022-10-17 14:54:27 +02:00
Picnic-Bot
2578857a37 Upgrade errorprone-slf4j 0.1.15 -> 0.1.16 (#296)
See:
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.16
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.15...v0.1.16
2022-10-17 11:10:20 +02:00
Picnic-Bot
1d28512f09 Upgrade swagger-annotations 1.6.7 -> 1.6.8 (#300)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.8
- https://github.com/swagger-api/swagger-core/compare/v1.6.7...v1.6.8
2022-10-17 10:44:11 +02:00
Picnic-Bot
4efd79bfa6 Upgrade Project Reactor 2020.0.23 -> 2020.0.24 (#295)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.24
- https://github.com/reactor/reactor/compare/2020.0.23...2020.0.24
2022-10-17 10:25:01 +02:00
Picnic-Bot
d6b28733f6 Upgrade Jackson 2.13.4 -> 2.13.4.20221013 (#294)
See:
- https://github.com/FasterXML/jackson-databind/compare/jackson-databind-2.13.4...jackson-databind-2.13.4.2
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.13.4...jackson-bom-2.13.4.20221013
2022-10-15 17:01:00 +02:00
Picnic-Bot
b9884fa6d6 Upgrade Error Prone 2.15.0 -> 2.16 (#291)
See:
- https://github.com/google/error-prone/releases/tag/v2.16
- https://github.com/google/error-prone/compare/v2.15.0...v2.16
- https://github.com/PicnicSupermarket/error-prone/compare/v2.15.0-picnic-3...v2.16-picnic-1
2022-10-15 13:22:02 +02:00
Picnic-Bot
4fd8f57430 Upgrade ruby/setup-ruby v1.117.0 -> v1.118.0 (#298)
See:
- https://github.com/ruby/setup-ruby/releases/tag/v1.118.0
- https://github.com/ruby/setup-ruby/compare/v1.117.0...v1.118.0
2022-10-15 11:03:17 +02:00
Jelmer Borst
a2559bddda Fix and simplify documented example compiler output (#297) 2022-10-13 10:12:37 +02:00
Stephan Schroevers
7de9bede19 [maven-release-plugin] prepare for next development iteration 2022-10-13 09:20:46 +02:00
Stephan Schroevers
85cb997f1b [maven-release-plugin] prepare release v0.4.0 2022-10-13 09:20:46 +02:00
Stephan Schroevers
d5a78186db Augment Descriptions of Refaster rule matches (#255)
By emitting a website link, if available, and reporting the matching Refaster
rule in the description's message rather than the check name. Additionally, it
is now possible to provide a custom explanatory text, to assign a custom
severity to Refaster rules, and to override the severity of matches for all
Refaster rules by passing `-Xep:Refaster:[SEVERITY]`.

Violations of Refaster rules defined in this repository now include a link to
the rule's documentation, hosted on https://error-prone.picnic.tech.
2022-10-12 11:41:14 +02:00
Rick Ossendrijver
128e178d37 Consistently prefer "Refaster rule" over "Refaster template" (#286)
As the former term references a class containing one or more `@BeforeTemplate`
methods, one or more `@Placeholder` methods and an optional `@AfterTemplate`, 
while the latter term more narrowly references a single `@BeforeTemplate` or 
`@AfterTemplate` method.
2022-10-11 17:23:54 +02:00
Picnic-Bot
7aef2cfe51 Upgrade pitest-maven-plugin 1.9.7 -> 1.9.8 (#290)
See https://github.com/hcoles/pitest/compare/1.9.7...1.9.8
2022-10-11 15:43:05 +02:00
Pieter Dirk Soels
5cec0dd508 Rename Slf4JLogStatementTest to Slf4jLogStatementTest (#289) 2022-10-11 14:57:19 +02:00
Rick Ossendrijver
3f1399c139 Accommodate rapid website development on the website branch (#287)
By (a) deploying from that branch and (b) temporarily disabling external link
checking.
2022-10-11 14:43:34 +02:00
Jelmer Borst
757d5b1d70 Unify local and GitHub Actions website generation flow (#274) 2022-10-09 19:43:01 +02:00
Jelmer Borst
45cac6105e Have website use theme variables instead of custom SASS overrides (#285) 2022-10-09 19:41:32 +02:00
Picnic-Bot
8f8f57fc5b Upgrade AutoValue 1.9 -> 1.10 (#283)
See:
- https://github.com/google/auto/releases/tag/auto-value-1.10
- https://github.com/google/auto/compare/auto-value-1.9...auto-value-1.10
2022-10-09 10:03:55 +02:00
Bastien Diederichs
902d4f7736 Suggest Flux#concatMap{,Iterable} usage in more contexts (#279) 2022-10-08 11:12:41 +02:00
Sander Mak
4ec349582c Reference blog post in README (#282) 2022-10-07 21:28:08 +02:00
Bastien Diederichs
57836103ea Fix LexicographicalAnnotationAttributeListing string sorting (#281)
In particular, the empty string is now ordered first.
2022-10-07 14:34:14 +02:00
chamil-prabodha
bd73243c34 Introduce {Mono,Flux}OnErrorComplete Refaster rules (#273) 2022-10-07 11:54:50 +02:00
Stephan Schroevers
9af50d7e0b Introduce StringJoin check (#194)
This new `BugChecker` flags `String#format` invocations which can be
replaced with a `String#join` or even `String#valueOf` invocation.
2022-10-06 11:27:29 +02:00
Picnic-Bot
f5ae47fbac Upgrade pitest-maven-plugin 1.9.6 -> 1.9.7 (#280)
See https://github.com/hcoles/pitest/compare/1.9.6...1.9.7
2022-10-06 10:40:32 +02:00
Picnic-Bot
9ad8c275d3 Upgrade actions/checkout v3.0.2 -> v3.1.0 (#277)
See:
- https://github.com/actions/checkout/releases/tag/v3.1.0
- https://github.com/actions/checkout/compare/v3.0.2...v3.1.0
2022-10-05 15:57:16 +02:00
Jelmer Borst
f4e191e33b Fix default branch reference in GitHub Actions definition (#278) 2022-10-05 12:48:07 +02:00
Picnic-Bot
c4e476a731 Upgrade Checker Framework Annotations 3.25.0 -> 3.26.0 (#276)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.26.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.25.0...checker-framework-3.26.0
2022-10-04 10:03:16 +02:00
Jelmer Borst
5ca95eb36d Set up documentation website generation and deployment (#253)
Generating the website is done by Jekyll with a theme called `just-the-docs`. 
Deployment of the website is done via GitHub Pages.

See:
- https://github.com/jekyll/jekyll
- https://github.com/just-the-docs/just-the-docs
2022-10-04 09:08:23 +02:00
Picnic-Bot
9204ef0e84 Upgrade pitest-maven-plugin 1.9.5 -> 1.9.6 (#275)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.6
- https://github.com/hcoles/pitest/compare/1.9.5...1.9.6
2022-10-04 08:53:45 +02:00
Picnic-Bot
ed45be4e15 Upgrade Forbidden APIs plugin 3.3 -> 3.4 (#272)
See:
- https://github.com/policeman-tools/forbidden-apis/wiki/Changes
- https://github.com/policeman-tools/forbidden-apis/compare/3.3...3.4
2022-10-03 07:04:08 +02:00
Rick Ossendrijver
0561c371de Emit website link along with BugChecker rewrite suggestions (#251) 2022-10-02 14:12:27 +02:00
Nadir Belarouci
aa5ad4d25b Introduce Comparators{Min,Max} Refaster templates (#270) 2022-09-29 20:35:05 +02:00
Rick Ossendrijver
8c0041a94e Fix typos and grammar in pom.xml (#268) 2022-09-29 16:10:30 +02:00
Stephan Schroevers
397f9c3df7 Suggest canonical modifier usage for Refaster template definitions (#254) 2022-09-29 13:07:56 +02:00
Stephan Schroevers
2ba7bf9f46 Have RefasterTemplateCollection verify template test class names (#233) 2022-09-29 11:53:22 +02:00
Rick Ossendrijver
5b079eef84 Rename package tech.picnic.errorprone.refaster.{util => matchers} (#267) 2022-09-29 10:29:36 +02:00
Picnic-Bot
a2ce053daf Upgrade SLF4J API 2.0.2 -> 2.0.3 (#269)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_2.0.2...v_2.0.3
2022-09-29 08:28:00 +02:00
Picnic-Bot
ba02bad9bf Upgrade pitest-junit5-plugin 1.0.0 -> 1.1.0 (#265)
See https://github.com/pitest/pitest-junit5-plugin/compare/1.0.0...1.1.0
2022-09-28 20:13:53 +02:00
Picnic-Bot
d97a20247f Upgrade swagger-annotations 2.2.2 -> 2.2.3 (#263)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.3
- https://github.com/swagger-api/swagger-core/compare/v2.2.2...v2.2.3
2022-09-28 19:47:13 +02:00
Sander Mak
50970eb932 Apply small README improvements (#266) 2022-09-28 17:21:51 +02:00
Picnic-Bot
7e7318ad80 Upgrade swagger-annotations 1.6.6 -> 1.6.7 (#264)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.7
- https://github.com/swagger-api/swagger-core/compare/v1.6.6...v1.6.7
2022-09-28 08:26:53 +02:00
Rick Ossendrijver
fb6fe5a96e Introduce GitHub issue template for feature requests (#244) 2022-09-27 14:53:33 +02:00
Rick Ossendrijver
e37da2a1ed Drop unnecessary BugCheckerRefactoringTestHelper file path prefixes (#248) 2022-09-27 14:22:52 +02:00
Picnic-Bot
7bef1c8e67 Upgrade actions/setup-java v3.4.1 -> v3.5.1 (#262)
See:
- https://github.com/actions/setup-java/releases/tag/v3.5.0
- https://github.com/actions/setup-java/releases/tag/v3.5.1
- https://github.com/actions/setup-java/compare/v3.4.1...v3.5.1
2022-09-27 07:57:25 +02:00
Picnic-Bot
0160eafca0 Upgrade Checkstyle 10.3.3 -> 10.3.4 (#260)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.3.4
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.3.3...checkstyle-10.3.4
2022-09-26 09:01:51 +02:00
Rick Ossendrijver
891fecd297 Replace occurrences of "which" with "that" in defining clauses (#259) 2022-09-25 19:09:22 +02:00
Jelmer Borst
7f18bd9030 Introduce GitHub issue template for reporting a bug (#223) 2022-09-25 11:26:12 +02:00
Picnic-Bot
1473a70de8 Upgrade Spring Boot 2.7.3 -> 2.7.4 (#257)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.4
- https://github.com/spring-projects/spring-boot/compare/v2.7.3...v2.7.4
2022-09-23 13:55:00 +02:00
Rick Ossendrijver
c0c3ce2644 Set project home page to https://error-prone.picnic.tech (#258) 2022-09-23 13:04:46 +02:00
Picnic-Bot
100d5c86f7 Upgrade NullAway 0.10.1 -> 0.10.2 (#256)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.1...v0.10.2
2022-09-22 10:32:30 +02:00
Picnic-Bot
e12f99975b Upgrade SLF4J API 1.7.36 -> 2.0.2 (#209)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_1.7.36...v_2.0.1
2022-09-22 09:00:19 +02:00
Picnic-Bot
791113669f Upgrade JUnit Jupiter 5.9.0 -> 5.9.1 (#252)
See:
- https://junit.org/junit5/docs/current/release-notes/index.html
- https://github.com/junit-team/junit5/releases/tag/r5.9.1
- https://github.com/junit-team/junit5/compare/r5.9.0...r5.9.1
2022-09-21 16:07:03 +02:00
Stephan Schroevers
564bc7e1d1 Generate reproducible build output (#243)
By deriving `project.build.outputTimestamp` from the timestamp of the 
most recent commit, the timestamp embedded in generated JARs no longer
depends on the exact time at which the artifacts are built. As such
repeated executions of `mvn clean install` yield byte-for-byte identical
results.

This change requires replacing `buildnumber-maven-plugin` with
`git-commit-id-maven-plugin`.

See https://maven.apache.org/guides/mini/guide-reproducible-builds.html
2022-09-21 13:23:02 +02:00
Rick Ossendrijver
43bcbeaa98 Update XXX comments to reference google/error-prone#2706 (#249) 2022-09-21 08:23:09 +02:00
Svava Bjarnadóttir
d682b7d41f Fix typos and grammar in error-prone-contrib/README.md (#250)
While there, drop an obsolete TODO entry.
2022-09-21 07:55:07 +02:00
Stephan Schroevers
72a124a20e [maven-release-plugin] prepare for next development iteration 2022-09-20 13:47:18 +02:00
Stephan Schroevers
326f3328a7 [maven-release-plugin] prepare release v0.3.0 2022-09-20 13:47:16 +02:00
Stephan Schroevers
ae7068f464 Fix Javadoc JAR generation (#246)
For performance reasons, the Javadoc JARs are not generated when executing `mvn
install`. They are generally only compiled when running `mvn release:perform`,
as part of the `release` Maven profile.

The downside of this setup is that Javadoc generation issues may not be caught
until release time. This change resolves such an issue. To prevent future
regressions, Javadoc generation is now also performed by the GitHub Actions
build workflow.

While there, drop the deprecated `useReleaseProfile` configuration setting of
the javadoc-maven-plugin, as its value matches the default.
2022-09-20 13:42:52 +02:00
Stephan Schroevers
066931fe53 Add newline at end of logo.svg and logo-dark.svg (#247)
For compatibility with our internal format script.
2022-09-20 07:39:50 +02:00
Svava Bjarnadóttir
3874ca9be2 Introduce OptionalIdentity Refaster template (#245) 2022-09-19 21:20:50 +02:00
Jelmer Borst
84ba3946d9 Introduce {CONTRIBUTING,LICENSE,README}.md and Error Prone Support's logo (#212) 2022-09-19 08:50:08 +02:00
Picnic-Bot
b675ff680f Upgrade Error Prone 2.14.0 -> 2.15.0 (#179)
See:
- https://github.com/google/error-prone/releases/tag/v2.15.0
- https://github.com/google/error-prone/compare/v2.14.0...v2.15.0
- https://github.com/PicnicSupermarket/error-prone/compare/v2.14.0-picnic-2...v2.15.0-picnic-3
2022-09-18 15:25:18 +02:00
Shang Xiang
8e7d04a24c Introduce AssertJComparableTemplates and AssertJPrimitiveTemplates (#225) 2022-09-18 14:59:18 +02:00
Rick Ossendrijver
bfc951b61f Introduce IsCharacter matcher for use by Refaster templates (#237)
This new matcher is used to improve the `AssertThatIsOdd` and
`AssertThatIsEven` Refaster templates.

While there, apply assorted semi-related test improvements.
2022-09-18 14:39:25 +02:00
Picnic-Bot
b30562bbd8 Upgrade maven-jar-plugin 3.2.2 -> 3.3.0 (#242)
See:
- https://github.com/apache/maven-jar-plugin/releases/tag/maven-jar-plugin-3.3.0
- https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.2.2...maven-jar-plugin-3.3.0
2022-09-17 13:10:30 +02:00
Picnic-Bot
9be85204ae Upgrade versions-maven-plugin 2.11.0 -> 2.12.0 (#226)
See:
- https://github.com/mojohaus/versions-maven-plugin/releases/tag/versions-maven-plugin-2.12.0
- https://github.com/mojohaus/versions-maven-plugin/compare/versions-maven-plugin-2.11.0...versions-maven-plugin-2.12.0
2022-09-16 20:29:26 +02:00
Picnic-Bot
6fbf1b0cb2 Upgrade New Relic Java Agent 7.9.0 -> 7.10.0 (#241)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.10.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.9.0...v7.10.0
2022-09-16 09:06:18 +02:00
Picnic-Bot
5a428e6e29 Upgrade Spring 5.3.22 -> 5.3.23 (#240)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.23
- https://github.com/spring-projects/spring-framework/compare/v5.3.22...v5.3.23
2022-09-16 08:52:40 +02:00
Picnic-Bot
71163c0061 Upgrade Project Reactor 2020.0.22 -> 2020.0.23 (#239)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.23
- https://github.com/reactor/reactor/compare/2020.0.22...2020.0.23
2022-09-15 21:30:56 +02:00
Picnic-Bot
880be0dbdd Upgrade NullAway 0.10.0 -> 0.10.1 (#238)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.10.0...v0.10.1
2022-09-15 21:08:43 +02:00
Stephan Schroevers
62fe10f2cd Prefer Mono#fromSupplier over Mono#fromCallable where possible (#232)
This rule is implemented using a Refaster template, relying on the new 
`ThrowsCheckedException` matcher.

While there, introduce `AbstractTestChecker` to simplify the test setup for
Refaster `Matcher`s. This base class flags all `ExpressionTree`s matched by the
`Matcher` under test.
2022-09-15 09:42:16 +02:00
Nathan Kooij
f7ec28368a Drop or replace references to Travis CI (#236)
- Update Maven's `ciManagement` section to refer to GitHub Actions.
- Drop an obsolete "wish list" entry.
2022-09-14 07:38:22 +02:00
Jeanderson Barros Candido
e34c2baf7c Prefer simple null reference check over calling Objects#{isNull,nonNull} (#228) 2022-09-10 14:37:54 +02:00
Picnic-Bot
184ba8af51 Upgrade NullAway 0.9.10 -> 0.10.0 (#231)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.10...v0.10.0
2022-09-10 14:04:36 +02:00
Stephan Schroevers
63c3aa8259 Improve the RedundantStringConversion check (#193)
- Describe the set of well-known string conversion methods more
  concisely.
- Extend said set to include all relevant `String#valueOf` overloads.
2022-09-10 13:11:44 +02:00
Picnic-Bot
7daabeee48 Upgrade Mockito 4.7.0 -> 4.8.0 (#230)
See:
- https://github.com/mockito/mockito/releases/tag/v4.8.0
- https://github.com/mockito/mockito/compare/v4.7.0...v4.8.0
2022-09-09 10:14:20 +02:00
Picnic-Bot
0acfd8a723 Upgrade Immutables Annotations 2.9.1 -> 2.9.2 (#229)
See:
- https://github.com/immutables/immutables/releases/tag/2.9.2
- https://github.com/immutables/immutables/compare/2.9.1r...2.9.2
2022-09-09 09:04:13 +02:00
Vincent Koeman
000fcefe92 Have RequestMappingAnnotation recognize @RequestPart parameters (#227) 2022-09-08 15:25:46 +02:00
Rick Ossendrijver
1e3ad0fe32 Fix typo in pom.xml (#222) 2022-09-08 12:49:45 +02:00
Stephan Schroevers
b88a668819 Reduce GitHub Actions build workflow permissions (#221) 2022-09-08 08:54:43 +02:00
Stephan Schroevers
4c8e125dcb Drop the dependency on com.google.errorprone:javac (#197)
This new setup matches the upstream Error Prone build configuration and
simplifies development against JDK 11+ internal APIs.
2022-09-05 16:11:06 +02:00
Picnic-Bot
4ab5dc4f32 Upgrade Jackson 2.13.3 -> 2.13.4 (#220)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.13.4
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.13.3...jackson-bom-2.13.4
2022-09-05 09:11:41 +02:00
Picnic-Bot
7c667334cc Upgrade Checker Framework Annotations 3.24.0 -> 3.25.0 (#219)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.25.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.24.0...checker-framework-3.25.0
2022-09-03 13:31:57 +02:00
Picnic-Bot
b4b2afd130 Upgrade NullAway 0.9.9 -> 0.9.10 (#217)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.9...v0.9.10
2022-09-01 08:06:51 +02:00
Picnic-Bot
4445c93f6e Upgrade errorprone-slf4j 0.1.13 -> 0.1.15 (#218)
See:
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.14
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.15
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.13...v0.1.15
2022-09-01 08:00:59 +02:00
Picnic-Bot
5a7d7ff89b Upgrade Checkstyle 10.3.2 -> 10.3.3 (#216)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.3.3
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.3.2...checkstyle-10.3.3
2022-08-30 10:02:17 +02:00
Picnic-Bot
7ef75e8f07 Upgrade maven-checkstyle-plugin 3.1.2 -> 3.2.0 (#215)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MCHECKSTYLE%20AND%20fixVersion%20%3E%203.1.2%20AND%20fixVersion%20%3C%3D%203.2.0
- https://github.com/apache/maven-checkstyle-plugin/compare/maven-checkstyle-plugin-3.1.2...maven-checkstyle-plugin-3.2.0
2022-08-25 09:26:59 +02:00
Rick Ossendrijver
a1f2418805 Introduce release.yml to improve GitHub release notes generation (#213) 2022-08-24 16:31:15 +02:00
Picnic-Bot
39bfcc75ca Upgrade Immutables 2.9.0 -> 2.9.1 (#210)
See:
- https://github.com/immutables/immutables/releases/tag/2.9.1
- https://github.com/immutables/immutables/compare/2.9.0...2.9.1
2022-08-24 09:33:53 +02:00
Stephan Schroevers
753cdce29e [maven-release-plugin] prepare for next development iteration 2022-08-23 08:33:02 +02:00
Stephan Schroevers
36654883e5 [maven-release-plugin] prepare release v0.2.0 2022-08-23 08:33:02 +02:00
Picnic-Bot
d5372934ec Upgrade pitest-maven-plugin 1.9.4 -> 1.9.5 (#211)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.5
- https://github.com/hcoles/pitest/compare/1.9.4...1.9.5
2022-08-23 07:55:01 +02:00
Stephan Schroevers
f810530599 Fix several RxJava2Adapter Refaster templates (#205)
This reverts some changes from d2bbee3ed9
and instead drops some invalid `Flowable#compose` and `Flux#transform`
rewrite rules.
2022-08-22 11:05:24 +02:00
Stephan Schroevers
6928381403 Drop unnecessary dependency declarations (#208) 2022-08-22 10:49:40 +02:00
Stephan Schroevers
5657a48552 Prefer String#valueOf over Objects#toString (#192)
While there, drop obsolete `NoFunctionalReturnType` warning suppressions.
2022-08-22 10:29:23 +02:00
Stephan Schroevers
50aaf77a9e Enable nohttp-checkstyle (#206)
While this Checkstyle configuration only flags `http://` usages in
Maven-managed source files (thus not in e.g. `pom.xml` or `README.md`
files), this is a low-effort improvement.
2022-08-22 09:39:19 +02:00
Cernat Catalin Stefan
b8e22ffef0 Introduce NonEmptyMono check (#200) 2022-08-20 12:47:56 +02:00
Picnic-Bot
17035a1623 Upgrade Spring Boot 2.7.2 -> 2.7.3 (#207)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.3
- https://github.com/spring-projects/spring-boot/compare/v2.7.2...v2.7.3
2022-08-20 09:54:57 +02:00
Picnic-Bot
e7dacd19d7 Upgrade Maven API 3.6.3 -> 3.8.6 (#184)
See:
- https://maven.apache.org/release-notes-all.html
- https://github.com/apache/maven/releases/tag/maven-3.8.4
- https://github.com/apache/maven/releases/tag/maven-3.8.5
- https://github.com/apache/maven/releases/tag/maven-3.8.6
- https://github.com/apache/maven/compare/maven-3.6.3...maven-3.8.6
2022-08-19 19:05:18 +02:00
Bastien Diederichs
e64af1dde0 Don't enforce sorting of Spring resource locations (#204)
Because their order matters.
2022-08-19 15:29:21 +02:00
Rick Ossendrijver
a58630bccf Improve StreamMapToOptionalGet Refaster template documentation (#203) 2022-08-19 13:33:23 +02:00
Gijs de Jong
9ab5bbe042 Require static import of com.google.errorprone.matchers.Matchers methods (#201) 2022-08-18 15:21:16 +02:00
Stephan Schroevers
4ca75c6cf6 Enable Error Prone's VoidMissingNullable check (#180) 2022-08-18 14:28:01 +02:00
Ferdinand Swoboda
7883b31eb6 Introduce ImmutablesSortedSetComparator check (#102) 2022-08-18 11:33:20 +02:00
Stephan Schroevers
ef751ce785 Drop various vacuous null checks (#191)
Recent versions of Error Prone guarantee that `ASTHelpers#getSymbol`
never returns `null`.
2022-08-18 11:25:35 +02:00
Vincent Koeman
130c3d0bc3 Introduce NestedOptionals check (#202) 2022-08-17 22:14:31 +02:00
Picnic-Bot
c89e3905bf Upgrade Mockito 4.6.1 -> 4.7.0 (#196)
See:
- https://github.com/mockito/mockito/releases/tag/v4.7.0
- https://github.com/mockito/mockito/compare/v4.6.1...v4.7.0
2022-08-17 16:37:54 +02:00
Picnic-Bot
21421ce753 Upgrade maven-javadoc-plugin 3.4.0 -> 3.4.1 (#195)
See:
- https://github.com/apache/maven-javadoc-plugin/releases/tag/maven-javadoc-plugin-3.4.1
- https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.4.0...maven-javadoc-plugin-3.4.1
2022-08-17 16:00:15 +02:00
Ivan Fedorov
c39d1251d2 Rewrite another ThrowableAssertAlternative#withMessage(String, Object...) expression (#190) 2022-08-17 07:38:22 +02:00
Dario Deya Diaz
9bc732b4fe Have RequestMappingAnnotation recognize @RequestAttribute parameters (#189) 2022-08-12 20:56:28 +02:00
Picnic-Bot
74100b6c41 Upgrade Project Reactor 2020.0.21 -> 2020.0.22 (#187)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.22
- https://github.com/reactor/reactor/compare/2020.0.21...2020.0.22
2022-08-11 08:21:06 +02:00
Stephan Schroevers
624f2ce753 [maven-release-plugin] prepare for next development iteration 2022-08-10 15:06:32 +02:00
Stephan Schroevers
967017eed9 [maven-release-plugin] prepare release v0.1.0 2022-08-10 15:06:30 +02:00
Rick Ossendrijver
b06945b833 Introduce utilities to validate Refaster template collections (#43)
The `Refaster` check is now located in the new `refaster-runner` Maven module.

The new `refaster-test-support` module exposes
`RefasterTemplateCollection#validate`, which for a given template collection
validates:
- That there exist corresponding `*Test{Input,Output}.java` files.
- That each template is exercised by precisely one method in these files.
2022-08-10 14:40:07 +02:00
Rick Ossendrijver
ef562c1644 Rewrite more ThrowableAssertAlternative#withMessage(String, Object...) expressions (#185) 2022-08-10 14:32:44 +02:00
Rick Ossendrijver
efbde936dc Only suggest bulk removal operations on sets (#186)
If a collection may contain duplicates, then removing a single occurrence of
each element in some other set is not equivalent to removing all such
occurrences.
2022-08-10 14:09:36 +02:00
Stephan Schroevers
c57653dd5b Introduce run-mutation-tests.sh (#170)
This script executes Pitest to determine the code base' mutation test coverage.
The set of tests executed can optionally be restricted by name. The results are 
found in each Maven module's `target/pit-reports` directory.
2022-08-09 14:38:19 +02:00
Stephan Schroevers
12b03e95b1 Manage version of org.apache.maven:maven-plugin-api (#183)
By managing the version of this dependency we expect Renovate to file a pull
request any time a new Maven version is released. Through a shared property,
this also enforces that the project is built using the latest Maven release.
2022-08-08 13:57:51 +02:00
Stephan Schroevers
c2f24ac739 Speed up the build (#169)
The build is sped up in two ways:
1. By tweaking the JVM flags passed to the main process.
2. By tweaking the JVM flags passed to the forked Surefire processes.
2022-08-08 13:41:27 +02:00
Rick Ossendrijver
4f5ea8beac Migrate from Travis CI to GitHub Actions (#158)
While there, drop the now-obsolete Takari Maven plugin.
2022-08-07 18:33:25 +02:00
Stephan Schroevers
21646ffcb1 Enable the BugPatternNaming check (#86)
While there, introduce a `.util` subpackage for non-`Bugchecker` classes.
2022-08-07 18:12:10 +02:00
Picnic-Bot
c58dceb9df Upgrade errorprone-slf4j 0.1.12 -> 0.1.13 (#53)
See:
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.13
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.12...v0.1.13
2022-08-07 14:21:02 +02:00
Picnic-Bot
90ef2f4042 Upgrade pitest-maven-plugin 1.9.3 -> 1.9.4 (#178)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.4
- https://github.com/hcoles/pitest/compare/1.9.3...1.9.4
2022-08-06 10:17:26 +02:00
Picnic-Bot
459a498d6c Upgrade maven-site-plugin 3.12.0 -> 3.12.1 (#177)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MSITE%20AND%20fixVersion%20%3E%203.12.0%20AND%20fixVersion%20%3C%3D%203.12.1%20AND%20statusCategory%20%3D%20Done%20
- https://github.com/apache/maven-site-plugin/compare/maven-site-plugin-3.12.0...maven-site-plugin-3.12.1
2022-08-06 09:39:38 +02:00
Picnic-Bot
78035644dc Upgrade NullAway 0.9.8 -> 0.9.9 (#175)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.8...v0.9.9
2022-08-05 09:10:49 +02:00
Picnic-Bot
ef67d41512 Upgrade pitest-maven-plugin 1.9.2 -> 1.9.3 (#159)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.3
- https://github.com/hcoles/pitest/compare/1.9.2...1.9.3
2022-08-04 16:53:54 +02:00
Picnic-Bot
4cecff923a Upgrade Checker Framework Annotations 3.23.0 -> 3.24.0 (#174)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.24.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.23.0...checker-framework-3.24.0
2022-08-04 08:10:10 +02:00
Stephan Schroevers
38a57db994 Introduce ErrorProneTestHelperSourceFormat check (#147)
This new checker inspects inline code passed to `CompilationTestHelper` and
`BugCheckerRefactoringTestHelper` instances. It requires that this code is
properly formatted and that its imports are organized. Only code that
represents the expected output of a refactoring operation is allowed to have
unused imports, as most `BugChecker`s do not (and are not able to) remove
imports that become obsolete as a result of applying their suggested fix(es).
2022-08-03 21:47:31 +02:00
Stephan Schroevers
336557cf8e Introduce apply-error-prone-suggestions.sh (#171)
This script compiles the code using Error Prone and applies its suggestions. 
The set of checks applied can optionally be restricted by name.
2022-08-03 17:05:38 +02:00
Picnic-Bot
9055dfff19 Upgrade Checkstyle 10.3.1 -> 10.3.2 (#173)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.3.2
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.3.1...checkstyle-10.3.2
2022-08-02 12:26:40 +02:00
Rick Ossendrijver
3712a15195 Implement workaround for MCOMPILER-503 (#149)
By moving around some annotation processor classpath entries we ensure that the
`maven-compiler-plugin` uses the appropriate version of Error Prone.

See https://issues.apache.org/jira/browse/MCOMPILER-503
2022-08-02 09:36:46 +02:00
Picnic-Bot
9d487e4a88 Upgrade New Relic Java Agent 7.8.0 -> 7.9.0 (#168)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.9.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.8.0...v7.9.0
2022-08-01 17:35:58 +02:00
Picnic-Bot
b2b086761c Upgrade JUnit Jupiter 5.8.2 -> 5.9.0 (#167)
See:
- https://junit.org/junit5/docs/current/release-notes/index.html
- https://github.com/junit-team/junit5/releases/tag/r5.9.0
- https://github.com/junit-team/junit5/compare/r5.8.2...r5.9.0
2022-08-01 17:27:08 +02:00
Picnic-Bot
ff64247b6d Upgrade maven-resources-plugin 3.2.0 -> 3.3.0 (#166)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MRESOURCES%20AND%20fixVersion%20%3E%203.2.0%20AND%20fixVersion%20%3C%3D%203.3.0
- https://github.com/apache/maven-resources-plugin/compare/maven-resources-plugin-3.2.0...maven-resources-plugin-3.3.0
2022-08-01 17:15:19 +02:00
Picnic-Bot
bc7443c72d Upgrade maven-install-plugin 3.0.0 -> 3.0.1 (#164)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MINSTALL%20AND%20fixVersion%20%3E%20%203.0.0%20AND%20fixVersion%20%3C%3D%203.0.1
- https://github.com/apache/maven-install-plugin/compare/maven-install-plugin-3.0.0...maven-install-plugin-3.0.1
2022-08-01 16:21:54 +02:00
Picnic-Bot
abf4d68fba Upgrade extra-enforcer-rules 1.6.0 -> 1.6.1 (#165)
See:
- https://github.com/mojohaus/extra-enforcer-rules/releases/tag/extra-enforcer-rules-1.6.1
- https://github.com/mojohaus/extra-enforcer-rules/compare/extra-enforcer-rules-1.6.0...extra-enforcer-rules-1.6.1
2022-08-01 16:20:24 +02:00
Picnic-Bot
5c5f7d849e Upgrade Guava 31.0.1-jre -> 31.1-jre (#77)
See:
- https://guava.dev/releases/31.1-jre/api/diffs/
- https://github.com/google/guava/releases/tag/v31.1
- https://github.com/google/guava/compare/v31.0.1...v31.1
2022-08-01 14:48:56 +02:00
Picnic-Bot
65c4694936 Upgrade Error Prone 2.10.0 -> 2.14.0 (#76)
This also requires the upgrade of errorprone-slf4j 0.1.4 -> 0.1.12.

See:
- https://github.com/google/error-prone/releases/tag/v2.11.0
- https://github.com/google/error-prone/releases/tag/v2.12.0
- https://github.com/google/error-prone/releases/tag/v2.12.1
- https://github.com/google/error-prone/releases/tag/v2.13.0
- https://github.com/google/error-prone/releases/tag/v2.13.1
- https://github.com/google/error-prone/releases/tag/v2.14.0
- https://github.com/google/error-prone/compare/v2.10.0...v2.14.0
- https://github.com/PicnicSupermarket/error-prone/compare/v2.10.0-picnic-3...v2.14.0-picnic-2
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.5
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.6
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.7
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.8
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.9
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.10
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.11
- https://github.com/KengoTODA/errorprone-slf4j/releases/tag/v0.1.12
- https://github.com/KengoTODA/errorprone-slf4j/compare/v0.1.4...v0.1.12
2022-07-31 15:50:16 +02:00
Picnic-Bot
a45291c7d8 Upgrade Spring Boot 2.7.1 -> 2.7.2 (#163)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.2
- https://github.com/spring-projects/spring-boot/compare/v2.7.1...v2.7.2
2022-07-30 15:11:37 +02:00
Picnic-Bot
71012f31ab Upgrade swagger-annotations 2.2.1 -> 2.2.2 (#162)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.2
- https://github.com/swagger-api/swagger-core/compare/v2.2.1...v2.2.2
2022-07-30 14:43:54 +02:00
Picnic-Bot
6e0905c033 Upgrade maven-install-plugin 2.5.2 -> 3.0.0 (#161)
See: 
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MINSTALL%20AND%20fixVersion%20%3E%20%202.5.2%20AND%20fixVersion%20%3C%3D%203.0.0
- https://github.com/apache/maven-install-plugin/compare/maven-install-plugin-2.5.2...maven-install-plugin-3.0.0
2022-07-21 09:01:43 +02:00
Picnic-Bot
af5ac85428 Upgrade maven-deploy-plugin 2.8.2 -> 3.0.0 (#160)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEPLOY%20AND%20fixVersion%20%3E%202.8.2%20AND%20fixVersion%20%3C%3D%203.0.0
- https://github.com/apache/maven-deploy-plugin/compare/maven-deploy-plugin-2.8.2...maven-deploy-plugin-3.0.0
2022-07-21 08:49:42 +02:00
Picnic-Bot
0329c25f78 Upgrade sortpom-maven-plugin 3.1.3 -> 3.2.0 (#157)
See:
- https://github.com/Ekryd/sortpom/wiki/Versions
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.2.0
- https://github.com/Ekryd/sortpom/compare/sortpom-parent-3.1.3...sortpom-parent-3.2.0
2022-07-21 08:04:22 +02:00
Picnic-Bot
9e67e2b795 Upgrade Spring 5.3.21 -> 5.3.22 (#155)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.22
- https://github.com/spring-projects/spring-framework/compare/v5.3.21...v5.3.22
2022-07-15 14:52:27 +02:00
Picnic-Bot
4bafea05f4 Upgrade Project Reactor 2020.0.20 -> 2020.0.21 (#154)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.21
- https://github.com/reactor/reactor/compare/2020.0.20...2020.0.21
2022-07-15 08:46:21 +02:00
Picnic-Bot
8ce9cab2dd Upgrade Checker Framework Annotations 3.22.2 -> 3.23.0 (#153)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.23.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.22.2...checker-framework-3.23.0
2022-07-13 07:34:25 +02:00
Pieter Dirk Soels
ae30625524 Clarify MapToNullable Refaster template (#150) 2022-07-12 12:54:22 +02:00
Picnic-Bot
dc0046ebfc Upgrade extra-enforcer-rules 1.5.1 -> 1.6.0 (#152)
See:
- https://github.com/mojohaus/extra-enforcer-rules/releases/tag/extra-enforcer-rules-1.6.0
- https://github.com/mojohaus/extra-enforcer-rules/compare/extra-enforcer-rules-1.5.1...extra-enforcer-rules-1.6.0
2022-07-12 11:41:23 +02:00
Picnic-Bot
ad6d774818 Upgrade pitest-maven-plugin 1.9.0 -> 1.9.2 (#151)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.1
- https://github.com/hcoles/pitest/releases/tag/1.9.2
- https://github.com/hcoles/pitest/compare/1.9.0...1.9.2
2022-07-12 11:11:30 +02:00
Stephan Schroevers
405f5874ac Apply Checkstyle to Refaster test resources (#146)
Similar to formatting the `*TemplatesTest{In,Out}put.java` files to enforce
certain style aspects, this is expected to reduce future code review effort.

The test code changes were applied to appease the
`SimplifyBooleanExpression` check.
2022-07-06 13:39:59 +02:00
Stephan Schroevers
bf5199ea3d Fix build-time Refaster template loading (#121)
When using the system classloader, `RefasterCheckTest` is able to
successfully load the Refaster templates from the classpath, causing the
tests to pass. However, when during a build the Java compiler loads
`RefasterCheck`, the templates on the annotation processor classpath are
_not_ exposed through the system classloader.
2022-06-30 13:30:03 +02:00
Gijs de Jong
c500516bb4 Prefer AssertJ's isNull() assertion over isEqualTo(null) (#133) 2022-06-29 18:55:22 +02:00
Picnic-Bot
85d68a4f34 Upgrade Spring Boot 2.5.14 -> 2.7.1 (#81)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.0-M1
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.0-M2
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.0-M3
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.0-RC1
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.0
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.1
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.2
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.3
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.4
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.5
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.6
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.7
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.8
- https://github.com/spring-projects/spring-boot/releases/tag/v2.6.9
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.0-M1
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.0-M2
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.0-M3
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.0-RC1
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.0
- https://github.com/spring-projects/spring-boot/releases/tag/v2.7.1
- https://github.com/spring-projects/spring-boot/compare/v2.5.14...v2.7.1
2022-06-29 10:33:15 +02:00
Rick Ossendrijver
46467951dd Have Checkstyle disallow blank lines at the start of blocks (#141) 2022-06-28 14:11:55 +02:00
Picnic-Bot
6f7ce2067f Upgrade Checkstyle 10.3 -> 10.3.1 (#148)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.3.1
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.3...checkstyle-10.3.1
2022-06-28 12:58:32 +02:00
Gijs de Jong
f30ba36d18 Prefer {Mono,Flux}#cast over {Mono,Flux}#map performing a cast (#127) 2022-06-28 08:51:26 +02:00
Picnic-Bot
65736ce83f Upgrade NullAway 0.9.7 -> 0.9.8 (#145)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.7...v0.9.8
2022-06-27 08:19:39 +02:00
Rick Ossendrijver
17d5805d5a Drop public modifier from BugPattern test classes (#136) 2022-06-26 11:20:07 +02:00
Picnic-Bot
ce01b62832 Upgrade pitest-maven-plugin 1.8.1 -> 1.9.0 and pitest-junit5-plugin 0.16 -> 1.0.0 (#143)
See:
- https://github.com/hcoles/pitest/releases/tag/1.9.0
- https://github.com/hcoles/pitest/compare/1.8.1...1.9.0
- https://github.com/pitest/pitest-junit5-plugin/compare/0.16...1.0.0
2022-06-24 14:51:13 +02:00
Picnic-Bot
4ee555c62b Upgrade maven-enforcer-plugin 3.0.0 -> 3.1.0 (#126)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MENFORCER%20AND%20fixVersion%20%3E%203.0.0%20AND%20fixVersion%20%3C%3D%203.1.0%20
- https://github.com/apache/maven-enforcer/compare/enforcer-3.0.0...enforcer-3.1.0
2022-06-21 13:23:32 +02:00
Gijs de Jong
a24bbbe99d Rewrite Web{,Test}Client HTTP method specification expressions (#129) 2022-06-21 07:37:04 +02:00
Gijs de Jong
679e83bc48 Replace unnecessary UriBuilder arguments passed to Web(Test)Client#uri (#128) 2022-06-20 22:37:49 +02:00
Gijs de Jong
0bdc171613 Introduce CollectorMutability check (#135)
This check flags `Collectors.to{List,Map,Set}` usages, suggesting that they be
replaced with expressions that clearly indicate the (im)mutability of the 
resultant collection.

Refaster templates that violated the new check are simplified by removing the
relevant expressions; they were too contrived to be updated some other way.
2022-06-20 11:08:06 +02:00
Picnic-Bot
9b05ec62c6 Upgrade Spring Boot 2.5.6 -> 2.5.14 (#134)
See:
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.7
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.8
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.9
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.10
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.11
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.12
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.13
- https://github.com/spring-projects/spring-boot/releases/tag/v2.5.14
- https://github.com/spring-projects/spring-boot/compare/v2.5.6...v2.5.14
2022-06-20 09:52:31 +02:00
Picnic-Bot
72866183f5 Upgrade Spring 5.3.20 -> 5.3.21 (#139)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.21
- https://github.com/spring-projects/spring-framework/compare/v5.3.20...v5.3.21
2022-06-20 09:08:43 +02:00
Picnic-Bot
9d7f569be5 Upgrade swagger-annotations 2.2.0 -> 2.2.1 (#137)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.1
- https://github.com/swagger-api/swagger-core/compare/v2.2.0...v2.2.1
2022-06-19 17:59:34 +02:00
Picnic-Bot
f72adca292 Upgrade New Relic Java Agent 7.7.0 -> 7.8.0 (#140)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.8.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.7.0...v7.8.0
2022-06-19 15:35:04 +02:00
Picnic-Bot
5148143ae5 Upgrade Project Reactor 2020.0.19 -> 2020.0.20 (#130)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.20
- https://github.com/reactor/reactor/compare/2020.0.19...2020.0.20
2022-06-19 15:07:38 +02:00
Picnic-Bot
3d7fbbf7a2 Upgrade pitest-maven-plugin 1.8.0 -> 1.8.1 (#138)
See:
- https://github.com/hcoles/pitest/releases/tag/1.8.1
- https://github.com/hcoles/pitest/compare/1.8.0...1.8.1
2022-06-19 14:57:43 +02:00
Picnic-Bot
8b6864d8a0 Upgrade baseline-error-prone 4.42.0 -> 4.145.0 (#58)
See:
- https://github.com/palantir/gradle-baseline/releases/tag/4.47.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.48.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.49.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.50.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.51.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.52.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.53.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.54.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.55.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.56.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.57.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.58.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.59.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.60.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.61.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.62.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.63.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.64.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.65.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.66.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.67.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.68.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.69.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.70.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.71.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.72.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.73.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.74.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.75.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.76.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.77.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.78.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.79.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.80.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.81.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.82.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.83.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.84.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.85.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.86.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.87.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.88.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.89.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.90.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.91.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.92.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.93.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.94.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.95.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.96.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.97.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.98.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.99.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.100.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.101.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.102.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.103.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.104.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.105.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.106.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.107.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.108.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.109.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.110.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.111.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.112.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.113.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.114.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.115.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.116.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.117.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.118.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.119.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.120.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.121.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.122.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.123.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.124.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.125.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.126.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.127.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.128.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.129.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.130.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.131.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.132.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.133.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.134.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.135.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.136.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.137.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.138.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.139.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.140.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.141.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.142.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.143.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.144.0
- https://github.com/palantir/gradle-baseline/releases/tag/4.145.0
- https://github.com/palantir/gradle-baseline/compare/4.46.0...4.145.0
2022-06-19 14:40:46 +02:00
Picnic-Bot
a03017b5e6 Upgrade Checker Framework Annotations 3.22.1 -> 3.22.2 (#131)
See https://github.com/typetools/checker-framework/compare/checker-framework-3.22.1...checker-framework-3.22.2
2022-06-16 22:23:05 +02:00
Rick Ossendrijver
a227436f19 Introduce .renovaterc.json (#125) 2022-06-15 16:46:12 +02:00
Picnic-Bot
3f6558b7c0 Upgrade fmt-maven-plugin 2.18 -> 2.19 (#132)
See:
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.19.0
- https://github.com/spotify/fmt-maven-plugin/compare/2.18.0...2.19.0
2022-06-15 08:43:35 +02:00
Picnic-Bot
ce06396521 Upgrade pitest-junit5-plugin 0.15 -> 0.16 (#124)
See https://github.com/pitest/pitest-junit5-plugin/compare/0.15...0.16
2022-06-11 14:39:01 +02:00
Rick Ossendrijver
268766a32a Fix copy-paste error in ReactorTemplates Javadoc (#123) 2022-06-09 09:08:36 +02:00
Rick Ossendrijver
5366effd74 Upgrade Error Prone fork v2.10.0-picnic-1 -> v2.10.0-picnic-3 (#120)
See:
- https://github.com/PicnicSupermarket/error-prone/releases/tag/v2.10.0-picnic-2
- https://github.com/PicnicSupermarket/error-prone/releases/tag/v2.10.0-picnic-3
- https://github.com/PicnicSupermarket/error-prone/compare/v2.10.0-picnic-1...v2.10.0-picnic-3
2022-06-08 12:55:40 +02:00
Picnic-Bot
0a63361500 Upgrade Truth 1.0.1 -> 1.1.3 (#78)
See:
- https://github.com/google/truth/releases/tag/release_1_1
- https://github.com/google/truth/releases/tag/release_1_1_1
- https://github.com/google/truth/releases/tag/release_1_1_2
- https://github.com/google/truth/releases/tag/release_1_1_3
- https://github.com/google/truth/compare/release_1_0_1...release_1_1_3
2022-06-05 20:52:45 +02:00
Picnic-Bot
a074e2fdd6 Upgrade Checker Framework Annotations 3.22.0 -> 3.22.1 (#117)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.22.1
- https://github.com/typetools/checker-framework/compare/checker-framework-3.22.0...checker-framework-3.22.1
2022-06-03 14:59:14 +02:00
Picnic-Bot
f06d4e41cf Upgrade Mockito 4.6.0 -> 4.6.1 (#118)
See:
- https://github.com/mockito/mockito/releases/tag/v4.6.1
- https://github.com/mockito/mockito/compare/v4.6.0...v4.6.1
2022-06-03 09:20:27 +02:00
Rick Ossendrijver
cf7bb657fa Enable Checkstyle's LocalVariableName check (#111) 2022-06-01 16:53:07 +02:00
Rick Ossendrijver
8277b43955 Move Refaster template test resources to proper package (#113) 2022-06-01 14:55:29 +02:00
Picnic-Bot
691f2c8311 Upgrade AssertJ Core 3.22.0 -> 3.23.1 (#116)
See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://github.com/joel-costigliola/assertj-core/compare/assertj-core-3.22.0...assertj-core-3.23.1
2022-06-01 13:09:17 +02:00
Rick Ossendrijver
362518b0f4 Resolve Refaster template naming and test inconsistencies (#109) 2022-05-31 13:54:17 +02:00
Picnic-Bot
b9a3840e25 Upgrade Checkstyle 10.2 -> 10.3 (#115)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.3
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.2...checkstyle-10.3
2022-05-31 10:40:39 +02:00
Picnic-Bot
14d8bddbec Upgrade sortpom-maven-plugin 3.0.1 -> 3.1.3 (#112)
See:
- https://github.com/Ekryd/sortpom/wiki/Versions
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.1.0
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.1.1
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.1.2
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.1.3
- https://github.com/Ekryd/sortpom/compare/sortpom-parent-3.0.1...sortpom-parent-3.1.3
2022-05-31 09:51:13 +02:00
Picnic-Bot
6c7a0b81ea Upgrade Mockito 4.5.1 -> 4.6.0 (#114)
See:
- https://github.com/mockito/mockito/releases/tag/v4.6.0
- https://github.com/mockito/mockito/compare/v4.5.1...v4.6.0
2022-05-31 09:35:59 +02:00
David Mischke
3a3825f7ba Simplify unnecessary String.format(...) expressions passed to AssertJ (#101) 2022-05-26 14:24:23 +02:00
Stephan Schroevers
31e54cc990 Enforce test resources code formatting (#105)
This change should have been part of #75.
2022-05-26 13:56:19 +02:00
Pim Tegelaar
775a2688ca Introduce AssertJThrowingCallableTemplates (#92) 2022-05-26 13:29:35 +02:00
Rick Ossendrijver
3d854a0cc5 Rename RefasterRuleResourceCompiler to RefasterRuleCompiler (#110)
The associated Maven module is renamed from `refaster-resource-compiler` to
just `refaster-compiler`.
2022-05-26 13:21:28 +02:00
Stephan Schroevers
6ee013da58 Drop unnecessary dependency declarations (#106) 2022-05-26 10:51:47 +02:00
David Mischke
962d18dcb5 Drop unnecessary AssertJ usage in StepVerifier expression (#103) 2022-05-23 22:55:09 +02:00
Picnic-Bot
aab308a190 Upgrade pitest-maven-plugin 1.7.6 -> 1.8.0 (#108)
See:
- https://github.com/hcoles/pitest/releases/tag/1.8.0
- https://github.com/hcoles/pitest/compare/1.7.6...1.8.0
2022-05-23 09:21:53 +02:00
Picnic-Bot
009bd5d0d7 Upgrade versions-maven-plugin 2.10.0 -> 2.11.0 (#107)
See:
- https://github.com/mojohaus/versions-maven-plugin/releases/tag/versions-maven-plugin-2.11.0
- https://github.com/mojohaus/versions-maven-plugin/compare/versions-maven-plugin-2.10.0...versions-maven-plugin-2.11.0
2022-05-23 08:45:15 +02:00
Pim Tegelaar
8e57f64e31 Prevent JUnitMethodDeclarationCheck from renaming likely-overridden methods (#93) 2022-05-17 18:15:31 +02:00
Picnic-Bot
53e81f3611 Upgrade Jackson 2.13.2.20220328 -> 2.13.3 (#100)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.13.3
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.13.2.20220328...jackson-bom-2.13.3
2022-05-17 11:41:56 +02:00
Picnic-Bot
8745105251 Upgrade Spring 5.3.19 -> 5.3.20 (#99)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.20
- https://github.com/spring-projects/spring-framework/compare/v5.3.19...v5.3.20
2022-05-17 11:24:18 +02:00
Picnic-Bot
3eb3c20b1d Upgrade Project Reactor 2020.0.18 -> 2020.0.19 (#98)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.19
- https://github.com/reactor/reactor/compare/2020.0.18...2020.0.19
2022-05-17 10:26:33 +02:00
Picnic-Bot
121618f277 Upgrade NullAway 0.9.6 -> 0.9.7 (#97)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.6...v0.9.7
2022-05-17 10:09:59 +02:00
Picnic-Bot
5cf4194168 Upgrade pitest-maven-plugin 1.7.5 -> 1.7.6 (#94)
See:
- https://github.com/hcoles/pitest/releases/tag/1.7.6
- https://github.com/hcoles/pitest/compare/1.7.5...1.7.6
2022-05-10 09:28:27 +02:00
Picnic-Bot
c434cd318c Upgrade New Relic Java Agent 7.6.0 -> 7.7.0
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.7.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.6.0...v7.7.0
2022-05-10 09:02:30 +02:00
Picnic-Bot
22aa9cb213 Upgrade Checker Framework Annotations 3.21.4 -> 3.22.0
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.22.0
- https://github.com/typetools/checker-framework/compare/checker-framework-3.21.4...checker-framework-3.22.0
2022-05-10 07:36:16 +02:00
Rick Ossendrijver
3edc483e7c Extend set of parameter types recognized by RequestMappingAnnotationCheck (#91)
While there, restrict the supported set of `WebRequest` subtypes to just
`WebRequest` and `NativeWebRequest`.
2022-04-29 14:15:51 +02:00
Stephan Schroevers
fff5d7b329 Apply assorted Maven parent improvements (#85) 2022-04-29 13:35:14 +02:00
Picnic-Bot
4ca80952ab Upgrade modernizer-maven-plugin 2.3.0 -> 2.4.0 (#90)
See:
- https://github.com/gaul/modernizer-maven-plugin/releases/tag/modernizer-maven-plugin-2.4.0
- https://github.com/gaul/modernizer-maven-plugin/compare/modernizer-maven-plugin-2.3.0...modernizer-maven-plugin-2.4.0
2022-04-26 12:52:11 +02:00
Picnic-Bot
8cecb8bf30 Upgrade Spring 5.3.13 -> 5.3.19 (#74)
See:
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.14
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.15
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.16
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.17
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.18
- https://github.com/spring-projects/spring-framework/releases/tag/v5.3.19
- https://github.com/spring-projects/spring-framework/compare/v5.3.13...v5.3.19
2022-04-26 12:38:23 +02:00
Picnic-Bot
a937bf0ddf Upgrade Checker Framework Annotations 3.19.0 -> 3.21.4 (#87)
See:
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.20.0
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.21.0
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.21.1
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.21.2
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.21.3
- https://github.com/typetools/checker-framework/releases/tag/checker-framework-3.21.4
- https://github.com/typetools/checker-framework/compare/checker-framework-3.19.0...checker-framework-3.21.4
2022-04-26 12:31:02 +02:00
Picnic-Bot
0b71c2b576 Upgrade versions-maven-plugin 2.8.1 -> 2.10.0 (#89)
See:
- https://github.com/mojohaus/versions-maven-plugin/releases/tag/versions-maven-plugin-2.9.0
- https://github.com/mojohaus/versions-maven-plugin/releases/tag/versions-maven-plugin-2.10.0
- https://github.com/mojohaus/versions-maven-plugin/compare/versions-maven-plugin-2.8.1...versions-maven-plugin-2.10.0
2022-04-26 11:35:51 +02:00
Picnic-Bot
239d38d69f Upgrade extra-enforcer-rules 1.4 -> 1.5.1 (#88)
See:
- https://github.com/mojohaus/extra-enforcer-rules/releases/tag/extra-enforcer-rules-1.5.0
- https://github.com/mojohaus/extra-enforcer-rules/releases/tag/extra-enforcer-rules-1.5.1
- https://github.com/mojohaus/extra-enforcer-rules/compare/extra-enforcer-rules-1.4...extra-enforcer-rules-1.5.1
2022-04-26 11:09:17 +02:00
Picnic-Bot
ab57aa5eb6 Upgrade pitest-maven-plugin 1.7.3 -> 1.7.5 (#72)
See:
- https://github.com/hcoles/pitest/releases/tag/1.7.4
- https://github.com/hcoles/pitest/releases/tag/1.7.5
- https://github.com/hcoles/pitest/compare/1.7.3...1.7.5
2022-04-25 22:46:44 +02:00
Picnic-Bot
49267337cb Upgrade JUnit Jupiter 5.8.1 -> 5.8.2 (#71)
See:
- https://junit.org/junit5/docs/current/release-notes/index.html
- https://github.com/junit-team/junit5/releases/tag/r5.8.2
- https://github.com/junit-team/junit5/compare/r5.8.1...r5.8.2
2022-04-25 13:56:02 +02:00
Picnic-Bot
c201fe1fd2 Upgrade SLF4J API 1.7.32 -> 1.7.36 (#73)
See:
- https://www.slf4j.org/news.html
- https://github.com/qos-ch/slf4j/compare/v_1.7.32...v_1.7.36
2022-04-25 13:48:50 +02:00
Picnic-Bot
fb20b6f93d Upgrade AutoValue 1.8.2 -> 1.9 (#83)
See:
- https://github.com/google/auto/releases/tag/auto-value-1.9
- https://github.com/google/auto/compare/auto-value-1.8.2...auto-value-1.9
2022-04-25 13:36:41 +02:00
Picnic-Bot
9264c25b57 Upgrade fmt-maven-plugin 2.12 -> 2.18 (#75)
This also upgrades Google Java Format 1.11.0 -> 1.15.0, improving support for 
Java 17 syntax, among other things.

See:
- https://github.com/google/google-java-format/releases/tag/v1.12.0
- https://github.com/google/google-java-format/releases/tag/v1.13.0
- https://github.com/google/google-java-format/releases/tag/v1.14.0
- https://github.com/google/google-java-format/releases/tag/v1.15.0
- https://github.com/google/google-java-format/compare/v1.11.0...v1.15.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.13.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.14.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.15.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.16.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.17.0
- https://github.com/spotify/fmt-maven-plugin/releases/tag/2.18.0
- https://github.com/spotify/fmt-maven-plugin/compare/2.12.0...2.18.0
2022-04-25 13:29:19 +02:00
Picnic-Bot
ca628eef6c Upgrade New Relic Java Agent 7.4.3 -> 7.6.0 (#79)
See:
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.5.0
- https://github.com/newrelic/newrelic-java-agent/releases/tag/v7.6.0
- https://github.com/newrelic/newrelic-java-agent/compare/v7.4.3...v7.6.0
2022-04-25 09:27:25 +02:00
Picnic-Bot
62168dcd4b Upgrade Checkstyle 10.1 -> 10.2 (#80)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.2
- https://github.com/checkstyle/checkstyle/compare/checkstyle-10.1...checkstyle-10.2
2022-04-25 09:17:24 +02:00
Picnic-Bot
96a82eaf85 Upgrade Mockito 4.0.0 -> 4.5.1 (#84)
See:
- https://github.com/mockito/mockito/releases/tag/v4.1.0
- https://github.com/mockito/mockito/releases/tag/v4.2.0
- https://github.com/mockito/mockito/releases/tag/v4.3.0
- https://github.com/mockito/mockito/releases/tag/v4.3.1
- https://github.com/mockito/mockito/releases/tag/v4.4.0
- https://github.com/mockito/mockito/releases/tag/v4.5.0
- https://github.com/mockito/mockito/releases/tag/v4.5.1
- https://github.com/mockito/mockito/compare/v4.0.0...v4.5.1
2022-04-25 09:06:44 +02:00
Picnic-Bot
0c615b4c15 Upgrade Project Reactor 2020.0.13 -> 2020.0.18 (#51)
See:
- https://github.com/reactor/reactor/releases/tag/2020.0.14
- https://github.com/reactor/reactor/releases/tag/2020.0.15
- https://github.com/reactor/reactor/releases/tag/2020.0.16
- https://github.com/reactor/reactor/releases/tag/2020.0.17
- https://github.com/reactor/reactor/releases/tag/2020.0.18
- https://github.com/reactor/reactor/compare/2020.0.13...2020.0.18
2022-04-24 17:05:53 +02:00
Picnic-Bot
6304130ae3 Upgrade swagger-annotations 1.6.3 -> 1.6.6 (#52)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.4
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.5
- https://github.com/swagger-api/swagger-core/releases/tag/v1.6.6
- https://github.com/swagger-api/swagger-core/compare/v1.6.3...v1.6.6
2022-04-24 16:57:18 +02:00
Picnic-Bot
1674e99ba4 Upgrade maven-jar-plugin 3.2.0 -> 3.2.2 (#54)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MJAR%20AND%20fixVersion%20%3E%203.2.0%20AND%20fixVersion%20%3C%3D%203.2.2
- https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.2.0...maven-jar-plugin-3.2.2
2022-04-24 16:49:47 +02:00
Picnic-Bot
75bbc8e5b5 Upgrade AspectJ 1.9.7 -> 1.9.9.1 (#55)
See:
- https://github.com/eclipse/org.aspectj/releases/tag/V1_9_8
- https://github.com/eclipse/org.aspectj/releases/tag/V1_9_9
- https://github.com/eclipse/org.aspectj/releases/tag/V1_9_9_1
- https://github.com/eclipse/org.aspectj/compare/V1_9_7...V1_9_9_1
2022-04-24 16:27:16 +02:00
Picnic-Bot
fe3ed2be63 Upgrade jacoco-maven-plugin 0.8.7 -> 0.8.8 (#56)
See:
- https://github.com/jacoco/jacoco/releases/tag/v0.8.8
- https://github.com/jacoco/jacoco/compare/v0.8.7...v0.8.8
2022-04-24 16:20:18 +02:00
Picnic-Bot
f36350f3ba Upgrade Forbidden APIs plugin 3.2 -> 3.3 (#59)
See https://github.com/policeman-tools/forbidden-apis/compare/3.2...3.3
2022-04-24 16:12:47 +02:00
Picnic-Bot
4888ad3aaf Upgrade swagger-annotations 2.1.11 -> 2.2.0 (#60)
See:
- https://github.com/swagger-api/swagger-core/releases/tag/v2.1.12
- https://github.com/swagger-api/swagger-core/releases/tag/v2.1.13
- https://github.com/swagger-api/swagger-core/releases/tag/v2.2.0
- https://github.com/swagger-api/swagger-core/compare/v2.1.11...v2.2.0
2022-04-24 16:04:48 +02:00
Picnic-Bot
9daf73f148 Upgrade maven-clean-plugin 3.1.0 -> 3.2.0 (#61)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MCLEAN%20AND%20fixVersion%20%3E%203.1.0%20AND%20fixVersion%20%3C%3D%203.2.0
- https://github.com/apache/maven-clean-plugin/compare/maven-clean-plugin-3.1.0...maven-clean-plugin-3.2.0
2022-04-24 15:55:59 +02:00
Picnic-Bot
b08ca514c1 Upgrade maven-compiler-plugin 3.8.1 -> 3.10.1 (#62)
And drop the redundant `--source` and `--target` flags.

See:
- https://github.com/apache/maven-compiler-plugin/releases/tag/maven-compiler-plugin-3.9.0
- https://github.com/apache/maven-compiler-plugin/releases/tag/maven-compiler-plugin-3.10.0
- https://github.com/apache/maven-compiler-plugin/releases/tag/maven-compiler-plugin-3.10.1
- https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.1...maven-compiler-plugin-3.10.1
2022-04-24 15:48:25 +02:00
Picnic-Bot
4eed7dd0e8 Upgrade maven-dependency-plugin 3.1.2 -> 3.3.0 (#63)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MDEP%20AND%20fixVersion%20%3E%203.1.2%20AND%20fixVersion%20%3C%3D%203.3.0
- https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.1.2...maven-dependency-plugin-3.3.0
2022-04-24 15:37:56 +02:00
Picnic-Bot
618c62e7a5 Upgrade maven-javadoc-plugin 3.3.1 -> 3.4.0 (#64)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MJAVADOC%20AND%20fixVersion%20%3E%203.3.1%20AND%20fixVersion%20%3C%3D%203.4.0
- https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.3.1...maven-javadoc-plugin-3.4.0
2022-04-24 15:30:33 +02:00
Picnic-Bot
b46f075ddf Upgrade maven-site-plugin 3.9.1 -> 3.12.0 (#65)
See:
- https://issues.apache.org/jira/issues/?jql=project%20%3D%20MSITE%20AND%20fixVersion%20%3E%203.9.1%20AND%20fixVersion%20%3C%3D%203.12.0
- https://github.com/apache/maven-site-plugin/compare/maven-site-plugin-3.9.1...maven-site-plugin-3.12.0
2022-04-24 15:12:26 +02:00
Picnic-Bot
64436ff9b6 Upgrade AssertJ Core 3.21.0 -> 3.22.0 (#66)
See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://github.com/joel-costigliola/assertj-core/compare/assertj-core-3.21.0...assertj-core-3.22.0
2022-04-24 15:03:13 +02:00
Picnic-Bot
e028077f1e Upgrade Checkstyle 9.1 -> 10.1 (#67)
See:
- https://checkstyle.sourceforge.io/releasenotes.html
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-9.2
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-9.2.1
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-9.3
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.0
- https://github.com/checkstyle/checkstyle/releases/tag/checkstyle-10.1
- https://github.com/checkstyle/checkstyle/compare/checkstyle-9.1...checkstyle-10.1
2022-04-24 14:51:37 +02:00
Picnic-Bot
5aa386b5ba Upgrade buildnumber-maven-plugin 1.4 -> 3.0.0 (#69)
See:
- https://github.com/mojohaus/buildnumber-maven-plugin/releases/tag/buildnumber-maven-plugin-3.0.0
- https://github.com/mojohaus/buildnumber-maven-plugin/compare/buildnumber-maven-plugin-1.4...buildnumber-maven-plugin-3.0.0
2022-04-24 14:44:35 +02:00
Picnic-Bot
a480fe908d Upgrade Palantir assertj-error-prone 0.3.0 -> 0.6.0 (#57)
See:
- https://github.com/palantir/assertj-automation/releases/tag/0.4.0
- https://github.com/palantir/assertj-automation/releases/tag/0.5.0
- https://github.com/palantir/assertj-automation/releases/tag/0.6.0
- https://github.com/palantir/assertj-automation/compare/0.3.0...0.6.0
2022-04-24 14:37:29 +02:00
Picnic-Bot
b2316c744c Upgrade Hamcrest 1.3 -> 2.2 (#70)
See:
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.1-rc1
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.1-rc2
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.1-rc3
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.1-rc4
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.1
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.2-rc1
- https://github.com/hamcrest/JavaHamcrest/releases/tag/v2.2
- https://github.com/hamcrest/JavaHamcrest/compare/hamcrest-java-1.3...v2.2
2022-04-24 14:24:54 +02:00
Picnic-Bot
9334babfe8 Upgrade sortpom-maven-plugin 3.0.0 -> 3.0.1 (#48)
See:
- https://github.com/Ekryd/sortpom/wiki/Versions
- https://github.com/Ekryd/sortpom/releases/tag/sortpom-parent-3.0.1
- https://github.com/Ekryd/sortpom/compare/sortpom-parent-3.0.0...sortpom-parent-3.0.1
2022-04-24 14:15:13 +02:00
Picnic-Bot
b6632d393b Upgrade AutoCommon 1.2 -> 1.2.1 (#49)
See:
- https://github.com/google/auto/releases/tag/auto-common-1.2.1
- https://github.com/google/auto/compare/auto-common-1.2...auto-common-1.2.1
2022-04-24 14:01:28 +02:00
Picnic-Bot
53d191ff4f Upgrade NullAway 0.9.2 -> 0.9.6 (#50)
See:
- https://github.com/uber/NullAway/blob/master/CHANGELOG.md
- https://github.com/uber/NullAway/compare/v0.9.2...v0.9.6
2022-04-24 13:19:49 +02:00
Picnic-Bot
b8ddf3ac20 Upgrade Jackson 2.13.0 -> 2.13.2.20220328 (#47)
See:
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.13.1
- https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.13.2
- https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.13.0...jackson-bom-2.13.2.20220328
2022-04-24 13:05:17 +02:00
Rick Ossendrijver
e859c2774f JUnitMethodDeclarationCheck: better handle possibly-problematic method renames (#35)
By flagging affected test methods, but not suggesting a specific rename.
2022-04-12 18:16:21 +02:00
Rick Ossendrijver
1cb4ce97ae Require static import of most java.util.Collections methods (#23)
While there, statically import `ZoneOffset.UTC` in a few places.
2022-04-12 17:48:53 +02:00
Pieter Dirk Soels
92fe96286f Prefer Collectors.joining() over Collectors.joining("") (#44) 2022-04-12 14:25:39 +02:00
Vitor Mussatto
d7531abceb Introduce additional Immutable{List,Map,Set}#of Refaster templates (#40) 2022-04-12 11:51:45 +02:00
João Nogueira
cc7074a62f Introduce RequestParamTypeCheck (#33) 2022-04-12 10:45:34 +02:00
Pieter Dirk Soels
91922454b6 Require static import of com.google.errorprone.refaster.ImportPolicy members (#45) 2022-04-12 10:36:44 +02:00
Rick Ossendrijver
eaa98c985c Introduce assorted AssertJ Refaster templates (#37) 2022-04-11 22:25:14 +02:00
Pieter Dirk Soels
94908d6a37 Require static import of java.util.UUID#randomUUID (#42) 2022-04-11 17:55:57 +02:00
Rick Ossendrijver
e8d9221424 Have PrimitiveComparisonCheck retain relevant generic type parameters (#39) 2022-04-11 17:13:06 +02:00
Rick Ossendrijver
fea8f5b2c0 Suggest assorted canonical ZoneOffset usages (#38)
- Statically import `ZoneOffset.UTC`.
- Prefer `Instant#atOffset` over `OffsetDateTime#ofInstant`.
2022-04-11 10:16:37 +02:00
Rick Ossendrijver
2199accedc Drop or rewrite AssertJBigDecimalTemplates rules (#30) 2022-04-11 10:08:15 +02:00
Rick Ossendrijver
83670aeddf Require static import of java.util.regex.Pattern constants (#36)
The meaning of these constants will be apparent from context.

Note that `Pattern.{compile,matches,quote}` should not be statically imported,
as these methods have rather generic names.
2022-04-11 09:19:40 +02:00
Rick Ossendrijver
e8977bea67 Require static import of BugPattern.{LinkType,ServerityLevel,StandardTags} members (#34) 2022-04-11 08:16:20 +02:00
Pieter Dirk Soels
0d051064bb Prefer Duration.ofX(n) over Duration.of(n, ChronoUnit.X) (#41)
`TimeTemplates` now contains Refaster templates for
`Duration.of{Nanos,Millis,Seconds,Minutes,Hours,Days}(n)`.
2022-04-10 16:02:33 +02:00
Rick Ossendrijver
06913b6a5b Drop obsolete README entry (#29)
This issue is was resolved by google/error-prone#2257.
2022-04-10 15:34:36 +02:00
Rick Ossendrijver
d2bbee3ed9 Introduce IdentityConversionCheck (#27)
And remove any Refaster templates it subsumes.
2022-04-08 13:28:12 +02:00
Rick Ossendrijver
793a70c29b Configure static import policy for AssertThatSetContainsExactlyOneElement Refaster template (#32) 2022-01-24 10:02:34 +01:00
Rick Ossendrijver
63b4fae185 Introduce FluxFlatMapUsageCheck (#26)
And two (semi-)related Refaster templates.
2022-01-15 12:39:34 +01:00
Stephan Schroevers
73f8f056b4 Introduce ScheduledTransactionTraceCheck (#31) 2022-01-10 10:21:20 +01:00
Rick Ossendrijver
c1638066cd Define assorted StaticImportCheck exemptions
While there, require that most `org.springframework.http.MediaType` members are
statically imported.
2022-01-03 10:20:46 +01:00
Rick Ossendrijver
08e99fb54e Use matching lambda parameter names in Refaster before- and after-templates (#24) 2022-01-01 14:04:37 +01:00
Rick Ossendrijver
00012c6aa8 Extend StaticImportCheck test coverage (#21) 2021-11-14 14:39:15 +01:00
Rick Ossendrijver
193589d193 Require static import of SpringBootTest.WebEnvironment constants (#19) 2021-11-14 14:26:17 +01:00
Stephan Schroevers
1a1588d413 Upgrade Error Prone 2.9.0 -> 2.10.0 2021-11-14 13:50:26 +01:00
Stephan Schroevers
6656bd8186 Assorted upgrades 2021-11-14 13:50:26 +01:00
Rick Ossendrijver
26a9b46de7 Add Refaster rules for StepVerifier creation (#18) 2021-11-14 13:48:39 +01:00
Phil Werli
17e74f778b Add Refaster rules for redundant Flux#concat invocations (#20) 2021-11-13 18:04:49 +01:00
Stephan Schroevers
e1bdb098de Upgrade AssertJ Core 3.20.2 -> 3.21.0
See:
- https://assertj.github.io/doc/#assertj-core-release-notes
- https://github.com/joel-costigliola/assertj-core/compare/assertj-core-3.20.2...assertj-core-3.21.0
2021-09-25 13:53:58 +02:00
Stephan Schroevers
0be162c837 Assorted upgrades 2021-09-25 13:53:31 +02:00
Stephan Schroevers
edfb2a70e8 Upgrade Guava 30.1.1-jre -> 31.0-jre
And drop Refaster rules for APIs that are now `@Deprecated` or have an
`@InlineMe` annotation.

See:
- https://guava.dev/releases/31.0-jre/api/diffs/
- https://github.com/google/guava/releases/tag/v31.0
- https://github.com/google/guava/compare/v30.1.1...v31.0
2021-09-25 13:17:10 +02:00
Stephan Schroevers
c1e5dc4339 Assorted upgrades 2021-09-19 21:07:40 +02:00
Stephan Schroevers
7218006b3c Assorted upgrades 2021-09-03 07:42:57 +02:00
Rick Ossendrijver
a3f599ba1b Introduce WebClientTemplates (#16) 2021-08-30 21:54:28 +02:00
Stephan Schroevers
f819a3e42f Assorted upgrades 2021-08-20 08:50:15 +02:00
Stephan Schroevers
7fc865c769 Light RefasterRuleResourceCompilerTaskListener cleanup 2021-08-19 22:43:10 +02:00
Stephan Schroevers
0287060d96 Fix and optimize FormatStringConcatenationCheck 2021-08-19 22:42:41 +02:00
Stephan Schroevers
ac4e81f2c7 Support running the build using JDK 16+ 2021-08-14 19:29:55 +02:00
Stephan Schroevers
350f028781 Sync with PSM parent 2021-08-14 19:13:31 +02:00
Stephan Schroevers
299ce7b800 Assorted upgrades 2021-08-14 19:13:31 +02:00
Stephan Schroevers
f3a929a3bb Upgrade fmt-maven-plugin, reformat 2021-08-04 10:59:23 +02:00
Stephan Schroevers
625a55add5 Add extra Refaster rule, document possible FormatStringConcatenation extension 2021-08-04 10:58:16 +02:00
Stephan Schroevers
ef59340987 Assorted upgrades 2021-08-04 10:58:05 +02:00
Stephan Schroevers
f2aea38b17 Introduce AbstractOptionalAssertContainsSame Refaster template 2021-08-03 13:53:44 +02:00
Stephan Schroevers
5cd8863eb5 Slightly optimize MethodReferenceUsage check 2021-08-01 19:10:46 +02:00
Stephan Schroevers
5b57b4720b Introduce MockitoStubbing check 2021-08-01 18:29:54 +02:00
Stephan Schroevers
5224571407 Assorted FormatStringConcatenationCheck improvements 2021-08-01 15:56:32 +02:00
Stephan Schroevers
c8189e9431 Document RefasterCheck follow-up task 2021-08-01 12:41:00 +02:00
Stephan Schroevers
0fe42f1ea6 Introduce FormatStringConcatenation check 2021-08-01 12:32:08 +02:00
Stephan Schroevers
78b29107a3 Upgrade dependencies 2021-07-29 12:09:19 +02:00
Stephan Schroevers
7ae7d5105a Document StreamMapFirst gotcha, courtesy of Nathan 2021-07-29 11:51:11 +02:00
Stephan Schroevers
0976b33d61 Support Refaster templates without an @AfterTemplate method 2021-07-29 11:48:51 +02:00
Stephan Schroevers
4b6f81c4fa imeZoneUsageCheck: dDon't flag likely overrides 2021-07-27 17:44:04 +02:00
Stephan Schroevers
1e879c175e Don't flag empty test (helper) methods 2021-07-27 17:43:08 +02:00
Stephan Schroevers
d014fed400 Deduplicate Refaster templates 2021-07-24 23:20:26 +02:00
Stephan Schroevers
1357f60fbc Introduce refaster-support module
This new module is meant to expose helper logic for use with Refaster
templates. For a start, one can now use e.g.
`@NotMatches(IsArray.class)`.
2021-07-24 23:20:25 +02:00
Stephan Schroevers
03abbbf99c Introduce RefasterAnyOfUsageCheck 2021-07-24 17:08:08 +02:00
Stephan Schroevers
9b845782c2 Cleanup and add package-info.java files 2021-07-24 16:55:46 +02:00
Stephan Schroevers
08ce33fb19 Upgrade, fix typo 2021-07-24 12:18:00 +02:00
Stephan Schroevers
182724bc8e Upgrade dependencies 2021-07-23 08:00:18 +02:00
Stephan Schroevers
e9d361713a Upgrade Error Prone, deduplicate version configuration 2021-07-23 07:55:47 +02:00
Stephan Schroevers
b754880556 Assorted upgrades 2021-07-18 14:59:30 +02:00
Stephan Schroevers
affd5c7b93 Support self-application of the checks 2021-07-18 14:59:30 +02:00
Stephan Schroevers
d86611e66a TimeZoneUsageCheck should not flag Instant.now(clock)
Users _should_ rewrite that to `clock.instant()`, and indeed we have a
Refaster check for that.
2021-07-18 11:04:36 +02:00
Stephan Schroevers
2d6100a679 Further nudge to AssertJ 2021-07-18 10:46:47 +02:00
Stephan Schroevers
912797a55a Bintray is no more; Palantir now deploys to Maven Central 2021-07-18 10:46:47 +02:00
Stephan Schroevers
d097f31124 Assorted upgrades 2021-06-26 10:45:33 +02:00
Stephan Schroevers
eb05582f79 Assorted upgrades 2021-06-19 16:33:24 +02:00
Stephan Schroevers
964fc35b71 Upgrades 2021-05-29 18:04:57 +02:00
Stephan Schroevers
ddc05bf88c Assorted upgrades 2021-05-15 13:07:54 +02:00
Stephan Schroevers
24afa6a755 Some improvements from oss-parent 2021-04-24 00:00:10 +02:00
Stephan Schroevers
8e97121bdf Upgrade dependency 2021-04-23 22:37:19 +02:00
Stephan Schroevers
567c81a93d Upgrade to Error Prone 2.6.0 2021-04-23 22:20:11 +02:00
Stephan Schroevers
c0bfac7b4c Upgrades, some syncing with other parent 2021-04-22 15:10:58 +02:00
Rick Ossendrijver
28138f35eb Assorted upgrades (#15) 2021-04-19 09:51:25 +02:00
Stephan Schroevers
a9b691b856 Assorted upgrades 2021-04-06 17:35:38 +02:00
Ivan Fedorov
acfe87fbc4 Flag Ordering#explicit invocations listing a subset of an enum's values (#14) 2021-03-30 08:19:08 +02:00
Stephan Schroevers
091a6eee7a Fix the fork configuration 2021-03-30 08:04:01 +02:00
Stephan Schroevers
3c06e3ead3 Some consistency changes 2021-03-28 17:28:00 +02:00
Stephan Schroevers
3ecab2f4b9 Reduce memory assigned to Surefire
We may need to reintroduce this change in the future, but for now we can
keep the configuration in sync with other parent POMs.
2021-03-28 15:05:09 +02:00
Stephan Schroevers
4b3e79667d Address deprecations in the upcoming release 2021-03-28 15:05:09 +02:00
Stephan Schroevers
6505535525 Upgrades 2021-03-27 15:28:20 +01:00
Stephan Schroevers
e48bbf3a44 Upgrade to Error Prone 2.5.1 2021-03-27 15:03:50 +01:00
Stephan Schroevers
3391468746 Assorted upgrades 2021-03-20 19:03:37 +01:00
Stephan Schroevers
10172c426d Assorted upgrades 2021-03-14 10:15:00 +01:00
Stephan Schroevers
f2737b4fe9 Fix MissingRefasterAnnotationCheck 2021-03-11 16:37:22 +01:00
Anna Dvorkin
f9a1c82d68 PRP-10968 Flag discouraged time zone-dependent APIs (#9) 2021-03-01 23:08:19 +01:00
Halil İbrahim Şener
cbc886d0c2 PSM-442 Flag likely-wrong @JsonCreator usages (#2) 2021-03-01 18:50:58 +01:00
Rick Ossendrijver
e4e3aded84 Flag methods that appear to lack a Refaster annotation (#13) 2021-02-28 16:29:51 +01:00
Rick Ossendrijver
e84d0e1059 Flag unordered annotation declarations (#11) 2021-02-28 14:42:44 +01:00
Stephan Schroevers
5e763d06d0 Assorted upgrades 2021-02-27 08:22:07 +01:00
Stephan Schroevers
ec05456c96 Choose Arrays.stream over Stream.of 2021-02-27 08:22:07 +01:00
Phil Werli
f53c47b56f PSM-585 Flag controller method parameters lacking annotations (#4) 2021-02-15 20:45:26 +01:00
Rick Ossendrijver
8a4c6e1209 Drop deprecated @BugPattern parameter and fix typos (#12) 2021-02-15 16:41:02 +01:00
Rick Ossendrijver
89033e2216 Add a few ImmutableCollection Refaster templates (#8) 2021-02-14 14:57:00 +01:00
Stephan Schroevers
4dc955a976 Assorted upgrades 2021-02-14 13:40:38 +01:00
Stephan Schroevers
06aa037215 Make sure we're notified of all annotation processor path dependencies 2021-01-15 09:53:30 +01:00
Stephan Schroevers
eb2be03708 Assorted upgrades 2021-01-15 08:28:45 +01:00
Stephan Schroevers
9a9b5fdba5 Some tweaks before posting some code in a Github issue 2021-01-09 11:17:58 +01:00
Nicolas Garcia
a53e497153 PSM-671 Introduce JUnitMethodDeclaration bug pattern (#6) 2021-01-07 22:11:24 +01:00
Stephan Schroevers
5e20907737 Assorted dependency upgrades 2021-01-01 13:38:07 +01:00
Stephan Schroevers
16cf0afc8d Upgrade Palantir Baseline, fix typo noticed by Rick 2020-12-29 18:41:07 +01:00
Rick Ossendrijver
cfd88df324 Add .gitignore
And fix two typos.
2020-12-26 22:51:23 +01:00
Stephan Schroevers
44f8b565c8 pom.xml sync, upgrades 2020-12-20 16:50:40 +01:00
Stephan Schroevers
553d3617a1 Update the README, add Refaster extension ideas 2020-12-20 16:20:46 +01:00
Stephan Schroevers
5829612107 Force Optional#orElseThrow() over Optional#get()
And update other Refaster templates accordingly.
2020-12-20 16:00:20 +01:00
Stephan Schroevers
24d3dcf0b7 More checks 2020-12-20 14:34:51 +01:00
Stephan Schroevers
95c212e102 Improve StaticImportCheck 2020-12-13 14:54:10 +01:00
Stephan Schroevers
660f1a1fc9 Introduce StaticImportCheck 2020-12-12 23:59:15 +01:00
Stephan Schroevers
c908f4b266 Resolve PrimitiveComparisonCheck note 2020-12-12 16:28:47 +01:00
Stephan Schroevers
21a5533777 Some simplifications 2020-12-12 13:40:07 +01:00
Stephan Schroevers
c612c17c54 Upgrades 2020-12-09 09:34:11 +01:00
Stephan Schroevers
0625c1b361 Assorted upgrades 2020-12-04 18:27:44 +01:00
Stephan Schroevers
5e07645520 Assorted improvements 2020-12-04 18:10:10 +01:00
Stephan Schroevers
cae666b90e Simplify AutowiredConstructorCheck 2020-12-04 16:17:43 +01:00
Stephan Schroevers
d49182711f Assorted upgrades 2020-10-31 13:49:46 +01:00
Stephan Schroevers
3809446494 Add AssertThatHasToString rule 2020-10-31 13:07:00 +01:00
Stephan Schroevers
71f4d15db8 Add Refaster rules for the new Guava release 2020-10-17 16:53:32 +02:00
Stephan Schroevers
2c7d2174b4 Bump dependency version 2020-10-17 16:16:10 +02:00
Stephan Schroevers
ccb9c8ee9f Add AssertJ Refaster template 2020-10-03 21:52:38 +02:00
Stephan Schroevers
1c984b2c5d Assorted upgrades 2020-09-19 10:10:23 +02:00
Stephan Schroevers
423e9034fb Version bumps 2020-08-23 16:21:49 +02:00
Stephan Schroevers
a96dd12153 Add some Reactor Refaster rules 2020-08-16 00:30:49 +02:00
Stephan Schroevers
5c6bf112e6 Assorted improvements suggested by IDEA 2020-08-15 23:19:07 +02:00
Stephan Schroevers
a7ba5d4cf7 Assorted dependency upgrades 2020-08-15 23:02:08 +02:00
Phil Werli
d4d4676691 PSF-9432 Introduce JUnit Arguments Refaster rule (#3) 2020-08-14 11:31:26 +02:00
Stephan Schroevers
a842d30e33 Version bumps 2020-08-01 16:48:17 +02:00
Stephan Schroevers
1c3be73f70 Checkstyle upgrade 2020-07-26 18:32:51 +02:00
Stephan Schroevers
c01f3767c6 Upgrades 2020-07-25 21:57:33 +02:00
Stephan Schroevers
1c01ca94e4 Simplify 2020-06-15 19:58:42 +02:00
Stephan Schroevers
623a9258a3 Introduce MockitoTemplates 2020-06-15 19:51:06 +02:00
Stephan Schroevers
fed8615bf5 Introduce (but disable) Palantir checks, properly support non-Maven Central dependencies 2020-06-14 22:15:51 +02:00
Stephan Schroevers
dc7762eaf2 Bump Surefire max heap usage to increase build stability (and reduce build time) 2020-06-14 18:42:14 +02:00
Stephan Schroevers
89d78715ef More rules 2020-06-14 18:03:43 +02:00
Stephan Schroevers
24f12898f0 Resolve issues found while applying checks to current code 2020-06-14 13:35:44 +02:00
Stephan Schroevers
79b4f2abcd Upgrade Error Prone 2.3.4 -> 2.4.0 2020-06-14 11:38:09 +02:00
Stephan Schroevers
2dfe0450f2 Bumps 2020-06-13 21:24:14 +02:00
425 changed files with 29647 additions and 5648 deletions

51
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,51 @@
---
name: 🐛 Bug report
about: Create a report to help us improve.
title: ""
labels: bug
assignees: ""
---
### Describe the bug
<!-- Provide a clear and concise description of what the bug or issue is. -->
- [ ] I have verified that the issue is reproducible against the latest version
of the project.
- [ ] I have searched through existing issues to verify that this issue is not
already known.
### Minimal Reproducible Example
<!-- Provide a clear and concise description of what happened. Please include
steps on how to reproduce the issue. -->
```java
If applicable and possible, please replace this section with the code that
triggered the isue.
```
<details>
<summary>Logs</summary>
```sh
Please replace this sentence with log output, if applicable.
```
</details>
### Expected behavior
<!-- Provide a clear and concise description of what you expected to happen. -->
### Setup
<!-- Please complete the following information: -->
- Operating system (e.g. MacOS Monterey).
- Java version (i.e. `java --version`, e.g. `17.0.6`).
- Error Prone version (e.g. `2.18.0`).
- Error Prone Support version (e.g. `0.8.0`).
### Additional context
<!-- Provide any other context about the problem here. -->

View File

@@ -0,0 +1,58 @@
---
name: 🚀 Request a new feature
about: Suggest a new feature.
title: ""
labels: new feature
assignees: ""
---
### Problem
<!-- Here, describe the context of the problem that you're facing, and which
you'd like to be solved through Error Prone Support. -->
### Description of the proposed new feature
<!-- Please indicate the type of improvement. -->
- [ ] Support a stylistic preference.
- [ ] Avoid a common gotcha, or potential problem.
- [ ] Improve performance.
<!--
Here, provide a clear and concise description of the desired change.
If possible, provide a simple and minimal example using the following format:
-->
I would like to rewrite the following code:
```java
// XXX: Write the code to match here.
```
to:
```java
// XXX: Write the desired code here.
```
### Considerations
<!--
Here, mention any other aspects to consider. Relevant questions:
- If applicable, is the rewrite operation a clear improvement in all cases?
- Are there special cases to consider?
- Can we further generalize the proposed solution?
- Are there alternative solutions we should consider?
-->
### Participation
<!-- Pull requests are very welcome, and we happily review contributions. Are
you up for the challenge? :D -->
- [ ] I am willing to submit a pull request to implement this improvement.
### Additional context
<!-- Provide any other context about the request here. -->

29
.github/release.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
changelog:
exclude:
labels:
- "ignore-changelog"
categories:
- title: ":rocket: New Error Prone checks and Refaster rules"
labels:
- "new feature"
- title: ":sparkles: Improvements"
labels:
- "improvement"
- title: ":warning: Update considerations and deprecations"
labels:
- "breaking change"
- "deprecation"
- title: ":bug: Bug fixes"
labels:
- "bug"
- "bug fix"
- title: ":books: Documentation, test and build improvements"
labels:
- "documentation"
- "chore"
- title: ":chart_with_upwards_trend: Dependency upgrades"
labels:
- "dependencies"
- title: "Other changes"
labels:
- "*"

55
.github/workflows/build.yaml vendored Normal file
View File

@@ -0,0 +1,55 @@
name: Build and verify
on:
pull_request:
push:
branches: [ master ]
permissions:
contents: read
jobs:
build:
strategy:
matrix:
os: [ ubuntu-22.04 ]
jdk: [ 11.0.18, 17.0.6, 19.0.2 ]
distribution: [ temurin ]
experimental: [ false ]
include:
- os: macos-12
jdk: 17.0.6
distribution: temurin
experimental: false
- os: windows-2022
jdk: 17.0.6
distribution: temurin
experimental: false
- os: ubuntu-22.04
jdk: 20-ea
distribution: zulu
experimental: true
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
steps:
# We run the build twice for each supported JDK: once against the
# original Error Prone release, using only Error Prone checks available
# on Maven Central, and once against the Picnic Error Prone fork,
# additionally enabling all checks defined in this project and any
# Error Prone checks available only from other artifact repositories.
- name: Check out code
uses: actions/checkout@v3.1.0
- name: Set up JDK
uses: actions/setup-java@v3.8.0
with:
java-version: ${{ matrix.jdk }}
distribution: ${{ matrix.distribution }}
cache: maven
- name: Display build environment details
run: mvn --version
- name: Build project against vanilla Error Prone, compile Javadoc
run: mvn -T1C install javadoc:jar
- name: Build project with self-check against Error Prone fork
run: mvn -T1C clean verify -Perror-prone-fork -Pnon-maven-central -Pself-check -s settings.xml
- name: Remove installed project artifacts
run: mvn build-helper:remove-project-artifact
# XXX: Enable Codecov once we "go public".
# XXX: Enable SonarCloud once we "go public".

49
.github/workflows/deploy-website.yaml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Update `error-prone.picnic.tech` website content
on:
pull_request:
push:
branches: [ master, website ]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
jobs:
build:
permissions:
contents: read
runs-on: ubuntu-22.04
steps:
- name: Check out code
uses: actions/checkout@v3.1.0
- uses: ruby/setup-ruby@v1.126.0
with:
working-directory: ./website
bundler-cache: true
- name: Configure Github Pages
uses: actions/configure-pages@v2.1.3
- name: Generate documentation
run: ./generate-docs.sh
- name: Build website with Jekyll
working-directory: ./website
run: bundle exec jekyll build
- name: Validate HTML output
working-directory: ./website
# XXX: Drop `--disable_external true` once we fully adopted the
# "Refaster rules" terminology on our website and in the code.
run: bundle exec htmlproofer --disable_external true --check-external-hash false ./_site
- name: Upload website as artifact
uses: actions/upload-pages-artifact@v1.0.5
with:
path: ./website/_site
deploy:
if: github.ref == 'refs/heads/website'
needs: build
permissions:
id-token: write
pages: write
runs-on: ubuntu-22.04
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v1.2.3

37
.github/workflows/pitest-analyze-pr.yml vendored Normal file
View File

@@ -0,0 +1,37 @@
# Performs mutation testing analysis on the files changed by a pull request and
# uploads the results. The associated PR is subsequently updated by the
# `pitest-update-pr.yml` workflow. See https://blog.pitest.org/oss-pitest-pr/
# for details.
name: "Mutation testing"
on:
pull_request:
permissions:
contents: read
jobs:
analyze-pr:
runs-on: ubuntu-22.04
steps:
- name: Check out code
uses: actions/checkout@v3.1.0
with:
fetch-depth: 2
- name: Set up JDK
uses: actions/setup-java@v3.8.0
with:
java-version: 17.0.6
distribution: temurin
cache: maven
- name: Run Pitest
# By running with features `+GIT(from[HEAD~1]), +gitci`, Pitest only
# analyzes lines changed in the associated pull request, as GitHub
# exposes the changes unique to the PR as a single commit on top of the
# target branch. See https://blog.pitest.org/pitest-pr-setup for
# details.
run: mvn test pitest:mutationCoverage -DargLine.xmx=2048m -Dverification.skip -Dfeatures="+GIT(from[HEAD~1]), +gitci"
- name: Aggregate Pitest reports
run: mvn pitest-git:aggregate -DkilledEmoji=":tada:" -DmutantEmoji=":zombie:" -DtrailingText="Mutation testing report by [Pitest](https://pitest.org/). Review any surviving mutants by inspecting the line comments under [_Files changed_](${{ github.event.number }}/files)."
- name: Upload Pitest reports as artifact
uses: actions/upload-artifact@v3.1.1
with:
name: pitest-reports
path: ./target/pit-reports-ci

35
.github/workflows/pitest-update-pr.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
# Updates a pull request based on the corresponding mutation testing analysis
# performed by the `pitest-analyze-pr.yml` workflow. See
# https://blog.pitest.org/oss-pitest-pr/ for details.
name: "Mutation testing: post results"
on:
workflow_run:
workflows: ["Mutation testing"]
types:
- completed
permissions:
actions: read
checks: write
contents: read
pull-requests: write
jobs:
update-pr:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-22.04
steps:
- name: Check out code
uses: actions/checkout@v3.1.0
- name: Set up JDK
uses: actions/setup-java@v3.8.0
with:
java-version: 17.0.6
distribution: temurin
cache: maven
- name: Download Pitest analysis artifact
uses: dawidd6/action-download-artifact@v2.24.2
with:
workflow: ${{ github.event.workflow_run.workflow_id }}
name: pitest-reports
path: ./target/pit-reports-ci
- name: Update PR
run: mvn -DrepoToken="${{ secrets.GITHUB_TOKEN }}" pitest-github:updatePR

11
.gitignore vendored Normal file
View File

@@ -0,0 +1,11 @@
# General Java development.
.attach_pid*
.classpath
.DS_Store
.factorypath
.idea
.project
.settings
target
*.iml
*.swp

13
.mvn/jvm.config Normal file
View File

@@ -0,0 +1,13 @@
-XX:ReservedCodeCacheSize=512m
-XX:SoftRefLRUPolicyMSPerMB=10
-XX:+UseParallelGC
--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED

3
.mvn/maven.config Normal file
View File

@@ -0,0 +1,3 @@
--batch-mode
--errors
--strict-checksums

22
.renovaterc.json Normal file
View File

@@ -0,0 +1,22 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchPackagePatterns": [
"^org\\.springframework:spring-framework-bom$",
"^org\\.springframework\\.boot:spring-boot[a-z-]*$"
],
"separateMinorPatch": true
},
{
"matchPackagePatterns": [
"^ruby\\/setup-ruby$"
],
"schedule": "* * 1 * *"
}
],
"reviewers": [
"rickie",
"Stephan202"
]
}

View File

@@ -1,35 +0,0 @@
---
dist: bionic
language: java
jdk: openjdk11
addons:
sonarcloud:
organization: picnic-technologies
token: "${SONARCLOUD_TOKEN}"
install:
- mvn io.takari:maven:wrapper
script:
# We run the build twice: once against the original Error Prone release, and
# once against the Picnic Error Prone fork.
- ./mvnw clean install
- ./mvnw clean install -Perror-prone-fork -s settings.xml
# XXX: Enable SonarCloud once we "go public".
# ./mvnw jacoco:prepare-agent surefire:test jacoco:report sonar:sonar
- ./mvnw jacoco:prepare-agent surefire:test jacoco:report
before_cache:
# Don't cache the artifacts we just generated, for multiple reasons: (1) we
# shouldn't need them next time around and (2) if we do, that indicates a
# dependency issue which might otherwise go unnoticed until next time we bump
# the project's version (i.e., when tagging).
- find "${HOME}/.m2/repository" -depth -name '*-SNAPSHOT' -exec rm -r '{}' \;
cache:
directories:
# The local Maven repository in which third party dependencies are stored.
- ${HOME}/.m2/repository
# The Takari Maven Wrapper's storage for downloaded Maven distributions.
- ${HOME}/.m2/wrapper
# The SonarQube analysis cache.
- ${HOME}/.sonar/cache
# XXX: Enable Codecov once we "go public".
#after_success:
# - bash <(curl -s https://codecov.io/bash)

71
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,71 @@
# Contributing
Thank you for checking this document! This project is free software, and we
(the maintainers) encourage and value any contribution.
Here are some guidelines to help you get started.
## 🐛 Reporting a bug
Like any non-trivial piece of software, this library is probably not bug-free.
If you found a bug, feel free to [report the issue][error-prone-support-issues]
on GitHub.
Before doing so, please:
- Verify that the issue is reproducible against the latest version of the
project.
- Search through the existing set of issues to see whether the problem is
already known. With some luck a solution is already in place, or a workaround
may have been provided.
When filing a bug report, please include the following:
- Any relevant information about your environment. This should generally
include the output of `java --version`, as well as the version of Error Prone
you're using.
- A description of what is going on (e.g. logging output, stacktraces).
- A minimum reproducible example, so that other developers can try to reproduce
(and optionally fix) the bug.
- Any additional information that may be relevant.
## 💡 Reporting an improvement
If you would like to see an improvement, you can file a [GitHub
issue][error-prone-support-issues]. This is also a good idea when you're
already working towards opening a pull request, as this allows for discussion
around the idea.
## 🚀 Opening a pull request
All submissions, including submissions by project members, require approval by
at least two reviewers. We use [GitHub pull
requests][error-prone-support-pulls] for this purpose.
Before opening a pull request, please check whether there are any existing
(open or closed) issues or pull requests addressing the same problem. This
avoids double work or lots of time spent on a solution that may ultimately not
be accepted. When in doubt, make sure to first raise an
[issue][error-prone-support-issues] to discuss the idea.
To the extent possible, the pull request process guards our coding guidelines.
Some pointers:
- Checks should be _topical_: ideally they address a single concern.
- Where possible checks should provide _fixes_, and ideally these are
completely behavior-preserving. In order for a check to be adopted by users
it must not "get in the way". So for a check that addresses a relatively
trivial stylistic concern it is doubly important that the violations it
detects can be auto-patched.
- Make sure you have read Error Prone's [criteria for new
checks][error-prone-criteria]. Most guidelines described there apply to this
project as well, except that this project _does_ focus quite heavy on style
enforcement. But that just makes the previous point doubly important.
- Make sure that a check's [(mutation) test
coverage][error-prone-support-mutation-tests] is or remains about as high as
it can be. Not only does this lead to better tests, it also points out
opportunities to simplify the code.
- Please restrict the scope of a pull request to a single feature or fix. Don't
sneak in unrelated changes; instead just open more than one pull request 😉.
[error-prone-criteria]: https://errorprone.info/docs/criteria
[error-prone-support-issues]: https://github.com/PicnicSupermarket/error-prone-support/issues
[error-prone-support-mutation-tests]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/run-mutation-tests.sh
[error-prone-support-pulls]: https://github.com/PicnicSupermarket/error-prone-support/pulls

21
LICENSE.md Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017-2023 Picnic Technologies BV
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

259
README.md Normal file
View File

@@ -0,0 +1,259 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="website/assets/images/logo-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="website/assets/images/logo.svg">
<img alt="Error Prone Support logo" src="website/assets/images/logo.svg" width="50%">
</picture>
</div>
# Error Prone Support
Error Prone Support is a [Picnic][picnic-blog]-opinionated extension of
Google's [Error Prone][error-prone-orig-repo]. It aims to improve code quality,
focussing on maintainability, consistency and avoidance of common pitfalls.
> Error Prone is a static analysis tool for Java that catches common
> programming mistakes at compile-time.
Read more on how Picnic uses Error Prone (Support) in the blog post [_Picnic
loves Error Prone: producing high-quality and consistent Java
code_][picnic-blog-ep-post].
[![Maven Central][maven-central-badge]][maven-central-search]
[![Reproducible Builds][reproducible-builds-badge]][reproducible-builds-report]
[![GitHub Actions][github-actions-build-badge]][github-actions-build-master]
[![License][license-badge]][license]
[![PRs Welcome][pr-badge]][contributing]
[Getting started](#-getting-started) •
[Developing Error Prone Support](#-developing-error-prone-support) •
[How it works](#-how-it-works) • [Contributing](#%EF%B8%8F-contributing)
---
## ⚡ Getting started
### Installation
This library is built on top of [Error Prone][error-prone-orig-repo]. To use
it, read the installation guide for Maven or Gradle below.
#### Maven
1. First, follow Error Prone's [installation
guide][error-prone-installation-guide].
2. Next, edit your `pom.xml` file to add one or more Error Prone Support
modules to the `annotationProcessorPaths` of the `maven-compiler-plugin`:
```xml
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<!-- Error Prone itself. -->
<path>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_core</artifactId>
<version>${error-prone.version}</version>
</path>
<!-- Error Prone Support's additional bug checkers. -->
<path>
<groupId>tech.picnic.error-prone-support</groupId>
<artifactId>error-prone-contrib</artifactId>
<version>${error-prone-support.version}</version>
</path>
<!-- Error Prone Support's Refaster rules. -->
<path>
<groupId>tech.picnic.error-prone-support</groupId>
<artifactId>refaster-runner</artifactId>
<version>${error-prone-support.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>
-Xplugin:ErrorProne
<!-- Add other Error Prone flags here. See
https://errorprone.info/docs/flags. -->
</arg>
<arg>-XDcompilePolicy=simple</arg>
</compilerArgs>
<!-- Some checks raise warnings rather than errors. -->
<showWarnings>true</showWarnings>
<!-- Enable this if you'd like to fail your build upon warnings. -->
<!-- <failOnWarning>true</failOnWarning> -->
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
```
<!-- XXX: Reference `oss-parent`'s `pom.xml` once that project also uses Error
Prone Support. Alternatively reference this project's `self-check` profile
definition. -->
#### Gradle
1. First, follow the [installation guide]
[error-prone-gradle-installation-guide] of the `gradle-errorprone-plugin`.
2. Next, edit your `build.gradle` file to add one or more Error Prone Support
modules:
```groovy
dependencies {
// Error Prone itself.
errorprone("com.google.errorprone:error_prone_core:${errorProneVersion}")
// Error Prone Support's additional bug checkers.
errorprone("tech.picnic.error-prone-support:error-prone-contrib:${errorProneSupportVersion}")
// Error Prone Support's Refaster rules.
errorprone("tech.picnic.error-prone-support:refaster-runner:${errorProneSupportVersion}")
}
tasks.withType(JavaCompile).configureEach {
options.errorprone.disableWarningsInGeneratedCode = true
// Add other Error Prone flags here. See:
// - https://github.com/tbroyer/gradle-errorprone-plugin#configuration
// - https://errorprone.info/docs/flags
}
```
### Seeing it in action
Consider the following example code:
```java
import com.google.common.collect.ImmutableSet;
import java.math.BigDecimal;
public class Example {
static BigDecimal getNumber() {
return BigDecimal.valueOf(0);
}
public ImmutableSet<Integer> getSet() {
ImmutableSet<Integer> set = ImmutableSet.of(1);
return ImmutableSet.copyOf(set);
}
}
```
If the [installation](#installation) was successful, then building the above
code with Maven should yield two compiler warnings:
```sh
$ mvn clean install
...
[INFO] Example.java:[9,34] [Refaster Rule] BigDecimalRules.BigDecimalZero: Refactoring opportunity
(see https://error-prone.picnic.tech/refasterrules/BigDecimalRules#BigDecimalZero)
Did you mean 'return BigDecimal.ZERO;'?
...
[WARNING] Example.java:[13,35] [IdentityConversion] This method invocation appears redundant; remove it or suppress this warning and add a comment explaining its purpose
(see https://error-prone.picnic.tech/bugpatterns/IdentityConversion)
Did you mean 'return set;' or '@SuppressWarnings("IdentityConversion") public ImmutableSet<Integer> getSet() {'?
...
```
Two things are kicking in here:
1. An Error Prone [`BugChecker`][error-prone-bugchecker] that flags unnecessary
[identity conversions][bug-checks-identity-conversion].
2. A [Refaster][refaster] rule capable of
[rewriting][refaster-rules-bigdecimal] expressions of the form
`BigDecimal.valueOf(0)` and `new BigDecimal(0)` to `BigDecimal.ZERO`.
Be sure to check out all [bug checks][bug-checks] and [refaster
rules][refaster-rules].
## 👷 Developing Error Prone Support
This is a [Maven][maven] project, so running `mvn clean install` performs a
full clean build and installs the library to your local Maven repository. Some
relevant flags:
- `-Dverification.warn` makes the warnings and errors emitted by various
plugins and the Java compiler non-fatal, where possible.
- `-Dverification.skip` disables various non-essential plugins and compiles the
code with minimal checks (i.e. without linting, Error Prone checks, etc.).
- `-Dversion.error-prone=some-version` runs the build using the specified
version of Error Prone. This is useful e.g. when testing a locally built
Error Prone SNAPSHOT.
- `-Perror-prone-fork` runs the build using Picnic's [Error Prone
fork][error-prone-fork-repo], hosted on [Jitpack][error-prone-fork-jitpack].
This fork generally contains a few changes on top of the latest Error Prone
release.
- `-Pself-check` runs the checks defined by this project against itself.
Pending a release of [google/error-prone#3301][error-prone-pull-3301], this
flag must currently be used in combination with `-Perror-prone-fork`.
Some other commands one may find relevant:
- `mvn fmt:format` formats the code using
[`google-java-format`][google-java-format].
- `./run-mutation-tests.sh` runs mutation tests using [Pitest][pitest]. The
results can be reviewed by opening the respective
`target/pit-reports/index.html` files. For more information check the [PIT
Maven plugin][pitest-maven].
- `./apply-error-prone-suggestions.sh` applies Error Prone and Error Prone
Support code suggestions to this project. Before running this command, make
sure to have installed the project (`mvn clean install`) and make sure that
the current working directory does not contain unstaged or uncommited
changes.
When running the project's tests in IntelliJ IDEA, you might see the following
error:
```
java: exporting a package from system module jdk.compiler is not allowed with --release
```
If this happens, go to _Settings -> Build, Execution, Deployment -> Compiler ->
Java Compiler_ and deselect the option _Use '--release' option for
cross-compilation (Java 9 and later)_. See [IDEA-288052][idea-288052] for
details.
## 💡 How it works
This project provides additional [`BugChecker`][error-prone-bugchecker]
implementations.
<!-- XXX: Extend this section. -->
## ✍️ Contributing
Want to report or fix a bug, suggest or add a new feature, or improve the
documentation? That's awesome! Please read our [contribution
guidelines][contributing].
[bug-checks]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/
[bug-checks-identity-conversion]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/IdentityConversion.java
[contributing]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/CONTRIBUTING.md
[error-prone-bugchecker]: https://github.com/google/error-prone/blob/master/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
[error-prone-fork-jitpack]: https://jitpack.io/#PicnicSupermarket/error-prone
[error-prone-fork-repo]: https://github.com/PicnicSupermarket/error-prone
[error-prone-gradle-installation-guide]: https://github.com/tbroyer/gradle-errorprone-plugin
[error-prone-installation-guide]: https://errorprone.info/docs/installation#maven
[error-prone-orig-repo]: https://github.com/google/error-prone
[error-prone-pull-3301]: https://github.com/google/error-prone/pull/3301
[github-actions-build-badge]: https://github.com/PicnicSupermarket/error-prone-support/actions/workflows/build.yaml/badge.svg
[github-actions-build-master]: https://github.com/PicnicSupermarket/error-prone-support/actions/workflows/build.yaml?query=branch%3Amaster
[google-java-format]: https://github.com/google/google-java-format
[idea-288052]: https://youtrack.jetbrains.com/issue/IDEA-288052
[license-badge]: https://img.shields.io/github/license/PicnicSupermarket/error-prone-support
[license]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/LICENSE.md
[maven-central-badge]: https://img.shields.io/maven-central/v/tech.picnic.error-prone-support/error-prone-support?color=blue
[maven-central-search]: https://search.maven.org/artifact/tech.picnic.error-prone-support/error-prone-support
[maven]: https://maven.apache.org
[picnic-blog]: https://blog.picnic.nl
[picnic-blog-ep-post]: https://blog.picnic.nl/picnic-loves-error-prone-producing-high-quality-and-consistent-java-code-b8a566be6886
[pitest]: https://pitest.org
[pitest-maven]: https://pitest.org/quickstart/maven
[pr-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
[refaster]: https://errorprone.info/docs/refaster
[refaster-rules-bigdecimal]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/BigDecimalRules.java
[refaster-rules]: https://github.com/PicnicSupermarket/error-prone-support/blob/master/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/
[reproducible-builds-badge]: https://img.shields.io/badge/Reproducible_Builds-ok-success?labelColor=1e5b96
[reproducible-builds-report]: https://github.com/jvm-repo-rebuild/reproducible-central/blob/master/content/tech/picnic/error-prone-support/error-prone-support/README.md

View File

@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Compiles the code using Error Prone and applies its suggestions. The set of
# checks applied can optionally be restricted by name.
#
# As this script may modify the project's code, it is important to execute it
# in a clean Git working directory.
set -e -u -o pipefail
if [ "${#}" -gt 1 ]; then
echo "Usage: ${0} [PatchChecks]"
exit 1
fi
patchChecks=${1:-}
mvn clean test-compile fmt:format \
-s "$(dirname "${0}")/settings.xml" \
-T 1.0C \
-Perror-prone \
-Perror-prone-fork \
-Ppatch \
-Pself-check \
-Derror-prone.patch-checks="${patchChecks}" \
-Dverification.skip

7
cdg-pitest-licence.txt Normal file
View File

@@ -0,0 +1,7 @@
# Arcmutate license for Error Prone Support, requested by sending an email to
# support@arcmutate.com.
expires=07/11/2023
keyVersion=1
signature=MhZxMbnO6UovNfllM0JuVWkZyvRT3/G5o/uT0Mm36c7200VpZNVu03gTAGivnl9W5RzvZhfpIHccuQ5ctjQkrqhsFSrl4fyqPqu3y5V2fsHIdFXP/G72EGj6Kay9ndLpaEHalqE0bEwxdnHMzEYq5y3O9vUPv8MhUl57xk+rvBo\=
packages=tech.picnic.errorprone.*
type=OSSS

View File

@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>tech.picnic.error-prone-support</groupId>
<artifactId>error-prone-support</artifactId>
<version>0.9.0</version>
</parent>
<artifactId>documentation-support</artifactId>
<name>Picnic :: Error Prone Support :: Documentation Support</name>
<description>Data extraction support for the purpose of documentation generation.</description>
<dependencies>
<dependency>
<groupId>${groupId.error-prone}</groupId>
<artifactId>error_prone_annotation</artifactId>
</dependency>
<dependency>
<groupId>${groupId.error-prone}</groupId>
<artifactId>error_prone_annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${groupId.error-prone}</groupId>
<artifactId>error_prone_check_api</artifactId>
</dependency>
<dependency>
<groupId>${groupId.error-prone}</groupId>
<artifactId>error_prone_test_helpers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.google.auto</groupId>
<artifactId>auto-common</artifactId>
</dependency>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,103 @@
package tech.picnic.errorprone.documentation;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
import com.google.auto.common.AnnotationMirrors;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.util.Context;
import javax.lang.model.element.AnnotationValue;
import tech.picnic.errorprone.documentation.BugPatternExtractor.BugPatternDocumentation;
/**
* An {@link Extractor} that describes how to extract data from a {@code @BugPattern} annotation.
*/
@Immutable
final class BugPatternExtractor implements Extractor<BugPatternDocumentation> {
@Override
public BugPatternDocumentation extract(ClassTree tree, Context context) {
ClassSymbol symbol = ASTHelpers.getSymbol(tree);
BugPattern annotation = symbol.getAnnotation(BugPattern.class);
requireNonNull(annotation, "BugPattern annotation must be present");
return new AutoValue_BugPatternExtractor_BugPatternDocumentation(
symbol.getQualifiedName().toString(),
annotation.name().isEmpty() ? tree.getSimpleName().toString() : annotation.name(),
ImmutableList.copyOf(annotation.altNames()),
annotation.link(),
ImmutableList.copyOf(annotation.tags()),
annotation.summary(),
annotation.explanation(),
annotation.severity(),
annotation.disableable(),
annotation.documentSuppression() ? getSuppressionAnnotations(tree) : ImmutableList.of());
}
@Override
public boolean canExtract(ClassTree tree) {
return ASTHelpers.hasDirectAnnotationWithSimpleName(tree, BugPattern.class.getSimpleName());
}
/**
* Returns the fully-qualified class names of suppression annotations specified by the {@link
* BugPattern} annotation located on the given tree.
*
* @implNote This method cannot simply invoke {@link BugPattern#suppressionAnnotations()}, as that
* will yield an "Attempt to access Class objects for TypeMirrors" exception.
*/
private static ImmutableList<String> getSuppressionAnnotations(ClassTree tree) {
AnnotationTree annotationTree =
ASTHelpers.getAnnotationWithSimpleName(
ASTHelpers.getAnnotations(tree), BugPattern.class.getSimpleName());
requireNonNull(annotationTree, "BugPattern annotation must be present");
Attribute.Array types =
doCast(
AnnotationMirrors.getAnnotationValue(
ASTHelpers.getAnnotationMirror(annotationTree), "suppressionAnnotations"),
Attribute.Array.class);
return types.getValue().stream()
.map(v -> doCast(v, Attribute.Class.class).classType.toString())
.collect(toImmutableList());
}
@SuppressWarnings("unchecked")
private static <T extends AnnotationValue> T doCast(AnnotationValue value, Class<T> target) {
verify(target.isInstance(value), "Value '%s' is not of type '%s'", value, target);
return (T) value;
}
@AutoValue
abstract static class BugPatternDocumentation {
abstract String fullyQualifiedName();
abstract String name();
abstract ImmutableList<String> altNames();
abstract String link();
abstract ImmutableList<String> tags();
abstract String summary();
abstract String explanation();
abstract SeverityLevel severityLevel();
abstract boolean canDisable();
abstract ImmutableList<String> suppressionAnnotations();
}
}

View File

@@ -0,0 +1,56 @@
package tech.picnic.errorprone.documentation;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.auto.service.AutoService;
import com.google.common.annotations.VisibleForTesting;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Plugin;
import com.sun.tools.javac.api.BasicJavacTask;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A compiler {@link Plugin} that analyzes and extracts relevant information for documentation
* purposes from processed files.
*/
// XXX: Find a better name for this class; it doesn't generate documentation per se.
@AutoService(Plugin.class)
public final class DocumentationGenerator implements Plugin {
@VisibleForTesting static final String OUTPUT_DIRECTORY_FLAG = "-XoutputDirectory";
private static final Pattern OUTPUT_DIRECTORY_FLAG_PATTERN =
Pattern.compile(Pattern.quote(OUTPUT_DIRECTORY_FLAG) + "=(.*)");
/** Instantiates a new {@link DocumentationGenerator} instance. */
public DocumentationGenerator() {}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public void init(JavacTask javacTask, String... args) {
checkArgument(args.length == 1, "Precisely one path must be provided");
javacTask.addTaskListener(
new DocumentationGeneratorTaskListener(
((BasicJavacTask) javacTask).getContext(), getOutputPath(args[0])));
}
@VisibleForTesting
static Path getOutputPath(String pathArg) {
Matcher matcher = OUTPUT_DIRECTORY_FLAG_PATTERN.matcher(pathArg);
checkArgument(
matcher.matches(), "'%s' must be of the form '%s=<value>'", pathArg, OUTPUT_DIRECTORY_FLAG);
String path = matcher.group(1);
try {
return Path.of(path);
} catch (InvalidPathException e) {
throw new IllegalArgumentException(String.format("Invalid path '%s'", path), e);
}
}
}

View File

@@ -0,0 +1,91 @@
package tech.picnic.errorprone.documentation;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.source.tree.ClassTree;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskEvent.Kind;
import com.sun.source.util.TaskListener;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.util.Context;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.tools.JavaFileObject;
/**
* A {@link TaskListener} that identifies and extracts relevant content for documentation generation
* and writes it to disk.
*/
// XXX: Find a better name for this class; it doesn't generate documentation per se.
final class DocumentationGeneratorTaskListener implements TaskListener {
private static final ObjectMapper OBJECT_MAPPER =
new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
private final Context context;
private final Path docsPath;
DocumentationGeneratorTaskListener(Context context, Path path) {
this.context = context;
this.docsPath = path;
}
@Override
public void started(TaskEvent taskEvent) {
if (taskEvent.getKind() == Kind.ANALYZE) {
createDocsDirectory();
}
}
@Override
public void finished(TaskEvent taskEvent) {
if (taskEvent.getKind() != Kind.ANALYZE) {
return;
}
ClassTree classTree = JavacTrees.instance(context).getTree(taskEvent.getTypeElement());
JavaFileObject sourceFile = taskEvent.getSourceFile();
if (classTree == null || sourceFile == null) {
return;
}
ExtractorType.findMatchingType(classTree)
.ifPresent(
extractorType ->
writeToFile(
extractorType.getIdentifier(),
getSimpleClassName(sourceFile.toUri()),
extractorType.getExtractor().extract(classTree, context)));
}
private void createDocsDirectory() {
try {
Files.createDirectories(docsPath);
} catch (IOException e) {
throw new IllegalStateException(
String.format("Error while creating directory with path '%s'", docsPath), e);
}
}
private <T> void writeToFile(String identifier, String className, T data) {
File file = docsPath.resolve(String.format("%s-%s.json", identifier, className)).toFile();
try (FileWriter fileWriter = new FileWriter(file, UTF_8)) {
OBJECT_MAPPER.writeValue(fileWriter, data);
} catch (IOException e) {
throw new UncheckedIOException(String.format("Cannot write to file '%s'", file.getPath()), e);
}
}
private static String getSimpleClassName(URI path) {
return Paths.get(path).getFileName().toString().replace(".java", "");
}
}

View File

@@ -0,0 +1,33 @@
package tech.picnic.errorprone.documentation;
import com.google.errorprone.annotations.Immutable;
import com.sun.source.tree.ClassTree;
import com.sun.tools.javac.util.Context;
/**
* Interface implemented by classes that define how to extract data of some type {@link T} from a
* given {@link ClassTree}.
*
* @param <T> The type of data that is extracted.
*/
@Immutable
interface Extractor<T> {
/**
* Extracts and returns an instance of {@link T} using the provided arguments.
*
* @param tree The {@link ClassTree} to analyze and from which to extract instances of {@link T}.
* @param context The {@link Context} in which the current compilation takes place.
* @return A non-null instance of {@link T}.
*/
// XXX: Drop `Context` parameter unless used.
T extract(ClassTree tree, Context context);
/**
* Tells whether this {@link Extractor} can extract documentation content from the given {@link
* ClassTree}.
*
* @param tree The {@link ClassTree} of interest.
* @return {@code true} iff data extraction is supported.
*/
boolean canExtract(ClassTree tree);
}

View File

@@ -0,0 +1,35 @@
package tech.picnic.errorprone.documentation;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.sun.source.tree.ClassTree;
import java.util.EnumSet;
import java.util.Optional;
/** An enumeration of {@link Extractor} types. */
enum ExtractorType {
BUG_PATTERN("bugpattern", new BugPatternExtractor());
private static final ImmutableSet<ExtractorType> TYPES =
Sets.immutableEnumSet(EnumSet.allOf(ExtractorType.class));
private final String identifier;
private final Extractor<?> extractor;
ExtractorType(String identifier, Extractor<?> extractor) {
this.identifier = identifier;
this.extractor = extractor;
}
String getIdentifier() {
return identifier;
}
Extractor<?> getExtractor() {
return extractor;
}
static Optional<ExtractorType> findMatchingType(ClassTree tree) {
return TYPES.stream().filter(type -> type.getExtractor().canExtract(tree)).findFirst();
}
}

View File

@@ -0,0 +1,7 @@
/**
* A Java compiler plugin that extracts data from compiled classes, in support of the Error Prone
* Support documentation.
*/
@com.google.errorprone.annotations.CheckReturnValue
@org.jspecify.annotations.NullMarked
package tech.picnic.errorprone.documentation;

View File

@@ -0,0 +1,153 @@
package tech.picnic.errorprone.documentation;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.io.Resources;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ClassTree;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
final class BugPatternExtractorTest {
@Test
void noBugPattern(@TempDir Path outputDirectory) {
Compilation.compileWithDocumentationGenerator(
outputDirectory,
"TestCheckerWithoutAnnotation.java",
"import com.google.errorprone.bugpatterns.BugChecker;",
"",
"public final class TestCheckerWithoutAnnotation extends BugChecker {}");
assertThat(outputDirectory.toAbsolutePath()).isEmptyDirectory();
}
@Test
void minimalBugPattern(@TempDir Path outputDirectory) throws IOException {
Compilation.compileWithDocumentationGenerator(
outputDirectory,
"MinimalBugChecker.java",
"package pkg;",
"",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"",
"@BugPattern(summary = \"MinimalBugChecker summary\", severity = SeverityLevel.ERROR)",
"public final class MinimalBugChecker extends BugChecker {}");
verifyFileMatchesResource(
outputDirectory,
"bugpattern-MinimalBugChecker.json",
"bugpattern-documentation-minimal.json");
}
@Test
void completeBugPattern(@TempDir Path outputDirectory) throws IOException {
Compilation.compileWithDocumentationGenerator(
outputDirectory,
"CompleteBugChecker.java",
"package pkg;",
"",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"import org.junit.jupiter.api.Test;",
"",
"@BugPattern(",
" name = \"OtherName\",",
" summary = \"CompleteBugChecker summary\",",
" linkType = BugPattern.LinkType.CUSTOM,",
" link = \"https://error-prone.picnic.tech\",",
" explanation = \"Example explanation\",",
" severity = SeverityLevel.SUGGESTION,",
" altNames = \"Check\",",
" tags = BugPattern.StandardTags.SIMPLIFICATION,",
" disableable = false,",
" suppressionAnnotations = {BugPattern.class, Test.class})",
"public final class CompleteBugChecker extends BugChecker {}");
verifyFileMatchesResource(
outputDirectory,
"bugpattern-CompleteBugChecker.json",
"bugpattern-documentation-complete.json");
}
@Test
void undocumentedSuppressionBugPattern(@TempDir Path outputDirectory) throws IOException {
Compilation.compileWithDocumentationGenerator(
outputDirectory,
"UndocumentedSuppressionBugPattern.java",
"package pkg;",
"",
"import com.google.errorprone.BugPattern;",
"import com.google.errorprone.BugPattern.SeverityLevel;",
"import com.google.errorprone.bugpatterns.BugChecker;",
"",
"@BugPattern(",
" summary = \"UndocumentedSuppressionBugPattern summary\",",
" severity = SeverityLevel.WARNING,",
" documentSuppression = false)",
"public final class UndocumentedSuppressionBugPattern extends BugChecker {}");
verifyFileMatchesResource(
outputDirectory,
"bugpattern-UndocumentedSuppressionBugPattern.json",
"bugpattern-documentation-undocumented-suppression.json");
}
@Test
void bugPatternAnnotationIsAbsent() {
CompilationTestHelper.newInstance(TestChecker.class, getClass())
.addSourceLines(
"TestChecker.java",
"import com.google.errorprone.bugpatterns.BugChecker;",
"",
"// BUG: Diagnostic contains: Can extract: false",
"public final class TestChecker extends BugChecker {}")
.doTest();
}
private static void verifyFileMatchesResource(
Path outputDirectory, String fileName, String resourceName) throws IOException {
assertThat(outputDirectory.resolve(fileName))
.content(UTF_8)
.isEqualToIgnoringWhitespace(getResource(resourceName));
}
// XXX: Once we support only JDK 15+, drop this method in favour of including the resources as
// text blocks in this class. (This also requires renaming the `verifyFileMatchesResource`
// method.)
private static String getResource(String resourceName) throws IOException {
return Resources.toString(
Resources.getResource(BugPatternExtractorTest.class, resourceName), UTF_8);
}
/** A {@link BugChecker} that validates the {@link BugPatternExtractor}. */
@BugPattern(summary = "Validates `BugPatternExtractor` extraction", severity = ERROR)
public static final class TestChecker extends BugChecker implements ClassTreeMatcher {
private static final long serialVersionUID = 1L;
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
BugPatternExtractor extractor = new BugPatternExtractor();
assertThatThrownBy(() -> extractor.extract(tree, state.context))
.isInstanceOf(NullPointerException.class)
.hasMessage("BugPattern annotation must be present");
return buildDescription(tree)
.setMessage(String.format("Can extract: %s", extractor.canExtract(tree)))
.build();
}
}
}

View File

@@ -0,0 +1,45 @@
package tech.picnic.errorprone.documentation;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.FileManagers;
import com.google.errorprone.FileObjects;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import java.nio.file.Path;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
// XXX: Generalize and move this class so that it can also be used by `refaster-compiler`.
// XXX: Add support for this class to the `ErrorProneTestHelperSourceFormat` check.
public final class Compilation {
private Compilation() {}
public static void compileWithDocumentationGenerator(
Path outputDirectory, String fileName, String... lines) {
compileWithDocumentationGenerator(outputDirectory.toAbsolutePath().toString(), fileName, lines);
}
public static void compileWithDocumentationGenerator(
String outputDirectory, String fileName, String... lines) {
compile(
ImmutableList.of("-Xplugin:DocumentationGenerator -XoutputDirectory=" + outputDirectory),
FileObjects.forSourceLines(fileName, lines));
}
private static void compile(ImmutableList<String> options, JavaFileObject javaFileObject) {
JavacFileManager javacFileManager = FileManagers.testFileManager();
JavaCompiler compiler = JavacTool.create();
JavacTaskImpl task =
(JavacTaskImpl)
compiler.getTask(
null,
javacFileManager,
null,
options,
ImmutableList.of(),
ImmutableList.of(javaFileObject));
task.call();
}
}

View File

@@ -0,0 +1,77 @@
package tech.picnic.errorprone.documentation;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.nio.file.attribute.AclEntryPermission.ADD_SUBDIRECTORY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.condition.OS.WINDOWS;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclFileAttributeView;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.io.TempDir;
final class DocumentationGeneratorTaskListenerTest {
@EnabledOnOs(WINDOWS)
@Test
void readOnlyFileSystemWindows(@TempDir Path outputDirectory) throws IOException {
AclFileAttributeView view =
Files.getFileAttributeView(outputDirectory, AclFileAttributeView.class);
view.setAcl(
view.getAcl().stream()
.map(
entry ->
AclEntry.newBuilder(entry)
.setPermissions(
Sets.difference(entry.permissions(), ImmutableSet.of(ADD_SUBDIRECTORY)))
.build())
.collect(toImmutableList()));
readOnlyFileSystemFailsToWrite(outputDirectory.resolve("nonexistent"));
}
@DisabledOnOs(WINDOWS)
@Test
void readOnlyFileSystemNonWindows(@TempDir Path outputDirectory) {
assertThat(outputDirectory.toFile().setWritable(false))
.describedAs("Failed to make test directory unwritable")
.isTrue();
readOnlyFileSystemFailsToWrite(outputDirectory.resolve("nonexistent"));
}
private static void readOnlyFileSystemFailsToWrite(Path outputDirectory) {
assertThatThrownBy(
() ->
Compilation.compileWithDocumentationGenerator(
outputDirectory, "A.java", "class A {}"))
.hasRootCauseInstanceOf(FileSystemException.class)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageEndingWith("Error while creating directory with path '%s'", outputDirectory);
}
@Test
void noClassNoOutput(@TempDir Path outputDirectory) {
Compilation.compileWithDocumentationGenerator(outputDirectory, "A.java", "package pkg;");
assertThat(outputDirectory).isEmptyDirectory();
}
@Test
void excessArguments(@TempDir Path outputDirectory) {
assertThatThrownBy(
() ->
Compilation.compileWithDocumentationGenerator(
outputDirectory.toAbsolutePath() + " extra-arg", "A.java", "package pkg;"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Precisely one path must be provided");
}
}

View File

@@ -0,0 +1,38 @@
package tech.picnic.errorprone.documentation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static tech.picnic.errorprone.documentation.DocumentationGenerator.OUTPUT_DIRECTORY_FLAG;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
final class DocumentationGeneratorTest {
@ParameterizedTest
@ValueSource(strings = {"bar", "foo"})
void getOutputPath(String path) {
assertThat(DocumentationGenerator.getOutputPath(OUTPUT_DIRECTORY_FLAG + '=' + path))
.isEqualTo(Path.of(path));
}
@ParameterizedTest
@ValueSource(strings = {"", "-XoutputDirectory", "invalidOption=Test", "nothing"})
void getOutputPathWithInvalidArgument(String pathArg) {
assertThatThrownBy(() -> DocumentationGenerator.getOutputPath(pathArg))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'%s' must be of the form '%s=<value>'", pathArg, OUTPUT_DIRECTORY_FLAG);
}
@Test
void getOutputPathWithInvalidPath() {
String basePath = "path-with-null-char-\0";
assertThatThrownBy(
() -> DocumentationGenerator.getOutputPath(OUTPUT_DIRECTORY_FLAG + '=' + basePath))
.isInstanceOf(IllegalArgumentException.class)
.hasCauseInstanceOf(InvalidPathException.class)
.hasMessageEndingWith("Invalid path '%s'", basePath);
}
}

View File

@@ -0,0 +1,19 @@
{
"fullyQualifiedName": "pkg.CompleteBugChecker",
"name": "OtherName",
"altNames": [
"Check"
],
"link": "https://error-prone.picnic.tech",
"tags": [
"Simplification"
],
"summary": "CompleteBugChecker summary",
"explanation": "Example explanation",
"severityLevel": "SUGGESTION",
"canDisable": false,
"suppressionAnnotations": [
"com.google.errorprone.BugPattern",
"org.junit.jupiter.api.Test"
]
}

View File

@@ -0,0 +1,14 @@
{
"fullyQualifiedName": "pkg.MinimalBugChecker",
"name": "MinimalBugChecker",
"altNames": [],
"link": "",
"tags": [],
"summary": "MinimalBugChecker summary",
"explanation": "",
"severityLevel": "ERROR",
"canDisable": true,
"suppressionAnnotations": [
"java.lang.SuppressWarnings"
]
}

View File

@@ -0,0 +1,12 @@
{
"fullyQualifiedName": "pkg.UndocumentedSuppressionBugPattern",
"name": "UndocumentedSuppressionBugPattern",
"altNames": [],
"link": "",
"tags": [],
"summary": "UndocumentedSuppressionBugPattern summary",
"explanation": "",
"severityLevel": "WARNING",
"canDisable": true,
"suppressionAnnotations": []
}

View File

@@ -11,61 +11,22 @@ request.
### Building
This is a [Maven][maven] project, so running `mvn clean install` performs a
full clean build. Some relevant flags:
- `-Dverification.warn` makes the warnings and errors emitted by various
plugins and the Java compiler non-fatal, where possible.
- `-Dverification.skip` disables various non-essential plugins and compiles the code with
minimal checks (i.e. without linting, Error Prone checks, etc.)
- `-Perror-prone-fork` builds the code and runs the tests against Picnic's
[Error Prone fork][error-prone-fork-repo] (hosted on
[Jitpack][error-prone-fork-jitpack]). Refaster templates are only tested when
the fork is used, because they rely on changes in the unmerged PR
[google/error-prone#1239][[error-prone-issue-1239].
When loading the project in IntelliJ IDEA (and perhaps other IDEs) errors about
the inaccessibility of `com.sun.tools.javac.*` classes may be reported. If this
happens, configure your IDE to enable the `add-exports` profile.
See the main [readme][main-readme].
### Contribution guidelines
To the extend possible, the pull request process guards our coding guidelines.
Some pointers:
- Checks should we _topical_: Ideally they address a single concern.
- Where possible checks should provide _fixes_, and ideally these are
completely behavior preserving. In order for a check to be adopted by users
it must not "get in the way". So for a check which addresses a relatively
trivial stylistic concern it is doubly important that the violations it
detects can be auto-patched.
- Make sure you have read Error Prone's [criteria for new
checks][error-prone-criteria]. Most guidelines described there apply to this
project as well, except that this project _does_ focus quite heavy on style
enforcement. But that just makes the previous point doubly important.
- Make sure that a checks's (mutation) coverage is or remains about as high as
it can be. Not only does this lead to better tests, it also points out
opportunities to simplify the code.
- Please restrict the scope of a pull request to a single feature or fix. Don't
sneak in unrelated changes.
- When in doubt about whether a pull request will be accepted, please first
file an issue to discuss it.
See our [contributing guidelines][main-contributing].
### Our wishlist
We expect the following tasks to help improve the quality of this open source
project:
- Publish the artifact to Maven Central, then document the coordinates in this
`README.md`.
- Document how to enable the checks.
- Document how to apply patches.
- Document each of the checks.
- Add Travis CI, [SonarQube][sonarcloud] and [Codecov][codecov]
integrations.
- Investigate whether it makes sense to include license headers in each file.
If so, set that up and enforce it.
- Add [SonarQube][sonarcloud] and [Codecov][codecov] integrations.
- Add non-Java file formatting support, like we have internally at Picnic.
(I.e., somehow open-source that stuff.)
- Add relevant "badges" at the top of this `README.md`.
- Auto-generate a website listing each of the checks, just like the Error Prone
[bug patterns page][error-prone-bug-patterns]. The [Error Prone
repository][error-prone-repo] contains code for this.
@@ -83,7 +44,7 @@ project:
- Improve an existing check (see `XXX`-marked comments in the code) or write a
new one (see the list of suggestions below).
### Ideas for new checks
### BugChecker extension ideas
The following is a list of checks we'd like to see implemented:
@@ -93,7 +54,7 @@ The following is a list of checks we'd like to see implemented:
signature groups. Using Error Prone's method matchers forbidden method calls
can easily be identified. But Error Prone can go one step further by
auto-patching violations. For each violation two fixes can be proposed: a
purely behavior-preserving fix which makes the platform-dependent behavior
purely behavior-preserving fix, which makes the platform-dependent behavior
explicit, and another which replaces the platform-dependent behavior with the
preferred alternative. (Such as using `UTF-8` instead of the system default
charset.)
@@ -103,144 +64,223 @@ The following is a list of checks we'd like to see implemented:
functionality.
- A subset of the refactor operations provided by the Eclipse-specific
[AutoRefactor][autorefactor] plugin.
- A check which replaces fully qualified types with simple types in contexts
- A check that replaces fully qualified types with simple types in contexts
where this does not introduce ambiguity. Should consider both actual Java
code and Javadoc `@link` references.
- A check which simplifies array expressions. It would replace empty array
- A check that simplifies array expressions. It would replace empty array
expressions of the form `new int[] {}` with `new int[0]`. Statements of the
form `byte[] arr = new byte[] {'c'};` would be shortened to `byte[] arr =
{'c'};`.
- A check which replaces expressions of the form `String.format("some prefix
- A check that replaces expressions of the form `String.format("some prefix
%s", arg)` with `"some prefix " + arg`, and similar for simple suffixes. Can
perhaps be generalized further, though it's unclear how far. (Well, a
`String.format` call without arguments can certainly be simplified, too.)
- A check which replaces single-character strings with `char`s where possible.
- A check that replaces single-character strings with `char`s where possible.
For example as argument to `StringBuilder.append` and in string
concatenations.
- A check which adds or removes the first `Locale` argument to `String.format`
- A check that adds or removes the first `Locale` argument to `String.format`
and similar calls as necessary. (For example, a format string containing only
`%s` placeholders is locale-insensitive unless any of the arguments is a
`Formattable`, while `%f` placeholders _are_ locale-sensitive.)
- A check which replaces `String.replaceAll` with `String.replace` if the first
- A check that replaces `String.replaceAll` with `String.replace` if the first
argument is certainly not a regular expression. And if both arguments are
single-character strings then the `(char, char)` overload can be invoked
instead.
- A check which flags (and ideally, replaces) `try-finally` constructs with
- A check that flags (and ideally, replaces) `try-finally` constructs with
equivalent `try-with-resources` constructs.
- A check which drops exceptions declared in `throws` clauses if they are (a)
- A check that drops exceptions declared in `throws` clauses if they are (a)
not actually thrown and (b) the associated method cannot be overridden.
- A check which tries to statically import certain methods whenever used, if
- A check that tries to statically import certain methods whenever used, if
possible. The set of targeted methods should be configurable, but may default
to e.g. `java.util.Function.identity()`, the static methods exposed by
`java.util.stream.Collectors` and the various Guava collector factory
methods.
- A check which replaces `new Random().someMethod()` calls with
`ThreadLocalRandom.current().someMethod()` calls, so as to avoid unnecessary
- A check that replaces `new Random().someMethod()` calls with
`ThreadLocalRandom.current().someMethod()` calls, to avoid unnecessary
synchronization.
- A check which drops `this.` from `this.someMethod()` calls and which
- A check that drops `this.` from `this.someMethod()` calls and which
optionally does the same for fields, if no ambiguity arises.
- A check which replaces `Integer.valueOf` calls with `Integer.parseInt` or
vice versa in order to prevent auto (un)boxing, and likewise for other number
- A check that replaces `Integer.valueOf` calls with `Integer.parseInt` or vice
versa in order to prevent auto (un)boxing, and likewise for other number
types.
- A check which flags nullable collections.
- A check which flags `AutoCloseable` resources not managed by a
- A check that flags nullable collections.
- A check that flags `AutoCloseable` resources not managed by a
`try-with-resources` construct. Certain subtypes, such as jOOQ's `DSLContext`
should be excluded.
- A check which flags `java.time` methods which implicitly consult the system
- A check that flags `java.time` methods which implicitly consult the system
clock, suggesting that a passed-in `Clock` is used instead.
- A check which flags public methods on public classes which reference
- A check that flags public methods on public classes which reference
non-public types. This can cause `IllegalAccessError`s and
`BootstrapMethodError`s at runtime.
- A check which swaps the LHS and RHS in expressions of the form
- A check that swaps the LHS and RHS in expressions of the form
`nonConstant.equals(someNonNullConstant)`.
- A check which annotates methods which only throw an exception with
- A check that annotates methods which only throw an exception with
`@Deprecated` or ` @DoNotCall`.
- A check which flags imports from other test classes.
- A Guava-specific check which replaces `Joiner.join` calls with `String.join`
- A check that flags imports from other test classes.
- A Guava-specific check that replaces `Joiner.join` calls with `String.join`
calls in those cases where the latter is a proper substitute for the former.
- A Guava-specific check which flags `{Immutable,}Multimap` type usages
where `{Immutable,}{List,Set}Multimap` would be more appropriate.
- A Guava-specific check which rewrites `if (conditional) { throw new
- A Guava-specific check that flags `{Immutable,}Multimap` type usages where
`{Immutable,}{List,Set}Multimap` would be more appropriate.
- A Guava-specific check that rewrites `if (conditional) { throw new
IllegalArgumentException(); }` and variants to an equivalent `checkArgument`
statement. Idem for other exception types.
- A Guava-specific check which replaces simple anonymous `CacheLoader` subclass
- A Guava-specific check that replaces simple anonymous `CacheLoader` subclass
declarations with `CacheLoader.from(someLambda)`.
- A Spring-specific check which enforces that methods with the `@Scheduled`
- A Spring-specific check that enforces that methods with the `@Scheduled`
annotation are also annotated with New Relic's `@Trace` annotation. Such
methods should ideally not also represent Spring MVC endpoints.
- A Spring-specific check which enforces that `@RequestMapping` annotations,
- A Spring-specific check that enforces that `@RequestMapping` annotations,
when applied to a method, explicitly specify one or more target HTTP methods.
- A Spring-specific check which looks for classes in which all
`@RequestMapping` annotations (and the various aliases) specify the same
`path`/`value` property and then moves that path to the class level.
- A Spring-specific check which flags `@Value("some.property")` annotations, as
- A Spring-specific check that looks for classes in which all `@RequestMapping`
annotations (and the various aliases) specify the same `path`/`value`
property and then moves that path to the class level.
- A Spring-specific check that flags `@Value("some.property")` annotations, as
these almost certainly should be `@Value("${some.property}")`.
- A Spring-specific check which drops the `required` attribute from
- A Spring-specific check that drops the `required` attribute from
`@RequestParam` annotations when the `defaultValue` attribute is also
specified.
- A Spring-specific check which rewrites a class which uses field injection to
- A Spring-specific check that rewrites a class which uses field injection to
one which uses constructor injection. This check wouldn't be strictly
behavior preserving, but could be used for a one-off code base migration.
- A Spring-specific check which disallows field injection, except in
- A Spring-specific check that disallows field injection, except in
`AbstractTestNGSpringContextTests` subclasses. (One known edge case:
self-injections so that a bean can call itself through an implicit proxy.)
- A Spring-specific check which verifies that public methods on all classes
- A Spring-specific check that verifies that public methods on all classes
whose name matches a certain pattern, e.g. `.*Service`, are annotated
`@Secured`.
- A Spring-specific check which verifies that annotations such as
- A Spring-specific check that verifies that annotations such as
`@RequestParam` are only present in `@RestController` classes.
- A Spring-specific check which disallows `@ResponseStatus` on MVC endpoint
- A Spring-specific check that disallows `@ResponseStatus` on MVC endpoint
methods, as this prevents communication of error status codes.
- A Hibernate Validator-specific check which looks for `@UnwrapValidatedValue`
- A Hibernate Validator-specific check that looks for `@UnwrapValidatedValue`
usages and migrates the associated constraint annotations to the generic type
argument to which they (are presumed to) apply.
- A TestNG-specific check which drops method-level `@Test` annotations if a
- A TestNG-specific check that drops method-level `@Test` annotations if a
matching/more specific annotation is already present at the class level.
- A TestNG-specific check which enforces that all tests are in a group.
- A TestNG-specific check which flags field assignments in
- A TestNG-specific check that enforces that all tests are in a group.
- A TestNG-specific check that flags field assignments in
`@BeforeMethod`-annotated methods unless the class is annotated
`@Test(singleThreaded = true)`.
- A TestNG-specific check which flags usages of the `expectedExceptions`
- A TestNG-specific check that flags usages of the `expectedExceptions`
attribute of the `@Test` annotation, pointing to `assertThrows`.
- A Jongo-specific check which disallows the creation of sparse indices, in
- A Jongo-specific check that disallows the creation of sparse indices, in
favour of partial indices.
- An Immutables-specific check which replaces
- An Immutables-specific check that replaces
`checkState`/`IllegalStateException` usages inside a `@Value.Check`-annotated
method with `checkArgument`/`IllegalArgument`, since the method is invoked
when a caller attempts to create an immutable instance.
- An Immutables-specific check which disallows references to collection types
- An Immutables-specific check that disallows references to collection types
other than the Guava immutable collections, including inside generic type
arguments.
- An SLF4J-specific check which drops or adds a trailing dot from log messages,
- An SLF4J-specific check that drops or adds a trailing dot from log messages,
as applicable.
- A Mockito-specific check which identifies sequences of statements which mock
a significant number of methods on a single object with "default data"; such
- A Mockito-specific check that identifies sequences of statements which mock a
significant number of methods on a single object with "default data"; such
constructions can often benefit from a different type of default answer, such
as `Answers.RETURNS_MOCKS`.
- An RxJava-specific check which flags `.toCompletable()` calls on expressions
- An RxJava-specific check that flags `.toCompletable()` calls on expressions
of type `Single<Completable>` etc., as most likely
`.flatMapCompletable(Functions.identity())` was meant instead. Idem for other
variations.
- An RxJava-specific check which flags `expr.firstOrError()` calls and suggests
- An RxJava-specific check that flags `expr.firstOrError()` calls and suggests
`expr.switchIfEmpty(Single.error(...))`, so that an application-specific
exception is thrown instead of `NoSuchElementException`.
- An RxJava-specific check which flags use of `#assertValueSet` without
`#assertValueCount`, as the former method doesn't do what one may intuitivily
- An RxJava-specific check that flags use of `#assertValueSet` without
`#assertValueCount`, as the former method doesn't do what one may intuitively
expect it to do. See ReactiveX/RxJava#6151.
### Refaster extension ideas
XXX: This section should live elsewhere.
It's much easier to implement a Refaster rule than an Error Prone bug checker,
but on the flip side Refaster is much less expressive. While this gap can never
be fully closed, there are some ways in which Refaster's scope of utility could
be extended. The following is a non-exhaustive list of ideas on how to extend
Refaster's expressiveness:
- Allow more control over _which_ methods are statically imported by
`@UseImportPolicy`. Sometimes the `@AfterTemplate` contains more than one
static method invocation, and only a subset should be statically imported.
- Provide a way to express that a lambda expression should also match an
equivalent method reference and/or vice versa.
- Provide a way to express that certain method invocations should also be
replaced when expressed as a method reference, or vice versa. (The latter may
be simpler: perhaps the rule `T::m1` -> `T::m2` can optionally be interpreted
to also cover `T.m1(..)` -> `T.m2(...)`.)
- Some Refaster refactorings (e.g. when dealing with lazy evaluation) are valid
only when some free parameter is a constant, variable reference or some other
pure expression. Introduce a way to express such a constraint. For example,
rewriting `optional1.map(Optional::of).orElse(optional2)` to `optional1.or(()
-> optional2)` is not behavior preserving if evaluation of `optional2` has
side effects.
- Similarly, certain refactoring operations are only valid if one of the
matched expressions is not `@Nullable`. It'd be nice to be able to express
this.
- Generalize `@Placeholder` support such that rules can reference e.g. "any
concrete unary method". This would allow refactorings such as
`Mono.just(constant).flatmap(this::someFun)` -> `Mono.defer(() ->
someFun(constant))`.
- Sometimes a Refaster refactoring can cause the resulting code not to compile
due to a lack of generic type information. Identify and resolve such
occurrences. For example, an `@AfterTemplate` may require the insertion of a
statically imported method, which can cause required generic type information
to be lost. In such a case don't statically import the method, so that the
generic type information can be retained. (There may be cases where generic
type information should even be _added_. Find an example.)
- Provide a way to express "match if (not) annotated (with _X_)". See #1 for a
motivating example.
- Provide a way to place match constraints on compile time constants. For
example, "match if this integer is less than 2" or "match if this string
matches the regular expression `X`".
- Provide a way to express transformations of compile-time constants. This
would allow one to e.g. rewrite single-character strings to chars or vice
versa, thereby accommodating a target API. Another example would be to
replace SLF4J's `{}` placeholders with `%s` or vice versa. Yet another
example would be to rewrite `BigDecimal.valueOf("<some-long-value>")` to
`BigDecimal.valueOf(theParsedLongValue)`.
- More generally, investigate ways to plug in fully dynamic behavior, e.g. by
providing hooks which enable plugging in arbitrary
predicates/transformations. The result would be a Refaster/`BugChecker`
hybrid. A feature like this could form the basis for many other features
listed here. (As a concrete example, consider the ability to reference
`com.google.errorprone.matchers.Matcher` implementations.)
- Provide an extension API that enables defining methods or expressions based
on functional properties. A motivating example is the Java Collections
framework, which allows many ways to define (im)mutable (un)ordered
collections with(out) duplicates. One could then express things like "match
any method call that collects its inputs into an immutable ordered list". An
enum analogous to `java.util.stream.Collector.Characteristics` could be used.
Out of the box JDK and Guava collection factory methods could be classified,
with the user having the option to extend the classification.
- Refaster currently unconditionally ignores expressions containing comments.
Provide two additional modes: (a) match and drop the comments or (b)
transport the comments to before/after the replaced expression.
- Extend Refaster to drop imports that become unnecessary as a result of a
refactoring. This e.g. allows one to replace a statically imported TestNG
`fail(...)` invocation with a statically imported equivalent AssertJ
`fail(...)` invocation. (Observe that without an import cleanup this
replacement would cause a compilation error.)
- Extend the `@Repeated` match semantics such that it also covers non-varargs
methods. For a motivating example see google/error-prone#568.
- When matching explicit type references, also match super types. For a
motivating example, see the two subtly different loop definitions in
`CollectionRemoveAllFromCollectionExpression`.
- Figure out why Refaster sometimes doesn't match the correct generic overload.
See the `AssertThatIterableHasOneComparableElementEqualTo` rule for an
example.
[autorefactor]: https://autorefactor.org
[bettercodehub]: https://bettercodehub.com
[checkstyle-external-project-tests]: https://github.com/checkstyle/checkstyle/blob/master/wercker.yml
[codecov]: https://codecov.io
[error-prone-bug-patterns]: http://errorprone.info/bugpatterns
[error-prone-criteria]: http://errorprone.info/docs/criteria
[error-prone-fork-jitpack]: https://jitpack.io/#PicnicSupermarket/error-prone
[error-prone-fork-repo]: https://github.com/PicnicSupermarket/error-prone
[error-prone]: http://errorprone.info
[error-prone-issue-1239]: https://github.com/google/error-prone/pull/1239
[error-prone-bug-patterns]: https://errorprone.info/bugpatterns
[error-prone]: https://errorprone.info
[error-prone-repo]: https://github.com/google/error-prone
[forbidden-apis]: https://github.com/policeman-tools/forbidden-apis
[fossa]: https://fossa.io
[maven]: https://maven.apache.org
[google-java-format]: https://github.com/google/google-java-format
[main-contributing]: ../CONTRIBUTING.md
[main-readme]: ../README.md
[modernizer-maven-plugin]: https://github.com/gaul/modernizer-maven-plugin
[sonarcloud]: https://sonarcloud.io

View File

@@ -5,7 +5,7 @@
<parent>
<groupId>tech.picnic.error-prone-support</groupId>
<artifactId>error-prone-support</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.9.0</version>
</parent>
<artifactId>error-prone-contrib</artifactId>
@@ -37,41 +37,55 @@
<dependency>
<groupId>${groupId.error-prone}</groupId>
<artifactId>error_prone_test_helpers</artifactId>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-resource-compiler</artifactId>
<artifactId>documentation-support</artifactId>
<!-- This dependency is declared only as a hint to Maven that
compilation depends on it; see the `maven-compiler-plugin`'s
`annotationProcessorPaths` configuration below. -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-support</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-test-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.auto</groupId>
<artifactId>auto-common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>javac</artifactId>
<scope>provided</scope>
<groupId>com.google.googlejavaformat</groupId>
<artifactId>google-java-format</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.newrelic.agent.java</groupId>
<artifactId>newrelic-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
@@ -87,6 +101,11 @@
<artifactId>reactor-adapter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.projectreactor.addons</groupId>
<artifactId>reactor-extra</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
@@ -97,20 +116,45 @@
<artifactId>swagger-annotations</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.immutables</groupId>
<artifactId>value-annotations</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
@@ -120,7 +164,12 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.reactivestreams</groupId>
@@ -134,13 +183,28 @@
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<artifactId>spring-context</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
@@ -152,15 +216,6 @@
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>com.coveo</groupId>
<artifactId>fmt-maven-plugin</artifactId>
<configuration>
<additionalSourceDirectories>
<additionalSourceDirectory>${basedir}/src/test/resources</additionalSourceDirectory>
</additionalSourceDirectories>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -168,15 +223,37 @@
<annotationProcessorPaths combine.children="append">
<path>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-resource-compiler</artifactId>
<artifactId>documentation-support</artifactId>
<version>${project.version}</version>
</path>
<path>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-compiler</artifactId>
<version>${project.version}</version>
</path>
<path>
<groupId>${project.groupId}</groupId>
<artifactId>refaster-support</artifactId>
<version>${project.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs combine.children="append">
<arg>-Xplugin:RefasterRuleResourceCompiler</arg>
<arg>-Xplugin:RefasterRuleCompiler</arg>
<arg>-Xplugin:DocumentationGenerator -XoutputDirectory=${project.build.directory}/docs</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<configuration>
<ignoredUnusedDeclaredDependencies>
<!-- XXX: Figure out why the plugin thinks this
dependency is unused. -->
<ignoredUnusedDeclaredDependency>${project.groupId}:refaster-support</ignoredUnusedDeclaredDependency>
</ignoredUnusedDeclaredDependencies>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

View File

@@ -0,0 +1,72 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.Matchers.isType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import java.util.Map;
import javax.lang.model.element.AnnotationValue;
/** A {@link BugChecker} that flags ambiguous {@code @JsonCreator}s in enums. */
@AutoService(BugChecker.class)
@BugPattern(
summary = "`JsonCreator.Mode` should be set for single-argument creators",
link = BUG_PATTERNS_BASE_URL + "AmbiguousJsonCreator",
linkType = CUSTOM,
severity = WARNING,
tags = LIKELY_ERROR)
public final class AmbiguousJsonCreator extends BugChecker implements AnnotationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<AnnotationTree> IS_JSON_CREATOR_ANNOTATION =
isType("com.fasterxml.jackson.annotation.JsonCreator");
/** Instantiates a new {@link AmbiguousJsonCreator} instance. */
public AmbiguousJsonCreator() {}
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (!IS_JSON_CREATOR_ANNOTATION.matches(tree, state)) {
return Description.NO_MATCH;
}
ClassTree clazz = state.findEnclosing(ClassTree.class);
if (clazz == null || clazz.getKind() != Tree.Kind.ENUM) {
return Description.NO_MATCH;
}
MethodTree method = state.findEnclosing(MethodTree.class);
if (method == null || method.getParameters().size() != 1) {
return Description.NO_MATCH;
}
boolean customMode =
ASTHelpers.getAnnotationMirror(tree).getElementValues().entrySet().stream()
.filter(entry -> entry.getKey().getSimpleName().contentEquals("mode"))
.map(Map.Entry::getValue)
.map(AnnotationValue::getValue)
.filter(Symbol.VarSymbol.class::isInstance)
.map(Symbol.VarSymbol.class::cast)
.anyMatch(varSymbol -> !varSymbol.getSimpleName().contentEquals("DEFAULT"));
return customMode
? Description.NO_MATCH
: describeMatch(
tree, SuggestedFix.replace(tree, "@JsonCreator(mode = JsonCreator.Mode.DELEGATING)"));
}
}

View File

@@ -0,0 +1,62 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.argumentCount;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.nullLiteral;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodInvocationTree;
/**
* A {@link BugChecker} that flags AssertJ {@code isEqualTo(null)} checks for simplification.
*
* <p>This bug checker cannot be replaced with a simple Refaster rule, as the Refaster approach
* would require that all overloads of {@link org.assertj.core.api.Assert#isEqualTo(Object)} (such
* as {@link org.assertj.core.api.AbstractStringAssert#isEqualTo(String)}) are explicitly
* enumerated. This bug checker generically matches all such current and future overloads.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer `.isNull()` over `.isEqualTo(null)`",
link = BUG_PATTERNS_BASE_URL + "AssertJIsNull",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class AssertJIsNull extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<MethodInvocationTree> ASSERT_IS_EQUAL_TO_NULL =
allOf(
instanceMethod().onDescendantOf("org.assertj.core.api.Assert").named("isEqualTo"),
argumentCount(1),
argument(0, nullLiteral()));
/** Instantiates a new {@link AssertJIsNull} instance. */
public AssertJIsNull() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!ASSERT_IS_EQUAL_TO_NULL.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fix =
SuggestedFix.builder().merge(SuggestedFixes.renameMethodInvocation(tree, "isNull", state));
tree.getArguments().forEach(arg -> fix.merge(SuggestedFix.delete(arg)));
return describeMatch(tree, fix.build());
}
}

View File

@@ -0,0 +1,67 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.isType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.List;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} that flags redundant {@code @Autowired} constructor annotations. */
@AutoService(BugChecker.class)
@BugPattern(
summary = "Omit `@Autowired` on a class' sole constructor, as it is redundant",
link = BUG_PATTERNS_BASE_URL + "AutowiredConstructor",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class AutowiredConstructor extends BugChecker implements ClassTreeMatcher {
private static final long serialVersionUID = 1L;
private static final MultiMatcher<Tree, AnnotationTree> AUTOWIRED_ANNOTATION =
annotations(AT_LEAST_ONE, isType("org.springframework.beans.factory.annotation.Autowired"));
/** Instantiates a new {@link AutowiredConstructor} instance. */
public AutowiredConstructor() {}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
List<MethodTree> constructors = ASTHelpers.getConstructors(tree);
if (constructors.size() != 1) {
return Description.NO_MATCH;
}
ImmutableList<AnnotationTree> annotations =
AUTOWIRED_ANNOTATION
.multiMatchResult(Iterables.getOnlyElement(constructors), state)
.matchingNodes();
if (annotations.size() != 1) {
return Description.NO_MATCH;
}
/*
* This is the only `@Autowired` constructor: suggest that it be removed. Note that this likely
* means that the associated import can be removed as well. Rather than adding code for this case we
* leave flagging the unused import to Error Prone's `RemoveUnusedImports` check.
*/
AnnotationTree annotation = Iterables.getOnlyElement(annotations);
return describeMatch(annotation, SourceCode.deleteWithTrailingWhitespace(annotation, state));
}
}

View File

@@ -1,68 +0,0 @@
package tech.picnic.errorprone.bugpatterns;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.AnnotationType;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/** A {@link BugChecker} which flags redundant {@code @Autowired} constructor annotations. */
@AutoService(BugChecker.class)
@BugPattern(
name = "AutowiredConstructor",
summary = "Omit `@Autowired` on a class' sole constructor, as it is redundant",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.SIMPLIFICATION,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class AutowiredConstructorCheck extends BugChecker implements AnnotationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<AnnotationTree> AUTOWIRED_ANNOTATION =
new AnnotationType("org.springframework.beans.factory.annotation.Autowired");
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (!AUTOWIRED_ANNOTATION.matches(tree, state)) {
return Description.NO_MATCH;
}
if (!isWithinConstructor(state)) {
return Description.NO_MATCH;
}
ClassTree clazz = state.findEnclosing(ClassTree.class);
if (clazz == null || ASTHelpers.getConstructors(clazz).size() != 1) {
return Description.NO_MATCH;
}
/*
* This is the only `@Autowired` constructor: suggest that it be removed. Note that this likely
* means that the associated import can be removed as well. Rather than adding code for this case we
* leave flagging the unused import to Error Prone's `RemoveUnusedImports` check.
*/
return describeMatch(tree, SuggestedFix.delete(tree));
}
private static boolean isWithinConstructor(VisitorState state) {
MethodTree method = state.findEnclosing(MethodTree.class);
if (method == null) {
return false;
}
MethodSymbol sym = ASTHelpers.getSymbol(method);
return sym != null && sym.isConstructor();
}
}

View File

@@ -1,22 +1,23 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.AnnotationMatcherUtils;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.Tree.Kind;
import java.util.ArrayList;
@@ -25,26 +26,28 @@ import java.util.Optional;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} which flags annotations that could be written more concisely. */
/** A {@link BugChecker} that flags annotations that could be written more concisely. */
@AutoService(BugChecker.class)
@BugPattern(
name = "CanonicalAnnotationSyntax",
summary = "Omit redundant syntax from annotation declarations",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.SIMPLIFICATION,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class CanonicalAnnotationSyntaxCheck extends BugChecker
implements AnnotationTreeMatcher {
link = BUG_PATTERNS_BASE_URL + "CanonicalAnnotationSyntax",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class CanonicalAnnotationSyntax extends BugChecker implements AnnotationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Pattern TRAILING_ARRAY_COMMA = Pattern.compile(",\\s*}$");
private static final ImmutableSet<BiFunction<AnnotationTree, VisitorState, Optional<Fix>>>
FIX_FACTORIES =
ImmutableSet.of(
CanonicalAnnotationSyntaxCheck::dropRedundantParentheses,
CanonicalAnnotationSyntaxCheck::dropRedundantValueAttribute,
CanonicalAnnotationSyntaxCheck::dropRedundantCurlies);
CanonicalAnnotationSyntax::dropRedundantParentheses,
CanonicalAnnotationSyntax::dropRedundantValueAttribute,
CanonicalAnnotationSyntax::dropRedundantCurlies);
/** Instantiates a new {@link CanonicalAnnotationSyntax} instance. */
public CanonicalAnnotationSyntax() {}
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
@@ -86,26 +89,26 @@ public final class CanonicalAnnotationSyntaxCheck extends BugChecker
}
ExpressionTree arg = args.get(0);
if (arg.getKind() != Kind.ASSIGNMENT) {
/* Evidently `value` isn't assigned to explicitly. */
if (state.getSourceForNode(arg) == null) {
/*
* The annotation argument isn't doesn't have a source representation, e.g. because `value`
* isn't assigned to explicitly.
*/
return Optional.empty();
}
AssignmentTree assignment = (AssignmentTree) arg;
ExpressionTree variable = assignment.getVariable();
if (variable.getKind() != Kind.IDENTIFIER
|| !((IdentifierTree) variable).getName().contentEquals("value")
|| state.getSourceForNode(variable) == null) {
ExpressionTree expr = AnnotationMatcherUtils.getArgument(tree, "value");
if (expr == null) {
/* This is not an explicit assignment to the `value` attribute. */
return Optional.empty();
}
/* Replace the assignment with (the simplified representation of) just its value. */
ExpressionTree expr = assignment.getExpression();
return Optional.of(
SuggestedFix.replace(
arg,
simplifyAttributeValue(expr, state).orElseGet(() -> Util.treeToString(expr, state))));
simplifyAttributeValue(expr, state)
.orElseGet(() -> SourceCode.treeToString(expr, state))));
}
private static Optional<Fix> dropRedundantCurlies(AnnotationTree tree, VisitorState state) {
@@ -140,11 +143,11 @@ public final class CanonicalAnnotationSyntaxCheck extends BugChecker
private static Optional<String> simplifySingletonArray(NewArrayTree array, VisitorState state) {
return Optional.of(array.getInitializers())
.filter(initializers -> initializers.size() == 1)
.map(initializers -> Util.treeToString(initializers.get(0), state));
.map(initializers -> SourceCode.treeToString(initializers.get(0), state));
}
private static Optional<String> dropTrailingComma(NewArrayTree array, VisitorState state) {
String src = Util.treeToString(array, state);
String src = SourceCode.treeToString(array, state);
return Optional.of(TRAILING_ARRAY_COMMA.matcher(src))
.filter(Matcher::find)
.map(m -> src.substring(0, m.start()) + '}');

View File

@@ -0,0 +1,124 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.stream.Collector;
import tech.picnic.errorprone.bugpatterns.util.ThirdPartyLibrary;
/**
* A {@link BugChecker} that flags {@link Collector Collectors} that don't clearly express
* (im)mutability.
*
* <p>Replacing such collectors with alternatives that produce immutable collections is preferred.
* Do note that Guava's immutable collections are null-hostile.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary =
"Avoid `Collectors.to{List,Map,Set}` in favour of alternatives that emphasize (im)mutability",
link = BUG_PATTERNS_BASE_URL + "CollectorMutability",
linkType = CUSTOM,
severity = WARNING,
tags = FRAGILE_CODE)
public final class CollectorMutability extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> COLLECTOR_METHOD =
staticMethod().onClass("java.util.stream.Collectors");
private static final Matcher<ExpressionTree> LIST_COLLECTOR =
staticMethod().anyClass().named("toList");
private static final Matcher<ExpressionTree> MAP_COLLECTOR =
staticMethod().anyClass().named("toMap");
private static final Matcher<ExpressionTree> SET_COLLECTOR =
staticMethod().anyClass().named("toSet");
/** Instantiates a new {@link CollectorMutability} instance. */
public CollectorMutability() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!ThirdPartyLibrary.GUAVA.isIntroductionAllowed(state)
|| !COLLECTOR_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
if (LIST_COLLECTOR.matches(tree, state)) {
return suggestToCollectionAlternatives(
tree, "com.google.common.collect.ImmutableList.toImmutableList", "ArrayList", state);
}
if (MAP_COLLECTOR.matches(tree, state)) {
return suggestToMapAlternatives(tree, state);
}
if (SET_COLLECTOR.matches(tree, state)) {
return suggestToCollectionAlternatives(
tree, "com.google.common.collect.ImmutableSet.toImmutableSet", "HashSet", state);
}
return Description.NO_MATCH;
}
private Description suggestToCollectionAlternatives(
MethodInvocationTree tree,
String fullyQualifiedImmutableReplacement,
String mutableReplacement,
VisitorState state) {
SuggestedFix.Builder mutableFix = SuggestedFix.builder();
String toCollectionSelect =
SuggestedFixes.qualifyStaticImport(
"java.util.stream.Collectors.toCollection", mutableFix, state);
return buildDescription(tree)
.addFix(replaceMethodInvocation(tree, fullyQualifiedImmutableReplacement, state))
.addFix(
mutableFix
.addImport(String.format("java.util.%s", mutableReplacement))
.replace(tree, String.format("%s(%s::new)", toCollectionSelect, mutableReplacement))
.build())
.build();
}
private Description suggestToMapAlternatives(MethodInvocationTree tree, VisitorState state) {
int argCount = tree.getArguments().size();
if (argCount > 3) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.addFix(
replaceMethodInvocation(
tree, "com.google.common.collect.ImmutableMap.toImmutableMap", state))
.addFix(
SuggestedFix.builder()
.addImport("java.util.HashMap")
.postfixWith(
tree.getArguments().get(argCount - 1),
(argCount == 2 ? ", (a, b) -> { throw new IllegalStateException(); }" : "")
+ ", HashMap::new")
.build())
.build();
}
private static SuggestedFix replaceMethodInvocation(
MethodInvocationTree tree, String fullyQualifiedReplacement, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
String replacement = SuggestedFixes.qualifyStaticImport(fullyQualifiedReplacement, fix, state);
fix.merge(SuggestedFix.replace(tree.getMethodSelect(), replacement));
return fix.build();
}
}

View File

@@ -0,0 +1,131 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isVariable;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.returnStatement;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.Matchers.toType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.BlockTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import java.util.List;
import java.util.Optional;
import tech.picnic.errorprone.bugpatterns.util.MoreASTHelpers;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags unnecessary local variable assignments preceding a return
* statement.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Variable assignment is redundant; value can be returned directly",
link = BUG_PATTERNS_BASE_URL + "DirectReturn",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class DirectReturn extends BugChecker implements BlockTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<StatementTree> VARIABLE_RETURN = returnStatement(isVariable());
private static final Matcher<ExpressionTree> MOCKITO_MOCK_OR_SPY_WITH_IMPLICIT_TYPE =
allOf(
not(toType(MethodInvocationTree.class, argument(0, isSameType(Class.class.getName())))),
staticMethod().onClass("org.mockito.Mockito").namedAnyOf("mock", "spy"));
/** Instantiates a new {@link DirectReturn} instance. */
public DirectReturn() {}
@Override
public Description matchBlock(BlockTree tree, VisitorState state) {
List<? extends StatementTree> statements = tree.getStatements();
if (statements.size() < 2) {
return Description.NO_MATCH;
}
StatementTree finalStatement = statements.get(statements.size() - 1);
if (!VARIABLE_RETURN.matches(finalStatement, state)) {
return Description.NO_MATCH;
}
Symbol variableSymbol = ASTHelpers.getSymbol(((ReturnTree) finalStatement).getExpression());
StatementTree precedingStatement = statements.get(statements.size() - 2);
return tryMatchAssignment(variableSymbol, precedingStatement)
.filter(resultExpr -> canInlineToReturnStatement(resultExpr, state))
.map(
resultExpr ->
describeMatch(
precedingStatement,
SuggestedFix.builder()
.replace(
precedingStatement,
String.format("return %s;", SourceCode.treeToString(resultExpr, state)))
.delete(finalStatement)
.build()))
.orElse(Description.NO_MATCH);
}
private static Optional<ExpressionTree> tryMatchAssignment(Symbol targetSymbol, Tree tree) {
if (tree instanceof ExpressionStatementTree) {
return tryMatchAssignment(targetSymbol, ((ExpressionStatementTree) tree).getExpression());
}
if (tree instanceof AssignmentTree) {
AssignmentTree assignment = (AssignmentTree) tree;
return targetSymbol.equals(ASTHelpers.getSymbol(assignment.getVariable()))
? Optional.of(assignment.getExpression())
: Optional.empty();
}
if (tree instanceof VariableTree) {
VariableTree declaration = (VariableTree) tree;
return declaration.getModifiers().getAnnotations().isEmpty()
&& targetSymbol.equals(ASTHelpers.getSymbol(declaration))
? Optional.ofNullable(declaration.getInitializer())
: Optional.empty();
}
return Optional.empty();
}
/**
* Tells whether inlining the given expression to the associated return statement can be done
* safely.
*
* <p>Inlining is generally safe, but in rare cases the operation may have a functional impact.
* The sole case considered here is the inlining of a Mockito mock or spy construction without an
* explicit type. In such a case the type created depends on context, such as the method's return
* type.
*/
private static boolean canInlineToReturnStatement(
ExpressionTree expressionTree, VisitorState state) {
return !MOCKITO_MOCK_OR_SPY_WITH_IMPLICIT_TYPE.matches(expressionTree, state)
|| MoreASTHelpers.findMethodExitedOnReturn(state)
.filter(m -> MoreASTHelpers.areSameType(expressionTree, m.getReturnType(), state))
.isPresent();
}
}

View File

@@ -0,0 +1,67 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.Optional;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} that flags empty methods that seemingly can simply be deleted. */
@AutoService(BugChecker.class)
@BugPattern(
summary = "Empty method can likely be deleted",
link = BUG_PATTERNS_BASE_URL + "EmptyMethod",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class EmptyMethod extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<Tree> PERMITTED_ANNOTATION =
annotations(
AT_LEAST_ONE,
anyOf(isType("java.lang.Override"), isType("org.aspectj.lang.annotation.Pointcut")));
/** Instantiates a new {@link EmptyMethod} instance. */
public EmptyMethod() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getBody() == null
|| !tree.getBody().getStatements().isEmpty()
|| ASTHelpers.containsComments(tree, state)
|| PERMITTED_ANNOTATION.matches(tree, state)
|| isInPossibleTestHelperClass(state)) {
return Description.NO_MATCH;
}
if (ASTHelpers.methodCanBeOverridden(ASTHelpers.getSymbol(tree))) {
return Description.NO_MATCH;
}
return describeMatch(tree, SourceCode.deleteWithTrailingWhitespace(tree, state));
}
private static boolean isInPossibleTestHelperClass(VisitorState state) {
return Optional.ofNullable(ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class))
.map(ClassTree::getSimpleName)
.filter(name -> name.toString().contains("Test"))
.isPresent();
}
}

View File

@@ -1,44 +0,0 @@
package tech.picnic.errorprone.bugpatterns;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/** A {@link BugChecker} which flags empty methods that seemingly can simply be deleted. */
@AutoService(BugChecker.class)
@BugPattern(
name = "EmptyMethod",
summary = "Empty method can likely be deleted",
linkType = LinkType.NONE,
severity = SeverityLevel.WARNING,
tags = StandardTags.SIMPLIFICATION,
providesFix = BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class EmptyMethodCheck extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getBody() == null || !tree.getBody().getStatements().isEmpty()) {
return Description.NO_MATCH;
}
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (sym == null
|| ASTHelpers.methodCanBeOverridden(sym)
|| ASTHelpers.hasAnnotation(sym, "java.lang.Override", state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFix.delete(tree));
}
}

View File

@@ -0,0 +1,165 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.Splitter;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;
import com.google.googlejavaformat.java.ImportOrderer;
import com.google.googlejavaformat.java.JavaFormatterOptions.Style;
import com.google.googlejavaformat.java.RemoveUnusedImports;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.util.Position;
import java.util.List;
import java.util.Optional;
/**
* A {@link BugChecker} that flags improperly formatted Error Prone test code.
*
* <p>All test code should be formatted in accordance with Google Java Format's {@link Formatter}
* output, and imports should be ordered according to the {@link Style#GOOGLE Google} style.
*
* <p>This checker inspects inline code passed to {@code
* com.google.errorprone.CompilationTestHelper} and {@code
* com.google.errorprone.BugCheckerRefactoringTestHelper}. It requires that this code is properly
* formatted and that its imports are organized. Only code that represents the expected output of a
* refactoring operation is allowed to have unused imports, as most {@link BugChecker}s do not (and
* are not able to) remove imports that become obsolete as a result of applying their suggested
* fix(es).
*/
// XXX: Once we target JDK 17 (optionally?) suggest text block fixes.
// XXX: GJF guesses the line separator to be used by inspecting the source. When using text blocks
// this may cause the current unconditional use of `\n` not to be sufficient when building on
// Windows; TBD.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Test code should follow the Google Java style",
link = BUG_PATTERNS_BASE_URL + "ErrorProneTestHelperSourceFormat",
linkType = CUSTOM,
severity = SUGGESTION,
tags = STYLE)
public final class ErrorProneTestHelperSourceFormat extends BugChecker
implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Formatter FORMATTER = new Formatter();
private static final Matcher<ExpressionTree> INPUT_SOURCE_ACCEPTING_METHOD =
anyOf(
instanceMethod()
.onDescendantOf("com.google.errorprone.CompilationTestHelper")
.named("addSourceLines"),
instanceMethod()
.onDescendantOf("com.google.errorprone.BugCheckerRefactoringTestHelper")
.named("addInputLines"));
private static final Matcher<ExpressionTree> OUTPUT_SOURCE_ACCEPTING_METHOD =
instanceMethod()
.onDescendantOf("com.google.errorprone.BugCheckerRefactoringTestHelper.ExpectOutput")
.named("addOutputLines");
/** Instantiates a new {@link ErrorProneTestHelperSourceFormat} instance. */
public ErrorProneTestHelperSourceFormat() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
boolean isOutputSource = OUTPUT_SOURCE_ACCEPTING_METHOD.matches(tree, state);
if (!isOutputSource && !INPUT_SOURCE_ACCEPTING_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> sourceLines =
tree.getArguments().subList(1, tree.getArguments().size());
if (sourceLines.isEmpty()) {
return buildDescription(tree).setMessage("No source code provided").build();
}
int startPos = ASTHelpers.getStartPosition(sourceLines.get(0));
int endPos = state.getEndPosition(sourceLines.get(sourceLines.size() - 1));
/* Attempt to format the source code only if it fully consists of constant expressions. */
return getConstantSourceCode(sourceLines)
.map(source -> flagFormattingIssues(startPos, endPos, source, isOutputSource, state))
.orElse(Description.NO_MATCH);
}
private Description flagFormattingIssues(
int startPos, int endPos, String source, boolean retainUnusedImports, VisitorState state) {
Tree methodInvocation = state.getPath().getLeaf();
String formatted;
try {
formatted = formatSourceCode(source, retainUnusedImports).trim();
} catch (FormatterException e) {
return buildDescription(methodInvocation)
.setMessage(String.format("Source code is malformed: %s", e.getMessage()))
.build();
}
if (source.trim().equals(formatted)) {
return Description.NO_MATCH;
}
if (startPos == Position.NOPOS || endPos == Position.NOPOS) {
/*
* We have insufficient source information to emit a fix, so we only flag the fact that the
* code isn't properly formatted.
*/
return describeMatch(methodInvocation);
}
/*
* The code isn't properly formatted; replace all lines with the properly formatted
* alternatives.
*/
return describeMatch(
methodInvocation,
SuggestedFix.replace(
startPos,
endPos,
Splitter.on('\n')
.splitToStream(formatted)
.map(state::getConstantExpression)
.collect(joining(", "))));
}
private static String formatSourceCode(String source, boolean retainUnusedImports)
throws FormatterException {
String withReorderedImports = ImportOrderer.reorderImports(source, Style.GOOGLE);
String withOptionallyRemovedImports =
retainUnusedImports
? withReorderedImports
: RemoveUnusedImports.removeUnusedImports(withReorderedImports);
return FORMATTER.formatSource(withOptionallyRemovedImports);
}
private static Optional<String> getConstantSourceCode(
List<? extends ExpressionTree> sourceLines) {
StringBuilder source = new StringBuilder();
for (ExpressionTree sourceLine : sourceLines) {
Object value = ASTHelpers.constValue(sourceLine);
if (value == null) {
return Optional.empty();
}
source.append(value).append('\n');
}
return Optional.of(source.toString());
}
}

View File

@@ -0,0 +1,94 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static java.util.stream.Collectors.collectingAndThen;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
/**
* A {@link BugChecker} that flags {@link Ordering#explicit(Object, Object[])}} invocations listing
* a subset of an enum type's values.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Make sure `Ordering#explicit` lists all of an enum's values",
link = BUG_PATTERNS_BASE_URL + "ExplicitEnumOrdering",
linkType = CUSTOM,
severity = WARNING,
tags = FRAGILE_CODE)
public final class ExplicitEnumOrdering extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> EXPLICIT_ORDERING =
staticMethod().onClass(Ordering.class.getName()).named("explicit");
/** Instantiates a new {@link ExplicitEnumOrdering} instance. */
public ExplicitEnumOrdering() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!EXPLICIT_ORDERING.matches(tree, state)) {
return Description.NO_MATCH;
}
ImmutableSet<String> missingEnumValues = getMissingEnumValues(tree.getArguments());
if (missingEnumValues.isEmpty()) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
String.format(
"Explicit ordering lacks some enum values: %s",
String.join(", ", missingEnumValues)))
.build();
}
private static ImmutableSet<String> getMissingEnumValues(
List<? extends ExpressionTree> expressions) {
return expressions.stream()
.map(ASTHelpers::getSymbol)
.filter(Symbol::isEnum)
.collect(
collectingAndThen(
toImmutableSetMultimap(Symbol::asType, Symbol::toString),
ExplicitEnumOrdering::getMissingEnumValues));
}
private static ImmutableSet<String> getMissingEnumValues(
ImmutableSetMultimap<Type, String> valuesByType) {
return Multimaps.asMap(valuesByType).entrySet().stream()
.flatMap(e -> getMissingEnumValues(e.getKey(), e.getValue()))
.collect(toImmutableSet());
}
private static Stream<String> getMissingEnumValues(Type enumType, Set<String> values) {
Symbol.TypeSymbol typeSymbol = enumType.asElement();
return Sets.difference(ASTHelpers.enumValues(typeSymbol), values).stream()
.map(v -> String.join(".", typeSymbol.getSimpleName(), v));
}
}

View File

@@ -0,0 +1,116 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.generic;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.subOf;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.type;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.unbound;
import com.google.auto.service.AutoService;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import java.util.function.Function;
import reactor.core.publisher.Flux;
/**
* A {@link BugChecker} that flags usages of {@link Flux#flatMap(Function)} and {@link
* Flux#flatMapSequential(Function)}.
*
* <p>{@link Flux#flatMap(Function)} and {@link Flux#flatMapSequential(Function)} eagerly perform up
* to {@link reactor.util.concurrent.Queues#SMALL_BUFFER_SIZE} subscriptions. Additionally, the
* former interleaves values as they are emitted, yielding nondeterministic results. In most cases
* {@link Flux#concatMap(Function)} should be preferred, as it produces consistent results and
* avoids potentially saturating the thread pool on which subscription happens. If {@code
* concatMap}'s sequential-subscription semantics are undesirable one should invoke a {@code
* flatMap} or {@code flatMapSequential} overload with an explicit concurrency level.
*
* <p>NB: The rarely-used overload {@link Flux#flatMap(Function, Function,
* java.util.function.Supplier)} is not flagged by this check because there is no clear alternative
* to point to.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary =
"`Flux#flatMap` and `Flux#flatMapSequential` have subtle semantics; "
+ "please use `Flux#concatMap` or explicitly specify the desired amount of concurrency",
link = BUG_PATTERNS_BASE_URL + "FluxFlatMapUsage",
linkType = CUSTOM,
severity = ERROR,
tags = LIKELY_ERROR)
public final class FluxFlatMapUsage extends BugChecker
implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String MAX_CONCURRENCY_ARG_NAME = "MAX_CONCURRENCY";
private static final Supplier<Type> FLUX =
Suppliers.typeFromString("reactor.core.publisher.Flux");
private static final Matcher<ExpressionTree> FLUX_FLATMAP =
instanceMethod()
.onDescendantOf(FLUX)
.namedAnyOf("flatMap", "flatMapSequential")
.withParameters(Function.class.getName());
private static final Supplier<Type> FLUX_OF_PUBLISHERS =
VisitorState.memoize(
generic(FLUX, subOf(generic(type("org.reactivestreams.Publisher"), unbound()))));
/** Instantiates a new {@link FluxFlatMapUsage} instance. */
public FluxFlatMapUsage() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!FLUX_FLATMAP.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix serializationFix = SuggestedFixes.renameMethodInvocation(tree, "concatMap", state);
SuggestedFix concurrencyCapFix =
SuggestedFix.builder()
.postfixWith(
Iterables.getOnlyElement(tree.getArguments()), ", " + MAX_CONCURRENCY_ARG_NAME)
.build();
Description.Builder description = buildDescription(tree);
if (state.getTypes().isSubtype(ASTHelpers.getType(tree), FLUX_OF_PUBLISHERS.get(state))) {
/*
* Nested publishers may need to be subscribed to eagerly in order to avoid a deadlock, e.g.
* if they are produced by `Flux#groupBy`. In this case we suggest specifying an explicit
* concurrently bound, in favour of sequential subscriptions using `Flux#concatMap`.
*/
description.addFix(concurrencyCapFix).addFix(serializationFix);
} else {
description.addFix(serializationFix).addFix(concurrencyCapFix);
}
return description.build();
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!FLUX_FLATMAP.matches(tree, state)) {
return Description.NO_MATCH;
}
// Method references are expected to occur very infrequently; generating both variants of
// suggested fixes is not worth the trouble.
return describeMatch(tree);
}
}

View File

@@ -0,0 +1,100 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.base.Preconditions.checkState;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.CONCURRENCY;
import static com.google.errorprone.BugPattern.StandardTags.PERFORMANCE;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
import java.util.stream.Stream;
import tech.picnic.errorprone.bugpatterns.util.ThirdPartyLibrary;
/**
* A {@link BugChecker} that flags {@link reactor.core.publisher.Flux} operator usages that may
* implicitly cause the calling thread to be blocked.
*
* <p>Note that the methods flagged here are not themselves blocking, but iterating over the
* resulting {@link Iterable} or {@link Stream} may be.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Avoid iterating over `Flux`es in an implicitly blocking manner",
link = BUG_PATTERNS_BASE_URL + "FluxImplicitBlock",
linkType = CUSTOM,
severity = WARNING,
tags = {CONCURRENCY, PERFORMANCE})
public final class FluxImplicitBlock extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> FLUX_WITH_IMPLICIT_BLOCK =
instanceMethod()
.onDescendantOf("reactor.core.publisher.Flux")
.namedAnyOf("toIterable", "toStream")
.withNoParameters();
private static final Supplier<Type> STREAM = Suppliers.typeFromString(Stream.class.getName());
/** Instantiates a new {@link FluxImplicitBlock} instance. */
public FluxImplicitBlock() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!FLUX_WITH_IMPLICIT_BLOCK.matches(tree, state)) {
return Description.NO_MATCH;
}
Description.Builder description =
buildDescription(tree).addFix(SuggestedFixes.addSuppressWarnings(state, canonicalName()));
if (ThirdPartyLibrary.GUAVA.isIntroductionAllowed(state)) {
description.addFix(
suggestBlockingElementCollection(
tree, "com.google.common.collect.ImmutableList.toImmutableList", state));
}
description.addFix(
suggestBlockingElementCollection(tree, "java.util.stream.Collectors.toList", state));
return description.build();
}
private static SuggestedFix suggestBlockingElementCollection(
MethodInvocationTree tree, String fullyQualifiedCollectorMethod, VisitorState state) {
SuggestedFix.Builder importSuggestion = SuggestedFix.builder();
String replacementMethodInvocation =
SuggestedFixes.qualifyStaticImport(fullyQualifiedCollectorMethod, importSuggestion, state);
boolean isStream =
ASTHelpers.isSubtype(ASTHelpers.getResultType(tree), STREAM.get(state), state);
String replacement =
String.format(
".collect(%s()).block()%s", replacementMethodInvocation, isStream ? ".stream()" : "");
return importSuggestion.merge(replaceMethodInvocation(tree, replacement, state)).build();
}
private static SuggestedFix.Builder replaceMethodInvocation(
MethodInvocationTree tree, String replacement, VisitorState state) {
int startPosition = state.getEndPosition(ASTHelpers.getReceiver(tree));
int endPosition = state.getEndPosition(tree);
checkState(
startPosition != Position.NOPOS && endPosition != Position.NOPOS,
"Cannot locate method to be replaced in source code");
return SuggestedFix.builder().replace(startPosition, endPosition, replacement);
}
}

View File

@@ -0,0 +1,259 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.SimpleTreeVisitor;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags string concatenations that produce a format string; in such cases
* the string concatenation should instead be deferred to the invoked method.
*
* @implNote This checker is based on the implementation of {@link
* com.google.errorprone.bugpatterns.flogger.FloggerStringConcatenation}.
*/
// XXX: Support arbitrary `@FormatMethod`-annotated methods.
// XXX: For (explicit or delegated) invocations of `java.util.Formatter` _strictly speaking_ we
// should introduce special handling of `Formattable` arguments, as this check would replace a
// `Formattable#toString` invocation with a `Formattable#formatTo` invocation. But likely that
// should be considered a bug fix, too.
// XXX: Introduce a separate check that adds/removes the `Locale` parameter to `String.format`
// invocations, as necessary. See also a comment in the `StringJoin` check.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Defer string concatenation to the invoked method",
link = BUG_PATTERNS_BASE_URL + "FormatStringConcatenation",
linkType = CUSTOM,
severity = WARNING,
tags = SIMPLIFICATION)
public final class FormatStringConcatenation extends BugChecker
implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
/**
* AssertJ exposes varargs {@code fail} methods with a {@link Throwable}-accepting overload, the
* latter of which should not be flagged.
*/
private static final Matcher<ExpressionTree> ASSERTJ_FAIL_WITH_THROWABLE_METHOD =
anyMethod()
.anyClass()
.withAnyName()
.withParameters(String.class.getName(), Throwable.class.getName());
// XXX: Drop some of these methods if we use Refaster to replace some with others.
private static final Matcher<ExpressionTree> ASSERTJ_FORMAT_METHOD =
anyOf(
instanceMethod()
.onDescendantOf("org.assertj.core.api.AbstractAssert")
.namedAnyOf("overridingErrorMessage", "withFailMessage"),
allOf(
instanceMethod()
.onDescendantOf("org.assertj.core.api.AbstractSoftAssertions")
.named("fail"),
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)),
instanceMethod()
.onDescendantOf("org.assertj.core.api.AbstractStringAssert")
.named("isEqualTo"),
instanceMethod()
.onDescendantOf("org.assertj.core.api.AbstractThrowableAssert")
.namedAnyOf(
"hasMessage",
"hasMessageContaining",
"hasMessageEndingWith",
"hasMessageStartingWith",
"hasRootCauseMessage",
"hasStackTraceContaining"),
instanceMethod()
.onDescendantOf("org.assertj.core.api.Descriptable")
.namedAnyOf("as", "describedAs"),
instanceMethod()
.onDescendantOf("org.assertj.core.api.ThrowableAssertAlternative")
.namedAnyOf(
"withMessage",
"withMessageContaining",
"withMessageEndingWith",
"withMessageStartingWith",
"withStackTraceContaining"),
allOf(
instanceMethod().onDescendantOf("org.assertj.core.api.WithAssertions").named("fail"),
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)),
allOf(
staticMethod()
.onClassAny(
"org.assertj.core.api.Assertions",
"org.assertj.core.api.BDDAssertions",
"org.assertj.core.api.Fail")
.named("fail"),
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)));
private static final Matcher<ExpressionTree> GUAVA_FORMAT_METHOD =
anyOf(
staticMethod()
.onClass("com.google.common.base.Preconditions")
.namedAnyOf("checkArgument", "checkNotNull", "checkState"),
staticMethod().onClass("com.google.common.base.Verify").named("verify"));
// XXX: Add `PrintWriter`, maybe others.
private static final Matcher<ExpressionTree> JDK_FORMAT_METHOD =
anyOf(
staticMethod().onClass("java.lang.String").named("format"),
instanceMethod().onExactClass("java.util.Formatter").named("format"));
private static final Matcher<ExpressionTree> SLF4J_FORMAT_METHOD =
instanceMethod()
.onDescendantOf("org.slf4j.Logger")
.namedAnyOf("debug", "error", "info", "trace", "warn");
/** Instantiates a new {@link FormatStringConcatenation} instance. */
public FormatStringConcatenation() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (hasNonConstantStringConcatenationArgument(tree, 0, state)) {
return flagViolation(tree, ASSERTJ_FORMAT_METHOD, 0, "%s", state)
.or(() -> flagViolation(tree, JDK_FORMAT_METHOD, 0, "%s", state))
.or(() -> flagViolation(tree, SLF4J_FORMAT_METHOD, 0, "{}", state))
.orElse(Description.NO_MATCH);
}
if (hasNonConstantStringConcatenationArgument(tree, 1, state)) {
return flagViolation(tree, GUAVA_FORMAT_METHOD, 1, "%s", state)
.or(() -> flagViolation(tree, JDK_FORMAT_METHOD, 1, "%s", state))
.or(() -> flagViolation(tree, SLF4J_FORMAT_METHOD, 1, "{}", state))
.orElse(Description.NO_MATCH);
}
return Description.NO_MATCH;
}
/**
* Flags the given method invocation if it matches a targeted method and passes a non-compile time
* constant string concatenation as a format string.
*/
private Optional<Description> flagViolation(
MethodInvocationTree tree,
Matcher<ExpressionTree> matcher,
int formatStringParam,
String formatSpecifier,
VisitorState state) {
if (!matcher.matches(tree, state)) {
/* The invoked method is not targeted by this check. */
return Optional.empty();
}
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.size() > formatStringParam + 1) {
/*
* This method invocation uses explicit string concatenation but _also_ already relies on
* format specifiers: flag but don't suggest a fix.
*/
return Optional.of(describeMatch(tree));
}
ExpressionTree formatStringArg = arguments.get(formatStringParam);
ReplacementArgumentsConstructor replacementConstructor =
new ReplacementArgumentsConstructor(formatSpecifier);
formatStringArg.accept(replacementConstructor, state);
return Optional.of(
describeMatch(
tree,
SuggestedFix.replace(
formatStringArg, replacementConstructor.getReplacementArguments(state))));
}
private static boolean hasNonConstantStringConcatenationArgument(
MethodInvocationTree tree, int argPosition, VisitorState state) {
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.size() <= argPosition) {
/* This method doesn't accept enough parameters. */
return false;
}
ExpressionTree argument = ASTHelpers.stripParentheses(arguments.get(argPosition));
return argument instanceof BinaryTree
&& isStringTyped(argument, state)
&& ASTHelpers.constValue(argument, String.class) == null;
}
private static boolean isStringTyped(ExpressionTree tree, VisitorState state) {
return ASTHelpers.isSameType(ASTHelpers.getType(tree), state.getSymtab().stringType, state);
}
private static class ReplacementArgumentsConstructor
extends SimpleTreeVisitor<@Nullable Void, VisitorState> {
private final StringBuilder formatString = new StringBuilder();
private final List<Tree> formatArguments = new ArrayList<>();
private final String formatSpecifier;
ReplacementArgumentsConstructor(String formatSpecifier) {
this.formatSpecifier = formatSpecifier;
}
@Override
public @Nullable Void visitBinary(BinaryTree tree, VisitorState state) {
if (tree.getKind() == Kind.PLUS && isStringTyped(tree, state)) {
tree.getLeftOperand().accept(this, state);
tree.getRightOperand().accept(this, state);
} else {
appendExpression(tree);
}
return null;
}
@Override
public @Nullable Void visitParenthesized(ParenthesizedTree tree, VisitorState state) {
return tree.getExpression().accept(this, state);
}
@Override
protected @Nullable Void defaultAction(Tree tree, VisitorState state) {
appendExpression(tree);
return null;
}
private void appendExpression(Tree tree) {
if (tree instanceof LiteralTree) {
formatString.append(((LiteralTree) tree).getValue());
} else {
formatString.append(formatSpecifier);
formatArguments.add(tree);
}
}
private String getReplacementArguments(VisitorState state) {
return state.getConstantExpression(formatString.toString())
+ ", "
+ formatArguments.stream()
.map(tree -> SourceCode.treeToString(tree, state))
.collect(joining(", "));
}
}
}

View File

@@ -0,0 +1,128 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.suppliers.Suppliers.OBJECT_TYPE;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.primitives.Primitives;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.TypesWithUndefinedEquality;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ASTHelpers.TargetType;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.Arrays;
import java.util.List;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} that flags redundant identity conversions. */
// XXX: Consider detecting cases where a flagged expression is passed to a method, and where removal
// of the identity conversion would cause a different method overload to be selected. Depending on
// the target method such a modification may change the code's semantics or performance.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Avoid or clarify identity conversions",
link = BUG_PATTERNS_BASE_URL + "IdentityConversion",
linkType = CUSTOM,
severity = WARNING,
tags = SIMPLIFICATION)
public final class IdentityConversion extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> IS_CONVERSION_METHOD =
anyOf(
staticMethod()
.onClassAny(
Primitives.allWrapperTypes().stream()
.map(Class::getName)
.collect(toImmutableSet()))
.named("valueOf"),
staticMethod().onClass(String.class.getName()).named("valueOf"),
staticMethod()
.onClassAny(
"com.google.common.collect.ImmutableBiMap",
"com.google.common.collect.ImmutableList",
"com.google.common.collect.ImmutableListMultimap",
"com.google.common.collect.ImmutableMap",
"com.google.common.collect.ImmutableMultimap",
"com.google.common.collect.ImmutableMultiset",
"com.google.common.collect.ImmutableRangeMap",
"com.google.common.collect.ImmutableRangeSet",
"com.google.common.collect.ImmutableSet",
"com.google.common.collect.ImmutableSetMultimap",
"com.google.common.collect.ImmutableTable")
.named("copyOf"),
staticMethod()
.onClass("com.google.errorprone.matchers.Matchers")
.namedAnyOf("allOf", "anyOf"),
staticMethod().onClass("reactor.adapter.rxjava.RxJava2Adapter"),
staticMethod()
.onClass("reactor.core.publisher.Flux")
.namedAnyOf("concat", "firstWithSignal", "from", "merge"),
staticMethod().onClass("reactor.core.publisher.Mono").namedAnyOf("from", "fromDirect"));
/** Instantiates a new {@link IdentityConversion} instance. */
public IdentityConversion() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.size() != 1 || !IS_CONVERSION_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree sourceTree = arguments.get(0);
Type sourceType = ASTHelpers.getType(sourceTree);
Type resultType = ASTHelpers.getType(tree);
TargetType targetType = ASTHelpers.targetType(state);
if (sourceType == null || resultType == null || targetType == null) {
return Description.NO_MATCH;
}
if (!state.getTypes().isSameType(sourceType, resultType)
&& !isConvertibleWithWellDefinedEquality(sourceType, targetType.type(), state)) {
return Description.NO_MATCH;
}
if (sourceType.isPrimitive()
&& state.getPath().getParentPath().getLeaf() instanceof MemberSelectTree) {
/*
* The result of the conversion method is dereferenced, while the source type is a primitive:
* dropping the conversion would yield uncompilable code.
*/
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
"This method invocation appears redundant; remove it or suppress this warning and "
+ "add a comment explaining its purpose")
.addFix(SuggestedFix.replace(tree, SourceCode.treeToString(sourceTree, state)))
.addFix(SuggestedFixes.addSuppressWarnings(state, canonicalName()))
.build();
}
private static boolean isConvertibleWithWellDefinedEquality(
Type sourceType, Type targetType, VisitorState state) {
Types types = state.getTypes();
return !types.isSameType(targetType, OBJECT_TYPE.get(state))
&& types.isConvertible(sourceType, targetType)
&& Arrays.stream(TypesWithUndefinedEquality.values())
.noneMatch(b -> b.matchesType(sourceType, state) || b.matchesType(targetType, state));
}
}

View File

@@ -0,0 +1,86 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.not;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import java.util.SortedSet;
import javax.lang.model.element.Modifier;
/**
* A {@link BugChecker} that flags {@link SortedSet} property declarations inside
* {@code @Value.Immutable}- and {@code @Value.Modifiable}-annotated types that lack a
* {@code @Value.NaturalOrder} or {@code @Value.ReverseOrder} annotation.
*
* <p>Without such an annotation:
*
* <ul>
* <li>deserialization of the enclosing type requires that the associated JSON property is
* present, contrary to the way in which Immutables handles other collection properties; and
* <li>different instances may use different comparator implementations (e.g. deserialization
* would default to natural order sorting), potentially leading to subtle bugs.
* </ul>
*/
@AutoService(BugChecker.class)
@BugPattern(
summary =
"`SortedSet` properties of a `@Value.Immutable` or `@Value.Modifiable` type must be "
+ "annotated with `@Value.NaturalOrder` or `@Value.ReverseOrder`",
link = BUG_PATTERNS_BASE_URL + "ImmutablesSortedSetComparator",
linkType = CUSTOM,
severity = ERROR,
tags = LIKELY_ERROR)
public final class ImmutablesSortedSetComparator extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<MethodTree> METHOD_LACKS_ANNOTATION =
allOf(
methodReturns(isSubtypeOf(SortedSet.class)),
anyOf(
allOf(
hasModifier(Modifier.ABSTRACT),
enclosingClass(
anyOf(
hasAnnotation("org.immutables.value.Value.Immutable"),
hasAnnotation("org.immutables.value.Value.Modifiable")))),
hasAnnotation("org.immutables.value.Value.Default")),
not(
anyOf(
hasAnnotation("org.immutables.value.Value.NaturalOrder"),
hasAnnotation("org.immutables.value.Value.ReverseOrder"))));
/** Instantiates a new {@link ImmutablesSortedSetComparator} instance. */
public ImmutablesSortedSetComparator() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!METHOD_LACKS_ANNOTATION.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder builder = SuggestedFix.builder();
String valueTypeIdentifier =
SuggestedFixes.qualifyType(state, builder, "org.immutables.value.Value");
return describeMatch(
tree,
builder.prefixWith(tree, String.format("@%s.NaturalOrder ", valueTypeIdentifier)).build());
}
}

View File

@@ -0,0 +1,60 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags lambda expressions that can be replaced with a method reference
* of the form {@code T.class::isInstance}.
*
* @see MethodReferenceUsage
*/
// XXX: Consider folding this logic into the `MethodReferenceUsage` check.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer `Class::isInstance` method reference over equivalent lambda expression",
link = BUG_PATTERNS_BASE_URL + "IsInstanceLambdaUsage",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class IsInstanceLambdaUsage extends BugChecker implements LambdaExpressionTreeMatcher {
private static final long serialVersionUID = 1L;
/** Instantiates a new {@link IsInstanceLambdaUsage} instance. */
public IsInstanceLambdaUsage() {}
@Override
public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) {
if (tree.getParameters().size() != 1 || tree.getBody().getKind() != Kind.INSTANCE_OF) {
return Description.NO_MATCH;
}
VariableTree param = Iterables.getOnlyElement(tree.getParameters());
InstanceOfTree instanceOf = (InstanceOfTree) tree.getBody();
if (!ASTHelpers.getSymbol(param).equals(ASTHelpers.getSymbol(instanceOf.getExpression()))) {
return Description.NO_MATCH;
}
return describeMatch(
tree,
SuggestedFix.replace(
tree, SourceCode.treeToString(instanceOf.getType(), state) + ".class::isInstance"));
}
}

View File

@@ -0,0 +1,82 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasMethod;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.not;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import static tech.picnic.errorprone.bugpatterns.util.MoreJUnitMatchers.TEST_METHOD;
import static tech.picnic.errorprone.bugpatterns.util.MoreMatchers.hasMetaAnnotation;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
import javax.lang.model.element.Modifier;
/**
* A {@link BugChecker} that flags non-final and non package-private JUnit test class declarations,
* unless abstract.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Non-abstract JUnit test classes should be declared package-private and final",
linkType = CUSTOM,
link = BUG_PATTERNS_BASE_URL + "JUnitClassModifiers",
severity = SUGGESTION,
tags = STYLE)
public final class JUnitClassModifiers extends BugChecker implements ClassTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ClassTree> HAS_SPRING_CONFIGURATION_ANNOTATION =
annotations(
AT_LEAST_ONE,
anyOf(
isType("org.springframework.context.annotation.Configuration"),
hasMetaAnnotation("org.springframework.context.annotation.Configuration")));
private static final Matcher<ClassTree> TEST_CLASS_WITH_INCORRECT_MODIFIERS =
allOf(
hasMethod(TEST_METHOD),
not(hasModifier(Modifier.ABSTRACT)),
anyOf(
hasModifier(Modifier.PRIVATE),
hasModifier(Modifier.PROTECTED),
hasModifier(Modifier.PUBLIC),
allOf(not(hasModifier(Modifier.FINAL)), not(HAS_SPRING_CONFIGURATION_ANNOTATION))));
/** Instantiates a new {@link JUnitClassModifiers} instance. */
public JUnitClassModifiers() {}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!TEST_CLASS_WITH_INCORRECT_MODIFIERS.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
SuggestedFixes.removeModifiers(
tree.getModifiers(),
state,
ImmutableSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC))
.ifPresent(fixBuilder::merge);
if (!HAS_SPRING_CONFIGURATION_ANNOTATION.matches(tree, state)) {
SuggestedFixes.addModifiers(tree, state, Modifier.FINAL).ifPresent(fixBuilder::merge);
}
return describeMatch(tree, fixBuilder.build());
}
}

View File

@@ -0,0 +1,118 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.not;
import static java.util.function.Predicate.not;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import static tech.picnic.errorprone.bugpatterns.util.MoreJUnitMatchers.SETUP_OR_TEARDOWN_METHOD;
import static tech.picnic.errorprone.bugpatterns.util.MoreJUnitMatchers.TEST_METHOD;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import java.util.Optional;
import javax.lang.model.element.Modifier;
import tech.picnic.errorprone.bugpatterns.util.ConflictDetection;
/** A {@link BugChecker} that flags non-canonical JUnit method declarations. */
// XXX: Consider introducing a class-level check that enforces that test classes:
// 1. Are named `*Test` or `Abstract*TestCase`.
// 2. If not `abstract`, are package-private and don't have public methods and subclasses.
// 3. Only have private fields.
// XXX: If implemented, the current logic could flag only `private` JUnit methods.
@AutoService(BugChecker.class)
@BugPattern(
summary = "JUnit method declaration can likely be improved",
link = BUG_PATTERNS_BASE_URL + "JUnitMethodDeclaration",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class JUnitMethodDeclaration extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String TEST_PREFIX = "test";
private static final ImmutableSet<Modifier> ILLEGAL_MODIFIERS =
Sets.immutableEnumSet(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC);
private static final Matcher<MethodTree> IS_LIKELY_OVERRIDDEN =
allOf(
not(hasModifier(Modifier.FINAL)),
not(hasModifier(Modifier.PRIVATE)),
enclosingClass(hasModifier(Modifier.ABSTRACT)));
/** Instantiates a new {@link JUnitMethodDeclaration} instance. */
public JUnitMethodDeclaration() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (IS_LIKELY_OVERRIDDEN.matches(tree, state) || isOverride(tree, state)) {
return Description.NO_MATCH;
}
boolean isTestMethod = TEST_METHOD.matches(tree, state);
if (!isTestMethod && !SETUP_OR_TEARDOWN_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
SuggestedFixes.removeModifiers(tree.getModifiers(), state, ILLEGAL_MODIFIERS)
.ifPresent(fixBuilder::merge);
if (isTestMethod) {
suggestTestMethodRenameIfApplicable(tree, fixBuilder, state);
}
return fixBuilder.isEmpty() ? Description.NO_MATCH : describeMatch(tree, fixBuilder.build());
}
private void suggestTestMethodRenameIfApplicable(
MethodTree tree, SuggestedFix.Builder fixBuilder, VisitorState state) {
MethodSymbol symbol = ASTHelpers.getSymbol(tree);
tryCanonicalizeMethodName(symbol)
.ifPresent(
newName ->
ConflictDetection.findMethodRenameBlocker(symbol, newName, state)
.ifPresentOrElse(
blocker -> reportMethodRenameBlocker(tree, blocker, state),
() -> fixBuilder.merge(SuggestedFixes.renameMethod(tree, newName, state))));
}
private void reportMethodRenameBlocker(MethodTree tree, String reason, VisitorState state) {
state.reportMatch(
buildDescription(tree)
.setMessage(
String.format(
"This method's name should not redundantly start with `%s` (but note that %s)",
TEST_PREFIX, reason))
.build());
}
private static Optional<String> tryCanonicalizeMethodName(MethodSymbol symbol) {
return Optional.of(symbol.getQualifiedName().toString())
.filter(name -> name.startsWith(TEST_PREFIX))
.map(name -> name.substring(TEST_PREFIX.length()))
.filter(not(String::isEmpty))
.map(name -> Character.toLowerCase(name.charAt(0)) + name.substring(1))
.filter(name -> !Character.isDigit(name.charAt(0)));
}
private static boolean isOverride(MethodTree tree, VisitorState state) {
return ASTHelpers.streamSuperMethods(ASTHelpers.getSymbol(tree), state.getTypes())
.findAny()
.isPresent();
}
}

View File

@@ -0,0 +1,307 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.anything;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.argumentCount;
import static com.google.errorprone.matchers.Matchers.classLiteral;
import static com.google.errorprone.matchers.Matchers.hasArguments;
import static com.google.errorprone.matchers.Matchers.isPrimitiveOrBoxedPrimitiveType;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.Matchers.toType;
import static java.util.function.Predicate.not;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import static tech.picnic.errorprone.bugpatterns.util.MoreJUnitMatchers.HAS_METHOD_SOURCE;
import static tech.picnic.errorprone.bugpatterns.util.MoreJUnitMatchers.getMethodSourceFactoryNames;
import com.google.auto.service.AutoService;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags JUnit tests with a {@link
* org.junit.jupiter.params.provider.MethodSource} annotation that can be replaced with an
* equivalent {@link org.junit.jupiter.params.provider.ValueSource} annotation.
*/
// XXX: Where applicable, also flag `@MethodSource` annotations that reference multiple value
// factory methods (or that repeat the same value factory method multiple times).
// XXX: Support inlining of overloaded value factory methods.
// XXX: Support inlining of value factory methods referenced by multiple `@MethodSource`
// annotations.
// XXX: Support value factory return expressions of the form `Stream.of(a, b,
// c).map(Arguments::argument)`.
// XXX: Support simplification of test methods that accept additional injected parameters such as
// `TestInfo`; such parameters should be ignored for the purpose of this check.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer `@ValueSource` over a `@MethodSource` where possible and reasonable",
linkType = CUSTOM,
link = BUG_PATTERNS_BASE_URL + "JUnitValueSource",
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class JUnitValueSource extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> SUPPORTED_VALUE_FACTORY_VALUES =
anyOf(
isArrayArgumentValueCandidate(),
toType(
MethodInvocationTree.class,
allOf(
staticMethod()
.onClass("org.junit.jupiter.params.provider.Arguments")
.namedAnyOf("arguments", "of"),
argumentCount(1),
argument(0, isArrayArgumentValueCandidate()))));
private static final Matcher<ExpressionTree> ARRAY_OF_SUPPORTED_SINGLE_VALUE_ARGUMENTS =
isSingleDimensionArrayCreationWithAllElementsMatching(SUPPORTED_VALUE_FACTORY_VALUES);
private static final Matcher<ExpressionTree> ENUMERATION_OF_SUPPORTED_SINGLE_VALUE_ARGUMENTS =
toType(
MethodInvocationTree.class,
allOf(
staticMethod()
.onClassAny(
Stream.class.getName(),
IntStream.class.getName(),
LongStream.class.getName(),
DoubleStream.class.getName(),
List.class.getName(),
Set.class.getName(),
"com.google.common.collect.ImmutableList",
"com.google.common.collect.ImmutableSet")
.named("of"),
hasArguments(AT_LEAST_ONE, anything()),
hasArguments(ALL, SUPPORTED_VALUE_FACTORY_VALUES)));
private static final Matcher<MethodTree> IS_UNARY_METHOD_WITH_SUPPORTED_PARAMETER =
methodHasParameters(
anyOf(
isPrimitiveOrBoxedPrimitiveType(),
isSameType(String.class),
isSameType(state -> state.getSymtab().classType)));
/** Instantiates a new {@link JUnitValueSource} instance. */
public JUnitValueSource() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!IS_UNARY_METHOD_WITH_SUPPORTED_PARAMETER.matches(tree, state)) {
return Description.NO_MATCH;
}
Type parameterType = ASTHelpers.getType(Iterables.getOnlyElement(tree.getParameters()));
return findMethodSourceAnnotation(tree, state)
.flatMap(
methodSourceAnnotation ->
getSoleLocalFactoryName(methodSourceAnnotation, tree)
.filter(factory -> !hasSiblingReferencingValueFactory(tree, factory, state))
.flatMap(factory -> findSiblingWithName(tree, factory, state))
.flatMap(
factoryMethod ->
tryConstructValueSourceFix(
parameterType, methodSourceAnnotation, factoryMethod, state))
.map(fix -> describeMatch(methodSourceAnnotation, fix)))
.orElse(Description.NO_MATCH);
}
/**
* Returns the name of the value factory method pointed to by the given {@code @MethodSource}
* annotation, if it (a) is the only one and (b) is a method in the same class as the annotated
* method.
*/
private static Optional<String> getSoleLocalFactoryName(
AnnotationTree methodSourceAnnotation, MethodTree method) {
return getElementIfSingleton(getMethodSourceFactoryNames(methodSourceAnnotation, method))
.filter(name -> name.indexOf('#') < 0);
}
/**
* Tells whether the given method has a sibling method in the same class that depends on the
* specified value factory method.
*/
private static boolean hasSiblingReferencingValueFactory(
MethodTree tree, String valueFactory, VisitorState state) {
return findMatchingSibling(tree, m -> hasValueFactory(m, valueFactory, state), state)
.isPresent();
}
private static Optional<MethodTree> findSiblingWithName(
MethodTree tree, String methodName, VisitorState state) {
return findMatchingSibling(tree, m -> m.getName().contentEquals(methodName), state);
}
private static Optional<MethodTree> findMatchingSibling(
MethodTree tree, Predicate<? super MethodTree> predicate, VisitorState state) {
return state.findEnclosing(ClassTree.class).getMembers().stream()
.filter(MethodTree.class::isInstance)
.map(MethodTree.class::cast)
.filter(not(tree::equals))
.filter(predicate)
.findFirst();
}
private static boolean hasValueFactory(
MethodTree tree, String valueFactoryMethodName, VisitorState state) {
return findMethodSourceAnnotation(tree, state).stream()
.anyMatch(
annotation ->
getMethodSourceFactoryNames(annotation, tree).contains(valueFactoryMethodName));
}
private static Optional<AnnotationTree> findMethodSourceAnnotation(
MethodTree tree, VisitorState state) {
return HAS_METHOD_SOURCE.multiMatchResult(tree, state).matchingNodes().stream().findFirst();
}
private static Optional<SuggestedFix> tryConstructValueSourceFix(
Type parameterType,
AnnotationTree methodSourceAnnotation,
MethodTree valueFactoryMethod,
VisitorState state) {
return getSingleReturnExpression(valueFactoryMethod)
.flatMap(expression -> tryExtractValueSourceAttributeValue(expression, state))
.map(
valueSourceAttributeValue ->
SuggestedFix.builder()
.addImport("org.junit.jupiter.params.provider.ValueSource")
.replace(
methodSourceAnnotation,
String.format(
"@ValueSource(%s = %s)",
toValueSourceAttributeName(parameterType), valueSourceAttributeValue))
.delete(valueFactoryMethod)
.build());
}
// XXX: This pattern also occurs a few times inside Error Prone; contribute upstream.
private static Optional<ExpressionTree> getSingleReturnExpression(MethodTree methodTree) {
List<ExpressionTree> returnExpressions = new ArrayList<>();
new TreeScanner<@Nullable Void, @Nullable Void>() {
@Override
public @Nullable Void visitClass(ClassTree node, @Nullable Void unused) {
/* Ignore `return` statements inside anonymous/local classes. */
return null;
}
@Override
public @Nullable Void visitReturn(ReturnTree node, @Nullable Void unused) {
returnExpressions.add(node.getExpression());
return super.visitReturn(node, unused);
}
@Override
public @Nullable Void visitLambdaExpression(
LambdaExpressionTree node, @Nullable Void unused) {
/* Ignore `return` statements inside lambda expressions. */
return null;
}
}.scan(methodTree, null);
return getElementIfSingleton(returnExpressions);
}
private static Optional<String> tryExtractValueSourceAttributeValue(
ExpressionTree tree, VisitorState state) {
List<? extends ExpressionTree> arguments;
if (ENUMERATION_OF_SUPPORTED_SINGLE_VALUE_ARGUMENTS.matches(tree, state)) {
arguments = ((MethodInvocationTree) tree).getArguments();
} else if (ARRAY_OF_SUPPORTED_SINGLE_VALUE_ARGUMENTS.matches(tree, state)) {
arguments = ((NewArrayTree) tree).getInitializers();
} else {
return Optional.empty();
}
/*
* Join the values into a comma-separated string, unwrapping `Arguments` factory method
* invocations if applicable.
*/
return Optional.of(
arguments.stream()
.map(
arg ->
arg instanceof MethodInvocationTree
? Iterables.getOnlyElement(((MethodInvocationTree) arg).getArguments())
: arg)
.map(argument -> SourceCode.treeToString(argument, state))
.collect(joining(", ")))
.map(value -> arguments.size() > 1 ? String.format("{%s}", value) : value);
}
private static String toValueSourceAttributeName(Type type) {
String typeString = type.tsym.name.toString();
switch (typeString) {
case "Class":
return "classes";
case "Character":
return "chars";
case "Integer":
return "ints";
default:
return typeString.toLowerCase(Locale.ROOT) + 's';
}
}
private static <T> Optional<T> getElementIfSingleton(Collection<T> collection) {
return Optional.of(collection)
.filter(elements -> elements.size() == 1)
.map(Iterables::getOnlyElement);
}
private static Matcher<ExpressionTree> isSingleDimensionArrayCreationWithAllElementsMatching(
Matcher<? super ExpressionTree> elementMatcher) {
return (tree, state) -> {
if (!(tree instanceof NewArrayTree)) {
return false;
}
NewArrayTree newArray = (NewArrayTree) tree;
return newArray.getDimensions().isEmpty()
&& !newArray.getInitializers().isEmpty()
&& newArray.getInitializers().stream()
.allMatch(element -> elementMatcher.matches(element, state));
};
}
private static Matcher<ExpressionTree> isArrayArgumentValueCandidate() {
return anyOf(classLiteral(anything()), (tree, state) -> ASTHelpers.constValue(tree) != null);
}
}

View File

@@ -1,16 +1,20 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static java.util.Comparator.comparing;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.Splitter;
import com.google.common.collect.Comparators;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
@@ -31,28 +35,30 @@ import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
import tech.picnic.errorprone.bugpatterns.util.AnnotationAttributeMatcher;
import tech.picnic.errorprone.bugpatterns.util.Flags;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} which flags annotation array listings which aren't sorted lexicographically.
* A {@link BugChecker} that flags annotation array listings which aren't sorted lexicographically.
*
* <p>The idea behind this checker is that maintaining a sorted sequence simplifies conflict
* resolution, and can even avoid it if two branches add the same entry.
*/
@AutoService(BugChecker.class)
@BugPattern(
name = "LexicographicalAnnotationAttributeListing",
summary = "Where possible, sort annotation array attributes lexicographically",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.STYLE,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class LexicographicalAnnotationAttributeListingCheck extends BugChecker
link = BUG_PATTERNS_BASE_URL + "LexicographicalAnnotationAttributeListing",
linkType = CUSTOM,
severity = SUGGESTION,
tags = STYLE)
public final class LexicographicalAnnotationAttributeListing extends BugChecker
implements AnnotationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final ImmutableSet<String> BLACKLISTED_ANNOTATIONS =
@@ -60,24 +66,34 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
// XXX: unless JsonPropertyOrder#alphabetic is true...
"com.fasterxml.jackson.annotation.JsonPropertyOrder#value",
"io.swagger.annotations.ApiImplicitParams#value",
"javax.xml.bind.annotation.XmlType#propOrder");
"io.swagger.v3.oas.annotations.Parameters#value",
"javax.xml.bind.annotation.XmlType#propOrder",
"org.springframework.context.annotation.PropertySource#value",
"org.springframework.test.context.TestPropertySource#locations",
"org.springframework.test.context.TestPropertySource#value");
private static final String FLAG_PREFIX = "LexicographicalAnnotationAttributeListing:";
private static final String INCLUDED_ANNOTATIONS_FLAG = FLAG_PREFIX + "Includes";
private static final String EXCLUDED_ANNOTATIONS_FLAG = FLAG_PREFIX + "Excludes";
/**
* The splitter applied to string-typed annotation arguments prior to lexicographical sorting. By
* splitting on {@code =}, strings that represent e.g. inline Spring property declarations are
* properly sorted by key, then value.
*/
private static final Splitter STRING_ARGUMENT_SPLITTER = Splitter.on('=');
private final AnnotationAttributeMatcher matcher;
/** Instantiates the default {@link LexicographicalAnnotationAttributeListingCheck}. */
public LexicographicalAnnotationAttributeListingCheck() {
/** Instantiates a default {@link LexicographicalAnnotationAttributeListing} instance. */
public LexicographicalAnnotationAttributeListing() {
this(ErrorProneFlags.empty());
}
/**
* Instantiates a customized {@link LexicographicalAnnotationAttributeListingCheck}.
* Instantiates a customized {@link LexicographicalAnnotationAttributeListing}.
*
* @param flags Any provided command line flags.
*/
public LexicographicalAnnotationAttributeListingCheck(ErrorProneFlags flags) {
public LexicographicalAnnotationAttributeListing(ErrorProneFlags flags) {
matcher = createAnnotationAttributeMatcher(flags);
}
@@ -119,7 +135,7 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
}
List<? extends ExpressionTree> actualOrdering = array.getInitializers();
ImmutableList<? extends ExpressionTree> desiredOrdering = doSort(actualOrdering, state);
ImmutableList<? extends ExpressionTree> desiredOrdering = doSort(actualOrdering);
if (actualOrdering.equals(desiredOrdering)) {
/* In the (presumably) common case the elements are already sorted. */
return Optional.empty();
@@ -128,7 +144,7 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
/* The elements aren't sorted. Suggest the sorted alternative. */
String suggestion =
desiredOrdering.stream()
.map(expr -> Util.treeToString(expr, state))
.map(expr -> SourceCode.treeToString(expr, state))
.collect(joining(", ", "{", "}"));
return Optional.of(SuggestedFix.builder().replace(array, suggestion));
}
@@ -149,12 +165,15 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
}
private static ImmutableList<? extends ExpressionTree> doSort(
Iterable<? extends ExpressionTree> elements, VisitorState state) {
Iterable<? extends ExpressionTree> elements) {
// XXX: Perhaps we should use `Collator` with `.setStrength(Collator.PRIMARY)` and
// `getCollationKey`. Not clear whether that's worth the hassle at this point.
return ImmutableList.sortedCopyOf(
Comparator.comparing(
e -> getStructure(e, state),
comparing(
LexicographicalAnnotationAttributeListing::getStructure,
Comparators.lexicographical(
Comparators.lexicographical(Comparator.<String>naturalOrder()))),
Comparators.lexicographical(
String.CASE_INSENSITIVE_ORDER.thenComparing(naturalOrder())))),
elements);
}
@@ -163,35 +182,31 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
* performed. This approach disregards e.g. irrelevant whitespace. It also allows special
* structure within string literals to be respected.
*/
private static ImmutableList<ImmutableList<String>> getStructure(
ExpressionTree array, VisitorState state) {
private static ImmutableList<ImmutableList<String>> getStructure(ExpressionTree array) {
ImmutableList.Builder<ImmutableList<String>> nodes = ImmutableList.builder();
new TreeScanner<Void, Void>() {
new TreeScanner<@Nullable Void, @Nullable Void>() {
@Override
public Void visitIdentifier(IdentifierTree node, Void ctx) {
nodes.add(tokenize(node));
return super.visitIdentifier(node, ctx);
public @Nullable Void visitIdentifier(IdentifierTree node, @Nullable Void unused) {
nodes.add(ImmutableList.of(node.getName().toString()));
return super.visitIdentifier(node, unused);
}
@Override
public Void visitLiteral(LiteralTree node, Void ctx) {
nodes.add(tokenize(node));
return super.visitLiteral(node, ctx);
public @Nullable Void visitLiteral(LiteralTree node, @Nullable Void unused) {
Object value = ASTHelpers.constValue(node);
nodes.add(
value instanceof String
? STRING_ARGUMENT_SPLITTER.splitToStream((String) value).collect(toImmutableList())
: ImmutableList.of(String.valueOf(value)));
return super.visitLiteral(node, unused);
}
@Override
public Void visitPrimitiveType(PrimitiveTypeTree node, Void ctx) {
nodes.add(tokenize(node));
return super.visitPrimitiveType(node, ctx);
}
private ImmutableList<String> tokenize(Tree node) {
/*
* Tokens are split on `=` so that e.g. inline Spring property declarations are properly
* sorted by key, then value.
*/
return ImmutableList.copyOf(Util.treeToString(node, state).split("=", -1));
public @Nullable Void visitPrimitiveType(PrimitiveTypeTree node, @Nullable Void unused) {
nodes.add(ImmutableList.of(node.getPrimitiveTypeKind().toString()));
return super.visitPrimitiveType(node, unused);
}
}.scan(array, null);
@@ -206,7 +221,7 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
private static ImmutableList<String> excludedAnnotations(ErrorProneFlags flags) {
Set<String> exclusions = new HashSet<>();
flags.getList(EXCLUDED_ANNOTATIONS_FLAG).ifPresent(exclusions::addAll);
exclusions.addAll(Flags.getList(flags, EXCLUDED_ANNOTATIONS_FLAG));
exclusions.addAll(BLACKLISTED_ANNOTATIONS);
return ImmutableList.copyOf(exclusions);
}

View File

@@ -0,0 +1,99 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static com.sun.tools.javac.code.TypeAnnotations.AnnotationType.DECLARATION;
import static com.sun.tools.javac.code.TypeAnnotations.AnnotationType.TYPE;
import static java.util.Comparator.comparing;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.TypeAnnotations.AnnotationType;
import java.util.Comparator;
import java.util.List;
import org.jspecify.annotations.Nullable;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags annotations that are not lexicographically sorted.
*
* <p>The idea behind this checker is that maintaining a sorted sequence simplifies conflict
* resolution, and can even avoid it if two branches add the same annotation.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Sort annotations lexicographically where possible",
link = BUG_PATTERNS_BASE_URL + "LexicographicalAnnotationListing",
linkType = CUSTOM,
severity = SUGGESTION,
tags = STYLE)
public final class LexicographicalAnnotationListing extends BugChecker
implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Comparator<@Nullable AnnotationType> BY_ANNOTATION_TYPE =
(a, b) ->
(a == null || a == DECLARATION) && b == TYPE ? -1 : a == TYPE && b == DECLARATION ? 1 : 0;
/** Instantiates a new {@link LexicographicalAnnotationListing} instance. */
public LexicographicalAnnotationListing() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
List<? extends AnnotationTree> originalOrdering = tree.getModifiers().getAnnotations();
if (originalOrdering.size() < 2) {
return Description.NO_MATCH;
}
ImmutableList<? extends AnnotationTree> sortedAnnotations =
sort(originalOrdering, ASTHelpers.getSymbol(tree), state);
if (originalOrdering.equals(sortedAnnotations)) {
return Description.NO_MATCH;
}
return describeMatch(
originalOrdering.get(0), fixOrdering(originalOrdering, sortedAnnotations, state));
}
private static ImmutableList<? extends AnnotationTree> sort(
List<? extends AnnotationTree> annotations, Symbol symbol, VisitorState state) {
return annotations.stream()
.sorted(
comparing(
(AnnotationTree annotation) ->
ASTHelpers.getAnnotationType(annotation, symbol, state),
BY_ANNOTATION_TYPE)
.thenComparing(annotation -> SourceCode.treeToString(annotation, state)))
.collect(toImmutableList());
}
private static Fix fixOrdering(
List<? extends AnnotationTree> originalAnnotations,
ImmutableList<? extends AnnotationTree> sortedAnnotations,
VisitorState state) {
return Streams.zip(
originalAnnotations.stream(),
sortedAnnotations.stream(),
(original, replacement) ->
SuggestedFix.builder()
.replace(original, SourceCode.treeToString(replacement, state)))
.reduce(SuggestedFix.Builder::merge)
.map(SuggestedFix.Builder::build)
.orElseThrow(() -> new VerifyException("No annotations were provided"));
}
}

View File

@@ -1,15 +1,15 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher;
@@ -36,7 +36,9 @@ import java.util.Optional;
import javax.lang.model.element.Name;
/**
* A {@link BugChecker} which flags lambda expressions that can be replaced with method references.
* A {@link BugChecker} that flags lambda expressions that can be replaced with method references.
*
* @see IsInstanceLambdaUsage
*/
// XXX: Other custom expressions we could rewrite:
// - `a -> "str" + a` to `"str"::concat`. But only if `str` is provably non-null.
@@ -48,18 +50,24 @@ import javax.lang.model.element.Name;
// black-and-white. Maybe we can more closely approximate it?
// XXX: With Java 9's introduction of `Predicate.not`, we could write many lambda expressions to
// `not(some::reference)`.
// XXX: This check is extremely inefficient due to its reliance on `SuggestedFixes.compilesWithFix`.
// Palantir's `LambdaMethodReference` check seems to suffer a similar issue at this time.
// XXX: Expressions of the form `i -> SomeType.class.isInstance(i)` are not replaced; fix that using
// a suitable generalization.
// XXX: Consider folding the `IsInstanceLambdaUsage` check into this class.
@AutoService(BugChecker.class)
@BugPattern(
name = "MethodReferenceUsage",
summary = "Prefer method references over lambda expressions",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.STYLE,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class MethodReferenceUsageCheck extends BugChecker
implements LambdaExpressionTreeMatcher {
link = BUG_PATTERNS_BASE_URL + "MethodReferenceUsage",
linkType = CUSTOM,
severity = SUGGESTION,
tags = STYLE)
public final class MethodReferenceUsage extends BugChecker implements LambdaExpressionTreeMatcher {
private static final long serialVersionUID = 1L;
/** Instantiates a new {@link MethodReferenceUsage} instance. */
public MethodReferenceUsage() {}
@Override
public Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) {
/*
@@ -69,7 +77,10 @@ public final class MethodReferenceUsageCheck extends BugChecker
*/
return constructMethodRef(tree, tree.getBody())
.map(SuggestedFix.Builder::build)
.filter(fix -> SuggestedFixes.compilesWithFix(fix, state))
.filter(
fix ->
SuggestedFixes.compilesWithFix(
fix, state, ImmutableList.of(), /* onlyInSameCompilationUnit= */ true))
.map(fix -> describeMatch(tree, fix))
.orElse(Description.NO_MATCH);
}
@@ -99,6 +110,8 @@ public final class MethodReferenceUsageCheck extends BugChecker
.flatMap(statements -> constructMethodRef(lambdaExpr, statements.get(0)));
}
// XXX: Replace nested `Optional` usage.
@SuppressWarnings("NestedOptionals")
private static Optional<SuggestedFix.Builder> constructMethodRef(
LambdaExpressionTree lambdaExpr, MethodInvocationTree subTree) {
return matchArguments(lambdaExpr, subTree)
@@ -117,7 +130,7 @@ public final class MethodReferenceUsageCheck extends BugChecker
return Optional.empty();
}
Symbol sym = ASTHelpers.getSymbol(methodSelect);
if (!sym.isStatic()) {
if (!ASTHelpers.isStatic(sym)) {
return constructFix(lambdaExpr, "this", methodSelect);
}
return constructFix(lambdaExpr, sym.owner, methodSelect);
@@ -155,6 +168,8 @@ public final class MethodReferenceUsageCheck extends BugChecker
return constructFix(lambdaExpr, lhsType.tsym, subTree.getIdentifier());
}
// XXX: Refactor or replace inner `Optional` with a custom type.
@SuppressWarnings("NestedOptionals")
private static Optional<Optional<Name>> matchArguments(
LambdaExpressionTree lambdaExpr, MethodInvocationTree subTree) {
ImmutableList<Name> expectedArguments = getVariables(lambdaExpr);
@@ -185,7 +200,7 @@ public final class MethodReferenceUsageCheck extends BugChecker
Name sName = target.getSimpleName();
Optional<SuggestedFix.Builder> fix = constructFix(lambdaExpr, sName, methodName);
if (!"java.lang".equals(target.packge().toString())) {
if (!"java.lang".equals(ASTHelpers.enclosingPackage(target).toString())) {
Name fqName = target.getQualifiedName();
if (!sName.equals(fqName)) {
return fix.map(b -> b.addImport(fqName.toString()));

View File

@@ -0,0 +1,59 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
/** A {@link BugChecker} that flags likely missing Refaster annotations. */
@AutoService(BugChecker.class)
@BugPattern(
summary = "The Refaster rule contains a method without any Refaster annotations",
link = BUG_PATTERNS_BASE_URL + "MissingRefasterAnnotation",
linkType = CUSTOM,
severity = WARNING,
tags = LIKELY_ERROR)
public final class MissingRefasterAnnotation extends BugChecker implements ClassTreeMatcher {
private static final long serialVersionUID = 1L;
private static final MultiMatcher<Tree, AnnotationTree> REFASTER_ANNOTATION =
annotations(
AT_LEAST_ONE,
anyOf(
isType("com.google.errorprone.refaster.annotation.Placeholder"),
isType("com.google.errorprone.refaster.annotation.BeforeTemplate"),
isType("com.google.errorprone.refaster.annotation.AfterTemplate")));
/** Instantiates a new {@link MissingRefasterAnnotation} instance. */
public MissingRefasterAnnotation() {}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
long methodTypes =
tree.getMembers().stream()
.filter(member -> member.getKind() == Tree.Kind.METHOD)
.map(MethodTree.class::cast)
.filter(method -> !ASTHelpers.isGeneratedConstructor(method))
.map(method -> REFASTER_ANNOTATION.matches(method, state))
.distinct()
.count();
return methodTypes < 2 ? Description.NO_MATCH : buildDescription(tree).build();
}
}

View File

@@ -0,0 +1,86 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isVariable;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import java.util.List;
import tech.picnic.errorprone.bugpatterns.util.MoreASTHelpers;
/**
* A {@link BugChecker} that flags the use of {@link org.mockito.Mockito#mock(Class)} and {@link
* org.mockito.Mockito#spy(Class)} where instead the type to be mocked or spied can be derived from
* context.
*/
// XXX: This check currently does not flag method invocation arguments. When adding support for
// this, consider that in some cases the type to be mocked or spied must be specified explicitly so
// as to disambiguate between method overloads.
// XXX: This check currently does not flag (implicit or explicit) lambda return expressions.
// XXX: This check currently does not drop suppressions that become obsolete after the
// suggested fix is applied; consider adding support for this.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods",
link = BUG_PATTERNS_BASE_URL + "MockitoMockClassReference",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class MockitoMockClassReference extends BugChecker
implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<MethodInvocationTree> MOCKITO_MOCK_OR_SPY_WITH_HARDCODED_TYPE =
allOf(
argument(0, allOf(isSameType(Class.class.getName()), not(isVariable()))),
staticMethod().onClass("org.mockito.Mockito").namedAnyOf("mock", "spy"));
/** Instantiates a new {@link MockitoMockClassReference} instance. */
public MockitoMockClassReference() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MOCKITO_MOCK_OR_SPY_WITH_HARDCODED_TYPE.matches(tree, state)
|| !isTypeDerivableFromContext(tree, state)) {
return Description.NO_MATCH;
}
List<? extends ExpressionTree> arguments = tree.getArguments();
return describeMatch(tree, SuggestedFixes.removeElement(arguments.get(0), arguments, state));
}
private static boolean isTypeDerivableFromContext(MethodInvocationTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
switch (parent.getKind()) {
case VARIABLE:
return !ASTHelpers.hasNoExplicitType((VariableTree) parent, state)
&& MoreASTHelpers.areSameType(tree, parent, state);
case ASSIGNMENT:
return MoreASTHelpers.areSameType(tree, parent, state);
case RETURN:
return MoreASTHelpers.findMethodExitedOnReturn(state)
.filter(m -> MoreASTHelpers.areSameType(tree, m.getReturnType(), state))
.isPresent();
default:
return false;
}
}
}

View File

@@ -0,0 +1,63 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.List;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags method invocations for which all arguments are wrapped using
* {@link org.mockito.Mockito#eq}; this is redundant.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Don't unnecessarily use Mockito's `eq(...)`",
link = BUG_PATTERNS_BASE_URL + "MockitoStubbing",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class MockitoStubbing extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> MOCKITO_EQ_METHOD =
staticMethod().onClass("org.mockito.ArgumentMatchers").named("eq");
/** Instantiates a new {@link MockitoStubbing} instance. */
public MockitoStubbing() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
List<? extends ExpressionTree> arguments = tree.getArguments();
if (arguments.isEmpty() || !arguments.stream().allMatch(arg -> isEqInvocation(arg, state))) {
return Description.NO_MATCH;
}
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
for (ExpressionTree arg : arguments) {
suggestedFix.replace(
arg,
SourceCode.treeToString(
Iterables.getOnlyElement(((MethodInvocationTree) arg).getArguments()), state));
}
return describeMatch(tree, suggestedFix.build());
}
private static boolean isEqInvocation(ExpressionTree tree, VisitorState state) {
return tree instanceof MethodInvocationTree && MOCKITO_EQ_METHOD.matches(tree, state);
}
}

View File

@@ -0,0 +1,51 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.generic;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.raw;
import static tech.picnic.errorprone.bugpatterns.util.MoreTypes.subOf;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/** A {@link BugChecker} that flags nesting of {@link Optional Optionals}. */
@AutoService(BugChecker.class)
@BugPattern(
summary =
"Avoid nesting `Optional`s inside `Optional`s; the resultant code is hard to reason about",
link = BUG_PATTERNS_BASE_URL + "NestedOptionals",
linkType = CUSTOM,
severity = WARNING,
tags = FRAGILE_CODE)
public final class NestedOptionals extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Supplier<Type> OPTIONAL = Suppliers.typeFromClass(Optional.class);
private static final Supplier<Type> OPTIONAL_OF_OPTIONAL =
VisitorState.memoize(generic(OPTIONAL, subOf(raw(OPTIONAL))));
/** Instantiates a new {@link NestedOptionals} instance. */
public NestedOptionals() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Type type = OPTIONAL_OF_OPTIONAL.get(state);
if (type == null || !state.getTypes().isSubtype(ASTHelpers.getType(tree), type)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}

View File

@@ -0,0 +1,96 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.function.BiFunction;
import reactor.core.publisher.Mono;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags {@link Mono} operations that are known to be vacuous, given that
* they are invoked on a {@link Mono} that is known not to complete empty.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Avoid vacuous operations on known non-empty `Mono`s",
link = BUG_PATTERNS_BASE_URL + "NonEmptyMono",
linkType = CUSTOM,
severity = WARNING,
tags = SIMPLIFICATION)
// XXX: This check does not simplify `someFlux.defaultIfEmpty(T).{defaultIfEmpty(T),hasElements()}`,
// as `someFlux.defaultIfEmpty(T)` yields a `Flux` rather than a `Mono`. Consider adding support for
// these cases.
// XXX: Given more advanced analysis many more expressions could be flagged. Consider
// `Mono.just(someValue)`, `Flux.just(someNonEmptySequence)`,
// `someMono.switchIfEmpty(someProvablyNonEmptyMono)` and many other variants.
// XXX: Consider implementing a similar check for `Publisher`s that are known to complete without
// emitting a value (e.g. `Mono.empty()`, `someFlux.then()`, ...), or known not to complete normally
// (`Mono.never()`, `someFlux.repeat()`, `Mono.error(...)`, ...). The latter category could
// potentially be split out further.
public final class NonEmptyMono extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> MONO_SIZE_CHECK =
instanceMethod()
.onDescendantOf("reactor.core.publisher.Mono")
.namedAnyOf("defaultIfEmpty", "single", "switchIfEmpty");
private static final Matcher<ExpressionTree> NON_EMPTY_MONO =
anyOf(
instanceMethod()
.onDescendantOf("reactor.core.publisher.Flux")
.namedAnyOf(
"all",
"any",
"collect",
"collectList",
"collectMap",
"collectMultimap",
"collectSortedList",
"count",
"elementAt",
"hasElement",
"hasElements",
"last",
"reduceWith",
"single"),
instanceMethod()
.onDescendantOf("reactor.core.publisher.Flux")
.named("reduce")
.withParameters(Object.class.getName(), BiFunction.class.getName()),
instanceMethod()
.onDescendantOf("reactor.core.publisher.Mono")
.namedAnyOf("defaultIfEmpty", "hasElement", "single"));
/** Instantiates a new {@link NonEmptyMono} instance. */
public NonEmptyMono() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MONO_SIZE_CHECK.matches(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree receiver = ASTHelpers.getReceiver(tree);
if (!NON_EMPTY_MONO.matches(receiver, state)) {
return Description.NO_MATCH;
}
return describeMatch(
tree, SuggestedFix.replace(tree, SourceCode.treeToString(receiver, state)));
}
}

View File

@@ -0,0 +1,181 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.PERFORMANCE;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.VerifyException;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags {@code Comparator#comparing*} invocations that can be replaced
* with an equivalent alternative so as to avoid unnecessary (un)boxing.
*/
// XXX: Add more documentation. Explain how this is useful in the face of refactoring to more
// specific types.
@AutoService(BugChecker.class)
@BugPattern(
summary =
"Ensure invocations of `Comparator#comparing{,Double,Int,Long}` match the return type"
+ " of the provided function",
link = BUG_PATTERNS_BASE_URL + "PrimitiveComparison",
linkType = CUSTOM,
severity = WARNING,
tags = PERFORMANCE)
public final class PrimitiveComparison extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> STATIC_COMPARISON_METHOD =
anyOf(
staticMethod()
.onClass(Comparator.class.getName())
.namedAnyOf("comparingInt", "comparingLong", "comparingDouble"),
staticMethod()
.onClass(Comparator.class.getName())
.named("comparing")
.withParameters(Function.class.getName()));
private static final Matcher<ExpressionTree> INSTANCE_COMPARISON_METHOD =
anyOf(
instanceMethod()
.onDescendantOf(Comparator.class.getName())
.namedAnyOf("thenComparingInt", "thenComparingLong", "thenComparingDouble"),
instanceMethod()
.onDescendantOf(Comparator.class.getName())
.named("thenComparing")
.withParameters(Function.class.getName()));
/** Instantiates a new {@link PrimitiveComparison} instance. */
public PrimitiveComparison() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
boolean isStatic = STATIC_COMPARISON_METHOD.matches(tree, state);
if (!isStatic && !INSTANCE_COMPARISON_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
return getPotentiallyBoxedReturnType(tree.getArguments().get(0))
.flatMap(cmpType -> attemptMethodInvocationReplacement(tree, cmpType, isStatic, state))
.map(fix -> describeMatch(tree, fix))
.orElse(Description.NO_MATCH);
}
private static Optional<Fix> attemptMethodInvocationReplacement(
MethodInvocationTree tree, Type cmpType, boolean isStatic, VisitorState state) {
String actualMethodName = ASTHelpers.getSymbol(tree).getSimpleName().toString();
String preferredMethodName = getPreferredMethod(cmpType, isStatic, state);
if (actualMethodName.equals(preferredMethodName)) {
return Optional.empty();
}
return Optional.of(
suggestFix(
tree, prefixTypeArgumentsIfRelevant(preferredMethodName, tree, cmpType, state), state));
}
/**
* Prefixes the given method name with generic type parameters if it replaces a {@code
* Comparator#comparing{,Double,Long,Int}} method which also has generic type parameters.
*
* <p>Such type parameters are retained as they are likely required.
*
* <p>Note that any type parameter to {@code Comparator#thenComparing} is likely redundant, and in
* any case becomes obsolete once that method is replaced with {@code
* Comparator#thenComparing{Double,Long,Int}}. Conversion in the opposite direction does not
* require the introduction of a generic type parameter.
*/
private static String prefixTypeArgumentsIfRelevant(
String preferredMethodName, MethodInvocationTree tree, Type cmpType, VisitorState state) {
if (tree.getTypeArguments().isEmpty() || preferredMethodName.startsWith("then")) {
return preferredMethodName;
}
String typeArguments =
Stream.concat(
Stream.of(SourceCode.treeToString(tree.getTypeArguments().get(0), state)),
Stream.of(cmpType.tsym.getSimpleName())
.filter(u -> "comparing".equals(preferredMethodName)))
.collect(joining(", ", "<", ">"));
return typeArguments + preferredMethodName;
}
private static String getPreferredMethod(Type cmpType, boolean isStatic, VisitorState state) {
Types types = state.getTypes();
Symtab symtab = state.getSymtab();
if (types.isSubtype(cmpType, symtab.intType)) {
return isStatic ? "comparingInt" : "thenComparingInt";
}
if (types.isSubtype(cmpType, symtab.longType)) {
return isStatic ? "comparingLong" : "thenComparingLong";
}
if (types.isSubtype(cmpType, symtab.doubleType)) {
return isStatic ? "comparingDouble" : "thenComparingDouble";
}
return isStatic ? "comparing" : "thenComparing";
}
private static Optional<Type> getPotentiallyBoxedReturnType(ExpressionTree tree) {
switch (tree.getKind()) {
case LAMBDA_EXPRESSION:
/* Return the lambda expression's actual return type. */
return Optional.ofNullable(ASTHelpers.getType(((LambdaExpressionTree) tree).getBody()));
case MEMBER_REFERENCE:
/* Return the method's declared return type. */
// XXX: Very fragile. Do better.
Type subType2 = ((JCMemberReference) tree).referentType;
return Optional.of(subType2.getReturnType());
default:
/* This appears to be a genuine `{,ToInt,ToLong,ToDouble}Function`. */
return Optional.empty();
}
}
private static Fix suggestFix(
MethodInvocationTree tree, String preferredMethodName, VisitorState state) {
ExpressionTree expr = tree.getMethodSelect();
switch (expr.getKind()) {
case IDENTIFIER:
return SuggestedFix.builder()
.addStaticImport(Comparator.class.getName() + '.' + preferredMethodName)
.replace(expr, preferredMethodName)
.build();
case MEMBER_SELECT:
MemberSelectTree ms = (MemberSelectTree) tree.getMethodSelect();
return SuggestedFix.replace(
ms, SourceCode.treeToString(ms.getExpression(), state) + '.' + preferredMethodName);
default:
throw new VerifyException("Unexpected type of expression: " + expr.getKind());
}
}
}

View File

@@ -1,166 +0,0 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static java.util.function.Predicate.not;
import com.google.auto.service.AutoService;
import com.google.common.base.VerifyException;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* A {@link BugChecker} which flags {@code Comparator#comparing*} invocations that can be replaced
* with an equivalent alternative so as to avoid unnecessary (un)boxing.
*/
// XXX: Add more documentation. Explain how this is useful in the face of refactoring to more
// specific types.
// XXX: Change this checker's name?
// XXX: Introduce a companion checker (or Refaster template?) for
// https://youtrack.jetbrains.com/issue/IDEA-185548.
@AutoService(BugChecker.class)
@BugPattern(
name = "PrimitiveComparison",
summary =
"Ensure invocations of `Comparator#comparing{,Double,Int,Long}` match the return type"
+ " of the provided function",
linkType = LinkType.NONE,
severity = SeverityLevel.WARNING,
tags = StandardTags.PERFORMANCE,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class PrimitiveComparisonCheck extends BugChecker
implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> STATIC_MATCH = getStaticTargetMatcher();
private static final Matcher<ExpressionTree> INSTANCE_MATCH = getInstanceTargetMatcher();
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
boolean isStatic = STATIC_MATCH.matches(tree, state);
if (!isStatic && !INSTANCE_MATCH.matches(tree, state)) {
return Description.NO_MATCH;
}
return getPotentiallyBoxedReturnType(tree.getArguments().get(0))
.flatMap(cmpType -> tryFix(tree, state, cmpType, isStatic))
.map(fix -> describeMatch(tree, fix))
.orElse(Description.NO_MATCH);
}
private static Optional<Fix> tryFix(
MethodInvocationTree tree, VisitorState state, Type cmpType, boolean isStatic) {
return Optional.ofNullable(ASTHelpers.getSymbol(tree))
.map(methodSymbol -> methodSymbol.getSimpleName().toString())
.flatMap(
actualMethodName ->
Optional.of(getPreferredMethod(state, cmpType, isStatic))
.filter(not(actualMethodName::equals)))
.map(preferredMethodName -> suggestFix(tree, preferredMethodName, state));
}
private static String getPreferredMethod(VisitorState state, Type cmpType, boolean isStatic) {
Types types = state.getTypes();
Symtab symtab = state.getSymtab();
if (types.isSubtype(cmpType, symtab.intType)) {
return isStatic ? "comparingInt" : "thenComparingInt";
}
if (types.isSubtype(cmpType, symtab.longType)) {
return isStatic ? "comparingLong" : "thenComparingLong";
}
if (types.isSubtype(cmpType, symtab.doubleType)) {
return isStatic ? "comparingDouble" : "thenComparingDouble";
}
return isStatic ? "comparing" : "thenComparing";
}
private static Optional<Type> getPotentiallyBoxedReturnType(ExpressionTree tree) {
switch (tree.getKind()) {
case LAMBDA_EXPRESSION:
/* Return the lambda expression's actual return type. */
return Optional.ofNullable(ASTHelpers.getType(((LambdaExpressionTree) tree).getBody()));
case MEMBER_REFERENCE:
/* Return the method's declared return type. */
// XXX: Very fragile. Do better.
Type subType2 = ((JCMemberReference) tree).referentType;
return Optional.of(subType2.getReturnType());
default:
/* This appears to be a genuine `{,ToInt,ToLong,ToDouble}Function`. */
return Optional.empty();
}
}
// XXX: We drop explicitly specified generic type information. In case the number of type
// arguments before and after doesn't match, that's for the better. But if we e.g. replace
// `comparingLong` with `comparingInt`, then we should retain it.
private static Fix suggestFix(
MethodInvocationTree tree, String preferredMethodName, VisitorState state) {
ExpressionTree expr = tree.getMethodSelect();
switch (expr.getKind()) {
case IDENTIFIER:
return SuggestedFix.builder()
.addStaticImport(Comparator.class.getName() + '.' + preferredMethodName)
.replace(expr, preferredMethodName)
.build();
case MEMBER_SELECT:
MemberSelectTree ms = (MemberSelectTree) tree.getMethodSelect();
return SuggestedFix.replace(
ms, Util.treeToString(ms.getExpression(), state) + '.' + preferredMethodName);
default:
throw new VerifyException("Unexpected type of expression: " + expr.getKind());
}
}
private static Matcher<ExpressionTree> getStaticTargetMatcher() {
String clazz = Comparator.class.getName();
return anyMatch(
staticMethod()
.onClass(clazz)
.namedAnyOf("comparingInt", "comparingLong", "comparingDouble"),
staticMethod().onClass(clazz).named("comparing").withParameters(Function.class.getName()));
}
private static Matcher<ExpressionTree> getInstanceTargetMatcher() {
String clazz = Comparator.class.getName();
return anyMatch(
instanceMethod()
.onDescendantOf(clazz)
.namedAnyOf("thenComparingInt", "thenComparingLong", "thenComparingDouble"),
instanceMethod()
.onDescendantOf(clazz)
.named("thenComparing")
.withParameters(Function.class.getName()));
}
@SafeVarargs
@SuppressWarnings("varargs")
private static Matcher<ExpressionTree> anyMatch(Matcher<ExpressionTree>... matchers) {
return (ExpressionTree t, VisitorState s) -> Stream.of(matchers).anyMatch(m -> m.matches(t, s));
}
}

View File

@@ -1,21 +1,27 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isNonNull;
import static com.google.errorprone.matchers.Matchers.anything;
import static com.google.errorprone.matchers.Matchers.argumentCount;
import static com.google.errorprone.matchers.Matchers.isNonNullUsingDataflow;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
@@ -25,6 +31,7 @@ import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionTree;
@@ -42,77 +49,58 @@ import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import tech.picnic.errorprone.bugpatterns.util.Flags;
import tech.picnic.errorprone.bugpatterns.util.MethodMatcherFactory;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} which flags redundant explicit string conversions. */
/** A {@link BugChecker} that flags redundant explicit string conversions. */
@AutoService(BugChecker.class)
@BugPattern(
name = "RedundantStringConversion",
summary = "Avoid redundant string conversions when possible",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.SIMPLIFICATION,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class RedundantStringConversionCheck extends BugChecker
link = BUG_PATTERNS_BASE_URL + "RedundantStringConversion",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class RedundantStringConversion extends BugChecker
implements BinaryTreeMatcher, CompoundAssignmentTreeMatcher, MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String FLAG_PREFIX = "RedundantStringConversion:";
private static final String EXTRA_STRING_CONVERSION_METHODS_FLAG =
FLAG_PREFIX + "ExtraConversionMethods";
@SuppressWarnings("UnnecessaryLambda")
private static final Matcher<ExpressionTree> ANY_EXPR = (t, s) -> true;
"RedundantStringConversion:ExtraConversionMethods";
private static final Matcher<ExpressionTree> ANY_EXPR = anything();
private static final Matcher<ExpressionTree> LOCALE = isSameType(Locale.class);
private static final Matcher<ExpressionTree> MARKER = isSubtypeOf("org.slf4j.Marker");
private static final Matcher<ExpressionTree> STRING = isSameType(String.class);
private static final Matcher<ExpressionTree> THROWABLE = isSubtypeOf(Throwable.class);
private static final Matcher<ExpressionTree> NON_NULL_STRING = allOf(STRING, isNonNull());
private static final Matcher<ExpressionTree> NON_NULL_STRING =
allOf(STRING, isNonNullUsingDataflow());
private static final Matcher<ExpressionTree> NOT_FORMATTABLE =
not(isSubtypeOf(Formattable.class));
private static final Matcher<ExpressionTree> WELL_KNOWN_STRING_CONVERSION_METHODS =
private static final Matcher<MethodInvocationTree> WELL_KNOWN_STRING_CONVERSION_METHODS =
anyOf(
instanceMethod().onDescendantOfAny(Object.class.getName()).named("toString"),
staticMethod()
.onClass(Objects.class.getName())
instanceMethod()
.onDescendantOfAny(Object.class.getName())
.named("toString")
.withParameters(Object.class.getName()),
staticMethod()
.onClass(String.class.getName())
.named("valueOf")
.withParameters(Object.class.getName()),
staticMethod()
.onClass(String.class.getName())
.named("valueOf")
.withParameters(String.class.getName()),
staticMethod()
.onClass(Byte.class.getName())
.named("toString")
.withParameters(byte.class.getName()),
staticMethod()
.onClass(Character.class.getName())
.named("toString")
.withParameters(char.class.getName()),
staticMethod()
.onClass(Short.class.getName())
.named("toString")
.withParameters(short.class.getName()),
staticMethod()
.onClass(Integer.class.getName())
.named("toString")
.withParameters(int.class.getName()),
staticMethod()
.onClass(Long.class.getName())
.named("toString")
.withParameters(long.class.getName()),
staticMethod()
.onClass(Float.class.getName())
.named("toString")
.withParameters(float.class.getName()),
staticMethod()
.onClass(Double.class.getName())
.named("toString")
.withParameters(double.class.getName()));
.withNoParameters(),
allOf(
argumentCount(1),
anyOf(
staticMethod()
.onClassAny(
Stream.concat(
Primitives.allWrapperTypes().stream(), Stream.of(Objects.class))
.map(Class::getName)
.collect(toImmutableSet()))
.named("toString"),
allOf(
staticMethod().onClass(String.class.getName()).named("valueOf"),
not(
anyMethod()
.anyClass()
.withAnyName()
.withParametersOfType(
ImmutableList.of(Suppliers.arrayOf(Suppliers.CHAR_TYPE))))))));
private static final Matcher<ExpressionTree> STRINGBUILDER_APPEND_INVOCATION =
instanceMethod()
.onDescendantOf(StringBuilder.class.getName())
@@ -128,48 +116,41 @@ public final class RedundantStringConversionCheck extends BugChecker
staticMethod().onClass(String.class.getName()).named("format"),
instanceMethod().onDescendantOf(Formatter.class.getName()).named("format"),
instanceMethod()
.onDescendantOf(PrintStream.class.getName())
.withNameMatching(Pattern.compile("format|printf")),
.onDescendantOfAny(PrintStream.class.getName(), PrintWriter.class.getName())
.namedAnyOf("format", "printf"),
instanceMethod()
.onDescendantOf(PrintStream.class.getName())
.withNameMatching(Pattern.compile("print|println"))
.withParameters(Object.class.getName()),
instanceMethod()
.onDescendantOf(PrintWriter.class.getName())
.withNameMatching(Pattern.compile("format|printf")),
instanceMethod()
.onDescendantOf(PrintWriter.class.getName())
.withNameMatching(Pattern.compile("print|println"))
.onDescendantOfAny(PrintStream.class.getName(), PrintWriter.class.getName())
.namedAnyOf("print", "println")
.withParameters(Object.class.getName()),
staticMethod()
.onClass(Console.class.getName())
.withNameMatching(Pattern.compile("format|printf|readline|readPassword")));
.namedAnyOf("format", "printf", "readline", "readPassword"));
private static final Matcher<ExpressionTree> GUAVA_GUARD_INVOCATION =
anyOf(
staticMethod()
.onClass("com.google.common.base.Preconditions")
.withNameMatching(Pattern.compile("checkArgument|checkState|checkNotNull")),
.namedAnyOf("checkArgument", "checkState", "checkNotNull"),
staticMethod()
.onClass("com.google.common.base.Verify")
.withNameMatching(Pattern.compile("verify|verifyNotNull")));
.namedAnyOf("verify", "verifyNotNull"));
private static final Matcher<ExpressionTree> SLF4J_LOGGER_INVOCATION =
instanceMethod()
.onDescendantOf("org.slf4j.Logger")
.withNameMatching(Pattern.compile("trace|debug|info|warn|error"));
.namedAnyOf("trace", "debug", "info", "warn", "error");
private final Matcher<ExpressionTree> conversionMethodMatcher;
private final Matcher<MethodInvocationTree> conversionMethodMatcher;
/** Instantiates the default {@link RedundantStringConversionCheck}. */
public RedundantStringConversionCheck() {
/** Instantiates a default {@link RedundantStringConversion} instance. */
public RedundantStringConversion() {
this(ErrorProneFlags.empty());
}
/**
* Instantiates a customized {@link RedundantStringConversionCheck}.
* Instantiates a customized {@link RedundantStringConversion}.
*
* @param flags Any provided command line flags.
*/
public RedundantStringConversionCheck(ErrorProneFlags flags) {
public RedundantStringConversion(ErrorProneFlags flags) {
conversionMethodMatcher = createConversionMethodMatcher(flags);
}
@@ -187,15 +168,14 @@ public final class RedundantStringConversionCheck extends BugChecker
List<SuggestedFix.Builder> fixes = new ArrayList<>();
// XXX: Not so nice: we try to simplify the RHS twice.
// XXX: Avoid trying to simplify the RHS twice.
ExpressionTree preferredRhs = trySimplify(rhs, state).orElse(rhs);
if (STRING.matches(preferredRhs, state)) {
tryFix(lhs, state, ANY_EXPR).ifPresent(fixes::add);
tryFix(rhs, state, ANY_EXPR).ifPresent(fixes::add);
} else {
tryFix(lhs, state, STRING).ifPresent(fixes::add);
tryFix(rhs, state, ANY_EXPR).ifPresent(fixes::add);
}
tryFix(rhs, state, ANY_EXPR).ifPresent(fixes::add);
return finalize(tree, fixes.stream().reduce(SuggestedFix.Builder::merge));
}
@@ -245,7 +225,7 @@ public final class RedundantStringConversionCheck extends BugChecker
.flatMap(args -> tryFix(args.get(index), state, ANY_EXPR));
}
// XXX: Write another check which checks that Formatter patterns don't use `{}` and have a
// XXX: Write another check that checks that Formatter patterns don't use `{}` and have a
// matching number of arguments of the appropriate type. Also flag explicit conversions from
// `Formattable` to string.
private Optional<SuggestedFix.Builder> tryFixFormatter(
@@ -276,17 +256,17 @@ public final class RedundantStringConversionCheck extends BugChecker
return tryFixFormatterArguments(arguments, state, ANY_EXPR, ANY_EXPR);
}
// XXX: Write another check which checks that SLF4J patterns don't use `%s` and have a matching
// XXX: Write another check that checks that SLF4J patterns don't use `%s` and have a matching
// number of arguments of the appropriate type. Also flag explicit conversions from `Throwable` to
// string as the last logger argument. Suggests either dropping the converison or going with
// string as the last logger argument. Suggests either dropping the conversion or going with
// `Throwable#getMessage()` instead.
private Optional<SuggestedFix.Builder> tryFixSlf4jLogger(
List<? extends ExpressionTree> arguments, VisitorState state) {
/*
* SLF4J treats the final argument to a log statement specially if it is a `Throwabe`: it
* SLF4J treats the final argument to a log statement specially if it is a `Throwable`: it
* will always choose to render the associated stacktrace, even if the argument has a
* matching `{}` placeholder. (In this case the `{}` will simply be logged verbatim.) So if
* a log statement's final argument is the string representation of a `Throwble`, then we
* a log statement's final argument is the string representation of a `Throwable`, then we
* must not strip this explicit string conversion, as that would change the statement's
* semantics.
*/
@@ -329,7 +309,7 @@ public final class RedundantStringConversionCheck extends BugChecker
return trySimplify(tree, state, filter)
.map(
replacement ->
SuggestedFix.builder().replace(tree, Util.treeToString(replacement, state)));
SuggestedFix.builder().replace(tree, SourceCode.treeToString(replacement, state)));
}
private Optional<ExpressionTree> trySimplify(
@@ -340,11 +320,15 @@ public final class RedundantStringConversionCheck extends BugChecker
}
private Optional<ExpressionTree> trySimplify(ExpressionTree tree, VisitorState state) {
if (tree.getKind() != Kind.METHOD_INVOCATION || !conversionMethodMatcher.matches(tree, state)) {
if (tree.getKind() != Kind.METHOD_INVOCATION) {
return Optional.empty();
}
MethodInvocationTree methodInvocation = (MethodInvocationTree) tree;
if (!conversionMethodMatcher.matches(methodInvocation, state)) {
return Optional.empty();
}
switch (methodInvocation.getArguments().size()) {
case 0:
return trySimplifyNullaryMethod(methodInvocation, state);
@@ -353,7 +337,7 @@ public final class RedundantStringConversionCheck extends BugChecker
default:
throw new IllegalStateException(
"Cannot simplify method call with two or more arguments: "
+ Util.treeToString(tree, state));
+ SourceCode.treeToString(tree, state));
}
}
@@ -366,7 +350,7 @@ public final class RedundantStringConversionCheck extends BugChecker
return Optional.of(methodInvocation.getMethodSelect())
.filter(methodSelect -> methodSelect.getKind() == Kind.MEMBER_SELECT)
.map(methodSelect -> ((MemberSelectTree) methodSelect).getExpression())
.filter(expr -> !"super".equals(Util.treeToString(expr, state)));
.filter(expr -> !"super".equals(SourceCode.treeToString(expr, state)));
}
private static Optional<ExpressionTree> trySimplifyUnaryMethod(
@@ -385,13 +369,13 @@ public final class RedundantStringConversionCheck extends BugChecker
.orElse(Description.NO_MATCH);
}
private static Matcher<ExpressionTree> createConversionMethodMatcher(ErrorProneFlags flags) {
private static Matcher<MethodInvocationTree> createConversionMethodMatcher(
ErrorProneFlags flags) {
// XXX: ErrorProneFlags#getList splits by comma, but method signatures may also contain commas.
// For this class methods accepting more than one argument are not valid, but still: not nice.
return flags
.getList(EXTRA_STRING_CONVERSION_METHODS_FLAG)
.map(new MethodMatcherFactory()::create)
.map(m -> anyOf(WELL_KNOWN_STRING_CONVERSION_METHODS, m))
.orElse(WELL_KNOWN_STRING_CONVERSION_METHODS);
return anyOf(
WELL_KNOWN_STRING_CONVERSION_METHODS,
new MethodMatcherFactory()
.create(Flags.getList(flags, EXTRA_STRING_CONVERSION_METHODS_FLAG)));
}
}

View File

@@ -0,0 +1,62 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.refaster.Refaster;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags unnecessary {@link Refaster#anyOf(Object[])} usages.
*
* <p>Note that this logic can't be implemented as a Refaster rule, as the {@link Refaster} class is
* treated specially.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "`Refaster#anyOf` should be passed at least two parameters",
link = BUG_PATTERNS_BASE_URL + "RefasterAnyOfUsage",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class RefasterAnyOfUsage extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> REFASTER_ANY_OF =
staticMethod().onClass(Refaster.class.getName()).named("anyOf");
/** Instantiates a new {@link RefasterAnyOfUsage} instance. */
public RefasterAnyOfUsage() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (REFASTER_ANY_OF.matches(tree, state)) {
switch (tree.getArguments().size()) {
case 0:
// We can't safely fix this case; dropping the expression may produce non-compilable code.
return describeMatch(tree);
case 1:
return describeMatch(
tree,
SuggestedFix.replace(
tree, SourceCode.treeToString(tree.getArguments().get(0), state)));
default:
/* Handled below. */
}
}
return Description.NO_MATCH;
}
}

View File

@@ -1,224 +0,0 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableRangeSet.toImmutableRangeSet;
import com.google.auto.service.AutoService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ResourceInfo;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.CodeTransformer;
import com.google.errorprone.CompositeCodeTransformer;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.SubContext;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.Replacement;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* A {@link BugChecker} which flags code which can be simplified using Refaster templates located on
* the classpath.
*
* <p>This checker locates all {@code *.refaster} classpath resources and assumes they contain a
* {@link CodeTransformer}. The set of loaded Refaster templates can be restricted by passing {@code
* -XepOpt:Refaster:NamePattern=<someRegex>}.
*/
@AutoService(BugChecker.class)
@BugPattern(
name = "Refaster",
summary = "Write idiomatic code when possible",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.SIMPLIFICATION,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class RefasterCheck extends BugChecker implements CompilationUnitTreeMatcher {
private static final String REFASTER_TEMPLATE_SUFFIX = ".refaster";
private static final String INCLUDED_TEMPLATES_PATTERN_FLAG = "Refaster:NamePattern";
private static final long serialVersionUID = 1L;
private final CodeTransformer codeTransformer;
/** Instantiates the default {@link RefasterCheck}. */
public RefasterCheck() {
this(ErrorProneFlags.empty());
}
/**
* Instantiates a customized {@link RefasterCheck}.
*
* @param flags Any provided command line flags.
*/
public RefasterCheck(ErrorProneFlags flags) {
codeTransformer = createCompositeCodeTransformer(flags, loadAllCodeTransformers());
}
@VisibleForTesting
RefasterCheck(
ErrorProneFlags flags, ImmutableListMultimap<String, CodeTransformer> allTransformers) {
codeTransformer = createCompositeCodeTransformer(flags, allTransformers);
}
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
/* First, collect all matches. */
List<Description> matches = new ArrayList<>();
codeTransformer.apply(state.getPath(), new SubContext(state.context), matches::add);
/* Then apply them. */
applyMatches(matches, ((JCCompilationUnit) tree).endPositions, state);
/* Any matches were already reported by the code above, directly to the `VisitorState`. */
return Description.NO_MATCH;
}
/**
* Reports a subset of the given matches, such that no two reported matches suggest a replacement
* of the same part of the source code.
*
* <p>Generally all matches will be reported. In case of overlap the match which replaces the
* largest piece of source code is preferred. In case two matches wish to replace exactly the same
* piece of code, preference is given to the match which suggests the shortest replacement.
*/
// XXX: This selection logic solves an issue described in
// https://github.com/google/error-prone/issues/559. Consider contributing it back upstream.
private static void applyMatches(
Iterable<Description> allMatches, EndPosTable endPositions, VisitorState state) {
ImmutableList<Description> byReplacementSize =
ImmutableList.sortedCopyOf(
Comparator.<Description>comparingInt(d -> getReplacedCodeSize(d, endPositions))
.reversed()
.thenComparingInt(d -> getInsertedCodeSize(d, endPositions)),
allMatches);
RangeSet<Integer> replacedSections = TreeRangeSet.create();
for (Description description : byReplacementSize) {
ImmutableRangeSet<Integer> ranges = getReplacementRanges(description, endPositions);
if (ranges.asRanges().stream().noneMatch(replacedSections::intersects)) {
/* This suggested fix does not overlap with any ("larger") replacement seen until now. Apply it. */
state.reportMatch(description);
replacedSections.addAll(ranges);
}
}
}
private static int getReplacedCodeSize(Description description, EndPosTable endPositions) {
return getReplacements(description, endPositions).mapToInt(Replacement::length).sum();
}
// XXX: Strictly speaking we should prefer the shortest replacement *post formatting*!
private static int getInsertedCodeSize(Description description, EndPosTable endPositions) {
return getReplacements(description, endPositions).mapToInt(r -> r.replaceWith().length()).sum();
}
private static ImmutableRangeSet<Integer> getReplacementRanges(
Description description, EndPosTable endPositions) {
return getReplacements(description, endPositions)
.map(Replacement::range)
.collect(toImmutableRangeSet());
}
private static Stream<Replacement> getReplacements(
Description description, EndPosTable endPositions) {
return description.fixes.stream()
.limit(1)
.flatMap(fix -> fix.getReplacements(endPositions).stream());
}
private static CodeTransformer createCompositeCodeTransformer(
ErrorProneFlags flags, ImmutableListMultimap<String, CodeTransformer> allTransformers) {
return CompositeCodeTransformer.compose(
flags
.get(INCLUDED_TEMPLATES_PATTERN_FLAG)
.map(Pattern::compile)
.map(nameFilter -> filterCodeTransformers(allTransformers, nameFilter))
.orElseGet(allTransformers::values));
}
private static ImmutableCollection<CodeTransformer> filterCodeTransformers(
ImmutableListMultimap<String, CodeTransformer> transformers, Pattern nameFilter) {
return transformers.entries().stream()
.filter(e -> nameFilter.matcher(e.getKey()).matches())
.map(Map.Entry::getValue)
.collect(toImmutableList());
}
@VisibleForTesting
static ImmutableListMultimap<String, CodeTransformer> loadAllCodeTransformers() {
ImmutableListMultimap.Builder<String, CodeTransformer> transformers =
ImmutableListMultimap.builder();
for (ResourceInfo resource : getClassPathResources()) {
getRefasterTemplateName(resource)
.ifPresent(
templateName ->
loadCodeTransformer(resource)
.ifPresent(transformer -> transformers.put(templateName, transformer)));
}
return transformers.build();
}
private static ImmutableSet<ResourceInfo> getClassPathResources() {
try {
return ClassPath.from(
Objects.requireNonNullElseGet(
RefasterCheck.class.getClassLoader(), () -> ClassLoader.getSystemClassLoader()))
.getResources();
} catch (IOException e) {
throw new IllegalStateException("Failed to scan classpath for resources", e);
}
}
private static Optional<String> getRefasterTemplateName(ResourceInfo resource) {
String resourceName = resource.getResourceName();
if (!resourceName.endsWith(REFASTER_TEMPLATE_SUFFIX)) {
return Optional.empty();
}
int lastPathSeparator = resourceName.lastIndexOf('/');
int beginIndex = lastPathSeparator < 0 ? 0 : lastPathSeparator + 1;
int endIndex = resourceName.length() - REFASTER_TEMPLATE_SUFFIX.length();
return Optional.of(resourceName.substring(beginIndex, endIndex));
}
private static Optional<CodeTransformer> loadCodeTransformer(ResourceInfo resource) {
try (InputStream in = resource.url().openStream();
ObjectInputStream ois = new ObjectInputStream(in)) {
return Optional.of((CodeTransformer) ois.readObject());
} catch (NoSuchElementException e) {
/* For some reason we can't load the resource. Skip it. */
// XXX: Should we log this?
return Optional.empty();
} catch (IOException | ClassNotFoundException e) {
throw new IllegalStateException("Can't load `CodeTransformer` from " + resource, e);
}
}
}

View File

@@ -0,0 +1,116 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.Placeholder;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.EnumSet;
import java.util.Set;
import javax.lang.model.element.Modifier;
/**
* A {@link BugChecker} that suggests a canonical set of modifiers for Refaster class and method
* definitions.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Refaster class and method definitions should specify a canonical set of modifiers",
link = BUG_PATTERNS_BASE_URL + "RefasterRuleModifiers",
linkType = CUSTOM,
severity = SUGGESTION,
tags = STYLE)
public final class RefasterRuleModifiers extends BugChecker
implements ClassTreeMatcher, MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<Tree> BEFORE_TEMPLATE_METHOD = hasAnnotation(BeforeTemplate.class);
private static final Matcher<Tree> AFTER_TEMPLATE_METHOD = hasAnnotation(AfterTemplate.class);
private static final Matcher<Tree> PLACEHOLDER_METHOD = hasAnnotation(Placeholder.class);
private static final Matcher<Tree> REFASTER_METHOD =
anyOf(BEFORE_TEMPLATE_METHOD, AFTER_TEMPLATE_METHOD, PLACEHOLDER_METHOD);
/** Instantiates a new {@link RefasterRuleModifiers} instance. */
public RefasterRuleModifiers() {}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (!hasMatchingMember(tree, BEFORE_TEMPLATE_METHOD, state)) {
/* This class does not contain a Refaster template. */
return Description.NO_MATCH;
}
SuggestedFix fix = suggestCanonicalModifiers(tree, state);
return fix.isEmpty() ? Description.NO_MATCH : describeMatch(tree, fix);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!REFASTER_METHOD.matches(tree, state)) {
return Description.NO_MATCH;
}
return SuggestedFixes.removeModifiers(
tree,
state,
Modifier.FINAL,
Modifier.PRIVATE,
Modifier.PROTECTED,
Modifier.PUBLIC,
Modifier.STATIC,
Modifier.SYNCHRONIZED)
.map(fix -> describeMatch(tree, fix))
.orElse(Description.NO_MATCH);
}
private static SuggestedFix suggestCanonicalModifiers(ClassTree tree, VisitorState state) {
Set<Modifier> modifiersToAdd = EnumSet.noneOf(Modifier.class);
Set<Modifier> modifiersToRemove =
EnumSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC, Modifier.SYNCHRONIZED);
if (!hasMatchingMember(tree, PLACEHOLDER_METHOD, state)) {
/*
* Rules without a `@Placeholder` method should be `final`. Note that Refaster enforces
* that `@Placeholder` methods are `abstract`, so rules _with_ such a method will
* naturally be `abstract` and non-`final`.
*/
modifiersToAdd.add(Modifier.FINAL);
modifiersToRemove.add(Modifier.ABSTRACT);
}
if (ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class) != null) {
/* Nested classes should be `static`. */
modifiersToAdd.add(Modifier.STATIC);
}
SuggestedFix.Builder fix = SuggestedFix.builder();
SuggestedFixes.addModifiers(tree, tree.getModifiers(), state, modifiersToAdd)
.ifPresent(fix::merge);
SuggestedFixes.removeModifiers(tree.getModifiers(), state, modifiersToRemove)
.ifPresent(fix::merge);
return fix.build();
}
private static boolean hasMatchingMember(
ClassTree tree, Matcher<Tree> matcher, VisitorState state) {
return tree.getMembers().stream().anyMatch(member -> matcher.matches(member, state));
}
}

View File

@@ -0,0 +1,107 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.not;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
/**
* A {@link BugChecker} that flags {@code @RequestMapping} methods that have one or more parameters
* that appear to lack a relevant annotation.
*
* <p>Matched mappings are {@code @{Delete,Get,Patch,Post,Put,Request}Mapping}.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Make sure all `@RequestMapping` method parameters are annotated",
link = BUG_PATTERNS_BASE_URL + "RequestMappingAnnotation",
linkType = CUSTOM,
severity = WARNING,
tags = LIKELY_ERROR)
public final class RequestMappingAnnotation extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String ANN_PACKAGE_PREFIX = "org.springframework.web.bind.annotation.";
// XXX: Generalize this logic to fully support Spring meta-annotations, then update the class
// documentation.
private static final Matcher<Tree> HAS_MAPPING_ANNOTATION =
annotations(
AT_LEAST_ONE,
anyOf(
isType(ANN_PACKAGE_PREFIX + "DeleteMapping"),
isType(ANN_PACKAGE_PREFIX + "GetMapping"),
isType(ANN_PACKAGE_PREFIX + "PatchMapping"),
isType(ANN_PACKAGE_PREFIX + "PostMapping"),
isType(ANN_PACKAGE_PREFIX + "PutMapping"),
isType(ANN_PACKAGE_PREFIX + "RequestMapping")));
// XXX: Add other parameters as necessary. Also consider whether it makes sense to have WebMVC-
// and WebFlux-specific logic. See
// https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-arguments
// and
// https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-arguments.
private static final Matcher<MethodTree> LACKS_PARAMETER_ANNOTATION =
not(
methodHasParameters(
ALL,
anyOf(
annotations(
AT_LEAST_ONE,
anyOf(
isType(ANN_PACKAGE_PREFIX + "PathVariable"),
isType(ANN_PACKAGE_PREFIX + "RequestAttribute"),
isType(ANN_PACKAGE_PREFIX + "RequestBody"),
isType(ANN_PACKAGE_PREFIX + "RequestHeader"),
isType(ANN_PACKAGE_PREFIX + "RequestParam"),
isType(ANN_PACKAGE_PREFIX + "RequestPart"))),
isSameType("java.io.InputStream"),
isSameType("java.time.ZoneId"),
isSameType("java.util.Locale"),
isSameType("java.util.TimeZone"),
isSameType("jakarta.servlet.http.HttpServletRequest"),
isSameType("jakarta.servlet.http.HttpServletResponse"),
isSameType("javax.servlet.http.HttpServletRequest"),
isSameType("javax.servlet.http.HttpServletResponse"),
isSameType("org.springframework.http.HttpMethod"),
isSameType("org.springframework.ui.Model"),
isSameType("org.springframework.validation.BindingResult"),
isSameType("org.springframework.web.context.request.NativeWebRequest"),
isSameType("org.springframework.web.context.request.WebRequest"),
isSameType("org.springframework.web.server.ServerWebExchange"),
isSameType("org.springframework.web.util.UriBuilder"),
isSameType("org.springframework.web.util.UriComponentsBuilder"))));
/** Instantiates a new {@link RequestMappingAnnotation} instance. */
public RequestMappingAnnotation() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
// XXX: Auto-add `@RequestParam` where applicable.
// XXX: What about the `PurchasingProposerRequestParams` in POM? Implies `@RequestBody`?
// (Documentation doesn't mention this, IIUC.)
return HAS_MAPPING_ANNOTATION.matches(tree, state)
&& LACKS_PARAMETER_ANNOTATION.matches(tree, state)
? buildDescription(tree)
.setMessage(
"Not all parameters of this request mapping method are annotated; this may be a mistake. "
+ "If the unannotated parameters represent query string parameters, annotate them with `@RequestParam`.")
.build()
: Description.NO_MATCH;
}
}

View File

@@ -0,0 +1,81 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.not;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import tech.picnic.errorprone.bugpatterns.util.Flags;
/** A {@link BugChecker} that flags {@code @RequestParam} parameters with an unsupported type. */
@AutoService(BugChecker.class)
@BugPattern(
summary =
"By default, `@RequestParam` does not support `ImmutableCollection` and `ImmutableMap` subtypes",
link = BUG_PATTERNS_BASE_URL + "RequestParamType",
linkType = CUSTOM,
severity = ERROR,
tags = LIKELY_ERROR)
public final class RequestParamType extends BugChecker implements VariableTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String SUPPORTED_CUSTOM_TYPES_FLAG = "RequestParamType:SupportedCustomTypes";
private final Matcher<VariableTree> hasUnsupportedRequestParamType;
/** Instantiates a default {@link RequestParamType} instance. */
public RequestParamType() {
this(ErrorProneFlags.empty());
}
/**
* Instantiates a customized {@link RequestParamType} instance.
*
* @param flags Any provided command line flags.
*/
public RequestParamType(ErrorProneFlags flags) {
hasUnsupportedRequestParamType = hasUnsupportedRequestParamType(flags);
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return hasUnsupportedRequestParamType.matches(tree, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
private static Matcher<VariableTree> hasUnsupportedRequestParamType(ErrorProneFlags flags) {
return allOf(
annotations(AT_LEAST_ONE, isType("org.springframework.web.bind.annotation.RequestParam")),
anyOf(isSubtypeOf(ImmutableCollection.class), isSubtypeOf(ImmutableMap.class)),
not(isSubtypeOfAny(Flags.getList(flags, SUPPORTED_CUSTOM_TYPES_FLAG))));
}
private static Matcher<Tree> isSubtypeOfAny(ImmutableList<String> inclusions) {
return anyOf(
inclusions.stream()
.map(inclusion -> isSubtypeOf(Suppliers.typeFromString(inclusion)))
.collect(toImmutableList()));
}
}

View File

@@ -0,0 +1,94 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.isType;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.common.AnnotationMirrors;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import tech.picnic.errorprone.bugpatterns.util.ThirdPartyLibrary;
/**
* A {@link BugChecker} that flags methods with Spring's {@code @Scheduled} annotation that lack New
* Relic Agent's {@code @Trace(dispatcher = true)}.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Scheduled operation must start a new New Relic transaction",
link = BUG_PATTERNS_BASE_URL + "ScheduledTransactionTrace",
linkType = CUSTOM,
severity = ERROR,
tags = LIKELY_ERROR)
public final class ScheduledTransactionTrace extends BugChecker implements MethodTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String TRACE_ANNOTATION_FQCN = "com.newrelic.api.agent.Trace";
private static final Matcher<Tree> IS_SCHEDULED =
hasAnnotation("org.springframework.scheduling.annotation.Scheduled");
private static final MultiMatcher<Tree, AnnotationTree> TRACE_ANNOTATION =
annotations(AT_LEAST_ONE, isType(TRACE_ANNOTATION_FQCN));
/** Instantiates a new {@link ScheduledTransactionTrace} instance. */
public ScheduledTransactionTrace() {}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!ThirdPartyLibrary.NEW_RELIC_AGENT_API.isIntroductionAllowed(state)
|| !IS_SCHEDULED.matches(tree, state)) {
return Description.NO_MATCH;
}
ImmutableList<AnnotationTree> traceAnnotations =
TRACE_ANNOTATION.multiMatchResult(tree, state).matchingNodes();
if (traceAnnotations.isEmpty()) {
/* This method completely lacks the `@Trace` annotation; add it. */
return describeMatch(
tree,
SuggestedFix.builder()
.addImport(TRACE_ANNOTATION_FQCN)
.prefixWith(tree, "@Trace(dispatcher = true)")
.build());
}
AnnotationTree traceAnnotation = Iterables.getOnlyElement(traceAnnotations);
if (isCorrectAnnotation(traceAnnotation)) {
return Description.NO_MATCH;
}
/*
* The `@Trace` annotation is present but does not specify `dispatcher = true`. Add or update
* the `dispatcher` annotation element.
*/
return describeMatch(
traceAnnotation,
SuggestedFixes.updateAnnotationArgumentValues(
traceAnnotation, state, "dispatcher", ImmutableList.of("true"))
.build());
}
private static boolean isCorrectAnnotation(AnnotationTree traceAnnotation) {
return Boolean.TRUE.equals(
AnnotationMirrors.getAnnotationValue(
ASTHelpers.getAnnotationMirror(traceAnnotation), "dispatcher")
.getValue());
}
}

View File

@@ -1,16 +1,16 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.base.Verify.verify;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.Splitter;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
@@ -23,31 +23,33 @@ import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree.Kind;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/** A {@link BugChecker} which flags SLF4J usages that are likely to be in error. */
/** A {@link BugChecker} that flags SLF4J usages that are likely to be in error. */
// XXX: The special-casing of Throwable applies only to SLF4J 1.6.0+; see
// https://www.slf4j.org/faq.html#paramException. That should be documented.
// XXX: Also simplify `LOG.error(String.format("Something %s", arg), throwable)`.
// XXX: Also simplify `LOG.error(String.join("sep", arg1, arg2), throwable)`? Perhaps too obscure.
// XXX: Write a similar checker for Spring RestTemplates, String.format and friends, Guava
// preconditions, ...
@AutoService(BugChecker.class)
@BugPattern(
name = "Slf4jLogStatement",
summary = "Make sure SLF4J log statements contain proper placeholders with matching arguments",
linkType = LinkType.NONE,
severity = SeverityLevel.WARNING,
tags = StandardTags.LIKELY_ERROR,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class Slf4jLogStatementCheck extends BugChecker
implements MethodInvocationTreeMatcher {
link = BUG_PATTERNS_BASE_URL + "Slf4jLogStatement",
linkType = CUSTOM,
severity = WARNING,
tags = LIKELY_ERROR)
public final class Slf4jLogStatement extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> MARKER = isSubtypeOf("org.slf4j.Marker");
private static final Matcher<ExpressionTree> THROWABLE = isSubtypeOf(Throwable.class);
private static final Matcher<ExpressionTree> SLF4J_LOGGER_INVOCATION =
instanceMethod()
.onDescendantOf("org.slf4j.Logger")
.withNameMatching(Pattern.compile("trace|debug|info|warn|error"));
.namedAnyOf("trace", "debug", "info", "warn", "error");
/** Instantiates a new {@link Slf4jLogStatement} instance. */
public Slf4jLogStatement() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
@@ -117,7 +119,7 @@ public final class Slf4jLogStatementCheck extends BugChecker
* replaced at this usage site.
*/
description.addFix(
SuggestedFix.replace(tree, Util.treeToString(tree, state).replace("%s", "{}")));
SuggestedFix.replace(tree, SourceCode.treeToString(tree, state).replace("%s", "{}")));
}
return false;

View File

@@ -1,17 +1,18 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.common.base.Verify.verify;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static java.util.function.Predicate.not;
import static java.util.stream.Collectors.joining;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
@@ -25,21 +26,22 @@ import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.Tree.Kind;
import java.util.Optional;
import tech.picnic.errorprone.bugpatterns.util.AnnotationAttributeMatcher;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} which flags {@code @RequestMapping} annotations that can be written more
* A {@link BugChecker} that flags {@code @RequestMapping} annotations that can be written more
* concisely.
*/
@AutoService(BugChecker.class)
@BugPattern(
name = "SpringMvcAnnotation",
summary =
"Prefer the conciseness of `@{Get,Put,Post,Delete,Patch}Mapping` over `@RequestMapping`",
linkType = LinkType.NONE,
severity = SeverityLevel.SUGGESTION,
tags = StandardTags.SIMPLIFICATION,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class SpringMvcAnnotationCheck extends BugChecker implements AnnotationTreeMatcher {
link = BUG_PATTERNS_BASE_URL + "SpringMvcAnnotation",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class SpringMvcAnnotation extends BugChecker implements AnnotationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final String ANN_PACKAGE_PREFIX = "org.springframework.web.bind.annotation.";
private static final AnnotationAttributeMatcher ARGUMENT_SELECTOR =
@@ -55,6 +57,9 @@ public final class SpringMvcAnnotationCheck extends BugChecker implements Annota
.put("PUT", "PutMapping")
.build();
/** Instantiates a new {@link SpringMvcAnnotation} instance. */
public SpringMvcAnnotation() {}
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
// XXX: We could remove the `@RequestMapping` import if not other usages remain.
@@ -70,7 +75,7 @@ public final class SpringMvcAnnotationCheck extends BugChecker implements Annota
AnnotationTree tree, ExpressionTree arg, VisitorState state) {
return extractUniqueMethod(arg, state)
.map(REPLACEMENTS::get)
.map(newAnnotation -> replaceAnnotation(tree, arg, newAnnotation));
.map(newAnnotation -> replaceAnnotation(tree, arg, newAnnotation, state));
}
private static Optional<String> extractUniqueMethod(ExpressionTree arg, VisitorState state) {
@@ -93,7 +98,7 @@ public final class SpringMvcAnnotationCheck extends BugChecker implements Annota
private static String extractMethod(ExpressionTree expr, VisitorState state) {
switch (expr.getKind()) {
case IDENTIFIER:
return Util.treeToString(expr, state);
return SourceCode.treeToString(expr, state);
case MEMBER_SELECT:
return ((MemberSelectTree) expr).getIdentifier().toString();
default:
@@ -102,11 +107,11 @@ public final class SpringMvcAnnotationCheck extends BugChecker implements Annota
}
private static Fix replaceAnnotation(
AnnotationTree tree, ExpressionTree arg, String newAnnotation) {
AnnotationTree tree, ExpressionTree argToRemove, String newAnnotation, VisitorState state) {
String newArguments =
tree.getArguments().stream()
.filter(a -> !a.equals(arg))
.map(Object::toString)
.filter(not(argToRemove::equals))
.map(arg -> SourceCode.treeToString(arg, state))
.collect(joining(", "));
return SuggestedFix.builder()

View File

@@ -0,0 +1,262 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static java.util.Objects.requireNonNull;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
import com.google.errorprone.bugpatterns.StaticImports;
import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/**
* A {@link BugChecker} that flags methods and constants that can and should be statically imported.
*/
// XXX: Tricky cases:
// - `org.springframework.http.HttpStatus` (not always an improvement, and `valueOf` must
// certainly be excluded)
// - `com.google.common.collect.Tables`
// - `ch.qos.logback.classic.Level.{DEBUG, ERROR, INFO, TRACE, WARN"}`
// XXX: Also introduce a check that disallows static imports of certain methods. Candidates:
// - `com.google.common.base.Strings`
// - `java.util.Optional.empty`
// - `java.util.Locale.ROOT`
// - `ZoneOffset.ofHours` and other `ofXXX`-style methods.
// - `java.time.Clock`.
// - Several other `java.time` classes.
// - Likely any of `*.{ZERO, ONE, MIX, MAX, MIN_VALUE, MAX_VALUE}`.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Identifier should be statically imported",
link = BUG_PATTERNS_BASE_URL + "StaticImport",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class StaticImport extends BugChecker implements MemberSelectTreeMatcher {
private static final long serialVersionUID = 1L;
/**
* Types whose members should be statically imported, unless exempted by {@link
* #STATIC_IMPORT_EXEMPTED_MEMBERS} or {@link #STATIC_IMPORT_EXEMPTED_IDENTIFIERS}.
*/
@VisibleForTesting
static final ImmutableSet<String> STATIC_IMPORT_CANDIDATE_TYPES =
ImmutableSet.of(
"com.google.common.base.Preconditions",
"com.google.common.base.Predicates",
"com.google.common.base.Verify",
"com.google.common.collect.MoreCollectors",
"com.google.errorprone.BugPattern.LinkType",
"com.google.errorprone.BugPattern.SeverityLevel",
"com.google.errorprone.BugPattern.StandardTags",
"com.google.errorprone.matchers.Matchers",
"com.google.errorprone.refaster.ImportPolicy",
"com.mongodb.client.model.Accumulators",
"com.mongodb.client.model.Aggregates",
"com.mongodb.client.model.Filters",
"com.mongodb.client.model.Indexes",
"com.mongodb.client.model.Projections",
"com.mongodb.client.model.Sorts",
"com.mongodb.client.model.Updates",
"java.nio.charset.StandardCharsets",
"java.util.Collections",
"java.util.Comparator",
"java.util.Map.Entry",
"java.util.regex.Pattern",
"java.util.stream.Collectors",
"org.assertj.core.api.Assertions",
"org.assertj.core.api.InstanceOfAssertFactories",
"org.assertj.core.api.SoftAssertions",
"org.assertj.core.data.Offset",
"org.assertj.core.groups.Tuple",
"org.hamcrest.Matchers",
"org.hamcrest.text.MatchesPattern",
"org.hibernate.validator.testutil.ConstraintViolationAssert",
"org.junit.jupiter.api.Assertions",
"org.mockito.AdditionalAnswers",
"org.mockito.Answers",
"org.mockito.ArgumentMatchers",
"org.mockito.Mockito",
"org.springframework.boot.test.context.SpringBootTest.WebEnvironment",
"org.springframework.format.annotation.DateTimeFormat.ISO",
"org.springframework.http.HttpHeaders",
"org.springframework.http.HttpMethod",
"org.springframework.http.MediaType",
"org.testng.Assert",
"reactor.function.TupleUtils",
"tech.picnic.errorprone.bugpatterns.util.MoreTypes");
/** Type members that should be statically imported. */
@VisibleForTesting
static final ImmutableSetMultimap<String, String> STATIC_IMPORT_CANDIDATE_MEMBERS =
ImmutableSetMultimap.<String, String>builder()
.putAll(
"com.google.common.collect.ImmutableListMultimap",
"flatteningToImmutableListMultimap",
"toImmutableListMultimap")
.put("com.google.common.collect.ImmutableList", "toImmutableList")
.put("com.google.common.collect.ImmutableMap", "toImmutableMap")
.put("com.google.common.collect.ImmutableMultiset", "toImmutableMultiset")
.put("com.google.common.collect.ImmutableRangeSet", "toImmutableRangeSet")
.putAll(
"com.google.common.collect.ImmutableSetMultimap",
"flatteningToImmutableSetMultimap",
"toImmutableSetMultimap")
.put("com.google.common.collect.ImmutableSet", "toImmutableSet")
.put("com.google.common.collect.ImmutableSortedMap", "toImmutableSortedMap")
.put("com.google.common.collect.ImmutableSortedMultiset", "toImmutableSortedMultiset")
.put("com.google.common.collect.ImmutableSortedSet", "toImmutableSortedSet")
.put("com.google.common.collect.ImmutableTable", "toImmutableTable")
.put("com.google.common.collect.Sets", "toImmutableEnumSet")
.put("com.google.common.base.Functions", "identity")
.put("java.time.ZoneOffset", "UTC")
.put("java.util.function.Function", "identity")
.put("java.util.function.Predicate", "not")
.put("java.util.UUID", "randomUUID")
.put("org.junit.jupiter.params.provider.Arguments", "arguments")
.putAll(
"java.util.Objects",
"checkIndex",
"checkFromIndexSize",
"checkFromToIndex",
"requireNonNull",
"requireNonNullElse",
"requireNonNullElseGet")
.putAll("com.google.common.collect.Comparators", "emptiesFirst", "emptiesLast")
.build();
/**
* Type members that should never be statically imported.
*
* <p>Identifiers listed by {@link #STATIC_IMPORT_EXEMPTED_IDENTIFIERS} should be omitted from
* this collection.
*/
// XXX: Perhaps the set of exempted `java.util.Collections` methods is too strict. For now any
// method name that could be considered "too vague" or could conceivably mean something else in a
// specific context is left out.
@VisibleForTesting
static final ImmutableSetMultimap<String, String> STATIC_IMPORT_EXEMPTED_MEMBERS =
ImmutableSetMultimap.<String, String>builder()
.put("com.mongodb.client.model.Filters", "empty")
.putAll(
"java.util.Collections",
"addAll",
"copy",
"fill",
"list",
"max",
"min",
"nCopies",
"rotate",
"sort",
"swap")
.putAll("java.util.regex.Pattern", "compile", "matches", "quote")
.put("org.springframework.http.MediaType", "ALL")
.build();
/**
* Identifiers that should never be statically imported.
*
* <p>This should be a superset of the identifiers flagged by {@link
* com.google.errorprone.bugpatterns.BadImport}.
*/
@VisibleForTesting
static final ImmutableSet<String> STATIC_IMPORT_EXEMPTED_IDENTIFIERS =
ImmutableSet.of(
"builder",
"create",
"copyOf",
"from",
"getDefaultInstance",
"INSTANCE",
"newBuilder",
"of",
"valueOf");
/** Instantiates a new {@link StaticImport} instance. */
public StaticImport() {}
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
if (!isCandidateContext(state) || !isCandidate(tree)) {
return Description.NO_MATCH;
}
StaticImportInfo importInfo = StaticImports.tryCreate(tree, state);
if (importInfo == null) {
return Description.NO_MATCH;
}
return getCandidateSimpleName(importInfo)
.flatMap(n -> tryStaticImport(tree, importInfo.canonicalName() + '.' + n, n, state))
.map(fix -> describeMatch(tree, fix))
.orElse(Description.NO_MATCH);
}
private static boolean isCandidateContext(VisitorState state) {
Tree parentTree =
requireNonNull(state.getPath().getParentPath(), "MemberSelectTree lacks enclosing node")
.getLeaf();
switch (parentTree.getKind()) {
case IMPORT:
case MEMBER_SELECT:
return false;
case METHOD_INVOCATION:
return ((MethodInvocationTree) parentTree).getTypeArguments().isEmpty();
default:
return true;
}
}
private static boolean isCandidate(MemberSelectTree tree) {
String identifier = tree.getIdentifier().toString();
if (STATIC_IMPORT_EXEMPTED_IDENTIFIERS.contains(identifier)) {
return false;
}
Type type = ASTHelpers.getType(tree.getExpression());
return type != null
&& !STATIC_IMPORT_EXEMPTED_MEMBERS.containsEntry(type.toString(), identifier);
}
private static Optional<String> getCandidateSimpleName(StaticImportInfo importInfo) {
String canonicalName = importInfo.canonicalName();
return importInfo
.simpleName()
.toJavaUtil()
.filter(
name ->
STATIC_IMPORT_CANDIDATE_TYPES.contains(canonicalName)
|| STATIC_IMPORT_CANDIDATE_MEMBERS.containsEntry(canonicalName, name));
}
private static Optional<Fix> tryStaticImport(
MemberSelectTree tree, String fullyQualifiedName, String simpleName, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder().replace(tree, simpleName);
if (!simpleName.equals(SuggestedFixes.qualifyStaticImport(fullyQualifiedName, fix, state))) {
/* Statically importing this symbol would clash with an existing import. */
return Optional.empty();
}
return Optional.of(fix.build());
}
}

View File

@@ -0,0 +1,89 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.sun.tools.javac.parser.Tokens.TokenKind.RPAREN;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.collect.Streams;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.ErrorProneTokens;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.util.Position;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags calls to {@link String#toLowerCase()} and {@link
* String#toUpperCase()}, as these methods implicitly rely on the environment's default locale.
*/
// XXX: Also flag `String::toLowerCase` and `String::toUpperCase` method references. For these cases
// the suggested fix should introduce a lambda expression with a parameter of which the name does
// not coincide with the name of an existing variable name. Such functionality should likely be
// introduced in a utility class.
@AutoService(BugChecker.class)
@BugPattern(
summary = "Specify a `Locale` when calling `String#to{Lower,Upper}Case`",
link = BUG_PATTERNS_BASE_URL + "StringCaseLocaleUsage",
linkType = CUSTOM,
severity = WARNING,
tags = FRAGILE_CODE)
public final class StringCaseLocaleUsage extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> DEFAULT_LOCALE_CASE_CONVERSION =
instanceMethod()
.onExactClass(String.class.getName())
.namedAnyOf("toLowerCase", "toUpperCase")
.withNoParameters();
/** Instantiates a new {@link StringCaseLocaleUsage} instance. */
public StringCaseLocaleUsage() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!DEFAULT_LOCALE_CASE_CONVERSION.matches(tree, state)) {
return Description.NO_MATCH;
}
int closingParenPosition = getClosingParenPosition(tree, state);
if (closingParenPosition == Position.NOPOS) {
return describeMatch(tree);
}
return buildDescription(tree)
.addFix(suggestLocale(closingParenPosition, "Locale.ROOT"))
.addFix(suggestLocale(closingParenPosition, "Locale.getDefault()"))
.build();
}
private static Fix suggestLocale(int insertPosition, String locale) {
return SuggestedFix.builder()
.addImport("java.util.Locale")
.replace(insertPosition, insertPosition, locale)
.build();
}
private static int getClosingParenPosition(MethodInvocationTree tree, VisitorState state) {
int startPosition = ASTHelpers.getStartPosition(tree);
if (startPosition == Position.NOPOS) {
return Position.NOPOS;
}
return Streams.findLast(
ErrorProneTokens.getTokens(SourceCode.treeToString(tree, state), state.context).stream()
.filter(t -> t.kind() == RPAREN))
.map(token -> startPosition + token.pos())
.orElse(Position.NOPOS);
}
}

View File

@@ -0,0 +1,187 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Convert;
import java.util.Formattable;
import java.util.Iterator;
import java.util.List;
import org.jspecify.annotations.Nullable;
import tech.picnic.errorprone.bugpatterns.util.SourceCode;
/**
* A {@link BugChecker} that flags {@link String#format(String, Object...)} invocations which can be
* replaced with a {@link String#join(CharSequence, CharSequence...)} or even a {@link
* String#valueOf} invocation.
*/
// XXX: What about `v1 + "sep" + v2` and similar expressions? Do we want to rewrite those to
// `String.join`, or should some `String.join` invocations be rewritten to use the `+` operator?
// (The latter suggestion would conflict with the `FormatStringConcatenation` check.)
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer `String#join` over `String#format`",
link = BUG_PATTERNS_BASE_URL + "StringJoin",
linkType = CUSTOM,
severity = SUGGESTION,
tags = SIMPLIFICATION)
public final class StringJoin extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Splitter FORMAT_SPECIFIER_SPLITTER = Splitter.on("%s");
private static final Matcher<ExpressionTree> STRING_FORMAT_INVOCATION =
staticMethod().onClass(String.class.getName()).named("format");
private static final Supplier<Type> CHAR_SEQUENCE_TYPE =
Suppliers.typeFromClass(CharSequence.class);
private static final Supplier<Type> FORMATTABLE_TYPE = Suppliers.typeFromClass(Formattable.class);
/** Instantiates a new {@link StringJoin} instance. */
public StringJoin() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!STRING_FORMAT_INVOCATION.matches(tree, state)) {
return Description.NO_MATCH;
}
// XXX: This check assumes that if the first argument to `String#format` is a `Locale`, that
// this argument is not vacuous, and that as a result the expression cannot be simplified using
// `#valueOf` or `#join`. Implement a separate check that identifies and drops redundant
// `Locale` arguments. See also a related comment in `FormatStringConcatenation`.
String formatString = ASTHelpers.constValue(tree.getArguments().get(0), String.class);
if (formatString == null) {
return Description.NO_MATCH;
}
List<String> separators = FORMAT_SPECIFIER_SPLITTER.splitToList(formatString);
if (separators.size() < 2) {
/* The format string does not contain `%s` format specifiers. */
return Description.NO_MATCH;
}
if (separators.size() != tree.getArguments().size()) {
/* The number of arguments does not match the number of `%s` format specifiers. */
return Description.NO_MATCH;
}
int lastIndex = separators.size() - 1;
if (!separators.get(0).isEmpty() || !separators.get(lastIndex).isEmpty()) {
/* The format string contains leading or trailing characters. */
return Description.NO_MATCH;
}
ImmutableSet<String> innerSeparators = ImmutableSet.copyOf(separators.subList(1, lastIndex));
if (innerSeparators.size() > 1) {
/* The `%s` format specifiers are not uniformly separated. */
return Description.NO_MATCH;
}
if (innerSeparators.isEmpty()) {
/*
* This `String#format` invocation performs a straightforward string conversion; use
* `String#valueOf` instead.
*/
return trySuggestExplicitStringConversion(tree, state);
}
String separator = Iterables.getOnlyElement(innerSeparators);
if (separator.indexOf('%') >= 0) {
/* The `%s` format specifiers are separated by another format specifier. */
// XXX: Strictly speaking we could support `%%` by mapping it to a literal `%`, but that
// doesn't seem worth the trouble.
return Description.NO_MATCH;
}
return trySuggestExplicitJoin(tree, separator, state);
}
/**
* If guaranteed to be behavior preserving, suggests replacing {@code String.format("%s", arg)}
* with {@code String.valueOf(arg)}.
*
* <p>If {@code arg} is already a string then the resultant conversion is vacuous. The {@link
* IdentityConversion} check will subsequently drop it.
*/
private Description trySuggestExplicitStringConversion(
MethodInvocationTree tree, VisitorState state) {
ExpressionTree argument = tree.getArguments().get(1);
if (isSubtype(ASTHelpers.getType(argument), FORMATTABLE_TYPE, state)) {
/*
* `Formattable` arguments are handled specially; `String#valueOf` is not a suitable
* alternative.
*/
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage("Prefer `String#valueOf` over `String#format`")
.addFix(SuggestedFix.replace(tree, withStringConversionExpression(argument, state)))
.build();
}
/**
* Unless the given {@code String.format} expression includes {@link Formattable} arguments,
* suggests replacing it with a {@code String.join} expression using the specified argument
* separator.
*/
private Description trySuggestExplicitJoin(
MethodInvocationTree tree, String separator, VisitorState state) {
Iterator<? extends ExpressionTree> arguments = tree.getArguments().iterator();
SuggestedFix.Builder fix =
SuggestedFix.builder()
.replace(tree.getMethodSelect(), "String.join")
.replace(arguments.next(), String.format("\"%s\"", Convert.quote(separator)));
while (arguments.hasNext()) {
ExpressionTree argument = arguments.next();
Type argumentType = ASTHelpers.getType(argument);
if (isSubtype(argumentType, FORMATTABLE_TYPE, state)) {
/*
* `Formattable` arguments are handled specially; `String#join` is not a suitable
* alternative.
*/
return Description.NO_MATCH;
}
if (!isSubtype(argumentType, CHAR_SEQUENCE_TYPE, state)) {
/*
* The argument was previously implicitly converted to a string; now this must happen
* explicitly.
*/
fix.replace(argument, withStringConversionExpression(argument, state));
}
}
return describeMatch(tree, fix.build());
}
private static boolean isSubtype(
@Nullable Type subType, Supplier<Type> superType, VisitorState state) {
return ASTHelpers.isSubtype(subType, superType.get(state), state);
}
private static String withStringConversionExpression(
ExpressionTree argument, VisitorState state) {
return String.format("String.valueOf(%s)", SourceCode.treeToString(argument, state));
}
}

View File

@@ -0,0 +1,80 @@
package tech.picnic.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZonedDateTime;
/** A {@link BugChecker} that flags illegal time-zone related operations. */
@AutoService(BugChecker.class)
@BugPattern(
summary =
"Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone",
link = BUG_PATTERNS_BASE_URL + "TimeZoneUsage",
linkType = CUSTOM,
severity = WARNING,
tags = FRAGILE_CODE)
public final class TimeZoneUsage extends BugChecker implements MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
private static final Matcher<ExpressionTree> BANNED_TIME_METHOD =
anyOf(
allOf(
instanceMethod()
.onDescendantOf(Clock.class.getName())
.namedAnyOf("getZone", "withZone"),
not(enclosingClass(isSubtypeOf(Clock.class)))),
staticMethod()
.onClass(Clock.class.getName())
.namedAnyOf(
"system",
"systemDefaultZone",
"systemUTC",
"tickMillis",
"tickMinutes",
"tickSeconds"),
staticMethod()
.onClassAny(
LocalDate.class.getName(),
LocalDateTime.class.getName(),
LocalTime.class.getName(),
OffsetDateTime.class.getName(),
OffsetTime.class.getName(),
ZonedDateTime.class.getName())
.named("now"),
staticMethod().onClassAny(Instant.class.getName()).named("now").withNoParameters());
/** Instantiates a new {@link TimeZoneUsage} instance. */
public TimeZoneUsage() {}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return BANNED_TIME_METHOD.matches(tree, state)
? buildDescription(tree).build()
: Description.NO_MATCH;
}
}

View File

@@ -1,20 +0,0 @@
package tech.picnic.errorprone.bugpatterns;
import com.google.errorprone.VisitorState;
import com.sun.source.tree.Tree;
// XXX: Can we locate this code in a better place? Maybe contribute it upstream?
final class Util {
private Util() {}
/**
* Returns a string representation of the given {@link Tree}, preferring the original source code
* (if available) over its prettified representation.
*
* @return A non-{@code null} string.
*/
static String treeToString(Tree tree, VisitorState state) {
String src = state.getSourceForNode(tree);
return src != null ? src : tree.toString();
}
}

View File

@@ -1,7 +1,4 @@
/** Picnic Error Prone Contrib checks. */
@CheckReturnValue
@ParametersAreNonnullByDefault
@com.google.errorprone.annotations.CheckReturnValue
@org.jspecify.annotations.NullMarked
package tech.picnic.errorprone.bugpatterns;
import com.google.errorprone.annotations.CheckReturnValue;
import javax.annotation.ParametersAreNonnullByDefault;

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.bugpatterns;
package tech.picnic.errorprone.bugpatterns.util;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultimap;
@@ -21,13 +21,14 @@ import java.util.stream.Stream;
// XXX: Redefine using auto-value
// XXX: Document design decision that the project stays as close as possible to Error Prone.
// ^ ... and *therefore* uses Google Auto Value rather than Immutables.org.
// XXX: Make this class implement the `MultiMatcher` interface.
/**
* A matcher of (annotation, attribute) pairs.
*
* <p>This class allows one to define a whitelist or blacklist of annotations or their attributes.
* Annotations are identified by their fully qualified name.
*/
final class AnnotationAttributeMatcher implements Serializable {
public final class AnnotationAttributeMatcher implements Serializable {
private static final long serialVersionUID = 1L;
private final boolean complement;
@@ -58,7 +59,7 @@ final class AnnotationAttributeMatcher implements Serializable {
* @param exclusions The listed annotations or annotation attributes are not matched.
* @return A non-{@code null} {@link AnnotationAttributeMatcher}.
*/
static AnnotationAttributeMatcher create(
public static AnnotationAttributeMatcher create(
Optional<? extends List<String>> inclusions, Iterable<String> exclusions) {
Set<String> includedWholeTypes = new HashSet<>();
Set<String> excludedWholeTypes = new HashSet<>();
@@ -88,7 +89,6 @@ final class AnnotationAttributeMatcher implements Serializable {
int hash = entry.indexOf('#');
if (hash < 0) {
wholeTypes.add(entry);
} else {
String annotationType = entry.substring(0, hash);
String attribute = entry.substring(hash + 1);
@@ -97,7 +97,13 @@ final class AnnotationAttributeMatcher implements Serializable {
}
}
Stream<? extends ExpressionTree> extractMatchingArguments(AnnotationTree tree) {
/**
* Returns the subset of arguments of the given {@link AnnotationTree} matched by this instance.
*
* @param tree The annotation AST node to be inspected.
* @return Any matching annotation arguments.
*/
public Stream<? extends ExpressionTree> extractMatchingArguments(AnnotationTree tree) {
Type type = ASTHelpers.getType(tree.getAnnotationType());
if (type == null) {
return Stream.empty();

View File

@@ -0,0 +1,75 @@
package tech.picnic.errorprone.bugpatterns.util;
import static tech.picnic.errorprone.bugpatterns.util.JavaKeywords.isValidIdentifier;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import java.util.Optional;
/** A set of helper methods for detecting conflicts that would be caused when applying fixes. */
public final class ConflictDetection {
private ConflictDetection() {}
/**
* If applicable, returns a human-readable argument against assigning the given name to an
* existing method.
*
* <p>This method implements imperfect heuristics. Things it currently does not consider include
* the following:
*
* <ul>
* <li>Whether the rename would merely introduce a method overload, rather than clashing with an
* existing method declaration in its class or a supertype.
* <li>Whether the rename would in fact clash with a static import. (It could be that a static
* import of the same name is only referenced from lexical scopes in which the method under
* consideration cannot be referenced directly.)
* </ul>
*
* @param method The method considered for renaming.
* @param newName The newly proposed name for the method.
* @param state The {@link VisitorState} to use when searching for blockers.
* @return A human-readable argument against assigning the proposed name to the given method, or
* {@link Optional#empty()} if no blocker was found.
*/
public static Optional<String> findMethodRenameBlocker(
MethodSymbol method, String newName, VisitorState state) {
if (isExistingMethodName(method.owner.type, newName, state)) {
return Optional.of(
String.format(
"a method named `%s` is already defined in this class or a supertype", newName));
}
if (isSimpleNameStaticallyImported(newName, state)) {
return Optional.of(String.format("`%s` is already statically imported", newName));
}
if (!isValidIdentifier(newName)) {
return Optional.of(String.format("`%s` is not a valid identifier", newName));
}
return Optional.empty();
}
private static boolean isExistingMethodName(Type clazz, String name, VisitorState state) {
return ASTHelpers.matchingMethods(state.getName(name), method -> true, clazz, state.getTypes())
.findAny()
.isPresent();
}
private static boolean isSimpleNameStaticallyImported(String simpleName, VisitorState state) {
return state.getPath().getCompilationUnit().getImports().stream()
.filter(ImportTree::isStatic)
.map(ImportTree::getQualifiedIdentifier)
.map(tree -> getStaticImportSimpleName(tree, state))
.anyMatch(simpleName::contentEquals);
}
private static CharSequence getStaticImportSimpleName(Tree tree, VisitorState state) {
String source = SourceCode.treeToString(tree, state);
return source.subSequence(source.lastIndexOf('.') + 1, source.length());
}
}

View File

@@ -0,0 +1,9 @@
package tech.picnic.errorprone.bugpatterns.util;
/** Utility class providing documentation-related code. */
public final class Documentation {
/** The base URL at which Error Prone Support bug patterns are hosted. */
public static final String BUG_PATTERNS_BASE_URL = "https://error-prone.picnic.tech/bugpatterns/";
private Documentation() {}
}

View File

@@ -0,0 +1,25 @@
package tech.picnic.errorprone.bugpatterns.util;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.ErrorProneFlags;
/** Helper methods for working with {@link ErrorProneFlags}. */
public final class Flags {
private Flags() {}
/**
* Returns the list of (comma-separated) arguments passed using the given Error Prone flag.
*
* @param errorProneFlags The full set of flags provided.
* @param name The name of the flag of interest.
* @return A non-{@code null} list of provided arguments; this list is empty if the flag was not
* provided, or if the flag's value is the empty string.
*/
public static ImmutableList<String> getList(ErrorProneFlags errorProneFlags, String name) {
return errorProneFlags
.getList(name)
.map(ImmutableList::copyOf)
.filter(flags -> !flags.equals(ImmutableList.of("")))
.orElseGet(ImmutableList::of);
}
}

View File

@@ -0,0 +1,155 @@
package tech.picnic.errorprone.bugpatterns.util;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/** Utility class that can be used to identify reserved keywords of the Java language. */
// XXX: This class is no longer only about keywords. Consider changing its name and class-level
// documentation.
public final class JavaKeywords {
/**
* Enumeration of boolean and null literals.
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.10.3">JDK 17
* JLS section 3.10.3: Boolean Literals</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.10.8">JDK 17
* JLS section 3.10.8: The Null Literal</a>
*/
private static final ImmutableSet<String> BOOLEAN_AND_NULL_LITERALS =
ImmutableSet.of("true", "false", "null");
/**
* List of all reserved keywords in the Java language.
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.9">JDK 17 JLS
* section 3.9: Keywords</a>
*/
private static final ImmutableSet<String> RESERVED_KEYWORDS =
ImmutableSet.of(
"_",
"abstract",
"assert",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extends",
"final",
"finally",
"float",
"for",
"goto",
"if",
"implements",
"import",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"strictfp",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"try",
"void",
"volatile",
"while");
/**
* List of all contextual keywords in the Java language.
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.9">JDK 17 JLS
* section 3.9: Keywords</a>
*/
private static final ImmutableSet<String> CONTEXTUAL_KEYWORDS =
ImmutableSet.of(
"exports",
"module",
"non-sealed",
"open",
"opens",
"permits",
"provides",
"record",
"requires",
"sealed",
"to",
"transitive",
"uses",
"var",
"with",
"yield");
/** List of all keywords in the Java language. */
private static final ImmutableSet<String> ALL_KEYWORDS =
Sets.union(RESERVED_KEYWORDS, CONTEXTUAL_KEYWORDS).immutableCopy();
private JavaKeywords() {}
/**
* Tells whether the given string is a valid identifier in the Java language.
*
* @param str The string of interest.
* @return {@code true} if the given string is a valid identifier in the Java language.
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.8">JDK 17 JLS
* section 3.8: Identifiers</a>
*/
public static boolean isValidIdentifier(String str) {
return !str.isEmpty()
&& !isReservedKeyword(str)
&& !BOOLEAN_AND_NULL_LITERALS.contains(str)
&& Character.isJavaIdentifierStart(str.codePointAt(0))
&& str.codePoints().skip(1).allMatch(Character::isUnicodeIdentifierPart);
}
/**
* Tells whether the given string is a reserved keyword in the Java language.
*
* @param str The string of interest.
* @return {@code true} if the given string is a reserved keyword in the Java language.
*/
public static boolean isReservedKeyword(String str) {
return RESERVED_KEYWORDS.contains(str);
}
/**
* Tells whether the given string is a contextual keyword in the Java language.
*
* @param str The string of interest.
* @return {@code true} if the given string is a contextual keyword in the Java language.
*/
public static boolean isContextualKeyword(String str) {
return CONTEXTUAL_KEYWORDS.contains(str);
}
/**
* Tells whether the given string is a reserved or contextual keyword in the Java language.
*
* @param str The string of interest.
* @return {@code true} if the given string is a reserved or contextual keyword in the Java
* language.
*/
public static boolean isKeyword(String str) {
return ALL_KEYWORDS.contains(str);
}
}

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.bugpatterns;
package tech.picnic.errorprone.bugpatterns.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
@@ -15,13 +15,23 @@ import java.util.regex.Pattern;
/** A method invocation expression {@link Matcher} factory. */
// XXX: Document better. The expressions accepted here could also be defined using `MethodMatchers`.
// So explain why this class is still useful.
final class MethodMatcherFactory {
public final class MethodMatcherFactory {
private static final Splitter ARGUMENT_TYPE_SPLITTER =
Splitter.on(',').trimResults().omitEmptyStrings();
private static final Pattern METHOD_SIGNATURE =
Pattern.compile("([^\\s#(,)]+)#([^\\s#(,)]+)\\(((?:[^\\s#(,)]+(?:,[^\\s#(,)]+)*)?)\\)");
Matcher<ExpressionTree> create(Collection<String> signatures) {
/** Instantiates a new {@link MethodMatcherFactory} instance. */
public MethodMatcherFactory() {}
/**
* Creates a {@link Matcher} of methods with any of the given signatures.
*
* @param signatures The method signatures of interest.
* @return A new {@link Matcher} which accepts invocation expressions of any method identified by
* the given signatures.
*/
public Matcher<ExpressionTree> create(Collection<String> signatures) {
return anyOf(
signatures.stream()
.map(MethodMatcherFactory::createMethodMatcher)

View File

@@ -0,0 +1,82 @@
package tech.picnic.errorprone.bugpatterns.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.Optional;
/**
* A collection of helper methods for working with the AST.
*
* <p>These methods are additions to the ones found in {@link
* com.google.errorprone.util.ASTHelpers}.
*/
public final class MoreASTHelpers {
private MoreASTHelpers() {}
/**
* Finds methods with the specified name in given the {@link VisitorState}'s current enclosing
* class.
*
* @param methodName The method name to search for.
* @param state The {@link VisitorState} from which to derive the enclosing class of interest.
* @return The {@link MethodTree}s of the methods with the given name in the enclosing class.
*/
public static ImmutableList<MethodTree> findMethods(CharSequence methodName, VisitorState state) {
ClassTree clazz = state.findEnclosing(ClassTree.class);
checkArgument(clazz != null, "Visited node is not enclosed by a class");
return clazz.getMembers().stream()
.filter(MethodTree.class::isInstance)
.map(MethodTree.class::cast)
.filter(method -> method.getName().contentEquals(methodName))
.collect(toImmutableList());
}
/**
* Determines whether there are any methods with the specified name in given the {@link
* VisitorState}'s current enclosing class.
*
* @param methodName The method name to search for.
* @param state The {@link VisitorState} from which to derive the enclosing class of interest.
* @return Whether there are any methods with the given name in the enclosing class.
*/
public static boolean methodExistsInEnclosingClass(CharSequence methodName, VisitorState state) {
return !findMethods(methodName, state).isEmpty();
}
/**
* Returns the {@link MethodTree} from which control flow would exit if there would be a {@code
* return} statement at the given {@link VisitorState}'s current {@link VisitorState#getPath()
* path}.
*
* @param state The {@link VisitorState} from which to derive the AST location of interest.
* @return A {@link MethodTree}, unless the {@link VisitorState}'s path does not point to an AST
* node located inside a method, or if the (hypothetical) {@code return} statement would exit
* a lambda expression instead.
*/
public static Optional<MethodTree> findMethodExitedOnReturn(VisitorState state) {
return Optional.ofNullable(state.findEnclosing(LambdaExpressionTree.class, MethodTree.class))
.filter(MethodTree.class::isInstance)
.map(MethodTree.class::cast);
}
/**
* Tells whether the given trees are of the same type, after type erasure.
*
* @param treeA The first tree of interest.
* @param treeB The second tree of interest.
* @param state The {@link VisitorState} describing the context in which the given trees were
* found.
* @return Whether the specified trees have the same erased types.
*/
public static boolean areSameType(Tree treeA, Tree treeB, VisitorState state) {
return ASTHelpers.isSameType(ASTHelpers.getType(treeA), ASTHelpers.getType(treeB), state);
}
}

View File

@@ -0,0 +1,115 @@
package tech.picnic.errorprone.bugpatterns.util;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static java.util.Objects.requireNonNullElse;
import static tech.picnic.errorprone.bugpatterns.util.MoreMatchers.hasMetaAnnotation;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.matchers.AnnotationMatcherUtils;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import org.jspecify.annotations.Nullable;
/**
* A collection of JUnit-specific helper methods and {@link Matcher}s.
*
* <p>These constants and methods are additions to the ones found in {@link
* com.google.errorprone.matchers.JUnitMatchers}.
*/
public final class MoreJUnitMatchers {
/** Matches JUnit Jupiter test methods. */
public static final MultiMatcher<MethodTree, AnnotationTree> TEST_METHOD =
annotations(
AT_LEAST_ONE,
anyOf(
isType("org.junit.jupiter.api.Test"),
hasMetaAnnotation("org.junit.jupiter.api.TestTemplate")));
/** Matches JUnit Jupiter setup and teardown methods. */
public static final MultiMatcher<MethodTree, AnnotationTree> SETUP_OR_TEARDOWN_METHOD =
annotations(
AT_LEAST_ONE,
anyOf(
isType("org.junit.jupiter.api.AfterAll"),
isType("org.junit.jupiter.api.AfterEach"),
isType("org.junit.jupiter.api.BeforeAll"),
isType("org.junit.jupiter.api.BeforeEach")));
/**
* Matches methods that have a {@link org.junit.jupiter.params.provider.MethodSource} annotation.
*/
public static final MultiMatcher<MethodTree, AnnotationTree> HAS_METHOD_SOURCE =
annotations(AT_LEAST_ONE, isType("org.junit.jupiter.params.provider.MethodSource"));
private MoreJUnitMatchers() {}
/**
* Returns the names of the JUnit value factory methods specified by the given {@link
* org.junit.jupiter.params.provider.MethodSource} annotation.
*
* <p>This method differs from {@link #getMethodSourceFactoryDescriptors(AnnotationTree,
* MethodTree)} in that it drops any parenthesized method parameter type enumerations. That is,
* method descriptors such as {@code factoryMethod()} and {@code factoryMethod(java.lang.String)}
* are both simplified to just {@code factoryMethod}. This also means that the returned method
* names may not unambiguously reference a single value factory method; in such a case JUnit will
* throw an error at runtime.
*
* @param methodSourceAnnotation The annotation from which to extract value factory method names.
* @param method The method on which the annotation is located.
* @return One or more value factory descriptors, in the order defined.
* @see #getMethodSourceFactoryDescriptors(AnnotationTree, MethodTree)
*/
// XXX: Drop this method in favour of `#getMethodSourceFactoryDescriptors`. That will require
// callers to either explicitly drop information, or perform a more advanced analysis.
public static ImmutableList<String> getMethodSourceFactoryNames(
AnnotationTree methodSourceAnnotation, MethodTree method) {
return getMethodSourceFactoryDescriptors(methodSourceAnnotation, method).stream()
.map(
descriptor -> {
int index = descriptor.indexOf('(');
return index < 0 ? descriptor : descriptor.substring(0, index);
})
.collect(toImmutableList());
}
/**
* Returns the descriptors of the JUnit value factory methods specified by the given {@link
* org.junit.jupiter.params.provider.MethodSource} annotation.
*
* @param methodSourceAnnotation The annotation from which to extract value factory method
* descriptors.
* @param method The method on which the annotation is located.
* @return One or more value factory descriptors, in the order defined.
* @see #getMethodSourceFactoryNames(AnnotationTree, MethodTree)
*/
// XXX: Rather than strings, have this method return instances of a value type capable of
// resolving the value factory method pointed to.
public static ImmutableList<String> getMethodSourceFactoryDescriptors(
AnnotationTree methodSourceAnnotation, MethodTree method) {
String methodName = method.getName().toString();
ExpressionTree value = AnnotationMatcherUtils.getArgument(methodSourceAnnotation, "value");
if (!(value instanceof NewArrayTree)) {
return ImmutableList.of(toMethodSourceFactoryDescriptor(value, methodName));
}
return ((NewArrayTree) value)
.getInitializers().stream()
.map(name -> toMethodSourceFactoryDescriptor(name, methodName))
.collect(toImmutableList());
}
private static String toMethodSourceFactoryDescriptor(
@Nullable ExpressionTree tree, String annotatedMethodName) {
return requireNonNullElse(
Strings.emptyToNull(ASTHelpers.constValue(tree, String.class)), annotatedMethodName);
}
}

View File

@@ -0,0 +1,39 @@
package tech.picnic.errorprone.bugpatterns.util;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.tools.javac.code.Symbol;
/**
* A collection of general-purpose {@link Matcher}s.
*
* <p>These methods are additions to the ones found in {@link Matchers}.
*/
public final class MoreMatchers {
private MoreMatchers() {}
/**
* Returns a {@link Matcher} that determines whether a given {@link AnnotationTree} has a
* meta-annotation of the specified type.
*
* @param <T> The type of tree to match against.
* @param annotationType The binary type name of the annotation (e.g.
* "org.jspecify.annotations.Nullable", or "some.package.OuterClassName$InnerClassName")
* @return A {@link Matcher} that matches trees with the specified meta-annotation.
*/
public static <T extends AnnotationTree> Matcher<T> hasMetaAnnotation(String annotationType) {
TypePredicate typePredicate = hasAnnotation(annotationType);
return (tree, state) -> {
Symbol sym = ASTHelpers.getSymbol(tree);
return sym != null && typePredicate.apply(sym.type, state);
};
}
// XXX: Consider moving to a `MoreTypePredicates` utility class.
private static TypePredicate hasAnnotation(String annotationClassName) {
return (type, state) -> ASTHelpers.hasAnnotation(type.tsym, annotationClassName, state);
}
}

View File

@@ -0,0 +1,132 @@
package tech.picnic.errorprone.bugpatterns.util;
import static java.util.stream.Collectors.toCollection;
import com.google.errorprone.VisitorState;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
/**
* A set of helper methods which together define a DSL for defining {@link Type types}.
*
* <p>These methods are meant to be statically imported. Example usage:
*
* <pre>{@code
* Supplier<Type> type =
* VisitorState.memoize(
* generic(
* type("reactor.core.publisher.Flux"),
* subOf(generic(type("org.reactivestreams.Publisher"), unbound()))));
* }</pre>
*
* This statement produces a memoized supplier of the type {@code Flux<? extends Publisher<?>>}.
*/
public final class MoreTypes {
private MoreTypes() {}
/**
* Creates a supplier of the type with the given fully qualified name.
*
* <p>This method should only be used when building more complex types in combination with other
* {@link MoreTypes} methods. In other cases prefer directly calling {@link
* Suppliers#typeFromString(String)}.
*
* @param typeName The type of interest.
* @return A supplier which returns the described type if available in the given state, and {@code
* null} otherwise.
*/
public static Supplier<Type> type(String typeName) {
return Suppliers.typeFromString(typeName);
}
/**
* Creates a supplier of the described generic type.
*
* @param type The base type of interest.
* @param typeArgs The desired type arguments.
* @return A supplier which returns the described type if available in the given state, and {@code
* null} otherwise.
*/
// XXX: The given `type` should be a generic type, so perhaps `withParams` would be a better
// method name. But the DSL wouldn't look as nice that way.
@SafeVarargs
@SuppressWarnings("varargs")
public static Supplier<Type> generic(Supplier<Type> type, Supplier<Type>... typeArgs) {
return propagateNull(
type,
(state, baseType) -> {
List<Type> params =
Arrays.stream(typeArgs).map(s -> s.get(state)).collect(toCollection(ArrayList::new));
if (params.stream().anyMatch(Objects::isNull)) {
return null;
}
return state.getType(baseType, /* isArray= */ false, params);
});
}
/**
* Creates a raw (erased, non-generic) variant of the given type.
*
* @param type The base type of interest.
* @return A supplier which returns the described type if available in the given state, and {@code
* null} otherwise.
*/
public static Supplier<Type> raw(Supplier<Type> type) {
return propagateNull(type, (state, baseType) -> baseType.tsym.erasure(state.getTypes()));
}
/**
* Creates a {@code ? super T} wildcard type, with {@code T} bound to the given type.
*
* @param type The base type of interest.
* @return A supplier which returns the described type if available in the given state, and {@code
* null} otherwise.
*/
public static Supplier<Type> superOf(Supplier<Type> type) {
return propagateNull(
type,
(state, baseType) ->
new Type.WildcardType(baseType, BoundKind.SUPER, state.getSymtab().boundClass));
}
/**
* Creates a {@code ? extends T} wildcard type, with {@code T} bound to the given type.
*
* @param type The base type of interest.
* @return A supplier which returns the described type if available in the given state, and {@code
* null} otherwise.
*/
public static Supplier<Type> subOf(Supplier<Type> type) {
return propagateNull(
type,
(state, baseType) ->
new Type.WildcardType(
type.get(state), BoundKind.EXTENDS, state.getSymtab().boundClass));
}
/**
* Creates an unbound wildcard type ({@code ?}).
*
* @return A supplier which returns the described type.
*/
public static Supplier<Type> unbound() {
return state ->
new Type.WildcardType(
state.getSymtab().objectType, BoundKind.UNBOUND, state.getSymtab().boundClass);
}
private static Supplier<Type> propagateNull(
Supplier<Type> type, BiFunction<VisitorState, Type, Type> transformer) {
return state ->
Optional.ofNullable(type.get(state)).map(t -> transformer.apply(state, t)).orElse(null);
}
}

View File

@@ -0,0 +1,62 @@
package tech.picnic.errorprone.bugpatterns.util;
import static com.sun.tools.javac.util.Position.NOPOS;
import com.google.common.base.CharMatcher;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.SuggestedFix;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
/**
* A collection of Error Prone utility methods for dealing with the source code representation of
* AST nodes.
*/
public final class SourceCode {
/** The complement of {@link CharMatcher#whitespace()}. */
private static final CharMatcher NON_WHITESPACE_MATCHER = CharMatcher.whitespace().negate();
private SourceCode() {}
/**
* Returns a string representation of the given {@link Tree}, preferring the original source code
* (if available) over its prettified representation.
*
* @param tree The AST node of interest.
* @param state A {@link VisitorState} describing the context in which the given {@link Tree} is
* found.
* @return A non-{@code null} string.
*/
public static String treeToString(Tree tree, VisitorState state) {
String src = state.getSourceForNode(tree);
return src != null ? src : tree.toString();
}
/**
* Creates a {@link SuggestedFix} for the deletion of the given {@link Tree}, including any
* whitespace that follows it.
*
* <p>Removing trailing whitespace may prevent the introduction of an empty line at the start of a
* code block; such empty lines are not removed when formatting the code using Google Java Format.
*
* @param tree The AST node of interest.
* @param state A {@link VisitorState} describing the context in which the given {@link Tree} is
* found.
* @return A non-{@code null} {@link SuggestedFix} similar to one produced by {@link
* SuggestedFix#delete(Tree)}.
*/
public static SuggestedFix deleteWithTrailingWhitespace(Tree tree, VisitorState state) {
CharSequence sourceCode = state.getSourceCode();
int endPos = state.getEndPosition(tree);
if (sourceCode == null || endPos == NOPOS) {
/* We can't identify the trailing whitespace; delete just the tree. */
return SuggestedFix.delete(tree);
}
int whitespaceEndPos = NON_WHITESPACE_MATCHER.indexIn(sourceCode, endPos);
return SuggestedFix.replace(
((DiagnosticPosition) tree).getStartPosition(),
whitespaceEndPos == -1 ? sourceCode.length() : whitespaceEndPos,
"");
}
}

View File

@@ -0,0 +1,105 @@
package tech.picnic.errorprone.bugpatterns.util;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.suppliers.Supplier;
import com.sun.tools.javac.code.ClassFinder;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.util.Name;
/**
* Utility class that helps decide whether it is appropriate to introduce references to (well-known)
* third-party libraries.
*
* <p>This class should be used by {@link BugChecker}s that may otherwise suggest the introduction
* of code that depends on possibly-not-present third-party libraries.
*/
// XXX: Consider giving users more fine-grained control. This would be beneficial in cases where a
// dependency is on the classpath, but new usages are undesirable.
public enum ThirdPartyLibrary {
/**
* AssertJ.
*
* @see <a href="https://assertj.github.io/doc">AssertJ documentation</a>
*/
ASSERTJ("org.assertj.core.api.Assertions"),
/**
* Google's Guava.
*
* @see <a href="https://github.com/google/guava">Guava on GitHub</a>
*/
GUAVA("com.google.common.collect.ImmutableList"),
/**
* New Relic's Java agent API.
*
* @see <a href="https://github.com/newrelic/newrelic-java-agent/tree/main/newrelic-api">New Relic
* Java agent API on GitHub</a>
*/
NEW_RELIC_AGENT_API("com.newrelic.api.agent.Agent"),
/**
* VMWare's Project Reactor.
*
* @see <a href="https://projectreactor.io">Home page</a>
*/
REACTOR("reactor.core.publisher.Flux");
private static final String IGNORE_CLASSPATH_COMPAT_FLAG =
"ErrorProneSupport:IgnoreClasspathCompat";
@SuppressWarnings("ImmutableEnumChecker" /* Supplier is deterministic. */)
private final Supplier<Boolean> canUse;
/**
* Instantiates a {@link ThirdPartyLibrary} enum value.
*
* @param witnessFqcn The fully-qualified class name of a type that is expected to be on the
* classpath iff the associated third-party library is on the classpath.
*/
ThirdPartyLibrary(String witnessFqcn) {
this.canUse = VisitorState.memoize(state -> canIntroduceUsage(witnessFqcn, state));
}
/**
* Tells whether it is okay to introduce a dependency on this well-known third party library in
* the given context.
*
* @param state The context under consideration.
* @return {@code true} iff it is okay to assume or create a dependency on this library.
*/
public boolean isIntroductionAllowed(VisitorState state) {
return canUse.get(state);
}
private static boolean canIntroduceUsage(String className, VisitorState state) {
return shouldIgnoreClasspath(state) || isKnownClass(className, state);
}
/**
* Attempts to determine whether a class with the given FQCN is on the classpath.
*
* <p>The {@link VisitorState}'s symbol table is consulted first. If the type has not yet been
* loaded, then an attempt is made to do so.
*/
private static boolean isKnownClass(String className, VisitorState state) {
return state.getTypeFromString(className) != null || canLoadClass(className, state);
}
private static boolean canLoadClass(String className, VisitorState state) {
ClassFinder classFinder = ClassFinder.instance(state.context);
Name binaryName = state.binaryNameFromClassname(className);
try {
classFinder.loadClass(state.getSymtab().unnamedModule, binaryName);
return true;
} catch (CompletionFailure e) {
return false;
}
}
private static boolean shouldIgnoreClasspath(VisitorState state) {
return state
.errorProneOptions()
.getFlags()
.getBoolean(IGNORE_CLASSPATH_COMPAT_FLAG)
.orElse(Boolean.FALSE);
}
}

View File

@@ -0,0 +1,4 @@
/** Auxiliary utilities for use by Error Prone checks. */
@com.google.errorprone.annotations.CheckReturnValue
@org.jspecify.annotations.NullMarked
package tech.picnic.errorprone.bugpatterns.util;

View File

@@ -0,0 +1,55 @@
package tech.picnic.errorprone.refasterrules;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.data.Percentage.withPercentage;
import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.math.BigDecimal;
import org.assertj.core.api.AbstractBigDecimalAssert;
import org.assertj.core.api.BigDecimalAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
/**
* Refaster rules related to AssertJ assertions over {@link BigDecimal}s.
*
* <p>Note that, contrary to collections of Refaster rules for other {@link
* org.assertj.core.api.NumberAssert} subtypes, these rules do not rewrite to/from {@link
* BigDecimalAssert#isEqualTo(Object)} and {@link BigDecimalAssert#isNotEqualTo(Object)}. This is
* because {@link BigDecimal#equals(Object)} considers not only the numeric value of compared
* instances, but also their scale. As a result various seemingly straightforward transformations
* would actually subtly change the assertion's semantics.
*/
@OnlineDocumentation
final class AssertJBigDecimalRules {
private AssertJBigDecimalRules() {}
static final class AbstractBigDecimalAssertIsEqualByComparingTo {
@BeforeTemplate
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
return Refaster.anyOf(
bigDecimalAssert.isCloseTo(n, offset(BigDecimal.ZERO)),
bigDecimalAssert.isCloseTo(n, withPercentage(0)));
}
@AfterTemplate
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
return bigDecimalAssert.isEqualByComparingTo(n);
}
}
static final class AbstractBigDecimalAssertIsNotEqualByComparingTo {
@BeforeTemplate
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
return Refaster.anyOf(
bigDecimalAssert.isNotCloseTo(n, offset(BigDecimal.ZERO)),
bigDecimalAssert.isNotCloseTo(n, withPercentage(0)));
}
@AfterTemplate
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
return bigDecimalAssert.isNotEqualByComparingTo(n);
}
}
}

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.data.Percentage.withPercentage;
@@ -8,11 +8,13 @@ import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.math.BigInteger;
import org.assertj.core.api.AbstractBigIntegerAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
// XXX: If we add a rule which drops unnecessary `L` suffixes from literal longs, then the `0L`/`1L`
// XXX: If we add a rule that drops unnecessary `L` suffixes from literal longs, then the `0L`/`1L`
// cases below can go.
final class AssertJBigIntegerTemplates {
private AssertJBigIntegerTemplates() {}
@OnlineDocumentation
final class AssertJBigIntegerRules {
private AssertJBigIntegerRules() {}
static final class AbstractBigIntegerAssertIsEqualTo {
@BeforeTemplate

View File

@@ -1,16 +1,18 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.errorprone.refaster.ImportPolicy;
import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import org.assertj.core.api.AbstractBooleanAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJBooleanTemplates {
private AssertJBooleanTemplates() {}
@OnlineDocumentation
final class AssertJBooleanRules {
private AssertJBooleanRules() {}
static final class AbstractBooleanAssertIsEqualTo {
@BeforeTemplate
@@ -59,7 +61,7 @@ final class AssertJBooleanTemplates {
}
@AfterTemplate
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractBooleanAssert<?> after(boolean b) {
return assertThat(b).isTrue();
}
@@ -88,7 +90,7 @@ final class AssertJBooleanTemplates {
}
@AfterTemplate
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractBooleanAssert<?> after(boolean b) {
return assertThat(b).isFalse();
}

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.data.Percentage.withPercentage;
@@ -7,19 +7,17 @@ import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import org.assertj.core.api.AbstractByteAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJByteTemplates {
private AssertJByteTemplates() {}
@OnlineDocumentation
final class AssertJByteRules {
private AssertJByteRules() {}
static final class AbstractByteAssertIsEqualTo {
@BeforeTemplate
AbstractByteAssert<?> before(AbstractByteAssert<?> byteAssert, byte n) {
return Refaster.anyOf(
byteAssert.isCloseTo(n, offset((byte) 0)),
byteAssert.isCloseTo(Byte.valueOf(n), offset((byte) 0)),
byteAssert.isCloseTo(n, withPercentage(0)),
byteAssert.isCloseTo(Byte.valueOf(n), withPercentage(0)),
byteAssert.isEqualTo(Byte.valueOf(n)));
byteAssert.isCloseTo(n, offset((byte) 0)), byteAssert.isCloseTo(n, withPercentage(0)));
}
@AfterTemplate
@@ -33,10 +31,7 @@ final class AssertJByteTemplates {
AbstractByteAssert<?> before(AbstractByteAssert<?> byteAssert, byte n) {
return Refaster.anyOf(
byteAssert.isNotCloseTo(n, offset((byte) 0)),
byteAssert.isNotCloseTo(Byte.valueOf(n), offset((byte) 0)),
byteAssert.isNotCloseTo(n, withPercentage(0)),
byteAssert.isNotCloseTo(Byte.valueOf(n), withPercentage(0)),
byteAssert.isNotEqualTo(Byte.valueOf(n)));
byteAssert.isNotCloseTo(n, withPercentage(0)));
}
@AfterTemplate

View File

@@ -1,16 +1,18 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.errorprone.refaster.ImportPolicy;
import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import org.assertj.core.api.AbstractAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJCharSequenceTemplates {
private AssertJCharSequenceTemplates() {}
@OnlineDocumentation
final class AssertJCharSequenceRules {
private AssertJCharSequenceRules() {}
static final class AssertThatCharSequenceIsEmpty {
@BeforeTemplate
@@ -21,7 +23,7 @@ final class AssertJCharSequenceTemplates {
}
@AfterTemplate
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
void after(CharSequence charSequence) {
assertThat(charSequence).isEmpty();
}
@@ -36,7 +38,7 @@ final class AssertJCharSequenceTemplates {
}
@AfterTemplate
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractAssert<?, ?> after(CharSequence charSequence) {
return assertThat(charSequence).isNotEmpty();
}
@@ -49,7 +51,7 @@ final class AssertJCharSequenceTemplates {
}
@AfterTemplate
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractAssert<?, ?> after(CharSequence charSequence, int length) {
return assertThat(charSequence).hasSize(length);
}

View File

@@ -0,0 +1,94 @@
package tech.picnic.errorprone.refasterrules;
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import org.assertj.core.api.AbstractComparableAssert;
import org.assertj.core.api.AbstractIntegerAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
@OnlineDocumentation
final class AssertJComparableRules {
private AssertJComparableRules() {}
static final class AssertThatIsEqualByComparingTo<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isEqualTo(0);
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isEqualByComparingTo(expected);
}
}
static final class AssertThatIsNotEqualByComparingTo<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isNotEqualTo(0);
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isNotEqualByComparingTo(expected);
}
}
static final class AssertThatIsLessThan<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isNegative();
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isLessThan(expected);
}
}
static final class AssertThatIsLessThanOrEqualTo<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isNotPositive();
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isLessThanOrEqualTo(expected);
}
}
static final class AssertThatIsGreaterThan<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isPositive();
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isGreaterThan(expected);
}
}
static final class AssertThatIsGreaterThanOrEqualTo<T extends Comparable<? super T>> {
@BeforeTemplate
AbstractIntegerAssert<?> before(T actual, T expected) {
return assertThat(actual.compareTo(expected)).isNotNegative();
}
@AfterTemplate
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
AbstractComparableAssert<?, ?> after(T actual, T expected) {
return assertThat(actual).isGreaterThanOrEqualTo(expected);
}
}
}

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.data.Percentage.withPercentage;
@@ -8,9 +8,11 @@ import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import org.assertj.core.api.AbstractDoubleAssert;
import org.assertj.core.data.Offset;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJDoubleTemplates {
private AssertJDoubleTemplates() {}
@OnlineDocumentation
final class AssertJDoubleRules {
private AssertJDoubleRules() {}
static final class AbstractDoubleAssertIsCloseToWithOffset {
@BeforeTemplate
@@ -36,11 +38,7 @@ final class AssertJDoubleTemplates {
@BeforeTemplate
AbstractDoubleAssert<?> before(AbstractDoubleAssert<?> doubleAssert, double n) {
return Refaster.anyOf(
doubleAssert.isCloseTo(n, offset(0.0)),
doubleAssert.isCloseTo(Double.valueOf(n), offset(0.0)),
doubleAssert.isCloseTo(n, withPercentage(0.0)),
doubleAssert.isCloseTo(Double.valueOf(n), withPercentage(0.0)),
doubleAssert.isEqualTo(Double.valueOf(n)));
doubleAssert.isCloseTo(n, offset(0.0)), doubleAssert.isCloseTo(n, withPercentage(0.0)));
}
@AfterTemplate
@@ -54,10 +52,7 @@ final class AssertJDoubleTemplates {
AbstractDoubleAssert<?> before(AbstractDoubleAssert<?> doubleAssert, double n) {
return Refaster.anyOf(
doubleAssert.isNotCloseTo(n, offset(0.0)),
doubleAssert.isNotCloseTo(Double.valueOf(n), offset(0.0)),
doubleAssert.isNotCloseTo(n, withPercentage(0.0)),
doubleAssert.isNotCloseTo(Double.valueOf(n), withPercentage(0.0)),
doubleAssert.isNotEqualTo(Double.valueOf(n)));
doubleAssert.isNotCloseTo(n, withPercentage(0.0)));
}
@AfterTemplate

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import com.google.common.collect.Iterables;
import com.google.errorprone.refaster.Refaster;
@@ -6,9 +6,11 @@ import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.util.Collection;
import org.assertj.core.api.EnumerableAssert;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJEnumerableTemplates {
private AssertJEnumerableTemplates() {}
@OnlineDocumentation
final class AssertJEnumerableRules {
private AssertJEnumerableRules() {}
static final class EnumerableAssertIsEmpty<E> {
@BeforeTemplate

View File

@@ -1,4 +1,4 @@
package tech.picnic.errorprone.refastertemplates;
package tech.picnic.errorprone.refasterrules;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.data.Percentage.withPercentage;
@@ -8,9 +8,11 @@ import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import org.assertj.core.api.AbstractFloatAssert;
import org.assertj.core.data.Offset;
import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation;
final class AssertJFloatTemplates {
private AssertJFloatTemplates() {}
@OnlineDocumentation
final class AssertJFloatRules {
private AssertJFloatRules() {}
static final class AbstractFloatAssertIsCloseToWithOffset {
@BeforeTemplate
@@ -36,11 +38,7 @@ final class AssertJFloatTemplates {
@BeforeTemplate
AbstractFloatAssert<?> before(AbstractFloatAssert<?> floatAssert, float n) {
return Refaster.anyOf(
floatAssert.isCloseTo(n, offset(0F)),
floatAssert.isCloseTo(Float.valueOf(n), offset(0F)),
floatAssert.isCloseTo(n, withPercentage(0)),
floatAssert.isCloseTo(Float.valueOf(n), withPercentage(0)),
floatAssert.isEqualTo(Float.valueOf(n)));
floatAssert.isCloseTo(n, offset(0F)), floatAssert.isCloseTo(n, withPercentage(0)));
}
@AfterTemplate
@@ -53,11 +51,7 @@ final class AssertJFloatTemplates {
@BeforeTemplate
AbstractFloatAssert<?> before(AbstractFloatAssert<?> floatAssert, float n) {
return Refaster.anyOf(
floatAssert.isNotCloseTo(n, offset(0F)),
floatAssert.isNotCloseTo(Float.valueOf(n), offset(0F)),
floatAssert.isNotCloseTo(n, withPercentage(0)),
floatAssert.isNotCloseTo(Float.valueOf(n), withPercentage(0)),
floatAssert.isNotEqualTo(Float.valueOf(n)));
floatAssert.isNotCloseTo(n, offset(0F)), floatAssert.isNotCloseTo(n, withPercentage(0)));
}
@AfterTemplate

Some files were not shown because too many files have changed in this diff Show More