An extensible multilanguage static code analyzer.
The PMD team is pleased to announce PMD 6.41.0.
This is a minor release.
PMD now has its own official GitHub Action: GitHub Action for PMD. It can execute PMD with your own ruleset against your project. It creates a SARIF report which is uploaded as a build artifact. Furthermore the build can be failed based on the number of violations.
Feedback and pull requests are welcome at https://github.com/pmd/pmd-github-action.
This minor release will be the last one in 2021. The next release is scheduled to be end of January 2022.
valueOf(char [], int, int)
is usedThe command line options for PMD and CPD now use GNU-syle long options format. E.g. instead of -rulesets
the
preferred usage is now --rulesets
. Alternatively one can still use the short option -R
.
Some options also have been renamed to a more consistent casing pattern at the same time
(--fail-on-violation
instead of -failOnViolation
).
The old single-dash options are still supported but are deprecated and will be removed with PMD 7.
This change makes the command line interface more consistent within PMD and also less surprising
compared to other cli tools.
The changes in detail for PMD:
old option | new option |
---|---|
-rulesets |
--rulesets (or -R ) |
-uri |
--uri |
-dir |
--dir (or -d ) |
-filelist |
--file-list |
-ignorelist |
--ignore-list |
-format |
--format (or -f ) |
-debug |
--debug |
-verbose |
--verbose |
-help |
--help |
-encoding |
--encoding |
-threads |
--threads |
-benchmark |
--benchmark |
-stress |
--stress |
-shortnames |
--short-names |
-showsuppressed |
--show-suppressed |
-suppressmarker |
--suppress-marker |
-minimumpriority |
--minimum-priority |
-property |
--property |
-reportfile |
--report-file |
-force-language |
--force-language |
-auxclasspath |
--aux-classpath |
-failOnViolation |
--fail-on-violation |
--failOnViolation |
--fail-on-violation |
-norulesetcompatibility |
--no-ruleset-compatibility |
-cache |
--cache |
-no-cache |
--no-cache |
The changes in detail for CPD:
old option | new option |
---|---|
--failOnViolation |
--fail-on-violation |
-failOnViolation |
--fail-on-violation |
--filelist |
--file-list |
The PMD team is pleased to announce PMD 6.40.0.
This is a minor release.
EagerlyLoadedDescribeSObjectResult
finds
DescribeSObjectResult
s which could have been loaded eagerly via SObjectType.getDescribe()
. <rule ref="category/apex/performance.xml/EagerlyLoadedDescribeSObjectResult" />
The Apex rule ApexUnitTestClassShouldHaveAsserts
has a new property
additionalAssertMethodPattern
. When specified the pattern is evaluated against each invoked
method name to determine whether it represents a test assertion in addition to the standard names.
The Apex rule ApexDoc
has a new property reportMissingDescription
.
If set to false
(default is true
if unspecified) doesn't report an issue if the @description
tag is missing. This is consistent with the ApexDoc dialect supported by derivatives such as
SfApexDoc and also with analogous documentation tools for
other languages, e.g., JavaDoc, ESDoc/JSDoc, etc.
The Apex rule ApexCRUDViolation
has a couple of new properties:
These allow specification of regular-expression-based patterns for additional methods that should
be considered valid for pre-CRUD authorization beyond those offered by the system Apex checks and
ESAPI, e.g., sirono-common
's AuthorizationUtil
class.
Two new properties have been added per-CRUD operation, one to specify the naming pattern for a method
that authorizes that operation and another to specify the argument passed to that method that contains
the SObjectType
instance of the type being authorized. Here is an example of these new properties:
<rule ref="category/apex/security.xml/ApexCRUDViolation" message="...">
<priority>3</priority>
<properties>
<property name="createAuthMethodPattern" value="AuthorizationUtil\.(is|assert)(Createable|Upsertable)"/>
<!--
There's one of these properties for each operation, and the default value is 0 so this is technically
superfluous, but it's included it here for example purposes.
-->
<property name="createAuthMethodTypeParamIndex" value="0"/>
<property name="readAuthMethodPattern" value="AuthorizationUtil\.(is|assert)Accessible"/>
<property name="updateAuthMethodPattern" value="AuthorizationUtil\.(is|assert)(Updateable|Upsertable)"/>
<property name="deleteAuthMethodPattern" value="AuthorizationUtil\.(is|assert)Deletable"/>
<property name="undeleteAuthMethodPattern" value="AuthorizationUtil\.(is|assert)Undeletable"/>
<property name="mergeAuthMethodPattern" value="AuthorizationUtil\.(is|assert)Mergeable"/>
</properties>
</rule>
The Apex rule EmptyStatementBlock
has two new properties:
Setting reportEmptyPrivateNoArgConstructor
to false
ignores empty private no-arg constructors
that are commonly used in singleton pattern implementations and utility classes in support of
prescribed best practices.
Setting reportEmptyVirtualMethod
to false
ignores empty virtual methods that are commonly used in
abstract base classes as default no-op implementations when derived classes typically only override a
subset of virtual methods.
By default, both properties are true
to not change the default behaviour of this rule.
The Apex rule EmptyCatchBlock
has two new properties modeled after the analgous Java rule:
The allowCommentedBlocks
property, when set to true
(defaults to false
), ignores empty blocks containing comments, e.g.:
try {
doSomethingThatThrowsAnExpectedException();
System.assert(false, 'Expected to catch an exception.');
} catch (Exception e) {
// Expected
}
The allowExceptionNameRegex
property is a regular expression for exception variable names for which empty catch blocks should be ignored by this rule. For example, using the default property value of ^(ignored|expected)$
, the following empty catch blocks will not be reported:
try {
doSomethingThatThrowsAnExpectedException();
System.assert(false, 'Expected to catch an exception.');
} catch (IllegalStateException ignored) {
} catch (NumberFormatException expected) {
}
The Apex rule OneDeclarationPerLine
has a new property reportInForLoopInitializer
:
If set to false
(default is true
if unspecified) doesn't report an issue for multiple declarations in
a for
loop's initializer section. This is support the common idiom of one declaration for the loop variable
and another for the loop bounds condition, e.g.,
for (Integer i = 0, numIterations = computeNumIterations(); i < numIterations; i++) {
}
The Java rule ClassNamingConventions
uses a different default value of the
property utilityClassPattern
: This rule was detecting utility classes by default since PMD 6.3.0
and enforcing the naming convention that utility classes has to be suffixed with Util or Helper or Constants.
However this turned out to be not so useful as a default configuration, as there is no standard
naming convention for utility classes.
With PMD 6.40.0, the default value of this property has been changed to [A-Z][a-zA-Z0-9]*
(Pascal case), effectively disabling the special handling of utility classes. This is the same default
pattern used for concrete classes.
This means, that the feature to enforce a naming convention for utility classes is now a opt-in feature and can be enabled on demand.
To use the old behaviour, the property needs to be configured as follows:
<rule ref="category/java/codestyle.xml/ClassNamingConventions">
<properties>
<property name="utilityClassPattern" value="[A-Z][a-zA-Z0-9]+(Utils?|Helper|Constants)" />
</properties>
</rule>
ASTCommentContainer
has been added to the Apex AST.
It provides a way to check whether a node contains at least one comment. Currently this is only implemented for
ASTCatchBlockStatement
and used by the rule
EmptyCatchBlock
.
This information is also available via XPath attribute @ContainsComment
.The PMD team is pleased to announce PMD 6.39.0.
This is a minor release.
PMD follows the All Contributors specification. Contributions of any kind welcome!
See credits for our complete contributors list.
No changes.
The PMD team is pleased to announce PMD 6.38.0.
This is a minor release.
The PMD team is pleased to announce PMD 6.37.0.
This is a minor release.
This release of PMD brings support for Java 17. PMD supports JEP 409: Sealed Classes which has been promoted to be a standard language feature of Java 17.
PMD also supports JEP 406: Pattern Matching for switch (Preview) as a preview
language feature. In order to analyze a project with PMD that uses these language features, you'll need to enable
it via the environment variable PMD_JAVA_OPTS
and select the new language version 17-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 17-preview ...
Note: Support for Java 15 preview language features have been removed. The version "15-preview" is no longer available.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
This release ships with 3 new Java rules.
PrimitiveWrapperInstantiation
reports usages of primitive wrapper
constructors. They are deprecated since Java 9 and should not be used. <rule ref="category/java/bestpractices.xml/PrimitiveWrapperInstantiation" />
The rule is part of the quickstart.xml ruleset.
SimplifiableTestAssertion
suggests rewriting
some test assertions to be more readable. <rule ref="category/java/bestpractices.xml/SimplifiableTestAssertion" />
The rule is part of the quickstart.xml ruleset.
ReturnEmptyCollectionRatherThanNull
suggests returning empty collections / arrays
instead of null. <rule ref="category/java/errorprone.xml/ReturnEmptyCollectionRatherThanNull" />
The rule is part of the quickstart.xml ruleset.
MissingBreakInSwitch
has been renamed to
ImplicitSwitchFallThrough
(category error prone) to better reflect the rule's
purpose: The rule finds implicit fall-through cases in switch statements, which are most
likely unexpected. The old rule name described only one way how to avoid a fall-through,
namely using break
but continue
, throw
and return
avoid a fall-through
as well. This enables us to improve this rule in the future.The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule SimplifiableTestAssertion
merges
their functionality:
The Java rule ReturnEmptyArrayRatherThanNull
is deprecated and removed from
the quickstart ruleset, as the new rule ReturnEmptyCollectionRatherThanNull
supersedes it.
The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule PrimitiveWrapperInstantiation
merges
their functionality:
The Java rule UnnecessaryWrapperObjectCreation
is deprecated
with no planned replacement before PMD 7. In it's current state, the rule is not useful
as it finds only contrived cases of creating a primitive wrapper and unboxing it explicitly
in the same expression. In PMD 7 this and more cases will be covered by a
new rule UnnecessaryBoxing
.
InefficientStringBuffering
with RecordsPMD has a new CLI option -force-language
. With that a language can be forced to be used for all input files,
irrespective of filenames. When using this option, the automatic language selection by extension is disabled
and all files are tried to be parsed with the given language. Parsing errors are ignored and unparsable files
are skipped.
This option allows to use the xml language for files, that don't use xml as extension. See also the examples on PMD CLI reference.
Those APIs are not intended to be used by clients, and will be hidden or removed with PMD 7.0.0.
You can identify them with the @InternalApi
annotation. You'll also get a deprecation warning.
net.sourceforge.pmd.cpd.TokenEntry.State
is considered to be internal API.
It will probably be moved away with PMD 7.The PMD team is pleased to announce PMD 6.36.0.
This is a minor release.
Incremental Analysis has long helped our users obtain faster analysis results, however, its implementation tended to be too cautious in detecting changes to the runtime and type resolution classpaths, producing more cache invalidations than necessary. We have now improved the heuristics to remove several bogus invalidations, and slightly sped up the cache usage along the way.
PMD will now ignore:
AvoidDebugStatements
finds usages of System.debug
calls.
Debug statements contribute to longer transactions and consume Apex CPU time even when debug logs are not
being captured.
You can try out this rule like so: <rule ref="category/apex/performance.xml/AvoidDebugStatements" />
InaccessibleAuraEnabledGetter
checks that an AuraEnabled
getter is public or global. This is necessary if it is referenced in Lightning components.
You can try out this rule like so: <rule ref="category/apex/errorprone.xml/InaccessibleAuraEnabledGetter" />
BadComparison
has been renamed to
ComparisonWithNaN
to better reflect what the rule actually detects.
It now considers usages of Double.NaN
or Float.NaN
in more cases and fixes false negatives.@exception
tagNo changes.
@exception
tag - Piotrek Żygieło
The PMD team is pleased to announce PMD 6.35.0.
This is a minor release.
The latest version of Rhino, the implementation of JavaScript we use for parsing JavaScript code, requires at least Java 8. Therefore we decided to upgrade the pmd-javascript module to Java 8 as well. This means that from now on, a Java 8 or later runtime is required in order to analyze JavaScript code. Note that PMD core still only requires Java 7.
This release ships with 3 new Java rules.
JUnit5TestShouldBePackagePrivate
enforces the convention that JUnit 5 tests should have minimal visibility.
You can try out this rule like so: <rule ref="category/java/bestpractices.xml/JUnit5TestShouldBePackagePrivate" />
CognitiveComplexity
uses the cognitive complexity
metric to find overly complex code. This metric improves on the similar cyclomatic complexity
in several ways, for instance, it incentivizes using clearly readable shorthands and idioms.
See the rule documentation for more details. You can try out this rule like so: <rule ref="category/java/design.xml/CognitiveComplexity" />
MutableStaticState
finds non-private static fields
that are not final. These fields break encapsulation since these fields can be modified from anywhere
within the program. You can try out this rule like so: <rule ref="category/java/design.xml/MutableStaticState" />
CompareObjectsWithEquals
has now a new property
typesThatCompareByReference
. With that property, you can configure types, that should be whitelisted
for comparison by reference. By default, java.lang.Enum
and java.lang.Class
are allowed, but
you could add custom types here.
Additionally comparisons against constants are allowed now. This makes the rule less noisy when two constants
are compared. Constants are identified by looking for an all-caps identifier.The java rule DefaultPackage
has been deprecated in favor of
CommentDefaultAccessModifier
.
The rule "DefaultPackage" assumes that any usage of package-access is accidental, and by doing so, prohibits using a really fundamental and useful feature of the language.
To satisfy the rule, you have to make the member public even if it doesn't need to, or make it protected,
which muddies your intent even more if you don't intend the class to be extended, and may be at odds with
other rules like AvoidProtectedFieldInFinalClass
.
The rule CommentDefaultAccessModifier
should be used instead.
It flags the same thing, but has an escape hatch.
The Java rule CloneThrowsCloneNotSupportedException
has been deprecated without
replacement.
The rule has no real value as CloneNotSupportedException
is a
checked exception and therefore you need to deal with it while implementing the clone()
method. You either
need to declare the exception or catch it. If you catch it, then subclasses can't throw it themselves explicitly.
However, Object.clone()
will still throw this exception if the Cloneable
interface is not implemented.
Note, this rule has also been removed from the Quickstart Ruleset (rulesets/java/quickstart.xml
).
PMD#doPMD
is deprecated.
Use PMD#runPMD
instead.PMD#run
is deprecated.
Use PMD#runPMD
instead.ThreadSafeReportListener
and the methods to use them in Report
(addListener
,
getListeners
, addListeners
)
are deprecated. This functionality will be replaced by another TBD mechanism in PMD 7.The PMD team is pleased to announce PMD 6.34.0.
This is a minor release.
The new Java rule UseStandardCharsets
finds usages of Charset.forName
,
where StandardCharsets
can be used instead.
This rule is also part of the Quickstart Ruleset (rulesets/java/quickstart.xml
) for Java.
The new Java rule UnnecessaryImport
replaces the rules
UnusedImports
, DuplicateImports
,
ImportFromSamePackage
, and DontImportJavaLang
.
This rule is also part of the Quickstart Ruleset (rulesets/java/quickstart.xml
) for Java.
ApexCRUDViolation
does not ignore getters anymore and also flags
SOQL/SOSL/DML operations without access permission checks in getters. This will produce false positives now for
VF getter methods, but we can't reliably detect, whether a getter is a VF getter or not. In such cases,
the violation should be suppressed.java-bestpractices
UnusedImports
: use the rule UnnecessaryImport
insteadjava-codestyle
DuplicateImports
: use the rule UnnecessaryImport
insteadDontImportJavaLang
: use the rule UnnecessaryImport
insteadjava-errorprone
ImportFromSamePackage
: use the rule UnnecessaryImport
insteadNo changes.
The PMD team is pleased to announce PMD 6.33.0.
This is a minor release.
The PMD PLSQL parser might not parse every valid PL/SQL code without problems. In order to still use PMD on such files, you can now mark certain lines for exclusion from the parser. More information can be found in the language specific documentation for PLSQL.
The PMD team is pleased to announce PMD 6.32.0.
This is a minor release.
This release of PMD brings support for Java 16. PMD supports JEP 394: Pattern Matching for instanceof and JEP 395: Records. Both have been promoted to be a standard language feature of Java 16.
PMD also supports JEP 397: Sealed Classes (Second Preview) as a preview
language feature. In order to analyze a project with PMD that uses these language features, you'll need to enable
it via the environment variable PMD_JAVA_OPTS
and select the new language version 16-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 16-preview ...
Note: Support for Java 14 preview language features have been removed. The version "14-preview" is no longer available.
ApexDoc
has two new properties: reportPrivate
and
reportProtected
. Previously the rule only considered public and global classes, methods, and
properties. With these properties, you can verify the existence of ApexDoc comments for private
and protected methods as well. By default, these properties are disabled to preserve backwards
compatible behavior.ASTTypeTestPattern
has been renamed to ASTTypePattern
in order to align the naming to the JLS.ASTRecordConstructorDeclaration
has been renamed to ASTCompactConstructorDeclaration
in order to align the naming to the JLS.Those APIs are not intended to be used by clients, and will be hidden or removed with PMD 7.0.0.
You can identify them with the @InternalApi
annotation. You'll also get a deprecation warning.
AvoidUsingHardCodedIPRule
are deprecated and considered to be internal API. They will be removed with PMD 7.